v0.3.0
This commit is contained in:
parent
f936aeb807
commit
968211baad
99 changed files with 15548 additions and 14530 deletions
33
AGENTS.md
33
AGENTS.md
|
|
@ -1,33 +0,0 @@
|
||||||
# AGENT INSTRUCTIONS
|
|
||||||
|
|
||||||
This repository contains the WordPress plugin **2FA (by ROBOTSTXT)**. Follow these rules whenever you work on any file within this repository:
|
|
||||||
|
|
||||||
1. **Language**
|
|
||||||
- Write every piece of documentation, copy, and code comments in English.
|
|
||||||
|
|
||||||
2. **Code standards**
|
|
||||||
- All PHP code must comply with **PHPCS** and **WPCS**.
|
|
||||||
- Use tabs for indentation (no spaces).
|
|
||||||
- Ensure compatibility with **PHP 8.2** or higher.
|
|
||||||
- Provide proper **PHPDoc** annotations for classes, properties, and methods.
|
|
||||||
|
|
||||||
3. **WordPress security**
|
|
||||||
- Sanitize, validate, and escape all user-provided data.
|
|
||||||
- Include nonces in forms and verify them before processing submissions.
|
|
||||||
- Do not suppress validation or authentication errors.
|
|
||||||
|
|
||||||
4. **Plugin structure**
|
|
||||||
- Keep the code modular inside the `includes/` directory.
|
|
||||||
- Place admin-related logic in subdirectories under `includes/admin/`.
|
|
||||||
- Store presentational templates in `templates/`.
|
|
||||||
- Whenever new persistent data (options, tables, user meta, etc.) is introduced, update `uninstall.php` so the plugin removes it on uninstall.
|
|
||||||
|
|
||||||
5. **Testing and tooling**
|
|
||||||
- Run all available checks (PHPCS, PHPUnit, etc.) after making changes.
|
|
||||||
- Summarize the commands executed and their results in the final message.
|
|
||||||
|
|
||||||
6. **Documentation**
|
|
||||||
- Update `readme.txt` and `changelog.txt` whenever functional changes are introduced.
|
|
||||||
- Explain *why* when the reason for a piece of code is not obvious.
|
|
||||||
|
|
||||||
These instructions apply to the entire repository tree.
|
|
||||||
69
CHANGELOG.md
Normal file
69
CHANGELOG.md
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project are documented in this file.
|
||||||
|
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.3.0] - 2026-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Delete-on-uninstall option in admin settings Data Management section (off by default — all data is preserved).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Network admin settings page now correctly saves to `wp_sitemeta` via a dedicated `network_admin_edit_` handler.
|
||||||
|
- Settings option stored with `autoload=false` — not needed on every page load.
|
||||||
|
- Recovery code preview transient TTL reduced from 0 (persistent) to 300 seconds (5 minutes).
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- Email verification codes now use `random_int()` (CSPRNG) instead of `wp_rand()` (Mersenne Twister), consistent with recovery codes and OTP secrets.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- `get_required_capability()` now returns `manage_network_options` in network admin context.
|
||||||
|
- `bin/deploy.sh` now excludes `CLAUDE.md`, `AGENTS.md`, `README.md`, `DOCUMENTATION-*.md`, and `.phpunit.result.cache` from the ZIP artifact.
|
||||||
|
- `update.json` corrected: was shipping SMTP plugin data instead of 2FA plugin data.
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Per-role 2FA method matrix: admins choose exactly which verification methods (email, OTP, recovery codes) are required for each WordPress role, with select-all row and column toggles.
|
||||||
|
- Authenticator app (TOTP) support: secrets stored as Base32, QR code rendered via `bacon/bacon-qr-code`, manual setup key displayed as fallback.
|
||||||
|
- Recovery codes: 10 single-use 8-digit codes, one-time display grid with copy-to-clipboard, mandatory confirmation before activation, auto-refresh when batch exhausted.
|
||||||
|
- Email verification codes: 7-digit codes, 10-minute expiry, 60-second resend throttle.
|
||||||
|
- Configurable verification frequency remembered per device fingerprint (every login / daily / weekly / monthly); administrators can lock the global schedule.
|
||||||
|
- Dedicated stage token (WP nonce) securing the 2FA screen between password validation and code entry.
|
||||||
|
- Method-switch links on the verification screen (OTP ↔ email ↔ recovery codes) without restarting the login.
|
||||||
|
- Multisite support: `Network: true` header; network admins set and lock enforcement settings.
|
||||||
|
- `uninstall.php` removes all plugin options and user meta on deletion.
|
||||||
|
- `bin/deploy.sh` for manual ZIP packaging.
|
||||||
|
- PHPUnit test suite with plugin-header tests.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Settings UI replaces flat forced-roles list with per-role method matrix; existing `force_roles` + `default_method` data is automatically migrated.
|
||||||
|
- Profile method checkboxes require explicit confirmation before activating (OTP: valid 6-digit code; recovery codes: enter one displayed code).
|
||||||
|
- Required methods indicated with a "required for your role" badge in the profile; checkboxes disabled and hidden inputs ensure values survive submission.
|
||||||
|
- Login screen hides username/password fields, removes Remember Me, focuses code input, and auto-submits when digit count is reached.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- QR generation errors caught and surfaced to administrators; graceful fallback to text setup key.
|
||||||
|
- Recovery-code preview persists via transient until explicitly acknowledged.
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- All `$_POST`/`$_GET`/`$_SERVER` reads guarded with `is_string()` before passing to sanitize functions.
|
||||||
|
- PHPStan level 9 passes with zero errors; no mixed-type casts.
|
||||||
|
- `composer audit`: no known vulnerabilities in any dependency.
|
||||||
|
|
||||||
|
## [0.1.0] - 2024-04-08
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Initial plugin skeleton with placeholder classes for login handling, user profile, and admin settings.
|
||||||
|
- Initial documentation files.
|
||||||
|
|
@ -1,2 +0,0 @@
|
||||||
# robotstxt-2fa
|
|
||||||
Simple 2FA WordPress plugin
|
|
||||||
|
|
@ -1,42 +1,69 @@
|
||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
### Added
|
|
||||||
- Authenticator app support with stored secrets and QR provisioning powered by the optional `bacon/bacon-qr-code` library.
|
|
||||||
- Recovery code confirmation workflow that requires entering one of the freshly generated codes before hiding them.
|
|
||||||
- Single-use recovery codes with profile management, one-time display, and login validation.
|
|
||||||
- Dedicated verification stage token that secures 2FA screens and allows protected email code resends.
|
|
||||||
- Admin settings page with role-based enforcement controls for two-factor authentication.
|
|
||||||
- Uninstall routine that removes stored plugin options.
|
|
||||||
- Network-wide enforcement options for WordPress multisite installations.
|
|
||||||
- Email-based verification codes with throttled delivery and expiry handling.
|
|
||||||
- Configurable verification frequency that remembers trusted devices while allowing administrators to lock the schedule per site.
|
|
||||||
|
|
||||||
### Changed
|
## [0.3.0] - 2026-06-05
|
||||||
- Profile method toggles now start unchecked and require validating authenticator and recovery codes before activation, with new inline prompts and regenerated secrets when options are disabled.
|
|
||||||
- The profile screen now keeps recovery codes visible in a two-column grid until one is confirmed, shows remaining counts, and automatically refreshes the list when the stored batch is exhausted.
|
### Added
|
||||||
- Email verification now displays the destination address alongside the method label.
|
|
||||||
- The login verification screen now hides the username/password fields, exposes a back-to-login link, and supports email code resends from a dedicated query-flagged URL.
|
- Delete-on-uninstall option (disabled by default — all plugin data is preserved on removal).
|
||||||
- The verification stage now enforces authenticator app codes when they are enabled and exposes secure links to switch between OTP, email, and recovery-code challenges without restarting the login.
|
|
||||||
- Promoted the settings interface to a dedicated top-level Two-Factor Authentication menu for easier discovery.
|
### Security
|
||||||
- Adjusted the Two-Factor Authentication menu position so it appears within the plugins section of the admin navigation.
|
|
||||||
- User profile settings now persist preferences and automatically enforce role-based 2FA requirements.
|
- Email verification codes now use `random_int()` (CSPRNG) for cryptographically secure code generation.
|
||||||
- The login screen now auto-submits verification forms once the active method reaches its required length (six digits for OTP, seven for email, eight for recovery codes) and removes the Remember Me control during OTP checks.
|
- Recovery code preview transient TTL reduced from indefinite to 5 minutes.
|
||||||
- Recovery code requests now submit through the native profile form, regenerate codes server-side, and remember the section anchor on the redirect so the refreshed screen focuses the two-factor settings.
|
|
||||||
- The refreshed profile screen renders the newly issued ten codes inside a notice, including copy controls and updated status messaging, without relying on JavaScript-driven form submissions.
|
|
||||||
- The generator button now submits the profile form directly, honours core capability checks, and shares nonce validation with the existing profile workflow.
|
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- Prevented a fatal error on the profile screen by exposing the recovery code batch size helper used during rendering.
|
|
||||||
- Corrected the recovery-code confirmation flow so previews persist until acknowledged and the confirmation code is accepted.
|
- Network admin settings now save correctly via a dedicated handler writing to `wp_sitemeta`.
|
||||||
- Hardened authenticator QR generation by catching library errors and pointing administrators to the required bacon/bacon-qr-code ^3.0 dependency.
|
- Settings option registered with `autoload=false` to avoid loading on every page request.
|
||||||
- Improved recovery-code AJAX error handling so failed requests surface localized messages instead of silently failing.
|
- `update.json` corrected to reference the 2FA plugin instead of the SMTP plugin.
|
||||||
- Forced roles now see two-factor authentication enabled with the default email method selected in their profile, and per-user data is purged during uninstall.
|
|
||||||
- Restored the login verification handlers so the authenticate filter no longer triggers fatal errors and email challenges complete successfully.
|
**Compatibility**
|
||||||
- Ensured the profile recovery-code generator always reaches `admin-ajax.php`, even when localized data is missing, so the button reliably displays the codes inline.
|
|
||||||
|
* WordPress: 6.4 – 7.1
|
||||||
|
* PHP: 8.2 – 8.5
|
||||||
|
|
||||||
|
**Tests**
|
||||||
|
|
||||||
|
* PHP Coding Standards: PHP_CodeSniffer 3.13.5 / WPCS 3.3.0
|
||||||
|
* PHPStan: level 9 — 0 errors
|
||||||
|
* PHPCompatibility: 8.2–8.5 — 0 issues
|
||||||
|
* PHPUnit: 9.6.34 — 42 tests, 109 assertions
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Per-role 2FA method matrix in admin settings: administrators can now choose exactly which verification methods (email, authenticator app, recovery codes) are required for each WordPress role, with select-all row and column controls.
|
||||||
|
- Authenticator app (TOTP) support: stored secrets, QR code provisioning via `bacon/bacon-qr-code`, manual setup key display, and one-time activation confirmation.
|
||||||
|
- Recovery codes: 10 single-use 8-digit codes with profile management, one-time display grid, copy-to-clipboard, and mandatory confirmation before activation.
|
||||||
|
- Email-based verification codes with throttled delivery (60 s resend cooldown) and 10-minute expiry.
|
||||||
|
- Configurable verification frequency (every login, daily, weekly, or every 28 days) remembered per device fingerprint; administrators can lock the global schedule.
|
||||||
|
- Dedicated verification stage token (WP nonce) securing the 2FA screen between password validation and code submission.
|
||||||
|
- Secure method-switch links on the verification screen letting users change between OTP, email, and recovery-code challenges without restarting the login.
|
||||||
|
- Network-wide multisite support: network administrators can set and lock enforcement settings across all sites (`Network: true` header).
|
||||||
|
- Uninstall routine removing all plugin options and user meta.
|
||||||
|
- Admin settings page as a top-level menu with `manage_options` capability guard.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Settings page now uses the per-role method matrix instead of a flat forced-roles list; old `force_roles` + `default_method` data is automatically migrated on first read.
|
||||||
|
- Profile method checkboxes require explicit confirmation: OTP demands a valid 6-digit code, recovery codes demand entering one of the displayed codes before the method activates.
|
||||||
|
- Profile screen regenerates the OTP secret when the authenticator method is disabled and provides a "Generate new secret" button.
|
||||||
|
- Recovery code batch exhaustion now auto-generates a fresh batch and surfaces a confirmation prompt rather than locking the user out.
|
||||||
|
- Login screen hides the username/password fields, removes the Remember Me checkbox, and focuses the verification code input during the 2FA stage.
|
||||||
|
- Login form auto-submits once the input reaches the method's expected digit count.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Hardened authenticator QR generation by catching library errors and guiding administrators to the required dependency.
|
||||||
|
- Recovery-code preview persists via transient until explicitly acknowledged; fixes cases where codes disappeared before confirmation.
|
||||||
|
|
||||||
## [0.1.0] - 2024-04-08
|
## [0.1.0] - 2024-04-08
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- Initial skeleton for the 2FA (by ROBOTSTXT) plugin.
|
- Initial skeleton for the 2FA (by ROBOTSTXT) plugin.
|
||||||
- Initial documentation files (`readme.txt`, `AGENTS.md`, `changelog.txt`).
|
- Initial documentation files (`readme.txt`, `AGENTS.md`, `changelog.txt`).
|
||||||
- Placeholder classes for login handling, user profile integration, and admin settings.
|
- Placeholder classes for login handling, user profile integration, and admin settings.
|
||||||
|
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
{
|
|
||||||
"require": {
|
|
||||||
"bacon/bacon-qr-code": "^3.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
123
composer.lock
generated
123
composer.lock
generated
|
|
@ -1,123 +0,0 @@
|
||||||
{
|
|
||||||
"_readme": [
|
|
||||||
"This file locks the dependencies of your project to a known state",
|
|
||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
|
||||||
"This file is @generated automatically"
|
|
||||||
],
|
|
||||||
"content-hash": "9d7cd0dbebfa0273a358b926795e7b8a",
|
|
||||||
"packages": [
|
|
||||||
{
|
|
||||||
"name": "bacon/bacon-qr-code",
|
|
||||||
"version": "v3.0.1",
|
|
||||||
"source": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/Bacon/BaconQrCode.git",
|
|
||||||
"reference": "f9cc1f52b5a463062251d666761178dbdb6b544f"
|
|
||||||
},
|
|
||||||
"dist": {
|
|
||||||
"type": "zip",
|
|
||||||
"url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/f9cc1f52b5a463062251d666761178dbdb6b544f",
|
|
||||||
"reference": "f9cc1f52b5a463062251d666761178dbdb6b544f",
|
|
||||||
"shasum": ""
|
|
||||||
},
|
|
||||||
"require": {
|
|
||||||
"dasprid/enum": "^1.0.3",
|
|
||||||
"ext-iconv": "*",
|
|
||||||
"php": "^8.1"
|
|
||||||
},
|
|
||||||
"require-dev": {
|
|
||||||
"phly/keep-a-changelog": "^2.12",
|
|
||||||
"phpunit/phpunit": "^10.5.11 || 11.0.4",
|
|
||||||
"spatie/phpunit-snapshot-assertions": "^5.1.5",
|
|
||||||
"squizlabs/php_codesniffer": "^3.9"
|
|
||||||
},
|
|
||||||
"suggest": {
|
|
||||||
"ext-imagick": "to generate QR code images"
|
|
||||||
},
|
|
||||||
"type": "library",
|
|
||||||
"autoload": {
|
|
||||||
"psr-4": {
|
|
||||||
"BaconQrCode\\": "src/"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"notification-url": "https://packagist.org/downloads/",
|
|
||||||
"license": [
|
|
||||||
"BSD-2-Clause"
|
|
||||||
],
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "Ben Scholzen 'DASPRiD'",
|
|
||||||
"email": "mail@dasprids.de",
|
|
||||||
"homepage": "https://dasprids.de/",
|
|
||||||
"role": "Developer"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "BaconQrCode is a QR code generator for PHP.",
|
|
||||||
"homepage": "https://github.com/Bacon/BaconQrCode",
|
|
||||||
"support": {
|
|
||||||
"issues": "https://github.com/Bacon/BaconQrCode/issues",
|
|
||||||
"source": "https://github.com/Bacon/BaconQrCode/tree/v3.0.1"
|
|
||||||
},
|
|
||||||
"time": "2024-10-01T13:55:55+00:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "dasprid/enum",
|
|
||||||
"version": "1.0.7",
|
|
||||||
"source": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/DASPRiD/Enum.git",
|
|
||||||
"reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce"
|
|
||||||
},
|
|
||||||
"dist": {
|
|
||||||
"type": "zip",
|
|
||||||
"url": "https://api.github.com/repos/DASPRiD/Enum/zipball/b5874fa9ed0043116c72162ec7f4fb50e02e7cce",
|
|
||||||
"reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce",
|
|
||||||
"shasum": ""
|
|
||||||
},
|
|
||||||
"require": {
|
|
||||||
"php": ">=7.1 <9.0"
|
|
||||||
},
|
|
||||||
"require-dev": {
|
|
||||||
"phpunit/phpunit": "^7 || ^8 || ^9 || ^10 || ^11",
|
|
||||||
"squizlabs/php_codesniffer": "*"
|
|
||||||
},
|
|
||||||
"type": "library",
|
|
||||||
"autoload": {
|
|
||||||
"psr-4": {
|
|
||||||
"DASPRiD\\Enum\\": "src/"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"notification-url": "https://packagist.org/downloads/",
|
|
||||||
"license": [
|
|
||||||
"BSD-2-Clause"
|
|
||||||
],
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "Ben Scholzen 'DASPRiD'",
|
|
||||||
"email": "mail@dasprids.de",
|
|
||||||
"homepage": "https://dasprids.de/",
|
|
||||||
"role": "Developer"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "PHP 7.1 enum implementation",
|
|
||||||
"keywords": [
|
|
||||||
"enum",
|
|
||||||
"map"
|
|
||||||
],
|
|
||||||
"support": {
|
|
||||||
"issues": "https://github.com/DASPRiD/Enum/issues",
|
|
||||||
"source": "https://github.com/DASPRiD/Enum/tree/1.0.7"
|
|
||||||
},
|
|
||||||
"time": "2025-09-16T12:23:56+00:00"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"packages-dev": [],
|
|
||||||
"aliases": [],
|
|
||||||
"minimum-stability": "stable",
|
|
||||||
"stability-flags": [],
|
|
||||||
"prefer-stable": false,
|
|
||||||
"prefer-lowest": false,
|
|
||||||
"platform": [],
|
|
||||||
"platform-dev": [],
|
|
||||||
"plugin-api-version": "2.6.0"
|
|
||||||
}
|
|
||||||
|
|
@ -32,6 +32,17 @@ class Settings_Page {
|
||||||
*/
|
*/
|
||||||
private const PAGE_SLUG = 'robotstxt-2fa-settings';
|
private const PAGE_SLUG = 'robotstxt-2fa-settings';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verification methods available for per-role configuration.
|
||||||
|
*
|
||||||
|
* @var array<string, string>
|
||||||
|
*/
|
||||||
|
private const AVAILABLE_METHODS = array(
|
||||||
|
'email' => 'Email code',
|
||||||
|
'otp' => 'Authenticator app (OTP)',
|
||||||
|
'recovery_codes' => 'Recovery codes',
|
||||||
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register admin-related hooks.
|
* Register admin-related hooks.
|
||||||
*
|
*
|
||||||
|
|
@ -42,6 +53,7 @@ class Settings_Page {
|
||||||
|
|
||||||
if ( is_multisite() ) {
|
if ( is_multisite() ) {
|
||||||
add_action( 'network_admin_menu', array( $this, 'register_network_menu' ) );
|
add_action( 'network_admin_menu', array( $this, 'register_network_menu' ) );
|
||||||
|
add_action( 'network_admin_edit_robotstxt_2fa_network_save', array( $this, 'handle_network_save' ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
add_action( 'admin_init', array( $this, 'register_settings' ) );
|
add_action( 'admin_init', array( $this, 'register_settings' ) );
|
||||||
|
|
@ -78,12 +90,20 @@ class Settings_Page {
|
||||||
}
|
}
|
||||||
|
|
||||||
settings_errors( self::OPTION_NAME );
|
settings_errors( self::OPTION_NAME );
|
||||||
|
|
||||||
|
$form_action = $this->is_network_context()
|
||||||
|
? network_admin_url( 'edit.php?action=robotstxt_2fa_network_save' )
|
||||||
|
: 'options.php';
|
||||||
?>
|
?>
|
||||||
<div class="wrap">
|
<div class="wrap">
|
||||||
<h1><?php esc_html_e( 'Two-Factor Authentication settings', 'robotstxt-2fa' ); ?></h1>
|
<h1><?php esc_html_e( 'Two-Factor Authentication settings', 'robotstxt-2fa' ); ?></h1>
|
||||||
<form action="options.php" method="post">
|
<form action="<?php echo esc_url( $form_action ); ?>" method="post">
|
||||||
<?php
|
<?php
|
||||||
settings_fields( self::OPTION_GROUP );
|
if ( $this->is_network_context() ) {
|
||||||
|
wp_nonce_field( 'robotstxt_2fa_network_save', 'robotstxt_2fa_network_nonce' );
|
||||||
|
} else {
|
||||||
|
settings_fields( self::OPTION_GROUP );
|
||||||
|
}
|
||||||
do_settings_sections( self::PAGE_SLUG );
|
do_settings_sections( self::PAGE_SLUG );
|
||||||
submit_button();
|
submit_button();
|
||||||
?>
|
?>
|
||||||
|
|
@ -105,6 +125,7 @@ class Settings_Page {
|
||||||
'type' => 'array',
|
'type' => 'array',
|
||||||
'sanitize_callback' => array( $this, 'sanitize_settings' ),
|
'sanitize_callback' => array( $this, 'sanitize_settings' ),
|
||||||
'default' => $this->get_default_settings(),
|
'default' => $this->get_default_settings(),
|
||||||
|
'autoload' => false,
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -115,29 +136,44 @@ class Settings_Page {
|
||||||
self::PAGE_SLUG
|
self::PAGE_SLUG
|
||||||
);
|
);
|
||||||
|
|
||||||
add_settings_field(
|
add_settings_field(
|
||||||
'robotstxt_2fa_force_roles',
|
'robotstxt_2fa_role_methods',
|
||||||
__( 'Forced roles', 'robotstxt-2fa' ),
|
__( 'Required methods per role', 'robotstxt-2fa' ),
|
||||||
array( $this, 'render_force_roles_field' ),
|
array( $this, 'render_role_methods_field' ),
|
||||||
self::PAGE_SLUG,
|
self::PAGE_SLUG,
|
||||||
'robotstxt_2fa_general'
|
'robotstxt_2fa_general'
|
||||||
);
|
);
|
||||||
|
|
||||||
add_settings_field(
|
add_settings_field(
|
||||||
'robotstxt_2fa_frequency',
|
'robotstxt_2fa_frequency',
|
||||||
__( 'Verification frequency', 'robotstxt-2fa' ),
|
__( 'Verification frequency', 'robotstxt-2fa' ),
|
||||||
array( $this, 'render_frequency_field' ),
|
array( $this, 'render_frequency_field' ),
|
||||||
self::PAGE_SLUG,
|
self::PAGE_SLUG,
|
||||||
'robotstxt_2fa_general'
|
'robotstxt_2fa_general'
|
||||||
);
|
);
|
||||||
|
|
||||||
add_settings_field(
|
add_settings_field(
|
||||||
'robotstxt_2fa_force_frequency',
|
'robotstxt_2fa_force_frequency',
|
||||||
__( 'Enforce frequency', 'robotstxt-2fa' ),
|
__( 'Enforce frequency', 'robotstxt-2fa' ),
|
||||||
array( $this, 'render_force_frequency_field' ),
|
array( $this, 'render_force_frequency_field' ),
|
||||||
self::PAGE_SLUG,
|
self::PAGE_SLUG,
|
||||||
'robotstxt_2fa_general'
|
'robotstxt_2fa_general'
|
||||||
);
|
);
|
||||||
|
|
||||||
|
add_settings_section(
|
||||||
|
'robotstxt_2fa_data',
|
||||||
|
__( 'Data management', 'robotstxt-2fa' ),
|
||||||
|
array( $this, 'render_data_section' ),
|
||||||
|
self::PAGE_SLUG
|
||||||
|
);
|
||||||
|
|
||||||
|
add_settings_field(
|
||||||
|
'robotstxt_2fa_delete_on_uninstall',
|
||||||
|
__( 'Delete data on uninstall', 'robotstxt-2fa' ),
|
||||||
|
array( $this, 'render_delete_on_uninstall_field' ),
|
||||||
|
self::PAGE_SLUG,
|
||||||
|
'robotstxt_2fa_data'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -154,42 +190,186 @@ class Settings_Page {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Render forced roles field.
|
* Render the per-role method matrix field.
|
||||||
|
*
|
||||||
|
* Each row represents a role; each column represents a verification method.
|
||||||
|
* Checking a method for a role forces users of that role to verify with it.
|
||||||
|
* Leaving all methods unchecked for a role makes 2FA optional for that role.
|
||||||
|
* Row and column "select all" controls are provided via JavaScript.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function render_force_roles_field(): void {
|
public function render_role_methods_field(): void {
|
||||||
$settings = $this->get_settings();
|
$settings = $this->get_settings();
|
||||||
$selected_roles = array();
|
$role_methods = $settings['role_methods'];
|
||||||
$disabled_attr = '';
|
$roles = get_editable_roles();
|
||||||
|
$locked = $this->has_network_settings() && ! $this->is_network_context();
|
||||||
if ( isset( $settings['force_roles'] ) && is_array( $settings['force_roles'] ) ) {
|
$disabled = $locked ? disabled( true, true, false ) : '';
|
||||||
$selected_roles = $settings['force_roles'];
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
|
|
||||||
$disabled_attr = disabled( true, true, false );
|
|
||||||
}
|
|
||||||
|
|
||||||
$roles = get_editable_roles();
|
|
||||||
|
|
||||||
if ( empty( $roles ) ) {
|
if ( empty( $roles ) ) {
|
||||||
echo '<p class="description">' . esc_html__( 'No editable roles were found.', 'robotstxt-2fa' ) . '</p>';
|
echo '<p class="description">' . esc_html__( 'No editable roles were found.', 'robotstxt-2fa' ) . '</p>';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ( $roles as $role_key => $role_details ) {
|
$methods = array(
|
||||||
printf(
|
'email' => __( 'Email code', 'robotstxt-2fa' ),
|
||||||
'<label><input type="checkbox" name="%1$s[force_roles][]" value="%2$s" %3$s %4$s/> %5$s</label><br />',
|
'otp' => __( 'Authenticator app', 'robotstxt-2fa' ),
|
||||||
esc_attr( self::OPTION_NAME ),
|
'recovery_codes' => __( 'Recovery codes', 'robotstxt-2fa' ),
|
||||||
esc_attr( $role_key ),
|
);
|
||||||
checked( in_array( $role_key, $selected_roles, true ), true, false ),
|
?>
|
||||||
$disabled_attr,
|
<table class="widefat fixed striped robotstxt-2fa-role-methods-table" id="robotstxt-2fa-role-methods-table" style="max-width:680px;">
|
||||||
esc_html( translate_user_role( $role_details['name'] ) )
|
<thead>
|
||||||
);
|
<tr>
|
||||||
}
|
<th><?php esc_html_e( 'Role', 'robotstxt-2fa' ); ?></th>
|
||||||
|
<?php foreach ( $methods as $method_key => $method_label ) : ?>
|
||||||
|
<th style="text-align:center;">
|
||||||
|
<?php echo esc_html( $method_label ); ?>
|
||||||
|
<?php if ( ! $locked ) : ?>
|
||||||
|
<br />
|
||||||
|
<label style="font-weight:normal;font-size:11px;cursor:pointer;">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="robotstxt-2fa-col-toggle"
|
||||||
|
data-2fa-col="<?php echo esc_attr( $method_key ); ?>"
|
||||||
|
style="margin-top:4px;"
|
||||||
|
/>
|
||||||
|
<?php esc_html_e( 'All', 'robotstxt-2fa' ); ?>
|
||||||
|
</label>
|
||||||
|
<?php endif; ?>
|
||||||
|
</th>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
<?php if ( ! $locked ) : ?>
|
||||||
|
<th style="text-align:center;font-weight:normal;font-size:11px;">
|
||||||
|
<?php esc_html_e( 'All methods', 'robotstxt-2fa' ); ?>
|
||||||
|
</th>
|
||||||
|
<?php endif; ?>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<?php foreach ( $roles as $role_key => $role_details ) : ?>
|
||||||
|
<tr data-2fa-role="<?php echo esc_attr( $role_key ); ?>">
|
||||||
|
<td><?php echo esc_html( translate_user_role( $role_details['name'] ) ); ?></td>
|
||||||
|
<?php foreach ( $methods as $method_key => $method_label ) : ?>
|
||||||
|
<td style="text-align:center;">
|
||||||
|
<label>
|
||||||
|
<span class="screen-reader-text">
|
||||||
|
<?php
|
||||||
|
printf(
|
||||||
|
/* translators: 1: role name, 2: method name. */
|
||||||
|
esc_html__( '%1$s: require %2$s', 'robotstxt-2fa' ),
|
||||||
|
esc_html( translate_user_role( $role_details['name'] ) ),
|
||||||
|
esc_html( $method_label )
|
||||||
|
);
|
||||||
|
?>
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="robotstxt-2fa-cell"
|
||||||
|
data-2fa-role="<?php echo esc_attr( $role_key ); ?>"
|
||||||
|
data-2fa-method="<?php echo esc_attr( $method_key ); ?>"
|
||||||
|
name="<?php echo esc_attr( self::OPTION_NAME ); ?>[role_methods][<?php echo esc_attr( $role_key ); ?>][]"
|
||||||
|
value="<?php echo esc_attr( $method_key ); ?>"
|
||||||
|
<?php checked( in_array( $method_key, $role_methods[ $role_key ] ?? array(), true ) ); ?>
|
||||||
|
<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function. ?>
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</td>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
<?php if ( ! $locked ) : ?>
|
||||||
|
<td style="text-align:center;">
|
||||||
|
<label style="font-size:11px;cursor:pointer;">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="robotstxt-2fa-row-toggle"
|
||||||
|
data-2fa-row="<?php echo esc_attr( $role_key ); ?>"
|
||||||
|
/>
|
||||||
|
<?php esc_html_e( 'All', 'robotstxt-2fa' ); ?>
|
||||||
|
</label>
|
||||||
|
</td>
|
||||||
|
<?php endif; ?>
|
||||||
|
</tr>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<p class="description">
|
||||||
|
<?php esc_html_e( 'Check which verification methods are required for each role. Users assigned to a role with at least one checked method must complete two-factor authentication using one of those methods. Roles with no methods checked leave the choice to the user.', 'robotstxt-2fa' ); ?>
|
||||||
|
</p>
|
||||||
|
<?php if ( ! $locked ) : ?>
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
var table = document.getElementById( 'robotstxt-2fa-role-methods-table' );
|
||||||
|
if ( ! table ) { return; }
|
||||||
|
|
||||||
echo '<p class="description">' . esc_html__( 'Users assigned to the selected roles must enable two-factor authentication. Leave all roles unchecked to allow each user to decide whether to activate 2FA.', 'robotstxt-2fa' ) . '</p>';
|
function cells() {
|
||||||
|
return table.querySelectorAll( '.robotstxt-2fa-cell' );
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateToggle( toggle, checked, total ) {
|
||||||
|
if ( total === 0 ) { return; }
|
||||||
|
toggle.indeterminate = checked > 0 && checked < total;
|
||||||
|
toggle.checked = checked === total;
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncRow( roleKey ) {
|
||||||
|
var rowCells = table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-role="' + roleKey + '"]' );
|
||||||
|
var rowToggle = table.querySelector( '.robotstxt-2fa-row-toggle[data-2fa-row="' + roleKey + '"]' );
|
||||||
|
if ( ! rowToggle ) { return; }
|
||||||
|
var checked = 0;
|
||||||
|
rowCells.forEach( function ( c ) { if ( c.checked ) { checked++; } } );
|
||||||
|
updateToggle( rowToggle, checked, rowCells.length );
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncCol( methodKey ) {
|
||||||
|
var colCells = table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-method="' + methodKey + '"]' );
|
||||||
|
var colToggle = table.querySelector( '.robotstxt-2fa-col-toggle[data-2fa-col="' + methodKey + '"]' );
|
||||||
|
if ( ! colToggle ) { return; }
|
||||||
|
var checked = 0;
|
||||||
|
colCells.forEach( function ( c ) { if ( c.checked ) { checked++; } } );
|
||||||
|
updateToggle( colToggle, checked, colCells.length );
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sync all toggles on load */
|
||||||
|
var allRoles = {}, allMethods = {};
|
||||||
|
cells().forEach( function ( c ) {
|
||||||
|
allRoles[ c.dataset['2faRole'] ] = true;
|
||||||
|
allMethods[ c.dataset['2faMethod'] ] = true;
|
||||||
|
} );
|
||||||
|
Object.keys( allRoles ).forEach( syncRow );
|
||||||
|
Object.keys( allMethods ).forEach( syncCol );
|
||||||
|
|
||||||
|
/* Row toggle: check / uncheck all cells in that role's row */
|
||||||
|
table.querySelectorAll( '.robotstxt-2fa-row-toggle' ).forEach( function ( toggle ) {
|
||||||
|
toggle.addEventListener( 'change', function () {
|
||||||
|
var roleKey = toggle.dataset['2faRow'];
|
||||||
|
table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-role="' + roleKey + '"]' ).forEach( function ( c ) {
|
||||||
|
c.checked = toggle.checked;
|
||||||
|
} );
|
||||||
|
Object.keys( allMethods ).forEach( syncCol );
|
||||||
|
} );
|
||||||
|
} );
|
||||||
|
|
||||||
|
/* Column toggle: check / uncheck all cells in that method's column */
|
||||||
|
table.querySelectorAll( '.robotstxt-2fa-col-toggle' ).forEach( function ( toggle ) {
|
||||||
|
toggle.addEventListener( 'change', function () {
|
||||||
|
var methodKey = toggle.dataset['2faCol'];
|
||||||
|
table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-method="' + methodKey + '"]' ).forEach( function ( c ) {
|
||||||
|
c.checked = toggle.checked;
|
||||||
|
} );
|
||||||
|
Object.keys( allRoles ).forEach( syncRow );
|
||||||
|
} );
|
||||||
|
} );
|
||||||
|
|
||||||
|
/* Individual cell: keep toggles in sync */
|
||||||
|
cells().forEach( function ( c ) {
|
||||||
|
c.addEventListener( 'change', function () {
|
||||||
|
syncRow( c.dataset['2faRole'] );
|
||||||
|
syncCol( c.dataset['2faMethod'] );
|
||||||
|
} );
|
||||||
|
} );
|
||||||
|
}());
|
||||||
|
</script>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -197,7 +377,7 @@ class Settings_Page {
|
||||||
*
|
*
|
||||||
* @param mixed $raw_settings Raw settings submitted by the user.
|
* @param mixed $raw_settings Raw settings submitted by the user.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
|
||||||
*/
|
*/
|
||||||
public function sanitize_settings( $raw_settings ): array {
|
public function sanitize_settings( $raw_settings ): array {
|
||||||
$capability = $this->get_required_capability();
|
$capability = $this->get_required_capability();
|
||||||
|
|
@ -212,160 +392,311 @@ class Settings_Page {
|
||||||
return $this->get_settings();
|
return $this->get_settings();
|
||||||
}
|
}
|
||||||
|
|
||||||
$raw_settings = is_array( $raw_settings ) ? $raw_settings : array();
|
$raw_settings = is_array( $raw_settings ) ? $raw_settings : array();
|
||||||
|
$sanitized = $this->get_default_settings();
|
||||||
|
$current_settings = $this->get_settings();
|
||||||
|
$editable_roles = array_keys( get_editable_roles() );
|
||||||
|
$valid_methods = array_keys( self::AVAILABLE_METHODS );
|
||||||
|
|
||||||
$sanitized = $this->get_default_settings();
|
$sanitized['role_methods'] = array();
|
||||||
$current_settings = $this->get_settings();
|
|
||||||
|
|
||||||
$sanitized['force_roles'] = array();
|
if ( isset( $raw_settings['role_methods'] ) && is_array( $raw_settings['role_methods'] ) ) {
|
||||||
|
foreach ( $raw_settings['role_methods'] as $role_key => $raw_methods ) {
|
||||||
|
$role_key = sanitize_key( is_string( $role_key ) ? $role_key : '' );
|
||||||
|
|
||||||
if ( isset( $raw_settings['force_roles'] ) && is_array( $raw_settings['force_roles'] ) ) {
|
if ( '' === $role_key || ! in_array( $role_key, $editable_roles, true ) ) {
|
||||||
$editable_roles = array_keys( get_editable_roles() );
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
foreach ( $raw_settings['force_roles'] as $role_key ) {
|
if ( ! is_array( $raw_methods ) ) {
|
||||||
$role_key = sanitize_key( $role_key );
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if ( in_array( $role_key, $editable_roles, true ) ) {
|
$methods = array();
|
||||||
$sanitized['force_roles'][] = $role_key;
|
|
||||||
|
foreach ( $raw_methods as $method ) {
|
||||||
|
$method = sanitize_key( is_string( $method ) ? $method : '' );
|
||||||
|
|
||||||
|
if ( in_array( $method, $valid_methods, true ) ) {
|
||||||
|
$methods[] = $method;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( ! empty( $methods ) ) {
|
||||||
|
$sanitized['role_methods'][ $role_key ] = array_values( array_unique( $methods ) );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$sanitized['force_roles'] = array_values( array_unique( $sanitized['force_roles'] ) );
|
$frequency_value = $current_settings['frequency'];
|
||||||
|
|
||||||
$frequency_value = $sanitized['frequency'];
|
if ( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ) {
|
||||||
|
$frequency_value = $raw_settings['frequency'];
|
||||||
if ( isset( $current_settings['frequency'] ) ) {
|
|
||||||
$frequency_value = (string) $current_settings['frequency'];
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( isset( $raw_settings['frequency'] ) ) {
|
|
||||||
$frequency_value = (string) $raw_settings['frequency'];
|
|
||||||
}
|
|
||||||
|
|
||||||
$sanitized['frequency'] = Frequency_Options::sanitize( $frequency_value );
|
|
||||||
|
|
||||||
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
|
|
||||||
$sanitized['force_frequency'] = ! empty( $current_settings['force_frequency'] ?? false );
|
|
||||||
} elseif ( array_key_exists( 'force_frequency', $raw_settings ) ) {
|
|
||||||
$sanitized['force_frequency'] = '1' === (string) $raw_settings['force_frequency'];
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sanitized;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$sanitized['frequency'] = Frequency_Options::sanitize( $frequency_value );
|
||||||
|
|
||||||
|
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
|
||||||
|
$sanitized['force_frequency'] = $current_settings['force_frequency'];
|
||||||
|
} elseif ( array_key_exists( 'force_frequency', $raw_settings ) ) {
|
||||||
|
$sanitized['force_frequency'] = '1' === ( is_scalar( $raw_settings['force_frequency'] ) ? (string) $raw_settings['force_frequency'] : '' );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( array_key_exists( 'delete_on_uninstall', $raw_settings ) ) {
|
||||||
|
$sanitized['delete_on_uninstall'] = '1' === ( is_scalar( $raw_settings['delete_on_uninstall'] ) ? (string) $raw_settings['delete_on_uninstall'] : '' );
|
||||||
|
}
|
||||||
|
|
||||||
|
return $sanitized;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve plugin settings.
|
* Retrieve plugin settings, migrating from legacy format when necessary.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
|
||||||
*/
|
*/
|
||||||
public function get_settings(): array {
|
public function get_settings(): array {
|
||||||
$options = array();
|
$options = array();
|
||||||
|
|
||||||
if ( is_multisite() ) {
|
if ( is_multisite() ) {
|
||||||
/** @var array<string, mixed>|false $network_options */
|
|
||||||
$network_options = get_site_option( self::OPTION_NAME, false );
|
$network_options = get_site_option( self::OPTION_NAME, false );
|
||||||
|
|
||||||
if ( false !== $network_options && is_array( $network_options ) ) {
|
if ( is_array( $network_options ) ) {
|
||||||
$options = $network_options;
|
$options = $network_options;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( empty( $options ) ) {
|
if ( empty( $options ) ) {
|
||||||
/** @var array<string, mixed> $options */
|
$raw = get_option( self::OPTION_NAME, array() );
|
||||||
$options = get_option( self::OPTION_NAME, array() );
|
if ( is_array( $raw ) ) {
|
||||||
|
$options = $raw;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return wp_parse_args( $options, $this->get_default_settings() );
|
return array(
|
||||||
|
'role_methods' => $this->resolve_role_methods( $options ),
|
||||||
|
'frequency' => Frequency_Options::sanitize( isset( $options['frequency'] ) && is_string( $options['frequency'] ) ? $options['frequency'] : '' ),
|
||||||
|
'force_frequency' => ! empty( $options['force_frequency'] ),
|
||||||
|
'delete_on_uninstall' => ! empty( $options['delete_on_uninstall'] ),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve default settings.
|
* Retrieve default settings.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
|
||||||
*/
|
*/
|
||||||
private function get_default_settings(): array {
|
private function get_default_settings(): array {
|
||||||
return array(
|
return array(
|
||||||
'force_roles' => array(),
|
'role_methods' => array(),
|
||||||
'default_method' => 'email',
|
'frequency' => Frequency_Options::FREQUENCY_SESSION,
|
||||||
'frequency' => Frequency_Options::FREQUENCY_SESSION,
|
'force_frequency' => false,
|
||||||
'force_frequency' => false,
|
'delete_on_uninstall' => false,
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve role_methods from stored options, migrating legacy force_roles + default_method if needed.
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $options Raw stored options.
|
||||||
|
*
|
||||||
|
* @return array<string, array<int, string>>
|
||||||
|
*/
|
||||||
|
private function resolve_role_methods( array $options ): array {
|
||||||
|
$valid_methods = array_keys( self::AVAILABLE_METHODS );
|
||||||
|
|
||||||
|
if ( isset( $options['role_methods'] ) && is_array( $options['role_methods'] ) ) {
|
||||||
|
$role_methods = array();
|
||||||
|
|
||||||
|
foreach ( $options['role_methods'] as $role => $methods ) {
|
||||||
|
$role = is_string( $role ) ? sanitize_key( $role ) : '';
|
||||||
|
|
||||||
|
if ( '' === $role || ! is_array( $methods ) ) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$clean = array();
|
||||||
|
|
||||||
|
foreach ( $methods as $m ) {
|
||||||
|
$m = is_string( $m ) ? sanitize_key( $m ) : '';
|
||||||
|
|
||||||
|
if ( in_array( $m, $valid_methods, true ) ) {
|
||||||
|
$clean[] = $m;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( ! empty( $clean ) ) {
|
||||||
|
$role_methods[ $role ] = array_values( array_unique( $clean ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $role_methods;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Migrate legacy force_roles + default_method to role_methods.
|
||||||
* Render verification frequency field.
|
if ( isset( $options['force_roles'] ) && is_array( $options['force_roles'] ) ) {
|
||||||
*
|
$default_method = isset( $options['default_method'] ) && is_string( $options['default_method'] ) ? sanitize_key( $options['default_method'] ) : 'email';
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function render_frequency_field(): void {
|
|
||||||
$settings = $this->get_settings();
|
|
||||||
$selected = Frequency_Options::sanitize( (string) $settings['frequency'] );
|
|
||||||
$disabled_attr = '';
|
|
||||||
|
|
||||||
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
|
if ( ! in_array( $default_method, $valid_methods, true ) ) {
|
||||||
$disabled_attr = disabled( true, true, false );
|
$default_method = 'email';
|
||||||
|
}
|
||||||
|
|
||||||
|
$role_methods = array();
|
||||||
|
|
||||||
|
foreach ( $options['force_roles'] as $role ) {
|
||||||
|
$role = is_string( $role ) ? sanitize_key( $role ) : '';
|
||||||
|
|
||||||
|
if ( '' !== $role ) {
|
||||||
|
$role_methods[ $role ] = array( $default_method );
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$options = Frequency_Options::get_options();
|
return $role_methods;
|
||||||
|
|
||||||
echo '<select name="' . esc_attr( self::OPTION_NAME ) . '[frequency]" ' . $disabled_attr . '>';
|
|
||||||
|
|
||||||
foreach ( $options as $value => $labels ) {
|
|
||||||
printf(
|
|
||||||
'<option value="%1$s" %2$s>%3$s</option>',
|
|
||||||
esc_attr( $value ),
|
|
||||||
selected( $selected, $value, false ),
|
|
||||||
esc_html( $labels['label'] )
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
echo '</select>';
|
|
||||||
|
|
||||||
if ( isset( $options[ $selected ]['description'] ) && '' !== $options[ $selected ]['description'] ) {
|
|
||||||
echo '<p class="description">' . esc_html( $options[ $selected ]['description'] ) . '</p>';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
return array();
|
||||||
* Render frequency enforcement checkbox.
|
}
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function render_force_frequency_field(): void {
|
|
||||||
$settings = $this->get_settings();
|
|
||||||
$is_checked = ! empty( $settings['force_frequency'] );
|
|
||||||
$disabled_attr = '';
|
|
||||||
|
|
||||||
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
|
/**
|
||||||
$disabled_attr = disabled( true, true, false );
|
* Render verification frequency field.
|
||||||
}
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function render_frequency_field(): void {
|
||||||
|
$settings = $this->get_settings();
|
||||||
|
$selected = $settings['frequency'];
|
||||||
|
$disabled_attr = '';
|
||||||
|
|
||||||
if ( '' === $disabled_attr ) {
|
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
|
||||||
printf(
|
$disabled_attr = disabled( true, true, false );
|
||||||
'<input type="hidden" name="%1$s[force_frequency]" value="0" />',
|
|
||||||
esc_attr( self::OPTION_NAME )
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
printf(
|
|
||||||
'<label><input type="checkbox" name="%1$s[force_frequency]" value="1" %2$s %3$s/> %4$s</label>',
|
|
||||||
esc_attr( self::OPTION_NAME ),
|
|
||||||
checked( $is_checked, true, false ),
|
|
||||||
$disabled_attr,
|
|
||||||
esc_html__( 'Prevent users from overriding the global verification frequency.', 'robotstxt-2fa' )
|
|
||||||
);
|
|
||||||
|
|
||||||
echo '<p class="description">' . esc_html__( 'When enabled, users will see the profile frequency control disabled and must follow the global schedule.', 'robotstxt-2fa' ) . '</p>';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$options = Frequency_Options::get_options();
|
||||||
|
|
||||||
|
echo '<select name="' . esc_attr( self::OPTION_NAME ) . '[frequency]" ' . $disabled_attr . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function.
|
||||||
|
|
||||||
|
foreach ( $options as $value => $labels ) {
|
||||||
|
printf(
|
||||||
|
'<option value="%1$s" %2$s>%3$s</option>',
|
||||||
|
esc_attr( $value ),
|
||||||
|
selected( $selected, $value, false ),
|
||||||
|
esc_html( $labels['label'] )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
echo '</select>';
|
||||||
|
|
||||||
|
if ( isset( $options[ $selected ]['description'] ) && '' !== $options[ $selected ]['description'] ) {
|
||||||
|
echo '<p class="description">' . esc_html( $options[ $selected ]['description'] ) . '</p>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render frequency enforcement checkbox.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function render_force_frequency_field(): void {
|
||||||
|
$settings = $this->get_settings();
|
||||||
|
$is_checked = $settings['force_frequency'];
|
||||||
|
$disabled_attr = '';
|
||||||
|
|
||||||
|
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
|
||||||
|
$disabled_attr = disabled( true, true, false );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( '' === $disabled_attr ) {
|
||||||
|
printf(
|
||||||
|
'<input type="hidden" name="%1$s[force_frequency]" value="0" />',
|
||||||
|
esc_attr( self::OPTION_NAME )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
printf(
|
||||||
|
'<label><input type="checkbox" name="%1$s[force_frequency]" value="1" %2$s %3$s/> %4$s</label>',
|
||||||
|
esc_attr( self::OPTION_NAME ),
|
||||||
|
checked( $is_checked, true, false ),
|
||||||
|
$disabled_attr, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function.
|
||||||
|
esc_html__( 'Prevent users from overriding the global verification frequency.', 'robotstxt-2fa' )
|
||||||
|
);
|
||||||
|
|
||||||
|
echo '<p class="description">' . esc_html__( 'When enabled, users will see the profile frequency control disabled and must follow the global schedule.', 'robotstxt-2fa' ) . '</p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the data management section description.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function render_data_section(): void {
|
||||||
|
echo '<p>' . esc_html__( 'Control what happens to plugin data when the plugin is deleted.', 'robotstxt-2fa' ) . '</p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the delete-on-uninstall checkbox.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function render_delete_on_uninstall_field(): void {
|
||||||
|
$settings = $this->get_settings();
|
||||||
|
$is_checked = $settings['delete_on_uninstall'];
|
||||||
|
|
||||||
|
printf(
|
||||||
|
'<input type="hidden" name="%1$s[delete_on_uninstall]" value="0" />',
|
||||||
|
esc_attr( self::OPTION_NAME )
|
||||||
|
);
|
||||||
|
|
||||||
|
printf(
|
||||||
|
'<label><input type="checkbox" name="%1$s[delete_on_uninstall]" value="1" %2$s /> %3$s</label>',
|
||||||
|
esc_attr( self::OPTION_NAME ),
|
||||||
|
checked( $is_checked, true, false ),
|
||||||
|
esc_html__( 'Remove all plugin data when the plugin is deleted.', 'robotstxt-2fa' )
|
||||||
|
);
|
||||||
|
|
||||||
|
echo '<p class="description">' . esc_html__( 'When checked, deleting this plugin will permanently remove all settings, per-user 2FA preferences, stored secrets, recovery codes, and verification history. This action cannot be undone. Leave unchecked (default) to preserve all data if you reinstall later.', 'robotstxt-2fa' ) . '</p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the network admin settings form submission.
|
||||||
|
*
|
||||||
|
* WordPress's Settings API does not work in network admin; this handler
|
||||||
|
* validates the nonce, sanitizes input, and saves via update_site_option().
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function handle_network_save(): void {
|
||||||
|
check_admin_referer( 'robotstxt_2fa_network_save', 'robotstxt_2fa_network_nonce' );
|
||||||
|
|
||||||
|
if ( ! current_user_can( 'manage_network_options' ) ) {
|
||||||
|
wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
$raw = isset( $_POST[ self::OPTION_NAME ] ) && is_array( $_POST[ self::OPTION_NAME ] )
|
||||||
|
? wp_unslash( $_POST[ self::OPTION_NAME ] )
|
||||||
|
: array();
|
||||||
|
|
||||||
|
$sanitized = $this->sanitize_settings( $raw );
|
||||||
|
|
||||||
|
update_site_option( self::OPTION_NAME, $sanitized );
|
||||||
|
|
||||||
|
wp_safe_redirect(
|
||||||
|
add_query_arg(
|
||||||
|
array(
|
||||||
|
'page' => 'robotstxt-2fa-settings',
|
||||||
|
'updated' => 'true',
|
||||||
|
),
|
||||||
|
network_admin_url( 'admin.php' )
|
||||||
|
)
|
||||||
|
);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine the capability required to manage settings.
|
* Determine the capability required to manage settings.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
private function get_required_capability(): string {
|
private function get_required_capability(): string {
|
||||||
return 'manage_options';
|
return $this->is_network_context() ? 'manage_network_options' : 'manage_options';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -412,4 +743,3 @@ class Settings_Page {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -72,10 +72,10 @@ class Plugin {
|
||||||
* Constructor.
|
* Constructor.
|
||||||
*/
|
*/
|
||||||
public function __construct() {
|
public function __construct() {
|
||||||
$this->login_manager = new Login_Form_Manager();
|
$this->login_manager = new Login_Form_Manager();
|
||||||
$this->profile_settings = new Profile_Settings();
|
$this->profile_settings = new Profile_Settings();
|
||||||
$this->recovery_codes = new Recovery_Codes();
|
$this->recovery_codes = new Recovery_Codes();
|
||||||
$this->settings_page = new Settings_Page();
|
$this->settings_page = new Settings_Page();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -44,24 +44,24 @@ class Email_Code_Sender {
|
||||||
*/
|
*/
|
||||||
public function __construct() {
|
public function __construct() {
|
||||||
$this->user_settings_repository = new User_Settings_Repository();
|
$this->user_settings_repository = new User_Settings_Repository();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the expected code length.
|
* Retrieve the expected code length.
|
||||||
*
|
*
|
||||||
* @return int
|
* @return int
|
||||||
*/
|
*/
|
||||||
public function get_code_length(): int {
|
public function get_code_length(): int {
|
||||||
return self::CODE_LENGTH;
|
return self::CODE_LENGTH;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send a verification code to the provided user.
|
* Send a verification code to the provided user.
|
||||||
*
|
*
|
||||||
* @param \WP_User $user User who is requesting authentication.
|
* @param \WP_User $user User who is requesting authentication.
|
||||||
*
|
*
|
||||||
* @return bool True when the email was sent or throttled successfully, false on failure.
|
* @return bool True when the email was sent or throttled successfully, false on failure.
|
||||||
*/
|
*/
|
||||||
public function send_code( \WP_User $user ): bool {
|
public function send_code( \WP_User $user ): bool {
|
||||||
if ( empty( $user->user_email ) || ! is_email( $user->user_email ) ) {
|
if ( empty( $user->user_email ) || ! is_email( $user->user_email ) ) {
|
||||||
return false;
|
return false;
|
||||||
|
|
@ -77,16 +77,18 @@ class Email_Code_Sender {
|
||||||
$code = $this->generate_code();
|
$code = $this->generate_code();
|
||||||
$expires = $current_time + self::EXPIRATION_SECONDS;
|
$expires = $current_time + self::EXPIRATION_SECONDS;
|
||||||
|
|
||||||
$blog_name = wp_specialchars_decode( get_option( 'blogname', '' ), ENT_QUOTES );
|
$raw_blogname = get_option( 'blogname', '' );
|
||||||
$display_name = wp_strip_all_tags( $user->display_name ?: $user->user_login );
|
$blog_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES );
|
||||||
$email_subject = sprintf( __( '[%s] Your verification code', 'robotstxt-2fa' ), $blog_name ?: __( 'WordPress', 'robotstxt-2fa' ) );
|
$display_name = wp_strip_all_tags( ! empty( $user->display_name ) ? $user->display_name : $user->user_login );
|
||||||
|
/* translators: %s: site name. */
|
||||||
|
$email_subject = sprintf( __( '[%s] Your verification code', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'WordPress', 'robotstxt-2fa' ) );
|
||||||
|
|
||||||
$message_lines = array(
|
$message_lines = array(
|
||||||
/* translators: %s: user display name. */
|
/* translators: %s: user display name. */
|
||||||
sprintf( __( 'Hi %s,', 'robotstxt-2fa' ), $display_name ),
|
sprintf( __( 'Hi %s,', 'robotstxt-2fa' ), $display_name ),
|
||||||
'',
|
'',
|
||||||
/* translators: %s: site name. */
|
/* translators: %s: site name. */
|
||||||
sprintf( __( 'Use the following verification code to finish signing in to %s:', 'robotstxt-2fa' ), $blog_name ?: __( 'your site', 'robotstxt-2fa' ) ),
|
sprintf( __( 'Use the following verification code to finish signing in to %s:', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'your site', 'robotstxt-2fa' ) ),
|
||||||
'',
|
'',
|
||||||
$code,
|
$code,
|
||||||
'',
|
'',
|
||||||
|
|
@ -118,9 +120,9 @@ class Email_Code_Sender {
|
||||||
*/
|
*/
|
||||||
public function verify_code( \WP_User $user, string $code ): bool {
|
public function verify_code( \WP_User $user, string $code ): bool {
|
||||||
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
|
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
|
||||||
$code = preg_replace( '/[^0-9]/', '', $code );
|
$code = preg_replace( '/[^0-9]/', '', $code ) ?? '';
|
||||||
|
|
||||||
if ( empty( $challenge['hash'] ) ) {
|
if ( '' === $challenge['hash'] ) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -142,7 +144,7 @@ class Email_Code_Sender {
|
||||||
*/
|
*/
|
||||||
private function generate_code(): string {
|
private function generate_code(): string {
|
||||||
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
||||||
$code = (string) wp_rand( 0, (int) $max_value );
|
$code = (string) random_int( 0, $max_value );
|
||||||
|
|
||||||
return str_pad( $code, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
return str_pad( $code, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -43,23 +43,23 @@ class Login_Form_Manager {
|
||||||
private const QUERY_METHOD = 'robotstxt-2fa-method';
|
private const QUERY_METHOD = 'robotstxt-2fa-method';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query argument carrying the nonce that validates the verification stage.
|
* Query argument carrying the nonce that validates the verification stage.
|
||||||
*/
|
*/
|
||||||
private const QUERY_STAGE_TOKEN = 'robotstxt-2fa-stage-token';
|
private const QUERY_STAGE_TOKEN = 'robotstxt-2fa-stage-token';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query argument requesting a new verification code delivery.
|
* Query argument requesting a new verification code delivery.
|
||||||
*/
|
*/
|
||||||
private const QUERY_RESEND = 'robotstxt-2fa-resend';
|
private const QUERY_RESEND = 'robotstxt-2fa-resend';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query argument providing additional contextual notices for the stage.
|
* Query argument providing additional contextual notices for the stage.
|
||||||
*/
|
*/
|
||||||
private const QUERY_NOTICE = 'robotstxt-2fa-notice';
|
private const QUERY_NOTICE = 'robotstxt-2fa-notice';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query argument requesting a verification method switch during the stage.
|
* Query argument requesting a verification method switch during the stage.
|
||||||
*/
|
*/
|
||||||
private const QUERY_SWITCH = 'robotstxt-2fa-switch';
|
private const QUERY_SWITCH = 'robotstxt-2fa-switch';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -83,8 +83,8 @@ class Login_Form_Manager {
|
||||||
private const FIELD_METHOD = 'robotstxt_2fa_method';
|
private const FIELD_METHOD = 'robotstxt_2fa_method';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Form field carrying the nonce that validates the verification stage.
|
* Form field carrying the nonce that validates the verification stage.
|
||||||
*/
|
*/
|
||||||
private const FIELD_STAGE_TOKEN = 'robotstxt_2fa_stage_token';
|
private const FIELD_STAGE_TOKEN = 'robotstxt_2fa_stage_token';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -93,8 +93,8 @@ class Login_Form_Manager {
|
||||||
private const STAGE_VERIFY = 'verify';
|
private const STAGE_VERIFY = 'verify';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Nonce action used to secure verification stage requests.
|
* Nonce action used to secure verification stage requests.
|
||||||
*/
|
*/
|
||||||
private const STAGE_TOKEN_ACTION = 'robotstxt_2fa_stage_token';
|
private const STAGE_TOKEN_ACTION = 'robotstxt_2fa_stage_token';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -144,11 +144,11 @@ class Login_Form_Manager {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle verification method switches requested on the login stage.
|
* Handle verification method switches requested on the login stage.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
private function process_method_switch(): void {
|
private function process_method_switch(): void {
|
||||||
$method = $this->get_requested_method();
|
$method = $this->get_requested_method();
|
||||||
|
|
||||||
$login = $this->get_requested_login();
|
$login = $this->get_requested_login();
|
||||||
|
|
@ -194,37 +194,37 @@ class Login_Form_Manager {
|
||||||
|
|
||||||
wp_safe_redirect( $redirect_url );
|
wp_safe_redirect( $redirect_url );
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register WordPress hooks.
|
* Register WordPress hooks.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function register_hooks(): void {
|
public function register_hooks(): void {
|
||||||
add_action( 'login_init', array( $this, 'maybe_process_stage_requests' ) );
|
add_action( 'login_init', array( $this, 'maybe_process_stage_requests' ) );
|
||||||
add_action( 'login_form', array( $this, 'render_form_fields' ) );
|
add_action( 'login_form', array( $this, 'render_form_fields' ) );
|
||||||
add_action( 'login_head', array( $this, 'render_stage_styles' ) );
|
add_action( 'login_head', array( $this, 'render_stage_styles' ) );
|
||||||
add_action( 'login_footer', array( $this, 'render_stage_scripts' ) );
|
add_action( 'login_footer', array( $this, 'render_stage_scripts' ) );
|
||||||
add_filter( 'login_message', array( $this, 'filter_login_message' ) );
|
add_filter( 'login_message', array( $this, 'filter_login_message' ) );
|
||||||
add_filter( 'authenticate', array( $this, 'maybe_complete_verification' ), 5, 3 );
|
add_filter( 'authenticate', array( $this, 'maybe_complete_verification' ), 5, 3 );
|
||||||
add_filter( 'authenticate', array( $this, 'enforce_verification_challenge' ), 30, 3 );
|
add_filter( 'authenticate', array( $this, 'enforce_verification_challenge' ), 30, 3 );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Render custom fields on the login form.
|
* Render custom fields on the login form.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function render_form_fields(): void {
|
public function render_form_fields(): void {
|
||||||
if ( ! $this->is_verification_stage() ) {
|
if ( ! $this->is_verification_stage() ) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$login = $this->get_requested_login();
|
$login = $this->get_requested_login();
|
||||||
$method = $this->get_requested_method();
|
$method = $this->get_requested_method();
|
||||||
$code_length = $this->get_method_code_length( $method );
|
$code_length = $this->get_method_code_length( $method );
|
||||||
$alternates = array();
|
$alternates = array();
|
||||||
|
|
||||||
if ( '' !== $login ) {
|
if ( '' !== $login ) {
|
||||||
$user = get_user_by( 'login', $login );
|
$user = get_user_by( 'login', $login );
|
||||||
|
|
@ -238,20 +238,20 @@ class Login_Form_Manager {
|
||||||
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::FIELD_LOGIN ), esc_attr( $login ) );
|
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::FIELD_LOGIN ), esc_attr( $login ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::FIELD_METHOD ), esc_attr( $method ) );
|
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::FIELD_METHOD ), esc_attr( $method ) );
|
||||||
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::FIELD_STAGE ), esc_attr( self::STAGE_VERIFY ) );
|
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::FIELD_STAGE ), esc_attr( self::STAGE_VERIFY ) );
|
||||||
|
|
||||||
$stage_token = $this->get_requested_stage_token();
|
$stage_token = $this->get_requested_stage_token();
|
||||||
|
|
||||||
if ( '' !== $stage_token ) {
|
if ( '' !== $stage_token ) {
|
||||||
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::FIELD_STAGE_TOKEN ), esc_attr( $stage_token ) );
|
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::FIELD_STAGE_TOKEN ), esc_attr( $stage_token ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
wp_nonce_field( self::LOGIN_NONCE_ACTION, self::LOGIN_NONCE_FIELD );
|
wp_nonce_field( self::LOGIN_NONCE_ACTION, self::LOGIN_NONCE_FIELD );
|
||||||
?>
|
?>
|
||||||
<p class="robotstxt-2fa-login-field robotstxt-2fa-stage-field">
|
<p class="robotstxt-2fa-login-field robotstxt-2fa-stage-field">
|
||||||
<label for="robotstxt-2fa-token"><?php esc_html_e( 'Verification code', 'robotstxt-2fa' ); ?><br />
|
<label for="robotstxt-2fa-token"><?php esc_html_e( 'Verification code', 'robotstxt-2fa' ); ?><br />
|
||||||
<input type="tel" name="robotstxt_2fa_token" id="robotstxt-2fa-token" class="input" value="" size="<?php echo esc_attr( $code_length ); ?>" maxlength="<?php echo esc_attr( $code_length ); ?>" pattern="\d{<?php echo esc_attr( $code_length ); ?>}" inputmode="numeric" autocomplete="one-time-code" required />
|
<input type="tel" name="robotstxt_2fa_token" id="robotstxt-2fa-token" class="input" value="" size="<?php echo absint( $code_length ); ?>" maxlength="<?php echo absint( $code_length ); ?>" pattern="\d{<?php echo absint( $code_length ); ?>}" inputmode="numeric" autocomplete="one-time-code" required />
|
||||||
</label>
|
</label>
|
||||||
</p>
|
</p>
|
||||||
<?php
|
<?php
|
||||||
|
|
@ -298,58 +298,67 @@ class Login_Form_Manager {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( ! empty( $link_markup ) ) {
|
printf(
|
||||||
printf(
|
'<p class="robotstxt-2fa-alternate description robotstxt-2fa-stage-field">%1$s %2$s</p>',
|
||||||
'<p class="robotstxt-2fa-alternate description robotstxt-2fa-stage-field">%1$s %2$s</p>',
|
esc_html__( 'Prefer a different verification method?', 'robotstxt-2fa' ),
|
||||||
esc_html__( 'Prefer a different verification method?', 'robotstxt-2fa' ),
|
wp_kses_post( implode( ' <span class="robotstxt-2fa-links-separator" aria-hidden="true">•</span> ', $link_markup ) )
|
||||||
wp_kses_post( implode( ' <span class="robotstxt-2fa-links-separator" aria-hidden="true">•</span> ', $link_markup ) )
|
);
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$back_url = wp_login_url( $this->get_requested_redirect() );
|
$back_url = wp_login_url( $this->get_requested_redirect() );
|
||||||
?>
|
?>
|
||||||
<p class="robotstxt-2fa-login-links robotstxt-2fa-stage-field">
|
<p class="robotstxt-2fa-login-links robotstxt-2fa-stage-field">
|
||||||
<a class="robotstxt-2fa-back-link" href="<?php echo esc_url( $back_url ); ?>"><?php esc_html_e( 'Back to login', 'robotstxt-2fa' ); ?></a>
|
<a class="robotstxt-2fa-back-link" href="<?php echo esc_url( $back_url ); ?>"><?php esc_html_e( 'Back to login', 'robotstxt-2fa' ); ?></a>
|
||||||
<?php if ( 'email' === $method && '' !== $stage_token ) : ?>
|
<?php if ( 'email' === $method && '' !== $stage_token ) : ?>
|
||||||
<span class="robotstxt-2fa-links-separator" aria-hidden="true">•</span>
|
<span class="robotstxt-2fa-links-separator" aria-hidden="true">•</span>
|
||||||
<a class="robotstxt-2fa-resend-link" href="<?php echo esc_url( $this->get_stage_url( array( self::QUERY_RESEND => '1', self::QUERY_NOTICE => null ) ) ); ?>"><?php esc_html_e( 'Send the code again', 'robotstxt-2fa' ); ?></a>
|
<a class="robotstxt-2fa-resend-link" href="
|
||||||
|
<?php
|
||||||
|
echo esc_url(
|
||||||
|
$this->get_stage_url(
|
||||||
|
array(
|
||||||
|
self::QUERY_RESEND => '1',
|
||||||
|
self::QUERY_NOTICE => null,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
?>
|
||||||
|
"><?php esc_html_e( 'Send the code again', 'robotstxt-2fa' ); ?></a>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</p>
|
</p>
|
||||||
<?php
|
<?php
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Output inline styles used during the verification stage.
|
* Output inline styles used during the verification stage.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function render_stage_styles(): void {
|
public function render_stage_styles(): void {
|
||||||
if ( ! $this->is_verification_stage() ) {
|
if ( ! $this->is_verification_stage() ) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
?>
|
||||||
<style id="robotstxt-2fa-stage-styles">
|
<style id="robotstxt-2fa-stage-styles">
|
||||||
#loginform .user-pass-wrap,
|
#loginform .user-pass-wrap,
|
||||||
#loginform .login-password,
|
#loginform .login-password,
|
||||||
#loginform label[for="user_pass"],
|
#loginform label[for="user_pass"],
|
||||||
#loginform #user_pass,
|
#loginform #user_pass,
|
||||||
#loginform .wp-pwd,
|
#loginform .wp-pwd,
|
||||||
#loginform .wp-hide-pw {
|
#loginform .wp-hide-pw {
|
||||||
display: none !important;
|
display: none !important;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<?php
|
<?php
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Display a contextual login message during the verification stage.
|
* Display a contextual login message during the verification stage.
|
||||||
*
|
*
|
||||||
* @param string $message Existing login form message HTML.
|
* @param string $message Existing login form message HTML.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function filter_login_message( string $message ): string {
|
public function filter_login_message( string $message ): string {
|
||||||
if ( ! $this->is_verification_stage() ) {
|
if ( ! $this->is_verification_stage() ) {
|
||||||
return $message;
|
return $message;
|
||||||
|
|
@ -467,8 +476,8 @@ class Login_Form_Manager {
|
||||||
* Attempt to finish the verification stage during authentication.
|
* Attempt to finish the verification stage during authentication.
|
||||||
*
|
*
|
||||||
* @param \WP_User|\WP_Error|null $user Previously authenticated user or error.
|
* @param \WP_User|\WP_Error|null $user Previously authenticated user or error.
|
||||||
* @param string $username Submitted username.
|
* @param string $username Submitted username.
|
||||||
* @param string $password Submitted password.
|
* @param string $password Submitted password.
|
||||||
*
|
*
|
||||||
* @return \WP_User|\WP_Error|null
|
* @return \WP_User|\WP_Error|null
|
||||||
*/
|
*/
|
||||||
|
|
@ -479,7 +488,7 @@ class Login_Form_Manager {
|
||||||
|
|
||||||
unset( $password );
|
unset( $password );
|
||||||
|
|
||||||
if ( ! isset( $_POST[ self::LOGIN_NONCE_FIELD ] ) ) {
|
if ( ! isset( $_POST[ self::LOGIN_NONCE_FIELD ] ) || ! is_string( $_POST[ self::LOGIN_NONCE_FIELD ] ) ) {
|
||||||
return new \WP_Error( 'robotstxt_2fa_missing_nonce', __( 'The verification form is missing a security token. Please try again.', 'robotstxt-2fa' ) );
|
return new \WP_Error( 'robotstxt_2fa_missing_nonce', __( 'The verification form is missing a security token. Please try again.', 'robotstxt-2fa' ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -511,16 +520,16 @@ class Login_Form_Manager {
|
||||||
return new \WP_Error( 'robotstxt_2fa_invalid_stage', __( 'Your verification session expired. Please sign in again.', 'robotstxt-2fa' ) );
|
return new \WP_Error( 'robotstxt_2fa_invalid_stage', __( 'Your verification session expired. Please sign in again.', 'robotstxt-2fa' ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
$method = $this->get_requested_method();
|
$method = $this->get_requested_method();
|
||||||
$allowed_methods = $this->get_enabled_verification_methods( $authenticated_user );
|
$allowed_methods = $this->get_enabled_verification_methods( $authenticated_user );
|
||||||
|
|
||||||
if ( ! in_array( $method, $allowed_methods, true ) ) {
|
if ( ! in_array( $method, $allowed_methods, true ) ) {
|
||||||
return new \WP_Error( 'robotstxt_2fa_method_unavailable', __( 'The selected verification method is not available right now.', 'robotstxt-2fa' ) );
|
return new \WP_Error( 'robotstxt_2fa_method_unavailable', __( 'The selected verification method is not available right now.', 'robotstxt-2fa' ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
$token = '';
|
$token = '';
|
||||||
|
|
||||||
if ( isset( $_POST['robotstxt_2fa_token'] ) ) {
|
if ( isset( $_POST['robotstxt_2fa_token'] ) && is_string( $_POST['robotstxt_2fa_token'] ) ) {
|
||||||
$token = sanitize_text_field( wp_unslash( $_POST['robotstxt_2fa_token'] ) );
|
$token = sanitize_text_field( wp_unslash( $_POST['robotstxt_2fa_token'] ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -566,8 +575,8 @@ class Login_Form_Manager {
|
||||||
* Enforce the verification step for eligible users.
|
* Enforce the verification step for eligible users.
|
||||||
*
|
*
|
||||||
* @param \WP_User|\WP_Error|null $user Previously authenticated user or error.
|
* @param \WP_User|\WP_Error|null $user Previously authenticated user or error.
|
||||||
* @param string $username Submitted username.
|
* @param string $username Submitted username.
|
||||||
* @param string $password Submitted password.
|
* @param string $password Submitted password.
|
||||||
*
|
*
|
||||||
* @return \WP_User|\WP_Error|null
|
* @return \WP_User|\WP_Error|null
|
||||||
*/
|
*/
|
||||||
|
|
@ -597,9 +606,9 @@ class Login_Form_Manager {
|
||||||
$stage_token = wp_create_nonce( self::STAGE_TOKEN_ACTION . '|' . $user->ID );
|
$stage_token = wp_create_nonce( self::STAGE_TOKEN_ACTION . '|' . $user->ID );
|
||||||
|
|
||||||
$query_args = array(
|
$query_args = array(
|
||||||
self::QUERY_STAGE => self::STAGE_VERIFY,
|
self::QUERY_STAGE => self::STAGE_VERIFY,
|
||||||
self::QUERY_METHOD => $method,
|
self::QUERY_METHOD => $method,
|
||||||
self::QUERY_LOGIN => sanitize_user( $user->user_login, true ),
|
self::QUERY_LOGIN => sanitize_user( $user->user_login, true ),
|
||||||
self::QUERY_STAGE_TOKEN => $stage_token,
|
self::QUERY_STAGE_TOKEN => $stage_token,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -611,22 +620,25 @@ class Login_Form_Manager {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Process additional verification stage actions triggered from the login screen.
|
* Process additional verification stage actions triggered from the login screen.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function maybe_process_stage_requests(): void {
|
public function maybe_process_stage_requests(): void {
|
||||||
if ( ! $this->is_verification_stage() ) {
|
if ( ! $this->is_verification_stage() ) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( ! empty( $_GET[ self::QUERY_SWITCH ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage operations rely on dedicated nonce validation.
|
$has_switch = ! empty( $_GET[ self::QUERY_SWITCH ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Query flag only; nonce/stage-token verified inside process_method_switch().
|
||||||
|
$has_resend = ! empty( $_GET[ self::QUERY_RESEND ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Query flag only; stage-token verified before sending.
|
||||||
|
|
||||||
|
if ( $has_switch ) {
|
||||||
$this->process_method_switch();
|
$this->process_method_switch();
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( empty( $_GET[ self::QUERY_RESEND ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Action is protected by a dedicated nonce below.
|
if ( ! $has_resend ) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -679,13 +691,15 @@ class Login_Form_Manager {
|
||||||
private function get_requested_method(): string {
|
private function get_requested_method(): string {
|
||||||
$method = '';
|
$method = '';
|
||||||
|
|
||||||
if ( isset( $_REQUEST[ self::FIELD_METHOD ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage verification relies on dedicated nonce checks.
|
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Stage helper; nonce verified in calling context.
|
||||||
|
if ( isset( $_REQUEST[ self::FIELD_METHOD ] ) && is_string( $_REQUEST[ self::FIELD_METHOD ] ) ) {
|
||||||
$method = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_METHOD ] ) );
|
$method = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_METHOD ] ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( '' === $method && isset( $_REQUEST[ self::QUERY_METHOD ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Value used only for display context.
|
if ( '' === $method && isset( $_REQUEST[ self::QUERY_METHOD ] ) && is_string( $_REQUEST[ self::QUERY_METHOD ] ) ) {
|
||||||
$method = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_METHOD ] ) );
|
$method = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_METHOD ] ) );
|
||||||
}
|
}
|
||||||
|
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||||
|
|
||||||
if ( '' === $method ) {
|
if ( '' === $method ) {
|
||||||
$method = 'email';
|
$method = 'email';
|
||||||
|
|
@ -716,8 +730,14 @@ class Login_Form_Manager {
|
||||||
/**
|
/**
|
||||||
* Retrieve the verification methods that are active for the provided user.
|
* Retrieve the verification methods that are active for the provided user.
|
||||||
*
|
*
|
||||||
* @param \WP_User $user User attempting to authenticate.
|
* When 2FA is enforced by role, only methods that are both required by the
|
||||||
* @param array<string,mixed>|null $user_settings Optional preloaded settings.
|
* user's role(s) and actually set up on their profile are returned. If the
|
||||||
|
* user has not configured any of the required methods yet, all required
|
||||||
|
* methods that the system can deliver (e.g. email) are returned so the login
|
||||||
|
* can still be challenged.
|
||||||
|
*
|
||||||
|
* @param \WP_User $user User attempting to authenticate.
|
||||||
|
* @param array{enabled: bool, methods: array<int, string>, frequency: string}|null $user_settings Optional preloaded settings.
|
||||||
*
|
*
|
||||||
* @return array<int, string>
|
* @return array<int, string>
|
||||||
*/
|
*/
|
||||||
|
|
@ -726,44 +746,58 @@ class Login_Form_Manager {
|
||||||
$user_settings = $this->user_settings_repository->get_user_settings( $user->ID );
|
$user_settings = $this->user_settings_repository->get_user_settings( $user->ID );
|
||||||
}
|
}
|
||||||
|
|
||||||
$is_forced = $this->config->is_two_factor_forced_for_user( $user );
|
$required_methods = $this->config->get_required_methods_for_user( $user );
|
||||||
$enabled = $is_forced ? true : ! empty( $user_settings['enabled'] );
|
$is_forced = ! empty( $required_methods );
|
||||||
|
$enabled = $is_forced ? true : $user_settings['enabled'];
|
||||||
|
|
||||||
if ( ! $enabled ) {
|
if ( ! $enabled ) {
|
||||||
return array();
|
return array();
|
||||||
}
|
}
|
||||||
|
|
||||||
$methods = array();
|
// Normalize user's profile methods to login-stage slugs.
|
||||||
|
$profile_methods = array();
|
||||||
|
|
||||||
if ( ! empty( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ) {
|
foreach ( $user_settings['methods'] as $method_key ) {
|
||||||
$methods = $user_settings['methods'];
|
$slug = $this->normalize_method_slug( $method_key );
|
||||||
|
|
||||||
|
if ( '' !== $slug ) {
|
||||||
|
$profile_methods[] = $slug;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( $is_forced && empty( $methods ) ) {
|
$profile_methods = array_values( array_unique( $profile_methods ) );
|
||||||
$methods = array( $this->config->get_default_method() );
|
|
||||||
}
|
|
||||||
|
|
||||||
$normalized = array();
|
// When forced, restrict to methods required by the user's roles.
|
||||||
|
if ( $is_forced ) {
|
||||||
|
$required_slugs = array();
|
||||||
|
|
||||||
foreach ( $methods as $method_key ) {
|
foreach ( $required_methods as $method ) {
|
||||||
$normalized_method = $this->normalize_method_slug( (string) $method_key );
|
$slug = $this->normalize_method_slug( $method );
|
||||||
|
|
||||||
if ( '' === $normalized_method ) {
|
if ( '' !== $slug ) {
|
||||||
continue;
|
$required_slugs[] = $slug;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$normalized[] = $normalized_method;
|
$required_slugs = array_values( array_unique( $required_slugs ) );
|
||||||
|
|
||||||
|
// Prefer the intersection of profile-enabled and role-required methods.
|
||||||
|
$candidate_methods = array_values( array_intersect( $profile_methods, $required_slugs ) );
|
||||||
|
|
||||||
|
// Fall back to all role-required methods if none are set up yet.
|
||||||
|
if ( empty( $candidate_methods ) ) {
|
||||||
|
$candidate_methods = $required_slugs;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$candidate_methods = $profile_methods;
|
||||||
}
|
}
|
||||||
|
|
||||||
$normalized = array_values( array_unique( $normalized ) );
|
// Filter to methods the system can actually deliver right now.
|
||||||
|
|
||||||
$available = array();
|
$available = array();
|
||||||
|
|
||||||
foreach ( $normalized as $method ) {
|
foreach ( $candidate_methods as $method ) {
|
||||||
if ( 'email' === $method ) {
|
if ( 'email' === $method ) {
|
||||||
$email = sanitize_email( $user->user_email );
|
if ( '' !== sanitize_email( $user->user_email ) ) {
|
||||||
|
|
||||||
if ( '' !== $email ) {
|
|
||||||
$available[] = 'email';
|
$available[] = 'email';
|
||||||
}
|
}
|
||||||
} elseif ( 'otp' === $method ) {
|
} elseif ( 'otp' === $method ) {
|
||||||
|
|
@ -807,9 +841,9 @@ class Login_Form_Manager {
|
||||||
/**
|
/**
|
||||||
* Check whether any verification method was recently validated within the configured interval.
|
* Check whether any verification method was recently validated within the configured interval.
|
||||||
*
|
*
|
||||||
* @param \WP_User $user User attempting to authenticate.
|
* @param \WP_User $user User attempting to authenticate.
|
||||||
* @param array<int, string> $methods Active verification methods.
|
* @param array<int, string> $methods Active verification methods.
|
||||||
* @param string $frequency Selected frequency slug.
|
* @param string $frequency Selected frequency slug.
|
||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
|
|
@ -853,31 +887,19 @@ class Login_Form_Manager {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
$preferred = $this->normalize_method_slug( $this->config->get_default_method() );
|
// Prefer OTP (most secure), then email, then recovery codes (last resort).
|
||||||
|
foreach ( array( 'otp', 'email' ) as $method ) {
|
||||||
$priority = array_values(
|
|
||||||
array_filter(
|
|
||||||
array_unique(
|
|
||||||
array_merge(
|
|
||||||
array( 'otp' ),
|
|
||||||
array( $preferred ),
|
|
||||||
array( 'email', 'recovery' )
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
foreach ( $priority as $method ) {
|
|
||||||
if ( 'recovery' === $method && count( $methods ) > 1 ) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( in_array( $method, $methods, true ) ) {
|
if ( in_array( $method, $methods, true ) ) {
|
||||||
return $method;
|
return $method;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (string) $methods[0];
|
// Use recovery only when it is the sole option.
|
||||||
|
if ( in_array( 'recovery', $methods, true ) ) {
|
||||||
|
return 'recovery';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $methods[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -960,7 +982,8 @@ class Login_Form_Manager {
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
private function is_verification_stage(): bool {
|
private function is_verification_stage(): bool {
|
||||||
if ( isset( $_REQUEST[ self::FIELD_STAGE ] ) ) {
|
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Stage-detection only; nonce verified in calling context.
|
||||||
|
if ( isset( $_REQUEST[ self::FIELD_STAGE ] ) && is_string( $_REQUEST[ self::FIELD_STAGE ] ) ) {
|
||||||
$stage = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_STAGE ] ) );
|
$stage = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_STAGE ] ) );
|
||||||
|
|
||||||
if ( self::STAGE_VERIFY === $stage ) {
|
if ( self::STAGE_VERIFY === $stage ) {
|
||||||
|
|
@ -968,13 +991,14 @@ class Login_Form_Manager {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( isset( $_REQUEST[ self::QUERY_STAGE ] ) ) {
|
if ( isset( $_REQUEST[ self::QUERY_STAGE ] ) && is_string( $_REQUEST[ self::QUERY_STAGE ] ) ) {
|
||||||
$stage = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_STAGE ] ) );
|
$stage = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_STAGE ] ) );
|
||||||
|
|
||||||
if ( self::STAGE_VERIFY === $stage ) {
|
if ( self::STAGE_VERIFY === $stage ) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
@ -985,11 +1009,12 @@ class Login_Form_Manager {
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
private function is_verification_submission(): bool {
|
private function is_verification_submission(): bool {
|
||||||
if ( ! isset( $_POST[ self::FIELD_STAGE ] ) ) {
|
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage flag only; nonce verified in maybe_complete_verification().
|
||||||
|
if ( ! isset( $_POST[ self::FIELD_STAGE ] ) || ! is_string( $_POST[ self::FIELD_STAGE ] ) ) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$stage = sanitize_key( wp_unslash( $_POST[ self::FIELD_STAGE ] ) );
|
$stage = sanitize_key( wp_unslash( $_POST[ self::FIELD_STAGE ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
|
||||||
|
|
||||||
return self::STAGE_VERIFY === $stage;
|
return self::STAGE_VERIFY === $stage;
|
||||||
}
|
}
|
||||||
|
|
@ -1002,81 +1027,88 @@ class Login_Form_Manager {
|
||||||
private function get_requested_login(): string {
|
private function get_requested_login(): string {
|
||||||
$login = '';
|
$login = '';
|
||||||
|
|
||||||
if ( isset( $_REQUEST[ self::FIELD_LOGIN ] ) ) {
|
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Login identifier helper; nonce verified in calling context.
|
||||||
|
if ( isset( $_REQUEST[ self::FIELD_LOGIN ] ) && is_string( $_REQUEST[ self::FIELD_LOGIN ] ) ) {
|
||||||
$login = sanitize_user( wp_unslash( $_REQUEST[ self::FIELD_LOGIN ] ), true );
|
$login = sanitize_user( wp_unslash( $_REQUEST[ self::FIELD_LOGIN ] ), true );
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( '' === $login && isset( $_REQUEST[ self::QUERY_LOGIN ] ) ) {
|
if ( '' === $login && isset( $_REQUEST[ self::QUERY_LOGIN ] ) && is_string( $_REQUEST[ self::QUERY_LOGIN ] ) ) {
|
||||||
$login = sanitize_user( wp_unslash( $_REQUEST[ self::QUERY_LOGIN ] ), true );
|
$login = sanitize_user( wp_unslash( $_REQUEST[ self::QUERY_LOGIN ] ), true );
|
||||||
}
|
}
|
||||||
|
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||||
|
|
||||||
return $login;
|
return $login;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the stage nonce carried in the current request.
|
* Retrieve the stage nonce carried in the current request.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
private function get_requested_stage_token(): string {
|
private function get_requested_stage_token(): string {
|
||||||
$token = '';
|
$token = '';
|
||||||
|
|
||||||
if ( isset( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ) {
|
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Stage-token helper; token itself is the nonce verified in validate_stage_token().
|
||||||
|
if ( isset( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) && is_string( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ) {
|
||||||
$token = sanitize_text_field( wp_unslash( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) );
|
$token = sanitize_text_field( wp_unslash( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( '' === $token && isset( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ) {
|
if ( '' === $token && isset( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) && is_string( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ) {
|
||||||
$token = sanitize_text_field( wp_unslash( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) );
|
$token = sanitize_text_field( wp_unslash( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) );
|
||||||
}
|
}
|
||||||
|
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||||
|
|
||||||
return $token;
|
return $token;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the notice slug carried in the current request.
|
* Retrieve the notice slug carried in the current request.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
private function get_requested_notice(): string {
|
private function get_requested_notice(): string {
|
||||||
if ( ! isset( $_REQUEST[ self::QUERY_NOTICE ] ) ) {
|
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Notice slug helper; display-only, not security-sensitive.
|
||||||
|
if ( ! isset( $_REQUEST[ self::QUERY_NOTICE ] ) || ! is_string( $_REQUEST[ self::QUERY_NOTICE ] ) ) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
return sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_NOTICE ] ) );
|
return sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_NOTICE ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate whether the provided stage token is valid for the given user.
|
* Validate whether the provided stage token is valid for the given user.
|
||||||
*
|
*
|
||||||
* @param \WP_User $user Authenticated user.
|
* @param \WP_User $user Authenticated user.
|
||||||
* @param string $stage_token Submitted stage token.
|
* @param string $stage_token Submitted stage token.
|
||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
private function validate_stage_token( \WP_User $user, string $stage_token ): bool {
|
private function validate_stage_token( \WP_User $user, string $stage_token ): bool {
|
||||||
return (bool) wp_verify_nonce( $stage_token, self::STAGE_TOKEN_ACTION . '|' . $user->ID );
|
return (bool) wp_verify_nonce( $stage_token, self::STAGE_TOKEN_ACTION . '|' . $user->ID );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the sanitized redirect_to parameter from the current request.
|
* Retrieve the sanitized redirect_to parameter from the current request.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
private function get_requested_redirect(): string {
|
private function get_requested_redirect(): string {
|
||||||
if ( ! isset( $_REQUEST['redirect_to'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Value is only echoed back.
|
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- redirect_to is a standard WP login parameter; value is passed through esc_url_raw.
|
||||||
|
if ( ! isset( $_REQUEST['redirect_to'] ) || ! is_string( $_REQUEST['redirect_to'] ) ) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
return esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) );
|
return esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) );
|
||||||
|
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build a URL pointing to the active verification stage.
|
* Build a URL pointing to the active verification stage.
|
||||||
*
|
*
|
||||||
* @param array<string, string|null> $extra_args Optional additional query parameters to merge.
|
* @param array<string, string|null> $extra_args Optional additional query parameters to merge.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
private function get_stage_url( array $extra_args = array() ): string {
|
private function get_stage_url( array $extra_args = array() ): string {
|
||||||
$redirect_to = $this->get_requested_redirect();
|
$redirect_to = $this->get_requested_redirect();
|
||||||
$login_url = wp_login_url( $redirect_to );
|
$login_url = wp_login_url( $redirect_to );
|
||||||
|
|
@ -1110,7 +1142,7 @@ class Login_Form_Manager {
|
||||||
$args = array_filter(
|
$args = array_filter(
|
||||||
$args,
|
$args,
|
||||||
static function ( $value ) {
|
static function ( $value ) {
|
||||||
return null !== $value && '' !== $value;
|
return '' !== $value;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -1120,8 +1152,8 @@ class Login_Form_Manager {
|
||||||
/**
|
/**
|
||||||
* Determine the effective verification frequency for the current user.
|
* Determine the effective verification frequency for the current user.
|
||||||
*
|
*
|
||||||
* @param \WP_User $user Authenticated user object.
|
* @param \WP_User $user Authenticated user object.
|
||||||
* @param array<string, mixed> $user_settings Stored per-user preferences.
|
* @param array{enabled: bool, methods: array<int, string>, frequency: string} $user_settings Stored per-user preferences.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
|
|
@ -1132,8 +1164,8 @@ class Login_Form_Manager {
|
||||||
return $this->config->get_frequency();
|
return $this->config->get_frequency();
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( ! empty( $user_settings['frequency'] ) ) {
|
if ( '' !== $user_settings['frequency'] ) {
|
||||||
return Frequency_Options::sanitize( (string) $user_settings['frequency'] );
|
return Frequency_Options::sanitize( $user_settings['frequency'] );
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->config->get_frequency();
|
return $this->config->get_frequency();
|
||||||
|
|
@ -1148,15 +1180,16 @@ class Login_Form_Manager {
|
||||||
$ip = '';
|
$ip = '';
|
||||||
|
|
||||||
if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
|
if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
|
||||||
$ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
|
$raw_addr = is_string( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
|
||||||
$ip = wp_privacy_anonymize_ip( $ip );
|
$ip = sanitize_text_field( wp_unslash( $raw_addr ) );
|
||||||
$ip = is_string( $ip ) ? $ip : '';
|
$ip = wp_privacy_anonymize_ip( $ip );
|
||||||
}
|
}
|
||||||
|
|
||||||
$user_agent = '';
|
$user_agent = '';
|
||||||
|
|
||||||
if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
|
if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
|
||||||
$user_agent = sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) );
|
$raw_ua = is_string( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
|
||||||
|
$user_agent = sanitize_text_field( wp_unslash( $raw_ua ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
$user_agent = strtolower( substr( $user_agent, 0, 255 ) );
|
$user_agent = strtolower( substr( $user_agent, 0, 255 ) );
|
||||||
|
|
|
||||||
|
|
@ -153,9 +153,10 @@ class OTP_Manager {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
$site_name = wp_specialchars_decode( get_option( 'blogname', '' ), ENT_QUOTES );
|
$raw_blogname = get_option( 'blogname', '' );
|
||||||
$site_name = '' !== $site_name ? $site_name : __( 'WordPress Site', 'robotstxt-2fa' );
|
$site_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES );
|
||||||
$label = '' !== $user->user_email ? $user->user_email : $user->user_login;
|
$site_name = '' !== $site_name ? $site_name : __( 'WordPress Site', 'robotstxt-2fa' );
|
||||||
|
$label = '' !== $user->user_email ? $user->user_email : $user->user_login;
|
||||||
|
|
||||||
$encoded_label = rawurlencode( sanitize_text_field( $label ) );
|
$encoded_label = rawurlencode( sanitize_text_field( $label ) );
|
||||||
$encoded_site = rawurlencode( $site_name );
|
$encoded_site = rawurlencode( $site_name );
|
||||||
|
|
@ -238,6 +239,14 @@ class OTP_Manager {
|
||||||
|
|
||||||
return $writer->writeString( $data );
|
return $writer->writeString( $data );
|
||||||
} catch ( \Throwable $exception ) {
|
} catch ( \Throwable $exception ) {
|
||||||
|
/**
|
||||||
|
* Fires when QR code SVG generation fails.
|
||||||
|
*
|
||||||
|
* @since 0.2.0
|
||||||
|
*
|
||||||
|
* @param \Throwable $exception The caught exception.
|
||||||
|
* @param string $data The provisioning URI that failed to render.
|
||||||
|
*/
|
||||||
do_action( 'robotstxt_2fa_qr_generation_failed', $exception, $data );
|
do_action( 'robotstxt_2fa_qr_generation_failed', $exception, $data );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -267,7 +276,7 @@ class OTP_Manager {
|
||||||
$chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT );
|
$chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT );
|
||||||
}
|
}
|
||||||
|
|
||||||
$encoded .= $alphabet[ bindec( $chunk ) ];
|
$encoded .= $alphabet[ (int) bindec( $chunk ) ];
|
||||||
}
|
}
|
||||||
|
|
||||||
return $encoded;
|
return $encoded;
|
||||||
|
|
@ -309,7 +318,7 @@ class OTP_Manager {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$binary .= chr( bindec( $chunk ) );
|
$binary .= chr( (int) bindec( $chunk ) & 0xFF );
|
||||||
}
|
}
|
||||||
|
|
||||||
return $binary;
|
return $binary;
|
||||||
|
|
@ -329,7 +338,9 @@ class OTP_Manager {
|
||||||
$hash = hash_hmac( 'sha1', $binary_counter, $secret, true );
|
$hash = hash_hmac( 'sha1', $binary_counter, $secret, true );
|
||||||
$offset = ord( substr( $hash, -1 ) ) & 0x0F;
|
$offset = ord( substr( $hash, -1 ) ) & 0x0F;
|
||||||
$segment = substr( $hash, $offset, 4 );
|
$segment = substr( $hash, $offset, 4 );
|
||||||
$value = unpack( 'N', $segment )[1] & 0x7FFFFFFF;
|
$unpacked = unpack( 'N', $segment );
|
||||||
|
$raw_value = is_array( $unpacked ) && isset( $unpacked[1] ) && is_int( $unpacked[1] ) ? $unpacked[1] : 0;
|
||||||
|
$value = $raw_value & 0x7FFFFFFF;
|
||||||
$code = $value % ( 10 ** self::CODE_DIGITS );
|
$code = $value % ( 10 ** self::CODE_DIGITS );
|
||||||
|
|
||||||
return str_pad( (string) $code, self::CODE_DIGITS, '0', STR_PAD_LEFT );
|
return str_pad( (string) $code, self::CODE_DIGITS, '0', STR_PAD_LEFT );
|
||||||
|
|
|
||||||
|
|
@ -35,9 +35,10 @@ class Profile_Settings {
|
||||||
private const SECTION_ANCHOR = 'robotstxt-2fa-settings';
|
private const SECTION_ANCHOR = 'robotstxt-2fa-settings';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lifetime for temporary recovery-code previews in seconds (0 = persistent until cleared).
|
* Lifetime for temporary recovery-code previews in seconds.
|
||||||
|
* Codes are shown once and must be confirmed; 5 minutes is enough.
|
||||||
*/
|
*/
|
||||||
private const PREVIEW_TTL = 0;
|
private const PREVIEW_TTL = 300;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Form field used to submit OTP verification codes.
|
* Form field used to submit OTP verification codes.
|
||||||
|
|
@ -168,6 +169,7 @@ class Profile_Settings {
|
||||||
|
|
||||||
$user_settings = $this->user_settings_repository->get_user_settings( $user->ID );
|
$user_settings = $this->user_settings_repository->get_user_settings( $user->ID );
|
||||||
$is_forced = $this->config->is_two_factor_forced_for_user( $user );
|
$is_forced = $this->config->is_two_factor_forced_for_user( $user );
|
||||||
|
$required_methods = $this->config->get_required_methods_for_user( $user );
|
||||||
$is_enabled = $is_forced ? true : (bool) $user_settings['enabled'];
|
$is_enabled = $is_forced ? true : (bool) $user_settings['enabled'];
|
||||||
$enabled_methods = $is_enabled ? $user_settings['methods'] : array();
|
$enabled_methods = $is_enabled ? $user_settings['methods'] : array();
|
||||||
$available_methods = $this->get_available_methods( $user );
|
$available_methods = $this->get_available_methods( $user );
|
||||||
|
|
@ -185,8 +187,10 @@ class Profile_Settings {
|
||||||
$otp_enabled = in_array( 'otp', $enabled_methods, true );
|
$otp_enabled = in_array( 'otp', $enabled_methods, true );
|
||||||
$recovery_enabled = in_array( 'recovery_codes', $enabled_methods, true );
|
$recovery_enabled = in_array( 'recovery_codes', $enabled_methods, true );
|
||||||
|
|
||||||
$date_format = (string) get_option( 'date_format' );
|
$raw_date_format = get_option( 'date_format' );
|
||||||
$time_format = (string) get_option( 'time_format' );
|
$raw_time_format = get_option( 'time_format' );
|
||||||
|
$date_format = is_string( $raw_date_format ) ? $raw_date_format : '';
|
||||||
|
$time_format = is_string( $raw_time_format ) ? $raw_time_format : '';
|
||||||
$datetime_format = trim( $date_format . ' ' . $time_format );
|
$datetime_format = trim( $date_format . ' ' . $time_format );
|
||||||
|
|
||||||
if ( '' === $datetime_format ) {
|
if ( '' === $datetime_format ) {
|
||||||
|
|
@ -198,8 +202,8 @@ class Profile_Settings {
|
||||||
$recovery_total = $this->recovery_codes->get_codes_per_batch();
|
$recovery_total = $this->recovery_codes->get_codes_per_batch();
|
||||||
$last_generated = $this->recovery_codes->get_last_generated_timestamp( $user->ID );
|
$last_generated = $this->recovery_codes->get_last_generated_timestamp( $user->ID );
|
||||||
$preview = $this->get_recovery_preview( $user->ID );
|
$preview = $this->get_recovery_preview( $user->ID );
|
||||||
$preview_codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $preview['codes'] : array();
|
$preview_codes = $preview['codes'];
|
||||||
$preview_generated = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0;
|
$preview_generated = $preview['generated_at'];
|
||||||
|
|
||||||
if ( $preview_generated > 0 ) {
|
if ( $preview_generated > 0 ) {
|
||||||
$last_generated = $preview_generated;
|
$last_generated = $preview_generated;
|
||||||
|
|
@ -223,8 +227,8 @@ class Profile_Settings {
|
||||||
|
|
||||||
$unused_count = $this->recovery_codes->count_unused_codes( $user->ID );
|
$unused_count = $this->recovery_codes->count_unused_codes( $user->ID );
|
||||||
$preview = $this->get_recovery_preview( $user->ID );
|
$preview = $this->get_recovery_preview( $user->ID );
|
||||||
$preview_codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $preview['codes'] : array();
|
$preview_codes = $preview['codes'];
|
||||||
$preview_generated = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0;
|
$preview_generated = $preview['generated_at'];
|
||||||
|
|
||||||
if ( $preview_generated > 0 ) {
|
if ( $preview_generated > 0 ) {
|
||||||
$last_generated = $preview_generated;
|
$last_generated = $preview_generated;
|
||||||
|
|
@ -235,8 +239,8 @@ class Profile_Settings {
|
||||||
|
|
||||||
if ( ! $recovery_enabled && empty( $preview_codes ) ) {
|
if ( ! $recovery_enabled && empty( $preview_codes ) ) {
|
||||||
$preview = $this->prepare_recovery_preview( $user );
|
$preview = $this->prepare_recovery_preview( $user );
|
||||||
$preview_codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $preview['codes'] : array();
|
$preview_codes = $preview['codes'];
|
||||||
$preview_generated = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0;
|
$preview_generated = $preview['generated_at'];
|
||||||
|
|
||||||
if ( $preview_generated > 0 ) {
|
if ( $preview_generated > 0 ) {
|
||||||
$last_generated = $preview_generated;
|
$last_generated = $preview_generated;
|
||||||
|
|
@ -247,7 +251,8 @@ class Profile_Settings {
|
||||||
$unused_count = count( $preview_codes );
|
$unused_count = count( $preview_codes );
|
||||||
}
|
}
|
||||||
|
|
||||||
$last_generated_formatted = $last_generated > 0 ? wp_date( $datetime_format, $last_generated ) : '';
|
$wp_date_result = $last_generated > 0 ? wp_date( $datetime_format, $last_generated ) : false;
|
||||||
|
$last_generated_formatted = ( false !== $wp_date_result ) ? $wp_date_result : '';
|
||||||
$has_preview = ! empty( $preview_codes );
|
$has_preview = ! empty( $preview_codes );
|
||||||
|
|
||||||
$otp_secret = $otp_enabled ? $this->otp_manager->get_secret( $user->ID ) : $this->otp_manager->ensure_secret( $user );
|
$otp_secret = $otp_enabled ? $this->otp_manager->get_secret( $user->ID ) : $this->otp_manager->ensure_secret( $user );
|
||||||
|
|
@ -305,10 +310,17 @@ class Profile_Settings {
|
||||||
<legend class="screen-reader-text">
|
<legend class="screen-reader-text">
|
||||||
<span><?php esc_html_e( 'Select the two-factor authentication methods you want to enable.', 'robotstxt-2fa' ); ?></span>
|
<span><?php esc_html_e( 'Select the two-factor authentication methods you want to enable.', 'robotstxt-2fa' ); ?></span>
|
||||||
</legend>
|
</legend>
|
||||||
|
<?php $email_required = in_array( 'email', $required_methods, true ); ?>
|
||||||
|
<?php if ( $email_required ) : ?>
|
||||||
|
<input type="hidden" name="robotstxt_2fa_settings[methods][]" value="email" />
|
||||||
|
<?php endif; ?>
|
||||||
<div class="robotstxt-2fa-method robotstxt-2fa-method-email">
|
<div class="robotstxt-2fa-method robotstxt-2fa-method-email">
|
||||||
<label for="robotstxt-2fa-method-email">
|
<label for="robotstxt-2fa-method-email">
|
||||||
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-email" value="email" <?php checked( $email_enabled, true ); ?> <?php disabled( ! $is_enabled, true ); ?> />
|
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-email" value="email" <?php checked( $email_enabled || $email_required, true ); ?> <?php disabled( ! $is_enabled || $email_required, true ); ?> />
|
||||||
<span class="robotstxt-2fa-method-label"><?php echo esc_html( $email_label ); ?></span>
|
<span class="robotstxt-2fa-method-label"><?php echo esc_html( $email_label ); ?></span>
|
||||||
|
<?php if ( $email_required ) : ?>
|
||||||
|
<span class="robotstxt-2fa-required-badge description"> — <?php esc_html_e( 'required for your role', 'robotstxt-2fa' ); ?></span>
|
||||||
|
<?php endif; ?>
|
||||||
</label>
|
</label>
|
||||||
<?php if ( ! empty( $available_methods['email']['description'] ) ) : ?>
|
<?php if ( ! empty( $available_methods['email']['description'] ) ) : ?>
|
||||||
<p class="description">
|
<p class="description">
|
||||||
|
|
@ -316,10 +328,17 @@ class Profile_Settings {
|
||||||
</p>
|
</p>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</div>
|
</div>
|
||||||
|
<?php $otp_required = in_array( 'otp', $required_methods, true ); ?>
|
||||||
|
<?php if ( $otp_required && $otp_enabled ) : ?>
|
||||||
|
<input type="hidden" name="robotstxt_2fa_settings[methods][]" value="otp" />
|
||||||
|
<?php endif; ?>
|
||||||
<div class="robotstxt-2fa-method robotstxt-2fa-method-otp">
|
<div class="robotstxt-2fa-method robotstxt-2fa-method-otp">
|
||||||
<label for="robotstxt-2fa-method-otp">
|
<label for="robotstxt-2fa-method-otp">
|
||||||
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-otp" value="otp" <?php checked( $otp_enabled, true ); ?> <?php disabled( ! $is_enabled, true ); ?> />
|
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-otp" value="otp" <?php checked( $otp_enabled, true ); ?> <?php disabled( ! $is_enabled || ( $otp_required && $otp_enabled ), true ); ?> />
|
||||||
<span class="robotstxt-2fa-method-label"><?php echo esc_html( $available_methods['otp']['label'] ); ?></span>
|
<span class="robotstxt-2fa-method-label"><?php echo esc_html( $available_methods['otp']['label'] ); ?></span>
|
||||||
|
<?php if ( $otp_required ) : ?>
|
||||||
|
<span class="robotstxt-2fa-required-badge description"> — <?php esc_html_e( 'required for your role', 'robotstxt-2fa' ); ?></span>
|
||||||
|
<?php endif; ?>
|
||||||
</label>
|
</label>
|
||||||
<?php if ( ! empty( $available_methods['otp']['description'] ) ) : ?>
|
<?php if ( ! empty( $available_methods['otp']['description'] ) ) : ?>
|
||||||
<p class="description">
|
<p class="description">
|
||||||
|
|
@ -354,7 +373,7 @@ class Profile_Settings {
|
||||||
<label class="screen-reader-text" for="robotstxt-2fa-otp-code">
|
<label class="screen-reader-text" for="robotstxt-2fa-otp-code">
|
||||||
<?php esc_html_e( 'Authenticator code', 'robotstxt-2fa' ); ?>
|
<?php esc_html_e( 'Authenticator code', 'robotstxt-2fa' ); ?>
|
||||||
</label>
|
</label>
|
||||||
<input type="text" name="<?php echo esc_attr( self::OTP_CODE_FIELD ); ?>" id="robotstxt-2fa-otp-code" pattern="\\d{<?php echo esc_attr( $otp_digits ); ?>}" inputmode="numeric" autocomplete="one-time-code" />
|
<input type="text" name="<?php echo esc_attr( self::OTP_CODE_FIELD ); ?>" id="robotstxt-2fa-otp-code" pattern="\\d{<?php echo absint( $otp_digits ); ?>}" inputmode="numeric" autocomplete="one-time-code" />
|
||||||
<p class="description">
|
<p class="description">
|
||||||
<?php esc_html_e( 'Need a different pairing? Use the button below to generate a new QR code.', 'robotstxt-2fa' ); ?>
|
<?php esc_html_e( 'Need a different pairing? Use the button below to generate a new QR code.', 'robotstxt-2fa' ); ?>
|
||||||
</p>
|
</p>
|
||||||
|
|
@ -363,10 +382,17 @@ class Profile_Settings {
|
||||||
<?php esc_html_e( 'Generate new secret', 'robotstxt-2fa' ); ?>
|
<?php esc_html_e( 'Generate new secret', 'robotstxt-2fa' ); ?>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<?php $recovery_required = in_array( 'recovery_codes', $required_methods, true ); ?>
|
||||||
|
<?php if ( $recovery_required ) : ?>
|
||||||
|
<input type="hidden" name="robotstxt_2fa_settings[methods][]" value="recovery_codes" />
|
||||||
|
<?php endif; ?>
|
||||||
<div class="robotstxt-2fa-method robotstxt-2fa-method-recovery">
|
<div class="robotstxt-2fa-method robotstxt-2fa-method-recovery">
|
||||||
<label for="robotstxt-2fa-method-recovery">
|
<label for="robotstxt-2fa-method-recovery">
|
||||||
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-recovery" value="recovery_codes" <?php checked( $recovery_enabled, true ); ?> <?php disabled( ! $is_enabled, true ); ?> />
|
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-recovery" value="recovery_codes" <?php checked( $recovery_enabled || $recovery_required, true ); ?> <?php disabled( ! $is_enabled || $recovery_required, true ); ?> />
|
||||||
<span class="robotstxt-2fa-method-label"><?php echo esc_html( $available_methods['recovery_codes']['label'] ); ?></span>
|
<span class="robotstxt-2fa-method-label"><?php echo esc_html( $available_methods['recovery_codes']['label'] ); ?></span>
|
||||||
|
<?php if ( $recovery_required ) : ?>
|
||||||
|
<span class="robotstxt-2fa-required-badge description"> — <?php esc_html_e( 'required for your role', 'robotstxt-2fa' ); ?></span>
|
||||||
|
<?php endif; ?>
|
||||||
</label>
|
</label>
|
||||||
<?php if ( ! empty( $available_methods['recovery_codes']['description'] ) ) : ?>
|
<?php if ( ! empty( $available_methods['recovery_codes']['description'] ) ) : ?>
|
||||||
<p class="description">
|
<p class="description">
|
||||||
|
|
@ -431,7 +457,7 @@ class Profile_Settings {
|
||||||
<label class="robotstxt-2fa-recovery-confirm-label" for="robotstxt-2fa-recovery-confirm">
|
<label class="robotstxt-2fa-recovery-confirm-label" for="robotstxt-2fa-recovery-confirm">
|
||||||
<?php esc_html_e( 'Enter one of the codes above to confirm you saved them.', 'robotstxt-2fa' ); ?>
|
<?php esc_html_e( 'Enter one of the codes above to confirm you saved them.', 'robotstxt-2fa' ); ?>
|
||||||
</label>
|
</label>
|
||||||
<input type="text" name="<?php echo esc_attr( self::RECOVERY_CONFIRM_FIELD ); ?>" id="robotstxt-2fa-recovery-confirm" pattern="\\d{<?php echo esc_attr( $recovery_code_length ); ?>}" inputmode="numeric" autocomplete="one-time-code" />
|
<input type="text" name="<?php echo esc_attr( self::RECOVERY_CONFIRM_FIELD ); ?>" id="robotstxt-2fa-recovery-confirm" pattern="\\d{<?php echo absint( $recovery_code_length ); ?>}" inputmode="numeric" autocomplete="one-time-code" />
|
||||||
</div>
|
</div>
|
||||||
<p class="description">
|
<p class="description">
|
||||||
<?php esc_html_e( 'Once confirmed, the codes disappear from this page but remain valid until you use them.', 'robotstxt-2fa' ); ?>
|
<?php esc_html_e( 'Once confirmed, the codes disappear from this page but remain valid until you use them.', 'robotstxt-2fa' ); ?>
|
||||||
|
|
@ -490,6 +516,35 @@ class Profile_Settings {
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
<?php if ( ! $is_forced ) : ?>
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
var toggle = document.getElementById( 'robotstxt-2fa-enabled' );
|
||||||
|
var methods = document.querySelector( '.robotstxt-2fa-profile-methods' );
|
||||||
|
var freq = document.querySelector( '.robotstxt-2fa-profile-frequency' );
|
||||||
|
|
||||||
|
if ( ! toggle || ! methods ) { return; }
|
||||||
|
|
||||||
|
function applyState() {
|
||||||
|
var on = toggle.checked;
|
||||||
|
methods.querySelectorAll( 'input, select, button' ).forEach( function ( el ) {
|
||||||
|
var isRequired = el.closest( '[data-2fa-required]' );
|
||||||
|
if ( ! isRequired ) {
|
||||||
|
el.disabled = ! on;
|
||||||
|
}
|
||||||
|
} );
|
||||||
|
if ( freq ) {
|
||||||
|
freq.querySelectorAll( 'select' ).forEach( function ( el ) {
|
||||||
|
el.disabled = ! on || <?php echo $frequency_forced ? 'true' : 'false'; ?>;
|
||||||
|
} );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
toggle.addEventListener( 'change', applyState );
|
||||||
|
applyState();
|
||||||
|
}());
|
||||||
|
</script>
|
||||||
|
<?php endif; ?>
|
||||||
<?php
|
<?php
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -498,12 +553,19 @@ class Profile_Settings {
|
||||||
*
|
*
|
||||||
* @param \WP_User $user User being edited.
|
* @param \WP_User $user User being edited.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{codes: array<int, string>, generated_at: int}
|
||||||
*/
|
*/
|
||||||
private function prepare_recovery_preview( \WP_User $user ): array {
|
private function prepare_recovery_preview( \WP_User $user ): array {
|
||||||
try {
|
try {
|
||||||
$result = $this->recovery_codes->regenerate_codes_for_user( $user );
|
$result = $this->recovery_codes->regenerate_codes_for_user( $user );
|
||||||
} catch ( \Throwable $exception ) {
|
} catch ( \Throwable $exception ) {
|
||||||
|
/**
|
||||||
|
* Fires when recovery code generation fails.
|
||||||
|
*
|
||||||
|
* @since 0.2.0
|
||||||
|
*
|
||||||
|
* @param \Throwable $exception The caught exception.
|
||||||
|
*/
|
||||||
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
|
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
|
||||||
return $this->get_recovery_preview( $user->ID );
|
return $this->get_recovery_preview( $user->ID );
|
||||||
}
|
}
|
||||||
|
|
@ -512,7 +574,7 @@ class Profile_Settings {
|
||||||
return $this->get_recovery_preview( $user->ID );
|
return $this->get_recovery_preview( $user->ID );
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->remember_recovery_preview( $user->ID, $result['codes'], (int) $result['generated_at'] );
|
$this->remember_recovery_preview( $user->ID, $result['codes'], $result['generated_at'] );
|
||||||
$this->focus_section = true;
|
$this->focus_section = true;
|
||||||
|
|
||||||
add_settings_error(
|
add_settings_error(
|
||||||
|
|
@ -528,14 +590,14 @@ class Profile_Settings {
|
||||||
/**
|
/**
|
||||||
* Reset recovery codes and user settings when all codes were consumed.
|
* Reset recovery codes and user settings when all codes were consumed.
|
||||||
*
|
*
|
||||||
* @param \WP_User $user User being edited.
|
* @param \WP_User $user User being edited.
|
||||||
* @param array<string, mixed> $user_settings Stored user settings prior to the reset.
|
* @param array{enabled: bool, methods: array<int, string>, frequency: string} $user_settings Stored user settings prior to the reset.
|
||||||
* @param bool $is_forced Whether two-factor authentication is enforced for the user.
|
* @param bool $is_forced Whether two-factor authentication is enforced for the user.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
private function reset_recovery_codes_after_exhaustion( \WP_User $user, array $user_settings, bool $is_forced ): void {
|
private function reset_recovery_codes_after_exhaustion( \WP_User $user, array $user_settings, bool $is_forced ): void {
|
||||||
$current_methods = isset( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ? $user_settings['methods'] : array();
|
$current_methods = $user_settings['methods'];
|
||||||
$remaining_methods = array_values( array_diff( $current_methods, array( 'recovery_codes' ) ) );
|
$remaining_methods = array_values( array_diff( $current_methods, array( 'recovery_codes' ) ) );
|
||||||
$enabled_flag = $is_forced ? true : ( ! empty( $remaining_methods ) && ! empty( $user_settings['enabled'] ) );
|
$enabled_flag = $is_forced ? true : ( ! empty( $remaining_methods ) && ! empty( $user_settings['enabled'] ) );
|
||||||
$frequency_value = $this->resolve_selected_frequency( $user_settings );
|
$frequency_value = $this->resolve_selected_frequency( $user_settings );
|
||||||
|
|
@ -552,6 +614,13 @@ class Profile_Settings {
|
||||||
try {
|
try {
|
||||||
$result = $this->recovery_codes->regenerate_codes_for_user( $user );
|
$result = $this->recovery_codes->regenerate_codes_for_user( $user );
|
||||||
} catch ( \Throwable $exception ) {
|
} catch ( \Throwable $exception ) {
|
||||||
|
/**
|
||||||
|
* Fires when recovery code generation fails.
|
||||||
|
*
|
||||||
|
* @since 0.2.0
|
||||||
|
*
|
||||||
|
* @param \Throwable $exception The caught exception.
|
||||||
|
*/
|
||||||
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
|
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
|
||||||
add_settings_error(
|
add_settings_error(
|
||||||
'robotstxt-2fa',
|
'robotstxt-2fa',
|
||||||
|
|
@ -563,7 +632,7 @@ class Profile_Settings {
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( ! empty( $result['codes'] ) ) {
|
if ( ! empty( $result['codes'] ) ) {
|
||||||
$this->remember_recovery_preview( $user->ID, $result['codes'], (int) $result['generated_at'] );
|
$this->remember_recovery_preview( $user->ID, $result['codes'], $result['generated_at'] );
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->focus_section = true;
|
$this->focus_section = true;
|
||||||
|
|
@ -591,7 +660,7 @@ class Profile_Settings {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( ! isset( $_POST[ self::NONCE_FIELD ] ) ) {
|
if ( ! isset( $_POST[ self::NONCE_FIELD ] ) || ! is_string( $_POST[ self::NONCE_FIELD ] ) ) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -607,19 +676,16 @@ class Profile_Settings {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$submitted_settings = array();
|
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above.
|
||||||
|
$raw_settings = isset( $_POST['robotstxt_2fa_settings'] ) && is_array( $_POST['robotstxt_2fa_settings'] )
|
||||||
$raw_settings = filter_input( INPUT_POST, 'robotstxt_2fa_settings', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
|
? wp_unslash( $_POST['robotstxt_2fa_settings'] ) // phpcs:ignore WordPress.Security.NonceVerification.Missing
|
||||||
|
: array();
|
||||||
if ( is_array( $raw_settings ) ) {
|
|
||||||
$submitted_settings = map_deep( wp_unslash( $raw_settings ), 'sanitize_text_field' );
|
|
||||||
}
|
|
||||||
|
|
||||||
$requested_methods = array();
|
$requested_methods = array();
|
||||||
|
|
||||||
if ( isset( $submitted_settings['methods'] ) && is_array( $submitted_settings['methods'] ) ) {
|
if ( isset( $raw_settings['methods'] ) && is_array( $raw_settings['methods'] ) ) {
|
||||||
foreach ( $submitted_settings['methods'] as $method_key ) {
|
foreach ( $raw_settings['methods'] as $raw_method ) {
|
||||||
$method_key = sanitize_key( $method_key );
|
$method_key = sanitize_key( is_string( $raw_method ) ? $raw_method : '' );
|
||||||
|
|
||||||
if ( '' !== $method_key ) {
|
if ( '' !== $method_key ) {
|
||||||
$requested_methods[] = $method_key;
|
$requested_methods[] = $method_key;
|
||||||
|
|
@ -629,15 +695,24 @@ class Profile_Settings {
|
||||||
|
|
||||||
$requested_methods = array_values( array_unique( $requested_methods ) );
|
$requested_methods = array_values( array_unique( $requested_methods ) );
|
||||||
|
|
||||||
$enabled = ! empty( $submitted_settings['enabled'] );
|
$required_methods = $this->config->get_required_methods_for_user( $user );
|
||||||
$is_forced = $this->config->is_two_factor_forced_for_user( $user );
|
$is_forced = ! empty( $required_methods );
|
||||||
|
|
||||||
|
// Merge role-required methods into the submission so they cannot be dropped server-side.
|
||||||
|
foreach ( $required_methods as $req_method ) {
|
||||||
|
if ( ! in_array( $req_method, $requested_methods, true ) ) {
|
||||||
|
$requested_methods[] = $req_method;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$enabled = ! empty( $raw_settings['enabled'] );
|
||||||
|
|
||||||
if ( $is_forced ) {
|
if ( $is_forced ) {
|
||||||
$enabled = true;
|
$enabled = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
$user_settings = $this->user_settings_repository->get_user_settings( $user_id );
|
$user_settings = $this->user_settings_repository->get_user_settings( $user_id );
|
||||||
$previous_methods = isset( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ? $user_settings['methods'] : array();
|
$previous_methods = $user_settings['methods'];
|
||||||
|
|
||||||
$otp_was_enabled = in_array( 'otp', $previous_methods, true );
|
$otp_was_enabled = in_array( 'otp', $previous_methods, true );
|
||||||
$recovery_was_enabled = in_array( 'recovery_codes', $previous_methods, true );
|
$recovery_was_enabled = in_array( 'recovery_codes', $previous_methods, true );
|
||||||
|
|
@ -650,13 +725,13 @@ class Profile_Settings {
|
||||||
|
|
||||||
$otp_code = '';
|
$otp_code = '';
|
||||||
|
|
||||||
if ( isset( $_POST[ self::OTP_CODE_FIELD ] ) ) {
|
if ( isset( $_POST[ self::OTP_CODE_FIELD ] ) && is_string( $_POST[ self::OTP_CODE_FIELD ] ) ) {
|
||||||
$otp_code = sanitize_text_field( wp_unslash( $_POST[ self::OTP_CODE_FIELD ] ) );
|
$otp_code = sanitize_text_field( wp_unslash( $_POST[ self::OTP_CODE_FIELD ] ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
$recovery_code_input = '';
|
$recovery_code_input = '';
|
||||||
|
|
||||||
if ( isset( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) ) {
|
if ( isset( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) && is_string( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) ) {
|
||||||
$recovery_code_input = sanitize_text_field( wp_unslash( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) );
|
$recovery_code_input = sanitize_text_field( wp_unslash( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -796,8 +871,8 @@ class Profile_Settings {
|
||||||
|
|
||||||
$frequency = Frequency_Options::FREQUENCY_SESSION;
|
$frequency = Frequency_Options::FREQUENCY_SESSION;
|
||||||
|
|
||||||
if ( isset( $submitted_settings['frequency'] ) ) {
|
if ( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ) {
|
||||||
$frequency = Frequency_Options::sanitize( (string) $submitted_settings['frequency'] );
|
$frequency = Frequency_Options::sanitize( sanitize_key( wp_unslash( $raw_settings['frequency'] ) ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( $this->config->is_frequency_forced() ) {
|
if ( $this->config->is_frequency_forced() ) {
|
||||||
|
|
@ -890,21 +965,21 @@ class Profile_Settings {
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @param int $user_id User identifier.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{codes: array<int, string>, generated_at: int}
|
||||||
*/
|
*/
|
||||||
private function get_recovery_preview( int $user_id ): array {
|
private function get_recovery_preview( int $user_id ): array {
|
||||||
$key = $this->get_recovery_preview_transient_key( $user_id );
|
$key = $this->get_recovery_preview_transient_key( $user_id );
|
||||||
$preview = get_transient( $key );
|
$preview = get_transient( $key );
|
||||||
|
|
||||||
if ( false === $preview || ! is_array( $preview ) ) {
|
if ( ! is_array( $preview ) ) {
|
||||||
return array(
|
return array(
|
||||||
'codes' => array(),
|
'codes' => array(),
|
||||||
'generated_at' => 0,
|
'generated_at' => 0,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
$codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $this->normalize_preview_codes( $preview['codes'] ) : array();
|
$codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $this->normalize_preview_codes( array_values( $preview['codes'] ) ) : array();
|
||||||
$generated_at = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0;
|
$generated_at = isset( $preview['generated_at'] ) && is_int( $preview['generated_at'] ) ? $preview['generated_at'] : 0;
|
||||||
|
|
||||||
return array(
|
return array(
|
||||||
'codes' => $codes,
|
'codes' => $codes,
|
||||||
|
|
@ -1001,7 +1076,7 @@ class Profile_Settings {
|
||||||
$length = $this->recovery_codes->get_code_length();
|
$length = $this->recovery_codes->get_code_length();
|
||||||
|
|
||||||
foreach ( $codes as $code ) {
|
foreach ( $codes as $code ) {
|
||||||
$digits = preg_replace( '/[^0-9]/', '', (string) $code );
|
$digits = preg_replace( '/[^0-9]/', '', is_string( $code ) ? $code : '' );
|
||||||
|
|
||||||
if ( null === $digits ) {
|
if ( null === $digits ) {
|
||||||
continue;
|
continue;
|
||||||
|
|
@ -1069,37 +1144,10 @@ class Profile_Settings {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve the default method key to use when no method was selected.
|
|
||||||
*
|
|
||||||
* @param array<string, array<string, string>> $available_methods Available method definitions.
|
|
||||||
*
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
private function get_default_method_key( array $available_methods ): string {
|
|
||||||
$configured_method = $this->config->get_default_method();
|
|
||||||
|
|
||||||
if ( isset( $available_methods[ $configured_method ] ) ) {
|
|
||||||
return $configured_method;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( isset( $available_methods['email'] ) ) {
|
|
||||||
return 'email';
|
|
||||||
}
|
|
||||||
|
|
||||||
$available_keys = array_keys( $available_methods );
|
|
||||||
|
|
||||||
if ( ! empty( $available_keys ) ) {
|
|
||||||
return (string) $available_keys[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'email';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve the frequency value shown and stored for the user.
|
* Resolve the frequency value shown and stored for the user.
|
||||||
*
|
*
|
||||||
* @param array<string, mixed> $user_settings Stored user settings.
|
* @param array{enabled: bool, methods: array<int, string>, frequency: string} $user_settings Stored user settings.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
|
|
@ -1110,8 +1158,8 @@ class Profile_Settings {
|
||||||
return $global_frequency;
|
return $global_frequency;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( ! empty( $user_settings['frequency'] ) ) {
|
if ( '' !== $user_settings['frequency'] ) {
|
||||||
return Frequency_Options::sanitize( (string) $user_settings['frequency'] );
|
return Frequency_Options::sanitize( $user_settings['frequency'] );
|
||||||
}
|
}
|
||||||
|
|
||||||
return $global_frequency;
|
return $global_frequency;
|
||||||
|
|
|
||||||
|
|
@ -87,7 +87,8 @@ class Recovery_Codes {
|
||||||
public function handle_ajax_generate_request(): void {
|
public function handle_ajax_generate_request(): void {
|
||||||
check_ajax_referer( self::NONCE_ACTION, self::NONCE_FIELD );
|
check_ajax_referer( self::NONCE_ACTION, self::NONCE_FIELD );
|
||||||
|
|
||||||
$user_id = isset( $_POST['user_id'] ) ? absint( wp_unslash( $_POST['user_id'] ) ) : 0;
|
$raw_user_id = isset( $_POST['user_id'] ) && is_string( $_POST['user_id'] ) ? wp_unslash( $_POST['user_id'] ) : '';
|
||||||
|
$user_id = absint( $raw_user_id );
|
||||||
|
|
||||||
if ( $user_id <= 0 ) {
|
if ( $user_id <= 0 ) {
|
||||||
wp_send_json_error(
|
wp_send_json_error(
|
||||||
|
|
@ -121,6 +122,13 @@ class Recovery_Codes {
|
||||||
try {
|
try {
|
||||||
$result = $this->regenerate_codes_for_user( $user );
|
$result = $this->regenerate_codes_for_user( $user );
|
||||||
} catch ( \Throwable $exception ) {
|
} catch ( \Throwable $exception ) {
|
||||||
|
/**
|
||||||
|
* Fires when recovery code generation fails.
|
||||||
|
*
|
||||||
|
* @since 0.2.0
|
||||||
|
*
|
||||||
|
* @param \Throwable $exception The caught exception.
|
||||||
|
*/
|
||||||
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
|
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
|
||||||
wp_send_json_error(
|
wp_send_json_error(
|
||||||
array(
|
array(
|
||||||
|
|
@ -147,7 +155,7 @@ class Recovery_Codes {
|
||||||
*
|
*
|
||||||
* @throws \Exception If secure randomness cannot be generated.
|
* @throws \Exception If secure randomness cannot be generated.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{codes: array<int, string>, generated_at: int, unused_count: int}
|
||||||
*/
|
*/
|
||||||
public function regenerate_codes_for_user( WP_User $user ): array {
|
public function regenerate_codes_for_user( WP_User $user ): array {
|
||||||
$codes = $this->generate_codes();
|
$codes = $this->generate_codes();
|
||||||
|
|
@ -269,7 +277,7 @@ class Recovery_Codes {
|
||||||
public function get_last_generated_timestamp( int $user_id ): int {
|
public function get_last_generated_timestamp( int $user_id ): int {
|
||||||
$record = $this->get_stored_codes( $user_id );
|
$record = $this->get_stored_codes( $user_id );
|
||||||
|
|
||||||
return (int) ( $record['generated_at'] ?? 0 );
|
return $record['generated_at'];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -287,9 +295,10 @@ class Recovery_Codes {
|
||||||
$date_format = get_option( 'date_format' );
|
$date_format = get_option( 'date_format' );
|
||||||
$time_format = get_option( 'time_format' );
|
$time_format = get_option( 'time_format' );
|
||||||
|
|
||||||
$format = trim( (string) $date_format . ' ' . (string) $time_format );
|
$format = trim( ( is_string( $date_format ) ? $date_format : '' ) . ' ' . ( is_string( $time_format ) ? $time_format : '' ) );
|
||||||
|
|
||||||
return '' !== $format ? wp_date( $format, $timestamp ) : wp_date( 'c', $timestamp );
|
$formatted = wp_date( '' !== $format ? $format : 'c', $timestamp );
|
||||||
|
return false !== $formatted ? $formatted : '';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -390,7 +399,7 @@ class Recovery_Codes {
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @param int $user_id User identifier.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{generated_at: int, codes: array<int, array{hash: string, used_at: int}>}
|
||||||
*/
|
*/
|
||||||
private function get_stored_codes( int $user_id ): array {
|
private function get_stored_codes( int $user_id ): array {
|
||||||
$record = get_user_meta( $user_id, self::META_KEY, true );
|
$record = get_user_meta( $user_id, self::META_KEY, true );
|
||||||
|
|
@ -399,23 +408,22 @@ class Recovery_Codes {
|
||||||
$record = array();
|
$record = array();
|
||||||
}
|
}
|
||||||
|
|
||||||
$record['generated_at'] = isset( $record['generated_at'] ) ? (int) $record['generated_at'] : 0;
|
$generated_at = isset( $record['generated_at'] ) && is_int( $record['generated_at'] ) ? $record['generated_at'] : 0;
|
||||||
$record['codes'] = isset( $record['codes'] ) && is_array( $record['codes'] ) ? $record['codes'] : array();
|
$raw_codes = isset( $record['codes'] ) && is_array( $record['codes'] ) ? $record['codes'] : array();
|
||||||
|
|
||||||
foreach ( $record['codes'] as $index => $entry ) {
|
$codes = array();
|
||||||
if ( ! is_array( $entry ) ) {
|
|
||||||
$record['codes'][ $index ] = array(
|
|
||||||
'hash' => '',
|
|
||||||
'used_at' => 0,
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$record['codes'][ $index ]['hash'] = isset( $entry['hash'] ) && is_string( $entry['hash'] ) ? $entry['hash'] : '';
|
foreach ( $raw_codes as $entry ) {
|
||||||
$record['codes'][ $index ]['used_at'] = isset( $entry['used_at'] ) ? (int) $entry['used_at'] : 0;
|
$codes[] = array(
|
||||||
|
'hash' => is_array( $entry ) && isset( $entry['hash'] ) && is_string( $entry['hash'] ) ? $entry['hash'] : '',
|
||||||
|
'used_at' => is_array( $entry ) && isset( $entry['used_at'] ) && is_int( $entry['used_at'] ) ? $entry['used_at'] : 0,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $record;
|
return array(
|
||||||
|
'generated_at' => $generated_at,
|
||||||
|
'codes' => $codes,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -21,55 +21,65 @@ class Two_Factor_Config {
|
||||||
/**
|
/**
|
||||||
* Retrieve global two-factor settings with multisite support.
|
* Retrieve global two-factor settings with multisite support.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
|
||||||
*/
|
*/
|
||||||
public function get_settings(): array {
|
public function get_settings(): array {
|
||||||
$settings = array();
|
$settings_page = new Settings_Page();
|
||||||
|
return $settings_page->get_settings();
|
||||||
if ( is_multisite() ) {
|
|
||||||
$network_settings = get_site_option( Settings_Page::OPTION_NAME, array() );
|
|
||||||
|
|
||||||
if ( is_array( $network_settings ) && ! empty( $network_settings ) ) {
|
|
||||||
$settings = $network_settings;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( empty( $settings ) ) {
|
|
||||||
$site_settings = get_option( Settings_Page::OPTION_NAME, array() );
|
|
||||||
|
|
||||||
if ( is_array( $site_settings ) ) {
|
|
||||||
$settings = $site_settings;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return wp_parse_args(
|
|
||||||
$settings,
|
|
||||||
array(
|
|
||||||
'force_roles' => array(),
|
|
||||||
'default_method' => 'email',
|
|
||||||
'frequency' => Frequency_Options::FREQUENCY_SESSION,
|
|
||||||
'force_frequency' => false,
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the list of roles that must enable two-factor authentication.
|
* Retrieve the per-role method map.
|
||||||
|
*
|
||||||
|
* @return array<string, array<int, string>>
|
||||||
|
*/
|
||||||
|
public function get_role_methods(): array {
|
||||||
|
return $this->get_settings()['role_methods'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the list of roles that have at least one required method configured.
|
||||||
*
|
*
|
||||||
* @return array<int, string>
|
* @return array<int, string>
|
||||||
*/
|
*/
|
||||||
public function get_forced_roles(): array {
|
public function get_forced_roles(): array {
|
||||||
$settings = $this->get_settings();
|
return array_keys( $this->get_role_methods() );
|
||||||
|
}
|
||||||
|
|
||||||
if ( empty( $settings['force_roles'] ) || ! is_array( $settings['force_roles'] ) ) {
|
/**
|
||||||
return array();
|
* Retrieve the required verification methods for a specific role.
|
||||||
|
*
|
||||||
|
* @param string $role Role slug.
|
||||||
|
*
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public function get_methods_for_role( string $role ): array {
|
||||||
|
$role_methods = $this->get_role_methods();
|
||||||
|
return $role_methods[ $role ] ?? array();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the union of required methods across all of a user's roles.
|
||||||
|
*
|
||||||
|
* Returns an empty array when none of the user's roles have required methods.
|
||||||
|
*
|
||||||
|
* @param \WP_User $user User object currently being authenticated.
|
||||||
|
*
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public function get_required_methods_for_user( \WP_User $user ): array {
|
||||||
|
$role_methods = $this->get_role_methods();
|
||||||
|
$required = array();
|
||||||
|
|
||||||
|
foreach ( $user->roles as $role ) {
|
||||||
|
if ( isset( $role_methods[ $role ] ) ) {
|
||||||
|
foreach ( $role_methods[ $role ] as $method ) {
|
||||||
|
$required[] = $method;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return array_values(
|
return array_values( array_unique( $required ) );
|
||||||
array_filter(
|
|
||||||
array_map( 'sanitize_key', $settings['force_roles'] )
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -80,30 +90,7 @@ class Two_Factor_Config {
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
public function is_two_factor_forced_for_user( \WP_User $user ): bool {
|
public function is_two_factor_forced_for_user( \WP_User $user ): bool {
|
||||||
$forced_roles = $this->get_forced_roles();
|
return ! empty( $this->get_required_methods_for_user( $user ) );
|
||||||
|
|
||||||
if ( empty( $forced_roles ) ) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ( $user->roles as $role ) {
|
|
||||||
if ( in_array( $role, $forced_roles, true ) ) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieve the default two-factor authentication method.
|
|
||||||
*
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
public function get_default_method(): string {
|
|
||||||
$settings = $this->get_settings();
|
|
||||||
|
|
||||||
return sanitize_key( $settings['default_method'] ?? 'email' );
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -112,9 +99,7 @@ class Two_Factor_Config {
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function get_frequency(): string {
|
public function get_frequency(): string {
|
||||||
$settings = $this->get_settings();
|
return $this->get_settings()['frequency'];
|
||||||
|
|
||||||
return Frequency_Options::sanitize( (string) ( $settings['frequency'] ?? Frequency_Options::FREQUENCY_SESSION ) );
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -123,8 +108,6 @@ class Two_Factor_Config {
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
public function is_frequency_forced(): bool {
|
public function is_frequency_forced(): bool {
|
||||||
$settings = $this->get_settings();
|
return $this->get_settings()['force_frequency'];
|
||||||
|
|
||||||
return ! empty( $settings['force_frequency'] );
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,7 @@ class User_Settings_Repository {
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @param int $user_id User identifier.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{enabled: bool, methods: array<int, string>, frequency: string}
|
||||||
*/
|
*/
|
||||||
public function get_user_settings( int $user_id ): array {
|
public function get_user_settings( int $user_id ): array {
|
||||||
$raw_settings = get_user_meta( $user_id, self::USER_SETTINGS_META, true );
|
$raw_settings = get_user_meta( $user_id, self::USER_SETTINGS_META, true );
|
||||||
|
|
@ -57,48 +57,51 @@ class User_Settings_Repository {
|
||||||
$raw_settings = array();
|
$raw_settings = array();
|
||||||
}
|
}
|
||||||
|
|
||||||
$defaults = array(
|
$raw_methods = isset( $raw_settings['methods'] ) && is_array( $raw_settings['methods'] ) ? $raw_settings['methods'] : array();
|
||||||
'enabled' => false,
|
|
||||||
'methods' => array(),
|
|
||||||
'frequency' => Frequency_Options::FREQUENCY_SESSION,
|
|
||||||
);
|
|
||||||
|
|
||||||
$settings = wp_parse_args( $raw_settings, $defaults );
|
return array(
|
||||||
|
'enabled' => ! empty( $raw_settings['enabled'] ),
|
||||||
$settings['enabled'] = (bool) $settings['enabled'];
|
'methods' => array_values(
|
||||||
|
array_unique(
|
||||||
$settings['methods'] = array_values(
|
array_filter(
|
||||||
array_unique(
|
array_map(
|
||||||
array_filter(
|
static function ( mixed $v ): string {
|
||||||
array_map( 'sanitize_key', (array) $settings['methods'] )
|
return sanitize_key( is_string( $v ) ? $v : '' );
|
||||||
|
},
|
||||||
|
$raw_methods
|
||||||
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
),
|
||||||
|
'frequency' => Frequency_Options::sanitize( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ? $raw_settings['frequency'] : '' ),
|
||||||
);
|
);
|
||||||
|
|
||||||
$settings['frequency'] = Frequency_Options::sanitize( (string) $settings['frequency'] );
|
|
||||||
|
|
||||||
return $settings;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Persist 2FA settings for a user.
|
* Persist 2FA settings for a user.
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @param int $user_id User identifier.
|
||||||
* @param array $settings Settings to store.
|
* @param array<string, mixed> $settings Settings to store.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function save_user_settings( int $user_id, array $settings ): void {
|
public function save_user_settings( int $user_id, array $settings ): void {
|
||||||
$prepared = array(
|
$raw_methods = isset( $settings['methods'] ) && is_array( $settings['methods'] ) ? $settings['methods'] : array();
|
||||||
|
$prepared = array(
|
||||||
'enabled' => ! empty( $settings['enabled'] ),
|
'enabled' => ! empty( $settings['enabled'] ),
|
||||||
'methods' => array_values(
|
'methods' => array_values(
|
||||||
array_unique(
|
array_unique(
|
||||||
array_filter(
|
array_filter(
|
||||||
array_map( 'sanitize_key', $settings['methods'] ?? array() )
|
array_map(
|
||||||
|
static function ( mixed $v ): string {
|
||||||
|
return sanitize_key( is_string( $v ) ? $v : '' );
|
||||||
|
},
|
||||||
|
$raw_methods
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
),
|
),
|
||||||
'frequency' => Frequency_Options::sanitize( (string) ( $settings['frequency'] ?? Frequency_Options::FREQUENCY_SESSION ) ),
|
'frequency' => Frequency_Options::sanitize( isset( $settings['frequency'] ) && is_string( $settings['frequency'] ) ? $settings['frequency'] : Frequency_Options::FREQUENCY_SESSION ),
|
||||||
);
|
);
|
||||||
|
|
||||||
update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared );
|
update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared );
|
||||||
|
|
@ -133,7 +136,7 @@ class User_Settings_Repository {
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @param int $user_id User identifier.
|
||||||
*
|
*
|
||||||
* @return array<string, int|string>
|
* @return array{hash: string, expires: int, sent_at: int}
|
||||||
*/
|
*/
|
||||||
public function get_email_challenge( int $user_id ): array {
|
public function get_email_challenge( int $user_id ): array {
|
||||||
$record = get_user_meta( $user_id, self::EMAIL_CHALLENGE_META, true );
|
$record = get_user_meta( $user_id, self::EMAIL_CHALLENGE_META, true );
|
||||||
|
|
@ -142,20 +145,11 @@ class User_Settings_Repository {
|
||||||
$record = array();
|
$record = array();
|
||||||
}
|
}
|
||||||
|
|
||||||
$record = wp_parse_args(
|
return array(
|
||||||
$record,
|
'hash' => isset( $record['hash'] ) && is_string( $record['hash'] ) ? $record['hash'] : '',
|
||||||
array(
|
'expires' => isset( $record['expires'] ) && is_numeric( $record['expires'] ) ? (int) $record['expires'] : 0,
|
||||||
'hash' => '',
|
'sent_at' => isset( $record['sent_at'] ) && is_numeric( $record['sent_at'] ) ? (int) $record['sent_at'] : 0,
|
||||||
'expires' => 0,
|
|
||||||
'sent_at' => 0,
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
$record['hash'] = is_string( $record['hash'] ) ? $record['hash'] : '';
|
|
||||||
$record['expires'] = (int) $record['expires'];
|
|
||||||
$record['sent_at'] = (int) $record['sent_at'];
|
|
||||||
|
|
||||||
return $record;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -205,8 +199,10 @@ class User_Settings_Repository {
|
||||||
if ( count( $record[ $method ] ) > self::CONTEXT_LIMIT ) {
|
if ( count( $record[ $method ] ) > self::CONTEXT_LIMIT ) {
|
||||||
uasort(
|
uasort(
|
||||||
$record[ $method ],
|
$record[ $method ],
|
||||||
static function ( array $a, array $b ): int {
|
static function ( mixed $a, mixed $b ): int {
|
||||||
return ( $a['verified_at'] ?? 0 ) <=> ( $b['verified_at'] ?? 0 );
|
$a_ts = is_array( $a ) && isset( $a['verified_at'] ) && is_int( $a['verified_at'] ) ? $a['verified_at'] : 0;
|
||||||
|
$b_ts = is_array( $b ) && isset( $b['verified_at'] ) && is_int( $b['verified_at'] ) ? $b['verified_at'] : 0;
|
||||||
|
return $a_ts <=> $b_ts;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -239,11 +235,13 @@ class User_Settings_Repository {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( empty( $record[ $method ][ $context_key ]['verified_at'] ) ) {
|
$entry = $record[ $method ][ $context_key ] ?? null;
|
||||||
|
|
||||||
|
if ( ! is_array( $entry ) || empty( $entry['verified_at'] ) || ! is_int( $entry['verified_at'] ) ) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (int) $record[ $method ][ $context_key ]['verified_at'];
|
return $entry['verified_at'];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
81
readme.txt
81
readme.txt
|
|
@ -2,44 +2,99 @@
|
||||||
Contributors: robotstxt
|
Contributors: robotstxt
|
||||||
Tags: security, two-factor authentication, login, otp
|
Tags: security, two-factor authentication, login, otp
|
||||||
Requires at least: 6.4
|
Requires at least: 6.4
|
||||||
Tested up to: 6.4
|
Tested up to: 7.0
|
||||||
Requires PHP: 8.2
|
Requires PHP: 8.2
|
||||||
Stable tag: 0.2.0
|
Stable tag: 0.3.0
|
||||||
License: GPLv3 or later
|
License: GPLv3 or later
|
||||||
License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
||||||
|
|
||||||
Security plugin that adds a two-factor authentication flow to the WordPress login screen.
|
Security plugin that adds per-role two-factor authentication to the WordPress login flow.
|
||||||
|
|
||||||
== Description ==
|
== Description ==
|
||||||
|
|
||||||
This plugin lets administrators enforce two-factor authentication per role and already delivers email verification codes during the login flow. After the username and password are validated, the login screen redirects to a dedicated verification step flagged with its own query parameter. The screen hides the username and password controls, automatically prioritizes authenticator apps when they are enabled, offers links to switch between authenticator, email, or recovery-code challenges, lets email users trigger an additional delivery when they need a fresh code, and auto-submits once the active method reaches its expected length (six digits for OTP, seven for email, eight for recovery codes). Users can manage their preferences from their profile, where every method starts unchecked until it is explicitly confirmed. The authenticator section now keeps the QR code and setup key visible until a valid six-digit code is entered, regenerates the secret whenever the option is disabled, and surfaces a dedicated button to issue a replacement secret. Recovery codes are shown in a two-column grid, expose the remaining count out of ten, require entering one code before activation, and automatically reset when the stored batch is exhausted so a fresh list is always available without extra clicks.
|
2FA (by ROBOTSTXT) enforces two-factor authentication on the WordPress login screen. Administrators configure a per-role matrix that specifies exactly which verification methods are required for each role: email codes, authenticator apps (TOTP), or recovery codes.
|
||||||
|
|
||||||
Administrators can remember successful verifications for a configurable duration—per login, daily, weekly, or every 28 days—and even lock the schedule so profiles inherit the global requirement. Device and IP fingerprints are stored securely to decide when a fresh challenge is needed, ensuring suspicious logins must re-validate regardless of the remembered interval.
|
After the username and password are validated, the login screen redirects to a dedicated verification step. The screen hides the username and password controls, prioritises authenticator apps when enabled, and offers links to switch between methods without restarting the login. Email users can request a fresh code from the same screen.
|
||||||
|
|
||||||
|
Users manage their preferences from their profile page. Every method starts unchecked until explicitly confirmed. Activating the authenticator app requires scanning the QR code and entering a valid six-digit code. Recovery codes must be saved and confirmed with one code before activation. Codes are shown in a two-column grid and automatically refresh when the batch is exhausted.
|
||||||
|
|
||||||
|
Administrators can remember successful verifications for a configurable duration — per login, daily, weekly, or every 28 days — and lock the schedule so all users follow the global setting. Device and IP fingerprints are stored securely to decide when a fresh challenge is needed.
|
||||||
|
|
||||||
|
Multisite is fully supported: network administrators can set and lock enforcement settings across all sites.
|
||||||
|
|
||||||
== Installation ==
|
== Installation ==
|
||||||
|
|
||||||
1. Upload the `robotstxt-2fa` directory to `/wp-content/plugins/`.
|
1. Upload the `robotstxt-2fa` directory to `/wp-content/plugins/`.
|
||||||
2. Activate the plugin through the "Plugins" menu in WordPress.
|
2. Activate the plugin through the "Plugins" menu in WordPress (or network-activate it for multisite).
|
||||||
3. Configure the authentication options in your profile and in the Two-Factor Authentication admin menu.
|
3. Open the **2FA** top-level menu in the dashboard and configure which methods are required per role.
|
||||||
|
4. Users can set up their preferred methods from their profile page.
|
||||||
|
|
||||||
== Frequently Asked Questions ==
|
== Frequently Asked Questions ==
|
||||||
|
|
||||||
= Is this plugin production ready? =
|
= Is this plugin production ready? =
|
||||||
|
|
||||||
Yes. Email codes, recovery confirmations, and authenticator apps with on-site QR codes are all available, though you should still test changes in a staging environment before enforcing them across your site.
|
Yes. Email codes, authenticator apps with on-site QR codes, and recovery codes are all available and tested.
|
||||||
|
|
||||||
= How do I enable the authenticator QR code? =
|
= How do I enable the authenticator QR code? =
|
||||||
|
|
||||||
Install the optional QR library inside this plugin directory with `composer require bacon/bacon-qr-code:^3.0`. The plugin will automatically load the Composer autoloader when it exists, enabling the QR code renderer for the OTP method.
|
Install the optional QR library inside this plugin directory with `composer require bacon/bacon-qr-code:^3.0`. The plugin loads the Composer autoloader automatically when present.
|
||||||
|
|
||||||
|
= Can I enforce 2FA for specific roles only? =
|
||||||
|
|
||||||
|
Yes. The admin settings page shows a matrix of roles × methods. Check the methods you want to require for each role. Roles with no methods checked leave the choice to the user.
|
||||||
|
|
||||||
|
= What happens if a user loses all their verification methods? =
|
||||||
|
|
||||||
|
An administrator can edit the user's profile and generate a fresh batch of recovery codes, or disable the role enforcement temporarily while the user regains access.
|
||||||
|
|
||||||
|
= Is multisite supported? =
|
||||||
|
|
||||||
|
Yes. Activate the plugin at the network level. Network administrators can set and lock enforcement settings; per-site settings are overridden when network settings exist.
|
||||||
|
|
||||||
|
== Compatibility ==
|
||||||
|
|
||||||
|
* WordPress: 6.4 – 7.0
|
||||||
|
* PHP: 8.2 – 8.5
|
||||||
|
* MariaDB: 11.4 or newer
|
||||||
|
|
||||||
== Changelog ==
|
== Changelog ==
|
||||||
|
|
||||||
Review the `changelog.txt` file for additional details.
|
= 0.3.0 =
|
||||||
|
|
||||||
== Upgrade Notice ==
|
_Release date: 2026-06-05_
|
||||||
|
|
||||||
|
* Added delete-on-uninstall option (data preserved by default per AGENTS.md).
|
||||||
|
* Security: email verification codes now use `random_int()` (CSPRNG) instead of `wp_rand()`.
|
||||||
|
* Security: recovery code preview transient now expires after 5 minutes.
|
||||||
|
* Fixed network admin settings page form submission.
|
||||||
|
* Fixed settings option set to `autoload=false` (not needed on every page load).
|
||||||
|
|
||||||
= 0.2.0 =
|
= 0.2.0 =
|
||||||
Authenticator apps now include on-page QR codes and recovery codes stay visible until you confirm one of them. This update also fixes the confirmation workflow and improves the QR fallback guidance when PHP extensions are missing.
|
|
||||||
|
_Release date: 2026-06-05_
|
||||||
|
|
||||||
|
* Added per-role 2FA method matrix in admin settings with select-all row and column controls.
|
||||||
|
* Added authenticator app (TOTP) support with QR provisioning and manual setup key.
|
||||||
|
* Added recovery codes: 10 single-use 8-digit codes with confirmation workflow.
|
||||||
|
* Added configurable verification frequency remembered per device.
|
||||||
|
* Added network-wide multisite support.
|
||||||
|
* Changed profile method checkboxes to require explicit confirmation before activation.
|
||||||
|
* Fixed recovery-code preview persistence and QR generation error handling.
|
||||||
|
|
||||||
= 0.1.0 =
|
= 0.1.0 =
|
||||||
Initial version containing the basic plugin structure.
|
|
||||||
|
Initial release.
|
||||||
|
|
||||||
|
= Previous versions =
|
||||||
|
|
||||||
|
For the full changelog see the [changelog.txt](https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/raw/branch/main/changelog.txt) file.
|
||||||
|
|
||||||
|
== Compliance ==
|
||||||
|
|
||||||
|
This plugin adheres to the following security measures and review protocols for each version:
|
||||||
|
|
||||||
|
* [WordPress Plugin Handbook](https://developer.wordpress.org/plugins/)
|
||||||
|
* [WordPress Plugin Security](https://developer.wordpress.org/plugins/wordpress-org/plugin-security/)
|
||||||
|
* [WordPress APIs Security](https://developer.wordpress.org/apis/security/)
|
||||||
|
* [WordPress Coding Standards](https://github.com/WordPress/WordPress-Coding-Standards)
|
||||||
|
* [Plugin Check (PCP)](https://wordpress.org/plugins/plugin-check/)
|
||||||
|
|
|
||||||
|
|
@ -3,14 +3,15 @@
|
||||||
* Plugin Name: 2FA (by ROBOTSTXT)
|
* Plugin Name: 2FA (by ROBOTSTXT)
|
||||||
* Plugin URI: https://www.robotstxt.es/plugins/robotstxt-2fa/
|
* Plugin URI: https://www.robotstxt.es/plugins/robotstxt-2fa/
|
||||||
* Description: Adds two-factor authentication to the WordPress login flow.
|
* Description: Adds two-factor authentication to the WordPress login flow.
|
||||||
* Version: 0.2.0
|
* Version: 0.3.0
|
||||||
* Author: ROBOTSTXT
|
* Author: ROBOTSTXT
|
||||||
* Author URI: https://www.robotstxt.es/
|
* Author URI: https://www.robotstxt.es/
|
||||||
* Text Domain: robotstxt-2fa
|
* Text Domain: robotstxt-2fa
|
||||||
* Requires at least: 6.4
|
* Requires at least: 6.4
|
||||||
* Requires PHP: 8.2
|
* Requires PHP: 8.2
|
||||||
* License: GPLv2 or later
|
* Network: true
|
||||||
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
|
* License: GPLv3 or later
|
||||||
|
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
||||||
*
|
*
|
||||||
* @package Robotstxt_2FA
|
* @package Robotstxt_2FA
|
||||||
*/
|
*/
|
||||||
|
|
@ -22,7 +23,7 @@ if ( ! defined( 'ABSPATH' ) ) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) {
|
if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) {
|
||||||
define( 'ROBOTSTXT_2FA_VERSION', '0.2.0' );
|
define( 'ROBOTSTXT_2FA_VERSION', '0.3.0' );
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( ! defined( 'ROBOTSTXT_2FA_FILE' ) ) {
|
if ( ! defined( 'ROBOTSTXT_2FA_FILE' ) ) {
|
||||||
|
|
@ -37,27 +38,27 @@ if ( ! defined( 'ROBOTSTXT_2FA_URL' ) ) {
|
||||||
define( 'ROBOTSTXT_2FA_URL', plugin_dir_url( __FILE__ ) );
|
define( 'ROBOTSTXT_2FA_URL', plugin_dir_url( __FILE__ ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
$autoload = ROBOTSTXT_2FA_PATH . 'vendor/autoload.php';
|
$robotstxt_2fa_autoload = ROBOTSTXT_2FA_PATH . 'vendor/autoload.php';
|
||||||
|
|
||||||
if ( file_exists( $autoload ) ) {
|
if ( file_exists( $robotstxt_2fa_autoload ) ) {
|
||||||
require_once $autoload;
|
require_once $robotstxt_2fa_autoload;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple autoloader for the plugin classes.
|
* Simple autoloader for the plugin classes.
|
||||||
*
|
*
|
||||||
* @param string $class Fully qualified class name requested by PHP.
|
* @param string $class_name Fully qualified class name requested by PHP.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
function robotstxt_2fa_autoload( string $class ): void {
|
function robotstxt_2fa_autoload( string $class_name ): void {
|
||||||
$prefix = 'Robotstxt\\TwoFA\\';
|
$prefix = 'Robotstxt\\TwoFA\\';
|
||||||
|
|
||||||
if ( strncmp( $prefix, $class, strlen( $prefix ) ) !== 0 ) {
|
if ( strncmp( $prefix, $class_name, strlen( $prefix ) ) !== 0 ) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$relative_class = substr( $class, strlen( $prefix ) );
|
$relative_class = substr( $class_name, strlen( $prefix ) );
|
||||||
$relative_parts = explode( '\\', $relative_class );
|
$relative_parts = explode( '\\', $relative_class );
|
||||||
$filename = array_pop( $relative_parts );
|
$filename = array_pop( $relative_parts );
|
||||||
|
|
||||||
|
|
|
||||||
384
robotstxt-updater.php
Normal file
384
robotstxt-updater.php
Normal file
|
|
@ -0,0 +1,384 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Generic JSON-based updater for ROBOTSTXT plugins.
|
||||||
|
*
|
||||||
|
* This file is designed to be copied to any ROBOTSTXT plugin.
|
||||||
|
* It auto-configures itself by reading the plugin headers.
|
||||||
|
*
|
||||||
|
* @package ROBOTSTXT
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
|
||||||
|
if ( ! defined( 'ABSPATH' ) ) {
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( ! class_exists( 'Robotstxt_Updater' ) ) {
|
||||||
|
/**
|
||||||
|
* Class Robotstxt_Updater
|
||||||
|
*
|
||||||
|
* Generic updater that works with any plugin.
|
||||||
|
* Reads plugin headers and constructs update URL automatically.
|
||||||
|
*/
|
||||||
|
class Robotstxt_Updater {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plugin file path.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private string $plugin_file_path;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plugin basename (e.g., 'my-plugin/my-plugin.php').
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private string $plugin_basename;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plugin slug (directory name).
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private string $plugin_slug;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remote JSON URL.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private string $json_url;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache key.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private string $cache_key;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plugin headers.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
private array $plugin_data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the updater.
|
||||||
|
*
|
||||||
|
* Usage in your main plugin file:
|
||||||
|
* require_once __DIR__ . '/robotstxt-updater.php';
|
||||||
|
* Robotstxt_Updater::init( __FILE__ );
|
||||||
|
*
|
||||||
|
* @param string $plugin_file_path Absolute path to the main plugin file.
|
||||||
|
*/
|
||||||
|
public static function init( string $plugin_file_path ): void {
|
||||||
|
$instance = new self( $plugin_file_path );
|
||||||
|
$instance->register();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructor.
|
||||||
|
*
|
||||||
|
* @param string $plugin_file_path Absolute path to the main plugin file.
|
||||||
|
*/
|
||||||
|
private function __construct( string $plugin_file_path ) {
|
||||||
|
$this->plugin_file_path = $plugin_file_path;
|
||||||
|
$this->plugin_basename = plugin_basename( $plugin_file_path );
|
||||||
|
$this->plugin_slug = dirname( $this->plugin_basename );
|
||||||
|
$this->plugin_data = $this->get_plugin_data();
|
||||||
|
$this->json_url = $this->build_json_url();
|
||||||
|
$this->cache_key = 'robotstxt_updater_' . md5( $this->plugin_basename );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register WordPress hooks.
|
||||||
|
*/
|
||||||
|
private function register(): void {
|
||||||
|
add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'inject_update_info' ) );
|
||||||
|
add_filter( 'plugins_api', array( $this, 'provide_plugin_details' ), 10, 3 );
|
||||||
|
add_action( 'admin_init', array( $this, 'handle_cache_clear' ) );
|
||||||
|
add_action( 'robotstxt_updater_clear_cache', array( $this, 'clear_cache' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get plugin headers.
|
||||||
|
*
|
||||||
|
* @return array Plugin data.
|
||||||
|
*/
|
||||||
|
private function get_plugin_data(): array {
|
||||||
|
if ( ! function_exists( 'get_plugin_data' ) ) {
|
||||||
|
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||||
|
}
|
||||||
|
|
||||||
|
return get_plugin_data( $this->plugin_file_path, false, false );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build JSON URL from plugin headers.
|
||||||
|
*
|
||||||
|
* Tries to use "Gitea Plugin URI" header to construct the URL.
|
||||||
|
* Falls back to Plugin URI if Gitea URI is not available.
|
||||||
|
*
|
||||||
|
* @return string JSON URL.
|
||||||
|
*/
|
||||||
|
private function build_json_url(): string {
|
||||||
|
// Try Gitea Plugin URI (format: "OWNER/REPO" or full URL).
|
||||||
|
if ( ! empty( $this->plugin_data['Gitea Plugin URI'] ) ) {
|
||||||
|
$gitea_uri = $this->plugin_data['Gitea Plugin URI'];
|
||||||
|
|
||||||
|
// If it's already a full URL, use it.
|
||||||
|
if ( str_starts_with( $gitea_uri, 'http' ) ) {
|
||||||
|
// Extract base URL and construct JSON path.
|
||||||
|
return rtrim( $gitea_uri, '/' ) . '/raw/branch/main/update.json';
|
||||||
|
}
|
||||||
|
|
||||||
|
// If it's in format "OWNER/REPO", construct full URL.
|
||||||
|
if ( preg_match( '#^[^/]+/[^/]+$#', $gitea_uri ) ) {
|
||||||
|
return "https://git.robotstxt.es/{$gitea_uri}/raw/branch/main/update.json";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: try to extract from Plugin URI.
|
||||||
|
if ( ! empty( $this->plugin_data['PluginURI'] ) ) {
|
||||||
|
$plugin_uri = $this->plugin_data['PluginURI'];
|
||||||
|
if ( str_contains( $plugin_uri, 'git.robotstxt.es' ) ) {
|
||||||
|
return rtrim( $plugin_uri, '/' ) . '/raw/branch/main/update.json';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Last resort: construct from plugin slug.
|
||||||
|
return "https://git.robotstxt.es/ROBOTSTXT/{$this->plugin_slug}/raw/branch/main/update.json";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inject update info into WP's plugin update transient.
|
||||||
|
*
|
||||||
|
* @param object|mixed $transient The update_plugins transient.
|
||||||
|
*
|
||||||
|
* @return object The modified transient.
|
||||||
|
*/
|
||||||
|
public function inject_update_info( $transient ) {
|
||||||
|
if ( ! is_object( $transient ) ) {
|
||||||
|
$transient = new stdClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( empty( $transient->checked ) || ! is_array( $transient->checked ) ) {
|
||||||
|
return $transient;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( empty( $transient->checked[ $this->plugin_basename ] ) ) {
|
||||||
|
return $transient;
|
||||||
|
}
|
||||||
|
|
||||||
|
$current_version = $transient->checked[ $this->plugin_basename ];
|
||||||
|
$remote = $this->get_remote_data();
|
||||||
|
|
||||||
|
if ( empty( $remote['version'] ) || empty( $remote['download_url'] ) ) {
|
||||||
|
return $transient;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( ! $this->is_compatible( $remote ) ) {
|
||||||
|
return $transient;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( version_compare( $remote['version'], $current_version, '>' ) ) {
|
||||||
|
$update = (object) array(
|
||||||
|
'slug' => $remote['slug'] ?? $this->plugin_slug,
|
||||||
|
'plugin' => $this->plugin_basename,
|
||||||
|
'new_version' => $remote['version'],
|
||||||
|
'url' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '',
|
||||||
|
'package' => $remote['download_url'],
|
||||||
|
'tested' => $remote['tested'] ?? '',
|
||||||
|
'requires' => $remote['requires'] ?? '',
|
||||||
|
'requires_php' => $remote['requires_php'] ?? '',
|
||||||
|
);
|
||||||
|
|
||||||
|
$transient->response[ $this->plugin_basename ] = $update;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $transient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provide "View details" modal content.
|
||||||
|
*
|
||||||
|
* @param false|object|array $result The result object or array.
|
||||||
|
* @param string $action The type of information being requested.
|
||||||
|
* @param object $args Plugin API arguments.
|
||||||
|
*
|
||||||
|
* @return false|object The plugin information object or false.
|
||||||
|
*/
|
||||||
|
public function provide_plugin_details( $result, string $action, object $args ) {
|
||||||
|
if ( 'plugin_information' !== $action ) {
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( empty( $args->slug ) || $args->slug !== $this->plugin_slug ) {
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
$remote = $this->get_remote_data();
|
||||||
|
|
||||||
|
if ( empty( $remote['version'] ) ) {
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (object) array(
|
||||||
|
'name' => $remote['name'] ?? $this->plugin_data['Name'] ?? $this->plugin_slug,
|
||||||
|
'slug' => $remote['slug'] ?? $this->plugin_slug,
|
||||||
|
'version' => $remote['version'],
|
||||||
|
'author' => $remote['author'] ?? $this->plugin_data['Author'] ?? '',
|
||||||
|
'homepage' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '',
|
||||||
|
'requires' => $remote['requires'] ?? '',
|
||||||
|
'tested' => $remote['tested'] ?? '',
|
||||||
|
'requires_php' => $remote['requires_php'] ?? '',
|
||||||
|
'sections' => array(
|
||||||
|
'description' => $remote['description'] ?? $this->plugin_data['Description'] ?? '',
|
||||||
|
'changelog' => $remote['changelog'] ?? '',
|
||||||
|
),
|
||||||
|
'download_link' => $remote['download_url'] ?? '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get remote data with caching and HMAC signature verification.
|
||||||
|
*
|
||||||
|
* @return array Remote data.
|
||||||
|
*/
|
||||||
|
private function get_remote_data(): array {
|
||||||
|
$cached = get_site_transient( $this->cache_key );
|
||||||
|
|
||||||
|
// Verify HMAC signature if AUTH_SALT is defined and cache has signature.
|
||||||
|
if ( false !== $cached && defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
|
||||||
|
if ( is_array( $cached ) && isset( $cached['signature'], $cached['data'] ) ) {
|
||||||
|
$expected_sig = hash_hmac( 'sha256', $this->cache_key . serialize( $cached['data'] ), AUTH_SALT ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Used for HMAC signing, not for unserializing untrusted data.
|
||||||
|
|
||||||
|
if ( hash_equals( $expected_sig, $cached['signature'] ) ) {
|
||||||
|
// Signature valid, return data.
|
||||||
|
return is_array( $cached['data'] ) ? $cached['data'] : array();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Signature invalid, delete corrupted cache.
|
||||||
|
delete_site_transient( $this->cache_key );
|
||||||
|
$cached = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no valid cache, fetch fresh data.
|
||||||
|
if ( false === $cached ) {
|
||||||
|
$remote = $this->fetch_json();
|
||||||
|
|
||||||
|
// Store with HMAC signature if AUTH_SALT is available.
|
||||||
|
if ( defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
|
||||||
|
$remote_data = is_array( $remote ) ? $remote : array();
|
||||||
|
$payload = array(
|
||||||
|
'data' => $remote_data,
|
||||||
|
'timestamp' => time(),
|
||||||
|
'signature' => hash_hmac( 'sha256', $this->cache_key . serialize( $remote_data ), AUTH_SALT ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Used for HMAC signing, not for unserializing untrusted data.
|
||||||
|
);
|
||||||
|
set_site_transient( $this->cache_key, $payload, 6 * HOUR_IN_SECONDS );
|
||||||
|
} else {
|
||||||
|
// Fallback to standard caching.
|
||||||
|
set_site_transient( $this->cache_key, is_array( $remote ) ? $remote : array(), 6 * HOUR_IN_SECONDS );
|
||||||
|
}
|
||||||
|
|
||||||
|
return is_array( $remote ) ? $remote : array();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Legacy cache format without signature (backward compatibility).
|
||||||
|
return is_array( $cached ) ? $cached : array();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch JSON from remote URL.
|
||||||
|
*
|
||||||
|
* @return array Decoded JSON data.
|
||||||
|
*/
|
||||||
|
private function fetch_json(): array {
|
||||||
|
$response = wp_remote_get(
|
||||||
|
$this->json_url,
|
||||||
|
array(
|
||||||
|
'timeout' => 10,
|
||||||
|
'headers' => array(
|
||||||
|
'Accept' => 'application/json',
|
||||||
|
),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
if ( is_wp_error( $response ) ) {
|
||||||
|
return array();
|
||||||
|
}
|
||||||
|
|
||||||
|
$code = (int) wp_remote_retrieve_response_code( $response );
|
||||||
|
if ( $code < 200 || $code >= 300 ) {
|
||||||
|
return array();
|
||||||
|
}
|
||||||
|
|
||||||
|
$body = wp_remote_retrieve_body( $response );
|
||||||
|
$data = json_decode( $body, true );
|
||||||
|
|
||||||
|
return is_array( $data ) ? $data : array();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check compatibility.
|
||||||
|
*
|
||||||
|
* @param array $remote Remote data.
|
||||||
|
*
|
||||||
|
* @return bool True if compatible.
|
||||||
|
*/
|
||||||
|
private function is_compatible( array $remote ): bool {
|
||||||
|
if ( ! empty( $remote['requires_php'] ) ) {
|
||||||
|
if ( version_compare( PHP_VERSION, $remote['requires_php'], '<' ) ) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( ! empty( $remote['requires'] ) ) {
|
||||||
|
if ( version_compare( get_bloginfo( 'version' ), $remote['requires'], '<' ) ) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle manual cache clear via URL parameter.
|
||||||
|
*/
|
||||||
|
public function handle_cache_clear(): void {
|
||||||
|
// Check if this is a cache clear request first.
|
||||||
|
$clear_cache = filter_input( INPUT_GET, 'robotstxt_clear_update_cache', FILTER_UNSAFE_RAW );
|
||||||
|
if ( null === $clear_cache ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is a cache clear request - now verify nonce.
|
||||||
|
$nonce_raw = filter_input( INPUT_GET, '_wpnonce', FILTER_UNSAFE_RAW );
|
||||||
|
$nonce = $nonce_raw ? sanitize_text_field( wp_unslash( $nonce_raw ) ) : '';
|
||||||
|
|
||||||
|
if ( ! wp_verify_nonce( $nonce, 'robotstxt_clear_update_cache' ) ) {
|
||||||
|
wp_die( esc_html__( 'Security check failed', 'robotstxt-2fa' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check permissions.
|
||||||
|
if ( ! current_user_can( 'update_plugins' ) ) {
|
||||||
|
wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'robotstxt-2fa' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->clear_cache();
|
||||||
|
wp_safe_redirect( remove_query_arg( array( 'robotstxt_clear_update_cache', '_wpnonce' ) ) );
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear update cache.
|
||||||
|
*/
|
||||||
|
public function clear_cache(): void {
|
||||||
|
delete_site_transient( $this->cache_key );
|
||||||
|
delete_site_transient( 'update_plugins' );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue