This commit is contained in:
Javier Casares 2026-06-05 14:06:16 +00:00
commit 968211baad
99 changed files with 15548 additions and 14530 deletions

View file

@ -1,33 +0,0 @@
# AGENT INSTRUCTIONS
This repository contains the WordPress plugin **2FA (by ROBOTSTXT)**. Follow these rules whenever you work on any file within this repository:
1. **Language**
- Write every piece of documentation, copy, and code comments in English.
2. **Code standards**
- All PHP code must comply with **PHPCS** and **WPCS**.
- Use tabs for indentation (no spaces).
- Ensure compatibility with **PHP 8.2** or higher.
- Provide proper **PHPDoc** annotations for classes, properties, and methods.
3. **WordPress security**
- Sanitize, validate, and escape all user-provided data.
- Include nonces in forms and verify them before processing submissions.
- Do not suppress validation or authentication errors.
4. **Plugin structure**
- Keep the code modular inside the `includes/` directory.
- Place admin-related logic in subdirectories under `includes/admin/`.
- Store presentational templates in `templates/`.
- Whenever new persistent data (options, tables, user meta, etc.) is introduced, update `uninstall.php` so the plugin removes it on uninstall.
5. **Testing and tooling**
- Run all available checks (PHPCS, PHPUnit, etc.) after making changes.
- Summarize the commands executed and their results in the final message.
6. **Documentation**
- Update `readme.txt` and `changelog.txt` whenever functional changes are introduced.
- Explain *why* when the reason for a piece of code is not obvious.
These instructions apply to the entire repository tree.

69
CHANGELOG.md Normal file
View file

@ -0,0 +1,69 @@
# Changelog
All notable changes to this project are documented in this file.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]
## [0.3.0] - 2026-06-05
### Added
- Delete-on-uninstall option in admin settings Data Management section (off by default — all data is preserved).
### Changed
- Network admin settings page now correctly saves to `wp_sitemeta` via a dedicated `network_admin_edit_` handler.
- Settings option stored with `autoload=false` — not needed on every page load.
- Recovery code preview transient TTL reduced from 0 (persistent) to 300 seconds (5 minutes).
### Security
- Email verification codes now use `random_int()` (CSPRNG) instead of `wp_rand()` (Mersenne Twister), consistent with recovery codes and OTP secrets.
### Fixed
- `get_required_capability()` now returns `manage_network_options` in network admin context.
- `bin/deploy.sh` now excludes `CLAUDE.md`, `AGENTS.md`, `README.md`, `DOCUMENTATION-*.md`, and `.phpunit.result.cache` from the ZIP artifact.
- `update.json` corrected: was shipping SMTP plugin data instead of 2FA plugin data.
## [0.2.0] - 2026-06-05
### Added
- Per-role 2FA method matrix: admins choose exactly which verification methods (email, OTP, recovery codes) are required for each WordPress role, with select-all row and column toggles.
- Authenticator app (TOTP) support: secrets stored as Base32, QR code rendered via `bacon/bacon-qr-code`, manual setup key displayed as fallback.
- Recovery codes: 10 single-use 8-digit codes, one-time display grid with copy-to-clipboard, mandatory confirmation before activation, auto-refresh when batch exhausted.
- Email verification codes: 7-digit codes, 10-minute expiry, 60-second resend throttle.
- Configurable verification frequency remembered per device fingerprint (every login / daily / weekly / monthly); administrators can lock the global schedule.
- Dedicated stage token (WP nonce) securing the 2FA screen between password validation and code entry.
- Method-switch links on the verification screen (OTP ↔ email ↔ recovery codes) without restarting the login.
- Multisite support: `Network: true` header; network admins set and lock enforcement settings.
- `uninstall.php` removes all plugin options and user meta on deletion.
- `bin/deploy.sh` for manual ZIP packaging.
- PHPUnit test suite with plugin-header tests.
### Changed
- Settings UI replaces flat forced-roles list with per-role method matrix; existing `force_roles` + `default_method` data is automatically migrated.
- Profile method checkboxes require explicit confirmation before activating (OTP: valid 6-digit code; recovery codes: enter one displayed code).
- Required methods indicated with a "required for your role" badge in the profile; checkboxes disabled and hidden inputs ensure values survive submission.
- Login screen hides username/password fields, removes Remember Me, focuses code input, and auto-submits when digit count is reached.
### Fixed
- QR generation errors caught and surfaced to administrators; graceful fallback to text setup key.
- Recovery-code preview persists via transient until explicitly acknowledged.
### Security
- All `$_POST`/`$_GET`/`$_SERVER` reads guarded with `is_string()` before passing to sanitize functions.
- PHPStan level 9 passes with zero errors; no mixed-type casts.
- `composer audit`: no known vulnerabilities in any dependency.
## [0.1.0] - 2024-04-08
### Added
- Initial plugin skeleton with placeholder classes for login handling, user profile, and admin settings.
- Initial documentation files.

View file

@ -1,2 +0,0 @@
# robotstxt-2fa
Simple 2FA WordPress plugin

View file

@ -1,42 +1,69 @@
# Changelog
## [Unreleased]
### Added
- Authenticator app support with stored secrets and QR provisioning powered by the optional `bacon/bacon-qr-code` library.
- Recovery code confirmation workflow that requires entering one of the freshly generated codes before hiding them.
- Single-use recovery codes with profile management, one-time display, and login validation.
- Dedicated verification stage token that secures 2FA screens and allows protected email code resends.
- Admin settings page with role-based enforcement controls for two-factor authentication.
- Uninstall routine that removes stored plugin options.
- Network-wide enforcement options for WordPress multisite installations.
- Email-based verification codes with throttled delivery and expiry handling.
- Configurable verification frequency that remembers trusted devices while allowing administrators to lock the schedule per site.
### Changed
- Profile method toggles now start unchecked and require validating authenticator and recovery codes before activation, with new inline prompts and regenerated secrets when options are disabled.
- The profile screen now keeps recovery codes visible in a two-column grid until one is confirmed, shows remaining counts, and automatically refreshes the list when the stored batch is exhausted.
- Email verification now displays the destination address alongside the method label.
- The login verification screen now hides the username/password fields, exposes a back-to-login link, and supports email code resends from a dedicated query-flagged URL.
- The verification stage now enforces authenticator app codes when they are enabled and exposes secure links to switch between OTP, email, and recovery-code challenges without restarting the login.
- Promoted the settings interface to a dedicated top-level Two-Factor Authentication menu for easier discovery.
- Adjusted the Two-Factor Authentication menu position so it appears within the plugins section of the admin navigation.
- User profile settings now persist preferences and automatically enforce role-based 2FA requirements.
- The login screen now auto-submits verification forms once the active method reaches its required length (six digits for OTP, seven for email, eight for recovery codes) and removes the Remember Me control during OTP checks.
- Recovery code requests now submit through the native profile form, regenerate codes server-side, and remember the section anchor on the redirect so the refreshed screen focuses the two-factor settings.
- The refreshed profile screen renders the newly issued ten codes inside a notice, including copy controls and updated status messaging, without relying on JavaScript-driven form submissions.
- The generator button now submits the profile form directly, honours core capability checks, and shares nonce validation with the existing profile workflow.
## [0.3.0] - 2026-06-05
### Added
- Delete-on-uninstall option (disabled by default — all plugin data is preserved on removal).
### Security
- Email verification codes now use `random_int()` (CSPRNG) for cryptographically secure code generation.
- Recovery code preview transient TTL reduced from indefinite to 5 minutes.
### Fixed
- Prevented a fatal error on the profile screen by exposing the recovery code batch size helper used during rendering.
- Corrected the recovery-code confirmation flow so previews persist until acknowledged and the confirmation code is accepted.
- Hardened authenticator QR generation by catching library errors and pointing administrators to the required bacon/bacon-qr-code ^3.0 dependency.
- Improved recovery-code AJAX error handling so failed requests surface localized messages instead of silently failing.
- Forced roles now see two-factor authentication enabled with the default email method selected in their profile, and per-user data is purged during uninstall.
- Restored the login verification handlers so the authenticate filter no longer triggers fatal errors and email challenges complete successfully.
- Ensured the profile recovery-code generator always reaches `admin-ajax.php`, even when localized data is missing, so the button reliably displays the codes inline.
- Network admin settings now save correctly via a dedicated handler writing to `wp_sitemeta`.
- Settings option registered with `autoload=false` to avoid loading on every page request.
- `update.json` corrected to reference the 2FA plugin instead of the SMTP plugin.
**Compatibility**
* WordPress: 6.4 – 7.1
* PHP: 8.2 – 8.5
**Tests**
* PHP Coding Standards: PHP_CodeSniffer 3.13.5 / WPCS 3.3.0
* PHPStan: level 9 — 0 errors
* PHPCompatibility: 8.2–8.5 — 0 issues
* PHPUnit: 9.6.34 — 42 tests, 109 assertions
## [0.2.0] - 2026-06-05
### Added
- Per-role 2FA method matrix in admin settings: administrators can now choose exactly which verification methods (email, authenticator app, recovery codes) are required for each WordPress role, with select-all row and column controls.
- Authenticator app (TOTP) support: stored secrets, QR code provisioning via `bacon/bacon-qr-code`, manual setup key display, and one-time activation confirmation.
- Recovery codes: 10 single-use 8-digit codes with profile management, one-time display grid, copy-to-clipboard, and mandatory confirmation before activation.
- Email-based verification codes with throttled delivery (60 s resend cooldown) and 10-minute expiry.
- Configurable verification frequency (every login, daily, weekly, or every 28 days) remembered per device fingerprint; administrators can lock the global schedule.
- Dedicated verification stage token (WP nonce) securing the 2FA screen between password validation and code submission.
- Secure method-switch links on the verification screen letting users change between OTP, email, and recovery-code challenges without restarting the login.
- Network-wide multisite support: network administrators can set and lock enforcement settings across all sites (`Network: true` header).
- Uninstall routine removing all plugin options and user meta.
- Admin settings page as a top-level menu with `manage_options` capability guard.
### Changed
- Settings page now uses the per-role method matrix instead of a flat forced-roles list; old `force_roles` + `default_method` data is automatically migrated on first read.
- Profile method checkboxes require explicit confirmation: OTP demands a valid 6-digit code, recovery codes demand entering one of the displayed codes before the method activates.
- Profile screen regenerates the OTP secret when the authenticator method is disabled and provides a "Generate new secret" button.
- Recovery code batch exhaustion now auto-generates a fresh batch and surfaces a confirmation prompt rather than locking the user out.
- Login screen hides the username/password fields, removes the Remember Me checkbox, and focuses the verification code input during the 2FA stage.
- Login form auto-submits once the input reaches the method's expected digit count.
### Fixed
- Hardened authenticator QR generation by catching library errors and guiding administrators to the required dependency.
- Recovery-code preview persists via transient until explicitly acknowledged; fixes cases where codes disappeared before confirmation.
## [0.1.0] - 2024-04-08
### Added
- Initial skeleton for the 2FA (by ROBOTSTXT) plugin.
- Initial documentation files (`readme.txt`, `AGENTS.md`, `changelog.txt`).
- Placeholder classes for login handling, user profile integration, and admin settings.

View file

@ -1,5 +0,0 @@
{
"require": {
"bacon/bacon-qr-code": "^3.0"
}
}

123
composer.lock generated
View file

@ -1,123 +0,0 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "9d7cd0dbebfa0273a358b926795e7b8a",
"packages": [
{
"name": "bacon/bacon-qr-code",
"version": "v3.0.1",
"source": {
"type": "git",
"url": "https://github.com/Bacon/BaconQrCode.git",
"reference": "f9cc1f52b5a463062251d666761178dbdb6b544f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/f9cc1f52b5a463062251d666761178dbdb6b544f",
"reference": "f9cc1f52b5a463062251d666761178dbdb6b544f",
"shasum": ""
},
"require": {
"dasprid/enum": "^1.0.3",
"ext-iconv": "*",
"php": "^8.1"
},
"require-dev": {
"phly/keep-a-changelog": "^2.12",
"phpunit/phpunit": "^10.5.11 || 11.0.4",
"spatie/phpunit-snapshot-assertions": "^5.1.5",
"squizlabs/php_codesniffer": "^3.9"
},
"suggest": {
"ext-imagick": "to generate QR code images"
},
"type": "library",
"autoload": {
"psr-4": {
"BaconQrCode\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-2-Clause"
],
"authors": [
{
"name": "Ben Scholzen 'DASPRiD'",
"email": "mail@dasprids.de",
"homepage": "https://dasprids.de/",
"role": "Developer"
}
],
"description": "BaconQrCode is a QR code generator for PHP.",
"homepage": "https://github.com/Bacon/BaconQrCode",
"support": {
"issues": "https://github.com/Bacon/BaconQrCode/issues",
"source": "https://github.com/Bacon/BaconQrCode/tree/v3.0.1"
},
"time": "2024-10-01T13:55:55+00:00"
},
{
"name": "dasprid/enum",
"version": "1.0.7",
"source": {
"type": "git",
"url": "https://github.com/DASPRiD/Enum.git",
"reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/DASPRiD/Enum/zipball/b5874fa9ed0043116c72162ec7f4fb50e02e7cce",
"reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce",
"shasum": ""
},
"require": {
"php": ">=7.1 <9.0"
},
"require-dev": {
"phpunit/phpunit": "^7 || ^8 || ^9 || ^10 || ^11",
"squizlabs/php_codesniffer": "*"
},
"type": "library",
"autoload": {
"psr-4": {
"DASPRiD\\Enum\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-2-Clause"
],
"authors": [
{
"name": "Ben Scholzen 'DASPRiD'",
"email": "mail@dasprids.de",
"homepage": "https://dasprids.de/",
"role": "Developer"
}
],
"description": "PHP 7.1 enum implementation",
"keywords": [
"enum",
"map"
],
"support": {
"issues": "https://github.com/DASPRiD/Enum/issues",
"source": "https://github.com/DASPRiD/Enum/tree/1.0.7"
},
"time": "2025-09-16T12:23:56+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": [],
"plugin-api-version": "2.6.0"
}

View file

@ -32,6 +32,17 @@ class Settings_Page {
*/
private const PAGE_SLUG = 'robotstxt-2fa-settings';
/**
* Verification methods available for per-role configuration.
*
* @var array<string, string>
*/
private const AVAILABLE_METHODS = array(
'email' => 'Email code',
'otp' => 'Authenticator app (OTP)',
'recovery_codes' => 'Recovery codes',
);
/**
* Register admin-related hooks.
*
@ -42,6 +53,7 @@ class Settings_Page {
if ( is_multisite() ) {
add_action( 'network_admin_menu', array( $this, 'register_network_menu' ) );
add_action( 'network_admin_edit_robotstxt_2fa_network_save', array( $this, 'handle_network_save' ) );
}
add_action( 'admin_init', array( $this, 'register_settings' ) );
@ -78,12 +90,20 @@ class Settings_Page {
}
settings_errors( self::OPTION_NAME );
$form_action = $this->is_network_context()
? network_admin_url( 'edit.php?action=robotstxt_2fa_network_save' )
: 'options.php';
?>
<div class="wrap">
<h1><?php esc_html_e( 'Two-Factor Authentication settings', 'robotstxt-2fa' ); ?></h1>
<form action="options.php" method="post">
<form action="<?php echo esc_url( $form_action ); ?>" method="post">
<?php
if ( $this->is_network_context() ) {
wp_nonce_field( 'robotstxt_2fa_network_save', 'robotstxt_2fa_network_nonce' );
} else {
settings_fields( self::OPTION_GROUP );
}
do_settings_sections( self::PAGE_SLUG );
submit_button();
?>
@ -105,6 +125,7 @@ class Settings_Page {
'type' => 'array',
'sanitize_callback' => array( $this, 'sanitize_settings' ),
'default' => $this->get_default_settings(),
'autoload' => false,
)
);
@ -116,9 +137,9 @@ class Settings_Page {
);
add_settings_field(
'robotstxt_2fa_force_roles',
__( 'Forced roles', 'robotstxt-2fa' ),
array( $this, 'render_force_roles_field' ),
'robotstxt_2fa_role_methods',
__( 'Required methods per role', 'robotstxt-2fa' ),
array( $this, 'render_role_methods_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_general'
);
@ -138,6 +159,21 @@ class Settings_Page {
self::PAGE_SLUG,
'robotstxt_2fa_general'
);
add_settings_section(
'robotstxt_2fa_data',
__( 'Data management', 'robotstxt-2fa' ),
array( $this, 'render_data_section' ),
self::PAGE_SLUG
);
add_settings_field(
'robotstxt_2fa_delete_on_uninstall',
__( 'Delete data on uninstall', 'robotstxt-2fa' ),
array( $this, 'render_delete_on_uninstall_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_data'
);
}
/**
@ -154,42 +190,186 @@ class Settings_Page {
}
/**
* Render forced roles field.
* Render the per-role method matrix field.
*
* Each row represents a role; each column represents a verification method.
* Checking a method for a role forces users of that role to verify with it.
* Leaving all methods unchecked for a role makes 2FA optional for that role.
* Row and column "select all" controls are provided via JavaScript.
*
* @return void
*/
public function render_force_roles_field(): void {
public function render_role_methods_field(): void {
$settings = $this->get_settings();
$selected_roles = array();
$disabled_attr = '';
if ( isset( $settings['force_roles'] ) && is_array( $settings['force_roles'] ) ) {
$selected_roles = $settings['force_roles'];
}
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
$disabled_attr = disabled( true, true, false );
}
$role_methods = $settings['role_methods'];
$roles = get_editable_roles();
$locked = $this->has_network_settings() && ! $this->is_network_context();
$disabled = $locked ? disabled( true, true, false ) : '';
if ( empty( $roles ) ) {
echo '<p class="description">' . esc_html__( 'No editable roles were found.', 'robotstxt-2fa' ) . '</p>';
return;
}
foreach ( $roles as $role_key => $role_details ) {
printf(
'<label><input type="checkbox" name="%1$s[force_roles][]" value="%2$s" %3$s %4$s/> %5$s</label><br />',
esc_attr( self::OPTION_NAME ),
esc_attr( $role_key ),
checked( in_array( $role_key, $selected_roles, true ), true, false ),
$disabled_attr,
esc_html( translate_user_role( $role_details['name'] ) )
$methods = array(
'email' => __( 'Email code', 'robotstxt-2fa' ),
'otp' => __( 'Authenticator app', 'robotstxt-2fa' ),
'recovery_codes' => __( 'Recovery codes', 'robotstxt-2fa' ),
);
?>
<table class="widefat fixed striped robotstxt-2fa-role-methods-table" id="robotstxt-2fa-role-methods-table" style="max-width:680px;">
<thead>
<tr>
<th><?php esc_html_e( 'Role', 'robotstxt-2fa' ); ?></th>
<?php foreach ( $methods as $method_key => $method_label ) : ?>
<th style="text-align:center;">
<?php echo esc_html( $method_label ); ?>
<?php if ( ! $locked ) : ?>
<br />
<label style="font-weight:normal;font-size:11px;cursor:pointer;">
<input
type="checkbox"
class="robotstxt-2fa-col-toggle"
data-2fa-col="<?php echo esc_attr( $method_key ); ?>"
style="margin-top:4px;"
/>
<?php esc_html_e( 'All', 'robotstxt-2fa' ); ?>
</label>
<?php endif; ?>
</th>
<?php endforeach; ?>
<?php if ( ! $locked ) : ?>
<th style="text-align:center;font-weight:normal;font-size:11px;">
<?php esc_html_e( 'All methods', 'robotstxt-2fa' ); ?>
</th>
<?php endif; ?>
</tr>
</thead>
<tbody>
<?php foreach ( $roles as $role_key => $role_details ) : ?>
<tr data-2fa-role="<?php echo esc_attr( $role_key ); ?>">
<td><?php echo esc_html( translate_user_role( $role_details['name'] ) ); ?></td>
<?php foreach ( $methods as $method_key => $method_label ) : ?>
<td style="text-align:center;">
<label>
<span class="screen-reader-text">
<?php
printf(
/* translators: 1: role name, 2: method name. */
esc_html__( '%1$s: require %2$s', 'robotstxt-2fa' ),
esc_html( translate_user_role( $role_details['name'] ) ),
esc_html( $method_label )
);
?>
</span>
<input
type="checkbox"
class="robotstxt-2fa-cell"
data-2fa-role="<?php echo esc_attr( $role_key ); ?>"
data-2fa-method="<?php echo esc_attr( $method_key ); ?>"
name="<?php echo esc_attr( self::OPTION_NAME ); ?>[role_methods][<?php echo esc_attr( $role_key ); ?>][]"
value="<?php echo esc_attr( $method_key ); ?>"
<?php checked( in_array( $method_key, $role_methods[ $role_key ] ?? array(), true ) ); ?>
<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function. ?>
/>
</label>
</td>
<?php endforeach; ?>
<?php if ( ! $locked ) : ?>
<td style="text-align:center;">
<label style="font-size:11px;cursor:pointer;">
<input
type="checkbox"
class="robotstxt-2fa-row-toggle"
data-2fa-row="<?php echo esc_attr( $role_key ); ?>"
/>
<?php esc_html_e( 'All', 'robotstxt-2fa' ); ?>
</label>
</td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p class="description">
<?php esc_html_e( 'Check which verification methods are required for each role. Users assigned to a role with at least one checked method must complete two-factor authentication using one of those methods. Roles with no methods checked leave the choice to the user.', 'robotstxt-2fa' ); ?>
</p>
<?php if ( ! $locked ) : ?>
<script>
(function () {
var table = document.getElementById( 'robotstxt-2fa-role-methods-table' );
if ( ! table ) { return; }
function cells() {
return table.querySelectorAll( '.robotstxt-2fa-cell' );
}
echo '<p class="description">' . esc_html__( 'Users assigned to the selected roles must enable two-factor authentication. Leave all roles unchecked to allow each user to decide whether to activate 2FA.', 'robotstxt-2fa' ) . '</p>';
function updateToggle( toggle, checked, total ) {
if ( total === 0 ) { return; }
toggle.indeterminate = checked > 0 && checked < total;
toggle.checked = checked === total;
}
function syncRow( roleKey ) {
var rowCells = table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-role="' + roleKey + '"]' );
var rowToggle = table.querySelector( '.robotstxt-2fa-row-toggle[data-2fa-row="' + roleKey + '"]' );
if ( ! rowToggle ) { return; }
var checked = 0;
rowCells.forEach( function ( c ) { if ( c.checked ) { checked++; } } );
updateToggle( rowToggle, checked, rowCells.length );
}
function syncCol( methodKey ) {
var colCells = table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-method="' + methodKey + '"]' );
var colToggle = table.querySelector( '.robotstxt-2fa-col-toggle[data-2fa-col="' + methodKey + '"]' );
if ( ! colToggle ) { return; }
var checked = 0;
colCells.forEach( function ( c ) { if ( c.checked ) { checked++; } } );
updateToggle( colToggle, checked, colCells.length );
}
/* Sync all toggles on load */
var allRoles = {}, allMethods = {};
cells().forEach( function ( c ) {
allRoles[ c.dataset['2faRole'] ] = true;
allMethods[ c.dataset['2faMethod'] ] = true;
} );
Object.keys( allRoles ).forEach( syncRow );
Object.keys( allMethods ).forEach( syncCol );
/* Row toggle: check / uncheck all cells in that role's row */
table.querySelectorAll( '.robotstxt-2fa-row-toggle' ).forEach( function ( toggle ) {
toggle.addEventListener( 'change', function () {
var roleKey = toggle.dataset['2faRow'];
table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-role="' + roleKey + '"]' ).forEach( function ( c ) {
c.checked = toggle.checked;
} );
Object.keys( allMethods ).forEach( syncCol );
} );
} );
/* Column toggle: check / uncheck all cells in that method's column */
table.querySelectorAll( '.robotstxt-2fa-col-toggle' ).forEach( function ( toggle ) {
toggle.addEventListener( 'change', function () {
var methodKey = toggle.dataset['2faCol'];
table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-method="' + methodKey + '"]' ).forEach( function ( c ) {
c.checked = toggle.checked;
} );
Object.keys( allRoles ).forEach( syncRow );
} );
} );
/* Individual cell: keep toggles in sync */
cells().forEach( function ( c ) {
c.addEventListener( 'change', function () {
syncRow( c.dataset['2faRole'] );
syncCol( c.dataset['2faMethod'] );
} );
} );
}());
</script>
<?php endif; ?>
<?php
}
/**
@ -197,7 +377,7 @@ class Settings_Page {
*
* @param mixed $raw_settings Raw settings submitted by the user.
*
* @return array<string, mixed>
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
*/
public function sanitize_settings( $raw_settings ): array {
$capability = $this->get_required_capability();
@ -213,86 +393,169 @@ class Settings_Page {
}
$raw_settings = is_array( $raw_settings ) ? $raw_settings : array();
$sanitized = $this->get_default_settings();
$current_settings = $this->get_settings();
$sanitized['force_roles'] = array();
if ( isset( $raw_settings['force_roles'] ) && is_array( $raw_settings['force_roles'] ) ) {
$editable_roles = array_keys( get_editable_roles() );
$valid_methods = array_keys( self::AVAILABLE_METHODS );
foreach ( $raw_settings['force_roles'] as $role_key ) {
$role_key = sanitize_key( $role_key );
$sanitized['role_methods'] = array();
if ( in_array( $role_key, $editable_roles, true ) ) {
$sanitized['force_roles'][] = $role_key;
if ( isset( $raw_settings['role_methods'] ) && is_array( $raw_settings['role_methods'] ) ) {
foreach ( $raw_settings['role_methods'] as $role_key => $raw_methods ) {
$role_key = sanitize_key( is_string( $role_key ) ? $role_key : '' );
if ( '' === $role_key || ! in_array( $role_key, $editable_roles, true ) ) {
continue;
}
if ( ! is_array( $raw_methods ) ) {
continue;
}
$methods = array();
foreach ( $raw_methods as $method ) {
$method = sanitize_key( is_string( $method ) ? $method : '' );
if ( in_array( $method, $valid_methods, true ) ) {
$methods[] = $method;
}
}
if ( ! empty( $methods ) ) {
$sanitized['role_methods'][ $role_key ] = array_values( array_unique( $methods ) );
}
}
}
$sanitized['force_roles'] = array_values( array_unique( $sanitized['force_roles'] ) );
$frequency_value = $current_settings['frequency'];
$frequency_value = $sanitized['frequency'];
if ( isset( $current_settings['frequency'] ) ) {
$frequency_value = (string) $current_settings['frequency'];
}
if ( isset( $raw_settings['frequency'] ) ) {
$frequency_value = (string) $raw_settings['frequency'];
if ( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ) {
$frequency_value = $raw_settings['frequency'];
}
$sanitized['frequency'] = Frequency_Options::sanitize( $frequency_value );
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
$sanitized['force_frequency'] = ! empty( $current_settings['force_frequency'] ?? false );
$sanitized['force_frequency'] = $current_settings['force_frequency'];
} elseif ( array_key_exists( 'force_frequency', $raw_settings ) ) {
$sanitized['force_frequency'] = '1' === (string) $raw_settings['force_frequency'];
$sanitized['force_frequency'] = '1' === ( is_scalar( $raw_settings['force_frequency'] ) ? (string) $raw_settings['force_frequency'] : '' );
}
if ( array_key_exists( 'delete_on_uninstall', $raw_settings ) ) {
$sanitized['delete_on_uninstall'] = '1' === ( is_scalar( $raw_settings['delete_on_uninstall'] ) ? (string) $raw_settings['delete_on_uninstall'] : '' );
}
return $sanitized;
}
/**
* Retrieve plugin settings.
* Retrieve plugin settings, migrating from legacy format when necessary.
*
* @return array<string, mixed>
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
*/
public function get_settings(): array {
$options = array();
if ( is_multisite() ) {
/** @var array<string, mixed>|false $network_options */
$network_options = get_site_option( self::OPTION_NAME, false );
if ( false !== $network_options && is_array( $network_options ) ) {
if ( is_array( $network_options ) ) {
$options = $network_options;
}
}
if ( empty( $options ) ) {
/** @var array<string, mixed> $options */
$options = get_option( self::OPTION_NAME, array() );
$raw = get_option( self::OPTION_NAME, array() );
if ( is_array( $raw ) ) {
$options = $raw;
}
}
return wp_parse_args( $options, $this->get_default_settings() );
return array(
'role_methods' => $this->resolve_role_methods( $options ),
'frequency' => Frequency_Options::sanitize( isset( $options['frequency'] ) && is_string( $options['frequency'] ) ? $options['frequency'] : '' ),
'force_frequency' => ! empty( $options['force_frequency'] ),
'delete_on_uninstall' => ! empty( $options['delete_on_uninstall'] ),
);
}
/**
* Retrieve default settings.
*
* @return array<string, mixed>
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
*/
private function get_default_settings(): array {
return array(
'force_roles' => array(),
'default_method' => 'email',
'role_methods' => array(),
'frequency' => Frequency_Options::FREQUENCY_SESSION,
'force_frequency' => false,
'delete_on_uninstall' => false,
);
}
/**
* Resolve role_methods from stored options, migrating legacy force_roles + default_method if needed.
*
* @param array<string, mixed> $options Raw stored options.
*
* @return array<string, array<int, string>>
*/
private function resolve_role_methods( array $options ): array {
$valid_methods = array_keys( self::AVAILABLE_METHODS );
if ( isset( $options['role_methods'] ) && is_array( $options['role_methods'] ) ) {
$role_methods = array();
foreach ( $options['role_methods'] as $role => $methods ) {
$role = is_string( $role ) ? sanitize_key( $role ) : '';
if ( '' === $role || ! is_array( $methods ) ) {
continue;
}
$clean = array();
foreach ( $methods as $m ) {
$m = is_string( $m ) ? sanitize_key( $m ) : '';
if ( in_array( $m, $valid_methods, true ) ) {
$clean[] = $m;
}
}
if ( ! empty( $clean ) ) {
$role_methods[ $role ] = array_values( array_unique( $clean ) );
}
}
return $role_methods;
}
// Migrate legacy force_roles + default_method to role_methods.
if ( isset( $options['force_roles'] ) && is_array( $options['force_roles'] ) ) {
$default_method = isset( $options['default_method'] ) && is_string( $options['default_method'] ) ? sanitize_key( $options['default_method'] ) : 'email';
if ( ! in_array( $default_method, $valid_methods, true ) ) {
$default_method = 'email';
}
$role_methods = array();
foreach ( $options['force_roles'] as $role ) {
$role = is_string( $role ) ? sanitize_key( $role ) : '';
if ( '' !== $role ) {
$role_methods[ $role ] = array( $default_method );
}
}
return $role_methods;
}
return array();
}
/**
* Render verification frequency field.
*
@ -300,7 +563,7 @@ class Settings_Page {
*/
public function render_frequency_field(): void {
$settings = $this->get_settings();
$selected = Frequency_Options::sanitize( (string) $settings['frequency'] );
$selected = $settings['frequency'];
$disabled_attr = '';
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
@ -309,7 +572,7 @@ class Settings_Page {
$options = Frequency_Options::get_options();
echo '<select name="' . esc_attr( self::OPTION_NAME ) . '[frequency]" ' . $disabled_attr . '>';
echo '<select name="' . esc_attr( self::OPTION_NAME ) . '[frequency]" ' . $disabled_attr . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function.
foreach ( $options as $value => $labels ) {
printf(
@ -334,7 +597,7 @@ class Settings_Page {
*/
public function render_force_frequency_field(): void {
$settings = $this->get_settings();
$is_checked = ! empty( $settings['force_frequency'] );
$is_checked = $settings['force_frequency'];
$disabled_attr = '';
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
@ -352,20 +615,88 @@ class Settings_Page {
'<label><input type="checkbox" name="%1$s[force_frequency]" value="1" %2$s %3$s/> %4$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $is_checked, true, false ),
$disabled_attr,
$disabled_attr, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function.
esc_html__( 'Prevent users from overriding the global verification frequency.', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'When enabled, users will see the profile frequency control disabled and must follow the global schedule.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the data management section description.
*
* @return void
*/
public function render_data_section(): void {
echo '<p>' . esc_html__( 'Control what happens to plugin data when the plugin is deleted.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the delete-on-uninstall checkbox.
*
* @return void
*/
public function render_delete_on_uninstall_field(): void {
$settings = $this->get_settings();
$is_checked = $settings['delete_on_uninstall'];
printf(
'<input type="hidden" name="%1$s[delete_on_uninstall]" value="0" />',
esc_attr( self::OPTION_NAME )
);
printf(
'<label><input type="checkbox" name="%1$s[delete_on_uninstall]" value="1" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $is_checked, true, false ),
esc_html__( 'Remove all plugin data when the plugin is deleted.', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'When checked, deleting this plugin will permanently remove all settings, per-user 2FA preferences, stored secrets, recovery codes, and verification history. This action cannot be undone. Leave unchecked (default) to preserve all data if you reinstall later.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Handle the network admin settings form submission.
*
* WordPress's Settings API does not work in network admin; this handler
* validates the nonce, sanitizes input, and saves via update_site_option().
*
* @return void
*/
public function handle_network_save(): void {
check_admin_referer( 'robotstxt_2fa_network_save', 'robotstxt_2fa_network_nonce' );
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) );
}
$raw = isset( $_POST[ self::OPTION_NAME ] ) && is_array( $_POST[ self::OPTION_NAME ] )
? wp_unslash( $_POST[ self::OPTION_NAME ] )
: array();
$sanitized = $this->sanitize_settings( $raw );
update_site_option( self::OPTION_NAME, $sanitized );
wp_safe_redirect(
add_query_arg(
array(
'page' => 'robotstxt-2fa-settings',
'updated' => 'true',
),
network_admin_url( 'admin.php' )
)
);
exit;
}
/**
* Determine the capability required to manage settings.
*
* @return string
*/
private function get_required_capability(): string {
return 'manage_options';
return $this->is_network_context() ? 'manage_network_options' : 'manage_options';
}
/**
@ -412,4 +743,3 @@ class Settings_Page {
);
}
}

View file

@ -77,16 +77,18 @@ class Email_Code_Sender {
$code = $this->generate_code();
$expires = $current_time + self::EXPIRATION_SECONDS;
$blog_name = wp_specialchars_decode( get_option( 'blogname', '' ), ENT_QUOTES );
$display_name = wp_strip_all_tags( $user->display_name ?: $user->user_login );
$email_subject = sprintf( __( '[%s] Your verification code', 'robotstxt-2fa' ), $blog_name ?: __( 'WordPress', 'robotstxt-2fa' ) );
$raw_blogname = get_option( 'blogname', '' );
$blog_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES );
$display_name = wp_strip_all_tags( ! empty( $user->display_name ) ? $user->display_name : $user->user_login );
/* translators: %s: site name. */
$email_subject = sprintf( __( '[%s] Your verification code', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'WordPress', 'robotstxt-2fa' ) );
$message_lines = array(
/* translators: %s: user display name. */
sprintf( __( 'Hi %s,', 'robotstxt-2fa' ), $display_name ),
'',
/* translators: %s: site name. */
sprintf( __( 'Use the following verification code to finish signing in to %s:', 'robotstxt-2fa' ), $blog_name ?: __( 'your site', 'robotstxt-2fa' ) ),
sprintf( __( 'Use the following verification code to finish signing in to %s:', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'your site', 'robotstxt-2fa' ) ),
'',
$code,
'',
@ -118,9 +120,9 @@ class Email_Code_Sender {
*/
public function verify_code( \WP_User $user, string $code ): bool {
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
$code = preg_replace( '/[^0-9]/', '', $code );
$code = preg_replace( '/[^0-9]/', '', $code ) ?? '';
if ( empty( $challenge['hash'] ) ) {
if ( '' === $challenge['hash'] ) {
return false;
}
@ -142,7 +144,7 @@ class Email_Code_Sender {
*/
private function generate_code(): string {
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
$code = (string) wp_rand( 0, (int) $max_value );
$code = (string) random_int( 0, $max_value );
return str_pad( $code, self::CODE_LENGTH, '0', STR_PAD_LEFT );
}

View file

@ -251,7 +251,7 @@ class Login_Form_Manager {
?>
<p class="robotstxt-2fa-login-field robotstxt-2fa-stage-field">
<label for="robotstxt-2fa-token"><?php esc_html_e( 'Verification code', 'robotstxt-2fa' ); ?><br />
<input type="tel" name="robotstxt_2fa_token" id="robotstxt-2fa-token" class="input" value="" size="<?php echo esc_attr( $code_length ); ?>" maxlength="<?php echo esc_attr( $code_length ); ?>" pattern="\d{<?php echo esc_attr( $code_length ); ?>}" inputmode="numeric" autocomplete="one-time-code" required />
<input type="tel" name="robotstxt_2fa_token" id="robotstxt-2fa-token" class="input" value="" size="<?php echo absint( $code_length ); ?>" maxlength="<?php echo absint( $code_length ); ?>" pattern="\d{<?php echo absint( $code_length ); ?>}" inputmode="numeric" autocomplete="one-time-code" required />
</label>
</p>
<?php
@ -298,14 +298,12 @@ class Login_Form_Manager {
);
}
if ( ! empty( $link_markup ) ) {
printf(
'<p class="robotstxt-2fa-alternate description robotstxt-2fa-stage-field">%1$s %2$s</p>',
esc_html__( 'Prefer a different verification method?', 'robotstxt-2fa' ),
wp_kses_post( implode( ' <span class="robotstxt-2fa-links-separator" aria-hidden="true">&bull;</span> ', $link_markup ) )
);
}
}
$back_url = wp_login_url( $this->get_requested_redirect() );
?>
@ -313,7 +311,18 @@ class Login_Form_Manager {
<a class="robotstxt-2fa-back-link" href="<?php echo esc_url( $back_url ); ?>"><?php esc_html_e( 'Back to login', 'robotstxt-2fa' ); ?></a>
<?php if ( 'email' === $method && '' !== $stage_token ) : ?>
<span class="robotstxt-2fa-links-separator" aria-hidden="true">&bull;</span>
<a class="robotstxt-2fa-resend-link" href="<?php echo esc_url( $this->get_stage_url( array( self::QUERY_RESEND => '1', self::QUERY_NOTICE => null ) ) ); ?>"><?php esc_html_e( 'Send the code again', 'robotstxt-2fa' ); ?></a>
<a class="robotstxt-2fa-resend-link" href="
<?php
echo esc_url(
$this->get_stage_url(
array(
self::QUERY_RESEND => '1',
self::QUERY_NOTICE => null,
)
)
);
?>
"><?php esc_html_e( 'Send the code again', 'robotstxt-2fa' ); ?></a>
<?php endif; ?>
</p>
<?php
@ -479,7 +488,7 @@ class Login_Form_Manager {
unset( $password );
if ( ! isset( $_POST[ self::LOGIN_NONCE_FIELD ] ) ) {
if ( ! isset( $_POST[ self::LOGIN_NONCE_FIELD ] ) || ! is_string( $_POST[ self::LOGIN_NONCE_FIELD ] ) ) {
return new \WP_Error( 'robotstxt_2fa_missing_nonce', __( 'The verification form is missing a security token. Please try again.', 'robotstxt-2fa' ) );
}
@ -520,7 +529,7 @@ class Login_Form_Manager {
$token = '';
if ( isset( $_POST['robotstxt_2fa_token'] ) ) {
if ( isset( $_POST['robotstxt_2fa_token'] ) && is_string( $_POST['robotstxt_2fa_token'] ) ) {
$token = sanitize_text_field( wp_unslash( $_POST['robotstxt_2fa_token'] ) );
}
@ -620,13 +629,16 @@ class Login_Form_Manager {
return;
}
if ( ! empty( $_GET[ self::QUERY_SWITCH ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage operations rely on dedicated nonce validation.
$has_switch = ! empty( $_GET[ self::QUERY_SWITCH ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Query flag only; nonce/stage-token verified inside process_method_switch().
$has_resend = ! empty( $_GET[ self::QUERY_RESEND ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Query flag only; stage-token verified before sending.
if ( $has_switch ) {
$this->process_method_switch();
return;
}
if ( empty( $_GET[ self::QUERY_RESEND ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Action is protected by a dedicated nonce below.
if ( ! $has_resend ) {
return;
}
@ -679,13 +691,15 @@ class Login_Form_Manager {
private function get_requested_method(): string {
$method = '';
if ( isset( $_REQUEST[ self::FIELD_METHOD ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage verification relies on dedicated nonce checks.
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Stage helper; nonce verified in calling context.
if ( isset( $_REQUEST[ self::FIELD_METHOD ] ) && is_string( $_REQUEST[ self::FIELD_METHOD ] ) ) {
$method = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_METHOD ] ) );
}
if ( '' === $method && isset( $_REQUEST[ self::QUERY_METHOD ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Value used only for display context.
if ( '' === $method && isset( $_REQUEST[ self::QUERY_METHOD ] ) && is_string( $_REQUEST[ self::QUERY_METHOD ] ) ) {
$method = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_METHOD ] ) );
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ( '' === $method ) {
$method = 'email';
@ -716,8 +730,14 @@ 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.
*
* @param \WP_User $user User attempting to authenticate.
* @param array<string,mixed>|null $user_settings Optional preloaded settings.
* @param array{enabled: bool, methods: array<int, string>, frequency: string}|null $user_settings Optional preloaded settings.
*
* @return array<int, string>
*/
@ -726,44 +746,58 @@ class Login_Form_Manager {
$user_settings = $this->user_settings_repository->get_user_settings( $user->ID );
}
$is_forced = $this->config->is_two_factor_forced_for_user( $user );
$enabled = $is_forced ? true : ! empty( $user_settings['enabled'] );
$required_methods = $this->config->get_required_methods_for_user( $user );
$is_forced = ! empty( $required_methods );
$enabled = $is_forced ? true : $user_settings['enabled'];
if ( ! $enabled ) {
return array();
}
$methods = array();
// Normalize user's profile methods to login-stage slugs.
$profile_methods = array();
if ( ! empty( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ) {
$methods = $user_settings['methods'];
foreach ( $user_settings['methods'] as $method_key ) {
$slug = $this->normalize_method_slug( $method_key );
if ( '' !== $slug ) {
$profile_methods[] = $slug;
}
}
if ( $is_forced && empty( $methods ) ) {
$methods = array( $this->config->get_default_method() );
$profile_methods = array_values( array_unique( $profile_methods ) );
// When forced, restrict to methods required by the user's roles.
if ( $is_forced ) {
$required_slugs = array();
foreach ( $required_methods as $method ) {
$slug = $this->normalize_method_slug( $method );
if ( '' !== $slug ) {
$required_slugs[] = $slug;
}
}
$normalized = array();
$required_slugs = array_values( array_unique( $required_slugs ) );
foreach ( $methods as $method_key ) {
$normalized_method = $this->normalize_method_slug( (string) $method_key );
// Prefer the intersection of profile-enabled and role-required methods.
$candidate_methods = array_values( array_intersect( $profile_methods, $required_slugs ) );
if ( '' === $normalized_method ) {
continue;
// Fall back to all role-required methods if none are set up yet.
if ( empty( $candidate_methods ) ) {
$candidate_methods = $required_slugs;
}
} else {
$candidate_methods = $profile_methods;
}
$normalized[] = $normalized_method;
}
$normalized = array_values( array_unique( $normalized ) );
// Filter to methods the system can actually deliver right now.
$available = array();
foreach ( $normalized as $method ) {
foreach ( $candidate_methods as $method ) {
if ( 'email' === $method ) {
$email = sanitize_email( $user->user_email );
if ( '' !== $email ) {
if ( '' !== sanitize_email( $user->user_email ) ) {
$available[] = 'email';
}
} elseif ( 'otp' === $method ) {
@ -853,31 +887,19 @@ class Login_Form_Manager {
return '';
}
$preferred = $this->normalize_method_slug( $this->config->get_default_method() );
$priority = array_values(
array_filter(
array_unique(
array_merge(
array( 'otp' ),
array( $preferred ),
array( 'email', 'recovery' )
)
)
)
);
foreach ( $priority as $method ) {
if ( 'recovery' === $method && count( $methods ) > 1 ) {
continue;
}
// Prefer OTP (most secure), then email, then recovery codes (last resort).
foreach ( array( 'otp', 'email' ) as $method ) {
if ( in_array( $method, $methods, true ) ) {
return $method;
}
}
return (string) $methods[0];
// Use recovery only when it is the sole option.
if ( in_array( 'recovery', $methods, true ) ) {
return 'recovery';
}
return $methods[0];
}
/**
@ -960,7 +982,8 @@ class Login_Form_Manager {
* @return bool
*/
private function is_verification_stage(): bool {
if ( isset( $_REQUEST[ self::FIELD_STAGE ] ) ) {
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Stage-detection only; nonce verified in calling context.
if ( isset( $_REQUEST[ self::FIELD_STAGE ] ) && is_string( $_REQUEST[ self::FIELD_STAGE ] ) ) {
$stage = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_STAGE ] ) );
if ( self::STAGE_VERIFY === $stage ) {
@ -968,13 +991,14 @@ class Login_Form_Manager {
}
}
if ( isset( $_REQUEST[ self::QUERY_STAGE ] ) ) {
if ( isset( $_REQUEST[ self::QUERY_STAGE ] ) && is_string( $_REQUEST[ self::QUERY_STAGE ] ) ) {
$stage = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_STAGE ] ) );
if ( self::STAGE_VERIFY === $stage ) {
return true;
}
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
return false;
}
@ -985,11 +1009,12 @@ class Login_Form_Manager {
* @return bool
*/
private function is_verification_submission(): bool {
if ( ! isset( $_POST[ self::FIELD_STAGE ] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage flag only; nonce verified in maybe_complete_verification().
if ( ! isset( $_POST[ self::FIELD_STAGE ] ) || ! is_string( $_POST[ self::FIELD_STAGE ] ) ) {
return false;
}
$stage = sanitize_key( wp_unslash( $_POST[ self::FIELD_STAGE ] ) );
$stage = sanitize_key( wp_unslash( $_POST[ self::FIELD_STAGE ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
return self::STAGE_VERIFY === $stage;
}
@ -1002,13 +1027,15 @@ class Login_Form_Manager {
private function get_requested_login(): string {
$login = '';
if ( isset( $_REQUEST[ self::FIELD_LOGIN ] ) ) {
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Login identifier helper; nonce verified in calling context.
if ( isset( $_REQUEST[ self::FIELD_LOGIN ] ) && is_string( $_REQUEST[ self::FIELD_LOGIN ] ) ) {
$login = sanitize_user( wp_unslash( $_REQUEST[ self::FIELD_LOGIN ] ), true );
}
if ( '' === $login && isset( $_REQUEST[ self::QUERY_LOGIN ] ) ) {
if ( '' === $login && isset( $_REQUEST[ self::QUERY_LOGIN ] ) && is_string( $_REQUEST[ self::QUERY_LOGIN ] ) ) {
$login = sanitize_user( wp_unslash( $_REQUEST[ self::QUERY_LOGIN ] ), true );
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
return $login;
}
@ -1021,13 +1048,15 @@ class Login_Form_Manager {
private function get_requested_stage_token(): string {
$token = '';
if ( isset( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ) {
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Stage-token helper; token itself is the nonce verified in validate_stage_token().
if ( isset( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) && is_string( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ) {
$token = sanitize_text_field( wp_unslash( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) );
}
if ( '' === $token && isset( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ) {
if ( '' === $token && isset( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) && is_string( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ) {
$token = sanitize_text_field( wp_unslash( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) );
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
return $token;
}
@ -1038,11 +1067,12 @@ class Login_Form_Manager {
* @return string
*/
private function get_requested_notice(): string {
if ( ! isset( $_REQUEST[ self::QUERY_NOTICE ] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Notice slug helper; display-only, not security-sensitive.
if ( ! isset( $_REQUEST[ self::QUERY_NOTICE ] ) || ! is_string( $_REQUEST[ self::QUERY_NOTICE ] ) ) {
return '';
}
return sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_NOTICE ] ) );
return sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_NOTICE ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
}
/**
@ -1063,11 +1093,13 @@ class Login_Form_Manager {
* @return string
*/
private function get_requested_redirect(): string {
if ( ! isset( $_REQUEST['redirect_to'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Value is only echoed back.
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- redirect_to is a standard WP login parameter; value is passed through esc_url_raw.
if ( ! isset( $_REQUEST['redirect_to'] ) || ! is_string( $_REQUEST['redirect_to'] ) ) {
return '';
}
return esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) );
// phpcs:enable WordPress.Security.NonceVerification.Recommended
}
/**
@ -1110,7 +1142,7 @@ class Login_Form_Manager {
$args = array_filter(
$args,
static function ( $value ) {
return null !== $value && '' !== $value;
return '' !== $value;
}
);
@ -1121,7 +1153,7 @@ class Login_Form_Manager {
* Determine the effective verification frequency for the current user.
*
* @param \WP_User $user Authenticated user object.
* @param array<string, mixed> $user_settings Stored per-user preferences.
* @param array{enabled: bool, methods: array<int, string>, frequency: string} $user_settings Stored per-user preferences.
*
* @return string
*/
@ -1132,8 +1164,8 @@ class Login_Form_Manager {
return $this->config->get_frequency();
}
if ( ! empty( $user_settings['frequency'] ) ) {
return Frequency_Options::sanitize( (string) $user_settings['frequency'] );
if ( '' !== $user_settings['frequency'] ) {
return Frequency_Options::sanitize( $user_settings['frequency'] );
}
return $this->config->get_frequency();
@ -1148,15 +1180,16 @@ class Login_Form_Manager {
$ip = '';
if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
$ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
$raw_addr = is_string( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
$ip = sanitize_text_field( wp_unslash( $raw_addr ) );
$ip = wp_privacy_anonymize_ip( $ip );
$ip = is_string( $ip ) ? $ip : '';
}
$user_agent = '';
if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
$user_agent = sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) );
$raw_ua = is_string( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
$user_agent = sanitize_text_field( wp_unslash( $raw_ua ) );
}
$user_agent = strtolower( substr( $user_agent, 0, 255 ) );

View file

@ -153,7 +153,8 @@ class OTP_Manager {
return '';
}
$site_name = wp_specialchars_decode( get_option( 'blogname', '' ), ENT_QUOTES );
$raw_blogname = get_option( 'blogname', '' );
$site_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES );
$site_name = '' !== $site_name ? $site_name : __( 'WordPress Site', 'robotstxt-2fa' );
$label = '' !== $user->user_email ? $user->user_email : $user->user_login;
@ -238,6 +239,14 @@ class OTP_Manager {
return $writer->writeString( $data );
} catch ( \Throwable $exception ) {
/**
* Fires when QR code SVG generation fails.
*
* @since 0.2.0
*
* @param \Throwable $exception The caught exception.
* @param string $data The provisioning URI that failed to render.
*/
do_action( 'robotstxt_2fa_qr_generation_failed', $exception, $data );
}
@ -267,7 +276,7 @@ class OTP_Manager {
$chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT );
}
$encoded .= $alphabet[ bindec( $chunk ) ];
$encoded .= $alphabet[ (int) bindec( $chunk ) ];
}
return $encoded;
@ -309,7 +318,7 @@ class OTP_Manager {
continue;
}
$binary .= chr( bindec( $chunk ) );
$binary .= chr( (int) bindec( $chunk ) & 0xFF );
}
return $binary;
@ -329,7 +338,9 @@ class OTP_Manager {
$hash = hash_hmac( 'sha1', $binary_counter, $secret, true );
$offset = ord( substr( $hash, -1 ) ) & 0x0F;
$segment = substr( $hash, $offset, 4 );
$value = unpack( 'N', $segment )[1] & 0x7FFFFFFF;
$unpacked = unpack( 'N', $segment );
$raw_value = is_array( $unpacked ) && isset( $unpacked[1] ) && is_int( $unpacked[1] ) ? $unpacked[1] : 0;
$value = $raw_value & 0x7FFFFFFF;
$code = $value % ( 10 ** self::CODE_DIGITS );
return str_pad( (string) $code, self::CODE_DIGITS, '0', STR_PAD_LEFT );

View file

@ -35,9 +35,10 @@ class Profile_Settings {
private const SECTION_ANCHOR = 'robotstxt-2fa-settings';
/**
* Lifetime for temporary recovery-code previews in seconds (0 = persistent until cleared).
* Lifetime for temporary recovery-code previews in seconds.
* Codes are shown once and must be confirmed; 5 minutes is enough.
*/
private const PREVIEW_TTL = 0;
private const PREVIEW_TTL = 300;
/**
* Form field used to submit OTP verification codes.
@ -168,6 +169,7 @@ class Profile_Settings {
$user_settings = $this->user_settings_repository->get_user_settings( $user->ID );
$is_forced = $this->config->is_two_factor_forced_for_user( $user );
$required_methods = $this->config->get_required_methods_for_user( $user );
$is_enabled = $is_forced ? true : (bool) $user_settings['enabled'];
$enabled_methods = $is_enabled ? $user_settings['methods'] : array();
$available_methods = $this->get_available_methods( $user );
@ -185,8 +187,10 @@ class Profile_Settings {
$otp_enabled = in_array( 'otp', $enabled_methods, true );
$recovery_enabled = in_array( 'recovery_codes', $enabled_methods, true );
$date_format = (string) get_option( 'date_format' );
$time_format = (string) get_option( 'time_format' );
$raw_date_format = get_option( 'date_format' );
$raw_time_format = get_option( 'time_format' );
$date_format = is_string( $raw_date_format ) ? $raw_date_format : '';
$time_format = is_string( $raw_time_format ) ? $raw_time_format : '';
$datetime_format = trim( $date_format . ' ' . $time_format );
if ( '' === $datetime_format ) {
@ -198,8 +202,8 @@ class Profile_Settings {
$recovery_total = $this->recovery_codes->get_codes_per_batch();
$last_generated = $this->recovery_codes->get_last_generated_timestamp( $user->ID );
$preview = $this->get_recovery_preview( $user->ID );
$preview_codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $preview['codes'] : array();
$preview_generated = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0;
$preview_codes = $preview['codes'];
$preview_generated = $preview['generated_at'];
if ( $preview_generated > 0 ) {
$last_generated = $preview_generated;
@ -223,8 +227,8 @@ class Profile_Settings {
$unused_count = $this->recovery_codes->count_unused_codes( $user->ID );
$preview = $this->get_recovery_preview( $user->ID );
$preview_codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $preview['codes'] : array();
$preview_generated = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0;
$preview_codes = $preview['codes'];
$preview_generated = $preview['generated_at'];
if ( $preview_generated > 0 ) {
$last_generated = $preview_generated;
@ -235,8 +239,8 @@ class Profile_Settings {
if ( ! $recovery_enabled && empty( $preview_codes ) ) {
$preview = $this->prepare_recovery_preview( $user );
$preview_codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $preview['codes'] : array();
$preview_generated = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0;
$preview_codes = $preview['codes'];
$preview_generated = $preview['generated_at'];
if ( $preview_generated > 0 ) {
$last_generated = $preview_generated;
@ -247,7 +251,8 @@ class Profile_Settings {
$unused_count = count( $preview_codes );
}
$last_generated_formatted = $last_generated > 0 ? wp_date( $datetime_format, $last_generated ) : '';
$wp_date_result = $last_generated > 0 ? wp_date( $datetime_format, $last_generated ) : false;
$last_generated_formatted = ( false !== $wp_date_result ) ? $wp_date_result : '';
$has_preview = ! empty( $preview_codes );
$otp_secret = $otp_enabled ? $this->otp_manager->get_secret( $user->ID ) : $this->otp_manager->ensure_secret( $user );
@ -305,10 +310,17 @@ class Profile_Settings {
<legend class="screen-reader-text">
<span><?php esc_html_e( 'Select the two-factor authentication methods you want to enable.', 'robotstxt-2fa' ); ?></span>
</legend>
<?php $email_required = in_array( 'email', $required_methods, true ); ?>
<?php if ( $email_required ) : ?>
<input type="hidden" name="robotstxt_2fa_settings[methods][]" value="email" />
<?php endif; ?>
<div class="robotstxt-2fa-method robotstxt-2fa-method-email">
<label for="robotstxt-2fa-method-email">
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-email" value="email" <?php checked( $email_enabled, true ); ?> <?php disabled( ! $is_enabled, true ); ?> />
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-email" value="email" <?php checked( $email_enabled || $email_required, true ); ?> <?php disabled( ! $is_enabled || $email_required, true ); ?> />
<span class="robotstxt-2fa-method-label"><?php echo esc_html( $email_label ); ?></span>
<?php if ( $email_required ) : ?>
<span class="robotstxt-2fa-required-badge description"> — <?php esc_html_e( 'required for your role', 'robotstxt-2fa' ); ?></span>
<?php endif; ?>
</label>
<?php if ( ! empty( $available_methods['email']['description'] ) ) : ?>
<p class="description">
@ -316,10 +328,17 @@ class Profile_Settings {
</p>
<?php endif; ?>
</div>
<?php $otp_required = in_array( 'otp', $required_methods, true ); ?>
<?php if ( $otp_required && $otp_enabled ) : ?>
<input type="hidden" name="robotstxt_2fa_settings[methods][]" value="otp" />
<?php endif; ?>
<div class="robotstxt-2fa-method robotstxt-2fa-method-otp">
<label for="robotstxt-2fa-method-otp">
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-otp" value="otp" <?php checked( $otp_enabled, true ); ?> <?php disabled( ! $is_enabled, true ); ?> />
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-otp" value="otp" <?php checked( $otp_enabled, true ); ?> <?php disabled( ! $is_enabled || ( $otp_required && $otp_enabled ), true ); ?> />
<span class="robotstxt-2fa-method-label"><?php echo esc_html( $available_methods['otp']['label'] ); ?></span>
<?php if ( $otp_required ) : ?>
<span class="robotstxt-2fa-required-badge description"> — <?php esc_html_e( 'required for your role', 'robotstxt-2fa' ); ?></span>
<?php endif; ?>
</label>
<?php if ( ! empty( $available_methods['otp']['description'] ) ) : ?>
<p class="description">
@ -354,7 +373,7 @@ class Profile_Settings {
<label class="screen-reader-text" for="robotstxt-2fa-otp-code">
<?php esc_html_e( 'Authenticator code', 'robotstxt-2fa' ); ?>
</label>
<input type="text" name="<?php echo esc_attr( self::OTP_CODE_FIELD ); ?>" id="robotstxt-2fa-otp-code" pattern="\\d{<?php echo esc_attr( $otp_digits ); ?>}" inputmode="numeric" autocomplete="one-time-code" />
<input type="text" name="<?php echo esc_attr( self::OTP_CODE_FIELD ); ?>" id="robotstxt-2fa-otp-code" pattern="\\d{<?php echo absint( $otp_digits ); ?>}" inputmode="numeric" autocomplete="one-time-code" />
<p class="description">
<?php esc_html_e( 'Need a different pairing? Use the button below to generate a new QR code.', 'robotstxt-2fa' ); ?>
</p>
@ -363,10 +382,17 @@ class Profile_Settings {
<?php esc_html_e( 'Generate new secret', 'robotstxt-2fa' ); ?>
</button>
</div>
<?php $recovery_required = in_array( 'recovery_codes', $required_methods, true ); ?>
<?php if ( $recovery_required ) : ?>
<input type="hidden" name="robotstxt_2fa_settings[methods][]" value="recovery_codes" />
<?php endif; ?>
<div class="robotstxt-2fa-method robotstxt-2fa-method-recovery">
<label for="robotstxt-2fa-method-recovery">
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-recovery" value="recovery_codes" <?php checked( $recovery_enabled, true ); ?> <?php disabled( ! $is_enabled, true ); ?> />
<input type="checkbox" name="robotstxt_2fa_settings[methods][]" id="robotstxt-2fa-method-recovery" value="recovery_codes" <?php checked( $recovery_enabled || $recovery_required, true ); ?> <?php disabled( ! $is_enabled || $recovery_required, true ); ?> />
<span class="robotstxt-2fa-method-label"><?php echo esc_html( $available_methods['recovery_codes']['label'] ); ?></span>
<?php if ( $recovery_required ) : ?>
<span class="robotstxt-2fa-required-badge description"> — <?php esc_html_e( 'required for your role', 'robotstxt-2fa' ); ?></span>
<?php endif; ?>
</label>
<?php if ( ! empty( $available_methods['recovery_codes']['description'] ) ) : ?>
<p class="description">
@ -431,7 +457,7 @@ class Profile_Settings {
<label class="robotstxt-2fa-recovery-confirm-label" for="robotstxt-2fa-recovery-confirm">
<?php esc_html_e( 'Enter one of the codes above to confirm you saved them.', 'robotstxt-2fa' ); ?>
</label>
<input type="text" name="<?php echo esc_attr( self::RECOVERY_CONFIRM_FIELD ); ?>" id="robotstxt-2fa-recovery-confirm" pattern="\\d{<?php echo esc_attr( $recovery_code_length ); ?>}" inputmode="numeric" autocomplete="one-time-code" />
<input type="text" name="<?php echo esc_attr( self::RECOVERY_CONFIRM_FIELD ); ?>" id="robotstxt-2fa-recovery-confirm" pattern="\\d{<?php echo absint( $recovery_code_length ); ?>}" inputmode="numeric" autocomplete="one-time-code" />
</div>
<p class="description">
<?php esc_html_e( 'Once confirmed, the codes disappear from this page but remain valid until you use them.', 'robotstxt-2fa' ); ?>
@ -490,6 +516,35 @@ class Profile_Settings {
</tr>
</tbody>
</table>
<?php if ( ! $is_forced ) : ?>
<script>
(function () {
var toggle = document.getElementById( 'robotstxt-2fa-enabled' );
var methods = document.querySelector( '.robotstxt-2fa-profile-methods' );
var freq = document.querySelector( '.robotstxt-2fa-profile-frequency' );
if ( ! toggle || ! methods ) { return; }
function applyState() {
var on = toggle.checked;
methods.querySelectorAll( 'input, select, button' ).forEach( function ( el ) {
var isRequired = el.closest( '[data-2fa-required]' );
if ( ! isRequired ) {
el.disabled = ! on;
}
} );
if ( freq ) {
freq.querySelectorAll( 'select' ).forEach( function ( el ) {
el.disabled = ! on || <?php echo $frequency_forced ? 'true' : 'false'; ?>;
} );
}
}
toggle.addEventListener( 'change', applyState );
applyState();
}());
</script>
<?php endif; ?>
<?php
}
@ -498,12 +553,19 @@ class Profile_Settings {
*
* @param \WP_User $user User being edited.
*
* @return array<string, mixed>
* @return array{codes: array<int, string>, generated_at: int}
*/
private function prepare_recovery_preview( \WP_User $user ): array {
try {
$result = $this->recovery_codes->regenerate_codes_for_user( $user );
} catch ( \Throwable $exception ) {
/**
* Fires when recovery code generation fails.
*
* @since 0.2.0
*
* @param \Throwable $exception The caught exception.
*/
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
return $this->get_recovery_preview( $user->ID );
}
@ -512,7 +574,7 @@ class Profile_Settings {
return $this->get_recovery_preview( $user->ID );
}
$this->remember_recovery_preview( $user->ID, $result['codes'], (int) $result['generated_at'] );
$this->remember_recovery_preview( $user->ID, $result['codes'], $result['generated_at'] );
$this->focus_section = true;
add_settings_error(
@ -529,13 +591,13 @@ class Profile_Settings {
* Reset recovery codes and user settings when all codes were consumed.
*
* @param \WP_User $user User being edited.
* @param array<string, mixed> $user_settings Stored user settings prior to the reset.
* @param array{enabled: bool, methods: array<int, string>, frequency: string} $user_settings Stored user settings prior to the reset.
* @param bool $is_forced Whether two-factor authentication is enforced for the user.
*
* @return void
*/
private function reset_recovery_codes_after_exhaustion( \WP_User $user, array $user_settings, bool $is_forced ): void {
$current_methods = isset( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ? $user_settings['methods'] : array();
$current_methods = $user_settings['methods'];
$remaining_methods = array_values( array_diff( $current_methods, array( 'recovery_codes' ) ) );
$enabled_flag = $is_forced ? true : ( ! empty( $remaining_methods ) && ! empty( $user_settings['enabled'] ) );
$frequency_value = $this->resolve_selected_frequency( $user_settings );
@ -552,6 +614,13 @@ class Profile_Settings {
try {
$result = $this->recovery_codes->regenerate_codes_for_user( $user );
} catch ( \Throwable $exception ) {
/**
* Fires when recovery code generation fails.
*
* @since 0.2.0
*
* @param \Throwable $exception The caught exception.
*/
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
add_settings_error(
'robotstxt-2fa',
@ -563,7 +632,7 @@ class Profile_Settings {
}
if ( ! empty( $result['codes'] ) ) {
$this->remember_recovery_preview( $user->ID, $result['codes'], (int) $result['generated_at'] );
$this->remember_recovery_preview( $user->ID, $result['codes'], $result['generated_at'] );
}
$this->focus_section = true;
@ -591,7 +660,7 @@ class Profile_Settings {
return;
}
if ( ! isset( $_POST[ self::NONCE_FIELD ] ) ) {
if ( ! isset( $_POST[ self::NONCE_FIELD ] ) || ! is_string( $_POST[ self::NONCE_FIELD ] ) ) {
return;
}
@ -607,19 +676,16 @@ class Profile_Settings {
return;
}
$submitted_settings = array();
$raw_settings = filter_input( INPUT_POST, 'robotstxt_2fa_settings', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
if ( is_array( $raw_settings ) ) {
$submitted_settings = map_deep( wp_unslash( $raw_settings ), 'sanitize_text_field' );
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above.
$raw_settings = isset( $_POST['robotstxt_2fa_settings'] ) && is_array( $_POST['robotstxt_2fa_settings'] )
? wp_unslash( $_POST['robotstxt_2fa_settings'] ) // phpcs:ignore WordPress.Security.NonceVerification.Missing
: array();
$requested_methods = array();
if ( isset( $submitted_settings['methods'] ) && is_array( $submitted_settings['methods'] ) ) {
foreach ( $submitted_settings['methods'] as $method_key ) {
$method_key = sanitize_key( $method_key );
if ( isset( $raw_settings['methods'] ) && is_array( $raw_settings['methods'] ) ) {
foreach ( $raw_settings['methods'] as $raw_method ) {
$method_key = sanitize_key( is_string( $raw_method ) ? $raw_method : '' );
if ( '' !== $method_key ) {
$requested_methods[] = $method_key;
@ -629,15 +695,24 @@ class Profile_Settings {
$requested_methods = array_values( array_unique( $requested_methods ) );
$enabled = ! empty( $submitted_settings['enabled'] );
$is_forced = $this->config->is_two_factor_forced_for_user( $user );
$required_methods = $this->config->get_required_methods_for_user( $user );
$is_forced = ! empty( $required_methods );
// Merge role-required methods into the submission so they cannot be dropped server-side.
foreach ( $required_methods as $req_method ) {
if ( ! in_array( $req_method, $requested_methods, true ) ) {
$requested_methods[] = $req_method;
}
}
$enabled = ! empty( $raw_settings['enabled'] );
if ( $is_forced ) {
$enabled = true;
}
$user_settings = $this->user_settings_repository->get_user_settings( $user_id );
$previous_methods = isset( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ? $user_settings['methods'] : array();
$previous_methods = $user_settings['methods'];
$otp_was_enabled = in_array( 'otp', $previous_methods, true );
$recovery_was_enabled = in_array( 'recovery_codes', $previous_methods, true );
@ -650,13 +725,13 @@ class Profile_Settings {
$otp_code = '';
if ( isset( $_POST[ self::OTP_CODE_FIELD ] ) ) {
if ( isset( $_POST[ self::OTP_CODE_FIELD ] ) && is_string( $_POST[ self::OTP_CODE_FIELD ] ) ) {
$otp_code = sanitize_text_field( wp_unslash( $_POST[ self::OTP_CODE_FIELD ] ) );
}
$recovery_code_input = '';
if ( isset( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) ) {
if ( isset( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) && is_string( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) ) {
$recovery_code_input = sanitize_text_field( wp_unslash( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) );
}
@ -796,8 +871,8 @@ class Profile_Settings {
$frequency = Frequency_Options::FREQUENCY_SESSION;
if ( isset( $submitted_settings['frequency'] ) ) {
$frequency = Frequency_Options::sanitize( (string) $submitted_settings['frequency'] );
if ( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ) {
$frequency = Frequency_Options::sanitize( sanitize_key( wp_unslash( $raw_settings['frequency'] ) ) );
}
if ( $this->config->is_frequency_forced() ) {
@ -890,21 +965,21 @@ class Profile_Settings {
*
* @param int $user_id User identifier.
*
* @return array<string, mixed>
* @return array{codes: array<int, string>, generated_at: int}
*/
private function get_recovery_preview( int $user_id ): array {
$key = $this->get_recovery_preview_transient_key( $user_id );
$preview = get_transient( $key );
if ( false === $preview || ! is_array( $preview ) ) {
if ( ! is_array( $preview ) ) {
return array(
'codes' => array(),
'generated_at' => 0,
);
}
$codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $this->normalize_preview_codes( $preview['codes'] ) : array();
$generated_at = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0;
$codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $this->normalize_preview_codes( array_values( $preview['codes'] ) ) : array();
$generated_at = isset( $preview['generated_at'] ) && is_int( $preview['generated_at'] ) ? $preview['generated_at'] : 0;
return array(
'codes' => $codes,
@ -1001,7 +1076,7 @@ class Profile_Settings {
$length = $this->recovery_codes->get_code_length();
foreach ( $codes as $code ) {
$digits = preg_replace( '/[^0-9]/', '', (string) $code );
$digits = preg_replace( '/[^0-9]/', '', is_string( $code ) ? $code : '' );
if ( null === $digits ) {
continue;
@ -1069,37 +1144,10 @@ class Profile_Settings {
);
}
/**
* Resolve the default method key to use when no method was selected.
*
* @param array<string, array<string, string>> $available_methods Available method definitions.
*
* @return string
*/
private function get_default_method_key( array $available_methods ): string {
$configured_method = $this->config->get_default_method();
if ( isset( $available_methods[ $configured_method ] ) ) {
return $configured_method;
}
if ( isset( $available_methods['email'] ) ) {
return 'email';
}
$available_keys = array_keys( $available_methods );
if ( ! empty( $available_keys ) ) {
return (string) $available_keys[0];
}
return 'email';
}
/**
* Resolve the frequency value shown and stored for the user.
*
* @param array<string, mixed> $user_settings Stored user settings.
* @param array{enabled: bool, methods: array<int, string>, frequency: string} $user_settings Stored user settings.
*
* @return string
*/
@ -1110,8 +1158,8 @@ class Profile_Settings {
return $global_frequency;
}
if ( ! empty( $user_settings['frequency'] ) ) {
return Frequency_Options::sanitize( (string) $user_settings['frequency'] );
if ( '' !== $user_settings['frequency'] ) {
return Frequency_Options::sanitize( $user_settings['frequency'] );
}
return $global_frequency;

View file

@ -87,7 +87,8 @@ class Recovery_Codes {
public function handle_ajax_generate_request(): void {
check_ajax_referer( self::NONCE_ACTION, self::NONCE_FIELD );
$user_id = isset( $_POST['user_id'] ) ? absint( wp_unslash( $_POST['user_id'] ) ) : 0;
$raw_user_id = isset( $_POST['user_id'] ) && is_string( $_POST['user_id'] ) ? wp_unslash( $_POST['user_id'] ) : '';
$user_id = absint( $raw_user_id );
if ( $user_id <= 0 ) {
wp_send_json_error(
@ -121,6 +122,13 @@ class Recovery_Codes {
try {
$result = $this->regenerate_codes_for_user( $user );
} catch ( \Throwable $exception ) {
/**
* Fires when recovery code generation fails.
*
* @since 0.2.0
*
* @param \Throwable $exception The caught exception.
*/
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
wp_send_json_error(
array(
@ -147,7 +155,7 @@ class Recovery_Codes {
*
* @throws \Exception If secure randomness cannot be generated.
*
* @return array<string, mixed>
* @return array{codes: array<int, string>, generated_at: int, unused_count: int}
*/
public function regenerate_codes_for_user( WP_User $user ): array {
$codes = $this->generate_codes();
@ -269,7 +277,7 @@ class Recovery_Codes {
public function get_last_generated_timestamp( int $user_id ): int {
$record = $this->get_stored_codes( $user_id );
return (int) ( $record['generated_at'] ?? 0 );
return $record['generated_at'];
}
/**
@ -287,9 +295,10 @@ class Recovery_Codes {
$date_format = get_option( 'date_format' );
$time_format = get_option( 'time_format' );
$format = trim( (string) $date_format . ' ' . (string) $time_format );
$format = trim( ( is_string( $date_format ) ? $date_format : '' ) . ' ' . ( is_string( $time_format ) ? $time_format : '' ) );
return '' !== $format ? wp_date( $format, $timestamp ) : wp_date( 'c', $timestamp );
$formatted = wp_date( '' !== $format ? $format : 'c', $timestamp );
return false !== $formatted ? $formatted : '';
}
/**
@ -390,7 +399,7 @@ class Recovery_Codes {
*
* @param int $user_id User identifier.
*
* @return array<string, mixed>
* @return array{generated_at: int, codes: array<int, array{hash: string, used_at: int}>}
*/
private function get_stored_codes( int $user_id ): array {
$record = get_user_meta( $user_id, self::META_KEY, true );
@ -399,23 +408,22 @@ class Recovery_Codes {
$record = array();
}
$record['generated_at'] = isset( $record['generated_at'] ) ? (int) $record['generated_at'] : 0;
$record['codes'] = isset( $record['codes'] ) && is_array( $record['codes'] ) ? $record['codes'] : array();
$generated_at = isset( $record['generated_at'] ) && is_int( $record['generated_at'] ) ? $record['generated_at'] : 0;
$raw_codes = isset( $record['codes'] ) && is_array( $record['codes'] ) ? $record['codes'] : array();
foreach ( $record['codes'] as $index => $entry ) {
if ( ! is_array( $entry ) ) {
$record['codes'][ $index ] = array(
'hash' => '',
'used_at' => 0,
$codes = array();
foreach ( $raw_codes as $entry ) {
$codes[] = array(
'hash' => is_array( $entry ) && isset( $entry['hash'] ) && is_string( $entry['hash'] ) ? $entry['hash'] : '',
'used_at' => is_array( $entry ) && isset( $entry['used_at'] ) && is_int( $entry['used_at'] ) ? $entry['used_at'] : 0,
);
continue;
}
$record['codes'][ $index ]['hash'] = isset( $entry['hash'] ) && is_string( $entry['hash'] ) ? $entry['hash'] : '';
$record['codes'][ $index ]['used_at'] = isset( $entry['used_at'] ) ? (int) $entry['used_at'] : 0;
}
return $record;
return array(
'generated_at' => $generated_at,
'codes' => $codes,
);
}
/**

View file

@ -21,55 +21,65 @@ class Two_Factor_Config {
/**
* Retrieve global two-factor settings with multisite support.
*
* @return array<string, mixed>
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
*/
public function get_settings(): array {
$settings = array();
if ( is_multisite() ) {
$network_settings = get_site_option( Settings_Page::OPTION_NAME, array() );
if ( is_array( $network_settings ) && ! empty( $network_settings ) ) {
$settings = $network_settings;
}
}
if ( empty( $settings ) ) {
$site_settings = get_option( Settings_Page::OPTION_NAME, array() );
if ( is_array( $site_settings ) ) {
$settings = $site_settings;
}
}
return wp_parse_args(
$settings,
array(
'force_roles' => array(),
'default_method' => 'email',
'frequency' => Frequency_Options::FREQUENCY_SESSION,
'force_frequency' => false,
)
);
$settings_page = new Settings_Page();
return $settings_page->get_settings();
}
/**
* Retrieve the list of roles that must enable two-factor authentication.
* Retrieve the per-role method map.
*
* @return array<string, array<int, string>>
*/
public function get_role_methods(): array {
return $this->get_settings()['role_methods'];
}
/**
* Retrieve the list of roles that have at least one required method configured.
*
* @return array<int, string>
*/
public function get_forced_roles(): array {
$settings = $this->get_settings();
if ( empty( $settings['force_roles'] ) || ! is_array( $settings['force_roles'] ) ) {
return array();
return array_keys( $this->get_role_methods() );
}
return array_values(
array_filter(
array_map( 'sanitize_key', $settings['force_roles'] )
)
);
/**
* Retrieve the required verification methods for a specific role.
*
* @param string $role Role slug.
*
* @return array<int, string>
*/
public function get_methods_for_role( string $role ): array {
$role_methods = $this->get_role_methods();
return $role_methods[ $role ] ?? array();
}
/**
* Retrieve the union of required methods across all of a user's roles.
*
* Returns an empty array when none of the user's roles have required methods.
*
* @param \WP_User $user User object currently being authenticated.
*
* @return array<int, string>
*/
public function get_required_methods_for_user( \WP_User $user ): array {
$role_methods = $this->get_role_methods();
$required = array();
foreach ( $user->roles as $role ) {
if ( isset( $role_methods[ $role ] ) ) {
foreach ( $role_methods[ $role ] as $method ) {
$required[] = $method;
}
}
}
return array_values( array_unique( $required ) );
}
/**
@ -80,30 +90,7 @@ class Two_Factor_Config {
* @return bool
*/
public function is_two_factor_forced_for_user( \WP_User $user ): bool {
$forced_roles = $this->get_forced_roles();
if ( empty( $forced_roles ) ) {
return false;
}
foreach ( $user->roles as $role ) {
if ( in_array( $role, $forced_roles, true ) ) {
return true;
}
}
return false;
}
/**
* Retrieve the default two-factor authentication method.
*
* @return string
*/
public function get_default_method(): string {
$settings = $this->get_settings();
return sanitize_key( $settings['default_method'] ?? 'email' );
return ! empty( $this->get_required_methods_for_user( $user ) );
}
/**
@ -112,9 +99,7 @@ class Two_Factor_Config {
* @return string
*/
public function get_frequency(): string {
$settings = $this->get_settings();
return Frequency_Options::sanitize( (string) ( $settings['frequency'] ?? Frequency_Options::FREQUENCY_SESSION ) );
return $this->get_settings()['frequency'];
}
/**
@ -123,8 +108,6 @@ class Two_Factor_Config {
* @return bool
*/
public function is_frequency_forced(): bool {
$settings = $this->get_settings();
return ! empty( $settings['force_frequency'] );
return $this->get_settings()['force_frequency'];
}
}

View file

@ -48,7 +48,7 @@ class User_Settings_Repository {
*
* @param int $user_id User identifier.
*
* @return array<string, mixed>
* @return array{enabled: bool, methods: array<int, string>, frequency: string}
*/
public function get_user_settings( int $user_id ): array {
$raw_settings = get_user_meta( $user_id, self::USER_SETTINGS_META, true );
@ -57,48 +57,51 @@ class User_Settings_Repository {
$raw_settings = array();
}
$defaults = array(
'enabled' => false,
'methods' => array(),
'frequency' => Frequency_Options::FREQUENCY_SESSION,
);
$raw_methods = isset( $raw_settings['methods'] ) && is_array( $raw_settings['methods'] ) ? $raw_settings['methods'] : array();
$settings = wp_parse_args( $raw_settings, $defaults );
$settings['enabled'] = (bool) $settings['enabled'];
$settings['methods'] = array_values(
return array(
'enabled' => ! empty( $raw_settings['enabled'] ),
'methods' => array_values(
array_unique(
array_filter(
array_map( 'sanitize_key', (array) $settings['methods'] )
array_map(
static function ( mixed $v ): string {
return sanitize_key( is_string( $v ) ? $v : '' );
},
$raw_methods
)
)
)
),
'frequency' => Frequency_Options::sanitize( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ? $raw_settings['frequency'] : '' ),
);
$settings['frequency'] = Frequency_Options::sanitize( (string) $settings['frequency'] );
return $settings;
}
/**
* Persist 2FA settings for a user.
*
* @param int $user_id User identifier.
* @param array $settings Settings to store.
* @param array<string, mixed> $settings Settings to store.
*
* @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( 'sanitize_key', $settings['methods'] ?? array() )
array_map(
static function ( mixed $v ): string {
return sanitize_key( is_string( $v ) ? $v : '' );
},
$raw_methods
)
)
)
),
'frequency' => Frequency_Options::sanitize( (string) ( $settings['frequency'] ?? Frequency_Options::FREQUENCY_SESSION ) ),
'frequency' => Frequency_Options::sanitize( isset( $settings['frequency'] ) && is_string( $settings['frequency'] ) ? $settings['frequency'] : Frequency_Options::FREQUENCY_SESSION ),
);
update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared );
@ -133,7 +136,7 @@ class User_Settings_Repository {
*
* @param int $user_id User identifier.
*
* @return array<string, int|string>
* @return array{hash: string, expires: int, sent_at: int}
*/
public function get_email_challenge( int $user_id ): array {
$record = get_user_meta( $user_id, self::EMAIL_CHALLENGE_META, true );
@ -142,20 +145,11 @@ class User_Settings_Repository {
$record = array();
}
$record = wp_parse_args(
$record,
array(
'hash' => '',
'expires' => 0,
'sent_at' => 0,
)
return array(
'hash' => isset( $record['hash'] ) && is_string( $record['hash'] ) ? $record['hash'] : '',
'expires' => isset( $record['expires'] ) && is_numeric( $record['expires'] ) ? (int) $record['expires'] : 0,
'sent_at' => isset( $record['sent_at'] ) && is_numeric( $record['sent_at'] ) ? (int) $record['sent_at'] : 0,
);
$record['hash'] = is_string( $record['hash'] ) ? $record['hash'] : '';
$record['expires'] = (int) $record['expires'];
$record['sent_at'] = (int) $record['sent_at'];
return $record;
}
/**
@ -205,8 +199,10 @@ class User_Settings_Repository {
if ( count( $record[ $method ] ) > self::CONTEXT_LIMIT ) {
uasort(
$record[ $method ],
static function ( array $a, array $b ): int {
return ( $a['verified_at'] ?? 0 ) <=> ( $b['verified_at'] ?? 0 );
static function ( mixed $a, mixed $b ): int {
$a_ts = is_array( $a ) && isset( $a['verified_at'] ) && is_int( $a['verified_at'] ) ? $a['verified_at'] : 0;
$b_ts = is_array( $b ) && isset( $b['verified_at'] ) && is_int( $b['verified_at'] ) ? $b['verified_at'] : 0;
return $a_ts <=> $b_ts;
}
);
@ -239,11 +235,13 @@ class User_Settings_Repository {
return 0;
}
if ( empty( $record[ $method ][ $context_key ]['verified_at'] ) ) {
$entry = $record[ $method ][ $context_key ] ?? null;
if ( ! is_array( $entry ) || empty( $entry['verified_at'] ) || ! is_int( $entry['verified_at'] ) ) {
return 0;
}
return (int) $record[ $method ][ $context_key ]['verified_at'];
return $entry['verified_at'];
}
/**

View file

@ -2,44 +2,99 @@
Contributors: robotstxt
Tags: security, two-factor authentication, login, otp
Requires at least: 6.4
Tested up to: 6.4
Tested up to: 7.0
Requires PHP: 8.2
Stable tag: 0.2.0
Stable tag: 0.3.0
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.html
Security plugin that adds a two-factor authentication flow to the WordPress login screen.
Security plugin that adds per-role two-factor authentication to the WordPress login flow.
== Description ==
This plugin lets administrators enforce two-factor authentication per role and already delivers email verification codes during the login flow. After the username and password are validated, the login screen redirects to a dedicated verification step flagged with its own query parameter. The screen hides the username and password controls, automatically prioritizes authenticator apps when they are enabled, offers links to switch between authenticator, email, or recovery-code challenges, lets email users trigger an additional delivery when they need a fresh code, and auto-submits once the active method reaches its expected length (six digits for OTP, seven for email, eight for recovery codes). Users can manage their preferences from their profile, where every method starts unchecked until it is explicitly confirmed. The authenticator section now keeps the QR code and setup key visible until a valid six-digit code is entered, regenerates the secret whenever the option is disabled, and surfaces a dedicated button to issue a replacement secret. Recovery codes are shown in a two-column grid, expose the remaining count out of ten, require entering one code before activation, and automatically reset when the stored batch is exhausted so a fresh list is always available without extra clicks.
2FA (by ROBOTSTXT) enforces two-factor authentication on the WordPress login screen. Administrators configure a per-role matrix that specifies exactly which verification methods are required for each role: email codes, authenticator apps (TOTP), or recovery codes.
Administrators can remember successful verifications for a configurable duration—per login, daily, weekly, or every 28 days—and even lock the schedule so profiles inherit the global requirement. Device and IP fingerprints are stored securely to decide when a fresh challenge is needed, ensuring suspicious logins must re-validate regardless of the remembered interval.
After the username and password are validated, the login screen redirects to a dedicated verification step. The screen hides the username and password controls, prioritises authenticator apps when enabled, and offers links to switch between methods without restarting the login. Email users can request a fresh code from the same screen.
Users manage their preferences from their profile page. Every method starts unchecked until explicitly confirmed. Activating the authenticator app requires scanning the QR code and entering a valid six-digit code. Recovery codes must be saved and confirmed with one code before activation. Codes are shown in a two-column grid and automatically refresh when the batch is exhausted.
Administrators can remember successful verifications for a configurable duration — per login, daily, weekly, or every 28 days — and lock the schedule so all users follow the global setting. Device and IP fingerprints are stored securely to decide when a fresh challenge is needed.
Multisite is fully supported: network administrators can set and lock enforcement settings across all sites.
== Installation ==
1. Upload the `robotstxt-2fa` directory to `/wp-content/plugins/`.
2. Activate the plugin through the "Plugins" menu in WordPress.
3. Configure the authentication options in your profile and in the Two-Factor Authentication admin menu.
2. Activate the plugin through the "Plugins" menu in WordPress (or network-activate it for multisite).
3. Open the **2FA** top-level menu in the dashboard and configure which methods are required per role.
4. Users can set up their preferred methods from their profile page.
== Frequently Asked Questions ==
= Is this plugin production ready? =
Yes. Email codes, recovery confirmations, and authenticator apps with on-site QR codes are all available, though you should still test changes in a staging environment before enforcing them across your site.
Yes. Email codes, authenticator apps with on-site QR codes, and recovery codes are all available and tested.
= How do I enable the authenticator QR code? =
Install the optional QR library inside this plugin directory with `composer require bacon/bacon-qr-code:^3.0`. The plugin will automatically load the Composer autoloader when it exists, enabling the QR code renderer for the OTP method.
Install the optional QR library inside this plugin directory with `composer require bacon/bacon-qr-code:^3.0`. The plugin loads the Composer autoloader automatically when present.
= Can I enforce 2FA for specific roles only? =
Yes. The admin settings page shows a matrix of roles × methods. Check the methods you want to require for each role. Roles with no methods checked leave the choice to the user.
= What happens if a user loses all their verification methods? =
An administrator can edit the user's profile and generate a fresh batch of recovery codes, or disable the role enforcement temporarily while the user regains access.
= Is multisite supported? =
Yes. Activate the plugin at the network level. Network administrators can set and lock enforcement settings; per-site settings are overridden when network settings exist.
== Compatibility ==
* WordPress: 6.4 – 7.0
* PHP: 8.2 – 8.5
* MariaDB: 11.4 or newer
== Changelog ==
Review the `changelog.txt` file for additional details.
= 0.3.0 =
== Upgrade Notice ==
_Release date: 2026-06-05_
* Added delete-on-uninstall option (data preserved by default per AGENTS.md).
* Security: email verification codes now use `random_int()` (CSPRNG) instead of `wp_rand()`.
* Security: recovery code preview transient now expires after 5 minutes.
* Fixed network admin settings page form submission.
* Fixed settings option set to `autoload=false` (not needed on every page load).
= 0.2.0 =
Authenticator apps now include on-page QR codes and recovery codes stay visible until you confirm one of them. This update also fixes the confirmation workflow and improves the QR fallback guidance when PHP extensions are missing.
_Release date: 2026-06-05_
* Added per-role 2FA method matrix in admin settings with select-all row and column controls.
* Added authenticator app (TOTP) support with QR provisioning and manual setup key.
* Added recovery codes: 10 single-use 8-digit codes with confirmation workflow.
* Added configurable verification frequency remembered per device.
* Added network-wide multisite support.
* Changed profile method checkboxes to require explicit confirmation before activation.
* Fixed recovery-code preview persistence and QR generation error handling.
= 0.1.0 =
Initial version containing the basic plugin structure.
Initial release.
= Previous versions =
For the full changelog see the [changelog.txt](https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/raw/branch/main/changelog.txt) file.
== Compliance ==
This plugin adheres to the following security measures and review protocols for each version:
* [WordPress Plugin Handbook](https://developer.wordpress.org/plugins/)
* [WordPress Plugin Security](https://developer.wordpress.org/plugins/wordpress-org/plugin-security/)
* [WordPress APIs Security](https://developer.wordpress.org/apis/security/)
* [WordPress Coding Standards](https://github.com/WordPress/WordPress-Coding-Standards)
* [Plugin Check (PCP)](https://wordpress.org/plugins/plugin-check/)

View file

@ -3,14 +3,15 @@
* 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: 0.2.0
* Version: 0.3.0
* Author: ROBOTSTXT
* Author URI: https://www.robotstxt.es/
* Text Domain: robotstxt-2fa
* Requires at least: 6.4
* Requires PHP: 8.2
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Network: true
* License: GPLv3 or later
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
*
* @package Robotstxt_2FA
*/
@ -22,7 +23,7 @@ if ( ! defined( 'ABSPATH' ) ) {
}
if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) {
define( 'ROBOTSTXT_2FA_VERSION', '0.2.0' );
define( 'ROBOTSTXT_2FA_VERSION', '0.3.0' );
}
if ( ! defined( 'ROBOTSTXT_2FA_FILE' ) ) {
@ -37,27 +38,27 @@ if ( ! defined( 'ROBOTSTXT_2FA_URL' ) ) {
define( 'ROBOTSTXT_2FA_URL', plugin_dir_url( __FILE__ ) );
}
$autoload = ROBOTSTXT_2FA_PATH . 'vendor/autoload.php';
$robotstxt_2fa_autoload = ROBOTSTXT_2FA_PATH . 'vendor/autoload.php';
if ( file_exists( $autoload ) ) {
require_once $autoload;
if ( file_exists( $robotstxt_2fa_autoload ) ) {
require_once $robotstxt_2fa_autoload;
}
/**
* Simple autoloader for the plugin classes.
*
* @param string $class Fully qualified class name requested by PHP.
* @param string $class_name Fully qualified class name requested by PHP.
*
* @return void
*/
function robotstxt_2fa_autoload( string $class ): void {
function robotstxt_2fa_autoload( string $class_name ): void {
$prefix = 'Robotstxt\\TwoFA\\';
if ( strncmp( $prefix, $class, strlen( $prefix ) ) !== 0 ) {
if ( strncmp( $prefix, $class_name, strlen( $prefix ) ) !== 0 ) {
return;
}
$relative_class = substr( $class, strlen( $prefix ) );
$relative_class = substr( $class_name, strlen( $prefix ) );
$relative_parts = explode( '\\', $relative_class );
$filename = array_pop( $relative_parts );

384
robotstxt-updater.php Normal file
View file

@ -0,0 +1,384 @@
<?php
/**
* Generic JSON-based updater for ROBOTSTXT plugins.
*
* This file is designed to be copied to any ROBOTSTXT plugin.
* It auto-configures itself by reading the plugin headers.
*
* @package ROBOTSTXT
* @version 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Robotstxt_Updater' ) ) {
/**
* Class Robotstxt_Updater
*
* Generic updater that works with any plugin.
* Reads plugin headers and constructs update URL automatically.
*/
class Robotstxt_Updater {
/**
* Plugin file path.
*
* @var string
*/
private string $plugin_file_path;
/**
* Plugin basename (e.g., 'my-plugin/my-plugin.php').
*
* @var string
*/
private string $plugin_basename;
/**
* Plugin slug (directory name).
*
* @var string
*/
private string $plugin_slug;
/**
* Remote JSON URL.
*
* @var string
*/
private string $json_url;
/**
* Cache key.
*
* @var string
*/
private string $cache_key;
/**
* Plugin headers.
*
* @var array
*/
private array $plugin_data;
/**
* Initialize the updater.
*
* Usage in your main plugin file:
* require_once __DIR__ . '/robotstxt-updater.php';
* Robotstxt_Updater::init( __FILE__ );
*
* @param string $plugin_file_path Absolute path to the main plugin file.
*/
public static function init( string $plugin_file_path ): void {
$instance = new self( $plugin_file_path );
$instance->register();
}
/**
* Constructor.
*
* @param string $plugin_file_path Absolute path to the main plugin file.
*/
private function __construct( string $plugin_file_path ) {
$this->plugin_file_path = $plugin_file_path;
$this->plugin_basename = plugin_basename( $plugin_file_path );
$this->plugin_slug = dirname( $this->plugin_basename );
$this->plugin_data = $this->get_plugin_data();
$this->json_url = $this->build_json_url();
$this->cache_key = 'robotstxt_updater_' . md5( $this->plugin_basename );
}
/**
* Register WordPress hooks.
*/
private function register(): void {
add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'inject_update_info' ) );
add_filter( 'plugins_api', array( $this, 'provide_plugin_details' ), 10, 3 );
add_action( 'admin_init', array( $this, 'handle_cache_clear' ) );
add_action( 'robotstxt_updater_clear_cache', array( $this, 'clear_cache' ) );
}
/**
* Get plugin headers.
*
* @return array Plugin data.
*/
private function get_plugin_data(): array {
if ( ! function_exists( 'get_plugin_data' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
return get_plugin_data( $this->plugin_file_path, false, false );
}
/**
* Build JSON URL from plugin headers.
*
* Tries to use "Gitea Plugin URI" header to construct the URL.
* Falls back to Plugin URI if Gitea URI is not available.
*
* @return string JSON URL.
*/
private function build_json_url(): string {
// Try Gitea Plugin URI (format: "OWNER/REPO" or full URL).
if ( ! empty( $this->plugin_data['Gitea Plugin URI'] ) ) {
$gitea_uri = $this->plugin_data['Gitea Plugin URI'];
// If it's already a full URL, use it.
if ( str_starts_with( $gitea_uri, 'http' ) ) {
// Extract base URL and construct JSON path.
return rtrim( $gitea_uri, '/' ) . '/raw/branch/main/update.json';
}
// If it's in format "OWNER/REPO", construct full URL.
if ( preg_match( '#^[^/]+/[^/]+$#', $gitea_uri ) ) {
return "https://git.robotstxt.es/{$gitea_uri}/raw/branch/main/update.json";
}
}
// Fallback: try to extract from Plugin URI.
if ( ! empty( $this->plugin_data['PluginURI'] ) ) {
$plugin_uri = $this->plugin_data['PluginURI'];
if ( str_contains( $plugin_uri, 'git.robotstxt.es' ) ) {
return rtrim( $plugin_uri, '/' ) . '/raw/branch/main/update.json';
}
}
// Last resort: construct from plugin slug.
return "https://git.robotstxt.es/ROBOTSTXT/{$this->plugin_slug}/raw/branch/main/update.json";
}
/**
* Inject update info into WP's plugin update transient.
*
* @param object|mixed $transient The update_plugins transient.
*
* @return object The modified transient.
*/
public function inject_update_info( $transient ) {
if ( ! is_object( $transient ) ) {
$transient = new stdClass();
}
if ( empty( $transient->checked ) || ! is_array( $transient->checked ) ) {
return $transient;
}
if ( empty( $transient->checked[ $this->plugin_basename ] ) ) {
return $transient;
}
$current_version = $transient->checked[ $this->plugin_basename ];
$remote = $this->get_remote_data();
if ( empty( $remote['version'] ) || empty( $remote['download_url'] ) ) {
return $transient;
}
if ( ! $this->is_compatible( $remote ) ) {
return $transient;
}
if ( version_compare( $remote['version'], $current_version, '>' ) ) {
$update = (object) array(
'slug' => $remote['slug'] ?? $this->plugin_slug,
'plugin' => $this->plugin_basename,
'new_version' => $remote['version'],
'url' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '',
'package' => $remote['download_url'],
'tested' => $remote['tested'] ?? '',
'requires' => $remote['requires'] ?? '',
'requires_php' => $remote['requires_php'] ?? '',
);
$transient->response[ $this->plugin_basename ] = $update;
}
return $transient;
}
/**
* Provide "View details" modal content.
*
* @param false|object|array $result The result object or array.
* @param string $action The type of information being requested.
* @param object $args Plugin API arguments.
*
* @return false|object The plugin information object or false.
*/
public function provide_plugin_details( $result, string $action, object $args ) {
if ( 'plugin_information' !== $action ) {
return $result;
}
if ( empty( $args->slug ) || $args->slug !== $this->plugin_slug ) {
return $result;
}
$remote = $this->get_remote_data();
if ( empty( $remote['version'] ) ) {
return $result;
}
return (object) array(
'name' => $remote['name'] ?? $this->plugin_data['Name'] ?? $this->plugin_slug,
'slug' => $remote['slug'] ?? $this->plugin_slug,
'version' => $remote['version'],
'author' => $remote['author'] ?? $this->plugin_data['Author'] ?? '',
'homepage' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '',
'requires' => $remote['requires'] ?? '',
'tested' => $remote['tested'] ?? '',
'requires_php' => $remote['requires_php'] ?? '',
'sections' => array(
'description' => $remote['description'] ?? $this->plugin_data['Description'] ?? '',
'changelog' => $remote['changelog'] ?? '',
),
'download_link' => $remote['download_url'] ?? '',
);
}
/**
* Get remote data with caching and HMAC signature verification.
*
* @return array Remote data.
*/
private function get_remote_data(): array {
$cached = get_site_transient( $this->cache_key );
// Verify HMAC signature if AUTH_SALT is defined and cache has signature.
if ( false !== $cached && defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
if ( is_array( $cached ) && isset( $cached['signature'], $cached['data'] ) ) {
$expected_sig = hash_hmac( 'sha256', $this->cache_key . serialize( $cached['data'] ), AUTH_SALT ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Used for HMAC signing, not for unserializing untrusted data.
if ( hash_equals( $expected_sig, $cached['signature'] ) ) {
// Signature valid, return data.
return is_array( $cached['data'] ) ? $cached['data'] : array();
}
// Signature invalid, delete corrupted cache.
delete_site_transient( $this->cache_key );
$cached = false;
}
}
// If no valid cache, fetch fresh data.
if ( false === $cached ) {
$remote = $this->fetch_json();
// Store with HMAC signature if AUTH_SALT is available.
if ( defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
$remote_data = is_array( $remote ) ? $remote : array();
$payload = array(
'data' => $remote_data,
'timestamp' => time(),
'signature' => hash_hmac( 'sha256', $this->cache_key . serialize( $remote_data ), AUTH_SALT ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Used for HMAC signing, not for unserializing untrusted data.
);
set_site_transient( $this->cache_key, $payload, 6 * HOUR_IN_SECONDS );
} else {
// Fallback to standard caching.
set_site_transient( $this->cache_key, is_array( $remote ) ? $remote : array(), 6 * HOUR_IN_SECONDS );
}
return is_array( $remote ) ? $remote : array();
}
// Legacy cache format without signature (backward compatibility).
return is_array( $cached ) ? $cached : array();
}
/**
* Fetch JSON from remote URL.
*
* @return array Decoded JSON data.
*/
private function fetch_json(): array {
$response = wp_remote_get(
$this->json_url,
array(
'timeout' => 10,
'headers' => array(
'Accept' => 'application/json',
),
)
);
if ( is_wp_error( $response ) ) {
return array();
}
$code = (int) wp_remote_retrieve_response_code( $response );
if ( $code < 200 || $code >= 300 ) {
return array();
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
return is_array( $data ) ? $data : array();
}
/**
* Check compatibility.
*
* @param array $remote Remote data.
*
* @return bool True if compatible.
*/
private function is_compatible( array $remote ): bool {
if ( ! empty( $remote['requires_php'] ) ) {
if ( version_compare( PHP_VERSION, $remote['requires_php'], '<' ) ) {
return false;
}
}
if ( ! empty( $remote['requires'] ) ) {
if ( version_compare( get_bloginfo( 'version' ), $remote['requires'], '<' ) ) {
return false;
}
}
return true;
}
/**
* Handle manual cache clear via URL parameter.
*/
public function handle_cache_clear(): void {
// Check if this is a cache clear request first.
$clear_cache = filter_input( INPUT_GET, 'robotstxt_clear_update_cache', FILTER_UNSAFE_RAW );
if ( null === $clear_cache ) {
return;
}
// This is a cache clear request - now verify nonce.
$nonce_raw = filter_input( INPUT_GET, '_wpnonce', FILTER_UNSAFE_RAW );
$nonce = $nonce_raw ? sanitize_text_field( wp_unslash( $nonce_raw ) ) : '';
if ( ! wp_verify_nonce( $nonce, 'robotstxt_clear_update_cache' ) ) {
wp_die( esc_html__( 'Security check failed', 'robotstxt-2fa' ) );
}
// Check permissions.
if ( ! current_user_can( 'update_plugins' ) ) {
wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'robotstxt-2fa' ) );
}
$this->clear_cache();
wp_safe_redirect( remove_query_arg( array( 'robotstxt_clear_update_cache', '_wpnonce' ) ) );
exit;
}
/**
* Clear update cache.
*/
public function clear_cache(): void {
delete_site_transient( $this->cache_key );
delete_site_transient( 'update_plugins' );
}
}
}

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