v0.3.0
This commit is contained in:
parent
f936aeb807
commit
968211baad
99 changed files with 15548 additions and 14530 deletions
33
AGENTS.md
33
AGENTS.md
|
|
@ -1,33 +0,0 @@
|
|||
# AGENT INSTRUCTIONS
|
||||
|
||||
This repository contains the WordPress plugin **2FA (by ROBOTSTXT)**. Follow these rules whenever you work on any file within this repository:
|
||||
|
||||
1. **Language**
|
||||
- Write every piece of documentation, copy, and code comments in English.
|
||||
|
||||
2. **Code standards**
|
||||
- All PHP code must comply with **PHPCS** and **WPCS**.
|
||||
- Use tabs for indentation (no spaces).
|
||||
- Ensure compatibility with **PHP 8.2** or higher.
|
||||
- Provide proper **PHPDoc** annotations for classes, properties, and methods.
|
||||
|
||||
3. **WordPress security**
|
||||
- Sanitize, validate, and escape all user-provided data.
|
||||
- Include nonces in forms and verify them before processing submissions.
|
||||
- Do not suppress validation or authentication errors.
|
||||
|
||||
4. **Plugin structure**
|
||||
- Keep the code modular inside the `includes/` directory.
|
||||
- Place admin-related logic in subdirectories under `includes/admin/`.
|
||||
- Store presentational templates in `templates/`.
|
||||
- Whenever new persistent data (options, tables, user meta, etc.) is introduced, update `uninstall.php` so the plugin removes it on uninstall.
|
||||
|
||||
5. **Testing and tooling**
|
||||
- Run all available checks (PHPCS, PHPUnit, etc.) after making changes.
|
||||
- Summarize the commands executed and their results in the final message.
|
||||
|
||||
6. **Documentation**
|
||||
- Update `readme.txt` and `changelog.txt` whenever functional changes are introduced.
|
||||
- Explain *why* when the reason for a piece of code is not obvious.
|
||||
|
||||
These instructions apply to the entire repository tree.
|
||||
69
CHANGELOG.md
Normal file
69
CHANGELOG.md
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
# Changelog
|
||||
|
||||
All notable changes to this project are documented in this file.
|
||||
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.3.0] - 2026-06-05
|
||||
|
||||
### Added
|
||||
|
||||
- Delete-on-uninstall option in admin settings Data Management section (off by default — all data is preserved).
|
||||
|
||||
### Changed
|
||||
|
||||
- Network admin settings page now correctly saves to `wp_sitemeta` via a dedicated `network_admin_edit_` handler.
|
||||
- Settings option stored with `autoload=false` — not needed on every page load.
|
||||
- Recovery code preview transient TTL reduced from 0 (persistent) to 300 seconds (5 minutes).
|
||||
|
||||
### Security
|
||||
|
||||
- Email verification codes now use `random_int()` (CSPRNG) instead of `wp_rand()` (Mersenne Twister), consistent with recovery codes and OTP secrets.
|
||||
|
||||
### Fixed
|
||||
|
||||
- `get_required_capability()` now returns `manage_network_options` in network admin context.
|
||||
- `bin/deploy.sh` now excludes `CLAUDE.md`, `AGENTS.md`, `README.md`, `DOCUMENTATION-*.md`, and `.phpunit.result.cache` from the ZIP artifact.
|
||||
- `update.json` corrected: was shipping SMTP plugin data instead of 2FA plugin data.
|
||||
|
||||
## [0.2.0] - 2026-06-05
|
||||
|
||||
### Added
|
||||
|
||||
- Per-role 2FA method matrix: admins choose exactly which verification methods (email, OTP, recovery codes) are required for each WordPress role, with select-all row and column toggles.
|
||||
- Authenticator app (TOTP) support: secrets stored as Base32, QR code rendered via `bacon/bacon-qr-code`, manual setup key displayed as fallback.
|
||||
- Recovery codes: 10 single-use 8-digit codes, one-time display grid with copy-to-clipboard, mandatory confirmation before activation, auto-refresh when batch exhausted.
|
||||
- Email verification codes: 7-digit codes, 10-minute expiry, 60-second resend throttle.
|
||||
- Configurable verification frequency remembered per device fingerprint (every login / daily / weekly / monthly); administrators can lock the global schedule.
|
||||
- Dedicated stage token (WP nonce) securing the 2FA screen between password validation and code entry.
|
||||
- Method-switch links on the verification screen (OTP ↔ email ↔ recovery codes) without restarting the login.
|
||||
- Multisite support: `Network: true` header; network admins set and lock enforcement settings.
|
||||
- `uninstall.php` removes all plugin options and user meta on deletion.
|
||||
- `bin/deploy.sh` for manual ZIP packaging.
|
||||
- PHPUnit test suite with plugin-header tests.
|
||||
|
||||
### Changed
|
||||
|
||||
- Settings UI replaces flat forced-roles list with per-role method matrix; existing `force_roles` + `default_method` data is automatically migrated.
|
||||
- Profile method checkboxes require explicit confirmation before activating (OTP: valid 6-digit code; recovery codes: enter one displayed code).
|
||||
- Required methods indicated with a "required for your role" badge in the profile; checkboxes disabled and hidden inputs ensure values survive submission.
|
||||
- Login screen hides username/password fields, removes Remember Me, focuses code input, and auto-submits when digit count is reached.
|
||||
|
||||
### Fixed
|
||||
|
||||
- QR generation errors caught and surfaced to administrators; graceful fallback to text setup key.
|
||||
- Recovery-code preview persists via transient until explicitly acknowledged.
|
||||
|
||||
### Security
|
||||
|
||||
- All `$_POST`/`$_GET`/`$_SERVER` reads guarded with `is_string()` before passing to sanitize functions.
|
||||
- PHPStan level 9 passes with zero errors; no mixed-type casts.
|
||||
- `composer audit`: no known vulnerabilities in any dependency.
|
||||
|
||||
## [0.1.0] - 2024-04-08
|
||||
|
||||
### Added
|
||||
|
||||
- Initial plugin skeleton with placeholder classes for login handling, user profile, and admin settings.
|
||||
- Initial documentation files.
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
# robotstxt-2fa
|
||||
Simple 2FA WordPress plugin
|
||||
|
|
@ -1,42 +1,69 @@
|
|||
# Changelog
|
||||
|
||||
## [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.
|
||||
|
|
|
|||
|
|
@ -1,5 +0,0 @@
|
|||
{
|
||||
"require": {
|
||||
"bacon/bacon-qr-code": "^3.0"
|
||||
}
|
||||
}
|
||||
123
composer.lock
generated
123
composer.lock
generated
|
|
@ -1,123 +0,0 @@
|
|||
{
|
||||
"_readme": [
|
||||
"This file locks the dependencies of your project to a known state",
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "9d7cd0dbebfa0273a358b926795e7b8a",
|
||||
"packages": [
|
||||
{
|
||||
"name": "bacon/bacon-qr-code",
|
||||
"version": "v3.0.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/Bacon/BaconQrCode.git",
|
||||
"reference": "f9cc1f52b5a463062251d666761178dbdb6b544f"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/f9cc1f52b5a463062251d666761178dbdb6b544f",
|
||||
"reference": "f9cc1f52b5a463062251d666761178dbdb6b544f",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"dasprid/enum": "^1.0.3",
|
||||
"ext-iconv": "*",
|
||||
"php": "^8.1"
|
||||
},
|
||||
"require-dev": {
|
||||
"phly/keep-a-changelog": "^2.12",
|
||||
"phpunit/phpunit": "^10.5.11 || 11.0.4",
|
||||
"spatie/phpunit-snapshot-assertions": "^5.1.5",
|
||||
"squizlabs/php_codesniffer": "^3.9"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-imagick": "to generate QR code images"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"BaconQrCode\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"BSD-2-Clause"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Ben Scholzen 'DASPRiD'",
|
||||
"email": "mail@dasprids.de",
|
||||
"homepage": "https://dasprids.de/",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"description": "BaconQrCode is a QR code generator for PHP.",
|
||||
"homepage": "https://github.com/Bacon/BaconQrCode",
|
||||
"support": {
|
||||
"issues": "https://github.com/Bacon/BaconQrCode/issues",
|
||||
"source": "https://github.com/Bacon/BaconQrCode/tree/v3.0.1"
|
||||
},
|
||||
"time": "2024-10-01T13:55:55+00:00"
|
||||
},
|
||||
{
|
||||
"name": "dasprid/enum",
|
||||
"version": "1.0.7",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/DASPRiD/Enum.git",
|
||||
"reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/DASPRiD/Enum/zipball/b5874fa9ed0043116c72162ec7f4fb50e02e7cce",
|
||||
"reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=7.1 <9.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^7 || ^8 || ^9 || ^10 || ^11",
|
||||
"squizlabs/php_codesniffer": "*"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"DASPRiD\\Enum\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"BSD-2-Clause"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Ben Scholzen 'DASPRiD'",
|
||||
"email": "mail@dasprids.de",
|
||||
"homepage": "https://dasprids.de/",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"description": "PHP 7.1 enum implementation",
|
||||
"keywords": [
|
||||
"enum",
|
||||
"map"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/DASPRiD/Enum/issues",
|
||||
"source": "https://github.com/DASPRiD/Enum/tree/1.0.7"
|
||||
},
|
||||
"time": "2025-09-16T12:23:56+00:00"
|
||||
}
|
||||
],
|
||||
"packages-dev": [],
|
||||
"aliases": [],
|
||||
"minimum-stability": "stable",
|
||||
"stability-flags": [],
|
||||
"prefer-stable": false,
|
||||
"prefer-lowest": false,
|
||||
"platform": [],
|
||||
"platform-dev": [],
|
||||
"plugin-api-version": "2.6.0"
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,110 +1,110 @@
|
|||
<?php
|
||||
/**
|
||||
* Normalize and expose two-factor verification frequency options.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility helpers for two-factor verification frequency handling.
|
||||
*/
|
||||
class Frequency_Options {
|
||||
/**
|
||||
* Frequency key representing per-session verification.
|
||||
*/
|
||||
public const FREQUENCY_SESSION = 'session';
|
||||
|
||||
/**
|
||||
* Frequency key representing at most one verification per day.
|
||||
*/
|
||||
public const FREQUENCY_DAILY = 'daily';
|
||||
|
||||
/**
|
||||
* Frequency key representing at most one verification per week.
|
||||
*/
|
||||
public const FREQUENCY_WEEKLY = 'weekly';
|
||||
|
||||
/**
|
||||
* Frequency key representing at most one verification per 28 days.
|
||||
*/
|
||||
public const FREQUENCY_MONTHLY = 'monthly';
|
||||
|
||||
/**
|
||||
* Retrieve the available frequency options for display.
|
||||
*
|
||||
* @return array<string, array<string, string>>
|
||||
*/
|
||||
public static function get_options(): array {
|
||||
return array(
|
||||
self::FREQUENCY_SESSION => array(
|
||||
'label' => __( 'Every login', 'robotstxt-2fa' ),
|
||||
'description' => __( 'Always require a new verification code after the password step.', 'robotstxt-2fa' ),
|
||||
),
|
||||
self::FREQUENCY_DAILY => array(
|
||||
'label' => __( 'Daily', 'robotstxt-2fa' ),
|
||||
'description' => __( 'Remember successful verifications for 24 hours per device.', 'robotstxt-2fa' ),
|
||||
),
|
||||
self::FREQUENCY_WEEKLY => array(
|
||||
'label' => __( 'Weekly', 'robotstxt-2fa' ),
|
||||
'description' => __( 'Remember successful verifications for 7 days per device.', 'robotstxt-2fa' ),
|
||||
),
|
||||
self::FREQUENCY_MONTHLY => array(
|
||||
'label' => __( 'Monthly', 'robotstxt-2fa' ),
|
||||
'description' => __( 'Remember successful verifications for 28 days per device.', 'robotstxt-2fa' ),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the allowed option keys.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function get_allowed_keys(): array {
|
||||
return array_keys( self::get_options() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a frequency key against the supported values.
|
||||
*
|
||||
* @param string $frequency Submitted frequency value.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function sanitize( string $frequency ): string {
|
||||
$frequency = sanitize_key( $frequency );
|
||||
|
||||
if ( in_array( $frequency, self::get_allowed_keys(), true ) ) {
|
||||
return $frequency;
|
||||
}
|
||||
|
||||
return self::FREQUENCY_SESSION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the interval in seconds represented by a frequency.
|
||||
*
|
||||
* @param string $frequency Frequency identifier.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function get_interval_seconds( string $frequency ): int {
|
||||
switch ( $frequency ) {
|
||||
case self::FREQUENCY_DAILY:
|
||||
return DAY_IN_SECONDS;
|
||||
case self::FREQUENCY_WEEKLY:
|
||||
return WEEK_IN_SECONDS;
|
||||
case self::FREQUENCY_MONTHLY:
|
||||
return 28 * DAY_IN_SECONDS;
|
||||
case self::FREQUENCY_SESSION:
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
<?php
|
||||
/**
|
||||
* Normalize and expose two-factor verification frequency options.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility helpers for two-factor verification frequency handling.
|
||||
*/
|
||||
class Frequency_Options {
|
||||
/**
|
||||
* Frequency key representing per-session verification.
|
||||
*/
|
||||
public const FREQUENCY_SESSION = 'session';
|
||||
|
||||
/**
|
||||
* Frequency key representing at most one verification per day.
|
||||
*/
|
||||
public const FREQUENCY_DAILY = 'daily';
|
||||
|
||||
/**
|
||||
* Frequency key representing at most one verification per week.
|
||||
*/
|
||||
public const FREQUENCY_WEEKLY = 'weekly';
|
||||
|
||||
/**
|
||||
* Frequency key representing at most one verification per 28 days.
|
||||
*/
|
||||
public const FREQUENCY_MONTHLY = 'monthly';
|
||||
|
||||
/**
|
||||
* Retrieve the available frequency options for display.
|
||||
*
|
||||
* @return array<string, array<string, string>>
|
||||
*/
|
||||
public static function get_options(): array {
|
||||
return array(
|
||||
self::FREQUENCY_SESSION => array(
|
||||
'label' => __( 'Every login', 'robotstxt-2fa' ),
|
||||
'description' => __( 'Always require a new verification code after the password step.', 'robotstxt-2fa' ),
|
||||
),
|
||||
self::FREQUENCY_DAILY => array(
|
||||
'label' => __( 'Daily', 'robotstxt-2fa' ),
|
||||
'description' => __( 'Remember successful verifications for 24 hours per device.', 'robotstxt-2fa' ),
|
||||
),
|
||||
self::FREQUENCY_WEEKLY => array(
|
||||
'label' => __( 'Weekly', 'robotstxt-2fa' ),
|
||||
'description' => __( 'Remember successful verifications for 7 days per device.', 'robotstxt-2fa' ),
|
||||
),
|
||||
self::FREQUENCY_MONTHLY => array(
|
||||
'label' => __( 'Monthly', 'robotstxt-2fa' ),
|
||||
'description' => __( 'Remember successful verifications for 28 days per device.', 'robotstxt-2fa' ),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the allowed option keys.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function get_allowed_keys(): array {
|
||||
return array_keys( self::get_options() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a frequency key against the supported values.
|
||||
*
|
||||
* @param string $frequency Submitted frequency value.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function sanitize( string $frequency ): string {
|
||||
$frequency = sanitize_key( $frequency );
|
||||
|
||||
if ( in_array( $frequency, self::get_allowed_keys(), true ) ) {
|
||||
return $frequency;
|
||||
}
|
||||
|
||||
return self::FREQUENCY_SESSION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the interval in seconds represented by a frequency.
|
||||
*
|
||||
* @param string $frequency Frequency identifier.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function get_interval_seconds( string $frequency ): int {
|
||||
switch ( $frequency ) {
|
||||
case self::FREQUENCY_DAILY:
|
||||
return DAY_IN_SECONDS;
|
||||
case self::FREQUENCY_WEEKLY:
|
||||
return WEEK_IN_SECONDS;
|
||||
case self::FREQUENCY_MONTHLY:
|
||||
return 28 * DAY_IN_SECONDS;
|
||||
case self::FREQUENCY_SESSION:
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,120 +1,120 @@
|
|||
<?php
|
||||
/**
|
||||
* Core plugin bootstrap.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA;
|
||||
|
||||
use Robotstxt\TwoFA\Admin\Settings_Page;
|
||||
use Robotstxt\TwoFA\Login\Login_Form_Manager;
|
||||
use Robotstxt\TwoFA\User\Profile_Settings;
|
||||
use Robotstxt\TwoFA\User\Recovery_Codes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main plugin controller.
|
||||
*/
|
||||
class Plugin {
|
||||
/**
|
||||
* Plugin instance.
|
||||
*
|
||||
* @var Plugin|null
|
||||
*/
|
||||
private static ?Plugin $instance = null;
|
||||
|
||||
/**
|
||||
* Login form manager.
|
||||
*
|
||||
* @var Login_Form_Manager
|
||||
*/
|
||||
private Login_Form_Manager $login_manager;
|
||||
|
||||
/**
|
||||
* Profile settings manager.
|
||||
*
|
||||
* @var Profile_Settings
|
||||
*/
|
||||
private Profile_Settings $profile_settings;
|
||||
|
||||
/**
|
||||
* Recovery codes manager.
|
||||
*
|
||||
* @var Recovery_Codes
|
||||
*/
|
||||
private Recovery_Codes $recovery_codes;
|
||||
|
||||
/**
|
||||
* Settings page handler.
|
||||
*
|
||||
* @var Settings_Page
|
||||
*/
|
||||
private Settings_Page $settings_page;
|
||||
|
||||
/**
|
||||
* Get singleton instance.
|
||||
*
|
||||
* @return Plugin
|
||||
*/
|
||||
public static function get_instance(): Plugin {
|
||||
if ( null === self::$instance ) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->login_manager = new Login_Form_Manager();
|
||||
$this->profile_settings = new Profile_Settings();
|
||||
$this->recovery_codes = new Recovery_Codes();
|
||||
$this->settings_page = new Settings_Page();
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin initialization.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function init(): void {
|
||||
$this->maybe_load_textdomain();
|
||||
$this->login_manager->register_hooks();
|
||||
$this->profile_settings->register_hooks();
|
||||
$this->recovery_codes->register_hooks();
|
||||
$this->settings_page->register_hooks();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs on activation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function activate(): void {
|
||||
// Placeholder for activation tasks (option creation, migrations, etc.).
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs on deactivation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function deactivate(): void {
|
||||
// Placeholder for deactivation cleanup logic.
|
||||
}
|
||||
|
||||
/**
|
||||
* Load text domain for translations.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function maybe_load_textdomain(): void {
|
||||
load_plugin_textdomain( 'robotstxt-2fa', false, dirname( plugin_basename( ROBOTSTXT_2FA_FILE ) ) . '/languages/' );
|
||||
}
|
||||
}
|
||||
<?php
|
||||
/**
|
||||
* Core plugin bootstrap.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA;
|
||||
|
||||
use Robotstxt\TwoFA\Admin\Settings_Page;
|
||||
use Robotstxt\TwoFA\Login\Login_Form_Manager;
|
||||
use Robotstxt\TwoFA\User\Profile_Settings;
|
||||
use Robotstxt\TwoFA\User\Recovery_Codes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main plugin controller.
|
||||
*/
|
||||
class Plugin {
|
||||
/**
|
||||
* Plugin instance.
|
||||
*
|
||||
* @var Plugin|null
|
||||
*/
|
||||
private static ?Plugin $instance = null;
|
||||
|
||||
/**
|
||||
* Login form manager.
|
||||
*
|
||||
* @var Login_Form_Manager
|
||||
*/
|
||||
private Login_Form_Manager $login_manager;
|
||||
|
||||
/**
|
||||
* Profile settings manager.
|
||||
*
|
||||
* @var Profile_Settings
|
||||
*/
|
||||
private Profile_Settings $profile_settings;
|
||||
|
||||
/**
|
||||
* Recovery codes manager.
|
||||
*
|
||||
* @var Recovery_Codes
|
||||
*/
|
||||
private Recovery_Codes $recovery_codes;
|
||||
|
||||
/**
|
||||
* Settings page handler.
|
||||
*
|
||||
* @var Settings_Page
|
||||
*/
|
||||
private Settings_Page $settings_page;
|
||||
|
||||
/**
|
||||
* Get singleton instance.
|
||||
*
|
||||
* @return Plugin
|
||||
*/
|
||||
public static function get_instance(): Plugin {
|
||||
if ( null === self::$instance ) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->login_manager = new Login_Form_Manager();
|
||||
$this->profile_settings = new Profile_Settings();
|
||||
$this->recovery_codes = new Recovery_Codes();
|
||||
$this->settings_page = new Settings_Page();
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin initialization.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function init(): void {
|
||||
$this->maybe_load_textdomain();
|
||||
$this->login_manager->register_hooks();
|
||||
$this->profile_settings->register_hooks();
|
||||
$this->recovery_codes->register_hooks();
|
||||
$this->settings_page->register_hooks();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs on activation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function activate(): void {
|
||||
// Placeholder for activation tasks (option creation, migrations, etc.).
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs on deactivation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function deactivate(): void {
|
||||
// Placeholder for deactivation cleanup logic.
|
||||
}
|
||||
|
||||
/**
|
||||
* Load text domain for translations.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function maybe_load_textdomain(): void {
|
||||
load_plugin_textdomain( 'robotstxt-2fa', false, dirname( plugin_basename( ROBOTSTXT_2FA_FILE ) ) . '/languages/' );
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,149 +1,151 @@
|
|||
<?php
|
||||
/**
|
||||
* Email verification code sender.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\Login;
|
||||
|
||||
use Robotstxt\TwoFA\User\User_Settings_Repository;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles generation and delivery of email-based verification codes.
|
||||
*/
|
||||
class Email_Code_Sender {
|
||||
/**
|
||||
* Length of the generated numeric code.
|
||||
*/
|
||||
private const CODE_LENGTH = 7;
|
||||
|
||||
/**
|
||||
* Number of seconds the generated code remains valid.
|
||||
*/
|
||||
private const EXPIRATION_SECONDS = 600;
|
||||
|
||||
/**
|
||||
* Minimum delay between email deliveries in seconds.
|
||||
*/
|
||||
private const RESEND_INTERVAL = 60;
|
||||
|
||||
/**
|
||||
* User settings repository.
|
||||
*
|
||||
* @var User_Settings_Repository
|
||||
*/
|
||||
private User_Settings_Repository $user_settings_repository;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->user_settings_repository = new User_Settings_Repository();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the expected code length.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_code_length(): int {
|
||||
return self::CODE_LENGTH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a verification code to the provided user.
|
||||
*
|
||||
* @param \WP_User $user User who is requesting authentication.
|
||||
*
|
||||
* @return bool True when the email was sent or throttled successfully, false on failure.
|
||||
*/
|
||||
public function send_code( \WP_User $user ): bool {
|
||||
if ( empty( $user->user_email ) || ! is_email( $user->user_email ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
|
||||
$current_time = time();
|
||||
|
||||
if ( ! empty( $challenge['hash'] ) && $challenge['expires'] > $current_time && $challenge['sent_at'] >= ( $current_time - self::RESEND_INTERVAL ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$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' ) );
|
||||
|
||||
$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' ) ),
|
||||
'',
|
||||
$code,
|
||||
'',
|
||||
__( 'The code expires in 10 minutes.', 'robotstxt-2fa' ),
|
||||
'',
|
||||
__( 'If you did not request this code you can ignore this email.', 'robotstxt-2fa' ),
|
||||
);
|
||||
|
||||
$message = implode( "\n", $message_lines );
|
||||
|
||||
$headers = array( 'Content-Type: text/plain; charset=UTF-8' );
|
||||
|
||||
if ( ! wp_mail( $user->user_email, $email_subject, $message, $headers ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->user_settings_repository->store_email_challenge( $user->ID, $code, $expires );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a submitted code against the stored challenge.
|
||||
*
|
||||
* @param \WP_User $user User attempting to authenticate.
|
||||
* @param string $code Submitted verification code.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
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 );
|
||||
|
||||
if ( empty( $challenge['hash'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( $challenge['expires'] <= time() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( '' === $code ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return wp_check_password( $code, $challenge['hash'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random numeric verification code.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function generate_code(): string {
|
||||
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
||||
$code = (string) wp_rand( 0, (int) $max_value );
|
||||
|
||||
return str_pad( $code, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
||||
}
|
||||
}
|
||||
<?php
|
||||
/**
|
||||
* Email verification code sender.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\Login;
|
||||
|
||||
use Robotstxt\TwoFA\User\User_Settings_Repository;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles generation and delivery of email-based verification codes.
|
||||
*/
|
||||
class Email_Code_Sender {
|
||||
/**
|
||||
* Length of the generated numeric code.
|
||||
*/
|
||||
private const CODE_LENGTH = 7;
|
||||
|
||||
/**
|
||||
* Number of seconds the generated code remains valid.
|
||||
*/
|
||||
private const EXPIRATION_SECONDS = 600;
|
||||
|
||||
/**
|
||||
* Minimum delay between email deliveries in seconds.
|
||||
*/
|
||||
private const RESEND_INTERVAL = 60;
|
||||
|
||||
/**
|
||||
* User settings repository.
|
||||
*
|
||||
* @var User_Settings_Repository
|
||||
*/
|
||||
private User_Settings_Repository $user_settings_repository;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->user_settings_repository = new User_Settings_Repository();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the expected code length.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_code_length(): int {
|
||||
return self::CODE_LENGTH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a verification code to the provided user.
|
||||
*
|
||||
* @param \WP_User $user User who is requesting authentication.
|
||||
*
|
||||
* @return bool True when the email was sent or throttled successfully, false on failure.
|
||||
*/
|
||||
public function send_code( \WP_User $user ): bool {
|
||||
if ( empty( $user->user_email ) || ! is_email( $user->user_email ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
|
||||
$current_time = time();
|
||||
|
||||
if ( ! empty( $challenge['hash'] ) && $challenge['expires'] > $current_time && $challenge['sent_at'] >= ( $current_time - self::RESEND_INTERVAL ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$code = $this->generate_code();
|
||||
$expires = $current_time + self::EXPIRATION_SECONDS;
|
||||
|
||||
$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' ), ! empty( $blog_name ) ? $blog_name : __( 'your site', 'robotstxt-2fa' ) ),
|
||||
'',
|
||||
$code,
|
||||
'',
|
||||
__( 'The code expires in 10 minutes.', 'robotstxt-2fa' ),
|
||||
'',
|
||||
__( 'If you did not request this code you can ignore this email.', 'robotstxt-2fa' ),
|
||||
);
|
||||
|
||||
$message = implode( "\n", $message_lines );
|
||||
|
||||
$headers = array( 'Content-Type: text/plain; charset=UTF-8' );
|
||||
|
||||
if ( ! wp_mail( $user->user_email, $email_subject, $message, $headers ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->user_settings_repository->store_email_challenge( $user->ID, $code, $expires );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a submitted code against the stored challenge.
|
||||
*
|
||||
* @param \WP_User $user User attempting to authenticate.
|
||||
* @param string $code Submitted verification code.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
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 ) ?? '';
|
||||
|
||||
if ( '' === $challenge['hash'] ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( $challenge['expires'] <= time() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( '' === $code ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return wp_check_password( $code, $challenge['hash'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random numeric verification code.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function generate_code(): string {
|
||||
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
||||
$code = (string) random_int( 0, $max_value );
|
||||
|
||||
return str_pad( $code, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,337 +1,348 @@
|
|||
<?php
|
||||
/**
|
||||
* Manage authenticator app secrets and QR provisioning.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\User;
|
||||
|
||||
use WP_User;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles OTP secret storage, verification, and QR generation.
|
||||
*/
|
||||
class OTP_Manager {
|
||||
/**
|
||||
* User meta key that stores the OTP secret.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const META_KEY = 'robotstxt_2fa_otp_secret';
|
||||
|
||||
/**
|
||||
* Number of digits generated per OTP code.
|
||||
*/
|
||||
private const CODE_DIGITS = 6;
|
||||
|
||||
/**
|
||||
* Retrieve the number of digits expected for OTP codes.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_code_length(): int {
|
||||
return self::CODE_DIGITS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of seconds between OTP code changes.
|
||||
*/
|
||||
private const TIME_STEP = 30;
|
||||
|
||||
/**
|
||||
* Default length (in bytes) of generated secrets.
|
||||
*/
|
||||
private const SECRET_LENGTH = 20;
|
||||
|
||||
/**
|
||||
* Retrieve the stored OTP secret for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_secret( int $user_id ): string {
|
||||
$secret = get_user_meta( $user_id, self::META_KEY, true );
|
||||
|
||||
if ( ! is_string( $secret ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$secret = strtoupper( preg_replace( '/[^A-Z2-7]/', '', $secret ) ?? '' );
|
||||
|
||||
return $secret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the user has an OTP secret, generating one if necessary.
|
||||
*
|
||||
* @param WP_User $user User account that needs an OTP secret.
|
||||
*
|
||||
* @return string Generated or existing secret.
|
||||
*/
|
||||
public function ensure_secret( WP_User $user ): string {
|
||||
$secret = $this->get_secret( $user->ID );
|
||||
|
||||
if ( '' !== $secret ) {
|
||||
return $secret;
|
||||
}
|
||||
|
||||
$secret = $this->generate_secret();
|
||||
|
||||
update_user_meta( $user->ID, self::META_KEY, $secret );
|
||||
|
||||
return $secret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the stored OTP secret for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete_secret( int $user_id ): void {
|
||||
delete_user_meta( $user_id, self::META_KEY );
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify an OTP code against the stored secret.
|
||||
*
|
||||
* @param WP_User $user User attempting to authenticate.
|
||||
* @param string $code Submitted verification code.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function verify_code( WP_User $user, string $code ): bool {
|
||||
$secret = $this->get_secret( $user->ID );
|
||||
|
||||
if ( '' === $secret ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$code = preg_replace( '/[^0-9]/', '', $code );
|
||||
|
||||
if ( null === $code || strlen( $code ) !== self::CODE_DIGITS ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$binary_secret = $this->base32_decode( $secret );
|
||||
|
||||
if ( '' === $binary_secret ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$current_step = (int) floor( time() / self::TIME_STEP );
|
||||
|
||||
for ( $offset = -1; $offset <= 1; $offset++ ) {
|
||||
$otp = $this->generate_otp_for_counter( $binary_secret, $current_step + $offset );
|
||||
|
||||
if ( hash_equals( $otp, $code ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the provisioning URI used by authenticator apps.
|
||||
*
|
||||
* @param WP_User $user User who owns the OTP secret.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_provisioning_uri( WP_User $user ): string {
|
||||
$secret = $this->get_secret( $user->ID );
|
||||
|
||||
if ( '' === $secret ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$site_name = wp_specialchars_decode( get_option( 'blogname', '' ), ENT_QUOTES );
|
||||
$site_name = '' !== $site_name ? $site_name : __( 'WordPress Site', 'robotstxt-2fa' );
|
||||
$label = '' !== $user->user_email ? $user->user_email : $user->user_login;
|
||||
|
||||
$encoded_label = rawurlencode( sanitize_text_field( $label ) );
|
||||
$encoded_site = rawurlencode( $site_name );
|
||||
$encoded_secret = rawurlencode( $secret );
|
||||
$parameters = array(
|
||||
'issuer' => $encoded_site,
|
||||
'period' => (string) self::TIME_STEP,
|
||||
);
|
||||
|
||||
$query = array();
|
||||
|
||||
foreach ( $parameters as $key => $value ) {
|
||||
$query[] = rawurlencode( $key ) . '=' . $value;
|
||||
}
|
||||
|
||||
return sprintf(
|
||||
'otpauth://totp/%1$s:%2$s?secret=%3$s&%4$s',
|
||||
$encoded_site,
|
||||
$encoded_label,
|
||||
$encoded_secret,
|
||||
implode( '&', $query )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a QR code and return it as a data URI.
|
||||
*
|
||||
* @param WP_User $user User who owns the OTP secret.
|
||||
*
|
||||
* @return string Data URI containing an SVG image or an empty string when unavailable.
|
||||
*/
|
||||
public function get_qr_code_data_uri( WP_User $user ): string {
|
||||
$uri = $this->get_provisioning_uri( $user );
|
||||
|
||||
if ( '' === $uri ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$svg = $this->render_qr_svg( $uri );
|
||||
|
||||
if ( '' === $svg ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
/*
|
||||
* Encode the SVG payload so it can be embedded safely as a data URI in the admin form.
|
||||
*/
|
||||
return 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- The QR SVG is encoded to embed it safely as a data URI.
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new secret encoded in Base32.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function generate_secret(): string {
|
||||
$bytes = random_bytes( self::SECRET_LENGTH );
|
||||
|
||||
return $this->base32_encode( $bytes );
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a QR code in SVG format using an available library.
|
||||
*
|
||||
* @param string $data Data encoded inside the QR code.
|
||||
*
|
||||
* @return string SVG markup or empty string on failure.
|
||||
*/
|
||||
private function render_qr_svg( string $data ): string {
|
||||
if ( ! class_exists( '\BaconQrCode\Writer' ) || ! class_exists( '\BaconQrCode\Renderer\ImageRenderer' ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
$renderer = new \BaconQrCode\Renderer\ImageRenderer(
|
||||
new \BaconQrCode\Renderer\RendererStyle\RendererStyle( 256 ),
|
||||
new \BaconQrCode\Renderer\Image\SvgImageBackEnd()
|
||||
);
|
||||
$writer = new \BaconQrCode\Writer( $renderer );
|
||||
|
||||
return $writer->writeString( $data );
|
||||
} catch ( \Throwable $exception ) {
|
||||
do_action( 'robotstxt_2fa_qr_generation_failed', $exception, $data );
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode binary data using the Base32 alphabet.
|
||||
*
|
||||
* @param string $data Binary string to encode.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function base32_encode( string $data ): string {
|
||||
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
$bits = '';
|
||||
|
||||
for ( $i = 0, $length = strlen( $data ); $i < $length; $i++ ) {
|
||||
$bits .= str_pad( decbin( ord( $data[ $i ] ) ), 8, '0', STR_PAD_LEFT );
|
||||
}
|
||||
|
||||
$chunks = str_split( $bits, 5 );
|
||||
$encoded = '';
|
||||
|
||||
foreach ( $chunks as $chunk ) {
|
||||
if ( strlen( $chunk ) < 5 ) {
|
||||
$chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT );
|
||||
}
|
||||
|
||||
$encoded .= $alphabet[ bindec( $chunk ) ];
|
||||
}
|
||||
|
||||
return $encoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a Base32-encoded string.
|
||||
*
|
||||
* @param string $encoded Encoded secret.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function base32_decode( string $encoded ): string {
|
||||
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
$encoded = strtoupper( $encoded );
|
||||
$encoded = preg_replace( '/[^A-Z2-7]/', '', $encoded );
|
||||
|
||||
if ( null === $encoded || '' === $encoded ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$bits = '';
|
||||
|
||||
for ( $i = 0, $length = strlen( $encoded ); $i < $length; $i++ ) {
|
||||
$position = strpos( $alphabet, $encoded[ $i ] );
|
||||
|
||||
if ( false === $position ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$bits .= str_pad( decbin( $position ), 5, '0', STR_PAD_LEFT );
|
||||
}
|
||||
|
||||
$binary = '';
|
||||
$chunks = str_split( $bits, 8 );
|
||||
|
||||
foreach ( $chunks as $chunk ) {
|
||||
if ( strlen( $chunk ) < 8 ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$binary .= chr( bindec( $chunk ) );
|
||||
}
|
||||
|
||||
return $binary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an OTP value for a specific counter.
|
||||
*
|
||||
* @param string $secret Binary secret key.
|
||||
* @param int $counter Time-based counter value.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function generate_otp_for_counter( string $secret, int $counter ): string {
|
||||
$counter = max( 0, $counter );
|
||||
$binary_counter = pack( 'N*', 0 ) . pack( 'N*', $counter );
|
||||
$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;
|
||||
$code = $value % ( 10 ** self::CODE_DIGITS );
|
||||
|
||||
return str_pad( (string) $code, self::CODE_DIGITS, '0', STR_PAD_LEFT );
|
||||
}
|
||||
}
|
||||
<?php
|
||||
/**
|
||||
* Manage authenticator app secrets and QR provisioning.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\User;
|
||||
|
||||
use WP_User;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles OTP secret storage, verification, and QR generation.
|
||||
*/
|
||||
class OTP_Manager {
|
||||
/**
|
||||
* User meta key that stores the OTP secret.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const META_KEY = 'robotstxt_2fa_otp_secret';
|
||||
|
||||
/**
|
||||
* Number of digits generated per OTP code.
|
||||
*/
|
||||
private const CODE_DIGITS = 6;
|
||||
|
||||
/**
|
||||
* Retrieve the number of digits expected for OTP codes.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_code_length(): int {
|
||||
return self::CODE_DIGITS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of seconds between OTP code changes.
|
||||
*/
|
||||
private const TIME_STEP = 30;
|
||||
|
||||
/**
|
||||
* Default length (in bytes) of generated secrets.
|
||||
*/
|
||||
private const SECRET_LENGTH = 20;
|
||||
|
||||
/**
|
||||
* Retrieve the stored OTP secret for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_secret( int $user_id ): string {
|
||||
$secret = get_user_meta( $user_id, self::META_KEY, true );
|
||||
|
||||
if ( ! is_string( $secret ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$secret = strtoupper( preg_replace( '/[^A-Z2-7]/', '', $secret ) ?? '' );
|
||||
|
||||
return $secret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the user has an OTP secret, generating one if necessary.
|
||||
*
|
||||
* @param WP_User $user User account that needs an OTP secret.
|
||||
*
|
||||
* @return string Generated or existing secret.
|
||||
*/
|
||||
public function ensure_secret( WP_User $user ): string {
|
||||
$secret = $this->get_secret( $user->ID );
|
||||
|
||||
if ( '' !== $secret ) {
|
||||
return $secret;
|
||||
}
|
||||
|
||||
$secret = $this->generate_secret();
|
||||
|
||||
update_user_meta( $user->ID, self::META_KEY, $secret );
|
||||
|
||||
return $secret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the stored OTP secret for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete_secret( int $user_id ): void {
|
||||
delete_user_meta( $user_id, self::META_KEY );
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify an OTP code against the stored secret.
|
||||
*
|
||||
* @param WP_User $user User attempting to authenticate.
|
||||
* @param string $code Submitted verification code.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function verify_code( WP_User $user, string $code ): bool {
|
||||
$secret = $this->get_secret( $user->ID );
|
||||
|
||||
if ( '' === $secret ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$code = preg_replace( '/[^0-9]/', '', $code );
|
||||
|
||||
if ( null === $code || strlen( $code ) !== self::CODE_DIGITS ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$binary_secret = $this->base32_decode( $secret );
|
||||
|
||||
if ( '' === $binary_secret ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$current_step = (int) floor( time() / self::TIME_STEP );
|
||||
|
||||
for ( $offset = -1; $offset <= 1; $offset++ ) {
|
||||
$otp = $this->generate_otp_for_counter( $binary_secret, $current_step + $offset );
|
||||
|
||||
if ( hash_equals( $otp, $code ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the provisioning URI used by authenticator apps.
|
||||
*
|
||||
* @param WP_User $user User who owns the OTP secret.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_provisioning_uri( WP_User $user ): string {
|
||||
$secret = $this->get_secret( $user->ID );
|
||||
|
||||
if ( '' === $secret ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$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;
|
||||
|
||||
$encoded_label = rawurlencode( sanitize_text_field( $label ) );
|
||||
$encoded_site = rawurlencode( $site_name );
|
||||
$encoded_secret = rawurlencode( $secret );
|
||||
$parameters = array(
|
||||
'issuer' => $encoded_site,
|
||||
'period' => (string) self::TIME_STEP,
|
||||
);
|
||||
|
||||
$query = array();
|
||||
|
||||
foreach ( $parameters as $key => $value ) {
|
||||
$query[] = rawurlencode( $key ) . '=' . $value;
|
||||
}
|
||||
|
||||
return sprintf(
|
||||
'otpauth://totp/%1$s:%2$s?secret=%3$s&%4$s',
|
||||
$encoded_site,
|
||||
$encoded_label,
|
||||
$encoded_secret,
|
||||
implode( '&', $query )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a QR code and return it as a data URI.
|
||||
*
|
||||
* @param WP_User $user User who owns the OTP secret.
|
||||
*
|
||||
* @return string Data URI containing an SVG image or an empty string when unavailable.
|
||||
*/
|
||||
public function get_qr_code_data_uri( WP_User $user ): string {
|
||||
$uri = $this->get_provisioning_uri( $user );
|
||||
|
||||
if ( '' === $uri ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$svg = $this->render_qr_svg( $uri );
|
||||
|
||||
if ( '' === $svg ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
/*
|
||||
* Encode the SVG payload so it can be embedded safely as a data URI in the admin form.
|
||||
*/
|
||||
return 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- The QR SVG is encoded to embed it safely as a data URI.
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new secret encoded in Base32.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function generate_secret(): string {
|
||||
$bytes = random_bytes( self::SECRET_LENGTH );
|
||||
|
||||
return $this->base32_encode( $bytes );
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a QR code in SVG format using an available library.
|
||||
*
|
||||
* @param string $data Data encoded inside the QR code.
|
||||
*
|
||||
* @return string SVG markup or empty string on failure.
|
||||
*/
|
||||
private function render_qr_svg( string $data ): string {
|
||||
if ( ! class_exists( '\BaconQrCode\Writer' ) || ! class_exists( '\BaconQrCode\Renderer\ImageRenderer' ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
$renderer = new \BaconQrCode\Renderer\ImageRenderer(
|
||||
new \BaconQrCode\Renderer\RendererStyle\RendererStyle( 256 ),
|
||||
new \BaconQrCode\Renderer\Image\SvgImageBackEnd()
|
||||
);
|
||||
$writer = new \BaconQrCode\Writer( $renderer );
|
||||
|
||||
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 );
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode binary data using the Base32 alphabet.
|
||||
*
|
||||
* @param string $data Binary string to encode.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function base32_encode( string $data ): string {
|
||||
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
$bits = '';
|
||||
|
||||
for ( $i = 0, $length = strlen( $data ); $i < $length; $i++ ) {
|
||||
$bits .= str_pad( decbin( ord( $data[ $i ] ) ), 8, '0', STR_PAD_LEFT );
|
||||
}
|
||||
|
||||
$chunks = str_split( $bits, 5 );
|
||||
$encoded = '';
|
||||
|
||||
foreach ( $chunks as $chunk ) {
|
||||
if ( strlen( $chunk ) < 5 ) {
|
||||
$chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT );
|
||||
}
|
||||
|
||||
$encoded .= $alphabet[ (int) bindec( $chunk ) ];
|
||||
}
|
||||
|
||||
return $encoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a Base32-encoded string.
|
||||
*
|
||||
* @param string $encoded Encoded secret.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function base32_decode( string $encoded ): string {
|
||||
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
$encoded = strtoupper( $encoded );
|
||||
$encoded = preg_replace( '/[^A-Z2-7]/', '', $encoded );
|
||||
|
||||
if ( null === $encoded || '' === $encoded ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$bits = '';
|
||||
|
||||
for ( $i = 0, $length = strlen( $encoded ); $i < $length; $i++ ) {
|
||||
$position = strpos( $alphabet, $encoded[ $i ] );
|
||||
|
||||
if ( false === $position ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$bits .= str_pad( decbin( $position ), 5, '0', STR_PAD_LEFT );
|
||||
}
|
||||
|
||||
$binary = '';
|
||||
$chunks = str_split( $bits, 8 );
|
||||
|
||||
foreach ( $chunks as $chunk ) {
|
||||
if ( strlen( $chunk ) < 8 ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$binary .= chr( (int) bindec( $chunk ) & 0xFF );
|
||||
}
|
||||
|
||||
return $binary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an OTP value for a specific counter.
|
||||
*
|
||||
* @param string $secret Binary secret key.
|
||||
* @param int $counter Time-based counter value.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function generate_otp_for_counter( string $secret, int $counter ): string {
|
||||
$counter = max( 0, $counter );
|
||||
$binary_counter = pack( 'N*', 0 ) . pack( 'N*', $counter );
|
||||
$hash = hash_hmac( 'sha1', $binary_counter, $secret, true );
|
||||
$offset = ord( substr( $hash, -1 ) ) & 0x0F;
|
||||
$segment = substr( $hash, $offset, 4 );
|
||||
$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 );
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,454 +1,462 @@
|
|||
<?php
|
||||
/**
|
||||
* Manage generation and validation of recovery codes.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\User;
|
||||
|
||||
use WP_User;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles creation, storage, and consumption of recovery codes.
|
||||
*/
|
||||
class Recovery_Codes {
|
||||
/**
|
||||
* User meta key storing recovery code hashes.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const META_KEY = 'robotstxt_2fa_recovery_codes';
|
||||
|
||||
/**
|
||||
* Number of codes generated per batch.
|
||||
*/
|
||||
private const CODES_PER_BATCH = 10;
|
||||
|
||||
/**
|
||||
* Number of digits per recovery code.
|
||||
*/
|
||||
private const CODE_LENGTH = 8;
|
||||
|
||||
/**
|
||||
* Admin-post action slug used to request new recovery codes.
|
||||
*/
|
||||
public const ACTION_GENERATE = 'robotstxt_2fa_generate_recovery_codes';
|
||||
|
||||
/**
|
||||
* Nonce action securing recovery code generation.
|
||||
*/
|
||||
public const NONCE_ACTION = 'robotstxt_2fa_generate_recovery_codes';
|
||||
|
||||
/**
|
||||
* Nonce field key embedded in recovery code forms.
|
||||
*/
|
||||
public const NONCE_FIELD = 'robotstxt_2fa_recovery_nonce';
|
||||
|
||||
/**
|
||||
* Register hooks required by the recovery code workflow.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_hooks(): void {
|
||||
add_action( 'wp_ajax_' . self::ACTION_GENERATE, array( $this, 'handle_ajax_generate_request' ) );
|
||||
add_action( 'wp_ajax_nopriv_' . self::ACTION_GENERATE, array( $this, 'reject_unauthenticated_requests' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Block unauthenticated requests attempting to generate recovery codes.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function reject_unauthenticated_requests(): void {
|
||||
$message = esc_html__( 'You must be logged in to manage recovery codes.', 'robotstxt-2fa' );
|
||||
|
||||
if ( wp_doing_ajax() ) {
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => $message,
|
||||
),
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
wp_die( $message, '', array( 'response' => 403 ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $message is escaped via esc_html__().
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle AJAX requests to generate recovery codes without reloading the page.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
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;
|
||||
|
||||
if ( $user_id <= 0 ) {
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
|
||||
),
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'edit_user', $user_id ) ) {
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html__( 'You are not allowed to modify recovery codes for this account.', 'robotstxt-2fa' ),
|
||||
),
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
$user = get_user_by( 'ID', $user_id );
|
||||
|
||||
if ( ! $user instanceof WP_User ) {
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
|
||||
),
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $this->regenerate_codes_for_user( $user );
|
||||
} catch ( \Throwable $exception ) {
|
||||
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html__( 'We could not generate recovery codes. Please try again.', 'robotstxt-2fa' ),
|
||||
),
|
||||
500
|
||||
);
|
||||
}
|
||||
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'codes' => $result['codes'],
|
||||
'unused_count' => $result['unused_count'],
|
||||
'last_generated' => $result['generated_at'],
|
||||
'last_generated_formatted' => $this->format_generated_timestamp( $result['generated_at'] ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and persist a new batch of recovery codes for a user.
|
||||
*
|
||||
* @param WP_User $user User whose recovery codes are being regenerated.
|
||||
*
|
||||
* @throws \Exception If secure randomness cannot be generated.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function regenerate_codes_for_user( WP_User $user ): array {
|
||||
$codes = $this->generate_codes();
|
||||
|
||||
$this->store_codes( $user->ID, $codes );
|
||||
|
||||
return array(
|
||||
'codes' => $codes,
|
||||
'generated_at' => $this->get_last_generated_timestamp( $user->ID ),
|
||||
'unused_count' => $this->count_unused_codes( $user->ID ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the number of digits expected for each recovery code.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_code_length(): int {
|
||||
return self::CODE_LENGTH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the number of recovery codes generated per batch.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_codes_per_batch(): int {
|
||||
return self::CODES_PER_BATCH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the amount of unused recovery codes available for the user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function count_unused_codes( int $user_id ): int {
|
||||
$record = $this->get_stored_codes( $user_id );
|
||||
|
||||
if ( empty( $record['codes'] ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$unused = 0;
|
||||
|
||||
foreach ( $record['codes'] as $entry ) {
|
||||
if ( empty( $entry['used_at'] ) ) {
|
||||
++$unused;
|
||||
}
|
||||
}
|
||||
|
||||
return $unused;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user currently has any unused recovery codes.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function has_active_codes( int $user_id ): bool {
|
||||
return $this->count_unused_codes( $user_id ) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consume a recovery code if it matches one of the stored hashes.
|
||||
*
|
||||
* @param WP_User $user User attempting to validate a recovery code.
|
||||
* @param string $code Submitted plain-text code.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function consume_code( WP_User $user, string $code ): bool {
|
||||
$normalized_code = $this->normalize_code( $code );
|
||||
|
||||
if ( '' === $normalized_code ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$record = $this->get_stored_codes( $user->ID );
|
||||
|
||||
if ( empty( $record['codes'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$updated = false;
|
||||
|
||||
foreach ( $record['codes'] as $index => $entry ) {
|
||||
if ( ! empty( $entry['used_at'] ) || empty( $entry['hash'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
|
||||
$record['codes'][ $index ]['used_at'] = time();
|
||||
$updated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ( $updated ) {
|
||||
update_user_meta( $user->ID, self::META_KEY, $record );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the timestamp of the last generation batch.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_last_generated_timestamp( int $user_id ): int {
|
||||
$record = $this->get_stored_codes( $user_id );
|
||||
|
||||
return (int) ( $record['generated_at'] ?? 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the provided timestamp using the site's date and time preferences.
|
||||
*
|
||||
* @param int $timestamp Unix timestamp representing the generation time.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function format_generated_timestamp( int $timestamp ): string {
|
||||
if ( $timestamp <= 0 ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$date_format = get_option( 'date_format' );
|
||||
$time_format = get_option( 'time_format' );
|
||||
|
||||
$format = trim( (string) $date_format . ' ' . (string) $time_format );
|
||||
|
||||
return '' !== $format ? wp_date( $format, $timestamp ) : wp_date( 'c', $timestamp );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a batch of unique recovery codes.
|
||||
*
|
||||
* @throws \Exception If randomness cannot be generated.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function generate_codes(): array {
|
||||
$codes = array();
|
||||
$attempts = 0;
|
||||
$target_count = self::CODES_PER_BATCH;
|
||||
$max_attempts = $target_count * 3;
|
||||
$unique_count = 0;
|
||||
|
||||
while ( $unique_count < $target_count && $attempts < $max_attempts ) {
|
||||
++$attempts;
|
||||
|
||||
$code = $this->generate_single_code();
|
||||
|
||||
if ( in_array( $code, $codes, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$codes[] = $code;
|
||||
++$unique_count;
|
||||
}
|
||||
|
||||
return $codes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a single recovery code.
|
||||
*
|
||||
* @throws \Exception If secure randomness cannot be generated.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function generate_single_code(): string {
|
||||
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
||||
$number = random_int( 0, $max_value );
|
||||
|
||||
return str_pad( (string) $number, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize user-submitted recovery codes.
|
||||
*
|
||||
* @param string $code Submitted code.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function normalize_code( string $code ): string {
|
||||
$code = preg_replace( '/[^0-9]/', '', $code );
|
||||
|
||||
if ( null === $code ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$code = substr( $code, 0, self::CODE_LENGTH );
|
||||
|
||||
if ( strlen( $code ) !== self::CODE_LENGTH ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store recovery codes and metadata for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
* @param array<int, string> $codes Plain-text recovery codes.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function store_codes( int $user_id, array $codes ): void {
|
||||
$stored_codes = array();
|
||||
|
||||
foreach ( $codes as $code ) {
|
||||
$stored_codes[] = array(
|
||||
'hash' => wp_hash_password( $this->normalize_code( $code ) ),
|
||||
'used_at' => 0,
|
||||
);
|
||||
}
|
||||
|
||||
$record = array(
|
||||
'generated_at' => time(),
|
||||
'codes' => $stored_codes,
|
||||
);
|
||||
|
||||
update_user_meta( $user_id, self::META_KEY, $record );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve and sanitize stored recovery code metadata.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function get_stored_codes( int $user_id ): array {
|
||||
$record = get_user_meta( $user_id, self::META_KEY, true );
|
||||
|
||||
if ( ! is_array( $record ) ) {
|
||||
$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();
|
||||
|
||||
foreach ( $record['codes'] as $index => $entry ) {
|
||||
if ( ! is_array( $entry ) ) {
|
||||
$record['codes'][ $index ] = array(
|
||||
'hash' => '',
|
||||
'used_at' => 0,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
$record['codes'][ $index ]['hash'] = isset( $entry['hash'] ) && is_string( $entry['hash'] ) ? $entry['hash'] : '';
|
||||
$record['codes'][ $index ]['used_at'] = isset( $entry['used_at'] ) ? (int) $entry['used_at'] : 0;
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify whether the provided recovery code matches a stored hash without consuming it.
|
||||
*
|
||||
* @param WP_User $user User attempting to validate a recovery code.
|
||||
* @param string $code Submitted plain-text code.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function verify_code_without_consuming( WP_User $user, string $code ): bool {
|
||||
$normalized_code = $this->normalize_code( $code );
|
||||
|
||||
if ( '' === $normalized_code ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$record = $this->get_stored_codes( $user->ID );
|
||||
|
||||
if ( empty( $record['codes'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $record['codes'] as $entry ) {
|
||||
if ( empty( $entry['hash'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
<?php
|
||||
/**
|
||||
* Manage generation and validation of recovery codes.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\User;
|
||||
|
||||
use WP_User;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles creation, storage, and consumption of recovery codes.
|
||||
*/
|
||||
class Recovery_Codes {
|
||||
/**
|
||||
* User meta key storing recovery code hashes.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const META_KEY = 'robotstxt_2fa_recovery_codes';
|
||||
|
||||
/**
|
||||
* Number of codes generated per batch.
|
||||
*/
|
||||
private const CODES_PER_BATCH = 10;
|
||||
|
||||
/**
|
||||
* Number of digits per recovery code.
|
||||
*/
|
||||
private const CODE_LENGTH = 8;
|
||||
|
||||
/**
|
||||
* Admin-post action slug used to request new recovery codes.
|
||||
*/
|
||||
public const ACTION_GENERATE = 'robotstxt_2fa_generate_recovery_codes';
|
||||
|
||||
/**
|
||||
* Nonce action securing recovery code generation.
|
||||
*/
|
||||
public const NONCE_ACTION = 'robotstxt_2fa_generate_recovery_codes';
|
||||
|
||||
/**
|
||||
* Nonce field key embedded in recovery code forms.
|
||||
*/
|
||||
public const NONCE_FIELD = 'robotstxt_2fa_recovery_nonce';
|
||||
|
||||
/**
|
||||
* Register hooks required by the recovery code workflow.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_hooks(): void {
|
||||
add_action( 'wp_ajax_' . self::ACTION_GENERATE, array( $this, 'handle_ajax_generate_request' ) );
|
||||
add_action( 'wp_ajax_nopriv_' . self::ACTION_GENERATE, array( $this, 'reject_unauthenticated_requests' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Block unauthenticated requests attempting to generate recovery codes.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function reject_unauthenticated_requests(): void {
|
||||
$message = esc_html__( 'You must be logged in to manage recovery codes.', 'robotstxt-2fa' );
|
||||
|
||||
if ( wp_doing_ajax() ) {
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => $message,
|
||||
),
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
wp_die( $message, '', array( 'response' => 403 ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $message is escaped via esc_html__().
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle AJAX requests to generate recovery codes without reloading the page.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_ajax_generate_request(): void {
|
||||
check_ajax_referer( self::NONCE_ACTION, self::NONCE_FIELD );
|
||||
|
||||
$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(
|
||||
array(
|
||||
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
|
||||
),
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'edit_user', $user_id ) ) {
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html__( 'You are not allowed to modify recovery codes for this account.', 'robotstxt-2fa' ),
|
||||
),
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
$user = get_user_by( 'ID', $user_id );
|
||||
|
||||
if ( ! $user instanceof WP_User ) {
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
|
||||
),
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
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(
|
||||
'message' => esc_html__( 'We could not generate recovery codes. Please try again.', 'robotstxt-2fa' ),
|
||||
),
|
||||
500
|
||||
);
|
||||
}
|
||||
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'codes' => $result['codes'],
|
||||
'unused_count' => $result['unused_count'],
|
||||
'last_generated' => $result['generated_at'],
|
||||
'last_generated_formatted' => $this->format_generated_timestamp( $result['generated_at'] ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and persist a new batch of recovery codes for a user.
|
||||
*
|
||||
* @param WP_User $user User whose recovery codes are being regenerated.
|
||||
*
|
||||
* @throws \Exception If secure randomness cannot be generated.
|
||||
*
|
||||
* @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();
|
||||
|
||||
$this->store_codes( $user->ID, $codes );
|
||||
|
||||
return array(
|
||||
'codes' => $codes,
|
||||
'generated_at' => $this->get_last_generated_timestamp( $user->ID ),
|
||||
'unused_count' => $this->count_unused_codes( $user->ID ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the number of digits expected for each recovery code.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_code_length(): int {
|
||||
return self::CODE_LENGTH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the number of recovery codes generated per batch.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_codes_per_batch(): int {
|
||||
return self::CODES_PER_BATCH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the amount of unused recovery codes available for the user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function count_unused_codes( int $user_id ): int {
|
||||
$record = $this->get_stored_codes( $user_id );
|
||||
|
||||
if ( empty( $record['codes'] ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$unused = 0;
|
||||
|
||||
foreach ( $record['codes'] as $entry ) {
|
||||
if ( empty( $entry['used_at'] ) ) {
|
||||
++$unused;
|
||||
}
|
||||
}
|
||||
|
||||
return $unused;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user currently has any unused recovery codes.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function has_active_codes( int $user_id ): bool {
|
||||
return $this->count_unused_codes( $user_id ) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consume a recovery code if it matches one of the stored hashes.
|
||||
*
|
||||
* @param WP_User $user User attempting to validate a recovery code.
|
||||
* @param string $code Submitted plain-text code.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function consume_code( WP_User $user, string $code ): bool {
|
||||
$normalized_code = $this->normalize_code( $code );
|
||||
|
||||
if ( '' === $normalized_code ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$record = $this->get_stored_codes( $user->ID );
|
||||
|
||||
if ( empty( $record['codes'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$updated = false;
|
||||
|
||||
foreach ( $record['codes'] as $index => $entry ) {
|
||||
if ( ! empty( $entry['used_at'] ) || empty( $entry['hash'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
|
||||
$record['codes'][ $index ]['used_at'] = time();
|
||||
$updated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ( $updated ) {
|
||||
update_user_meta( $user->ID, self::META_KEY, $record );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the timestamp of the last generation batch.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_last_generated_timestamp( int $user_id ): int {
|
||||
$record = $this->get_stored_codes( $user_id );
|
||||
|
||||
return $record['generated_at'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the provided timestamp using the site's date and time preferences.
|
||||
*
|
||||
* @param int $timestamp Unix timestamp representing the generation time.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function format_generated_timestamp( int $timestamp ): string {
|
||||
if ( $timestamp <= 0 ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$date_format = get_option( 'date_format' );
|
||||
$time_format = get_option( 'time_format' );
|
||||
|
||||
$format = trim( ( is_string( $date_format ) ? $date_format : '' ) . ' ' . ( is_string( $time_format ) ? $time_format : '' ) );
|
||||
|
||||
$formatted = wp_date( '' !== $format ? $format : 'c', $timestamp );
|
||||
return false !== $formatted ? $formatted : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a batch of unique recovery codes.
|
||||
*
|
||||
* @throws \Exception If randomness cannot be generated.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function generate_codes(): array {
|
||||
$codes = array();
|
||||
$attempts = 0;
|
||||
$target_count = self::CODES_PER_BATCH;
|
||||
$max_attempts = $target_count * 3;
|
||||
$unique_count = 0;
|
||||
|
||||
while ( $unique_count < $target_count && $attempts < $max_attempts ) {
|
||||
++$attempts;
|
||||
|
||||
$code = $this->generate_single_code();
|
||||
|
||||
if ( in_array( $code, $codes, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$codes[] = $code;
|
||||
++$unique_count;
|
||||
}
|
||||
|
||||
return $codes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a single recovery code.
|
||||
*
|
||||
* @throws \Exception If secure randomness cannot be generated.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function generate_single_code(): string {
|
||||
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
||||
$number = random_int( 0, $max_value );
|
||||
|
||||
return str_pad( (string) $number, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize user-submitted recovery codes.
|
||||
*
|
||||
* @param string $code Submitted code.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function normalize_code( string $code ): string {
|
||||
$code = preg_replace( '/[^0-9]/', '', $code );
|
||||
|
||||
if ( null === $code ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$code = substr( $code, 0, self::CODE_LENGTH );
|
||||
|
||||
if ( strlen( $code ) !== self::CODE_LENGTH ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store recovery codes and metadata for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
* @param array<int, string> $codes Plain-text recovery codes.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function store_codes( int $user_id, array $codes ): void {
|
||||
$stored_codes = array();
|
||||
|
||||
foreach ( $codes as $code ) {
|
||||
$stored_codes[] = array(
|
||||
'hash' => wp_hash_password( $this->normalize_code( $code ) ),
|
||||
'used_at' => 0,
|
||||
);
|
||||
}
|
||||
|
||||
$record = array(
|
||||
'generated_at' => time(),
|
||||
'codes' => $stored_codes,
|
||||
);
|
||||
|
||||
update_user_meta( $user_id, self::META_KEY, $record );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve and sanitize stored recovery code metadata.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @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 );
|
||||
|
||||
if ( ! is_array( $record ) ) {
|
||||
$record = 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();
|
||||
|
||||
$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,
|
||||
);
|
||||
}
|
||||
|
||||
return array(
|
||||
'generated_at' => $generated_at,
|
||||
'codes' => $codes,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify whether the provided recovery code matches a stored hash without consuming it.
|
||||
*
|
||||
* @param WP_User $user User attempting to validate a recovery code.
|
||||
* @param string $code Submitted plain-text code.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function verify_code_without_consuming( WP_User $user, string $code ): bool {
|
||||
$normalized_code = $this->normalize_code( $code );
|
||||
|
||||
if ( '' === $normalized_code ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$record = $this->get_stored_codes( $user->ID );
|
||||
|
||||
if ( empty( $record['codes'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $record['codes'] as $entry ) {
|
||||
if ( empty( $entry['hash'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,130 +1,113 @@
|
|||
<?php
|
||||
/**
|
||||
* Resolve two-factor configuration from global settings.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\User;
|
||||
|
||||
use Robotstxt\TwoFA\Admin\Settings_Page;
|
||||
use Robotstxt\TwoFA\Frequency_Options;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exposes helpers to read plugin-level two-factor configuration.
|
||||
*/
|
||||
class Two_Factor_Config {
|
||||
/**
|
||||
* Retrieve global two-factor settings with multisite support.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the list of roles that must enable two-factor authentication.
|
||||
*
|
||||
* @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_values(
|
||||
array_filter(
|
||||
array_map( 'sanitize_key', $settings['force_roles'] )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if two-factor authentication is enforced for the provided user.
|
||||
*
|
||||
* @param \WP_User $user User object currently being authenticated.
|
||||
*
|
||||
* @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' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the globally configured verification frequency.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_frequency(): string {
|
||||
$settings = $this->get_settings();
|
||||
|
||||
return Frequency_Options::sanitize( (string) ( $settings['frequency'] ?? Frequency_Options::FREQUENCY_SESSION ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the global frequency must be enforced for all users.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_frequency_forced(): bool {
|
||||
$settings = $this->get_settings();
|
||||
|
||||
return ! empty( $settings['force_frequency'] );
|
||||
}
|
||||
}
|
||||
<?php
|
||||
/**
|
||||
* Resolve two-factor configuration from global settings.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\User;
|
||||
|
||||
use Robotstxt\TwoFA\Admin\Settings_Page;
|
||||
use Robotstxt\TwoFA\Frequency_Options;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exposes helpers to read plugin-level two-factor configuration.
|
||||
*/
|
||||
class Two_Factor_Config {
|
||||
/**
|
||||
* Retrieve global two-factor settings with multisite support.
|
||||
*
|
||||
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
|
||||
*/
|
||||
public function get_settings(): array {
|
||||
$settings_page = new Settings_Page();
|
||||
return $settings_page->get_settings();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
return array_keys( $this->get_role_methods() );
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if two-factor authentication is enforced for the provided user.
|
||||
*
|
||||
* @param \WP_User $user User object currently being authenticated.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_two_factor_forced_for_user( \WP_User $user ): bool {
|
||||
return ! empty( $this->get_required_methods_for_user( $user ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the globally configured verification frequency.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_frequency(): string {
|
||||
return $this->get_settings()['frequency'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the global frequency must be enforced for all users.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_frequency_forced(): bool {
|
||||
return $this->get_settings()['force_frequency'];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,259 +1,257 @@
|
|||
<?php
|
||||
/**
|
||||
* Manage persistence of user two-factor settings.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\User;
|
||||
|
||||
use Robotstxt\TwoFA\Frequency_Options;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides CRUD helpers for user 2FA preferences and challenges.
|
||||
*/
|
||||
class User_Settings_Repository {
|
||||
/**
|
||||
* User meta key storing 2FA settings.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const USER_SETTINGS_META = 'robotstxt_2fa_user_settings';
|
||||
|
||||
/**
|
||||
* User meta key storing email challenges.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const EMAIL_CHALLENGE_META = 'robotstxt_2fa_email_challenge';
|
||||
|
||||
/**
|
||||
* User meta key storing last successful verifications per context.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const LAST_VERIFICATIONS_META = 'robotstxt_2fa_last_verifications';
|
||||
|
||||
/**
|
||||
* Maximum number of device contexts stored per verification method.
|
||||
*/
|
||||
private const CONTEXT_LIMIT = 20;
|
||||
|
||||
/**
|
||||
* Retrieve stored 2FA settings for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function get_user_settings( int $user_id ): array {
|
||||
$raw_settings = get_user_meta( $user_id, self::USER_SETTINGS_META, true );
|
||||
|
||||
if ( ! is_array( $raw_settings ) ) {
|
||||
$raw_settings = array();
|
||||
}
|
||||
|
||||
$defaults = array(
|
||||
'enabled' => false,
|
||||
'methods' => array(),
|
||||
'frequency' => Frequency_Options::FREQUENCY_SESSION,
|
||||
);
|
||||
|
||||
$settings = wp_parse_args( $raw_settings, $defaults );
|
||||
|
||||
$settings['enabled'] = (bool) $settings['enabled'];
|
||||
|
||||
$settings['methods'] = array_values(
|
||||
array_unique(
|
||||
array_filter(
|
||||
array_map( 'sanitize_key', (array) $settings['methods'] )
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$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.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function save_user_settings( int $user_id, array $settings ): void {
|
||||
$prepared = array(
|
||||
'enabled' => ! empty( $settings['enabled'] ),
|
||||
'methods' => array_values(
|
||||
array_unique(
|
||||
array_filter(
|
||||
array_map( 'sanitize_key', $settings['methods'] ?? array() )
|
||||
)
|
||||
)
|
||||
),
|
||||
'frequency' => Frequency_Options::sanitize( (string) ( $settings['frequency'] ?? Frequency_Options::FREQUENCY_SESSION ) ),
|
||||
);
|
||||
|
||||
update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared );
|
||||
|
||||
if ( empty( $prepared['enabled'] ) ) {
|
||||
$this->delete_email_challenge( $user_id );
|
||||
$this->delete_last_verifications( $user_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store email challenge details for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
* @param string $code Plain-text verification code.
|
||||
* @param int $expires Expiration timestamp.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function store_email_challenge( int $user_id, string $code, int $expires ): void {
|
||||
$record = array(
|
||||
'hash' => wp_hash_password( $code ),
|
||||
'expires' => $expires,
|
||||
'sent_at' => time(),
|
||||
);
|
||||
|
||||
update_user_meta( $user_id, self::EMAIL_CHALLENGE_META, $record );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve email challenge details for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return array<string, int|string>
|
||||
*/
|
||||
public function get_email_challenge( int $user_id ): array {
|
||||
$record = get_user_meta( $user_id, self::EMAIL_CHALLENGE_META, true );
|
||||
|
||||
if ( ! is_array( $record ) ) {
|
||||
$record = array();
|
||||
}
|
||||
|
||||
$record = wp_parse_args(
|
||||
$record,
|
||||
array(
|
||||
'hash' => '',
|
||||
'expires' => 0,
|
||||
'sent_at' => 0,
|
||||
)
|
||||
);
|
||||
|
||||
$record['hash'] = is_string( $record['hash'] ) ? $record['hash'] : '';
|
||||
$record['expires'] = (int) $record['expires'];
|
||||
$record['sent_at'] = (int) $record['sent_at'];
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove stored email challenge details.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete_email_challenge( int $user_id ): void {
|
||||
delete_user_meta( $user_id, self::EMAIL_CHALLENGE_META );
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a successful verification timestamp for a method and device context.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
* @param string $method Verification method identifier.
|
||||
* @param string $context_key Normalized device context key.
|
||||
* @param int $timestamp Verification timestamp.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function record_last_verification( int $user_id, string $method, string $context_key, int $timestamp ): void {
|
||||
$method = sanitize_key( $method );
|
||||
$context_key = sanitize_text_field( $context_key );
|
||||
$timestamp = max( 0, $timestamp );
|
||||
|
||||
if ( '' === $method || '' === $context_key || 0 === $timestamp ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true );
|
||||
|
||||
if ( ! is_array( $record ) ) {
|
||||
$record = array();
|
||||
}
|
||||
|
||||
if ( ! isset( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) {
|
||||
$record[ $method ] = array();
|
||||
}
|
||||
|
||||
$record[ $method ][ $context_key ] = array(
|
||||
'verified_at' => $timestamp,
|
||||
);
|
||||
|
||||
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 );
|
||||
}
|
||||
);
|
||||
|
||||
$record[ $method ] = array_slice( $record[ $method ], -1 * self::CONTEXT_LIMIT, null, true );
|
||||
}
|
||||
|
||||
update_user_meta( $user_id, self::LAST_VERIFICATIONS_META, $record );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the last verification timestamp for a method and context.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
* @param string $method Verification method identifier.
|
||||
* @param string $context_key Normalized device context key.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_last_verification_timestamp( int $user_id, string $method, string $context_key ): int {
|
||||
$method = sanitize_key( $method );
|
||||
$context_key = sanitize_text_field( $context_key );
|
||||
|
||||
if ( '' === $method || '' === $context_key ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true );
|
||||
|
||||
if ( ! is_array( $record ) || empty( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if ( empty( $record[ $method ][ $context_key ]['verified_at'] ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (int) $record[ $method ][ $context_key ]['verified_at'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove stored verification timestamps.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete_last_verifications( int $user_id ): void {
|
||||
delete_user_meta( $user_id, self::LAST_VERIFICATIONS_META );
|
||||
}
|
||||
}
|
||||
<?php
|
||||
/**
|
||||
* Manage persistence of user two-factor settings.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\User;
|
||||
|
||||
use Robotstxt\TwoFA\Frequency_Options;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides CRUD helpers for user 2FA preferences and challenges.
|
||||
*/
|
||||
class User_Settings_Repository {
|
||||
/**
|
||||
* User meta key storing 2FA settings.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const USER_SETTINGS_META = 'robotstxt_2fa_user_settings';
|
||||
|
||||
/**
|
||||
* User meta key storing email challenges.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const EMAIL_CHALLENGE_META = 'robotstxt_2fa_email_challenge';
|
||||
|
||||
/**
|
||||
* User meta key storing last successful verifications per context.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const LAST_VERIFICATIONS_META = 'robotstxt_2fa_last_verifications';
|
||||
|
||||
/**
|
||||
* Maximum number of device contexts stored per verification method.
|
||||
*/
|
||||
private const CONTEXT_LIMIT = 20;
|
||||
|
||||
/**
|
||||
* Retrieve stored 2FA settings for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @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 );
|
||||
|
||||
if ( ! is_array( $raw_settings ) ) {
|
||||
$raw_settings = array();
|
||||
}
|
||||
|
||||
$raw_methods = isset( $raw_settings['methods'] ) && is_array( $raw_settings['methods'] ) ? $raw_settings['methods'] : array();
|
||||
|
||||
return array(
|
||||
'enabled' => ! empty( $raw_settings['enabled'] ),
|
||||
'methods' => array_values(
|
||||
array_unique(
|
||||
array_filter(
|
||||
array_map(
|
||||
static function ( mixed $v ): string {
|
||||
return sanitize_key( is_string( $v ) ? $v : '' );
|
||||
},
|
||||
$raw_methods
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
'frequency' => Frequency_Options::sanitize( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ? $raw_settings['frequency'] : '' ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist 2FA settings for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
* @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(
|
||||
static function ( mixed $v ): string {
|
||||
return sanitize_key( is_string( $v ) ? $v : '' );
|
||||
},
|
||||
$raw_methods
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
'frequency' => Frequency_Options::sanitize( isset( $settings['frequency'] ) && is_string( $settings['frequency'] ) ? $settings['frequency'] : Frequency_Options::FREQUENCY_SESSION ),
|
||||
);
|
||||
|
||||
update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared );
|
||||
|
||||
if ( empty( $prepared['enabled'] ) ) {
|
||||
$this->delete_email_challenge( $user_id );
|
||||
$this->delete_last_verifications( $user_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store email challenge details for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
* @param string $code Plain-text verification code.
|
||||
* @param int $expires Expiration timestamp.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function store_email_challenge( int $user_id, string $code, int $expires ): void {
|
||||
$record = array(
|
||||
'hash' => wp_hash_password( $code ),
|
||||
'expires' => $expires,
|
||||
'sent_at' => time(),
|
||||
);
|
||||
|
||||
update_user_meta( $user_id, self::EMAIL_CHALLENGE_META, $record );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve email challenge details for a user.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @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 );
|
||||
|
||||
if ( ! is_array( $record ) ) {
|
||||
$record = array();
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove stored email challenge details.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete_email_challenge( int $user_id ): void {
|
||||
delete_user_meta( $user_id, self::EMAIL_CHALLENGE_META );
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a successful verification timestamp for a method and device context.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
* @param string $method Verification method identifier.
|
||||
* @param string $context_key Normalized device context key.
|
||||
* @param int $timestamp Verification timestamp.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function record_last_verification( int $user_id, string $method, string $context_key, int $timestamp ): void {
|
||||
$method = sanitize_key( $method );
|
||||
$context_key = sanitize_text_field( $context_key );
|
||||
$timestamp = max( 0, $timestamp );
|
||||
|
||||
if ( '' === $method || '' === $context_key || 0 === $timestamp ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true );
|
||||
|
||||
if ( ! is_array( $record ) ) {
|
||||
$record = array();
|
||||
}
|
||||
|
||||
if ( ! isset( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) {
|
||||
$record[ $method ] = array();
|
||||
}
|
||||
|
||||
$record[ $method ][ $context_key ] = array(
|
||||
'verified_at' => $timestamp,
|
||||
);
|
||||
|
||||
if ( count( $record[ $method ] ) > self::CONTEXT_LIMIT ) {
|
||||
uasort(
|
||||
$record[ $method ],
|
||||
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;
|
||||
}
|
||||
);
|
||||
|
||||
$record[ $method ] = array_slice( $record[ $method ], -1 * self::CONTEXT_LIMIT, null, true );
|
||||
}
|
||||
|
||||
update_user_meta( $user_id, self::LAST_VERIFICATIONS_META, $record );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the last verification timestamp for a method and context.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
* @param string $method Verification method identifier.
|
||||
* @param string $context_key Normalized device context key.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_last_verification_timestamp( int $user_id, string $method, string $context_key ): int {
|
||||
$method = sanitize_key( $method );
|
||||
$context_key = sanitize_text_field( $context_key );
|
||||
|
||||
if ( '' === $method || '' === $context_key ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true );
|
||||
|
||||
if ( ! is_array( $record ) || empty( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$entry = $record[ $method ][ $context_key ] ?? null;
|
||||
|
||||
if ( ! is_array( $entry ) || empty( $entry['verified_at'] ) || ! is_int( $entry['verified_at'] ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $entry['verified_at'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove stored verification timestamps.
|
||||
*
|
||||
* @param int $user_id User identifier.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete_last_verifications( int $user_id ): void {
|
||||
delete_user_meta( $user_id, self::LAST_VERIFICATIONS_META );
|
||||
}
|
||||
}
|
||||
|
|
|
|||
145
readme.txt
145
readme.txt
|
|
@ -1,45 +1,100 @@
|
|||
=== 2FA (by ROBOTSTXT) ===
|
||||
Contributors: robotstxt
|
||||
Tags: security, two-factor authentication, login, otp
|
||||
Requires at least: 6.4
|
||||
Tested up to: 6.4
|
||||
Requires PHP: 8.2
|
||||
Stable tag: 0.2.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.
|
||||
|
||||
== 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.
|
||||
|
||||
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.
|
||||
|
||||
== 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.
|
||||
|
||||
== 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.
|
||||
|
||||
= 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.
|
||||
|
||||
== Changelog ==
|
||||
|
||||
Review the `changelog.txt` file for additional details.
|
||||
|
||||
== Upgrade Notice ==
|
||||
|
||||
= 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.
|
||||
|
||||
= 0.1.0 =
|
||||
Initial version containing the basic plugin structure.
|
||||
=== 2FA (by ROBOTSTXT) ===
|
||||
Contributors: robotstxt
|
||||
Tags: security, two-factor authentication, login, otp
|
||||
Requires at least: 6.4
|
||||
Tested up to: 7.0
|
||||
Requires PHP: 8.2
|
||||
Stable tag: 0.3.0
|
||||
License: GPLv3 or later
|
||||
License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
||||
|
||||
Security plugin that adds per-role two-factor authentication to the WordPress login flow.
|
||||
|
||||
== Description ==
|
||||
|
||||
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.
|
||||
|
||||
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 (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, 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 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 ==
|
||||
|
||||
= 0.3.0 =
|
||||
|
||||
_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 =
|
||||
|
||||
_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 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/)
|
||||
|
|
|
|||
|
|
@ -1,98 +1,99 @@
|
|||
<?php
|
||||
/**
|
||||
* 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
|
||||
* 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
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
use Robotstxt\TwoFA\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) {
|
||||
define( 'ROBOTSTXT_2FA_VERSION', '0.2.0' );
|
||||
}
|
||||
|
||||
if ( ! defined( 'ROBOTSTXT_2FA_FILE' ) ) {
|
||||
define( 'ROBOTSTXT_2FA_FILE', __FILE__ );
|
||||
}
|
||||
|
||||
if ( ! defined( 'ROBOTSTXT_2FA_PATH' ) ) {
|
||||
define( 'ROBOTSTXT_2FA_PATH', plugin_dir_path( __FILE__ ) );
|
||||
}
|
||||
|
||||
if ( ! defined( 'ROBOTSTXT_2FA_URL' ) ) {
|
||||
define( 'ROBOTSTXT_2FA_URL', plugin_dir_url( __FILE__ ) );
|
||||
}
|
||||
|
||||
$autoload = ROBOTSTXT_2FA_PATH . 'vendor/autoload.php';
|
||||
|
||||
if ( file_exists( $autoload ) ) {
|
||||
require_once $autoload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple autoloader for the plugin classes.
|
||||
*
|
||||
* @param string $class Fully qualified class name requested by PHP.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function robotstxt_2fa_autoload( string $class ): void {
|
||||
$prefix = 'Robotstxt\\TwoFA\\';
|
||||
|
||||
if ( strncmp( $prefix, $class, strlen( $prefix ) ) !== 0 ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$relative_class = substr( $class, strlen( $prefix ) );
|
||||
$relative_parts = explode( '\\', $relative_class );
|
||||
$filename = array_pop( $relative_parts );
|
||||
|
||||
$directories = '';
|
||||
|
||||
if ( ! empty( $relative_parts ) ) {
|
||||
$relative_parts = array_map(
|
||||
static function ( string $part ): string {
|
||||
return strtolower( str_replace( '_', '-', $part ) );
|
||||
},
|
||||
$relative_parts
|
||||
);
|
||||
|
||||
$directories = trailingslashit( implode( '/', $relative_parts ) );
|
||||
}
|
||||
|
||||
$filename = 'class-' . strtolower( str_replace( '_', '-', $filename ) ) . '.php';
|
||||
$path = trailingslashit( ROBOTSTXT_2FA_PATH . 'includes' ) . $directories . $filename;
|
||||
|
||||
if ( file_exists( $path ) ) {
|
||||
require_once $path;
|
||||
}
|
||||
}
|
||||
|
||||
spl_autoload_register( 'robotstxt_2fa_autoload' );
|
||||
|
||||
/**
|
||||
* Bootstrap the plugin once all plugins are loaded.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function robotstxt_2fa_bootstrap() {
|
||||
Plugin::get_instance()->init();
|
||||
}
|
||||
add_action( 'plugins_loaded', 'robotstxt_2fa_bootstrap' );
|
||||
|
||||
register_activation_hook( __FILE__, array( Plugin::class, 'activate' ) );
|
||||
register_deactivation_hook( __FILE__, array( Plugin::class, 'deactivate' ) );
|
||||
<?php
|
||||
/**
|
||||
* 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.3.0
|
||||
* Author: ROBOTSTXT
|
||||
* Author URI: https://www.robotstxt.es/
|
||||
* Text Domain: robotstxt-2fa
|
||||
* Requires at least: 6.4
|
||||
* Requires PHP: 8.2
|
||||
* Network: true
|
||||
* License: GPLv3 or later
|
||||
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
use Robotstxt\TwoFA\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) {
|
||||
define( 'ROBOTSTXT_2FA_VERSION', '0.3.0' );
|
||||
}
|
||||
|
||||
if ( ! defined( 'ROBOTSTXT_2FA_FILE' ) ) {
|
||||
define( 'ROBOTSTXT_2FA_FILE', __FILE__ );
|
||||
}
|
||||
|
||||
if ( ! defined( 'ROBOTSTXT_2FA_PATH' ) ) {
|
||||
define( 'ROBOTSTXT_2FA_PATH', plugin_dir_path( __FILE__ ) );
|
||||
}
|
||||
|
||||
if ( ! defined( 'ROBOTSTXT_2FA_URL' ) ) {
|
||||
define( 'ROBOTSTXT_2FA_URL', plugin_dir_url( __FILE__ ) );
|
||||
}
|
||||
|
||||
$robotstxt_2fa_autoload = ROBOTSTXT_2FA_PATH . 'vendor/autoload.php';
|
||||
|
||||
if ( file_exists( $robotstxt_2fa_autoload ) ) {
|
||||
require_once $robotstxt_2fa_autoload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple autoloader for the plugin classes.
|
||||
*
|
||||
* @param string $class_name Fully qualified class name requested by PHP.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function robotstxt_2fa_autoload( string $class_name ): void {
|
||||
$prefix = 'Robotstxt\\TwoFA\\';
|
||||
|
||||
if ( strncmp( $prefix, $class_name, strlen( $prefix ) ) !== 0 ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$relative_class = substr( $class_name, strlen( $prefix ) );
|
||||
$relative_parts = explode( '\\', $relative_class );
|
||||
$filename = array_pop( $relative_parts );
|
||||
|
||||
$directories = '';
|
||||
|
||||
if ( ! empty( $relative_parts ) ) {
|
||||
$relative_parts = array_map(
|
||||
static function ( string $part ): string {
|
||||
return strtolower( str_replace( '_', '-', $part ) );
|
||||
},
|
||||
$relative_parts
|
||||
);
|
||||
|
||||
$directories = trailingslashit( implode( '/', $relative_parts ) );
|
||||
}
|
||||
|
||||
$filename = 'class-' . strtolower( str_replace( '_', '-', $filename ) ) . '.php';
|
||||
$path = trailingslashit( ROBOTSTXT_2FA_PATH . 'includes' ) . $directories . $filename;
|
||||
|
||||
if ( file_exists( $path ) ) {
|
||||
require_once $path;
|
||||
}
|
||||
}
|
||||
|
||||
spl_autoload_register( 'robotstxt_2fa_autoload' );
|
||||
|
||||
/**
|
||||
* Bootstrap the plugin once all plugins are loaded.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function robotstxt_2fa_bootstrap() {
|
||||
Plugin::get_instance()->init();
|
||||
}
|
||||
add_action( 'plugins_loaded', 'robotstxt_2fa_bootstrap' );
|
||||
|
||||
register_activation_hook( __FILE__, array( Plugin::class, 'activate' ) );
|
||||
register_deactivation_hook( __FILE__, array( Plugin::class, 'deactivate' ) );
|
||||
|
|
|
|||
384
robotstxt-updater.php
Normal file
384
robotstxt-updater.php
Normal file
|
|
@ -0,0 +1,384 @@
|
|||
<?php
|
||||
/**
|
||||
* Generic JSON-based updater for ROBOTSTXT plugins.
|
||||
*
|
||||
* This file is designed to be copied to any ROBOTSTXT plugin.
|
||||
* It auto-configures itself by reading the plugin headers.
|
||||
*
|
||||
* @package ROBOTSTXT
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
if ( ! class_exists( 'Robotstxt_Updater' ) ) {
|
||||
/**
|
||||
* Class Robotstxt_Updater
|
||||
*
|
||||
* Generic updater that works with any plugin.
|
||||
* Reads plugin headers and constructs update URL automatically.
|
||||
*/
|
||||
class Robotstxt_Updater {
|
||||
|
||||
/**
|
||||
* Plugin file path.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $plugin_file_path;
|
||||
|
||||
/**
|
||||
* Plugin basename (e.g., 'my-plugin/my-plugin.php').
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $plugin_basename;
|
||||
|
||||
/**
|
||||
* Plugin slug (directory name).
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $plugin_slug;
|
||||
|
||||
/**
|
||||
* Remote JSON URL.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $json_url;
|
||||
|
||||
/**
|
||||
* Cache key.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $cache_key;
|
||||
|
||||
/**
|
||||
* Plugin headers.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private array $plugin_data;
|
||||
|
||||
/**
|
||||
* Initialize the updater.
|
||||
*
|
||||
* Usage in your main plugin file:
|
||||
* require_once __DIR__ . '/robotstxt-updater.php';
|
||||
* Robotstxt_Updater::init( __FILE__ );
|
||||
*
|
||||
* @param string $plugin_file_path Absolute path to the main plugin file.
|
||||
*/
|
||||
public static function init( string $plugin_file_path ): void {
|
||||
$instance = new self( $plugin_file_path );
|
||||
$instance->register();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param string $plugin_file_path Absolute path to the main plugin file.
|
||||
*/
|
||||
private function __construct( string $plugin_file_path ) {
|
||||
$this->plugin_file_path = $plugin_file_path;
|
||||
$this->plugin_basename = plugin_basename( $plugin_file_path );
|
||||
$this->plugin_slug = dirname( $this->plugin_basename );
|
||||
$this->plugin_data = $this->get_plugin_data();
|
||||
$this->json_url = $this->build_json_url();
|
||||
$this->cache_key = 'robotstxt_updater_' . md5( $this->plugin_basename );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register WordPress hooks.
|
||||
*/
|
||||
private function register(): void {
|
||||
add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'inject_update_info' ) );
|
||||
add_filter( 'plugins_api', array( $this, 'provide_plugin_details' ), 10, 3 );
|
||||
add_action( 'admin_init', array( $this, 'handle_cache_clear' ) );
|
||||
add_action( 'robotstxt_updater_clear_cache', array( $this, 'clear_cache' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get plugin headers.
|
||||
*
|
||||
* @return array Plugin data.
|
||||
*/
|
||||
private function get_plugin_data(): array {
|
||||
if ( ! function_exists( 'get_plugin_data' ) ) {
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
}
|
||||
|
||||
return get_plugin_data( $this->plugin_file_path, false, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Build JSON URL from plugin headers.
|
||||
*
|
||||
* Tries to use "Gitea Plugin URI" header to construct the URL.
|
||||
* Falls back to Plugin URI if Gitea URI is not available.
|
||||
*
|
||||
* @return string JSON URL.
|
||||
*/
|
||||
private function build_json_url(): string {
|
||||
// Try Gitea Plugin URI (format: "OWNER/REPO" or full URL).
|
||||
if ( ! empty( $this->plugin_data['Gitea Plugin URI'] ) ) {
|
||||
$gitea_uri = $this->plugin_data['Gitea Plugin URI'];
|
||||
|
||||
// If it's already a full URL, use it.
|
||||
if ( str_starts_with( $gitea_uri, 'http' ) ) {
|
||||
// Extract base URL and construct JSON path.
|
||||
return rtrim( $gitea_uri, '/' ) . '/raw/branch/main/update.json';
|
||||
}
|
||||
|
||||
// If it's in format "OWNER/REPO", construct full URL.
|
||||
if ( preg_match( '#^[^/]+/[^/]+$#', $gitea_uri ) ) {
|
||||
return "https://git.robotstxt.es/{$gitea_uri}/raw/branch/main/update.json";
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: try to extract from Plugin URI.
|
||||
if ( ! empty( $this->plugin_data['PluginURI'] ) ) {
|
||||
$plugin_uri = $this->plugin_data['PluginURI'];
|
||||
if ( str_contains( $plugin_uri, 'git.robotstxt.es' ) ) {
|
||||
return rtrim( $plugin_uri, '/' ) . '/raw/branch/main/update.json';
|
||||
}
|
||||
}
|
||||
|
||||
// Last resort: construct from plugin slug.
|
||||
return "https://git.robotstxt.es/ROBOTSTXT/{$this->plugin_slug}/raw/branch/main/update.json";
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject update info into WP's plugin update transient.
|
||||
*
|
||||
* @param object|mixed $transient The update_plugins transient.
|
||||
*
|
||||
* @return object The modified transient.
|
||||
*/
|
||||
public function inject_update_info( $transient ) {
|
||||
if ( ! is_object( $transient ) ) {
|
||||
$transient = new stdClass();
|
||||
}
|
||||
|
||||
if ( empty( $transient->checked ) || ! is_array( $transient->checked ) ) {
|
||||
return $transient;
|
||||
}
|
||||
|
||||
if ( empty( $transient->checked[ $this->plugin_basename ] ) ) {
|
||||
return $transient;
|
||||
}
|
||||
|
||||
$current_version = $transient->checked[ $this->plugin_basename ];
|
||||
$remote = $this->get_remote_data();
|
||||
|
||||
if ( empty( $remote['version'] ) || empty( $remote['download_url'] ) ) {
|
||||
return $transient;
|
||||
}
|
||||
|
||||
if ( ! $this->is_compatible( $remote ) ) {
|
||||
return $transient;
|
||||
}
|
||||
|
||||
if ( version_compare( $remote['version'], $current_version, '>' ) ) {
|
||||
$update = (object) array(
|
||||
'slug' => $remote['slug'] ?? $this->plugin_slug,
|
||||
'plugin' => $this->plugin_basename,
|
||||
'new_version' => $remote['version'],
|
||||
'url' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '',
|
||||
'package' => $remote['download_url'],
|
||||
'tested' => $remote['tested'] ?? '',
|
||||
'requires' => $remote['requires'] ?? '',
|
||||
'requires_php' => $remote['requires_php'] ?? '',
|
||||
);
|
||||
|
||||
$transient->response[ $this->plugin_basename ] = $update;
|
||||
}
|
||||
|
||||
return $transient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide "View details" modal content.
|
||||
*
|
||||
* @param false|object|array $result The result object or array.
|
||||
* @param string $action The type of information being requested.
|
||||
* @param object $args Plugin API arguments.
|
||||
*
|
||||
* @return false|object The plugin information object or false.
|
||||
*/
|
||||
public function provide_plugin_details( $result, string $action, object $args ) {
|
||||
if ( 'plugin_information' !== $action ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
if ( empty( $args->slug ) || $args->slug !== $this->plugin_slug ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$remote = $this->get_remote_data();
|
||||
|
||||
if ( empty( $remote['version'] ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return (object) array(
|
||||
'name' => $remote['name'] ?? $this->plugin_data['Name'] ?? $this->plugin_slug,
|
||||
'slug' => $remote['slug'] ?? $this->plugin_slug,
|
||||
'version' => $remote['version'],
|
||||
'author' => $remote['author'] ?? $this->plugin_data['Author'] ?? '',
|
||||
'homepage' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '',
|
||||
'requires' => $remote['requires'] ?? '',
|
||||
'tested' => $remote['tested'] ?? '',
|
||||
'requires_php' => $remote['requires_php'] ?? '',
|
||||
'sections' => array(
|
||||
'description' => $remote['description'] ?? $this->plugin_data['Description'] ?? '',
|
||||
'changelog' => $remote['changelog'] ?? '',
|
||||
),
|
||||
'download_link' => $remote['download_url'] ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get remote data with caching and HMAC signature verification.
|
||||
*
|
||||
* @return array Remote data.
|
||||
*/
|
||||
private function get_remote_data(): array {
|
||||
$cached = get_site_transient( $this->cache_key );
|
||||
|
||||
// Verify HMAC signature if AUTH_SALT is defined and cache has signature.
|
||||
if ( false !== $cached && defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
|
||||
if ( is_array( $cached ) && isset( $cached['signature'], $cached['data'] ) ) {
|
||||
$expected_sig = hash_hmac( 'sha256', $this->cache_key . serialize( $cached['data'] ), AUTH_SALT ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Used for HMAC signing, not for unserializing untrusted data.
|
||||
|
||||
if ( hash_equals( $expected_sig, $cached['signature'] ) ) {
|
||||
// Signature valid, return data.
|
||||
return is_array( $cached['data'] ) ? $cached['data'] : array();
|
||||
}
|
||||
|
||||
// Signature invalid, delete corrupted cache.
|
||||
delete_site_transient( $this->cache_key );
|
||||
$cached = false;
|
||||
}
|
||||
}
|
||||
|
||||
// If no valid cache, fetch fresh data.
|
||||
if ( false === $cached ) {
|
||||
$remote = $this->fetch_json();
|
||||
|
||||
// Store with HMAC signature if AUTH_SALT is available.
|
||||
if ( defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
|
||||
$remote_data = is_array( $remote ) ? $remote : array();
|
||||
$payload = array(
|
||||
'data' => $remote_data,
|
||||
'timestamp' => time(),
|
||||
'signature' => hash_hmac( 'sha256', $this->cache_key . serialize( $remote_data ), AUTH_SALT ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Used for HMAC signing, not for unserializing untrusted data.
|
||||
);
|
||||
set_site_transient( $this->cache_key, $payload, 6 * HOUR_IN_SECONDS );
|
||||
} else {
|
||||
// Fallback to standard caching.
|
||||
set_site_transient( $this->cache_key, is_array( $remote ) ? $remote : array(), 6 * HOUR_IN_SECONDS );
|
||||
}
|
||||
|
||||
return is_array( $remote ) ? $remote : array();
|
||||
}
|
||||
|
||||
// Legacy cache format without signature (backward compatibility).
|
||||
return is_array( $cached ) ? $cached : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch JSON from remote URL.
|
||||
*
|
||||
* @return array Decoded JSON data.
|
||||
*/
|
||||
private function fetch_json(): array {
|
||||
$response = wp_remote_get(
|
||||
$this->json_url,
|
||||
array(
|
||||
'timeout' => 10,
|
||||
'headers' => array(
|
||||
'Accept' => 'application/json',
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$code = (int) wp_remote_retrieve_response_code( $response );
|
||||
if ( $code < 200 || $code >= 300 ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$body = wp_remote_retrieve_body( $response );
|
||||
$data = json_decode( $body, true );
|
||||
|
||||
return is_array( $data ) ? $data : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check compatibility.
|
||||
*
|
||||
* @param array $remote Remote data.
|
||||
*
|
||||
* @return bool True if compatible.
|
||||
*/
|
||||
private function is_compatible( array $remote ): bool {
|
||||
if ( ! empty( $remote['requires_php'] ) ) {
|
||||
if ( version_compare( PHP_VERSION, $remote['requires_php'], '<' ) ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! empty( $remote['requires'] ) ) {
|
||||
if ( version_compare( get_bloginfo( 'version' ), $remote['requires'], '<' ) ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle manual cache clear via URL parameter.
|
||||
*/
|
||||
public function handle_cache_clear(): void {
|
||||
// Check if this is a cache clear request first.
|
||||
$clear_cache = filter_input( INPUT_GET, 'robotstxt_clear_update_cache', FILTER_UNSAFE_RAW );
|
||||
if ( null === $clear_cache ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// This is a cache clear request - now verify nonce.
|
||||
$nonce_raw = filter_input( INPUT_GET, '_wpnonce', FILTER_UNSAFE_RAW );
|
||||
$nonce = $nonce_raw ? sanitize_text_field( wp_unslash( $nonce_raw ) ) : '';
|
||||
|
||||
if ( ! wp_verify_nonce( $nonce, 'robotstxt_clear_update_cache' ) ) {
|
||||
wp_die( esc_html__( 'Security check failed', 'robotstxt-2fa' ) );
|
||||
}
|
||||
|
||||
// Check permissions.
|
||||
if ( ! current_user_can( 'update_plugins' ) ) {
|
||||
wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'robotstxt-2fa' ) );
|
||||
}
|
||||
|
||||
$this->clear_cache();
|
||||
wp_safe_redirect( remove_query_arg( array( 'robotstxt_clear_update_cache', '_wpnonce' ) ) );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear update cache.
|
||||
*/
|
||||
public function clear_cache(): void {
|
||||
delete_site_transient( $this->cache_key );
|
||||
delete_site_transient( 'update_plugins' );
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue