initial
This commit is contained in:
+114
@@ -0,0 +1,114 @@
|
||||
# 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.5] - 2026-06-25
|
||||
### Changed
|
||||
- Defer loading the password feature classes until the Account Protection module is active, reducing the per-request PHP/opcache footprint. [#49806]
|
||||
|
||||
## [0.3.4] - 2026-06-15
|
||||
### Added
|
||||
- Add `jetpack_account_protection_validation_min_length` and `jetpack_account_protection_validation_max_length` filters. [#49500]
|
||||
|
||||
## [0.3.3] - 2026-06-08
|
||||
### Changed
|
||||
- Internal updates.
|
||||
|
||||
## [0.3.2] - 2026-05-19
|
||||
### Changed
|
||||
- Internal updates.
|
||||
|
||||
## [0.3.1] - 2026-05-04
|
||||
### Changed
|
||||
- Internal: No longer require automattic/jetpack-changelogger as a per-project dev dependency. [#48225]
|
||||
|
||||
## [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.5]: https://github.com/Automattic/jetpack-account-protection/compare/v0.3.4...v0.3.5
|
||||
[0.3.4]: https://github.com/Automattic/jetpack-account-protection/compare/v0.3.3...v0.3.4
|
||||
[0.3.3]: https://github.com/Automattic/jetpack-account-protection/compare/v0.3.2...v0.3.3
|
||||
[0.3.2]: https://github.com/Automattic/jetpack-account-protection/compare/v0.3.1...v0.3.2
|
||||
[0.3.1]: https://github.com/Automattic/jetpack-account-protection/compare/v0.3.0...v0.3.1
|
||||
[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
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
<?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.5';
|
||||
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|null
|
||||
*/
|
||||
private $password_detection;
|
||||
|
||||
/**
|
||||
* Password manager instance
|
||||
*
|
||||
* @var Password_Manager|null
|
||||
*/
|
||||
private $password_manager;
|
||||
|
||||
/**
|
||||
* Password strength meter instance
|
||||
*
|
||||
* @var Password_Strength_Meter|null
|
||||
*/
|
||||
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();
|
||||
|
||||
/*
|
||||
* The password collaborators are only used by the runtime hooks, which
|
||||
* only register when the module is active. Keep any injected instances
|
||||
* (used by tests) but otherwise leave them unset and create them lazily,
|
||||
* so their classes are not autoloaded on requests where the module is
|
||||
* disabled.
|
||||
*/
|
||||
$this->password_detection = $password_detection;
|
||||
$this->password_manager = $password_manager;
|
||||
$this->password_strength_meter = $password_strength_meter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazily get the password detection instance.
|
||||
*
|
||||
* @return Password_Detection
|
||||
*/
|
||||
private function get_password_detection(): Password_Detection {
|
||||
if ( null === $this->password_detection ) {
|
||||
$this->password_detection = new Password_Detection();
|
||||
}
|
||||
return $this->password_detection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazily get the password manager instance.
|
||||
*
|
||||
* @return Password_Manager
|
||||
*/
|
||||
private function get_password_manager(): Password_Manager {
|
||||
if ( null === $this->password_manager ) {
|
||||
$this->password_manager = new Password_Manager();
|
||||
}
|
||||
return $this->password_manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazily get the password strength meter instance.
|
||||
*
|
||||
* @return Password_Strength_Meter
|
||||
*/
|
||||
private function get_password_strength_meter(): Password_Strength_Meter {
|
||||
if ( null === $this->password_strength_meter ) {
|
||||
$this->password_strength_meter = new Password_Strength_Meter();
|
||||
}
|
||||
return $this->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 {
|
||||
$password_detection = $this->get_password_detection();
|
||||
add_action( 'wp_authenticate_user', array( $password_detection, 'login_form_password_detection' ), 10, 2 );
|
||||
add_action( 'login_form_password-detection', array( $password_detection, 'render_page' ), 10, 2 );
|
||||
add_action( 'wp_enqueue_scripts', array( $password_detection, 'enqueue_styles' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register hooks for password manager.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_password_manager_hooks(): void {
|
||||
$password_manager = $this->get_password_manager();
|
||||
add_action( 'user_profile_update_errors', array( $password_manager, 'validate_profile_update' ), 10, 3 );
|
||||
add_action( 'validate_password_reset', array( $password_manager, 'validate_password_reset' ), 10, 2 );
|
||||
add_action( 'profile_update', array( $password_manager, 'on_profile_update' ), 10, 2 );
|
||||
add_action( 'after_password_reset', array( $password_manager, 'on_password_reset' ), 10, 1 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register hooks for password strength meter.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_password_strength_meter_hooks(): void {
|
||||
$password_strength_meter = $this->get_password_strength_meter();
|
||||
add_action( 'admin_enqueue_scripts', array( $password_strength_meter, 'enqueue_jetpack_password_strength_meter_profile_script' ) );
|
||||
add_action( 'login_enqueue_scripts', array( $password_strength_meter, 'enqueue_jetpack_password_strength_meter_reset_script' ) );
|
||||
add_action( 'wp_ajax_validate_password_ajax', array( $password_strength_meter, 'validate_password_ajax' ) );
|
||||
add_action( 'wp_ajax_nopriv_validate_password_ajax', array( $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;
|
||||
}
|
||||
}
|
||||
+28
@@ -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;
|
||||
}
|
||||
+170
@@ -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}";
|
||||
}
|
||||
}
|
||||
+547
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+154
@@ -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 );
|
||||
}
|
||||
}
|
||||
+183
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
+44
@@ -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;
|
||||
}
|
||||
}
|
||||
+376
@@ -0,0 +1,376 @@
|
||||
<?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' => sprintf(
|
||||
/* translators: %1$d is the minimum password length, %2$d is the maximum password length. */
|
||||
__( 'Between %1$d and %2$d characters', 'jetpack-account-protection' ),
|
||||
$this->get_min_length(),
|
||||
$this->get_max_length()
|
||||
),
|
||||
'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[] = sprintf(
|
||||
/* translators: %1$d is the minimum password length, %2$d is the maximum password length. */
|
||||
__( '<strong>Error:</strong> The password must be between %1$d and %2$d characters.', 'jetpack-account-protection' ),
|
||||
$this->get_min_length(),
|
||||
$this->get_max_length()
|
||||
);
|
||||
}
|
||||
|
||||
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 get_min_length() and get_max_length() characters, false otherwise.
|
||||
*/
|
||||
public function is_invalid_length( string $password ): bool {
|
||||
$length = strlen( $password );
|
||||
return $length < $this->get_min_length() || $length > $this->get_max_length();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the minimum allowed password length.
|
||||
*
|
||||
* @return int The minimum allowed password length.
|
||||
*/
|
||||
public function get_min_length(): int {
|
||||
/**
|
||||
* Filters the minimum allowed password length for Account Protection.
|
||||
*
|
||||
* The default is a floor: values below it are ignored, so the filter can only
|
||||
* raise the minimum, never lower it.
|
||||
*
|
||||
* @since 0.3.4
|
||||
*
|
||||
* @param int $min_length The minimum allowed password length.
|
||||
*/
|
||||
$min_length = (int) apply_filters( 'jetpack_account_protection_validation_min_length', Config::VALIDATION_SERVICE_MIN_LENGTH );
|
||||
return max( Config::VALIDATION_SERVICE_MIN_LENGTH, $min_length );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the maximum allowed password length.
|
||||
*
|
||||
* @return int The maximum allowed password length.
|
||||
*/
|
||||
public function get_max_length(): int {
|
||||
/**
|
||||
* Filters the maximum allowed password length for Account Protection.
|
||||
*
|
||||
* The default is a floor: values below it are ignored, so the filter can only
|
||||
* raise the maximum, never lower it.
|
||||
*
|
||||
* @since 0.3.4
|
||||
*
|
||||
* @param int $max_length The maximum allowed password length.
|
||||
*/
|
||||
$max_length = (int) apply_filters( 'jetpack_account_protection_validation_max_length', Config::VALIDATION_SERVICE_MAX_LENGTH );
|
||||
return max( Config::VALIDATION_SERVICE_MAX_LENGTH, $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;
|
||||
}
|
||||
}
|
||||
+109
@@ -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;
|
||||
}
|
||||
|
||||
+126
@@ -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;
|
||||
}
|
||||
}
|
||||
+401
@@ -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();
|
||||
} );
|
||||
Reference in New Issue
Block a user