From fd2880bece4711a83796eb640169bfee80142736 Mon Sep 17 00:00:00 2001
From: Javier Casares
Date: Fri, 7 Aug 2026 14:15:58 +0000
Subject: [PATCH] v1.6.0
---
changelog.txt | 55 ++++
includes/admin/class-migration-page.php | 1 -
includes/admin/class-settings-page.php | 85 +++++-
includes/class-attempts-log.php | 49 +++
includes/class-frequency-options.php | 22 ++
includes/class-geoip-updater.php | 287 ++++++++++++++++++
includes/class-plugin.php | 21 +-
includes/cli/class-cli-command.php | 30 +-
includes/login/class-login-form-manager.php | 90 ++++--
includes/rest/class-rest-controller.php | 272 +++++++++++++++++
includes/user/class-profile-settings.php | 84 ++++-
includes/user/class-two-factor-config.php | 24 +-
.../user/class-user-settings-repository.php | 75 +++--
readme.txt | 33 +-
robotstxt-2fa.php | 4 +-
uninstall.php | 15 +
update.json | 11 +-
vendor/composer/installed.php | 4 +-
18 files changed, 1075 insertions(+), 87 deletions(-)
create mode 100644 includes/class-geoip-updater.php
create mode 100644 includes/rest/class-rest-controller.php
diff --git a/changelog.txt b/changelog.txt
index 1b73924..f4d2e68 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -1,5 +1,60 @@
== Changelog ==
+= 1.6.0 =
+
+_Release date: 2026-08-07_
+
+**Added**
+
+* REST API (namespace `robotstxt-2fa/v1`, admin-only): `GET/PUT /settings` to read and update the full configuration; `GET /users?role=&status=` to list users with their 2FA status (enabled, configured methods, required methods, forced, frequency, preferred method, OTP configured, unused recovery codes). No secrets exposed.
+
+**Changed**
+
+* `wp 2fa list` — separate Enabled, Methods, and Required columns; new `--required` filter.
+
+**Compatibility**
+
+* WordPress: 6.4 – 7.1
+* PHP: 8.0 – 8.5
+
+**Tests**
+
+* PHP Coding Standards: PHP_CodeSniffer / WPCS — 0 errors
+* PHPStan: level 9 — 0 errors
+* PHPCompatibility: 8.0–8.5 — 0 issues
+* PHPUnit: 9.6.34 — 55 tests, 140 assertions
+
+= 1.5.3 =
+
+_Release date: 2026-08-07_
+
+**Added**
+
+* Per-user preferred sign-in method — "Preferred method" dropdown on the user profile (shown when two or more methods are enabled) lets each user pick which verification method is requested first at login.
+* Failed attempts are now cleared for the user on any successful 2FA login (email, OTP, or recovery), so no errors remain queued once they authenticate correctly.
+* GeoIP auto-download — optional "Use the free ROBOTSTXT GeoIP database" checkbox in 2FA > Settings downloads the country database from ip.robotstxt.es into the uploads directory and refreshes it daily via WordPress cron. Includes a manual "Update now" button.
+
+**Fixed**
+
+* Security: the "Require 2FA to create Application Passwords" guard could be bypassed by requesting `/wp/v2/users/me/application-passwords` (the regex only matched numeric user IDs). Now accepts the `me` alias.
+
+**Changed**
+
+* Role enforcement is now a floor, not a ceiling. Required methods are still forced on the profile (enforced setup), but at login users may authenticate with any method they have configured — not only the role-required ones. Fixes users who only saw email despite configuring OTP/recovery.
+* "Remember this browser" duration now follows each user's verification frequency (daily/weekly/monthly) instead of a fixed global value, so the checkbox always complies with the profile setting.
+
+**Compatibility**
+
+* WordPress: 6.4 – 7.1
+* PHP: 8.0 – 8.5
+
+**Tests**
+
+* PHP Coding Standards: PHP_CodeSniffer / WPCS — 0 errors
+* PHPStan: level 9 — 0 errors
+* PHPCompatibility: 8.0–8.5 — 0 issues
+* PHPUnit: 9.6.34 — 50 tests, 121 assertions
+
= 1.5.2 =
_Release date: 2026-06-06_
diff --git a/includes/admin/class-migration-page.php b/includes/admin/class-migration-page.php
index edb280b..d4456c2 100644
--- a/includes/admin/class-migration-page.php
+++ b/includes/admin/class-migration-page.php
@@ -508,7 +508,6 @@ class Migration_Page {
)
);
- /** @var array $results */
$results = $query->get_results();
$rows = array();
diff --git a/includes/admin/class-settings-page.php b/includes/admin/class-settings-page.php
index 7db3e2c..342a1f4 100644
--- a/includes/admin/class-settings-page.php
+++ b/includes/admin/class-settings-page.php
@@ -325,6 +325,14 @@ class Settings_Page {
'robotstxt_2fa_geoip'
);
+ add_settings_field(
+ 'robotstxt_2fa_geoip_auto_download',
+ __( 'Auto database', 'robotstxt-2fa' ),
+ array( $this, 'render_geoip_auto_download_field' ),
+ self::PAGE_SLUG,
+ 'robotstxt_2fa_geoip'
+ );
+
add_settings_field(
'robotstxt_2fa_geoip_country_allow',
__( 'Country allow list (bypass 2FA)', 'robotstxt-2fa' ),
@@ -551,7 +559,7 @@ class Settings_Page {
*
* @param mixed $raw_settings Raw settings submitted by the user.
*
- * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string}
+ * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string, geoip_auto_download: bool}
*/
public function sanitize_settings( $raw_settings ): array {
$capability = $this->get_required_capability();
@@ -689,13 +697,17 @@ class Settings_Page {
$sanitized['geoip_always_challenge'] = strtoupper( sanitize_textarea_field( $raw_settings['geoip_always_challenge'] ) );
}
+ if ( array_key_exists( 'geoip_auto_download', $raw_settings ) ) {
+ $sanitized['geoip_auto_download'] = '1' === ( is_scalar( $raw_settings['geoip_auto_download'] ) ? (string) $raw_settings['geoip_auto_download'] : '' );
+ }
+
return $sanitized;
}
/**
* Retrieve plugin settings, migrating from legacy format when necessary.
*
- * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string}
+ * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string, geoip_auto_download: bool}
*/
public function get_settings(): array {
$options = array();
@@ -745,13 +757,14 @@ class Settings_Page {
'geoip_country_allow' => isset( $options['geoip_country_allow'] ) && is_string( $options['geoip_country_allow'] ) ? $options['geoip_country_allow'] : $defaults['geoip_country_allow'],
'geoip_country_deny' => isset( $options['geoip_country_deny'] ) && is_string( $options['geoip_country_deny'] ) ? $options['geoip_country_deny'] : $defaults['geoip_country_deny'],
'geoip_always_challenge' => isset( $options['geoip_always_challenge'] ) && is_string( $options['geoip_always_challenge'] ) ? $options['geoip_always_challenge'] : $defaults['geoip_always_challenge'],
+ 'geoip_auto_download' => isset( $options['geoip_auto_download'] ) ? (bool) $options['geoip_auto_download'] : $defaults['geoip_auto_download'],
);
}
/**
* Retrieve default settings.
*
- * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string}
+ * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string, geoip_auto_download: bool}
*/
private function get_default_settings(): array {
return array(
@@ -780,6 +793,7 @@ class Settings_Page {
'geoip_country_allow' => '',
'geoip_country_deny' => '',
'geoip_always_challenge' => '',
+ 'geoip_auto_download' => false,
);
}
@@ -965,7 +979,7 @@ class Settings_Page {
absint( $settings['trust_device_days'] ),
esc_html__( 'days (0 = disable trusted devices)', 'robotstxt-2fa' )
);
- echo '
' . esc_html__( 'When greater than 0, users see a "Remember this browser" checkbox after a successful 2FA verification. Trusted browsers skip the 2FA challenge for the configured duration.', 'robotstxt-2fa' ) . '
';
+ echo '
' . esc_html__( 'When greater than 0, the "Remember this browser" checkbox is available after a successful 2FA verification. The trust duration is taken from each user\'s verification frequency (daily, weekly, or monthly), so the checkbox always complies with their profile setting. Set to 0 to disable the feature.', 'robotstxt-2fa' ) . '
' . esc_html__( 'When enabled, the country database is downloaded from ip.robotstxt.es into your uploads directory and refreshed every day by the WordPress cron. This overrides the manual database path above.', 'robotstxt-2fa' ) . '
';
+ }
+ }
+
/**
* Render the GeoIP country allow list textarea.
*
diff --git a/includes/class-attempts-log.php b/includes/class-attempts-log.php
index 258b109..db1b2d6 100644
--- a/includes/class-attempts-log.php
+++ b/includes/class-attempts-log.php
@@ -34,6 +34,7 @@ class Attempts_Log {
*/
public function register_hooks(): void {
add_action( 'robotstxt_2fa_verification_failed', array( $this, 'append' ), 10, 2 );
+ add_action( 'robotstxt_2fa_verification_success', array( $this, 'clear_on_success' ) );
}
/**
@@ -124,4 +125,52 @@ class Attempts_Log {
public static function delete(): void {
delete_option( self::OPTION_NAME );
}
+
+ /**
+ * Handle a successful verification by clearing the user's error history.
+ *
+ * Hooked to {@see 'robotstxt_2fa_verification_success'}; fires for every
+ * verification method (email, OTP, recovery) so a successful login with any
+ * method empties the user's queued failed attempts.
+ *
+ * @since 1.5.3
+ *
+ * @param \WP_User $user User who completed the challenge.
+ * @return void
+ */
+ public function clear_on_success( \WP_User $user ): void {
+ $this->clear_for_user( $user->ID );
+ }
+
+ /**
+ * Remove every failed-attempt entry belonging to a specific user.
+ *
+ * @since 1.5.3
+ *
+ * @param int $user_id User identifier whose entries should be removed.
+ * @return void
+ */
+ public function clear_for_user( int $user_id ): void {
+ $log = get_option( self::OPTION_NAME, array() );
+
+ if ( ! is_array( $log ) || empty( $log ) ) {
+ return;
+ }
+
+ $filtered = array();
+
+ foreach ( $log as $entry ) {
+ if ( ! is_array( $entry ) ) {
+ continue;
+ }
+
+ $entry_user_id = isset( $entry['user_id'] ) && is_numeric( $entry['user_id'] ) ? (int) $entry['user_id'] : 0;
+
+ if ( $entry_user_id !== $user_id ) {
+ $filtered[] = $entry;
+ }
+ }
+
+ update_option( self::OPTION_NAME, $filtered, false );
+ }
}
diff --git a/includes/class-frequency-options.php b/includes/class-frequency-options.php
index da4151b..c5a5d11 100644
--- a/includes/class-frequency-options.php
+++ b/includes/class-frequency-options.php
@@ -107,4 +107,26 @@ class Frequency_Options {
return 0;
}
}
+
+ /**
+ * Resolve the interval in whole days represented by a frequency.
+ *
+ * Used to align the "Remember this browser" trust duration with the user's
+ * profile verification frequency. Returns 0 for session-based frequency.
+ *
+ * @since 1.5.3
+ *
+ * @param string $frequency Frequency identifier.
+ *
+ * @return int
+ */
+ public static function get_interval_days( string $frequency ): int {
+ $seconds = self::get_interval_seconds( $frequency );
+
+ if ( $seconds <= 0 ) {
+ return 0;
+ }
+
+ return intdiv( $seconds, DAY_IN_SECONDS );
+ }
}
diff --git a/includes/class-geoip-updater.php b/includes/class-geoip-updater.php
new file mode 100644
index 0000000..6c6ef63
--- /dev/null
+++ b/includes/class-geoip-updater.php
@@ -0,0 +1,287 @@
+config = $config;
+ }
+
+ /**
+ * Register WordPress hooks.
+ *
+ * @return void
+ */
+ public function register_hooks(): void {
+ add_action( self::CRON_HOOK, array( $this, 'run_cron_update' ) );
+ add_action( 'init', array( $this, 'maybe_schedule_update' ) );
+ add_action( 'admin_post_robotstxt_2fa_geoip_update_now', array( $this, 'handle_update_now' ) );
+ }
+
+ /**
+ * Resolve the absolute path where the auto-downloaded database is stored.
+ *
+ * @return string Empty string when the uploads directory is unavailable.
+ */
+ public static function get_database_path(): string {
+ $uploads = wp_upload_dir();
+
+ if ( empty( $uploads['basedir'] ) ) {
+ return '';
+ }
+
+ return trailingslashit( $uploads['basedir'] ) . 'robotstxt-2fa/country.mmdb';
+ }
+
+ /**
+ * Schedule or clear the daily update cron based on the auto-download setting.
+ *
+ * @return void
+ */
+ public function maybe_schedule_update(): void {
+ if ( $this->config->get_geoip_auto_download() ) {
+ if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
+ wp_schedule_event( time(), 'daily', self::CRON_HOOK );
+ }
+ } elseif ( wp_next_scheduled( self::CRON_HOOK ) ) {
+ wp_clear_scheduled_hook( self::CRON_HOOK );
+ }
+ }
+
+ /**
+ * Cron callback: refresh the database.
+ *
+ * @return void
+ */
+ public function run_cron_update(): void {
+ $this->download_database();
+ }
+
+ /**
+ * Download the country database, validate it, and store it atomically.
+ *
+ * @return bool True on success, false on failure (status stored for UI).
+ */
+ public function download_database(): bool {
+ $path = self::get_database_path();
+
+ if ( '' === $path ) {
+ $this->store_status( false, __( 'The uploads directory is not writable.', 'robotstxt-2fa' ) );
+ return false;
+ }
+
+ $directory = dirname( $path );
+
+ if ( ! wp_mkdir_p( $directory ) ) {
+ $this->store_status( false, __( 'Could not create the storage directory for the GeoIP database.', 'robotstxt-2fa' ) );
+ return false;
+ }
+
+ $response = wp_remote_get(
+ self::DOWNLOAD_URL,
+ array(
+ 'timeout' => 60,
+ 'redirection' => 5,
+ )
+ );
+
+ if ( is_wp_error( $response ) ) {
+ $this->store_status( false, $response->get_error_message() );
+ return false;
+ }
+
+ $code = (int) wp_remote_retrieve_response_code( $response );
+ $body = wp_remote_retrieve_body( $response );
+
+ if ( 200 !== $code || '' === $body ) {
+ /* translators: %d: HTTP response code. */
+ $this->store_status( false, sprintf( __( 'Download failed (HTTP %d).', 'robotstxt-2fa' ), $code ) );
+ return false;
+ }
+
+ if ( false === strpos( $body, self::MAXMIND_MARKER ) ) {
+ $this->store_status( false, __( 'The downloaded file is not a valid MaxMind database.', 'robotstxt-2fa' ) );
+ return false;
+ }
+
+ $temp = $path . '.tmp';
+ $written = file_put_contents( $temp, $body ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Cron download; WP_Filesystem cannot run unattended.
+
+ if ( false === $written || 0 === $written ) {
+ $this->store_status( false, __( 'Could not write the GeoIP database file.', 'robotstxt-2fa' ) );
+ return false;
+ }
+
+ if ( ! rename( $temp, $path ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename -- Atomic replace within the uploads directory.
+ unlink( $temp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- Cleanup of the temp file on failure.
+ $this->store_status( false, __( 'Could not finalize the GeoIP database file.', 'robotstxt-2fa' ) );
+ return false;
+ }
+
+ $this->store_status( true, '' );
+ return true;
+ }
+
+ /**
+ * Persist the outcome of the latest download attempt.
+ *
+ * @param bool $success Whether the download succeeded.
+ * @param string $message Error or status message.
+ *
+ * @return void
+ */
+ private function store_status( bool $success, string $message ): void {
+ update_option(
+ self::STATUS_OPTION,
+ array(
+ 'success' => $success,
+ 'message' => $message,
+ 'timestamp' => time(),
+ ),
+ false
+ );
+ }
+
+ /**
+ * Retrieve the last download status.
+ *
+ * @return array{success: bool, message: string, timestamp: int}
+ */
+ public static function get_status(): array {
+ $raw = get_option( self::STATUS_OPTION, array() );
+
+ if ( ! is_array( $raw ) ) {
+ return array(
+ 'success' => false,
+ 'message' => '',
+ 'timestamp' => 0,
+ );
+ }
+
+ return array(
+ 'success' => isset( $raw['success'] ) ? (bool) $raw['success'] : false,
+ 'message' => isset( $raw['message'] ) && is_string( $raw['message'] ) ? $raw['message'] : '',
+ 'timestamp' => isset( $raw['timestamp'] ) && is_numeric( $raw['timestamp'] ) ? (int) $raw['timestamp'] : 0,
+ );
+ }
+
+ /**
+ * Build the URL for the manual "Update now" button.
+ *
+ * @return string
+ */
+ public static function get_update_now_url(): string {
+ return wp_nonce_url(
+ admin_url( 'admin-post.php?action=robotstxt_2fa_geoip_update_now' ),
+ self::UPDATE_NONCE_ACTION,
+ self::UPDATE_NONCE_FIELD
+ );
+ }
+
+ /**
+ * Handle the manual "Update now" request from the settings page.
+ *
+ * @return void
+ */
+ public function handle_update_now(): void {
+ if ( ! current_user_can( 'manage_options' ) ) {
+ wp_die( esc_html__( 'Sorry, you are not allowed to do this.', 'robotstxt-2fa' ), 403 );
+ }
+
+ check_admin_referer( self::UPDATE_NONCE_ACTION, self::UPDATE_NONCE_FIELD );
+
+ $this->download_database();
+
+ $redirect = add_query_arg(
+ 'geoip_updated',
+ '1',
+ admin_url( 'admin.php?page=robotstxt-2fa-settings' )
+ );
+
+ wp_safe_redirect( $redirect );
+ exit;
+ }
+
+ /**
+ * Remove the cron event and the downloaded database file.
+ *
+ * Called from uninstall.php.
+ *
+ * @return void
+ */
+ public static function cleanup(): void {
+ $timestamp = wp_next_scheduled( self::CRON_HOOK );
+
+ if ( $timestamp ) {
+ wp_clear_scheduled_hook( self::CRON_HOOK );
+ }
+
+ delete_option( self::STATUS_OPTION );
+
+ $path = self::get_database_path();
+
+ if ( '' !== $path && file_exists( $path ) && is_file( $path ) ) {
+ unlink( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- Removing our own artifact on uninstall.
+ }
+ }
+}
diff --git a/includes/class-plugin.php b/includes/class-plugin.php
index 5e200c3..da0c9e2 100644
--- a/includes/class-plugin.php
+++ b/includes/class-plugin.php
@@ -12,6 +12,7 @@ use Robotstxt\TwoFA\Admin\Migration_Page;
use Robotstxt\TwoFA\Admin\Settings_Page;
use Robotstxt\TwoFA\Cli\Cli_Command;
use Robotstxt\TwoFA\Login\Login_Form_Manager;
+use Robotstxt\TwoFA\Rest\Rest_Controller;
use Robotstxt\TwoFA\User\Frontend_Profile;
use Robotstxt\TwoFA\User\Grace_Period;
use Robotstxt\TwoFA\User\Profile_Settings;
@@ -112,6 +113,13 @@ class Plugin {
*/
private Geo_Restrictions $geo_restrictions;
+ /**
+ * GeoIP database auto-download handler.
+ *
+ * @var GeoIP_Updater
+ */
+ private GeoIP_Updater $geoip_updater;
+
/**
* Audit dashboard page.
*
@@ -126,6 +134,13 @@ class Plugin {
*/
private Migration_Page $migration_page;
+ /**
+ * REST API controller.
+ *
+ * @var Rest_Controller
+ */
+ private Rest_Controller $rest_controller;
+
/**
* Get singleton instance.
*
@@ -156,8 +171,10 @@ class Plugin {
$this->email_notifications = new Email_Notifications( $config );
$this->ip_restrictions = new IP_Restrictions( $config );
$this->geo_restrictions = new Geo_Restrictions( $config );
+ $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->rest_controller = new Rest_Controller();
}
/**
@@ -171,8 +188,10 @@ class Plugin {
$this->email_notifications->register_hooks();
$this->ip_restrictions->register_hooks();
$this->geo_restrictions->register_hooks();
+ $this->geoip_updater->register_hooks();
$this->dashboard_page->register_hooks();
$this->migration_page->register_hooks();
+ $this->rest_controller->register_hooks();
$this->login_manager->register_hooks();
$this->profile_settings->register_hooks();
$this->recovery_codes->register_hooks();
@@ -216,7 +235,7 @@ class Plugin {
return $result;
}
- if ( ! preg_match( '#^/wp/v2/users/\d+/application-passwords$#', $request->get_route() ) ) {
+ if ( ! preg_match( '#^/wp/v2/users/(?:\d+|me)/application-passwords$#', $request->get_route() ) ) {
return $result;
}
diff --git a/includes/cli/class-cli-command.php b/includes/cli/class-cli-command.php
index 1e9a282..eb9312c 100644
--- a/includes/cli/class-cli-command.php
+++ b/includes/cli/class-cli-command.php
@@ -232,6 +232,9 @@ class Cli_Command extends WP_CLI_Command {
* [--without-2fa]
* : Only show users who do not have 2FA enabled.
*
+ * [--required]
+ * : Only show users whose role requires 2FA (enforced).
+ *
* [--format=]
* : Output format. Accepts: table, csv, json. Default: table.
*
@@ -239,7 +242,10 @@ class Cli_Command extends WP_CLI_Command {
*
* wp 2fa list
* wp 2fa list --role=editor --without-2fa
- * wp 2fa list --format=csv
+ * wp 2fa list --required --format=csv
+ *
+ * Columns: ID, Login, Email, Enabled, Methods (configured), Required
+ * (role-enforced methods), Frequency.
*
* @subcommand list
*
@@ -266,8 +272,9 @@ class Cli_Command extends WP_CLI_Command {
continue;
}
- $settings = $this->repository->get_user_settings( $user->ID );
- $required = $this->config->get_required_methods_for_user( $user );
+ $settings = $this->repository->get_user_settings( $user->ID );
+ $required = $this->config->get_required_methods_for_user( $user );
+
$is_enabled = $settings['enabled'];
$is_forced = ! empty( $required );
@@ -275,23 +282,23 @@ class Cli_Command extends WP_CLI_Command {
continue;
}
- if ( $is_enabled ) {
- $status = 'enabled (' . implode( ', ', $settings['methods'] ) . ')';
- } elseif ( $is_forced ) {
- $status = 'disabled (required)';
- } else {
- $status = 'disabled';
+ if ( isset( $assoc_args['required'] ) && ! $is_forced ) {
+ continue;
}
$rows[] = array(
'ID' => (string) $user->ID,
'Login' => $user->user_login,
'Email' => $user->user_email,
- '2FA' => $status,
+ 'Enabled' => $is_enabled ? 'yes' : 'no',
+ 'Methods' => ! empty( $settings['methods'] ) ? implode( ',', $settings['methods'] ) : '-',
+ 'Required' => $is_forced ? implode( ',', $required ) : 'no',
'Frequency' => '' !== $settings['frequency'] ? $settings['frequency'] : 'session',
);
}
+ $headers = array( 'ID', 'Login', 'Email', 'Enabled', 'Methods', 'Required', 'Frequency' );
+
if ( 'json' === $format ) {
$encoded = wp_json_encode( $rows );
\WP_CLI::line( is_string( $encoded ) ? $encoded : '[]' );
@@ -299,7 +306,6 @@ class Cli_Command extends WP_CLI_Command {
}
if ( 'csv' === $format ) {
- $headers = array( 'ID', 'Login', 'Email', '2FA', 'Frequency' );
\WP_CLI::line( implode( ',', array_map( array( $this, 'csv_field' ), $headers ) ) );
foreach ( $rows as $row ) {
\WP_CLI::line( implode( ',', array_map( array( $this, 'csv_field' ), array_values( $row ) ) ) );
@@ -307,7 +313,7 @@ class Cli_Command extends WP_CLI_Command {
return;
}
- \WP_CLI\Utils\format_items( 'table', $rows, array( 'ID', 'Login', 'Email', '2FA', 'Frequency' ) );
+ \WP_CLI\Utils\format_items( 'table', $rows, $headers );
}
/**
diff --git a/includes/login/class-login-form-manager.php b/includes/login/class-login-form-manager.php
index 9c01cce..a859a0a 100644
--- a/includes/login/class-login-form-manager.php
+++ b/includes/login/class-login-form-manager.php
@@ -310,7 +310,8 @@ class Login_Form_Manager {
);
}
- $trust_days = $this->config->get_trust_device_days();
+ // Trust-device duration follows the user's profile verification frequency.
+ $trust_days = $pending_user instanceof WP_User ? $this->get_trust_days_for_user( $pending_user ) : 0;
if ( $trust_days > 0 ) {
?>
@@ -691,10 +692,13 @@ class Login_Form_Manager {
);
// Trusted devices: set cookie when user checked "Remember this browser".
- $trust_days = $this->config->get_trust_device_days();
+ // Duration complies with the user's profile verification frequency.
+ if ( isset( $_POST['robotstxt_2fa_trust_device'] ) && '1' === $_POST['robotstxt_2fa_trust_device'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified above.
+ $trust_days = $this->get_trust_days_for_user( $authenticated_user );
- if ( $trust_days > 0 && isset( $_POST['robotstxt_2fa_trust_device'] ) && '1' === $_POST['robotstxt_2fa_trust_device'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce already verified above.
- $this->trusted_devices->trust_current_device( $authenticated_user, $trust_days );
+ if ( $trust_days > 0 ) {
+ $this->trusted_devices->trust_current_device( $authenticated_user, $trust_days );
+ }
}
/**
@@ -931,14 +935,16 @@ class Login_Form_Manager {
/**
* Retrieve the verification methods that are active for the provided user.
*
- * When 2FA is enforced by role, only methods that are both required by the
- * 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.
+ * Role enforcement is treated as a floor, not a ceiling: when 2FA is
+ * enforced by role, the required methods are guaranteed to be set up on the
+ * profile (enforced at save time), but the user may authenticate with ANY
+ * method they have configured — not only the role-required ones. If the
+ * user has not configured any method yet, the role-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, frequency: string}|null $user_settings Optional preloaded settings.
+ * @param \WP_User $user User attempting to authenticate.
+ * @param array{enabled: bool, methods: array, frequency: string, preferred_method: string}|null $user_settings Optional preloaded settings.
*
* @return array
*/
@@ -968,8 +974,9 @@ class Login_Form_Manager {
$profile_methods = array_values( array_unique( $profile_methods ) );
- // When forced, restrict to methods required by the user's roles.
- if ( $is_forced ) {
+ if ( $is_forced && empty( $profile_methods ) ) {
+ // User has not configured any method yet — fall back to the methods the
+ // system can deliver from the required set so a challenge is still possible.
$required_slugs = array();
foreach ( $required_methods as $method ) {
@@ -980,16 +987,9 @@ class Login_Form_Manager {
}
}
- $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;
- }
+ $candidate_methods = array_values( array_unique( $required_slugs ) );
} else {
+ // Offer every method the user has configured (role enforcement is a floor).
$candidate_methods = $profile_methods;
}
@@ -1013,6 +1013,7 @@ class Login_Form_Manager {
}
// Return methods in canonical priority order: OTP first, email second, recovery last.
+ // The user's preferred method is honored separately in select_preferred_method().
$priority = array( 'otp', 'email', 'recovery' );
$sorted = array();
@@ -1059,7 +1060,7 @@ class Login_Form_Manager {
}
}
- return $this->select_preferred_method( $methods );
+ return $this->select_preferred_method( $methods, (string) $user_settings['preferred_method'] );
}
/**
@@ -1102,15 +1103,29 @@ class Login_Form_Manager {
/**
* Determine which method should be requested when a challenge is required.
*
- * @param array $methods Active verification methods.
+ * Honors the user's preferred method (set on their profile) when it is part
+ * of the available methods; otherwise falls back to the canonical order.
+ *
+ * @since 1.0.0
+ *
+ * @param array $methods Active verification methods (stage slugs).
+ * @param string $preferred_method Optional user-chosen preferred method key.
*
* @return string
*/
- private function select_preferred_method( array $methods ): string {
+ private function select_preferred_method( array $methods, string $preferred_method = '' ): string {
if ( empty( $methods ) ) {
return '';
}
+ if ( '' !== $preferred_method ) {
+ $preferred_slug = $this->normalize_method_slug( $preferred_method );
+
+ if ( '' !== $preferred_slug && in_array( $preferred_slug, $methods, true ) ) {
+ return $preferred_slug;
+ }
+ }
+
// Prefer OTP (most secure), then email, then recovery codes (last resort).
foreach ( array( 'otp', 'email' ) as $method ) {
if ( in_array( $method, $methods, true ) ) {
@@ -1438,6 +1453,31 @@ class Login_Form_Manager {
return $this->config->get_frequency();
}
+ /**
+ * Resolve the "Remember this browser" trust duration (in days) for a user.
+ *
+ * The feature must be enabled by the administrator (trust_device_days > 0)
+ * and the user's effective verification frequency must define a non-zero
+ * interval; the duration is taken from that frequency so the checkbox always
+ * complies with the user's profile setting.
+ *
+ * @since 1.5.3
+ *
+ * @param \WP_User $user User attempting to authenticate.
+ *
+ * @return int Number of days, or 0 when the feature is disabled or the
+ * user's frequency is per-session.
+ */
+ private function get_trust_days_for_user( \WP_User $user ): int {
+ if ( $this->config->get_trust_device_days() <= 0 ) {
+ return 0;
+ }
+
+ $user_settings = $this->user_settings_repository->get_user_settings( $user->ID );
+
+ return Frequency_Options::get_interval_days( $this->get_effective_frequency( $user, $user_settings ) );
+ }
+
/**
* Build a hashed context key representing the current login environment.
*
diff --git a/includes/rest/class-rest-controller.php b/includes/rest/class-rest-controller.php
new file mode 100644
index 0000000..9ef43d3
--- /dev/null
+++ b/includes/rest/class-rest-controller.php
@@ -0,0 +1,272 @@
+config = new Two_Factor_Config();
+ $this->settings_page = new Settings_Page();
+ $this->repository = new User_Settings_Repository();
+ $this->otp_manager = new OTP_Manager();
+ $this->recovery_codes = new Recovery_Codes();
+ }
+
+ /**
+ * Register WordPress hooks.
+ *
+ * @return void
+ */
+ public function register_hooks(): void {
+ add_action( 'rest_api_init', array( $this, 'register_routes' ) );
+ }
+
+ /**
+ * Register the REST routes.
+ *
+ * @return void
+ */
+ public function register_routes(): void {
+ register_rest_route(
+ self::NAMESPACE,
+ '/settings',
+ array(
+ array(
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => array( $this, 'get_settings' ),
+ 'permission_callback' => array( $this, 'check_permission' ),
+ ),
+ array(
+ 'methods' => WP_REST_Server::EDITABLE,
+ 'callback' => array( $this, 'update_settings' ),
+ 'permission_callback' => array( $this, 'check_permission' ),
+ ),
+ )
+ );
+
+ register_rest_route(
+ self::NAMESPACE,
+ '/users',
+ array(
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => array( $this, 'get_users' ),
+ 'permission_callback' => array( $this, 'check_permission' ),
+ 'args' => array(
+ 'role' => array(
+ 'type' => 'string',
+ 'description' => __( 'Restrict the list to a single role slug.', 'robotstxt-2fa' ),
+ 'sanitize_callback' => 'sanitize_key',
+ ),
+ 'status' => array(
+ 'type' => 'string',
+ 'description' => __( 'Filter by 2FA status: enabled, required, or disabled.', 'robotstxt-2fa' ),
+ 'enum' => array( 'enabled', 'required', 'disabled' ),
+ 'sanitize_callback' => 'sanitize_key',
+ ),
+ ),
+ )
+ );
+ }
+
+ /**
+ * Permission callback — every endpoint requires the admin capability.
+ *
+ * @return bool|\WP_Error
+ */
+ public function check_permission() {
+ if ( ! current_user_can( self::CAPABILITY ) ) {
+ return new \WP_Error(
+ 'robotstxt_2fa_rest_forbidden',
+ __( 'You are not allowed to manage 2FA settings.', 'robotstxt-2fa' ),
+ array( 'status' => rest_authorization_required_code() )
+ );
+ }
+
+ return true;
+ }
+
+ /**
+ * Retrieve the full 2FA settings object.
+ *
+ * @param WP_REST_Request $request Incoming request.
+ *
+ * @return WP_REST_Response
+ */
+ public function get_settings( WP_REST_Request $request ): WP_REST_Response {
+ unset( $request );
+
+ return rest_ensure_response( $this->settings_page->get_settings() );
+ }
+
+ /**
+ * Update the 2FA settings from a JSON body.
+ *
+ * Reuses {@see Settings_Page::sanitize_settings()} so the REST write path
+ * applies the exact same validation as the admin settings form.
+ *
+ * @param WP_REST_Request $request Incoming request with a JSON settings body.
+ *
+ * @return WP_REST_Response|\WP_Error
+ */
+ public function update_settings( WP_REST_Request $request ) {
+ $sanitized = $this->settings_page->sanitize_settings( $request->get_json_params() );
+
+ update_option( Settings_Page::OPTION_NAME, $sanitized, false );
+
+ if ( is_multisite() ) {
+ update_site_option( Settings_Page::OPTION_NAME, $sanitized );
+ }
+
+ return rest_ensure_response( $this->settings_page->get_settings() );
+ }
+
+ /**
+ * List users and their 2FA status, optionally filtered by role and status.
+ *
+ * @param WP_REST_Request $request Incoming request.
+ *
+ * @return WP_REST_Response
+ */
+ public function get_users( WP_REST_Request $request ): WP_REST_Response {
+ $query_args = array(
+ 'number' => -1,
+ 'fields' => 'all',
+ );
+
+ $role = $request->get_param( 'role' );
+
+ if ( is_string( $role ) && '' !== $role ) {
+ $query_args['role'] = sanitize_key( $role );
+ }
+
+ $status_filter = $request->get_param( 'status' );
+
+ if ( is_string( $status_filter ) && '' === $status_filter ) {
+ $status_filter = '';
+ }
+
+ $users = get_users( $query_args );
+ $out = array();
+
+ foreach ( $users as $user ) {
+ if ( ! $user instanceof \WP_User ) {
+ continue;
+ }
+
+ $entry = $this->build_user_entry( $user );
+
+ if ( is_string( $status_filter ) && '' !== $status_filter && $entry['status'] !== $status_filter ) {
+ continue;
+ }
+
+ $out[] = $entry;
+ }
+
+ return rest_ensure_response( $out );
+ }
+
+ /**
+ * Build the 2FA status payload for a single user.
+ *
+ * @param \WP_User $user User to describe.
+ *
+ * @return array
+ */
+ private function build_user_entry( \WP_User $user ): array {
+ $settings = $this->repository->get_user_settings( $user->ID );
+ $required = $this->config->get_required_methods_for_user( $user );
+ $forced = ! empty( $required );
+ $enabled = $settings['enabled'];
+
+ return array(
+ 'id' => $user->ID,
+ 'login' => $user->user_login,
+ 'email' => $user->user_email,
+ 'roles' => $user->roles,
+ 'enabled' => $enabled,
+ 'forced' => $forced,
+ 'status' => $enabled ? 'enabled' : ( $forced ? 'required' : 'disabled' ),
+ 'methods' => $settings['methods'],
+ 'required_methods' => $required,
+ 'frequency' => $settings['frequency'],
+ 'preferred_method' => $settings['preferred_method'],
+ 'has_otp' => '' !== $this->otp_manager->get_secret( $user->ID ),
+ 'unused_recovery_codes' => $this->recovery_codes->count_unused_codes( $user->ID ),
+ );
+ }
+}
diff --git a/includes/user/class-profile-settings.php b/includes/user/class-profile-settings.php
index 2994015..6e7751d 100644
--- a/includes/user/class-profile-settings.php
+++ b/includes/user/class-profile-settings.php
@@ -286,6 +286,31 @@ class Profile_Settings {
$email_destination
);
}
+
+ /*
+ * Build the preferred-method dropdown options from the methods the user
+ * has actually enabled. The control is only rendered when two or more
+ * methods are active, since a single method leaves nothing to choose.
+ */
+ $preferred_options = array();
+
+ if ( $email_enabled ) {
+ $preferred_options['email'] = $email_label;
+ }
+
+ if ( $otp_enabled && isset( $available_methods['otp']['label'] ) ) {
+ $preferred_options['otp'] = $available_methods['otp']['label'];
+ }
+
+ if ( $recovery_enabled && isset( $available_methods['recovery_codes']['label'] ) ) {
+ $preferred_options['recovery_codes'] = $available_methods['recovery_codes']['label'];
+ }
+
+ $preferred_value = (string) $user_settings['preferred_method'];
+
+ if ( '' !== $preferred_value && ! array_key_exists( $preferred_value, $preferred_options ) ) {
+ $preferred_value = '';
+ }
?>
@@ -474,17 +499,41 @@ class Profile_Settings {
-
-
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+ = 2 ) : ?>
+
+
+
+
+
+
+
@@ -664,9 +713,9 @@ class Profile_Settings {
/**
* Reset recovery codes and user settings when all codes were consumed.
*
- * @param \WP_User $user User being edited.
- * @param array{enabled: bool, methods: array, 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 \WP_User $user User being edited.
+ * @param array{enabled: bool, methods: array, frequency: string, preferred_method: string} $user_settings Stored user settings prior to the reset.
+ * @param bool $is_forced Whether two-factor authentication is enforced for the user.
*
* @return void
*/
@@ -1011,15 +1060,22 @@ class Profile_Settings {
$frequency = $this->config->get_frequency();
}
+ $preferred_method = '';
+
+ if ( isset( $raw_settings['preferred_method'] ) && is_string( $raw_settings['preferred_method'] ) ) {
+ $preferred_method = sanitize_key( wp_unslash( $raw_settings['preferred_method'] ) );
+ }
+
$methods_added = array_diff( $selected_methods, $previous_methods );
$methods_removed = array_diff( $previous_methods, $selected_methods );
$this->user_settings_repository->save_user_settings(
$user_id,
array(
- 'enabled' => $enabled,
- 'methods' => $selected_methods,
- 'frequency' => $frequency,
+ 'enabled' => $enabled,
+ 'methods' => $selected_methods,
+ 'frequency' => $frequency,
+ 'preferred_method' => $preferred_method,
)
);
@@ -1304,7 +1360,7 @@ class Profile_Settings {
/**
* Resolve the frequency value shown and stored for the user.
*
- * @param array{enabled: bool, methods: array, frequency: string} $user_settings Stored user settings.
+ * @param array{enabled: bool, methods: array, frequency: string, preferred_method: string} $user_settings Stored user settings.
*
* @return string
*/
diff --git a/includes/user/class-two-factor-config.php b/includes/user/class-two-factor-config.php
index aa99b1e..5c625ee 100644
--- a/includes/user/class-two-factor-config.php
+++ b/includes/user/class-two-factor-config.php
@@ -21,7 +21,7 @@ class Two_Factor_Config {
/**
* Retrieve global two-factor settings with multisite support.
*
- * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string}
+ * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string, geoip_auto_download: bool}
*/
public function get_settings(): array {
$settings_page = new Settings_Page();
@@ -240,12 +240,32 @@ class Two_Factor_Config {
/**
* Retrieve the GeoIP database file path.
*
+ * When auto-download is enabled, the managed uploads path is returned and
+ * the manual path setting is ignored.
+ *
* @since 1.5.0
*
* @return string
*/
public function get_geoip_database_path(): string {
- return $this->get_settings()['geoip_database_path'];
+ $settings = $this->get_settings();
+
+ if ( ! empty( $settings['geoip_auto_download'] ) ) {
+ return \Robotstxt\TwoFA\GeoIP_Updater::get_database_path();
+ }
+
+ return $settings['geoip_database_path'];
+ }
+
+ /**
+ * Determine whether the auto-download GeoIP database is enabled.
+ *
+ * @since 1.5.3
+ *
+ * @return bool
+ */
+ public function get_geoip_auto_download(): bool {
+ return ! empty( $this->get_settings()['geoip_auto_download'] );
}
/**
diff --git a/includes/user/class-user-settings-repository.php b/includes/user/class-user-settings-repository.php
index af5ed65..f2f5eaf 100644
--- a/includes/user/class-user-settings-repository.php
+++ b/includes/user/class-user-settings-repository.php
@@ -48,7 +48,7 @@ class User_Settings_Repository {
*
* @param int $user_id User identifier.
*
- * @return array{enabled: bool, methods: array, frequency: string}
+ * @return array{enabled: bool, methods: array, frequency: string, preferred_method: string}
*/
public function get_user_settings( int $user_id ): array {
$raw_settings = get_user_meta( $user_id, self::USER_SETTINGS_META, true );
@@ -60,8 +60,8 @@ class User_Settings_Repository {
$raw_methods = isset( $raw_settings['methods'] ) && is_array( $raw_settings['methods'] ) ? $raw_settings['methods'] : array();
return array(
- 'enabled' => ! empty( $raw_settings['enabled'] ),
- 'methods' => array_values(
+ 'enabled' => ! empty( $raw_settings['enabled'] ),
+ 'methods' => array_values(
array_unique(
array_filter(
array_map(
@@ -73,7 +73,8 @@ class User_Settings_Repository {
)
)
),
- 'frequency' => Frequency_Options::sanitize( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ? $raw_settings['frequency'] : '' ),
+ 'frequency' => Frequency_Options::sanitize( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ? $raw_settings['frequency'] : '' ),
+ 'preferred_method' => sanitize_key( isset( $raw_settings['preferred_method'] ) && is_string( $raw_settings['preferred_method'] ) ? $raw_settings['preferred_method'] : '' ),
);
}
@@ -86,22 +87,36 @@ class User_Settings_Repository {
* @return void
*/
public function save_user_settings( int $user_id, array $settings ): void {
- $raw_methods = isset( $settings['methods'] ) && is_array( $settings['methods'] ) ? $settings['methods'] : array();
- $prepared = array(
- 'enabled' => ! empty( $settings['enabled'] ),
- 'methods' => array_values(
- array_unique(
- array_filter(
- array_map(
- static function ( mixed $v ): string {
- return sanitize_key( is_string( $v ) ? $v : '' );
- },
- $raw_methods
- )
+ $raw_methods = isset( $settings['methods'] ) && is_array( $settings['methods'] ) ? $settings['methods'] : array();
+ $sanitized_methods = array_values(
+ array_unique(
+ array_filter(
+ array_map(
+ static function ( mixed $v ): string {
+ return sanitize_key( is_string( $v ) ? $v : '' );
+ },
+ $raw_methods
)
)
- ),
- 'frequency' => Frequency_Options::sanitize( isset( $settings['frequency'] ) && is_string( $settings['frequency'] ) ? $settings['frequency'] : Frequency_Options::FREQUENCY_SESSION ),
+ )
+ );
+
+ /*
+ * Preserve the existing preferred method when the caller does not
+ * explicitly provide one. This keeps unrelated updates (CLI commands,
+ * imports, recovery-code regeneration) from wiping the user's choice.
+ */
+ if ( array_key_exists( 'preferred_method', $settings ) ) {
+ $preferred_method = is_string( $settings['preferred_method'] ) ? $settings['preferred_method'] : '';
+ } else {
+ $preferred_method = $this->get_user_settings( $user_id )['preferred_method'];
+ }
+
+ $prepared = array(
+ 'enabled' => ! empty( $settings['enabled'] ),
+ 'methods' => $sanitized_methods,
+ 'frequency' => Frequency_Options::sanitize( isset( $settings['frequency'] ) && is_string( $settings['frequency'] ) ? $settings['frequency'] : Frequency_Options::FREQUENCY_SESSION ),
+ 'preferred_method' => $this->sanitize_preferred_method( $preferred_method, $sanitized_methods ),
);
update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared );
@@ -112,6 +127,30 @@ class User_Settings_Repository {
}
}
+ /**
+ * Sanitize the preferred method, ensuring it belongs to the enabled set.
+ *
+ * @since 1.5.3
+ *
+ * @param string $preferred_method Raw preferred method identifier.
+ * @param array $enabled_methods Sanitized list of enabled methods.
+ *
+ * @return string Empty when the preferred method is not enabled.
+ */
+ private function sanitize_preferred_method( string $preferred_method, array $enabled_methods ): string {
+ $preferred_method = sanitize_key( $preferred_method );
+
+ if ( '' === $preferred_method ) {
+ return '';
+ }
+
+ if ( in_array( $preferred_method, $enabled_methods, true ) ) {
+ return $preferred_method;
+ }
+
+ return '';
+ }
+
/**
* Store email challenge details for a user.
*
diff --git a/readme.txt b/readme.txt
index 187f664..a74bc1e 100644
--- a/readme.txt
+++ b/readme.txt
@@ -4,7 +4,7 @@ Tags: security, two-factor authentication, login, otp
Requires at least: 6.4
Tested up to: 7.0
Requires PHP: 8.0
-Stable tag: 1.5.2
+Stable tag: 1.6.0
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.html
@@ -59,6 +59,37 @@ Yes. Activate the plugin at the network level. Network administrators can set an
== Changelog ==
+= 1.6.0 =
+
+_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=&status=` — 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.
+
+**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.
+
= 1.5.2 =
_Release date: 2026-06-06_
diff --git a/robotstxt-2fa.php b/robotstxt-2fa.php
index f3bf3a4..49371d3 100644
--- a/robotstxt-2fa.php
+++ b/robotstxt-2fa.php
@@ -3,7 +3,7 @@
* Plugin Name: 2FA (by ROBOTSTXT)
* Plugin URI: https://www.robotstxt.es/plugins/robotstxt-2fa/
* Description: Adds two-factor authentication to the WordPress login flow.
- * Version: 1.5.2
+ * Version: 1.6.0
* Author: ROBOTSTXT
* Author URI: https://www.robotstxt.es/
* Text Domain: robotstxt-2fa
@@ -23,7 +23,7 @@ if ( ! defined( 'ABSPATH' ) ) {
}
if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) {
- define( 'ROBOTSTXT_2FA_VERSION', '1.5.2' );
+ define( 'ROBOTSTXT_2FA_VERSION', '1.6.0' );
}
if ( ! defined( 'ROBOTSTXT_2FA_FILE' ) ) {
diff --git a/uninstall.php b/uninstall.php
index 1068b31..84312a2 100644
--- a/uninstall.php
+++ b/uninstall.php
@@ -44,8 +44,23 @@ if ( ! robotstxt_2fa_should_delete_data() ) {
// Remove plugin-level options.
delete_option( 'robotstxt_2fa_settings' );
delete_option( 'robotstxt_2fa_failed_log' );
+delete_option( 'robotstxt_2fa_geoip_status' );
delete_site_option( 'robotstxt_2fa_settings' );
+// Clear the GeoIP auto-download cron event.
+wp_clear_scheduled_hook( 'robotstxt_2fa_geoip_update' );
+
+// Remove the auto-downloaded GeoIP database from the uploads directory.
+$robotstxt_2fa_uploads = wp_upload_dir();
+
+if ( ! empty( $robotstxt_2fa_uploads['basedir'] ) ) {
+ $robotstxt_2fa_geoip_file = trailingslashit( $robotstxt_2fa_uploads['basedir'] ) . 'robotstxt-2fa/country.mmdb';
+
+ if ( is_file( $robotstxt_2fa_geoip_file ) ) {
+ unlink( $robotstxt_2fa_geoip_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- Removing our own artifact on uninstall.
+ }
+}
+
global $wpdb;
$robotstxt_2fa_meta_keys = array(
diff --git a/update.json b/update.json
index 9ef960e..02ed343 100644
--- a/update.json
+++ b/update.json
@@ -1,21 +1,22 @@
{
"name": "2FA (by ROBOTSTXT)",
"slug": "robotstxt-2fa",
- "version": "1.5.2",
- "download_url": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/releases/download/1.5.2/robotstxt-2fa-1.5.2.zip",
+ "version": "1.6.0",
+ "download_url": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/releases/download/1.6.0/robotstxt-2fa-1.6.0.zip",
"requires": "6.4",
"requires_php": "8.0",
"tested": "7.1",
- "last_updated": "2026-06-06",
+ "last_updated": "2026-08-07",
"author": "ROBOTSTXT",
"author_profile": "https://www.robotstxt.es/",
"homepage": "https://www.robotstxt.es/plugins/robotstxt-2fa/",
"description": "Adds per-role two-factor authentication to the WordPress login flow. Supports email codes, authenticator apps (TOTP), and recovery codes.",
- "changelog": "
1.5.2 - 2026-06-06
Added: OTP import tool — import authenticator secrets from Two Factor, WP 2FA, and Wordfence without users reconfiguring their app
Added: Admin notice banner when importable secrets are detected, dismissible per-admin or permanently
Fixed: Deactivating OTP from profile now deletes the secret cleanly without pre-generating a replacement
",
+ "changelog": "
1.6.0 - 2026-08-07
Added: Admin-only REST API (robotstxt-2fa/v1) — GET/PUT /settings to read/update configuration and GET /users to list users with their 2FA status, configured methods, required methods, and more.
Changed:wp 2fa list now shows Enabled, Methods, and Required columns plus a --required filter.
",
"sections": {
"description": "Adds per-role two-factor authentication to the WordPress login flow. Supports email codes, authenticator apps (TOTP), and recovery codes.",
- "changelog": "
1.5.2 - 2026-06-06
Added: OTP import tool — import authenticator secrets from Two Factor, WP 2FA, and Wordfence without users reconfiguring their app
Added: Admin notice banner when importable secrets are detected, dismissible per-admin or permanently
Fixed: Deactivating OTP from profile now deletes the secret cleanly without pre-generating a replacement
"
+ "changelog": "
1.6.0 - 2026-08-07
Added: Admin-only REST API (robotstxt-2fa/v1) — GET/PUT /settings to read/update configuration and GET /users to list users with their 2FA status, configured methods, required methods, and more.
Changed:wp 2fa list now shows Enabled, Methods, and Required columns plus a --required filter.