This commit is contained in:
2026-07-02 15:54:39 -06:00
commit 9883323161
17470 changed files with 4470592 additions and 0 deletions
@@ -0,0 +1,89 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.3.0] - 2026-04-11
### Added
- Add `jetpack_account_protection_send_auth_email` filter to allow custom handling of the verification email. [#48003]
## [0.2.12] - 2026-02-23
### Changed
- Update dependencies.
## [0.2.11] - 2026-02-02
### Changed
- Update dependencies.
## [0.2.10] - 2025-12-15
### Changed
- Internal updates.
## [0.2.9] - 2025-12-08
### Fixed
- Ensure proper flags are used with `json_encode()`. [#46092]
## [0.2.8] - 2025-11-10
### Changed
- Tests: Ensure PHP 8.5 compatibility. [#45769]
## [0.2.7] - 2025-08-04
### Changed
- Internal updates.
## [0.2.6] - 2025-07-28
### Changed
- Internal updates.
## [0.2.5] - 2025-07-21
### Changed
- Internal updates.
## [0.2.4] - 2025-05-05
### Fixed
- Linting: Do additional stylesheet cleanup. [#43247]
- Prevent PHP error from errant third-party hook params. [#43352]
## [0.2.3] - 2025-04-28
### Fixed
- Fix an issue where authentication could fail when other authentication plugins are active. [#43240]
- Linting: Fix more Stylelint violations. [#43213]
## [0.2.2] - 2025-04-14
### Fixed
- Linting: Update stylesheets to use WordPress rules for fonts and colors. [#42920] [#42928]
- Fix: Improve compatibility with code using stdClass objects in `profile_update` hook. [#43045]
## [0.2.1] - 2025-04-07
### Changed
- Linting: First pass of style coding standards. [#42734]
## [0.2.0] - 2025-04-01
### Changed
- Add a default value for the error param in the `wp_login_failed` action callback. [#42819]
- Fix potential `wp_login_failed` action conflicts. [#42825]
## 0.1.0 - 2025-03-31
### Added
- Add initial account protection features. [#40925]
- Add a user requires protection filter. [#40925]
- Initial version. [#40923]
- Use jetpack-config package for Account Protection initialization. [#40925]
- Use jetpack-logo package for Account Protection logos. [#40925]
[0.3.0]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.12...v0.3.0
[0.2.12]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.11...v0.2.12
[0.2.11]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.10...v0.2.11
[0.2.10]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.9...v0.2.10
[0.2.9]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.8...v0.2.9
[0.2.8]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.7...v0.2.8
[0.2.7]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.6...v0.2.7
[0.2.6]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.5...v0.2.6
[0.2.5]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.4...v0.2.5
[0.2.4]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.3...v0.2.4
[0.2.3]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.2...v0.2.3
[0.2.2]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.1...v0.2.2
[0.2.1]: https://github.com/Automattic/jetpack-account-protection/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/Automattic/jetpack-account-protection/compare/v0.1.0...v0.2.0
@@ -0,0 +1,355 @@
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <https://www.gnu.org/licenses/>.
===================================
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Moe Ghoul>, 1 April 1989
Moe Ghoul, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
@@ -0,0 +1,47 @@
# Security Policy
Full details of the Automattic Security Policy can be found on [automattic.com](https://automattic.com/security/).
## Supported Versions
Generally, only the latest version of Jetpack and its associated plugins have continued support. If a critical vulnerability is found in the current version of a plugin, we may opt to backport any patches to previous versions.
## Reporting a Vulnerability
Our HackerOne program covers the below plugin software, as well as a variety of related projects and infrastructure:
* [Jetpack](https://jetpack.com/)
* Jetpack Backup
* Jetpack Boost
* Jetpack CRM
* Jetpack Protect
* Jetpack Search
* Jetpack Social
* Jetpack VideoPress
**For responsible disclosure of security issues and to be eligible for our bug bounty program, please submit your report via the [HackerOne](https://hackerone.com/automattic) portal.**
Our most critical targets are:
* Jetpack and the Jetpack composer packages (all within this repo)
* Jetpack.com -- the primary marketing site.
* cloud.jetpack.com -- a management site.
* wordpress.com -- the shared management site for both Jetpack and WordPress.com sites.
For more targets, see the `In Scope` section on [HackerOne](https://hackerone.com/automattic).
_Please note that the **WordPress software is a separate entity** from Automattic. Please report vulnerabilities for WordPress through [the WordPress Foundation's HackerOne page](https://hackerone.com/wordpress)._
## Guidelines
We're committed to working with security researchers to resolve the vulnerabilities they discover. You can help us by following these guidelines:
* Follow [HackerOne's disclosure guidelines](https://www.hackerone.com/disclosure-guidelines).
* Pen-testing Production:
* Please **setup a local environment** instead whenever possible. Most of our code is open source (see above).
* If that's not possible, **limit any data access/modification** to the bare minimum necessary to reproduce a PoC.
* **_Don't_ automate form submissions!** That's very annoying for us, because it adds extra work for the volunteers who manage those systems, and reduces the signal/noise ratio in our communication channels.
* To be eligible for a bounty, all of these guidelines must be followed.
* Be Patient - Give us a reasonable time to correct the issue before you disclose the vulnerability.
We also expect you to comply with all applicable laws. You're responsible to pay any taxes associated with your bounties.
@@ -0,0 +1,56 @@
{
"name": "automattic/jetpack-account-protection",
"description": "Account protection",
"type": "jetpack-library",
"license": "GPL-2.0-or-later",
"require": {
"php": ">=7.2",
"automattic/jetpack-connection": "^8.2.2",
"automattic/jetpack-logo": "^3.0.5",
"automattic/jetpack-constants": "^3.0.8",
"automattic/jetpack-status": "^6.1.2"
},
"require-dev": {
"yoast/phpunit-polyfills": "^4.0.0",
"automattic/jetpack-changelogger": "^6.0.14",
"automattic/jetpack-test-environment": "@dev",
"automattic/phpunit-select-config": "^1.0.4"
},
"autoload": {
"classmap": [
"src/"
]
},
"scripts": {
"build-development": "echo 'Add your build step to composer.json, please!'",
"build-production": "echo 'Add your build step to composer.json, please!'",
"phpunit": [
"phpunit-select-config phpunit.#.xml.dist --colors=always"
],
"test-coverage": [
"php -dpcov.directory=. ./vendor/bin/phpunit-select-config phpunit.#.xml.dist --coverage-php \"$COVERAGE_DIR/php.cov\""
],
"test-php": [
"@composer phpunit"
]
},
"minimum-stability": "dev",
"prefer-stable": true,
"extra": {
"autotagger": true,
"branch-alias": {
"dev-trunk": "0.3.x-dev"
},
"changelogger": {
"link-template": "https://github.com/Automattic/jetpack-account-protection/compare/v${old}...v${new}"
},
"mirror-repo": "Automattic/jetpack-account-protection",
"textdomain": "jetpack-account-protection",
"version-constants": {
"::PACKAGE_VERSION": "src/class-account-protection.php"
}
},
"suggest": {
"automattic/jetpack-autoloader": "Allow for better interoperability with other plugins that use this package."
}
}
@@ -0,0 +1,282 @@
<?php
/**
* Class used to define Account Protection.
*
* @package automattic/jetpack-account-protection
*/
namespace Automattic\Jetpack\Account_Protection;
use Automattic\Jetpack\Constants;
use Automattic\Jetpack\Modules;
use Automattic\Jetpack\Status\Host;
/**
* Class Account_Protection
*/
class Account_Protection {
const PACKAGE_VERSION = '0.3.0';
const ACCOUNT_PROTECTION_MODULE_NAME = 'account-protection';
/**
* Account_Protection instance
*
* @var Account_Protection
*/
private static $instance = null;
/**
* Flag to track if hooks have been registered.
*
* @var bool
*/
private static $hooks_registered = false;
/**
* Modules instance.
*
* @var Modules
*/
private $modules;
/**
* Password detection instance.
*
* @var Password_Detection
*/
private $password_detection;
/**
* Password manager instance
*
* @var Password_Manager
*/
private $password_manager;
/**
* Password strength meter instance
*
* @var Password_Strength_Meter
*/
private $password_strength_meter;
/**
* Initialize the Account_Protection instance
*
* @return Account_Protection
*/
public static function instance(): Account_Protection {
if ( self::$instance === null ) {
self::$instance = new Account_Protection();
}
return self::$instance;
}
/**
* Initializes the configurations needed for the account protection module.
*
* @return void
*/
public function initialize(): void {
if ( self::$hooks_registered ) {
return;
}
$this->register_hooks();
if ( $this->is_enabled() ) {
$this->register_runtime_hooks();
}
self::$hooks_registered = true;
}
/**
* Account_Protection constructor.
*
* @param ?Modules $modules Modules instance.
* @param ?Password_Detection $password_detection Password detection instance.
* @param ?Password_Manager $password_manager Password manager instance.
* @param ?Password_Strength_Meter $password_strength_meter Password strength meter instance.
*/
public function __construct( ?Modules $modules = null, ?Password_Detection $password_detection = null, ?Password_Manager $password_manager = null, ?Password_Strength_Meter $password_strength_meter = null ) {
$this->modules = $modules ?? new Modules();
$this->password_detection = $password_detection ?? new Password_Detection();
$this->password_manager = $password_manager ?? new Password_Manager();
$this->password_strength_meter = $password_strength_meter ?? new Password_Strength_Meter();
}
/**
* Register hooks for module activation and environment validation.
*
* @return void
*/
protected function register_hooks(): void {
// Do not run in unsupported environments
add_filter( 'jetpack_get_available_modules', array( $this, 'remove_module_on_unsupported_environments' ) );
add_filter( 'jetpack_get_available_standalone_modules', array( $this, 'remove_standalone_module_on_unsupported_environments' ) );
}
/**
* Register hooks for runtime operations.
*
* @return void
*/
protected function register_runtime_hooks(): void {
$this->register_password_detection_hooks();
$this->register_strong_passwords_hooks();
}
/**
* Register hooks for password detection.
*
* @return void
*/
public function register_password_detection_hooks(): void {
add_action( 'wp_authenticate_user', array( $this->password_detection, 'login_form_password_detection' ), 10, 2 );
add_action( 'login_form_password-detection', array( $this->password_detection, 'render_page' ), 10, 2 );
add_action( 'wp_enqueue_scripts', array( $this->password_detection, 'enqueue_styles' ) );
}
/**
* Register hooks for password manager.
*
* @return void
*/
public function register_password_manager_hooks(): void {
add_action( 'user_profile_update_errors', array( $this->password_manager, 'validate_profile_update' ), 10, 3 );
add_action( 'validate_password_reset', array( $this->password_manager, 'validate_password_reset' ), 10, 2 );
add_action( 'profile_update', array( $this->password_manager, 'on_profile_update' ), 10, 2 );
add_action( 'after_password_reset', array( $this->password_manager, 'on_password_reset' ), 10, 1 );
}
/**
* Register hooks for password strength meter.
*
* @return void
*/
public function register_password_strength_meter_hooks(): void {
add_action( 'admin_enqueue_scripts', array( $this->password_strength_meter, 'enqueue_jetpack_password_strength_meter_profile_script' ) );
add_action( 'login_enqueue_scripts', array( $this->password_strength_meter, 'enqueue_jetpack_password_strength_meter_reset_script' ) );
add_action( 'wp_ajax_validate_password_ajax', array( $this->password_strength_meter, 'validate_password_ajax' ) );
add_action( 'wp_ajax_nopriv_validate_password_ajax', array( $this->password_strength_meter, 'validate_password_ajax' ) );
}
/**
* Register hooks for strong passwords.
*
* @return void
*/
public function register_strong_passwords_hooks(): void {
$this->register_password_manager_hooks();
$this->register_password_strength_meter_hooks();
}
/**
* Determines if the account protection module is enabled on the site.
*
* @return bool
*/
public function is_enabled(): bool {
return $this->modules->is_active( self::ACCOUNT_PROTECTION_MODULE_NAME );
}
/**
* Enables the account protection module.
*
* @return bool
*/
public function enable(): bool {
// Return true if already enabled.
if ( $this->is_enabled() ) {
return true;
}
return $this->modules->activate( self::ACCOUNT_PROTECTION_MODULE_NAME, false, false );
}
/**
* Disables the account protection module.
*
* @return bool
*/
public function disable(): bool {
// Return true if already disabled.
if ( ! $this->is_enabled() ) {
return true;
}
return $this->modules->deactivate( self::ACCOUNT_PROTECTION_MODULE_NAME );
}
/**
* Determines if Account Protection is supported in the current environment.
*
* @return bool
*/
public function is_supported_environment(): bool {
// Do not run when killswitch is enabled
if ( defined( 'DISABLE_JETPACK_ACCOUNT_PROTECTION' ) && DISABLE_JETPACK_ACCOUNT_PROTECTION ) {
return false;
}
// Do not run for WordPress.com Simple sites
if ( ( new Host() )->is_wpcom_simple() ) {
return false;
}
return true;
}
/**
* Determines if the current Jetpack version is supported.
*
* @return bool
*/
public function has_unsupported_jetpack_version(): bool {
// Do not run when Jetpack version is less than 14.5
$jetpack_version = Constants::get_constant( 'JETPACK__VERSION' );
if ( $jetpack_version && version_compare( $jetpack_version, '14.5', '<' ) ) {
return true;
}
return false;
}
/**
* Disables the Account Protection module when on an unsupported platform in Jetpack.
*
* @param array $modules Filterable value for `jetpack_get_available_modules`.
*
* @return array Array of module slugs.
*/
public function remove_module_on_unsupported_environments( array $modules ): array {
if ( ! $this->is_supported_environment() ) {
// Account protection should never be available on unsupported platforms.
unset( $modules[ self::ACCOUNT_PROTECTION_MODULE_NAME ] );
}
return $modules;
}
/**
* Disables the Account Protection module when on an unsupported platform in a standalone plugin.
*
* @param array $modules Filterable value for `jetpack_get_available_standalone_modules`.
*
* @return array Array of module slugs.
*/
public function remove_standalone_module_on_unsupported_environments( array $modules ): array {
if ( ! $this->is_supported_environment() ) {
// Account Protection should never be available on unsupported platforms.
$modules = array_filter(
$modules,
function ( $module ) {
return $module !== self::ACCOUNT_PROTECTION_MODULE_NAME;
}
);
}
return $modules;
}
}
@@ -0,0 +1,28 @@
<?php
/**
* Class used to define Config.
*
* @package automattic/jetpack-account-protection
*/
namespace Automattic\Jetpack\Account_Protection;
/**
* Class Config
*/
class Config {
public const PREFIX = 'jetpack_account_protection';
public const SUPPORT_LINK = 'https://jetpack.com/?post_type=jetpack_support&p=324199';
public const RECENT_PASSWORD_HASHES_USER_META_KEY = self::PREFIX . '_recent_password_hashes';
// Password Detection Constants
public const PASSWORD_DETECTION_EMAIL_SENT_EXPIRATION = 600; // 10 minutes
public const PASSWORD_DETECTION_EMAIL_REQUEST_LIMIT = 4;
// Password Manager Constants
public const PASSWORD_MANAGER_RECENT_PASSWORDS_LIMIT = 10;
// Validation Service Constants
public const VALIDATION_SERVICE_MIN_LENGTH = 6;
public const VALIDATION_SERVICE_MAX_LENGTH = 150;
}
@@ -0,0 +1,170 @@
<?php
/**
* Class used to define Email Service.
*
* @package automattic/jetpack-account-protection
*/
namespace Automattic\Jetpack\Account_Protection;
use Automattic\Jetpack\Connection\Client;
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
use Jetpack_Options;
/**
* Class Email_Service
*/
class Email_Service {
/**
* Connection manager dependency.
*
* @var Connection_Manager
*/
private $connection_manager;
/**
* Constructor for dependency injection.
*
* @param Connection_Manager|null $connection_manager Connection manager dependency.
*/
public function __construct(
?Connection_Manager $connection_manager = null
) {
$this->connection_manager = $connection_manager ?? new Connection_Manager();
}
/**
* Send the email using the API.
*
* @param int $user_id The user ID.
* @param string $auth_code The authentication code.
*
* @return true|\WP_Error True if the email was sent successfully, \WP_Error otherwise.
*/
public function api_send_auth_email( int $user_id, string $auth_code ) {
$blog_id = Jetpack_Options::get_option( 'id' );
/**
* Filters whether the Account Protection verification email should be handled externally.
*
* When the filter returns a truthy value, the default WPCOM API email send is skipped,
* allowing sites to deliver the email locally (e.g. via `wp_mail()`).
*
* @since 0.3.0
*
* @param bool $handled Whether the email has been handled. Default false.
* @param int $user_id The user ID.
* @param string $auth_code The authentication code.
* @param int $blog_id The blog ID, or false if not available.
*/
$handled = apply_filters( 'jetpack_account_protection_send_auth_email', false, $user_id, $auth_code, $blog_id );
if ( $handled ) {
return true;
}
if ( ! $blog_id || ! $this->connection_manager->is_connected() ) {
return new \WP_Error( 'jetpack_connection_error', __( 'Jetpack is not connected. Please connect and try again.', 'jetpack-account-protection' ) );
}
$body = array(
'user_id' => $user_id,
'code' => $auth_code,
);
$response = $this->send_email_request( (int) $blog_id, $body );
if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
return new \WP_Error( 'email_send_error', __( 'Failed to send authentication code. Please try again.', 'jetpack-account-protection' ) );
}
$response_code = wp_remote_retrieve_response_code( $response );
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( 200 !== $response_code ) {
return new \WP_Error( $body['code'] ?? 'email_send_error', $body['message'] ?? __( 'Failed to send authentication code. Please try again.', 'jetpack-account-protection' ) );
}
if ( empty( $body['email_send_success'] ) ) {
return new \WP_Error( 'email_send_error', __( 'Failed to send authentication code. Please try again.', 'jetpack-account-protection' ) );
}
return true;
}
/**
* Dependency decoupling for the static call to the client.
*
* @param int $blog_id Blog ID.
* @param array $body The request body.
* @return array|\WP_Error Response data or error.
*/
protected function send_email_request( int $blog_id, array $body ) {
return Client::wpcom_json_api_request_as_blog(
sprintf( '/sites/%d/jetpack-protect-send-verification-code', $blog_id ),
'2',
array(
'method' => 'POST',
),
$body,
'wpcom'
);
}
/**
* Resend email attempts.
*
* @param int $user_id The user ID.
* @param array $transient_data The transient data.
* @param string $token The token.
*
* @return true|\WP_Error True if the email was resent successfully, \WP_Error otherwise.
*/
public function resend_auth_email( int $user_id, array $transient_data, string $token ) {
if ( $transient_data['requests'] >= Config::PASSWORD_DETECTION_EMAIL_REQUEST_LIMIT ) {
return new \WP_Error( 'email_request_limit_exceeded', __( 'Email request limit exceeded. Please try again later.', 'jetpack-account-protection' ) );
}
$auth_code = $this->generate_auth_code();
$transient_data['auth_code'] = $auth_code;
$resend = $this->api_send_auth_email( $user_id, $auth_code );
if ( is_wp_error( $resend ) ) {
return $resend;
}
++$transient_data['requests'];
if ( ! set_transient( Config::PREFIX . "_{$token}", $transient_data, Config::PASSWORD_DETECTION_EMAIL_SENT_EXPIRATION ) ) {
return new \WP_Error( 'transient_set_error', __( 'Failed to set transient data. Please try again.', 'jetpack-account-protection' ) );
}
return true;
}
/**
* Generate an auth code.
*
* @return string The generated auth code.
*/
public function generate_auth_code(): string {
return (string) wp_rand( 100000, 999999 );
}
/**
* Mask an email address like d*****@g*****.com.
*
* @param string $email The email address to mask.
*
* @return string The masked email address.
*/
public function mask_email_address( string $email ): string {
$parts = explode( '@', $email );
$name = substr( $parts[0], 0, 1 ) . str_repeat( '*', strlen( $parts[0] ) - 1 );
$domain_parts = explode( '.', $parts[1] );
$domain = substr( $domain_parts[0], 0, 1 ) . str_repeat( '*', strlen( $domain_parts[0] ) - 1 );
// Join all domain parts except the first one with dots
$tld = implode( '.', array_slice( $domain_parts, 1 ) );
return "{$name}@{$domain}.{$tld}";
}
}
@@ -0,0 +1,547 @@
<?php
/**
* Class used to define Password Detection.
*
* @package automattic/jetpack-account-protection
*/
namespace Automattic\Jetpack\Account_Protection;
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
/**
* Class Password_Detection
*/
class Password_Detection {
/**
* Email service dependency.
*
* @var Email_Service
*/
private $email_service;
/**
* Validation service dependency.
*
* @var Validation_Service
*/
private $validation_service;
/**
* Password_Detection constructor.
*
* @param ?Email_Service $email_service Email service instance.
* @param ?Validation_Service $validation_service Validation service instance.
*/
public function __construct( ?Email_Service $email_service = null, ?Validation_Service $validation_service = null ) {
$this->email_service = $email_service ?? new Email_Service();
$this->validation_service = $validation_service ?? new Validation_Service();
}
/**
* Check if the password is safe after login.
*
* @param \WP_User|\WP_Error|null $user The user or error object, or null.
* @param string|null $password The password.
*
* @return \WP_User|\WP_Error|null The user object, error object, or null.
*/
public function login_form_password_detection( $user, ?string $password ) {
// First check if the user object and password are valid. Third-party plugins might pass
// incompatible types to authentication hooks, so we need this extra check.
if ( is_wp_error( $user ) || ! ( $user instanceof \WP_User ) || $password === null ) {
return $user;
}
if ( ! $this->user_requires_protection( $user, $password ) ) {
return $user;
}
// Skip if we're validating a Brute force protection recovery token
if ( get_transient( 'jetpack_protect_recovery_key_validated_' . $user->ID ) ) {
return $user;
}
if ( ! $this->validation_service->is_leaked_password( $password ) ) {
return $user;
}
$auth_code = $this->email_service->generate_auth_code();
$existing_transient_token = get_transient( Config::PREFIX . "_last_valid_token_{$user->ID}" );
$existing_transient = $existing_transient_token ? get_transient( Config::PREFIX . "_{$existing_transient_token}" ) : null;
if ( $existing_transient && isset( $existing_transient['requests'] ) &&
$existing_transient['requests'] >= Config::PASSWORD_DETECTION_EMAIL_REQUEST_LIMIT ) {
// Resend limit reached, prevent sending new email
$this->set_transient_error(
$user->ID,
array(
'code' => 'email_request_limit_exceeded',
'message' => __( 'Email request limit exceeded. Please try again later.', 'jetpack-account-protection' ),
)
);
$this->redirect_and_exit( $this->get_redirect_url( $existing_transient_token ) );
}
$email_sent = $this->email_service->api_send_auth_email( $user->ID, $auth_code );
if ( is_wp_error( $email_sent ) ) {
$this->set_transient_error(
$user->ID,
array(
'code' => $email_sent->get_error_code(),
'message' => $email_sent->get_error_message(),
)
);
}
$new_transient_token = null;
// Update or create a transient token
if ( $existing_transient ) {
if ( ! is_wp_error( $email_sent ) ) {
$existing_transient['auth_code'] = $auth_code;
$existing_transient['requests'] = ( $existing_transient['requests'] ?? 0 ) + 1;
if ( ! set_transient( Config::PREFIX . "_{$existing_transient_token}", $existing_transient, Config::PASSWORD_DETECTION_EMAIL_SENT_EXPIRATION ) ) {
$this->set_transient_error(
$user->ID,
array(
'code' => 'transient_error',
'message' => __( 'Failed to update authentication token. Please try again.', 'jetpack-account-protection' ),
)
);
}
}
} else {
$new_transient_token = $this->generate_and_store_transient_data( $user->ID, $auth_code );
}
$this->redirect_and_exit( $this->get_redirect_url( $new_transient_token ? $new_transient_token : $existing_transient_token ) );
}
/**
* Redirect and exit.
*
* @param string $redirect_location The redirect location.
*
* @return never
*/
protected function redirect_and_exit( string $redirect_location ) {
wp_safe_redirect( $redirect_location );
$this->exit();
}
/**
* Exit decoupling.
*
* @return never
*/
protected function exit() {
exit;
}
/**
* Load user by ID. Dependency decoupling.
*
* @param int $user_id The user ID.
*
* @return \WP_User|null The user object.
*/
protected function load_user( int $user_id ) {
return get_user_by( 'ID', $user_id );
}
/**
* Render password detection page.
*/
public function render_page() {
if ( is_user_logged_in() ) {
$this->redirect_and_exit( admin_url() );
// @phan-suppress-next-line PhanPluginUnreachableCode This would fall through in unit tests otherwise.
return;
}
$token = isset( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : null;
$transient_data = get_transient( Config::PREFIX . "_{$token}" );
if ( ! $transient_data ) {
$this->redirect_to_login();
// @phan-suppress-next-line PhanPluginUnreachableCode This would fall through in unit tests otherwise.
return;
}
$user_id = $transient_data['user_id'] ?? null;
$user = $user_id ? $this->load_user( (int) $user_id ) : null;
if ( ! $user instanceof \WP_User ) {
$this->redirect_to_login();
// @phan-suppress-next-line PhanPluginUnreachableCode This would fall through in unit tests otherwise.
return;
}
// Handle resend email request
if ( isset( $_GET['resend_email'] ) && $_GET['resend_email'] === '1' ) {
if ( isset( $_GET['_wpnonce'] )
&& wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'resend_email_nonce' )
) {
$email_resent = $this->email_service->resend_auth_email( $user->ID, $transient_data, $token );
if ( is_wp_error( $email_resent ) ) {
$this->set_transient_error(
$user->ID,
array(
'code' => $email_resent->get_error_code(),
'message' => $email_resent->get_error_message(),
)
);
} else {
$this->set_transient_success(
$user->ID,
array(
'code' => 'email_resend_success',
'message' => __( 'Authentication email resent successfully.', 'jetpack-account-protection' ),
)
);
}
$this->redirect_and_exit( $this->get_redirect_url( $token ) );
// @phan-suppress-next-line PhanPluginUnreachableCode This would fall through in unit tests otherwise.
return;
} else {
$this->set_transient_error(
$user->ID,
array(
'code' => 'email_resend_nonce_error',
'message' => __( 'Resend nonce verification failed. Please try again.', 'jetpack-account-protection' ),
)
);
}
}
// Handle verify form submission
if ( isset( $_POST['verify'] ) ) {
if ( ! empty( $_POST['_wpnonce_verify'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce_verify'] ) ), 'verify_action' ) ) {
$user_input = isset( $_POST['user_input'] ) ? sanitize_text_field( wp_unslash( $_POST['user_input'] ) ) : null;
$this->handle_auth_form_submission( $user, $token, $transient_data['auth_code'] ?? null, $user_input );
} else {
$this->set_transient_error(
$user->ID,
array(
'code' => 'verify_nonce_error',
'message' => __( 'Verify nonce verification failed. Please try again.', 'jetpack-account-protection' ),
)
);
}
}
$this->render_content( $user, $token );
}
/**
* Extract transient data safely and delete the transient.
*
* @param string $transient_key The transient key.
* @return array An array containing 'message' and 'code'.
*/
public function extract_and_clear_transient_data( string $transient_key ): array {
$data = get_transient( $transient_key );
delete_transient( $transient_key );
return array(
'message' => $data['message'] ?? null,
'code' => $data['code'] ?? null,
);
}
/**
* Render content for password detection page.
*
* @param \WP_User $user The user.
* @param string $token The token.
*
* @return void
*/
public function render_content( \WP_User $user, string $token ): void {
$error_transient_key = Config::PREFIX . "_error_{$user->ID}";
$success_transient_key = Config::PREFIX . "_success_{$user->ID}";
$error_data = $this->extract_and_clear_transient_data( $error_transient_key );
$success_data = $this->extract_and_clear_transient_data( $success_transient_key );
$body_classes = 'password-detection-wrapper';
if ( 'auth_code_success' === $success_data['code'] ) {
$body_classes .= ' interim-login-success';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php esc_html_e( 'Jetpack - Secure Your Account', 'jetpack-account-protection' ); ?></title>
<?php wp_head(); ?>
</head>
<body class="<?php echo esc_attr( $body_classes ); ?>">
<div class="password-detection-content">
<?php
$jetpack_logo = new Jetpack_Logo();
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo $jetpack_logo->get_jp_emblem( true );
?>
<p class="password-detection-title"><?php echo $success_data['code'] === 'auth_code_success' ? esc_html__( 'Take action to stay secure', 'jetpack-account-protection' ) : esc_html__( 'Verify your identity', 'jetpack-account-protection' ); ?></p>
<?php if ( $error_data['message'] ) : ?>
<div class="error notice">
<p class="notice-message"><?php echo esc_html( $error_data['message'] ); ?></p>
</div>
<?php endif; ?>
<?php if ( $success_data['message'] ) : ?>
<div class="success notice">
<p class="notice-message"><?php echo esc_html( $success_data['message'] ); ?></p>
</div>
<?php endif; ?>
<?php if ( $success_data['code'] === 'auth_code_success' ) : ?>
<p><?php esc_html_e( "You're all set! You can now access your account.", 'jetpack-account-protection' ); ?></p>
<p><?php esc_html_e( 'Please keep in mind that your current password was found in a public leak, which means your account might be at risk. It is highly recommended that you update your password.', 'jetpack-account-protection' ); ?></p>
<div class="actions">
<a href="<?php echo esc_url( admin_url( 'profile.php#password' ) ); ?>" class="action action-update-password">
<?php esc_html_e( 'Create a new password', 'jetpack-account-protection' ); ?>
</a>
<a href="<?php echo esc_url( admin_url() ); ?>" class="action action-proceed">
<?php esc_html_e( 'Proceed without updating', 'jetpack-account-protection' ); ?>
</a>
</div>
<p>
<?php
printf(
/* translators: %s: Risks of using weak passwords link */
esc_html__( 'Learn more about the %s and how to protect your account.', 'jetpack-account-protection' ),
'<a class="risks-link" href="' . esc_url( Config::SUPPORT_LINK . '#risks-of-using-a-weak-password' ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'risks of using weak passwords', 'jetpack-account-protection' ) . '</a>'
);
?>
</p>
<?php else : ?>
<p><?php esc_html_e( 'We\'ve noticed that your current password may have been compromised in a public leak. To keep your account safe, we\'ve added an extra layer of security.', 'jetpack-account-protection' ); ?></p>
<p>
<?php
printf(
/* translators: %s: Masked email address */
esc_html__( 'We\'ve sent a code to %s. Please check your inbox and enter the code below to verify it\'s really you.', 'jetpack-account-protection' ),
esc_html( $this->email_service->mask_email_address( $user->user_email ) )
);
?>
</p>
<div class="actions">
<form method="post">
<?php wp_nonce_field( 'verify_action', '_wpnonce_verify' ); ?>
<input
type="text"
name="user_input"
class="action-input"
placeholder="<?php esc_attr_e( 'Enter verification code', 'jetpack-account-protection' ); ?>"
required
pattern="\d{6}"
minlength="6"
maxlength="6"
inputmode="numeric"
oninput="this.value = this.value.replace(/\D/g, '');"
/>
<button class="action action-verify" type="submit" name="verify"><?php esc_html_e( 'Verify', 'jetpack-account-protection' ); ?></button>
</form>
</div>
<?php if ( in_array( $error_data['code'], array( 'email_request_limit_exceeded', 'email_send_error' ), true ) ) : ?>
<p class="account-recovery">
<?php
printf(
/* translators: %s: Jetpack support link */
esc_html__( 'If you did not receive your authentication code, please try again later or %s now.', 'jetpack-account-protection' ),
'<a class="risks-link" href="' . esc_url( wp_lostpassword_url() ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'reset your password', 'jetpack-account-protection' ) . '</a>'
);
?>
</p>
<?php else : ?>
<p class="email-status">
<span><?php esc_html_e( "Didn't get the code?", 'jetpack-account-protection' ); ?> </span>
<a class="resend-email-link" href="<?php echo esc_url( $this->get_redirect_url( $token ) . '&resend_email=1&_wpnonce=' . wp_create_nonce( 'resend_email_nonce' ) ); ?>">
<?php esc_html_e( 'Resend email', 'jetpack-account-protection' ); ?>
</a>
</p>
<?php endif; ?>
<?php endif; ?>
</div>
<?php wp_footer(); ?>
</body>
</html>
<?php
$this->exit();
}
/**
* Check if the user requires password protection.
*
* @param \WP_User $user The user object.
* @param string $password The password.
*
* @return bool
*/
private function user_requires_protection( \WP_User $user, string $password ): bool {
if ( ! user_can( $user, 'publish_posts' ) && ! user_can( $user, 'edit_published_posts' ) ) {
return false;
}
/**
* Filter which determines whether or not password detection should be applied for the provided user.
*
* @since 0.1.0
*
* @param bool $requires_protection Whether or not password detection should be applied.
* @param \WP_User $user The user object to apply the filter against.
*/
$user_requires_protection = apply_filters( 'jetpack_account_protection_user_requires_protection', true, $user );
if ( ! $user_requires_protection ) {
return false;
}
return wp_check_password( $password, $user->user_pass, $user->ID );
}
/**
* Generate and store a consolidated transient for the user.
*
* @param int $user_id The user ID.
* @param string $auth_code The auth code.
*
* @return string The generated token associated with the new transient data.
*/
private function generate_and_store_transient_data( int $user_id, string $auth_code ): string {
$token = wp_generate_password( 32, false, false );
$data = array(
'user_id' => $user_id,
'auth_code' => $auth_code,
'requests' => 1,
);
$set_token_transient = set_transient( Config::PREFIX . "_{$token}", $data, Config::PASSWORD_DETECTION_EMAIL_SENT_EXPIRATION );
$set_user_transient = set_transient( Config::PREFIX . "_last_valid_token_{$user_id}", $token, Config::PASSWORD_DETECTION_EMAIL_SENT_EXPIRATION );
if ( ! $set_token_transient || ! $set_user_transient ) {
$this->set_transient_error(
$user_id,
array(
'code' => 'transient_error',
'message' => __( 'Failed to set transient data. Please try again.', 'jetpack-account-protection' ),
)
);
}
return $token;
}
/**
* Redirect to the login page.
*
* @return never
*/
private function redirect_to_login() {
$this->redirect_and_exit( wp_login_url() );
}
/**
* Get redirect URL.
*
* @param string $token The token.
*
* @return string The redirect URL.
*/
private function get_redirect_url( string $token ): string {
return home_url( '/wp-login.php?action=password-detection&token=' . $token );
}
/**
* Handle auth form submission.
*
* @param \WP_User $user The current user.
* @param string $token The token.
* @param string $auth_code The expected auth code.
* @param string $user_input The user input.
*
* @return void
*/
private function handle_auth_form_submission( \WP_User $user, string $token, string $auth_code, string $user_input ): void {
if ( $auth_code && $auth_code === $user_input ) {
$this->set_transient_success(
$user->ID,
array(
'code' => 'auth_code_success',
'message' => __( 'Authentication code verified successfully.', 'jetpack-account-protection' ),
)
);
delete_transient( Config::PREFIX . "_{$token}" );
delete_transient( Config::PREFIX . "_last_valid_token_{$user->ID}" );
wp_set_auth_cookie( $user->ID, true );
wp_set_current_user( $user->ID );
} else {
$this->set_transient_error(
$user->ID,
array(
'code' => 'auth_code_error',
'message' => __( 'Authentication code verification failed. Please try again.', 'jetpack-account-protection' ),
)
);
}
}
/**
* Set a transient success message.
*
* @param int $user_id The user ID.
* @param array $success An array of the success code and message.
* @param int $expiration The expiration time in seconds.
*
* @return void
*/
public function set_transient_success( int $user_id, array $success, int $expiration = 60 ): void {
set_transient( Config::PREFIX . "_success_{$user_id}", $success, $expiration );
}
/**
* Set a transient error message.
*
* @param int $user_id The user ID.
* @param array $error An array of the error code and message.
* @param int $expiration The expiration time in seconds.
*
* @return void
*/
public function set_transient_error( int $user_id, array $error, int $expiration = 60 ): void {
set_transient( Config::PREFIX . "_error_{$user_id}", $error, $expiration );
}
/**
* Enqueue the password detection page styles.
*
* @return void
*/
public function enqueue_styles(): void {
global $pagenow;
if ( ! isset( $pagenow ) || $pagenow !== 'wp-login.php' ) {
return;
}
// No nonce verification necessary - reading only
// phpcs:ignore WordPress.Security.NonceVerification
if ( isset( $_GET['action'] ) && $_GET['action'] === 'password-detection' ) {
wp_enqueue_style(
'password-detection-styles',
plugin_dir_url( __FILE__ ) . 'css/password-detection.css',
array(),
Account_Protection::PACKAGE_VERSION
);
}
}
}
@@ -0,0 +1,154 @@
<?php
/**
* Class used to define Password Manager.
*
* @package automattic/jetpack-account-protection
*/
namespace Automattic\Jetpack\Account_Protection;
/**
* Class Password_Manager
*/
class Password_Manager {
/**
* Validaton service instance
*
* @var Validation_Service
*/
private $validation_service;
/**
* Validation_Service constructor.
*
* @param ?Validation_Service $validation_service Password manager instance.
*/
public function __construct( ?Validation_Service $validation_service = null ) {
$this->validation_service = $validation_service ?? new Validation_Service();
}
/**
* Validate the profile update.
*
* @param \WP_Error $errors The error object.
* @param bool $update Whether the user is being updated.
* @param \stdClass $user A copy of the new user object.
*
* @return void
*/
public function validate_profile_update( \WP_Error $errors, bool $update, \stdClass $user ): void {
if ( empty( $user->user_pass ) ) {
return;
}
// If bypass is enabled, do not validate the password
// phpcs:ignore WordPress.Security.NonceVerification
if ( isset( $_POST['pw_weak'] ) && 'on' === $_POST['pw_weak'] ) {
return;
}
$core_validation_errors = $errors->get_error_messages( 'pass' );
$jetpack_validation_errors = $this->validation_service->get_validation_errors( $user->user_pass, true, $user );
$validation_errors = array_diff( $jetpack_validation_errors, $core_validation_errors );
foreach ( $validation_errors as $validation_error ) {
$errors->add( 'pass', $validation_error, array( 'form-field' => 'pass1' ) );
}
}
/**
* Validate the password reset.
*
* @param \WP_Error $errors The error object.
* @param \WP_User|\WP_Error $user The user object.
*
* @return void
*/
public function validate_password_reset( \WP_Error $errors, $user ): void {
if ( is_wp_error( $user ) ) {
return;
}
// phpcs:ignore WordPress.Security.NonceVerification
if ( empty( $_POST['pass1'] ) ) {
return;
}
// If bypass is enabled, do not validate the password
// phpcs:ignore WordPress.Security.NonceVerification
if ( isset( $_POST['pw_weak'] ) && 'on' === $_POST['pw_weak'] ) {
return;
}
// phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$password = wp_unslash( $_POST['pass1'] );
$core_validation_errors = $errors->get_error_messages( 'pass' );
$jetpack_validation_errors = $this->validation_service->get_validation_errors( $password );
$validation_errors = array_diff( $jetpack_validation_errors, $core_validation_errors );
foreach ( $validation_errors as $validation_error ) {
$errors->add( 'pass', $validation_error, array( 'form-field' => 'pass1' ) );
}
}
/**
* Handle the profile update.
*
* @param int $user_id The user ID.
* @param \WP_User|\stdClass|null $old_user_data Object containing user data prior to update.
*
* @return void
*/
public function on_profile_update( int $user_id, $old_user_data ): void {
if ( ! is_object( $old_user_data ) || empty( $old_user_data->user_pass ) ) {
return;
}
// phpcs:ignore WordPress.Security.NonceVerification
if ( isset( $_POST['action'] ) && $_POST['action'] === 'update' ) {
$this->save_recent_password_hash( $user_id, $old_user_data->user_pass );
}
}
/**
* Handle the password reset.
*
* @param \WP_User|\stdClass|null $user The user object.
*
* @return void
*/
public function on_password_reset( $user ): void {
if ( ! is_object( $user ) || ! isset( $user->ID ) || empty( $user->user_pass ) ) {
return;
}
$this->save_recent_password_hash( $user->ID, $user->user_pass );
}
/**
* Save the new password hash to the user's recent passwords list.
*
* @param int $user_id The user ID.
* @param string $password_hash The password hash to store.
*
* @return void
*/
public function save_recent_password_hash( int $user_id, string $password_hash ): void {
$recent_passwords = get_user_meta( $user_id, Config::RECENT_PASSWORD_HASHES_USER_META_KEY, true );
if ( ! is_array( $recent_passwords ) ) {
$recent_passwords = array();
}
if ( in_array( $password_hash, $recent_passwords, true ) ) {
return;
}
// Add the new hashed password and keep only the last 10
array_unshift( $recent_passwords, $password_hash );
$recent_passwords = array_slice( $recent_passwords, 0, Config::PASSWORD_MANAGER_RECENT_PASSWORDS_LIMIT );
update_user_meta( $user_id, Config::RECENT_PASSWORD_HASHES_USER_META_KEY, $recent_passwords );
}
}
@@ -0,0 +1,183 @@
<?php
/**
* Class used to define Password Strength Meter.
*
* @package automattic/jetpack-account-protection
*/
namespace Automattic\Jetpack\Account_Protection;
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
/**
* Class Password_Strength_Meter
*/
class Password_Strength_Meter {
/**
* Validaton service instance
*
* @var Validation_Service
*/
private $validation_service;
/**
* Validation_Service constructor.
*
* @param ?Validation_Service $validation_service Password manager instance.
*/
public function __construct( ?Validation_Service $validation_service = null ) {
$this->validation_service = $validation_service ?? new Validation_Service();
}
/**
* Wrapper method for nonce verification.
*
* @param string $nonce Nonce value.
* @param string $action Nonce action.
*
* @return bool
*/
protected function verify_nonce( string $nonce, string $action ): bool {
return wp_verify_nonce( $nonce, $action );
}
/**
* Wrapper method for sending a JSON error response.
*
* @param string $message The error message.
*
* @return void
*/
protected function send_json_error( string $message ): void {
// @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
wp_send_json_error( array( 'message' => $message ), null, JSON_UNESCAPED_SLASHES );
}
/**
* Wrapper method for sending a JSON success response.
*
* @param array $data The data to send.
*
* @return void
*/
protected function send_json_success( array $data ): void {
// @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
wp_send_json_success( $data, null, JSON_UNESCAPED_SLASHES );
}
/**
* AJAX endpoint for password validation.
*
* @return void
*/
public function validate_password_ajax(): void {
// phpcs:disable WordPress.Security.NonceVerification
if ( ! isset( $_POST['password'] ) ) {
$this->send_json_error( __( 'No password provided.', 'jetpack-account-protection' ) );
return;
}
if ( ! isset( $_POST['nonce'] ) || ! $this->verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'validate_password_nonce' ) ) {
$this->send_json_error( __( 'Invalid nonce.', 'jetpack-account-protection' ) );
return;
}
$user_specific = false;
if ( isset( $_POST['user_specific'] ) ) {
$user_specific = filter_var( sanitize_text_field( wp_unslash( $_POST['user_specific'] ) ), FILTER_VALIDATE_BOOLEAN );
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$password = wp_unslash( $_POST['password'] );
// phpcs:enable WordPress.Security.NonceVerification
$state = $this->validation_service->get_validation_state( $password, $user_specific );
$this->send_json_success( array( 'state' => $state ) );
}
/**
* Enqueue the password strength meter script on the profile page.
*
* @return void
*/
public function enqueue_jetpack_password_strength_meter_profile_script(): void {
global $pagenow;
if ( ! isset( $pagenow ) || ! in_array( $pagenow, array( 'profile.php', 'user-new.php', 'user-edit.php' ), true ) ) {
return;
}
$this->enqueue_script();
$this->enqueue_styles();
// Only profile page should run user specific checks.
$this->localize_jetpack_data( 'profile.php' === $pagenow );
}
/**
* Enqueue the password strength meter script on the reset password page.
*
* @return void
*/
public function enqueue_jetpack_password_strength_meter_reset_script(): void {
// No nonce verification necessary as the action includes a robust verification process
// phpcs:ignore WordPress.Security.NonceVerification
if ( isset( $_GET['action'] ) && ( 'rp' === $_GET['action'] || 'resetpass' === $_GET['action'] ) ) {
$this->enqueue_script();
$this->enqueue_styles();
$this->localize_jetpack_data();
}
}
/**
* Localize the Jetpack data for the password strength meter.
*
* @param bool $user_specific Whether or not to run user specific checks.
*
* @return void
*/
public function localize_jetpack_data( bool $user_specific = false ): void {
$jetpack_logo = new Jetpack_Logo();
wp_localize_script(
'jetpack-password-strength-meter',
'jetpackData',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'validate_password_nonce' ),
'userSpecific' => $user_specific,
'logo' => htmlspecialchars( $jetpack_logo->get_jp_emblem( true ), ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ),
'validationInitialState' => $this->validation_service->get_validation_initial_state( $user_specific ),
)
);
}
/**
* Enqueue the password strength meter script.
*
* @return void
*/
public function enqueue_script(): void {
wp_enqueue_script(
'jetpack-password-strength-meter',
plugin_dir_url( __FILE__ ) . 'js/jetpack-password-strength-meter.js',
array( 'jquery' ),
Account_Protection::PACKAGE_VERSION,
true
);
}
/**
* Enqueue the password strength meter styles.
*
* @return void
*/
public function enqueue_styles(): void {
wp_enqueue_style(
'strength-meter-styles',
plugin_dir_url( __FILE__ ) . 'css/strength-meter.css',
array(),
Account_Protection::PACKAGE_VERSION
);
}
}
@@ -0,0 +1,44 @@
<?php
/**
* Class used to manage settings related to Account Protection.
*
* @package automattic/jetpack-account-protection
*/
namespace Automattic\Jetpack\Account_Protection;
/**
* Account Protection Settings
*/
class Settings {
/**
* Account protection instance.
*
* @var Account_Protection
*/
private $account_protection;
/**
* Constructor for dependency injection.
*
* @param ?Account_Protection|null $account_protection Account protection dependency.
*/
public function __construct( ?Account_Protection $account_protection = null ) {
$this->account_protection = $account_protection ?? Account_Protection::instance();
}
/**
* Get account protection settings.
*
* @return array
*/
public function get() {
$settings = array(
'isEnabled' => $this->account_protection->is_enabled(),
'isSupported' => $this->account_protection->is_supported_environment(),
'hasUnsupportedJetpackVersion' => $this->account_protection->has_unsupported_jetpack_version(),
);
return $settings;
}
}
@@ -0,0 +1,326 @@
<?php
/**
* Class used to define Validation Service.
*
* @package automattic/jetpack-account-protection
*/
namespace Automattic\Jetpack\Account_Protection;
use Automattic\Jetpack\Connection\Client;
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
/**
* Class Validation_Service
*/
class Validation_Service {
/**
* Connection manager dependency.
*
* @var Connection_Manager
*/
private $connection_manager;
/**
* Constructor for dependency injection.
*
* @param Connection_Manager|null $connection_manager Connection manager dependency.
*/
public function __construct(
?Connection_Manager $connection_manager = null
) {
$this->connection_manager = $connection_manager ?? new Connection_Manager();
}
/**
* Dependency decoupling so we can test this class.
*
* @param string $password_prefix The password prefix to be checked.
* @return array|\WP_Error
*/
protected function request_suffixes( string $password_prefix ) {
return Client::wpcom_json_api_request_as_blog(
'/jetpack-protect-weak-password/' . $password_prefix,
'2',
array( 'method' => 'GET' ),
null,
'wpcom'
);
}
/**
* Return validation initial state.
*
* @param bool $user_specific Whether or not to include user specific checks.
*
* @return array An array of all validation statuses and messages.
*/
public function get_validation_initial_state( $user_specific ): array {
$base_conditions = array(
'core' => array(
'status' => null,
'message' => __( 'Strong password', 'jetpack-account-protection' ),
'info' => __( 'Passwords should meet WordPress core security requirements to enhance account protection.', 'jetpack-account-protection' ),
),
'contains_backslash' => array(
'status' => null,
'message' => __( "Doesn't contain a backslash (\\) character", 'jetpack-account-protection' ),
'info' => null,
),
'invalid_length' => array(
'status' => null,
'message' => __( 'Between 6 and 150 characters', 'jetpack-account-protection' ),
'info' => null,
),
'leaked' => array(
'status' => null,
'message' => __( 'Not a leaked password', 'jetpack-account-protection' ),
'info' => __( 'If found in a public breach, this password may already be known to attackers.', 'jetpack-account-protection' ),
),
);
if ( ! $user_specific ) {
return $base_conditions;
}
$user_specific_conditions = array(
'matches_user_data' => array(
'status' => null,
'message' => __( "Doesn't match existing user data", 'jetpack-account-protection' ),
'info' => __( 'Using a password similar to your username or email makes it easier to guess.', 'jetpack-account-protection' ),
),
'recent' => array(
'status' => null,
'message' => __( 'Not used recently', 'jetpack-account-protection' ),
'info' => __( 'Reusing old passwords may increase security risks. A fresh password improves protection.', 'jetpack-account-protection' ),
),
);
return array_merge( $base_conditions, $user_specific_conditions );
}
/**
* Return validation state - client-side.
*
* @param string $password The password to check.
* @param bool $user_specific Whether or not to run user specific checks.
*
* @return array An array of the status of each check.
*/
public function get_validation_state( string $password, $user_specific ): array {
$validation_state = $this->get_validation_initial_state( $user_specific );
$validation_state['contains_backslash']['status'] = $this->contains_backslash( $password );
$validation_state['invalid_length']['status'] = $this->is_invalid_length( $password );
$validation_state['leaked']['status'] = $this->is_leaked_password( $password );
if ( ! $user_specific ) {
return $validation_state;
}
// Run checks on existing user data
$user = wp_get_current_user();
$validation_state['matches_user_data']['status'] = $this->matches_user_data( $user, $password );
$validation_state['recent']['status'] = $this->is_recent_password_hash( $user, $password );
return $validation_state;
}
/**
* Return all validation errors - server-side.
*
* @param string $password The password to check.
* @param bool $user_specific Whether or not to run user specific checks.
* @param \stdClass|null $user The user data or null.
*
* @return array The validation errors (if any).
*/
public function get_validation_errors( string $password, $user_specific = false, $user = null ): array {
$errors = array();
if ( empty( $password ) ) {
$errors[] = __( '<strong>Error:</strong> The password cannot be a space or all spaces.', 'jetpack-account-protection' );
}
if ( $this->contains_backslash( $password ) ) {
$errors[] = __( '<strong>Error:</strong> Passwords may not contain the character "\\".', 'jetpack-account-protection' );
}
if ( $this->is_invalid_length( $password ) ) {
$errors[] = __( '<strong>Error:</strong> The password must be between 6 and 150 characters.', 'jetpack-account-protection' );
}
if ( $this->is_leaked_password( $password ) ) {
$errors[] = __( '<strong>Error:</strong> The password was found in a public leak.', 'jetpack-account-protection' );
}
// Skip user-specific checks during password reset
if ( $user_specific ) {
// Run checks on new user data
if ( $this->matches_user_data( $user, $password ) ) {
$errors[] = __( '<strong>Error:</strong> The password matches new user data.', 'jetpack-account-protection' );
}
if ( $this->is_recent_password_hash( $user, $password ) ) {
$errors[] = __( '<strong>Error:</strong> The password was used recently.', 'jetpack-account-protection' );
}
}
return $errors;
}
/**
* Check if the password contains a backslash.
*
* @param string $password The password to check.
*
* @return bool True if the password contains a backslash, false otherwise.
*/
public function contains_backslash( string $password ): bool {
return strpos( $password, '\\' ) !== false;
}
/**
* Check if the password length is within the allowed range.
*
* @param string $password The password to check.
*
* @return bool True if the password is between 6 and 150 characters, false otherwise.
*/
public function is_invalid_length( string $password ): bool {
$length = strlen( $password );
return $length < Config::VALIDATION_SERVICE_MIN_LENGTH || $length > Config::VALIDATION_SERVICE_MAX_LENGTH;
}
/**
* Check if the password matches any user data.
*
* @param \WP_User|\stdClass|null $user The user.
* @param string $password The password to check.
*
* @return bool True if the password matches any user data, false otherwise.
*/
public function matches_user_data( $user, string $password ): bool {
if ( ! $user ) {
return false;
}
$email_parts = explode( '@', $user->user_email ); // test@example.com
$email_username = $email_parts[0]; // 'test'
$email_domain = $email_parts[1]; // 'example.com'
$email_provider = explode( '.', $email_domain )[0]; // 'example'
$user_data = array(
$user->user_login ?? '',
$user->display_name ?? '',
$user->first_name ?? '',
$user->last_name ?? '',
$user->user_email ?? '',
$email_username ?? '',
$email_provider ?? '',
$user->nickname ?? '',
);
$password_lower = strtolower( $password );
foreach ( $user_data as $data ) {
// Skip if $data is 3 characters or less.
if ( strlen( $data ) <= 3 ) {
continue;
}
if ( ! empty( $data ) && strpos( $password_lower, strtolower( $data ) ) !== false ) {
return true;
}
}
return false;
}
/**
* Check if the password is in the list of compromised/common passwords.
*
* @param string $password The password to check.
*
* @return bool True if the password is in the list of compromised/common passwords, false otherwise.
*/
public function is_leaked_password( string $password ): bool {
if ( ! $this->connection_manager->is_connected() ) {
return false;
}
$hashed_password = sha1( $password );
$password_prefix = substr( $hashed_password, 0, 5 );
$response = $this->request_suffixes( $password_prefix );
$response_code = wp_remote_retrieve_response_code( $response );
if ( is_wp_error( $response ) || 200 !== $response_code || empty( $response['body'] ) ) {
return false;
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
$password_suffix = substr( $hashed_password, 5 );
if ( in_array( $password_suffix, $body['compromised'] ?? array(), true ) ) {
return true;
}
if ( in_array( $password_suffix, $body['common'] ?? array(), true ) ) {
return true;
}
return false;
}
/**
* Check if the password is the current password for the user.
*
* @param int $user_id The user ID.
* @param string $password The password to check.
*
* @return bool True if the password is the current password, false otherwise.
*/
public function is_current_password( int $user_id, string $password ): bool {
$user = get_userdata( $user_id );
if ( ! $user ) {
return false;
}
return wp_check_password( $password, $user->user_pass, $user->ID );
}
/**
* Check if the password has been used recently by the user.
*
* @param \WP_User|\stdClass $user The user data.
* @param string $password The password to check.
*
* @return bool True if the password was recently used, false otherwise.
*/
public function is_recent_password_hash( $user, string $password ): bool {
// Skip on user creation
if ( empty( $user->ID ) ) {
return false;
}
$user_data = $user instanceof \WP_User ? $user : get_userdata( $user->ID );
if ( $this->is_current_password( $user_data->ID, $password ) ) {
return true;
}
$recent_passwords = get_user_meta( $user->ID, Config::RECENT_PASSWORD_HASHES_USER_META_KEY, true );
if ( empty( $recent_passwords ) || ! is_array( $recent_passwords ) ) {
return false;
}
foreach ( $recent_passwords as $old_hashed_password ) {
if ( wp_check_password( $password, $old_hashed_password ) ) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,109 @@
.password-detection-wrapper {
background-color: #f0f0f1;
min-width: 0;
margin: 30px;
color: #3c434a;
font-family: -apple-system, system-ui, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
font-size: 13px;
line-height: 1.4;
}
.password-detection-content {
background: #fff;
max-width: 420px;
margin: auto;
padding: 26px 24px;
font-weight: 400;
overflow: hidden;
border: 1px solid #c3c4c7;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
#jetpack-logo__icon {
height: 30px;
}
}
.password-detection-title {
font-size: 24px;
font-weight: 500;
}
.actions {
display: flex;
flex-direction: column;
gap: 8px;
}
.action {
display: flex;
justify-content: center;
align-items: center;
height: 36px;
cursor: pointer;
width: 100%;
border-radius: 2px;
font-size: 13px;
text-decoration: none;
}
.action-input {
height: 36px;
cursor: pointer;
width: 100%;
box-sizing: border-box;
text-indent: 8px;
&::placeholder {
font-size: 13px;
}
}
.action-verify,
.action-update-password {
margin-top: 10px;
background-color: #00e;
border: 2px solid #00e;
color: #fff;
}
.action-proceed {
background-color: #fff;
border: 2px solid #00e;
color: #00e;
}
a.risks-link,
a.resend-email-link {
color: #00e;
}
.email-status {
text-align: center;
}
.notice {
width: 100%;
display: flex;
align-items: center;
font-weight: 500;
box-sizing: border-box;
justify-content: center;
}
.notice-message {
text-align: center;
margin: 7px 0;
}
.error {
background: #facfd2;
border: 2px solid #e65054;
color: #e65054;
}
.success {
background: #d0e6b8;
border: 2px solid #069e08;
color: #069e08;
}
@@ -0,0 +1,126 @@
#login .wp-pwd,
.user-pass1-wrap {
margin-bottom: 16px;
}
.validation-checklist {
display: flex;
flex-direction: column;
gap: 8px;
margin: 16px 0;
}
.validation-item {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 0;
.validation-icon {
display: inline-block;
background-size: contain;
background-repeat: no-repeat;
background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjNzY3Njc2IiBzdHJva2Utd2lkdGg9IjIiIG9wYWNpdHk9IjAuMyIvPgogIDxwYXRoIGQ9Ik0xMiAyYTEwIDEwIDAgMCAxIDAgMjAiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzc2NzY3NiIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiPgogICAgPGFuaW1hdGVUcmFuc2Zvcm0gYXR0cmlidXRlTmFtZT0idHJhbnNmb3JtIiB0eXBlPSJyb3RhdGUiIGZyb209IjAgMTIgMTIiIHRvPSIzNjAgMTIgMTIiIGR1cj0iMXMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIi8+CiAgPC9wYXRoPgo8L3N2Zz4=);
height: 24px;
width: 24px;
}
.check {
background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIgZmlsbD0iIzAwODcxMCIvPgogIDxwYXRoIGQ9Ik0xNi43IDcuMWwtNi4zIDguNS0zLjMtMi41LS45IDEuMiA0LjUgMy40TDE3LjkgOHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg==);
}
.cross {
background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIgZmlsbD0iI0U2NTA1NCIvPgogIDxwYXRoIGQ9Ik04IDhsOCA4TTE2IDhsLTggOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiLz4KPC9zdmc+);
}
.validation-message {
margin-top: 0;
margin-bottom: 2px;
}
}
.info-popover {
position: relative;
display: inline-block;
height: 20px;
}
.info-icon {
cursor: pointer;
display: inline-block;
background-size: contain;
background-repeat: no-repeat;
background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjQ4IiBoZWlnaHQ9IjQ4IiBmaWxsPSIjQTdBQUFEIj4KICA8cGF0aCBkPSJNMTIgMkM2LjQ4IDIgMiA2LjQ4IDIgMTJzNC40OCAxMCAxMCAxMCAxMC00LjQ4IDEwLTEwUzE3LjUyIDIgMTIgMnptMCAxOGMtNC40MSAwLTgtMy41OS04LThzMy41OS04IDgtOCA4IDMuNTkgOCA4LTMuNTkgOC04IDh6bTEtMTNoLTJ2MmgyVjd6bTAgNGgtMnY2aDJ2LTZ6Ii8+Cjwvc3ZnPg==);
height: 20px;
width: 20px;
}
.popover {
display: none;
position: absolute;
bottom: 30px;
left: 50%;
transform: translateX(-50%);
background: #333;
color: #fff;
padding: 6px 10px;
border-radius: 4px;
white-space: normal;
width: 150px;
font-size: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
z-index: 10;
text-align: center;
}
.popover-arrow {
position: absolute;
bottom: -6px;
left: 50%;
transform: translateX(-50%);
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 6px solid #333;
}
#your-profile .strength-meter,
#createuser .strength-meter {
margin: 0 1px;
}
.strength-meter {
display: flex;
justify-content: space-between;
align-items: center;
height: 30px;
padding: 0 16px;
margin-bottom: 16px;
border-radius: 0 0 4px 4px;
background-color: #c3c4c7;
}
.strength-meter .strength {
display: flex;
align-items: center;
font-size: 12px;
font-weight: 500;
color: #000;
margin: 0;
}
.branding {
display: flex;
align-items: center;
gap: 4px;
.powered-by {
font-size: 12px;
color: #000;
margin: 0;
}
#jetpack-logo__icon {
height: 18px;
}
}
@@ -0,0 +1,401 @@
/* global jQuery, jetpackData */
jQuery( document ).ready( function ( $ ) {
const UIComponents = {
core: {
passwordInput: $( '#pass1' ),
passwordStrengthResults: $( '#pass-strength-result' ),
weakPasswordConfirmation: $( '.pw-weak' ),
weakPasswordConfirmationCheckbox: $( '.pw-weak input[type="checkbox"]' ),
submitButtons: $( '#submit, #createusersub, #wp-submit' ),
},
passwordValidationStatus: $( '<div>', { id: 'password-validation-status' } ),
validationCheckList: $( '<ul>', { class: 'validation-checklist' } ),
strengthMeter: {},
validationChecklistItems: {},
};
let currentAjaxRequest = null;
/**
* Apply initial validation UI structure and styling
*/
function initializeValidationUI() {
initializeForm();
initializeStrengthMeter();
initializeValidationChecklist();
}
/**
* Generate and append the initial strength meter state
*/
function initializeForm() {
const { passwordInput, passwordStrengthResults } = UIComponents.core;
passwordInput.css( {
'border-color': '#8C8F94',
'border-radius': '4px 4px 0 0',
} );
passwordStrengthResults.hide();
passwordInput.after( UIComponents.passwordValidationStatus );
UIComponents.passwordValidationStatus.append( UIComponents.validationCheckList );
}
/**
* Generate and append the initial strength meter state
*/
function initializeStrengthMeter() {
const strengthMeterWrapper = $( '<div>', {
class: 'strength-meter',
'aria-live': 'polite',
} );
const strengthText = $( '<p>', {
class: 'strength',
text: 'Validating...',
} );
const branding = $( '<div>', { class: 'branding' } )
.append( $( '<p>', { class: 'powered-by', text: 'Powered by ' } ) )
.append( jetpackData.logo );
strengthMeterWrapper.append( strengthText, branding );
UIComponents.validationCheckList.before( strengthMeterWrapper );
UIComponents.strengthMeter = {
wrapper: strengthMeterWrapper,
text: strengthText,
branding,
};
}
/**
* Generate and append the initial validation checklist state
*/
function initializeValidationChecklist() {
Object.entries( jetpackData.validationInitialState ).forEach( ( [ key, value ] ) => {
const listItem = $( '<li>', { class: 'validation-item', 'data-key': key } );
// Hide the core and backslash validation items by default
if ( [ 'core', 'contains_backslash' ].includes( key ) ) {
listItem.hide();
}
const validationIcon = $( '<span>', {
class: 'validation-icon',
} );
const validationMessage = $( '<p>', {
text: value.message,
class: 'validation-message',
} );
const infoIconPopover = value.info ? createInfoIconPopover( value.info ) : null;
listItem.append( validationIcon, validationMessage, infoIconPopover );
UIComponents.validationCheckList.append( listItem );
UIComponents.validationChecklistItems[ key ] = {
icon: validationIcon,
text: validationMessage,
item: listItem,
};
} );
}
/**
* Debounce function to limit the number of requests
* @param {Function} func - The function to debounce
* @param {number} delay - The delay in milliseconds
*
* @return {Function} - The debounced function
*/
function debounce( func, delay ) {
let timer;
return function () {
clearTimeout( timer );
timer = setTimeout( () => func.apply( this, arguments ), delay );
};
}
/**
* Bind events to the UI components
*/
function bindEvents() {
const { passwordInput } = UIComponents.core;
passwordInput.on( 'input', debounce( validatePassword, 250 ) );
passwordInput.on( 'pwupdate', validatePassword );
}
/**
* Validate the current password input
*/
function validatePassword() {
const { passwordInput, passwordStrengthResults } = UIComponents.core;
const password = passwordInput.val();
if ( currentAjaxRequest ) {
const oldRequest = currentAjaxRequest;
currentAjaxRequest = null;
oldRequest.abort();
}
if ( ! password?.trim() ) {
updateValidationUI( 'empty' );
return;
}
// Ensure core strength meter is hidden
passwordStrengthResults.hide();
updateValidationUI( 'loading' );
currentAjaxRequest = $.ajax( {
url: jetpackData.ajaxurl,
type: 'POST',
data: {
action: 'validate_password_ajax',
nonce: jetpackData.nonce,
password: password,
user_specific: jetpackData.userSpecific,
},
success: handleValidationResponse,
error: handleValidationError,
} );
}
/**
* Handles the password validation response.
* @param {object} response - The response object.
*/
function handleValidationResponse( response ) {
currentAjaxRequest = null;
if ( response.success ) {
updateValidationUI( 'results', response.data.state );
} else {
restoreCoreStrengthMeter();
}
}
/**
* Handles validation errors.
* @param {object} jqXHR - The jqXHR object.
* @param {any} textStatus - The status of the request.
*/
function handleValidationError( jqXHR, textStatus ) {
if ( textStatus !== 'abort' ) {
restoreCoreStrengthMeter();
}
}
/**
* Get the core validation state
* @return {boolean} - Whether the core validation failed
*/
function getCoreValidationState() {
const corePasswordStrengthResultsClass =
UIComponents.core.passwordStrengthResults.attr( 'class' ) || '';
return ! (
corePasswordStrengthResultsClass.includes( 'strong' ) ||
corePasswordStrengthResultsClass.includes( 'good' )
);
}
/**
*
* Update the validation UI based on the current state
* @param {string} state - The current validation state
* @param {object} validationState - Object containing validation state
*/
function updateValidationUI( state, validationState ) {
if ( state === 'empty' ) {
renderEmptyState();
return;
}
UIComponents.passwordValidationStatus.show();
if ( state === 'loading' ) {
renderLoadingState();
return;
}
if ( validationState ) {
renderResultsState( validationState );
}
}
/**
* Render the empty input state
*/
function renderEmptyState() {
const { weakPasswordConfirmation, passwordInput } = UIComponents.core;
weakPasswordConfirmation.hide();
passwordInput.css( {
'border-color': '#8C8F94',
'border-radius': '4px',
} );
UIComponents.passwordValidationStatus.hide();
}
/**
* Render the loading state
*/
function renderLoadingState() {
renderFormLoadingState();
renderStrengthMeterLoadingState();
renderValidationChecklistLoadingState();
}
/**
* Render the form loading state
*/
function renderFormLoadingState() {
const { submitButtons, passwordInput } = UIComponents.core;
submitButtons.prop( 'disabled', true );
passwordInput.css( {
'border-color': '#C3C4C7',
'border-radius': '4px 4px 0px 0px',
} );
UIComponents.passwordValidationStatus.show();
}
/**
* Render the strength meter loading state
*/
function renderStrengthMeterLoadingState() {
const { wrapper, text } = UIComponents.strengthMeter;
text.text( 'Validating...' );
wrapper.css( 'background-color', '#C3C4C7' );
}
/**
* Render the validation checklist loading state
*/
function renderValidationChecklistLoadingState() {
Object.entries( UIComponents.validationChecklistItems ).forEach( ( [ key, itemData ] ) => {
const { icon, text, item } = itemData;
icon.removeClass( 'check cross' );
text.css( { color: '#3C434A' } );
// Re-hide the core and contains_backslash items
if ( [ 'core', 'contains_backslash' ].includes( key ) ) {
item.hide();
}
} );
UIComponents.strengthMeter.text.text( 'Validating...' );
UIComponents.strengthMeter.wrapper.css( 'background-color', '#C3C4C7' );
}
/**
* Render the validation results state
* @param {object} validationState - Object containing validation state
*/
function renderResultsState( validationState ) {
validationState.core.status = getCoreValidationState();
const isPasswordStrong = Object.values( validationState ).every( item => ! item.status );
const color = isPasswordStrong ? '#9DD977' : '#FFABAF';
const failedValidationKeys = ! isPasswordStrong
? Object.keys( validationState ).filter( key => validationState[ key ].status )
: [];
renderFormResultsState( isPasswordStrong, color );
renderStengthMeterResultsState( isPasswordStrong, color );
renderValidationChecklistResultsState( failedValidationKeys );
}
/**
* Update the form elements based on the current password strength
* @param {boolean} isPasswordStrong - Whether the password is strong
* @param {string} color - The color to apply to the form elements
*/
function renderFormResultsState( isPasswordStrong, color ) {
const {
passwordInput,
weakPasswordConfirmation,
weakPasswordConfirmationCheckbox,
submitButtons,
} = UIComponents.core;
passwordInput.css( { 'border-color': color, 'border-radius': '4px 4px 0px 0px' } );
weakPasswordConfirmation.css( 'display', isPasswordStrong ? 'none' : 'table-row' );
submitButtons.prop(
'disabled',
! isPasswordStrong && ! weakPasswordConfirmationCheckbox.prop( 'checked' )
);
}
/**
*
* Update the strength meter based on the current password strength
* @param {boolean} isPasswordStrong - Whether the password is strong
* @param {string} color - The color to apply to the strength meter
*/
function renderStengthMeterResultsState( isPasswordStrong, color ) {
const { wrapper, text } = UIComponents.strengthMeter;
text.text( isPasswordStrong ? 'Strong' : 'Weak' );
wrapper.css( 'background-color', color );
}
/**
*
* Update the validation checklist based on the failed validation keys
* @param {Array} failedValidationKeys - Array containing failed validation keys
*/
function renderValidationChecklistResultsState( failedValidationKeys ) {
Object.entries( UIComponents.validationChecklistItems ).forEach( ( [ key, itemData ] ) => {
const { icon, text, item } = itemData;
const validationFailed = failedValidationKeys.includes( key );
icon.attr( 'class', `validation-icon ${ validationFailed ? 'cross' : 'check' }` );
text.css( { color: validationFailed ? '#E65054' : '#008710' } );
// Display the core and backslash validation items they fail
if ( [ 'core', 'contains_backslash' ].includes( key ) ) {
item.css( 'display', validationFailed ? 'flex' : 'none' );
}
} );
}
/**
* Resets UI to core strength meter.
*/
function restoreCoreStrengthMeter() {
renderEmptyState();
UIComponents.core.passwordStrengthResults.show();
}
/**
* Creates an info popover element.
*
* @param {string} infoText - The text to display in the popover.
* @return {jQuery} - The info popover element.
*/
function createInfoIconPopover( infoText ) {
const popover = $( '<div>', { text: infoText, class: 'popover' } ).append(
$( '<div>', { class: 'popover-arrow' } )
);
const infoIcon = $( '<span>', { class: 'info-icon' } ).hover(
() => popover.fadeIn( 200 ),
() => popover.fadeOut( 200 )
);
return $( '<div>', { class: 'info-popover' } ).append( infoIcon, popover );
}
initializeValidationUI();
bindEvents();
} );