Compare commits

...
Author SHA1 Message Date
b5d03b7f81 v1.6.11 2026-11-04 18:43:02 +00:00
b81db2d302 v1.6.10 2026-11-04 14:38:18 +00:00
7379505d20 v1.6.9 2026-11-04 14:37:18 +00:00
1ff471299e v1.6.8 2026-11-04 14:36:03 +00:00
c3f0eac50c v1.6.7 2026-09-18 04:36:07 +00:00
f9c073a582 v1.6.6 2026-09-17 10:58:22 +00:00
c72a96e2a0 v1.6.5 2026-09-17 10:57:29 +00:00
e568b54336 v1.6.4 2026-09-11 10:29:29 +00:00
511d2fefae v1.6.3 2026-08-24 08:18:14 +00:00
3e4433cd13 v1.6.2 2026-08-17 15:55:46 +00:00
43 changed files with 3343 additions and 630 deletions

View file

@ -1,5 +1,231 @@
== Changelog ==
= 1.6.11 =
_Release date: 2026-11-04_
**Fixed**
* The 2FA verification screen is no longer hijacked on membership sites that redirect the WordPress login away from wp-login.php (confirmed live on Restrict Content Pro 4.0.9 with "Hijack Login URL" enabled and the login at a custom account page such as /mi-cuenta/). RCP implements the hijack twice: through the login_url filter (already handled since 1.6.4) and — new finding — through a `login_form_login` redirect that bounces every default-action wp-login.php request to the membership page, dropping the 2FA query arguments. Stage requests now carry a dedicated `action=robotstxt-2fa-verify` (declared to WordPress via a registered `login_form_` hook, preserved on submission through a hidden field), so they run core's login branch without firing `login_form_login`, out of reach of that redirect pattern in any plugin. Verified end to end on the reported replica: password at the membership page → verification screen renders → valid code → user lands back on the membership page, logged in.
* Users logging in from front-end forms (membership/account pages) now return to the page they logged in from after completing 2FA instead of landing in wp-admin: when the request carries no core `redirect_to`, the challenge falls back to the raw HTTP referer, validated to be same-host and not an admin or login URL (foreign and admin referers are ignored).
**Compatibility**
* WordPress: 7.0 - 7.2
* PHP: 8.3 - 8.6
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level max (10), no baseline — 0 errors
* PHPCompatibility: 8.3-8.6 — 0 issues
* PHPUnit: 9.6.38 — 125 tests, 236 assertions (PHP 8.6.0RC3 and 8.3.36)
* Live end-to-end on the reported site replica (WordPress 7.1.4 + Restrict Content Pro 4.0.9): full login → 2FA → return-to-page cycle, MariaDB 11.8.9
= 1.6.10 =
_Release date: 2026-11-03_
**Fixed**
* The 2FA verification stage now stays on the login URL the visitor actually used. When wp-login.php executes through an alias or renamed slug (a `/login` rewrite, a "hidden login" setup that does not filter `site_url`), the post-password redirect previously always targeted the literal `/wp-login.php` — on sites where that URL is blocked or renamed away at server level, users were stranded on a 403/404 page right after a correct password. The stage base URL now preserves the executing login surface (path only; host and scheme still come from the site's canonical URL; traversal sequences rejected), while logins submitted from custom pages calling `wp_signon()` keep landing on the real wp-login.php as before (the 1.6.4 Restrict Content Pro guarantee). Full root-cause analysis in `docs/report-login-surface-urls.md`.
**Compatibility**
* WordPress: 7.0 - 7.2
* PHP: 8.3 - 8.6
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level max (10), no baseline — 0 errors
* PHPCompatibility: 8.3-8.6 — 0 issues
* PHPUnit: 9.6.38 — 119 tests, 229 assertions (PHP 8.6.0RC3 and 8.3.36)
* Live surface probes: WordPress 7.2-beta4 (single site) and WordPress 7.0 (multisite) on PHP 8.6.0RC3, MariaDB 11.8.9
= 1.6.9 =
_Release date: 2026-11-03_
**Changed**
* Compatibility floors raised: minimum WordPress moved from 5.6 to 7.0 and minimum PHP from 8.0 to 8.3, matching the support policy (latest stable WordPress plus the two previous majors). The full-range compatibility review (WordPress 4.7-7.2 walked down with wp-compat; PHP 5.6-8.6 scanned with PHPCompatibility) confirmed the plugin uses no WordPress symbols newer than 6.0 and no PHP syntax newer than 8.0, so the real code floors are lower — the declared floors are the supported ones. WordPress 7.2 (beta 4, single-site) and WordPress 7.0 (multisite) were live-tested; PHP 8.6 (RC 3) was live-tested and PHP 8.3-8.6 scanned clean.
* The admin menu icon is now a brand SVG (shield with keyhole, base64 data URI) instead of `dashicons-shield`, on both single-site and network admin menus. WordPress core natively renders base64 SVG menu icons (centered at 20px), so the icon works identically on WordPress 7.0, 7.1 and 7.2, stays crisp on high-density screens, and is future-proof against the admin-wide move from Dashicons to SVG icons tracked in WordPress core (PR #12270 / Trac ticket #65089). Dashicons continue to work everywhere else.
* Composer tooling updated: wp-compat 3.0.1, PHPStan 2.3.5, wordpress-stubs 7.1.2, PHPUnit 9.6.38, maxmind-db/reader 1.14.0; `composer audit` reports no known vulnerabilities.
**Fixed**
* PHP 8.6 deprecation removed: the REST controller declared a class constant named `namespace` (case-insensitively), which PHP 8.6 deprecates and PHP 9 will reject as a fatal error. Renamed to `REST_NAMESPACE` with no functional change (the constant was private).
* Static-analysis hardening to pass PHPStan at the new maximum level (10) without a baseline: `$wpdb`, `$wp_filter` and `$post` globals are now properly typed; the uninstall routine deletes user meta through the `$wpdb->delete()` WordPress API instead of hand-built SQL; role names from `get_editable_roles()` are validated before translation; `AUTH_SALT` and `COOKIEPATH` are validated as strings before use in the trusted-device cookie; the trusted-device map discards corrupted non-string keys; `get_users()` results are instance-checked before use; a misplaced translators comment on an `_n()` call was fixed (WPCS error).
**Compatibility**
* WordPress: 7.0 - 7.2
* PHP: 8.3 - 8.6
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors, 1 accepted advisory warning (urlencode mirrors WordPress core's wp_login_url())
* PHPStan: 2.3.5 level max (10), no baseline — 0 errors
* PHPCompatibility: 9.3.5, testVersion 8.3-8.6 — 0 issues
* PHPUnit: 9.6.38 — 110 tests, 220 assertions (PHP 8.6.0RC3 and PHP 8.3.36)
* Live smoke tests: WordPress 7.2-beta4 (single site) and WordPress 7.0 (multisite) on PHP 8.6.0RC3, MariaDB 11.8.9
= 1.6.8 =
_Release date: 2026-09-21_
**Added**
* Administrator visibility when email delivery fails: failed verification-code deliveries record a marker and administrators see a persistent, self-clearing notice ("2FA: email delivery is failing…") in wp-admin and the network admin, since forced-email users cannot sign in while delivery is broken. The notice disappears automatically once a code is delivered successfully.
**Fixed**
* "We could not determine which account you are trying to access" during verification: the pending-stage token was stored in a transient, which external object caches (Redis/Memcached) can evict at any time, killing live verification sessions. Tokens now live in a persistent option map (capped, pruned, consumed on success, cleaned on uninstall) and the error message now says the session expired and asks the user to sign in again.
**Compatibility**
* WordPress: 5.6 – 7.1
* PHP: 8.0 – 8.5
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level 9 — 0 errors
* PHPCompatibility: 8.0–8.5 — 0 issues
* PHPUnit: 9.6.36 — 110 tests, 220 assertions
= 1.6.7 =
_Release date: 2026-09-17_
**Fixed**
* The forced-setup wizard felt like a broken redirect loop: the wizard redirect bounced users to the profile with no explanation (it now carries a flag that renders a clear "activate at least one verification method, then save" warning), and saving with an expired form nonce silently did nothing (it now raises a visible "form session expired" error so users know to try again).
**Compatibility**
* WordPress: 5.6 – 7.1
* PHP: 8.0 – 8.5
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level 9 — 0 errors
* PHPCompatibility: 8.0–8.5 — 0 issues
* PHPUnit: 9.6.36 — 98 tests, 197 assertions
= 1.6.6 =
_Release date: 2026-09-17_
**Added**
* Forced-enrollment warning on the profile 2FA section: when a user's role enforces 2FA but they have no verification method configured yet, the 2FA section of their profile (wp-admin and the frontend shortcode) opens with a warning notice asking them to activate at least one method. While a grace period is active, the notice appends the remaining days.
**Compatibility**
* WordPress: 5.6 – 7.1
* PHP: 8.0 – 8.5
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level 9 — 0 errors
* PHPCompatibility: 8.0–8.5 — 0 issues
* PHPUnit: 9.6.36 — 93 tests, 189 assertions
= 1.6.5 =
_Release date: 2026-09-17_
**Fixed**
* Fatal error on the login screen with newer WordPress versions: the `login_message` filter can deliver null when no message is set (observed on WordPress 7.x with PHP 8.4, TypeError on a plain visit to wp-login.php). The message callback now accepts `string|null` and coalesces null to an empty string.
* Hardened all externally-fed filter callbacks against null payloads: the four `authenticate` callbacks now accept `string|null` credentials (custom REST/SSO endpoints are known to apply the filter with null), and the `wp_redirect` filter callback coalesces a null location. Verified safe as-is: shortcode callback, Settings API sanitizer, activation hooks, and admin-hook parameters.
**Compatibility**
* WordPress: 5.6 – 7.1
* PHP: 8.0 – 8.5
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level 9 — 0 errors
* PHPCompatibility: 8.0–8.5 — 0 issues
* PHPUnit: 9.6.36 — 87 tests, 180 assertions
= 1.6.4 =
_Release date: 2026-09-11_
**Fixed**
* Compatibility with Restrict Content Pro's "Hijack Login URL" option: RCP's `login_url` filter made every `wp_login_url()` call return a membership page, so the 2FA verification redirect landed on a restricted page where the verification form cannot render, and the visitor was bounced to the registration page. Verification-stage URLs are now built from the canonical `wp-login.php`, mirroring WordPress core's URL construction before the filterable output. The "Back to login" link keeps the site-configured login URL.
**Compatibility**
* WordPress: 5.6 – 7.1
* PHP: 8.0 – 8.5
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level 9 — 0 errors
* PHPCompatibility: 8.0–8.5 — 0 issues
* PHPUnit: 9.6.36 — 78 tests, 171 assertions
= 1.6.3 =
_Release date: 2026-08-24_
**Changed**
* Manager detection now uses the ecosystem presence constant (`ROBOTSTXT_MANAGER_NOTICED`, defined by Manager 1.6.2+) with a fallback to the plugin-list scan for older Manager versions, so a stale plugin list can no longer produce false "Manager missing" notices.
**Fixed**
* Compatibility with the ALTCHA Spam Protection plugin: when "Protect login" was enabled, submitting the 2FA verification code failed with "[ALTCHA] Sorry, your request could not be processed.". The ALTCHA interceptor is now disabled while the verification screen is shown; the first login step keeps its ALTCHA check.
**Compatibility**
* WordPress: 5.6 – 7.1
* PHP: 8.0 – 8.5
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level 9 — 0 errors
* PHPCompatibility: 8.0–8.5 — 0 issues
* PHPUnit: 9.6.36 — 73 tests, 163 assertions
= 1.6.2 =
_Release date: 2026-08-17_
**Added**
* Recommendation notice for the Manager (by ROBOTSTXT) plugin: when it is not installed and active, a dismissible notice appears on the Plugins screen and a permanent notice is shown on the plugin settings page, since updates are delivered through the Manager plugin.
**Changed**
* Updates are now handled by the Manager (by ROBOTSTXT) plugin. The bundled self-updater (robotstxt-updater.php and update.json) has been removed.
* Plugin and update URLs moved to robotstxt.software.
* Minimum WordPress version lowered from 6.4 to 5.6 after a full compatibility review (the code only requires WordPress 5.3+ functions, and WordPress 5.6 is the first release that runs on the required PHP 8.0).
**Compatibility**
* WordPress: 5.6 – 7.1
* PHP: 8.0 – 8.5
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level 9 — 0 errors
* PHPCompatibility: 8.0–8.5 — 0 issues
* PHPUnit: 9.6.36 — 59 tests, 148 assertions
= 1.6.1 =
_Release date: 2026-08-14_

View file

@ -24,6 +24,18 @@ class Dashboard_Page {
*/
public const PAGE_SLUG = 'robotstxt-2fa-dashboard';
/**
* Brand SVG menu icon (shield with keyhole) as a base64 data URI.
*
* WordPress core renders base64-encoded SVG data URIs natively in admin
* menus (centered at 20px via the .wp-menu-image.svg CSS class), which
* keeps the icon crisp and independent of the Dashicons font while
* remaining fully backward compatible.
*
* @since 1.6.9
*/
public const MENU_ICON = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMCIgaGVpZ2h0PSIyMCIgdmlld0JveD0iMCAwIDIwIDIwIiByb2xlPSJpbWciIGFyaWEtaGlkZGVuPSJ0cnVlIiBmb2N1c2FibGU9ImZhbHNlIj48cGF0aCBmaWxsPSIjMDM4N2M5IiBkPSJNMTAgMSAxOCAzLjl2NS4zYzAgNS40LTMuMyA4LjYtOCA5LjgtNC43LTEuMi04LTQuNC04LTkuOFYzLjlaIi8+PGNpcmNsZSBjeD0iMTAiIGN5PSI4IiByPSIyLjIiIGZpbGw9IiNmZmVmZDQiLz48cGF0aCBmaWxsPSIjZmZlZmQ0IiBkPSJNOC44IDkuOSA3LjYgMTMuN2g0LjhMMTEuMiA5LjlaIi8+PC9zdmc+';
/**
* Failed attempts log.
*
@ -108,7 +120,7 @@ class Dashboard_Page {
'manage_options',
self::PAGE_SLUG,
array( $this, 'render_page' ),
'dashicons-shield'
self::MENU_ICON
);
add_submenu_page(

View file

@ -0,0 +1,198 @@
<?php
/**
* Manager plugin dependency notice.
*
* @package Robotstxt_2FA
*/
namespace Robotstxt\TwoFA\Admin;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Notifies administrators when the Manager (by ROBOTSTXT) plugin is missing.
*
* The Manager plugin delivers updates for ROBOTSTXT plugins. Without it, this
* plugin cannot receive updates. A dismissible notice is shown on the plugins
* list screen and a persistent notice is rendered on the plugin settings page.
*/
class Manager_Notice {
/**
* URL of the Manager plugin page.
*/
private const MANAGER_URL = 'https://www.robotstxt.software/plugins/robotstxt-manager/';
/**
* Action used to dismiss the plugins screen notice.
*/
private const DISMISS_ACTION = 'robotstxt_2fa_dismiss_manager_notice';
/**
* User meta key storing the dismissal flag.
*/
private const DISMISSED_META_KEY = 'robotstxt_2fa_manager_notice_dismissed';
/**
* Register WordPress hooks.
*
* @since 1.6.2
*
* @return void
*/
public function register_hooks(): void {
add_action( 'admin_notices', array( $this, 'maybe_show_plugins_notice' ) );
add_action( 'network_admin_notices', array( $this, 'maybe_show_plugins_notice' ) );
add_action( 'admin_init', array( $this, 'maybe_handle_dismiss' ) );
}
/**
* Whether the Manager (by ROBOTSTXT) plugin is active.
*
* Uses the ecosystem presence constant (Manager 1.6.2+) and falls back
* to a plugin-list scan for older Manager versions.
*
* @since 1.6.2
*
* @return bool True when the Manager plugin is present and activated.
*/
public static function is_manager_active(): bool {
if ( defined( 'ROBOTSTXT_MANAGER_NOTICED' ) && ROBOTSTXT_MANAGER_NOTICED ) {
return true;
}
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
foreach ( get_plugins() as $file => $data ) {
$slug = dirname( $file );
if ( '.' === $slug ) {
$slug = basename( $file, '.php' );
}
if ( 'robotstxt-manager' === $slug ) {
return is_plugin_active( $file );
}
}
return false;
}
/**
* Show a dismissible notice on the plugins list screen when the manager is missing.
*
* @since 1.6.2
*
* @return void
*/
public function maybe_show_plugins_notice(): void {
$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
if ( null === $screen ) {
return;
}
if ( ! in_array( $screen->id, array( 'plugins', 'plugins-network' ), true ) ) {
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
if ( self::is_manager_active() ) {
return;
}
if ( get_user_meta( get_current_user_id(), self::DISMISSED_META_KEY, true ) ) {
return;
}
$dismiss_url = wp_nonce_url(
add_query_arg( 'action', self::DISMISS_ACTION, self_admin_url( 'admin.php' ) ),
self::DISMISS_ACTION
);
?>
<div class="notice notice-warning">
<p>
<strong><?php esc_html_e( '2FA (by ROBOTSTXT):', 'robotstxt-2fa' ); ?></strong>
<?php
echo wp_kses_post(
sprintf(
/* translators: %s: URL of the Manager (by ROBOTSTXT) plugin page. */
__( 'This plugin needs <a href="%s">Manager (by ROBOTSTXT)</a> to be installed and active to receive updates.', 'robotstxt-2fa' ),
esc_url( self::MANAGER_URL )
)
);
?>
</p>
<p style="margin-top:0;">
<a href="<?php echo esc_url( $dismiss_url ); ?>" style="font-size:0.875em;"><?php esc_html_e( 'Dismiss this notice', 'robotstxt-2fa' ); ?></a>
</p>
</div>
<?php
}
/**
* Render the persistent manager notice shown on the plugin settings page.
*
* @since 1.6.2
*
* @return void
*/
public static function render_settings_notice(): void {
if ( self::is_manager_active() ) {
return;
}
?>
<div class="notice notice-warning inline">
<p>
<strong><?php esc_html_e( 'Manager (by ROBOTSTXT) is not active.', 'robotstxt-2fa' ); ?></strong>
<?php
echo wp_kses_post(
sprintf(
/* translators: %s: URL of the Manager (by ROBOTSTXT) plugin page. */
__( 'This plugin needs <a href="%s">Manager (by ROBOTSTXT)</a> to be installed and active to receive updates.', 'robotstxt-2fa' ),
esc_url( self::MANAGER_URL )
)
);
?>
</p>
</div>
<?php
}
/**
* Handle the dismiss-notice GET request.
*
* @since 1.6.2
*
* @return void
*/
public function maybe_handle_dismiss(): void {
if ( ! isset( $_GET['action'] ) || self::DISMISS_ACTION !== $_GET['action'] ) {
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$nonce_raw = isset( $_GET['_wpnonce'] ) && is_string( $_GET['_wpnonce'] )
? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) )
: '';
if ( ! wp_verify_nonce( $nonce_raw, self::DISMISS_ACTION ) ) {
return;
}
update_user_meta( get_current_user_id(), self::DISMISSED_META_KEY, 1 );
wp_safe_redirect( remove_query_arg( array( 'action', '_wpnonce' ) ) );
exit;
}
}

View file

@ -538,6 +538,11 @@ class Migration_Page {
* @return array<int, array{user: \WP_User, source: string}>
*/
private function get_candidates_from_wordfence(): array {
/**
* WordPress database abstraction. Typed for PHPStan level max.
*
* @var \wpdb $wpdb
*/
global $wpdb;
$table = $wpdb->prefix . self::WORDFENCE_TABLE;
@ -550,21 +555,17 @@ class Migration_Page {
return array();
}
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names are trusted constants.
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a trusted prefix constant; the user ID is a validated integer.
$rows = $wpdb->get_results(
"SELECT s.user_id, s.secret FROM `{$table}` s",
ARRAY_A
);
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
if ( ! is_array( $rows ) ) {
return array();
}
$candidates = array();
foreach ( $rows as $row ) {
if ( ! is_array( $row ) || ! isset( $row['user_id'] ) || ! is_numeric( $row['user_id'] ) ) {
if ( ! isset( $row['user_id'] ) || ! is_numeric( $row['user_id'] ) ) {
continue;
}
@ -716,14 +717,19 @@ class Migration_Page {
* @return string
*/
private function read_wordfence_secret( int $user_id ): string {
/**
* WordPress database abstraction. Typed for PHPStan level max.
*
* @var \wpdb $wpdb
*/
global $wpdb;
$table = $wpdb->prefix . self::WORDFENCE_TABLE;
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a trusted constant.
$secret_binary = $wpdb->get_var( $wpdb->prepare( "SELECT `secret` FROM `{$table}` WHERE `user_id` = %d LIMIT 1", $user_id ) );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a trusted prefix constant; the user ID is a validated integer.
$secret_binary = $wpdb->get_var( "SELECT `secret` FROM `{$table}` WHERE `user_id` = {$user_id} LIMIT 1" );
if ( ! is_string( $secret_binary ) || '' === $secret_binary ) {
if ( ! is_string( $secret_binary ) ) {
return '';
}

View file

@ -101,6 +101,8 @@ class Settings_Page {
settings_errors( self::OPTION_NAME );
Manager_Notice::render_settings_notice();
$form_action = $this->is_network_context()
? network_admin_url( 'edit.php?action=robotstxt_2fa_network_save' )
: 'options.php';
@ -429,8 +431,13 @@ class Settings_Page {
</thead>
<tbody>
<?php foreach ( $roles as $role_key => $role_details ) : ?>
<?php
$role_name = isset( $role_details['name'] ) && is_string( $role_details['name'] )
? $role_details['name']
: $role_key;
?>
<tr data-2fa-role="<?php echo esc_attr( $role_key ); ?>">
<td><?php echo esc_html( translate_user_role( $role_details['name'] ) ); ?></td>
<td><?php echo esc_html( translate_user_role( $role_name ) ); ?></td>
<?php foreach ( $methods as $method_key => $method_label ) : ?>
<td style="text-align:center;">
<label>
@ -439,7 +446,7 @@ class Settings_Page {
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( translate_user_role( $role_name ) ),
esc_html( $method_label )
);
?>
@ -800,7 +807,7 @@ class Settings_Page {
/**
* Resolve role_methods from stored options, migrating legacy force_roles + default_method if needed.
*
* @param array<string, mixed> $options Raw stored options.
* @param array<mixed> $options Raw stored options (untyped values from the options table).
*
* @return array<string, array<int, string>>
*/
@ -1143,7 +1150,7 @@ class Settings_Page {
$capability,
self::PAGE_SLUG,
array( $this, 'render_page' ),
'dashicons-shield'
Dashboard_Page::MENU_ICON
);
// Rename the first auto-created submenu entry to "Settings".

View file

@ -338,9 +338,14 @@ class Users_List_Table extends \WP_List_Table {
<div class="alignleft actions">
<select name="role_filter">
<option value=""><?php esc_html_e( '— All roles —', 'robotstxt-2fa' ); ?></option>
<?php foreach ( $roles as $role_key => $role_info ) : ?>
<?php
foreach ( $roles as $role_key => $role_info ) :
$role_name = isset( $role_info['name'] ) && is_string( $role_info['name'] )
? $role_info['name']
: $role_key;
?>
<option value="<?php echo esc_attr( $role_key ); ?>" <?php selected( $current_role, $role_key ); ?>>
<?php echo esc_html( translate_user_role( $role_info['name'] ) ); ?>
<?php echo esc_html( translate_user_role( $role_name ) ); ?>
</option>
<?php endforeach; ?>
</select>

View file

@ -7,6 +7,7 @@
namespace Robotstxt\TwoFA;
use Robotstxt\TwoFA\Login\Email_Code_Sender;
use Robotstxt\TwoFA\User\Two_Factor_Config;
if ( ! defined( 'ABSPATH' ) ) {
@ -61,6 +62,42 @@ class Email_Notifications {
add_action( self::DIGEST_CRON_HOOK, array( $this, 'send_digest' ) );
add_filter( 'cron_schedules', array( $this, 'add_cron_schedules' ) );
add_action( 'init', array( $this, 'maybe_schedule_digest' ) );
add_action( 'admin_notices', array( $this, 'render_delivery_failure_notice' ) );
add_action( 'network_admin_notices', array( $this, 'render_delivery_failure_notice' ) );
}
/**
* Warn administrators while verification-code delivery is failing.
*
* When a role forces email verification and wp_mail() fails, users are
* locked out at the login challenge with an error that points them at
* their administrator — while the real fault is the site's mail
* configuration. The failure marker is written by
* {@see Email_Code_Sender} on failed delivery and removed automatically
* once a code is delivered successfully.
*
* @since 1.6.8
*
* @return void
*/
public function render_delivery_failure_notice(): void {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$failure = get_option( Email_Code_Sender::MAIL_FAILURE_OPTION, array() );
if ( ! is_array( $failure ) || empty( $failure['at'] ) ) {
return;
}
?>
<div class="notice notice-error robotstxt-2fa-mail-failure">
<p>
<strong><?php esc_html_e( '2FA (by ROBOTSTXT): email delivery is failing.', 'robotstxt-2fa' ); ?></strong>
<?php esc_html_e( 'Verification code emails cannot be sent, so users required to sign in with an email code cannot access the site. Check the site mail or SMTP configuration — this notice disappears automatically once a code is delivered successfully.', 'robotstxt-2fa' ); ?>
</p>
</div>
<?php
}
/**
@ -368,6 +405,10 @@ Failed 2FA attempts (last 7 days): %4$d
$admins = get_users( array( 'capability' => 'manage_options' ) );
foreach ( $admins as $admin ) {
if ( ! $admin instanceof \WP_User ) {
continue;
}
$this->send_mail( $admin->user_email, $subject, $message );
}
}

View file

@ -85,13 +85,13 @@ class Geo_Restrictions {
*
* @since 1.5.0
*
* @param mixed $user Previously authenticated user or null.
* @param string $username Submitted username.
* @param string $password Submitted password.
* @param mixed $user Previously authenticated user or null.
* @param string|null $username Submitted username.
* @param string|null $password Submitted password.
*
* @return mixed
*/
public function maybe_block_denied_country( mixed $user, string $username, string $password ): mixed {
public function maybe_block_denied_country( mixed $user, ?string $username, ?string $password ): mixed {
unset( $username, $password );
$deny_list = $this->config->get_geoip_country_deny();

View file

@ -82,13 +82,13 @@ class IP_Restrictions {
*
* @since 1.3.0
*
* @param mixed $user Previously authenticated user or error.
* @param string $username Submitted username.
* @param string $password Submitted password.
* @param mixed $user Previously authenticated user or error.
* @param string|null $username Submitted username.
* @param string|null $password Submitted password.
*
* @return mixed
*/
public function maybe_block_denied_ip( mixed $user, string $username, string $password ): mixed {
public function maybe_block_denied_ip( mixed $user, ?string $username, ?string $password ): mixed {
unset( $username, $password );
$deny_list = $this->config->get_ip_deny();

View file

@ -8,6 +8,7 @@
namespace Robotstxt\TwoFA;
use Robotstxt\TwoFA\Admin\Dashboard_Page;
use Robotstxt\TwoFA\Admin\Manager_Notice;
use Robotstxt\TwoFA\Admin\Migration_Page;
use Robotstxt\TwoFA\Admin\Settings_Page;
use Robotstxt\TwoFA\Cli\Cli_Command;
@ -134,6 +135,13 @@ class Plugin {
*/
private Migration_Page $migration_page;
/**
* Manager plugin dependency notice.
*
* @var Manager_Notice
*/
private Manager_Notice $manager_notice;
/**
* REST API controller.
*
@ -174,6 +182,7 @@ class Plugin {
$this->geoip_updater = new GeoIP_Updater( $config );
$this->dashboard_page = new Dashboard_Page( $this->attempts_log, $config, $repository );
$this->migration_page = new Migration_Page();
$this->manager_notice = new Manager_Notice();
$this->rest_controller = new Rest_Controller();
}
@ -191,6 +200,7 @@ class Plugin {
$this->geoip_updater->register_hooks();
$this->dashboard_page->register_hooks();
$this->migration_page->register_hooks();
$this->manager_notice->register_hooks();
$this->rest_controller->register_hooks();
$this->login_manager->register_hooks();
$this->profile_settings->register_hooks();

View file

@ -17,6 +17,13 @@ if ( ! defined( 'ABSPATH' ) ) {
* Handles generation and delivery of email-based verification codes.
*/
class Email_Code_Sender {
/**
* Option key recording the last failed delivery attempt. Kept while mail
* delivery fails so administrators can see why forced-email users cannot
* sign in; cleared automatically once a code is delivered successfully.
*/
public const MAIL_FAILURE_OPTION = 'robotstxt_2fa_last_mail_failure';
/**
* Default length of the generated numeric code.
*/
@ -187,14 +194,57 @@ class Email_Code_Sender {
$headers = array( 'Content-Type: text/plain; charset=UTF-8' );
if ( ! wp_mail( $user->user_email, $email_subject, $message, $headers ) ) {
$this->record_mail_failure( $user->user_email );
return false;
}
$this->clear_mail_failure();
$this->user_settings_repository->store_email_challenge( $user->ID, $code, $expires );
return true;
}
/**
* Record a failed verification-code delivery for administrator visibility.
*
* When a role forces email verification, a failing wp_mail() locks users
* out of their accounts with no site-side signal. Store the failure so an
* admin notice can explain the root cause.
*
* @since 1.6.8
*
* @param string $to Intended recipient.
*
* @return void
*/
private function record_mail_failure( string $to ): void {
$existing = get_option( self::MAIL_FAILURE_OPTION, array() );
$record = is_array( $existing ) ? $existing : array();
update_option(
self::MAIL_FAILURE_OPTION,
array(
'at' => time(),
'to' => $to,
'count' => ( isset( $record['count'] ) && is_numeric( $record['count'] ) ? (int) $record['count'] : 0 ) + 1,
),
false
);
}
/**
* Clear the delivery failure marker after a successful delivery.
*
* @since 1.6.8
*
* @return void
*/
private function clear_mail_failure(): void {
delete_option( self::MAIL_FAILURE_OPTION );
}
/**
* Verify a submitted code against the stored challenge.
*

View file

@ -85,9 +85,21 @@ class Login_Form_Manager {
private const FIELD_METHOD = 'robotstxt_2fa_method';
/**
* Transient key prefix for pending-stage tokens.
* Option key storing the pending-stage token map.
*
* Maps token => array( user ID, expiry ). Persistent storage instead of a
* transient: external object caches can evict transients at any time,
* which would kill live verification stages and lock users out with
* "We could not determine which account you are trying to access."
*/
private const PENDING_TRANSIENT_PREFIX = 'robotstxt_2fa_stage_';
private const PENDING_OPTION = 'robotstxt_2fa_pending_stages';
/**
* Maximum concurrent pending-stage tokens kept in the map.
*
* The map is pruned on every write; the cap bounds its size.
*/
private const PENDING_MAX_TOKENS = 20;
/**
* Pending-stage token TTL in seconds — matches WP nonce lifetime (24 h).
@ -99,6 +111,26 @@ class Login_Form_Manager {
*/
private const FIELD_STAGE_TOKEN = 'robotstxt_2fa_stage_token';
/**
* Core login action used for verification-stage requests.
*
* The wp-login.php script validates the `action` parameter against its
* known actions plus any with a registered `login_form_{action}` hook,
* and resets unknown ones to `login`. Membership plugins (Restrict
* Content Pro's "Hijack Login URL", and others with the same pattern) hook
* `login_form_login` to bounce the default login action to their own
* page — which would prevent the verification screen from ever rendering.
* A dedicated action keeps stage requests out of that hook while still
* running core's default login branch (form rendering + credential
* processing).
*/
private const STAGE_ACTION = 'robotstxt-2fa-verify';
/**
* Query parameter carrying the core login action.
*/
private const QUERY_ACTION = 'action';
/**
* Identifier for the verification stage.
*/
@ -233,6 +265,164 @@ class Login_Form_Manager {
add_filter( 'login_message', array( $this, 'filter_login_message' ) );
add_filter( 'authenticate', array( $this, 'maybe_complete_verification' ), 5, 3 );
add_filter( 'authenticate', array( $this, 'enforce_verification_challenge' ), 30, 3 );
add_action( 'init', array( $this, 'maybe_remove_altcha_interceptor' ), 0 );
add_action( 'login_form_' . self::STAGE_ACTION, array( $this, 'stage_action_noop' ) );
}
/**
* No-op callback for the dedicated verification-stage login action.
*
* Core only accepts non-default `action` values that have a
* `login_form_{action}` hook registered; registering this callback
* declares the stage action so stage requests are not reset to the
* default `login` action — and therefore are not hijacked by
* third-party `login_form_login` redirects (membership plugins that
* move the login form to their own page).
*
* @since 1.6.11
*
* @return void
*/
public function stage_action_noop(): void {
// Intentionally empty; registration alone declares the action.
}
/**
* Retrieve the canonical wp-login.php URL used for 2FA stage navigation.
*
* Builds the URL from the real wp-login.php path instead of wp_login_url().
* The `login_url` filter applied by wp_login_url() can be hijacked by
* third-party plugins (for example Restrict Content Pro's "Hijack Login
* URL" option) to return a membership page, which would send the user to a
* page where the verification form cannot render: core only fires the
* login_init hook when wp-login.php itself loads. This mirrors the URL
* construction wp_login_url() performs before its filter runs.
*
* When wp-login.php executes through a different URL (a /login rewrite,
* a renamed "hidden login" slug), the stage keeps using that same URL so
* the verification screen stays reachable on sites that block the literal
* wp-login.php address. See get_stage_base_url().
*
* @since 1.6.4
* @since 1.6.10 Preserves the login surface currently in use when wp-login.php executes through an alias.
*
* @param string $redirect_to Optional redirect_to value to carry over.
*
* @return string Absolute login URL with optional redirect_to parameter.
*/
public static function get_canonical_login_url( string $redirect_to = '' ): string {
$url = self::get_stage_base_url();
if ( '' !== $redirect_to ) {
$url = add_query_arg( 'redirect_to', urlencode( $redirect_to ), $url );
}
return $url;
}
/**
* Return the base login URL the 2FA stage should navigate on.
*
* Priority order:
*
* 1. The URL the visitor actually used, when wp-login.php is the executing
* script but was reached through an alias or renamed slug (server
* rewrites such as /login, "hide login" plugins). Keeping the stage on
* the reachable surface avoids redirecting users to a blocked or
* rewritten-away wp-login.php URL after a correct password.
* 2. The canonical wp-login.php URL (site_url), which remains filterable
* by plugins that rewrite it, and which is always used when credentials
* were submitted from a custom page calling wp_signon() — the
* login_init hook does not fire there, and the verification form only
* renders on wp-login.php.
*
* The path from the current request is only trusted when wp-login.php is
* actually executing (login_init fired), traversal sequences are
* rejected, and only the path is reused — host and scheme always come
* from the site's own canonical URL.
*
* @since 1.6.10
*
* @return string Absolute login URL without any 2FA query arguments.
*/
private static function get_stage_base_url(): string {
$canonical = site_url( 'wp-login.php', 'login' );
if ( ! did_action( 'login_init' ) ) {
return $canonical;
}
$request_uri = isset( $_SERVER['REQUEST_URI'] ) && is_string( $_SERVER['REQUEST_URI'] )
? $_SERVER['REQUEST_URI']
: '';
$request_path = wp_parse_url( $request_uri, PHP_URL_PATH );
if ( ! is_string( $request_path ) ) {
return $canonical;
}
$request_path = rawurldecode( $request_path );
// Reject traversal attempts in both raw and percent-encoded form.
if ( str_contains( $request_path, '..' ) ) {
return $canonical;
}
$canonical_path = wp_parse_url( $canonical, PHP_URL_PATH );
if ( ! is_string( $canonical_path ) || '' === $canonical_path || $request_path === $canonical_path ) {
return $canonical;
}
return str_replace( $canonical_path, $request_path, $canonical );
}
/**
* Disable the ALTCHA Spam Protection login interceptor during the 2FA stage.
*
* ALTCHA's "Protect login" feature rejects any wp-login.php POST that does
* not carry a fresh proof-of-work payload (HTTP 403). Its JavaScript only
* produces that payload for classic username + password submissions, while
* the verification stage intentionally omits the password field, so every
* legitimate 2FA submission would otherwise be blocked. Human verification
* already happened on the first login step; this stage is protected by the
* pending-stage token, the stage nonce, and the failed-attempts lockout.
*
* @since 1.6.2
*
* @return void
*/
public function maybe_remove_altcha_interceptor(): void {
if ( ! $this->is_verification_stage() ) {
return;
}
if ( ! has_action( 'init', 'altcha_interceptor' ) ) {
return;
}
/**
* Registered filters and actions. Values are WP_Hook objects, but a
* corrupted container from third-party code is tolerated, hence mixed.
*
* @var array<string, mixed>|null $wp_filter
*/
global $wp_filter;
$init_hooks = $wp_filter['init'] ?? null;
if ( ! $init_hooks instanceof \WP_Hook ) {
return;
}
foreach ( array_keys( $init_hooks->callbacks ) as $priority ) {
if ( isset( $init_hooks->callbacks[ $priority ]['altcha_interceptor'] ) ) {
remove_action( 'init', 'altcha_interceptor', (int) $priority );
return;
}
}
}
/**
@ -270,6 +460,10 @@ class Login_Form_Manager {
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::FIELD_STAGE_TOKEN ), esc_attr( $stage_token ) );
}
// Keep the dedicated stage action on submission so third-party
// login_form_login redirects cannot bounce the verification POST.
printf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( self::QUERY_ACTION ), esc_attr( self::STAGE_ACTION ) );
wp_nonce_field( self::LOGIN_NONCE_ACTION, self::LOGIN_NONCE_FIELD );
?>
<p class="robotstxt-2fa-login-field robotstxt-2fa-stage-field">
@ -396,16 +590,21 @@ class Login_Form_Manager {
<?php
}
/**
* Display a contextual login message during the verification stage.
*
* @since 1.0.0
*
* @param string $message Existing login form message HTML.
*
* @return string
*/
public function filter_login_message( string $message ): string {
/**
* Display a contextual login message during the verification stage.
*
* @since 1.0.0
* @since 1.6.5 Accepts a null $message: newer WordPress versions pass
* null through the `login_message` filter when no message
* is set, which fatalled the string-typed parameter.
*
* @param string|null $message Existing login form message HTML.
*
* @return string
*/
public function filter_login_message( ?string $message ): string {
$message = $message ?? '';
if ( ! $this->is_verification_stage() ) {
return $message;
}
@ -552,12 +751,12 @@ class Login_Form_Manager {
* Attempt to finish the verification stage during authentication.
*
* @param \WP_User|\WP_Error|null $user Previously authenticated user or error.
* @param string $username Submitted username.
* @param string $password Submitted password.
* @param string|null $username Submitted username.
* @param string|null $password Submitted password.
*
* @return \WP_User|\WP_Error|null
*/
public function maybe_complete_verification( $user, string $username, string $password ) {
public function maybe_complete_verification( $user, ?string $username, ?string $password ) {
if ( ! $this->is_verification_submission() ) {
return $user;
}
@ -577,7 +776,7 @@ class Login_Form_Manager {
$authenticated_user = $this->resolve_pending_user();
if ( null === $authenticated_user ) {
return new \WP_Error( 'robotstxt_2fa_unknown_user', __( 'We could not determine which account you are trying to access.', 'robotstxt-2fa' ) );
return new \WP_Error( 'robotstxt_2fa_unknown_user', __( 'Your verification session expired or could not be found. Please sign in again.', 'robotstxt-2fa' ) );
}
// Brute-force: check if the account is currently locked out.
@ -681,7 +880,7 @@ class Login_Form_Manager {
// Consume the pending token so it cannot be replayed.
$pending_token = $this->get_requested_pending_token();
if ( '' !== $pending_token ) {
delete_transient( self::PENDING_TRANSIENT_PREFIX . $pending_token );
$this->consume_pending_token( $pending_token );
}
$this->user_settings_repository->record_last_verification(
@ -718,12 +917,12 @@ class Login_Form_Manager {
* Enforce the verification step for eligible users.
*
* @param \WP_User|\WP_Error|null $user Previously authenticated user or error.
* @param string $username Submitted username.
* @param string $password Submitted password.
* @param string|null $username Submitted username.
* @param string|null $password Submitted password.
*
* @return \WP_User|\WP_Error|null
*/
public function enforce_verification_challenge( $user, string $username, string $password ) {
public function enforce_verification_challenge( $user, ?string $username, ?string $password ) {
unset( $username, $password );
if ( $this->is_verification_stage() || $this->is_verification_submission() ) {
@ -817,13 +1016,14 @@ class Login_Form_Manager {
$stage_token = wp_create_nonce( self::STAGE_TOKEN_ACTION . '|' . $user->ID );
$query_args = array(
self::QUERY_STAGE => self::STAGE_VERIFY,
self::QUERY_METHOD => $method,
self::QUERY_PENDING => $this->issue_pending_token( $user->ID ),
self::QUERY_ACTION => self::STAGE_ACTION,
self::QUERY_STAGE => self::STAGE_VERIFY,
self::QUERY_METHOD => $method,
self::QUERY_PENDING => $this->issue_pending_token( $user->ID ),
self::QUERY_STAGE_TOKEN => $stage_token,
);
$login_url = wp_login_url( $redirect_to );
$login_url = self::get_canonical_login_url( $redirect_to );
$login_url = add_query_arg( $query_args, $login_url );
wp_safe_redirect( $login_url );
@ -1261,21 +1461,99 @@ class Login_Form_Manager {
/**
* Issue an opaque pending-stage token that maps to a user ID.
*
* Stores the user ID in a short-lived transient so the login username
* is never transmitted in the URL query string.
* Stores the token in a persistent option map (see PENDING_OPTION) so the
* login username is never transmitted in the URL query string and object
* cache eviction cannot kill a live stage.
*
* @since 1.3.0
* @since 1.6.8 Stored in a persistent option map instead of a transient.
*
* @param int $user_id User identifier.
*
* @return string 32-character alphanumeric token.
*/
private function issue_pending_token( int $user_id ): string {
$tokens = $this->get_pending_token_map();
$now = time();
foreach ( $tokens as $existing_token => $data ) {
if ( $data['e'] <= $now ) {
unset( $tokens[ $existing_token ] );
}
}
$token = wp_generate_password( 32, false, false );
set_transient( self::PENDING_TRANSIENT_PREFIX . $token, $user_id, self::PENDING_TTL );
$tokens[ $token ] = array(
'u' => $user_id,
'e' => $now + self::PENDING_TTL,
);
if ( count( $tokens ) > self::PENDING_MAX_TOKENS ) {
uasort(
$tokens,
static function ( array $a, array $b ): int {
return (int) $a['e'] <=> (int) $b['e'];
}
);
$tokens = array_slice( $tokens, -self::PENDING_MAX_TOKENS, null, true );
}
update_option( self::PENDING_OPTION, $tokens, false );
return $token;
}
/**
* Retrieve the raw pending-stage token map stored in the database.
*
* @since 1.6.8
*
* @return array<string, array{u: int, e: int}> Token => user ID + expiry.
*/
private function get_pending_token_map(): array {
$raw = get_option( self::PENDING_OPTION, array() );
if ( ! is_array( $raw ) ) {
return array();
}
$tokens = array();
foreach ( $raw as $token => $data ) {
if ( is_string( $token ) && is_array( $data ) && isset( $data['u'], $data['e'] ) && is_numeric( $data['u'] ) && is_numeric( $data['e'] ) ) {
$tokens[ $token ] = array(
'u' => (int) $data['u'],
'e' => (int) $data['e'],
);
}
}
return $tokens;
}
/**
* Remove a consumed pending-stage token from the map.
*
* @since 1.6.8
*
* @param string $token Token to consume.
*
* @return void
*/
private function consume_pending_token( string $token ): void {
$tokens = $this->get_pending_token_map();
if ( ! isset( $tokens[ $token ] ) ) {
return;
}
unset( $tokens[ $token ] );
update_option( self::PENDING_OPTION, $tokens, false );
}
/**
* Retrieve the raw pending-stage token from the current request.
*
@ -1301,6 +1579,7 @@ class Login_Form_Manager {
* Resolve the pending-stage token to its associated WP_User.
*
* @since 1.3.0
* @since 1.6.8 Reads the persistent token map instead of a transient.
*
* @return \WP_User|null Null when no valid token is present.
*/
@ -1311,13 +1590,13 @@ class Login_Form_Manager {
return null;
}
$user_id_raw = get_transient( self::PENDING_TRANSIENT_PREFIX . $token );
$data = $this->get_pending_token_map()[ $token ] ?? null;
if ( ! is_numeric( $user_id_raw ) ) {
if ( null === $data || $data['e'] <= time() ) {
return null;
}
$user = get_user_by( 'ID', (int) $user_id_raw );
$user = get_user_by( 'ID', $data['u'] );
return $user instanceof \WP_User ? $user : null;
}
@ -1372,16 +1651,53 @@ class Login_Form_Manager {
/**
* Retrieve the sanitized redirect_to parameter from the current request.
*
* Falls back to the referring front-end page when the request carries no
* core redirect_to value: membership and custom login pages rarely post
* one, and their own post-login redirects are bypassed by the challenge,
* so without this the user would land in wp-admin after verifying instead
* of returning to the page they logged in from. Only same-site, non-admin
* referers are honored.
*
* @since 1.0.0
* @since 1.6.11 Added the same-site front-end referer fallback.
*
* @return string
*/
private function get_requested_redirect(): string {
// 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'] ) ) {
if ( isset( $_REQUEST['redirect_to'] ) && is_string( $_REQUEST['redirect_to'] ) ) {
return esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) );
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
// The raw referer is used (not wp_get_referer()): login forms posted
// from their own page are self-referrals, which wp_get_referer()
// discards, and the form page is precisely the return target needed.
$raw_referer = wp_get_raw_referer();
if ( ! is_string( $raw_referer ) || '' === $raw_referer ) {
return '';
}
return esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) );
// phpcs:enable WordPress.Security.NonceVerification.Recommended
// Same-host URLs only (wp_validate_redirect applies the allowed hosts list).
$validated = wp_validate_redirect( wp_unslash( $raw_referer ), '' );
if ( '' === $validated ) {
return '';
}
$path = wp_parse_url( $validated, PHP_URL_PATH );
if ( ! is_string( $path ) || '' === $path ) {
return '';
}
// Never bounce back into admin or the login screen itself.
if ( '/wp-admin' === $path || str_starts_with( $path, '/wp-admin/' ) || '/wp-login.php' === $path || str_ends_with( $path, '/wp-login.php' ) ) {
return '';
}
return esc_url_raw( $validated );
}
/**
@ -1393,9 +1709,10 @@ class Login_Form_Manager {
*/
private function get_stage_url( array $extra_args = array() ): string {
$redirect_to = $this->get_requested_redirect();
$login_url = wp_login_url( $redirect_to );
$login_url = self::get_canonical_login_url( $redirect_to );
$args = array(
self::QUERY_ACTION => self::STAGE_ACTION,
self::QUERY_STAGE => self::STAGE_VERIFY,
self::QUERY_METHOD => $this->get_requested_method(),
);

View file

@ -33,8 +33,11 @@ class Rest_Controller {
/**
* REST namespace.
*
* Named REST_NAMESPACE instead of NAMESPACE: a class constant named
* "namespace" (case-insensitively) is deprecated in PHP 8.6.
*/
private const NAMESPACE = 'robotstxt-2fa/v1';
private const REST_NAMESPACE = 'robotstxt-2fa/v1';
/**
* Capability required to access any endpoint.
@ -103,7 +106,7 @@ class Rest_Controller {
*/
public function register_routes(): void {
register_rest_route(
self::NAMESPACE,
self::REST_NAMESPACE,
'/settings',
array(
array(
@ -120,7 +123,7 @@ class Rest_Controller {
);
register_rest_route(
self::NAMESPACE,
self::REST_NAMESPACE,
'/users',
array(
'methods' => WP_REST_Server::READABLE,

View file

@ -182,9 +182,14 @@ class Frontend_Profile {
* @return void
*/
public function maybe_enqueue_assets(): void {
/**
* Current post. Typed for PHPStan level max.
*
* @var \WP_Post|string|null $post
*/
global $post;
if ( ! is_a( $post, 'WP_Post' ) || ! has_shortcode( $post->post_content, 'robotstxt_2fa_profile' ) ) {
if ( ! $post instanceof \WP_Post || ! has_shortcode( $post->post_content, 'robotstxt_2fa_profile' ) ) {
return;
}

View file

@ -41,6 +41,7 @@ class Grace_Period {
public function register_hooks(): void {
add_action( 'admin_init', array( $this, 'maybe_redirect_to_setup_wizard' ) );
add_action( 'robotstxt_2fa_method_enabled', array( $this, 'clear_pending_setup' ), 10, 2 );
add_action( 'admin_notices', array( $this, 'maybe_show_setup_required_notice' ) );
}
/**
@ -167,10 +168,45 @@ class Grace_Period {
return;
}
wp_safe_redirect( admin_url( 'profile.php#robotstxt-2fa-settings' ) );
// The query flag lets the profile show WHY the user was redirected,
// so the mandatory setup does not feel like a silent loop.
$profile_url = add_query_arg( 'robotstxt-2fa-setup-required', '1', admin_url( 'profile.php' ) );
wp_safe_redirect( $profile_url . '#robotstxt-2fa-settings' );
exit;
}
/**
* Explain the setup wizard redirect on the profile screen.
*
* Rendered after {@see self::maybe_redirect_to_setup_wizard()} bounced the
* user back to their profile. Without it, users land on a regular profile
* page with no hint that 2FA enrollment is mandatory before they can
* continue to the dashboard — which reads as a broken redirect loop.
*
* @since 1.6.7
*
* @return void
*/
public function maybe_show_setup_required_notice(): void {
if ( ! $this->is_pending_setup() ) {
return;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only flag; no state change.
if ( ! isset( $_GET['robotstxt-2fa-setup-required'] ) ) {
return;
}
?>
<div class="notice notice-warning robotstxt-2fa-setup-required">
<p>
<strong><?php esc_html_e( 'Two-factor authentication is required.', 'robotstxt-2fa' ); ?></strong>
<?php esc_html_e( 'You must activate at least one verification method in the Two-Factor Authentication section of this page, then save, before you can continue to the dashboard.', 'robotstxt-2fa' ); ?>
</p>
</div>
<?php
}
/**
* Retrieve the grace period start timestamp, creating it on first call.
*

View file

@ -97,6 +97,13 @@ class Profile_Settings {
*/
private Trusted_Devices $trusted_devices;
/**
* Grace period manager.
*
* @var Grace_Period
*/
private Grace_Period $grace_period;
/**
* Whether the post-save redirect should focus the 2FA section.
*
@ -113,6 +120,7 @@ class Profile_Settings {
$this->otp_manager = new OTP_Manager();
$this->recovery_codes = new Recovery_Codes();
$this->trusted_devices = new Trusted_Devices();
$this->grace_period = new Grace_Period();
}
/**
@ -170,6 +178,57 @@ class Profile_Settings {
}
/**
* Render the forced-enrollment warning on the profile 2FA section.
*
* Shown when the user's role enforces 2FA but no verification method is
* configured yet, so the requirement is visible before the login flow
* (grace notice, setup wizard, or login block) kicks in. When a grace
* period is active, the number of remaining days is appended.
*
* @since 1.6.6
*
* @param \WP_User $user User whose profile section is being rendered.
*
* @return void
*/
public function render_forced_enrollment_warning( \WP_User $user ): void {
$user_settings = $this->user_settings_repository->get_user_settings( $user->ID );
if ( empty( $this->config->get_required_methods_for_user( $user ) ) || ! empty( $user_settings['methods'] ) ) {
return;
}
$grace_note = '';
$grace_days = $this->config->get_grace_period_days();
if ( $grace_days > 0 && $this->grace_period->is_active( $user, $grace_days ) ) {
$remaining = $this->grace_period->get_days_remaining( $user, $grace_days );
$grace_note = sprintf(
/* translators: %d: number of days remaining to complete the setup. */
_n(
'You have %d day left to complete the setup.',
'You have %d days left to complete the setup.',
$remaining,
'robotstxt-2fa'
),
$remaining
);
}
?>
<div class="notice notice-warning inline robotstxt-2fa-forced-warning">
<p>
<strong><?php esc_html_e( 'Two-factor authentication is required for your account.', 'robotstxt-2fa' ); ?></strong>
<?php esc_html_e( 'You have not set up any verification method yet. Activate at least one method below to keep access to your account.', 'robotstxt-2fa' ); ?>
<?php if ( '' !== $grace_note ) : ?>
<em><?php echo esc_html( $grace_note ); ?></em>
<?php endif; ?>
</p>
</div>
<?php
}
/**
* Render profile settings UI.
*
@ -313,6 +372,7 @@ class Profile_Settings {
}
?>
<h2 id="<?php echo esc_attr( self::SECTION_ANCHOR ); ?>"><?php esc_html_e( 'Two-Factor Authentication', 'robotstxt-2fa' ); ?></h2>
<?php $this->render_forced_enrollment_warning( $user ); ?>
<?php wp_nonce_field( self::NONCE_ACTION, self::NONCE_FIELD ); ?>
<table class="form-table" role="presentation">
<tbody>
@ -798,6 +858,20 @@ class Profile_Settings {
$nonce = sanitize_text_field( wp_unslash( $_POST[ self::NONCE_FIELD ] ) );
if ( ! wp_verify_nonce( $nonce, self::NONCE_ACTION ) ) {
/*
* A stale form (nonce expired) previously returned silently, which
* left wizard-trapped users clicking Save with no visible result
* while the setup-required redirect kept bouncing them back to the
* profile. Fail loudly so the user knows to try again.
*/
$this->focus_section = true;
add_settings_error(
'robotstxt-2fa',
'robotstxt-2fa-nonce-expired',
__( 'Your form session expired and nothing was saved. Please try saving again.', 'robotstxt-2fa' ),
'error'
);
return;
}
@ -1113,14 +1187,16 @@ class Profile_Settings {
/**
* Append the 2FA section anchor to redirects when requested.
*
* @param string $location Redirect destination.
* @param int $status HTTP status code.
* @param string|null $location Redirect destination (null from sloppy wp_redirect() callers).
* @param int|null $status HTTP status code.
*
* @return string
*/
public function maybe_append_section_anchor( string $location, int $status ): string {
public function maybe_append_section_anchor( ?string $location, ?int $status = null ): string {
unset( $status );
$location = $location ?? '';
if ( ! $this->focus_section ) {
return $location;
}

View file

@ -251,7 +251,7 @@ class Trusted_Devices {
return false;
}
if ( ! defined( 'AUTH_SALT' ) || '' === AUTH_SALT ) {
if ( ! defined( 'AUTH_SALT' ) || ! is_string( AUTH_SALT ) || '' === AUTH_SALT ) {
return false;
}
@ -283,7 +283,7 @@ class Trusted_Devices {
* @return void
*/
private function set_cookie( int $user_id, string $token, int $expires_at ): void {
if ( ! defined( 'AUTH_SALT' ) || '' === AUTH_SALT ) {
if ( ! defined( 'AUTH_SALT' ) || ! is_string( AUTH_SALT ) || '' === AUTH_SALT ) {
return;
}
@ -295,7 +295,7 @@ class Trusted_Devices {
$value,
array(
'expires' => $expires_at,
'path' => defined( 'COOKIEPATH' ) ? COOKIEPATH : '/',
'path' => defined( 'COOKIEPATH' ) && is_string( COOKIEPATH ) ? COOKIEPATH : '/',
'domain' => defined( 'COOKIE_DOMAIN' ) ? COOKIE_DOMAIN : '',
'secure' => is_ssl(),
'httponly' => true,
@ -315,7 +315,7 @@ class Trusted_Devices {
'',
array(
'expires' => time() - YEAR_IN_SECONDS,
'path' => defined( 'COOKIEPATH' ) ? COOKIEPATH : '/',
'path' => defined( 'COOKIEPATH' ) && is_string( COOKIEPATH ) ? COOKIEPATH : '/',
'domain' => defined( 'COOKIE_DOMAIN' ) ? COOKIE_DOMAIN : '',
'secure' => is_ssl(),
'httponly' => true,
@ -364,12 +364,20 @@ class Trusted_Devices {
/**
* Retrieve the raw device map from user meta.
*
* Non-string keys (corrupted meta) are discarded so callers always
* receive a token-hash-keyed map.
*
* @param int $user_id User ID.
*
* @return array<string, mixed>
*/
private function get_raw_devices( int $user_id ): array {
$raw = get_user_meta( $user_id, self::META_KEY, true );
return is_array( $raw ) ? $raw : array();
if ( ! is_array( $raw ) ) {
return array();
}
return array_filter( $raw, 'is_string', ARRAY_FILTER_USE_KEY );
}
}

1468
languages/robotstxt-2fa.pot Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,10 @@
=== 2FA (by ROBOTSTXT) ===
Contributors: robotstxt
Contributors: robotstxt, javiercasares
Tags: security, two-factor authentication, login, otp
Requires at least: 6.4
Tested up to: 7.0
Requires PHP: 8.0
Stable tag: 1.6.1
Requires at least: 7.0
Tested up to: 7.2
Requires PHP: 8.3
Stable tag: 1.6.11
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.html
@ -53,54 +53,57 @@ Yes. Activate the plugin at the network level. Network administrators can set an
== Compatibility ==
* WordPress: 6.4 – 7.0
* PHP: 8.0 – 8.5
* WordPress: 7.0 - 7.2
* PHP: 8.3 - 8.6
* MariaDB: 11.4 or newer
== Changelog ==
= 1.6.1 =
= 1.6.11 =
_Release date: 2026-08-14_
_Release date: 2026-11-04_
**Fixed**
* Fatal error during editor autosaves: the `[robotstxt_2fa_profile]` shortcode expanded when WordPress applied content filters to a post revision via REST (for example, an article that merely mentions the shortcode in its text). In that context the wp-admin render helpers are not loaded, causing a fatal error. The shortcode now bails out early on REST requests and loads the required wp-admin includes on demand elsewhere.
* The 2FA verification screen is no longer hijacked on membership sites that redirect the WordPress login away from wp-login.php (Restrict Content Pro's "Hijack Login URL" and any plugin using the same `login_form_login` redirect pattern). Stage requests now carry a dedicated login action that such redirects cannot intercept, verified end to end on the reported replica: password at the membership page → verification screen → valid code → back on the membership page, logged in.
* Users logging in from front-end forms now return to the page they logged in from after completing 2FA instead of landing in wp-admin.
= 1.6.0 =
= 1.6.10 =
_Release date: 2026-08-07_
**Added**
* REST API for administrators (namespace `robotstxt-2fa/v1`, all endpoints require `manage_options`):
* `GET /wp-json/robotstxt-2fa/v1/settings` — read the full 2FA configuration.
* `PUT /wp-json/robotstxt-2fa/v1/settings` — update the configuration (reuses the same validation as the admin settings form).
* `GET /wp-json/robotstxt-2fa/v1/users?role=<slug>&status=<enabled|required|disabled>` — list every user with their 2FA status: enabled, configured methods, role-required methods, forced flag, frequency, preferred method, whether OTP is set up, and unused recovery code count. No secrets are exposed.
**Changed**
* `wp 2fa list` now shows separate **Enabled**, **Methods** (configured), and **Required** (role-enforced) columns, plus a new `--required` filter to list only users whose role enforces 2FA.
= 1.5.3 =
_Release date: 2026-08-07_
**Added**
* Per-user preferred sign-in method — a new "Preferred method" dropdown on the user profile (visible when two or more methods are enabled) lets each user choose which verification method is requested first at the login screen. Users can still switch methods on the login screen via the existing alternate-method links.
**Changed**
* Role enforcement is now a floor, not a ceiling. When a role requires specific methods, those methods are still forced on the user's profile (enforced setup), but at login users may authenticate with any method they have configured — not only the role-required ones. Previously, users who configured extra methods (e.g. an authenticator app) only saw the role-required method at login.
_Release date: 2026-11-03_
**Fixed**
* Security: the "Require 2FA to create Application Passwords" check could be bypassed via the `/wp/v2/users/me/application-passwords` REST route. The route matcher now accepts the `me` alias.
* The 2FA verification stage now stays on the login URL the visitor actually used. When wp-login.php executes through an alias or renamed slug (a `/login` rewrite, a "hidden login" setup that does not filter `site_url`), the post-password redirect previously always targeted the literal `/wp-login.php` — on sites where that URL is blocked or renamed away at server level, users were stranded on a 403/404 page right after a correct password. Logins submitted from custom pages keep landing on the real wp-login.php as before.
= 1.6.9 =
_Release date: 2026-11-03_
**Changed**
* Compatibility floors raised to WordPress 7.0 and PHP 8.3, verified with full-range compatibility scans (WordPress 4.7-7.2, PHP 5.6-8.6). WordPress 7.2 and PHP 8.6 are now tested and documented.
* The admin menu icon is now a brand SVG (shield with keyhole) instead of the Dashicons shield. Rendered through WordPress' native SVG menu-icon support, it stays crisp on high-density screens, works identically on WordPress 7.0/7.1/7.2, and is future-proof against the ongoing move from Dashicons to SVG icons in the WordPress admin.
**Fixed**
* PHP 8.6 deprecation removed: a REST-controller class constant named `namespace` (case-insensitive) triggered a deprecation notice on PHP 8.6 and would become a fatal error on PHP 9.
**Compatibility**
* WordPress: 7.0 - 7.2
* PHP: 8.3 - 8.6
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.6 / WPCS 3.4.1 — 0 errors
* PHPStan: level max (10), no baseline — 0 errors
* PHPCompatibility: 8.3-8.6 — 0 issues
* PHPUnit: 9.6.38 — 110 tests, 220 assertions
= Previous versions =
For the full changelog see the [changelog.txt](https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/raw/branch/main/changelog.txt) file.
For the full changelog see the [changelog](https://www.robotstxt.software/plugins/robotstxt-2fa/) page.
== Compliance ==

View file

@ -1,14 +1,16 @@
<?php
/**
* Plugin Name: 2FA (by ROBOTSTXT)
* Plugin URI: https://www.robotstxt.es/plugins/robotstxt-2fa/
* Plugin URI: https://www.robotstxt.software/plugins/robotstxt-2fa/
* Update URI: https://www.robotstxt.software/plugins/robotstxt-2fa/
* Description: Adds two-factor authentication to the WordPress login flow.
* Version: 1.6.1
* Version: 1.6.11
* Author: ROBOTSTXT
* Author URI: https://www.robotstxt.es/
* Author URI: https://www.robotstxt.software/
* Text Domain: robotstxt-2fa
* Requires at least: 6.4
* Requires PHP: 8.0
* Domain Path: /languages
* Requires at least: 7.0
* Requires PHP: 8.3
* Network: true
* License: GPLv3 or later
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
@ -23,7 +25,7 @@ if ( ! defined( 'ABSPATH' ) ) {
}
if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) {
define( 'ROBOTSTXT_2FA_VERSION', '1.6.1' );
define( 'ROBOTSTXT_2FA_VERSION', '1.6.11' );
}
if ( ! defined( 'ROBOTSTXT_2FA_FILE' ) ) {

Some files were not shown because too many files have changed in this diff Show more