v0.3.0
This commit is contained in:
parent
f936aeb807
commit
968211baad
99 changed files with 15548 additions and 14530 deletions
33
AGENTS.md
33
AGENTS.md
|
|
@ -1,33 +0,0 @@
|
||||||
# AGENT INSTRUCTIONS
|
|
||||||
|
|
||||||
This repository contains the WordPress plugin **2FA (by ROBOTSTXT)**. Follow these rules whenever you work on any file within this repository:
|
|
||||||
|
|
||||||
1. **Language**
|
|
||||||
- Write every piece of documentation, copy, and code comments in English.
|
|
||||||
|
|
||||||
2. **Code standards**
|
|
||||||
- All PHP code must comply with **PHPCS** and **WPCS**.
|
|
||||||
- Use tabs for indentation (no spaces).
|
|
||||||
- Ensure compatibility with **PHP 8.2** or higher.
|
|
||||||
- Provide proper **PHPDoc** annotations for classes, properties, and methods.
|
|
||||||
|
|
||||||
3. **WordPress security**
|
|
||||||
- Sanitize, validate, and escape all user-provided data.
|
|
||||||
- Include nonces in forms and verify them before processing submissions.
|
|
||||||
- Do not suppress validation or authentication errors.
|
|
||||||
|
|
||||||
4. **Plugin structure**
|
|
||||||
- Keep the code modular inside the `includes/` directory.
|
|
||||||
- Place admin-related logic in subdirectories under `includes/admin/`.
|
|
||||||
- Store presentational templates in `templates/`.
|
|
||||||
- Whenever new persistent data (options, tables, user meta, etc.) is introduced, update `uninstall.php` so the plugin removes it on uninstall.
|
|
||||||
|
|
||||||
5. **Testing and tooling**
|
|
||||||
- Run all available checks (PHPCS, PHPUnit, etc.) after making changes.
|
|
||||||
- Summarize the commands executed and their results in the final message.
|
|
||||||
|
|
||||||
6. **Documentation**
|
|
||||||
- Update `readme.txt` and `changelog.txt` whenever functional changes are introduced.
|
|
||||||
- Explain *why* when the reason for a piece of code is not obvious.
|
|
||||||
|
|
||||||
These instructions apply to the entire repository tree.
|
|
||||||
69
CHANGELOG.md
Normal file
69
CHANGELOG.md
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project are documented in this file.
|
||||||
|
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.3.0] - 2026-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Delete-on-uninstall option in admin settings Data Management section (off by default — all data is preserved).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Network admin settings page now correctly saves to `wp_sitemeta` via a dedicated `network_admin_edit_` handler.
|
||||||
|
- Settings option stored with `autoload=false` — not needed on every page load.
|
||||||
|
- Recovery code preview transient TTL reduced from 0 (persistent) to 300 seconds (5 minutes).
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- Email verification codes now use `random_int()` (CSPRNG) instead of `wp_rand()` (Mersenne Twister), consistent with recovery codes and OTP secrets.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- `get_required_capability()` now returns `manage_network_options` in network admin context.
|
||||||
|
- `bin/deploy.sh` now excludes `CLAUDE.md`, `AGENTS.md`, `README.md`, `DOCUMENTATION-*.md`, and `.phpunit.result.cache` from the ZIP artifact.
|
||||||
|
- `update.json` corrected: was shipping SMTP plugin data instead of 2FA plugin data.
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Per-role 2FA method matrix: admins choose exactly which verification methods (email, OTP, recovery codes) are required for each WordPress role, with select-all row and column toggles.
|
||||||
|
- Authenticator app (TOTP) support: secrets stored as Base32, QR code rendered via `bacon/bacon-qr-code`, manual setup key displayed as fallback.
|
||||||
|
- Recovery codes: 10 single-use 8-digit codes, one-time display grid with copy-to-clipboard, mandatory confirmation before activation, auto-refresh when batch exhausted.
|
||||||
|
- Email verification codes: 7-digit codes, 10-minute expiry, 60-second resend throttle.
|
||||||
|
- Configurable verification frequency remembered per device fingerprint (every login / daily / weekly / monthly); administrators can lock the global schedule.
|
||||||
|
- Dedicated stage token (WP nonce) securing the 2FA screen between password validation and code entry.
|
||||||
|
- Method-switch links on the verification screen (OTP ↔ email ↔ recovery codes) without restarting the login.
|
||||||
|
- Multisite support: `Network: true` header; network admins set and lock enforcement settings.
|
||||||
|
- `uninstall.php` removes all plugin options and user meta on deletion.
|
||||||
|
- `bin/deploy.sh` for manual ZIP packaging.
|
||||||
|
- PHPUnit test suite with plugin-header tests.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Settings UI replaces flat forced-roles list with per-role method matrix; existing `force_roles` + `default_method` data is automatically migrated.
|
||||||
|
- Profile method checkboxes require explicit confirmation before activating (OTP: valid 6-digit code; recovery codes: enter one displayed code).
|
||||||
|
- Required methods indicated with a "required for your role" badge in the profile; checkboxes disabled and hidden inputs ensure values survive submission.
|
||||||
|
- Login screen hides username/password fields, removes Remember Me, focuses code input, and auto-submits when digit count is reached.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- QR generation errors caught and surfaced to administrators; graceful fallback to text setup key.
|
||||||
|
- Recovery-code preview persists via transient until explicitly acknowledged.
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- All `$_POST`/`$_GET`/`$_SERVER` reads guarded with `is_string()` before passing to sanitize functions.
|
||||||
|
- PHPStan level 9 passes with zero errors; no mixed-type casts.
|
||||||
|
- `composer audit`: no known vulnerabilities in any dependency.
|
||||||
|
|
||||||
|
## [0.1.0] - 2024-04-08
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Initial plugin skeleton with placeholder classes for login handling, user profile, and admin settings.
|
||||||
|
- Initial documentation files.
|
||||||
|
|
@ -1,2 +0,0 @@
|
||||||
# robotstxt-2fa
|
|
||||||
Simple 2FA WordPress plugin
|
|
||||||
|
|
@ -1,42 +1,69 @@
|
||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
### Added
|
|
||||||
- Authenticator app support with stored secrets and QR provisioning powered by the optional `bacon/bacon-qr-code` library.
|
|
||||||
- Recovery code confirmation workflow that requires entering one of the freshly generated codes before hiding them.
|
|
||||||
- Single-use recovery codes with profile management, one-time display, and login validation.
|
|
||||||
- Dedicated verification stage token that secures 2FA screens and allows protected email code resends.
|
|
||||||
- Admin settings page with role-based enforcement controls for two-factor authentication.
|
|
||||||
- Uninstall routine that removes stored plugin options.
|
|
||||||
- Network-wide enforcement options for WordPress multisite installations.
|
|
||||||
- Email-based verification codes with throttled delivery and expiry handling.
|
|
||||||
- Configurable verification frequency that remembers trusted devices while allowing administrators to lock the schedule per site.
|
|
||||||
|
|
||||||
### Changed
|
## [0.3.0] - 2026-06-05
|
||||||
- Profile method toggles now start unchecked and require validating authenticator and recovery codes before activation, with new inline prompts and regenerated secrets when options are disabled.
|
|
||||||
- The profile screen now keeps recovery codes visible in a two-column grid until one is confirmed, shows remaining counts, and automatically refreshes the list when the stored batch is exhausted.
|
### Added
|
||||||
- Email verification now displays the destination address alongside the method label.
|
|
||||||
- The login verification screen now hides the username/password fields, exposes a back-to-login link, and supports email code resends from a dedicated query-flagged URL.
|
- Delete-on-uninstall option (disabled by default — all plugin data is preserved on removal).
|
||||||
- The verification stage now enforces authenticator app codes when they are enabled and exposes secure links to switch between OTP, email, and recovery-code challenges without restarting the login.
|
|
||||||
- Promoted the settings interface to a dedicated top-level Two-Factor Authentication menu for easier discovery.
|
### Security
|
||||||
- Adjusted the Two-Factor Authentication menu position so it appears within the plugins section of the admin navigation.
|
|
||||||
- User profile settings now persist preferences and automatically enforce role-based 2FA requirements.
|
- Email verification codes now use `random_int()` (CSPRNG) for cryptographically secure code generation.
|
||||||
- The login screen now auto-submits verification forms once the active method reaches its required length (six digits for OTP, seven for email, eight for recovery codes) and removes the Remember Me control during OTP checks.
|
- Recovery code preview transient TTL reduced from indefinite to 5 minutes.
|
||||||
- Recovery code requests now submit through the native profile form, regenerate codes server-side, and remember the section anchor on the redirect so the refreshed screen focuses the two-factor settings.
|
|
||||||
- The refreshed profile screen renders the newly issued ten codes inside a notice, including copy controls and updated status messaging, without relying on JavaScript-driven form submissions.
|
|
||||||
- The generator button now submits the profile form directly, honours core capability checks, and shares nonce validation with the existing profile workflow.
|
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- Prevented a fatal error on the profile screen by exposing the recovery code batch size helper used during rendering.
|
|
||||||
- Corrected the recovery-code confirmation flow so previews persist until acknowledged and the confirmation code is accepted.
|
- Network admin settings now save correctly via a dedicated handler writing to `wp_sitemeta`.
|
||||||
- Hardened authenticator QR generation by catching library errors and pointing administrators to the required bacon/bacon-qr-code ^3.0 dependency.
|
- Settings option registered with `autoload=false` to avoid loading on every page request.
|
||||||
- Improved recovery-code AJAX error handling so failed requests surface localized messages instead of silently failing.
|
- `update.json` corrected to reference the 2FA plugin instead of the SMTP plugin.
|
||||||
- Forced roles now see two-factor authentication enabled with the default email method selected in their profile, and per-user data is purged during uninstall.
|
|
||||||
- Restored the login verification handlers so the authenticate filter no longer triggers fatal errors and email challenges complete successfully.
|
**Compatibility**
|
||||||
- Ensured the profile recovery-code generator always reaches `admin-ajax.php`, even when localized data is missing, so the button reliably displays the codes inline.
|
|
||||||
|
* WordPress: 6.4 – 7.1
|
||||||
|
* PHP: 8.2 – 8.5
|
||||||
|
|
||||||
|
**Tests**
|
||||||
|
|
||||||
|
* PHP Coding Standards: PHP_CodeSniffer 3.13.5 / WPCS 3.3.0
|
||||||
|
* PHPStan: level 9 — 0 errors
|
||||||
|
* PHPCompatibility: 8.2–8.5 — 0 issues
|
||||||
|
* PHPUnit: 9.6.34 — 42 tests, 109 assertions
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Per-role 2FA method matrix in admin settings: administrators can now choose exactly which verification methods (email, authenticator app, recovery codes) are required for each WordPress role, with select-all row and column controls.
|
||||||
|
- Authenticator app (TOTP) support: stored secrets, QR code provisioning via `bacon/bacon-qr-code`, manual setup key display, and one-time activation confirmation.
|
||||||
|
- Recovery codes: 10 single-use 8-digit codes with profile management, one-time display grid, copy-to-clipboard, and mandatory confirmation before activation.
|
||||||
|
- Email-based verification codes with throttled delivery (60 s resend cooldown) and 10-minute expiry.
|
||||||
|
- Configurable verification frequency (every login, daily, weekly, or every 28 days) remembered per device fingerprint; administrators can lock the global schedule.
|
||||||
|
- Dedicated verification stage token (WP nonce) securing the 2FA screen between password validation and code submission.
|
||||||
|
- Secure method-switch links on the verification screen letting users change between OTP, email, and recovery-code challenges without restarting the login.
|
||||||
|
- Network-wide multisite support: network administrators can set and lock enforcement settings across all sites (`Network: true` header).
|
||||||
|
- Uninstall routine removing all plugin options and user meta.
|
||||||
|
- Admin settings page as a top-level menu with `manage_options` capability guard.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Settings page now uses the per-role method matrix instead of a flat forced-roles list; old `force_roles` + `default_method` data is automatically migrated on first read.
|
||||||
|
- Profile method checkboxes require explicit confirmation: OTP demands a valid 6-digit code, recovery codes demand entering one of the displayed codes before the method activates.
|
||||||
|
- Profile screen regenerates the OTP secret when the authenticator method is disabled and provides a "Generate new secret" button.
|
||||||
|
- Recovery code batch exhaustion now auto-generates a fresh batch and surfaces a confirmation prompt rather than locking the user out.
|
||||||
|
- Login screen hides the username/password fields, removes the Remember Me checkbox, and focuses the verification code input during the 2FA stage.
|
||||||
|
- Login form auto-submits once the input reaches the method's expected digit count.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Hardened authenticator QR generation by catching library errors and guiding administrators to the required dependency.
|
||||||
|
- Recovery-code preview persists via transient until explicitly acknowledged; fixes cases where codes disappeared before confirmation.
|
||||||
|
|
||||||
## [0.1.0] - 2024-04-08
|
## [0.1.0] - 2024-04-08
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- Initial skeleton for the 2FA (by ROBOTSTXT) plugin.
|
- Initial skeleton for the 2FA (by ROBOTSTXT) plugin.
|
||||||
- Initial documentation files (`readme.txt`, `AGENTS.md`, `changelog.txt`).
|
- Initial documentation files (`readme.txt`, `AGENTS.md`, `changelog.txt`).
|
||||||
- Placeholder classes for login handling, user profile integration, and admin settings.
|
- Placeholder classes for login handling, user profile integration, and admin settings.
|
||||||
|
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
{
|
|
||||||
"require": {
|
|
||||||
"bacon/bacon-qr-code": "^3.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
123
composer.lock
generated
123
composer.lock
generated
|
|
@ -1,123 +0,0 @@
|
||||||
{
|
|
||||||
"_readme": [
|
|
||||||
"This file locks the dependencies of your project to a known state",
|
|
||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
|
||||||
"This file is @generated automatically"
|
|
||||||
],
|
|
||||||
"content-hash": "9d7cd0dbebfa0273a358b926795e7b8a",
|
|
||||||
"packages": [
|
|
||||||
{
|
|
||||||
"name": "bacon/bacon-qr-code",
|
|
||||||
"version": "v3.0.1",
|
|
||||||
"source": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/Bacon/BaconQrCode.git",
|
|
||||||
"reference": "f9cc1f52b5a463062251d666761178dbdb6b544f"
|
|
||||||
},
|
|
||||||
"dist": {
|
|
||||||
"type": "zip",
|
|
||||||
"url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/f9cc1f52b5a463062251d666761178dbdb6b544f",
|
|
||||||
"reference": "f9cc1f52b5a463062251d666761178dbdb6b544f",
|
|
||||||
"shasum": ""
|
|
||||||
},
|
|
||||||
"require": {
|
|
||||||
"dasprid/enum": "^1.0.3",
|
|
||||||
"ext-iconv": "*",
|
|
||||||
"php": "^8.1"
|
|
||||||
},
|
|
||||||
"require-dev": {
|
|
||||||
"phly/keep-a-changelog": "^2.12",
|
|
||||||
"phpunit/phpunit": "^10.5.11 || 11.0.4",
|
|
||||||
"spatie/phpunit-snapshot-assertions": "^5.1.5",
|
|
||||||
"squizlabs/php_codesniffer": "^3.9"
|
|
||||||
},
|
|
||||||
"suggest": {
|
|
||||||
"ext-imagick": "to generate QR code images"
|
|
||||||
},
|
|
||||||
"type": "library",
|
|
||||||
"autoload": {
|
|
||||||
"psr-4": {
|
|
||||||
"BaconQrCode\\": "src/"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"notification-url": "https://packagist.org/downloads/",
|
|
||||||
"license": [
|
|
||||||
"BSD-2-Clause"
|
|
||||||
],
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "Ben Scholzen 'DASPRiD'",
|
|
||||||
"email": "mail@dasprids.de",
|
|
||||||
"homepage": "https://dasprids.de/",
|
|
||||||
"role": "Developer"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "BaconQrCode is a QR code generator for PHP.",
|
|
||||||
"homepage": "https://github.com/Bacon/BaconQrCode",
|
|
||||||
"support": {
|
|
||||||
"issues": "https://github.com/Bacon/BaconQrCode/issues",
|
|
||||||
"source": "https://github.com/Bacon/BaconQrCode/tree/v3.0.1"
|
|
||||||
},
|
|
||||||
"time": "2024-10-01T13:55:55+00:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "dasprid/enum",
|
|
||||||
"version": "1.0.7",
|
|
||||||
"source": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/DASPRiD/Enum.git",
|
|
||||||
"reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce"
|
|
||||||
},
|
|
||||||
"dist": {
|
|
||||||
"type": "zip",
|
|
||||||
"url": "https://api.github.com/repos/DASPRiD/Enum/zipball/b5874fa9ed0043116c72162ec7f4fb50e02e7cce",
|
|
||||||
"reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce",
|
|
||||||
"shasum": ""
|
|
||||||
},
|
|
||||||
"require": {
|
|
||||||
"php": ">=7.1 <9.0"
|
|
||||||
},
|
|
||||||
"require-dev": {
|
|
||||||
"phpunit/phpunit": "^7 || ^8 || ^9 || ^10 || ^11",
|
|
||||||
"squizlabs/php_codesniffer": "*"
|
|
||||||
},
|
|
||||||
"type": "library",
|
|
||||||
"autoload": {
|
|
||||||
"psr-4": {
|
|
||||||
"DASPRiD\\Enum\\": "src/"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"notification-url": "https://packagist.org/downloads/",
|
|
||||||
"license": [
|
|
||||||
"BSD-2-Clause"
|
|
||||||
],
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "Ben Scholzen 'DASPRiD'",
|
|
||||||
"email": "mail@dasprids.de",
|
|
||||||
"homepage": "https://dasprids.de/",
|
|
||||||
"role": "Developer"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "PHP 7.1 enum implementation",
|
|
||||||
"keywords": [
|
|
||||||
"enum",
|
|
||||||
"map"
|
|
||||||
],
|
|
||||||
"support": {
|
|
||||||
"issues": "https://github.com/DASPRiD/Enum/issues",
|
|
||||||
"source": "https://github.com/DASPRiD/Enum/tree/1.0.7"
|
|
||||||
},
|
|
||||||
"time": "2025-09-16T12:23:56+00:00"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"packages-dev": [],
|
|
||||||
"aliases": [],
|
|
||||||
"minimum-stability": "stable",
|
|
||||||
"stability-flags": [],
|
|
||||||
"prefer-stable": false,
|
|
||||||
"prefer-lowest": false,
|
|
||||||
"platform": [],
|
|
||||||
"platform-dev": [],
|
|
||||||
"plugin-api-version": "2.6.0"
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,110 +1,110 @@
|
||||||
<?php
|
<?php
|
||||||
/**
|
/**
|
||||||
* Normalize and expose two-factor verification frequency options.
|
* Normalize and expose two-factor verification frequency options.
|
||||||
*
|
*
|
||||||
* @package Robotstxt_2FA
|
* @package Robotstxt_2FA
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace Robotstxt\TwoFA;
|
namespace Robotstxt\TwoFA;
|
||||||
|
|
||||||
if ( ! defined( 'ABSPATH' ) ) {
|
if ( ! defined( 'ABSPATH' ) ) {
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Utility helpers for two-factor verification frequency handling.
|
* Utility helpers for two-factor verification frequency handling.
|
||||||
*/
|
*/
|
||||||
class Frequency_Options {
|
class Frequency_Options {
|
||||||
/**
|
/**
|
||||||
* Frequency key representing per-session verification.
|
* Frequency key representing per-session verification.
|
||||||
*/
|
*/
|
||||||
public const FREQUENCY_SESSION = 'session';
|
public const FREQUENCY_SESSION = 'session';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Frequency key representing at most one verification per day.
|
* Frequency key representing at most one verification per day.
|
||||||
*/
|
*/
|
||||||
public const FREQUENCY_DAILY = 'daily';
|
public const FREQUENCY_DAILY = 'daily';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Frequency key representing at most one verification per week.
|
* Frequency key representing at most one verification per week.
|
||||||
*/
|
*/
|
||||||
public const FREQUENCY_WEEKLY = 'weekly';
|
public const FREQUENCY_WEEKLY = 'weekly';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Frequency key representing at most one verification per 28 days.
|
* Frequency key representing at most one verification per 28 days.
|
||||||
*/
|
*/
|
||||||
public const FREQUENCY_MONTHLY = 'monthly';
|
public const FREQUENCY_MONTHLY = 'monthly';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the available frequency options for display.
|
* Retrieve the available frequency options for display.
|
||||||
*
|
*
|
||||||
* @return array<string, array<string, string>>
|
* @return array<string, array<string, string>>
|
||||||
*/
|
*/
|
||||||
public static function get_options(): array {
|
public static function get_options(): array {
|
||||||
return array(
|
return array(
|
||||||
self::FREQUENCY_SESSION => array(
|
self::FREQUENCY_SESSION => array(
|
||||||
'label' => __( 'Every login', 'robotstxt-2fa' ),
|
'label' => __( 'Every login', 'robotstxt-2fa' ),
|
||||||
'description' => __( 'Always require a new verification code after the password step.', 'robotstxt-2fa' ),
|
'description' => __( 'Always require a new verification code after the password step.', 'robotstxt-2fa' ),
|
||||||
),
|
),
|
||||||
self::FREQUENCY_DAILY => array(
|
self::FREQUENCY_DAILY => array(
|
||||||
'label' => __( 'Daily', 'robotstxt-2fa' ),
|
'label' => __( 'Daily', 'robotstxt-2fa' ),
|
||||||
'description' => __( 'Remember successful verifications for 24 hours per device.', 'robotstxt-2fa' ),
|
'description' => __( 'Remember successful verifications for 24 hours per device.', 'robotstxt-2fa' ),
|
||||||
),
|
),
|
||||||
self::FREQUENCY_WEEKLY => array(
|
self::FREQUENCY_WEEKLY => array(
|
||||||
'label' => __( 'Weekly', 'robotstxt-2fa' ),
|
'label' => __( 'Weekly', 'robotstxt-2fa' ),
|
||||||
'description' => __( 'Remember successful verifications for 7 days per device.', 'robotstxt-2fa' ),
|
'description' => __( 'Remember successful verifications for 7 days per device.', 'robotstxt-2fa' ),
|
||||||
),
|
),
|
||||||
self::FREQUENCY_MONTHLY => array(
|
self::FREQUENCY_MONTHLY => array(
|
||||||
'label' => __( 'Monthly', 'robotstxt-2fa' ),
|
'label' => __( 'Monthly', 'robotstxt-2fa' ),
|
||||||
'description' => __( 'Remember successful verifications for 28 days per device.', 'robotstxt-2fa' ),
|
'description' => __( 'Remember successful verifications for 28 days per device.', 'robotstxt-2fa' ),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the allowed option keys.
|
* Retrieve the allowed option keys.
|
||||||
*
|
*
|
||||||
* @return array<int, string>
|
* @return array<int, string>
|
||||||
*/
|
*/
|
||||||
public static function get_allowed_keys(): array {
|
public static function get_allowed_keys(): array {
|
||||||
return array_keys( self::get_options() );
|
return array_keys( self::get_options() );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sanitize a frequency key against the supported values.
|
* Sanitize a frequency key against the supported values.
|
||||||
*
|
*
|
||||||
* @param string $frequency Submitted frequency value.
|
* @param string $frequency Submitted frequency value.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public static function sanitize( string $frequency ): string {
|
public static function sanitize( string $frequency ): string {
|
||||||
$frequency = sanitize_key( $frequency );
|
$frequency = sanitize_key( $frequency );
|
||||||
|
|
||||||
if ( in_array( $frequency, self::get_allowed_keys(), true ) ) {
|
if ( in_array( $frequency, self::get_allowed_keys(), true ) ) {
|
||||||
return $frequency;
|
return $frequency;
|
||||||
}
|
}
|
||||||
|
|
||||||
return self::FREQUENCY_SESSION;
|
return self::FREQUENCY_SESSION;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve the interval in seconds represented by a frequency.
|
* Resolve the interval in seconds represented by a frequency.
|
||||||
*
|
*
|
||||||
* @param string $frequency Frequency identifier.
|
* @param string $frequency Frequency identifier.
|
||||||
*
|
*
|
||||||
* @return int
|
* @return int
|
||||||
*/
|
*/
|
||||||
public static function get_interval_seconds( string $frequency ): int {
|
public static function get_interval_seconds( string $frequency ): int {
|
||||||
switch ( $frequency ) {
|
switch ( $frequency ) {
|
||||||
case self::FREQUENCY_DAILY:
|
case self::FREQUENCY_DAILY:
|
||||||
return DAY_IN_SECONDS;
|
return DAY_IN_SECONDS;
|
||||||
case self::FREQUENCY_WEEKLY:
|
case self::FREQUENCY_WEEKLY:
|
||||||
return WEEK_IN_SECONDS;
|
return WEEK_IN_SECONDS;
|
||||||
case self::FREQUENCY_MONTHLY:
|
case self::FREQUENCY_MONTHLY:
|
||||||
return 28 * DAY_IN_SECONDS;
|
return 28 * DAY_IN_SECONDS;
|
||||||
case self::FREQUENCY_SESSION:
|
case self::FREQUENCY_SESSION:
|
||||||
default:
|
default:
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,120 +1,120 @@
|
||||||
<?php
|
<?php
|
||||||
/**
|
/**
|
||||||
* Core plugin bootstrap.
|
* Core plugin bootstrap.
|
||||||
*
|
*
|
||||||
* @package Robotstxt_2FA
|
* @package Robotstxt_2FA
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace Robotstxt\TwoFA;
|
namespace Robotstxt\TwoFA;
|
||||||
|
|
||||||
use Robotstxt\TwoFA\Admin\Settings_Page;
|
use Robotstxt\TwoFA\Admin\Settings_Page;
|
||||||
use Robotstxt\TwoFA\Login\Login_Form_Manager;
|
use Robotstxt\TwoFA\Login\Login_Form_Manager;
|
||||||
use Robotstxt\TwoFA\User\Profile_Settings;
|
use Robotstxt\TwoFA\User\Profile_Settings;
|
||||||
use Robotstxt\TwoFA\User\Recovery_Codes;
|
use Robotstxt\TwoFA\User\Recovery_Codes;
|
||||||
|
|
||||||
if ( ! defined( 'ABSPATH' ) ) {
|
if ( ! defined( 'ABSPATH' ) ) {
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Main plugin controller.
|
* Main plugin controller.
|
||||||
*/
|
*/
|
||||||
class Plugin {
|
class Plugin {
|
||||||
/**
|
/**
|
||||||
* Plugin instance.
|
* Plugin instance.
|
||||||
*
|
*
|
||||||
* @var Plugin|null
|
* @var Plugin|null
|
||||||
*/
|
*/
|
||||||
private static ?Plugin $instance = null;
|
private static ?Plugin $instance = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Login form manager.
|
* Login form manager.
|
||||||
*
|
*
|
||||||
* @var Login_Form_Manager
|
* @var Login_Form_Manager
|
||||||
*/
|
*/
|
||||||
private Login_Form_Manager $login_manager;
|
private Login_Form_Manager $login_manager;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Profile settings manager.
|
* Profile settings manager.
|
||||||
*
|
*
|
||||||
* @var Profile_Settings
|
* @var Profile_Settings
|
||||||
*/
|
*/
|
||||||
private Profile_Settings $profile_settings;
|
private Profile_Settings $profile_settings;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recovery codes manager.
|
* Recovery codes manager.
|
||||||
*
|
*
|
||||||
* @var Recovery_Codes
|
* @var Recovery_Codes
|
||||||
*/
|
*/
|
||||||
private Recovery_Codes $recovery_codes;
|
private Recovery_Codes $recovery_codes;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Settings page handler.
|
* Settings page handler.
|
||||||
*
|
*
|
||||||
* @var Settings_Page
|
* @var Settings_Page
|
||||||
*/
|
*/
|
||||||
private Settings_Page $settings_page;
|
private Settings_Page $settings_page;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get singleton instance.
|
* Get singleton instance.
|
||||||
*
|
*
|
||||||
* @return Plugin
|
* @return Plugin
|
||||||
*/
|
*/
|
||||||
public static function get_instance(): Plugin {
|
public static function get_instance(): Plugin {
|
||||||
if ( null === self::$instance ) {
|
if ( null === self::$instance ) {
|
||||||
self::$instance = new self();
|
self::$instance = new self();
|
||||||
}
|
}
|
||||||
|
|
||||||
return self::$instance;
|
return self::$instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor.
|
* Constructor.
|
||||||
*/
|
*/
|
||||||
public function __construct() {
|
public function __construct() {
|
||||||
$this->login_manager = new Login_Form_Manager();
|
$this->login_manager = new Login_Form_Manager();
|
||||||
$this->profile_settings = new Profile_Settings();
|
$this->profile_settings = new Profile_Settings();
|
||||||
$this->recovery_codes = new Recovery_Codes();
|
$this->recovery_codes = new Recovery_Codes();
|
||||||
$this->settings_page = new Settings_Page();
|
$this->settings_page = new Settings_Page();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugin initialization.
|
* Plugin initialization.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function init(): void {
|
public function init(): void {
|
||||||
$this->maybe_load_textdomain();
|
$this->maybe_load_textdomain();
|
||||||
$this->login_manager->register_hooks();
|
$this->login_manager->register_hooks();
|
||||||
$this->profile_settings->register_hooks();
|
$this->profile_settings->register_hooks();
|
||||||
$this->recovery_codes->register_hooks();
|
$this->recovery_codes->register_hooks();
|
||||||
$this->settings_page->register_hooks();
|
$this->settings_page->register_hooks();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runs on activation.
|
* Runs on activation.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public static function activate(): void {
|
public static function activate(): void {
|
||||||
// Placeholder for activation tasks (option creation, migrations, etc.).
|
// Placeholder for activation tasks (option creation, migrations, etc.).
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runs on deactivation.
|
* Runs on deactivation.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public static function deactivate(): void {
|
public static function deactivate(): void {
|
||||||
// Placeholder for deactivation cleanup logic.
|
// Placeholder for deactivation cleanup logic.
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load text domain for translations.
|
* Load text domain for translations.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
private function maybe_load_textdomain(): void {
|
private function maybe_load_textdomain(): void {
|
||||||
load_plugin_textdomain( 'robotstxt-2fa', false, dirname( plugin_basename( ROBOTSTXT_2FA_FILE ) ) . '/languages/' );
|
load_plugin_textdomain( 'robotstxt-2fa', false, dirname( plugin_basename( ROBOTSTXT_2FA_FILE ) ) . '/languages/' );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,149 +1,151 @@
|
||||||
<?php
|
<?php
|
||||||
/**
|
/**
|
||||||
* Email verification code sender.
|
* Email verification code sender.
|
||||||
*
|
*
|
||||||
* @package Robotstxt_2FA
|
* @package Robotstxt_2FA
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace Robotstxt\TwoFA\Login;
|
namespace Robotstxt\TwoFA\Login;
|
||||||
|
|
||||||
use Robotstxt\TwoFA\User\User_Settings_Repository;
|
use Robotstxt\TwoFA\User\User_Settings_Repository;
|
||||||
|
|
||||||
if ( ! defined( 'ABSPATH' ) ) {
|
if ( ! defined( 'ABSPATH' ) ) {
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles generation and delivery of email-based verification codes.
|
* Handles generation and delivery of email-based verification codes.
|
||||||
*/
|
*/
|
||||||
class Email_Code_Sender {
|
class Email_Code_Sender {
|
||||||
/**
|
/**
|
||||||
* Length of the generated numeric code.
|
* Length of the generated numeric code.
|
||||||
*/
|
*/
|
||||||
private const CODE_LENGTH = 7;
|
private const CODE_LENGTH = 7;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Number of seconds the generated code remains valid.
|
* Number of seconds the generated code remains valid.
|
||||||
*/
|
*/
|
||||||
private const EXPIRATION_SECONDS = 600;
|
private const EXPIRATION_SECONDS = 600;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Minimum delay between email deliveries in seconds.
|
* Minimum delay between email deliveries in seconds.
|
||||||
*/
|
*/
|
||||||
private const RESEND_INTERVAL = 60;
|
private const RESEND_INTERVAL = 60;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* User settings repository.
|
* User settings repository.
|
||||||
*
|
*
|
||||||
* @var User_Settings_Repository
|
* @var User_Settings_Repository
|
||||||
*/
|
*/
|
||||||
private User_Settings_Repository $user_settings_repository;
|
private User_Settings_Repository $user_settings_repository;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor.
|
* Constructor.
|
||||||
*/
|
*/
|
||||||
public function __construct() {
|
public function __construct() {
|
||||||
$this->user_settings_repository = new User_Settings_Repository();
|
$this->user_settings_repository = new User_Settings_Repository();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the expected code length.
|
* Retrieve the expected code length.
|
||||||
*
|
*
|
||||||
* @return int
|
* @return int
|
||||||
*/
|
*/
|
||||||
public function get_code_length(): int {
|
public function get_code_length(): int {
|
||||||
return self::CODE_LENGTH;
|
return self::CODE_LENGTH;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send a verification code to the provided user.
|
* Send a verification code to the provided user.
|
||||||
*
|
*
|
||||||
* @param \WP_User $user User who is requesting authentication.
|
* @param \WP_User $user User who is requesting authentication.
|
||||||
*
|
*
|
||||||
* @return bool True when the email was sent or throttled successfully, false on failure.
|
* @return bool True when the email was sent or throttled successfully, false on failure.
|
||||||
*/
|
*/
|
||||||
public function send_code( \WP_User $user ): bool {
|
public function send_code( \WP_User $user ): bool {
|
||||||
if ( empty( $user->user_email ) || ! is_email( $user->user_email ) ) {
|
if ( empty( $user->user_email ) || ! is_email( $user->user_email ) ) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
|
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
|
||||||
$current_time = time();
|
$current_time = time();
|
||||||
|
|
||||||
if ( ! empty( $challenge['hash'] ) && $challenge['expires'] > $current_time && $challenge['sent_at'] >= ( $current_time - self::RESEND_INTERVAL ) ) {
|
if ( ! empty( $challenge['hash'] ) && $challenge['expires'] > $current_time && $challenge['sent_at'] >= ( $current_time - self::RESEND_INTERVAL ) ) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
$code = $this->generate_code();
|
$code = $this->generate_code();
|
||||||
$expires = $current_time + self::EXPIRATION_SECONDS;
|
$expires = $current_time + self::EXPIRATION_SECONDS;
|
||||||
|
|
||||||
$blog_name = wp_specialchars_decode( get_option( 'blogname', '' ), ENT_QUOTES );
|
$raw_blogname = get_option( 'blogname', '' );
|
||||||
$display_name = wp_strip_all_tags( $user->display_name ?: $user->user_login );
|
$blog_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES );
|
||||||
$email_subject = sprintf( __( '[%s] Your verification code', 'robotstxt-2fa' ), $blog_name ?: __( 'WordPress', 'robotstxt-2fa' ) );
|
$display_name = wp_strip_all_tags( ! empty( $user->display_name ) ? $user->display_name : $user->user_login );
|
||||||
|
/* translators: %s: site name. */
|
||||||
$message_lines = array(
|
$email_subject = sprintf( __( '[%s] Your verification code', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'WordPress', 'robotstxt-2fa' ) );
|
||||||
/* translators: %s: user display name. */
|
|
||||||
sprintf( __( 'Hi %s,', 'robotstxt-2fa' ), $display_name ),
|
$message_lines = array(
|
||||||
'',
|
/* translators: %s: user display name. */
|
||||||
/* translators: %s: site name. */
|
sprintf( __( 'Hi %s,', 'robotstxt-2fa' ), $display_name ),
|
||||||
sprintf( __( 'Use the following verification code to finish signing in to %s:', 'robotstxt-2fa' ), $blog_name ?: __( 'your site', 'robotstxt-2fa' ) ),
|
'',
|
||||||
'',
|
/* translators: %s: site name. */
|
||||||
$code,
|
sprintf( __( 'Use the following verification code to finish signing in to %s:', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'your site', 'robotstxt-2fa' ) ),
|
||||||
'',
|
'',
|
||||||
__( 'The code expires in 10 minutes.', 'robotstxt-2fa' ),
|
$code,
|
||||||
'',
|
'',
|
||||||
__( 'If you did not request this code you can ignore this email.', 'robotstxt-2fa' ),
|
__( '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' );
|
$message = implode( "\n", $message_lines );
|
||||||
|
|
||||||
if ( ! wp_mail( $user->user_email, $email_subject, $message, $headers ) ) {
|
$headers = array( 'Content-Type: text/plain; charset=UTF-8' );
|
||||||
return false;
|
|
||||||
}
|
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;
|
$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.
|
* Verify a submitted code against the stored challenge.
|
||||||
* @param string $code Submitted verification code.
|
*
|
||||||
*
|
* @param \WP_User $user User attempting to authenticate.
|
||||||
* @return bool
|
* @param string $code Submitted verification code.
|
||||||
*/
|
*
|
||||||
public function verify_code( \WP_User $user, string $code ): bool {
|
* @return bool
|
||||||
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
|
*/
|
||||||
$code = preg_replace( '/[^0-9]/', '', $code );
|
public function verify_code( \WP_User $user, string $code ): bool {
|
||||||
|
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
|
||||||
if ( empty( $challenge['hash'] ) ) {
|
$code = preg_replace( '/[^0-9]/', '', $code ) ?? '';
|
||||||
return false;
|
|
||||||
}
|
if ( '' === $challenge['hash'] ) {
|
||||||
|
return false;
|
||||||
if ( $challenge['expires'] <= time() ) {
|
}
|
||||||
return false;
|
|
||||||
}
|
if ( $challenge['expires'] <= time() ) {
|
||||||
|
return false;
|
||||||
if ( '' === $code ) {
|
}
|
||||||
return false;
|
|
||||||
}
|
if ( '' === $code ) {
|
||||||
|
return false;
|
||||||
return wp_check_password( $code, $challenge['hash'] );
|
}
|
||||||
}
|
|
||||||
|
return wp_check_password( $code, $challenge['hash'] );
|
||||||
/**
|
}
|
||||||
* Generate a random numeric verification code.
|
|
||||||
*
|
/**
|
||||||
* @return string
|
* Generate a random numeric verification code.
|
||||||
*/
|
*
|
||||||
private function generate_code(): string {
|
* @return string
|
||||||
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
*/
|
||||||
$code = (string) wp_rand( 0, (int) $max_value );
|
private function generate_code(): string {
|
||||||
|
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
||||||
return str_pad( $code, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
$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
|
<?php
|
||||||
/**
|
/**
|
||||||
* Manage authenticator app secrets and QR provisioning.
|
* Manage authenticator app secrets and QR provisioning.
|
||||||
*
|
*
|
||||||
* @package Robotstxt_2FA
|
* @package Robotstxt_2FA
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace Robotstxt\TwoFA\User;
|
namespace Robotstxt\TwoFA\User;
|
||||||
|
|
||||||
use WP_User;
|
use WP_User;
|
||||||
|
|
||||||
if ( ! defined( 'ABSPATH' ) ) {
|
if ( ! defined( 'ABSPATH' ) ) {
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles OTP secret storage, verification, and QR generation.
|
* Handles OTP secret storage, verification, and QR generation.
|
||||||
*/
|
*/
|
||||||
class OTP_Manager {
|
class OTP_Manager {
|
||||||
/**
|
/**
|
||||||
* User meta key that stores the OTP secret.
|
* User meta key that stores the OTP secret.
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
private const META_KEY = 'robotstxt_2fa_otp_secret';
|
private const META_KEY = 'robotstxt_2fa_otp_secret';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Number of digits generated per OTP code.
|
* Number of digits generated per OTP code.
|
||||||
*/
|
*/
|
||||||
private const CODE_DIGITS = 6;
|
private const CODE_DIGITS = 6;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the number of digits expected for OTP codes.
|
* Retrieve the number of digits expected for OTP codes.
|
||||||
*
|
*
|
||||||
* @return int
|
* @return int
|
||||||
*/
|
*/
|
||||||
public function get_code_length(): int {
|
public function get_code_length(): int {
|
||||||
return self::CODE_DIGITS;
|
return self::CODE_DIGITS;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Number of seconds between OTP code changes.
|
* Number of seconds between OTP code changes.
|
||||||
*/
|
*/
|
||||||
private const TIME_STEP = 30;
|
private const TIME_STEP = 30;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Default length (in bytes) of generated secrets.
|
* Default length (in bytes) of generated secrets.
|
||||||
*/
|
*/
|
||||||
private const SECRET_LENGTH = 20;
|
private const SECRET_LENGTH = 20;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the stored OTP secret for a user.
|
* Retrieve the stored OTP secret for a user.
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @param int $user_id User identifier.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function get_secret( int $user_id ): string {
|
public function get_secret( int $user_id ): string {
|
||||||
$secret = get_user_meta( $user_id, self::META_KEY, true );
|
$secret = get_user_meta( $user_id, self::META_KEY, true );
|
||||||
|
|
||||||
if ( ! is_string( $secret ) ) {
|
if ( ! is_string( $secret ) ) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
$secret = strtoupper( preg_replace( '/[^A-Z2-7]/', '', $secret ) ?? '' );
|
$secret = strtoupper( preg_replace( '/[^A-Z2-7]/', '', $secret ) ?? '' );
|
||||||
|
|
||||||
return $secret;
|
return $secret;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ensure the user has an OTP secret, generating one if necessary.
|
* Ensure the user has an OTP secret, generating one if necessary.
|
||||||
*
|
*
|
||||||
* @param WP_User $user User account that needs an OTP secret.
|
* @param WP_User $user User account that needs an OTP secret.
|
||||||
*
|
*
|
||||||
* @return string Generated or existing secret.
|
* @return string Generated or existing secret.
|
||||||
*/
|
*/
|
||||||
public function ensure_secret( WP_User $user ): string {
|
public function ensure_secret( WP_User $user ): string {
|
||||||
$secret = $this->get_secret( $user->ID );
|
$secret = $this->get_secret( $user->ID );
|
||||||
|
|
||||||
if ( '' !== $secret ) {
|
if ( '' !== $secret ) {
|
||||||
return $secret;
|
return $secret;
|
||||||
}
|
}
|
||||||
|
|
||||||
$secret = $this->generate_secret();
|
$secret = $this->generate_secret();
|
||||||
|
|
||||||
update_user_meta( $user->ID, self::META_KEY, $secret );
|
update_user_meta( $user->ID, self::META_KEY, $secret );
|
||||||
|
|
||||||
return $secret;
|
return $secret;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove the stored OTP secret for a user.
|
* Remove the stored OTP secret for a user.
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @param int $user_id User identifier.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function delete_secret( int $user_id ): void {
|
public function delete_secret( int $user_id ): void {
|
||||||
delete_user_meta( $user_id, self::META_KEY );
|
delete_user_meta( $user_id, self::META_KEY );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verify an OTP code against the stored secret.
|
* Verify an OTP code against the stored secret.
|
||||||
*
|
*
|
||||||
* @param WP_User $user User attempting to authenticate.
|
* @param WP_User $user User attempting to authenticate.
|
||||||
* @param string $code Submitted verification code.
|
* @param string $code Submitted verification code.
|
||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
public function verify_code( WP_User $user, string $code ): bool {
|
public function verify_code( WP_User $user, string $code ): bool {
|
||||||
$secret = $this->get_secret( $user->ID );
|
$secret = $this->get_secret( $user->ID );
|
||||||
|
|
||||||
if ( '' === $secret ) {
|
if ( '' === $secret ) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$code = preg_replace( '/[^0-9]/', '', $code );
|
$code = preg_replace( '/[^0-9]/', '', $code );
|
||||||
|
|
||||||
if ( null === $code || strlen( $code ) !== self::CODE_DIGITS ) {
|
if ( null === $code || strlen( $code ) !== self::CODE_DIGITS ) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$binary_secret = $this->base32_decode( $secret );
|
$binary_secret = $this->base32_decode( $secret );
|
||||||
|
|
||||||
if ( '' === $binary_secret ) {
|
if ( '' === $binary_secret ) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$current_step = (int) floor( time() / self::TIME_STEP );
|
$current_step = (int) floor( time() / self::TIME_STEP );
|
||||||
|
|
||||||
for ( $offset = -1; $offset <= 1; $offset++ ) {
|
for ( $offset = -1; $offset <= 1; $offset++ ) {
|
||||||
$otp = $this->generate_otp_for_counter( $binary_secret, $current_step + $offset );
|
$otp = $this->generate_otp_for_counter( $binary_secret, $current_step + $offset );
|
||||||
|
|
||||||
if ( hash_equals( $otp, $code ) ) {
|
if ( hash_equals( $otp, $code ) ) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the provisioning URI used by authenticator apps.
|
* Retrieve the provisioning URI used by authenticator apps.
|
||||||
*
|
*
|
||||||
* @param WP_User $user User who owns the OTP secret.
|
* @param WP_User $user User who owns the OTP secret.
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function get_provisioning_uri( WP_User $user ): string {
|
public function get_provisioning_uri( WP_User $user ): string {
|
||||||
$secret = $this->get_secret( $user->ID );
|
$secret = $this->get_secret( $user->ID );
|
||||||
|
|
||||||
if ( '' === $secret ) {
|
if ( '' === $secret ) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
$site_name = wp_specialchars_decode( get_option( 'blogname', '' ), ENT_QUOTES );
|
$raw_blogname = get_option( 'blogname', '' );
|
||||||
$site_name = '' !== $site_name ? $site_name : __( 'WordPress Site', 'robotstxt-2fa' );
|
$site_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES );
|
||||||
$label = '' !== $user->user_email ? $user->user_email : $user->user_login;
|
$site_name = '' !== $site_name ? $site_name : __( 'WordPress Site', 'robotstxt-2fa' );
|
||||||
|
$label = '' !== $user->user_email ? $user->user_email : $user->user_login;
|
||||||
$encoded_label = rawurlencode( sanitize_text_field( $label ) );
|
|
||||||
$encoded_site = rawurlencode( $site_name );
|
$encoded_label = rawurlencode( sanitize_text_field( $label ) );
|
||||||
$encoded_secret = rawurlencode( $secret );
|
$encoded_site = rawurlencode( $site_name );
|
||||||
$parameters = array(
|
$encoded_secret = rawurlencode( $secret );
|
||||||
'issuer' => $encoded_site,
|
$parameters = array(
|
||||||
'period' => (string) self::TIME_STEP,
|
'issuer' => $encoded_site,
|
||||||
);
|
'period' => (string) self::TIME_STEP,
|
||||||
|
);
|
||||||
$query = array();
|
|
||||||
|
$query = array();
|
||||||
foreach ( $parameters as $key => $value ) {
|
|
||||||
$query[] = rawurlencode( $key ) . '=' . $value;
|
foreach ( $parameters as $key => $value ) {
|
||||||
}
|
$query[] = rawurlencode( $key ) . '=' . $value;
|
||||||
|
}
|
||||||
return sprintf(
|
|
||||||
'otpauth://totp/%1$s:%2$s?secret=%3$s&%4$s',
|
return sprintf(
|
||||||
$encoded_site,
|
'otpauth://totp/%1$s:%2$s?secret=%3$s&%4$s',
|
||||||
$encoded_label,
|
$encoded_site,
|
||||||
$encoded_secret,
|
$encoded_label,
|
||||||
implode( '&', $query )
|
$encoded_secret,
|
||||||
);
|
implode( '&', $query )
|
||||||
}
|
);
|
||||||
|
}
|
||||||
/**
|
|
||||||
* Generate a QR code and return it as a data URI.
|
/**
|
||||||
*
|
* Generate a QR code and return it as a data URI.
|
||||||
* @param WP_User $user User who owns the OTP secret.
|
*
|
||||||
*
|
* @param WP_User $user User who owns the OTP secret.
|
||||||
* @return string Data URI containing an SVG image or an empty string when unavailable.
|
*
|
||||||
*/
|
* @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 );
|
public function get_qr_code_data_uri( WP_User $user ): string {
|
||||||
|
$uri = $this->get_provisioning_uri( $user );
|
||||||
if ( '' === $uri ) {
|
|
||||||
return '';
|
if ( '' === $uri ) {
|
||||||
}
|
return '';
|
||||||
|
}
|
||||||
$svg = $this->render_qr_svg( $uri );
|
|
||||||
|
$svg = $this->render_qr_svg( $uri );
|
||||||
if ( '' === $svg ) {
|
|
||||||
return '';
|
if ( '' === $svg ) {
|
||||||
}
|
return '';
|
||||||
|
}
|
||||||
/*
|
|
||||||
* Encode the SVG payload so it can be embedded safely as a data URI in the admin form.
|
/*
|
||||||
*/
|
* 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.
|
*/
|
||||||
}
|
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.
|
/**
|
||||||
*
|
* Generate a new secret encoded in Base32.
|
||||||
* @return string
|
*
|
||||||
*/
|
* @return string
|
||||||
private function generate_secret(): string {
|
*/
|
||||||
$bytes = random_bytes( self::SECRET_LENGTH );
|
private function generate_secret(): string {
|
||||||
|
$bytes = random_bytes( self::SECRET_LENGTH );
|
||||||
return $this->base32_encode( $bytes );
|
|
||||||
}
|
return $this->base32_encode( $bytes );
|
||||||
|
}
|
||||||
/**
|
|
||||||
* Render a QR code in SVG format using an available library.
|
/**
|
||||||
*
|
* Render a QR code in SVG format using an available library.
|
||||||
* @param string $data Data encoded inside the QR code.
|
*
|
||||||
*
|
* @param string $data Data encoded inside the QR code.
|
||||||
* @return string SVG markup or empty string on failure.
|
*
|
||||||
*/
|
* @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' ) ) {
|
private function render_qr_svg( string $data ): string {
|
||||||
return '';
|
if ( ! class_exists( '\BaconQrCode\Writer' ) || ! class_exists( '\BaconQrCode\Renderer\ImageRenderer' ) ) {
|
||||||
}
|
return '';
|
||||||
|
}
|
||||||
try {
|
|
||||||
$renderer = new \BaconQrCode\Renderer\ImageRenderer(
|
try {
|
||||||
new \BaconQrCode\Renderer\RendererStyle\RendererStyle( 256 ),
|
$renderer = new \BaconQrCode\Renderer\ImageRenderer(
|
||||||
new \BaconQrCode\Renderer\Image\SvgImageBackEnd()
|
new \BaconQrCode\Renderer\RendererStyle\RendererStyle( 256 ),
|
||||||
);
|
new \BaconQrCode\Renderer\Image\SvgImageBackEnd()
|
||||||
$writer = new \BaconQrCode\Writer( $renderer );
|
);
|
||||||
|
$writer = new \BaconQrCode\Writer( $renderer );
|
||||||
return $writer->writeString( $data );
|
|
||||||
} catch ( \Throwable $exception ) {
|
return $writer->writeString( $data );
|
||||||
do_action( 'robotstxt_2fa_qr_generation_failed', $exception, $data );
|
} catch ( \Throwable $exception ) {
|
||||||
}
|
/**
|
||||||
|
* Fires when QR code SVG generation fails.
|
||||||
return '';
|
*
|
||||||
}
|
* @since 0.2.0
|
||||||
|
*
|
||||||
/**
|
* @param \Throwable $exception The caught exception.
|
||||||
* Encode binary data using the Base32 alphabet.
|
* @param string $data The provisioning URI that failed to render.
|
||||||
*
|
*/
|
||||||
* @param string $data Binary string to encode.
|
do_action( 'robotstxt_2fa_qr_generation_failed', $exception, $data );
|
||||||
*
|
}
|
||||||
* @return string
|
|
||||||
*/
|
return '';
|
||||||
private function base32_encode( string $data ): string {
|
}
|
||||||
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
||||||
$bits = '';
|
/**
|
||||||
|
* Encode binary data using the Base32 alphabet.
|
||||||
for ( $i = 0, $length = strlen( $data ); $i < $length; $i++ ) {
|
*
|
||||||
$bits .= str_pad( decbin( ord( $data[ $i ] ) ), 8, '0', STR_PAD_LEFT );
|
* @param string $data Binary string to encode.
|
||||||
}
|
*
|
||||||
|
* @return string
|
||||||
$chunks = str_split( $bits, 5 );
|
*/
|
||||||
$encoded = '';
|
private function base32_encode( string $data ): string {
|
||||||
|
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||||
foreach ( $chunks as $chunk ) {
|
$bits = '';
|
||||||
if ( strlen( $chunk ) < 5 ) {
|
|
||||||
$chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT );
|
for ( $i = 0, $length = strlen( $data ); $i < $length; $i++ ) {
|
||||||
}
|
$bits .= str_pad( decbin( ord( $data[ $i ] ) ), 8, '0', STR_PAD_LEFT );
|
||||||
|
}
|
||||||
$encoded .= $alphabet[ bindec( $chunk ) ];
|
|
||||||
}
|
$chunks = str_split( $bits, 5 );
|
||||||
|
$encoded = '';
|
||||||
return $encoded;
|
|
||||||
}
|
foreach ( $chunks as $chunk ) {
|
||||||
|
if ( strlen( $chunk ) < 5 ) {
|
||||||
/**
|
$chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT );
|
||||||
* Decode a Base32-encoded string.
|
}
|
||||||
*
|
|
||||||
* @param string $encoded Encoded secret.
|
$encoded .= $alphabet[ (int) bindec( $chunk ) ];
|
||||||
*
|
}
|
||||||
* @return string
|
|
||||||
*/
|
return $encoded;
|
||||||
private function base32_decode( string $encoded ): string {
|
}
|
||||||
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
||||||
$encoded = strtoupper( $encoded );
|
/**
|
||||||
$encoded = preg_replace( '/[^A-Z2-7]/', '', $encoded );
|
* Decode a Base32-encoded string.
|
||||||
|
*
|
||||||
if ( null === $encoded || '' === $encoded ) {
|
* @param string $encoded Encoded secret.
|
||||||
return '';
|
*
|
||||||
}
|
* @return string
|
||||||
|
*/
|
||||||
$bits = '';
|
private function base32_decode( string $encoded ): string {
|
||||||
|
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||||
for ( $i = 0, $length = strlen( $encoded ); $i < $length; $i++ ) {
|
$encoded = strtoupper( $encoded );
|
||||||
$position = strpos( $alphabet, $encoded[ $i ] );
|
$encoded = preg_replace( '/[^A-Z2-7]/', '', $encoded );
|
||||||
|
|
||||||
if ( false === $position ) {
|
if ( null === $encoded || '' === $encoded ) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
$bits .= str_pad( decbin( $position ), 5, '0', STR_PAD_LEFT );
|
$bits = '';
|
||||||
}
|
|
||||||
|
for ( $i = 0, $length = strlen( $encoded ); $i < $length; $i++ ) {
|
||||||
$binary = '';
|
$position = strpos( $alphabet, $encoded[ $i ] );
|
||||||
$chunks = str_split( $bits, 8 );
|
|
||||||
|
if ( false === $position ) {
|
||||||
foreach ( $chunks as $chunk ) {
|
return '';
|
||||||
if ( strlen( $chunk ) < 8 ) {
|
}
|
||||||
continue;
|
|
||||||
}
|
$bits .= str_pad( decbin( $position ), 5, '0', STR_PAD_LEFT );
|
||||||
|
}
|
||||||
$binary .= chr( bindec( $chunk ) );
|
|
||||||
}
|
$binary = '';
|
||||||
|
$chunks = str_split( $bits, 8 );
|
||||||
return $binary;
|
|
||||||
}
|
foreach ( $chunks as $chunk ) {
|
||||||
|
if ( strlen( $chunk ) < 8 ) {
|
||||||
/**
|
continue;
|
||||||
* Generate an OTP value for a specific counter.
|
}
|
||||||
*
|
|
||||||
* @param string $secret Binary secret key.
|
$binary .= chr( (int) bindec( $chunk ) & 0xFF );
|
||||||
* @param int $counter Time-based counter value.
|
}
|
||||||
*
|
|
||||||
* @return string
|
return $binary;
|
||||||
*/
|
}
|
||||||
private function generate_otp_for_counter( string $secret, int $counter ): string {
|
|
||||||
$counter = max( 0, $counter );
|
/**
|
||||||
$binary_counter = pack( 'N*', 0 ) . pack( 'N*', $counter );
|
* Generate an OTP value for a specific counter.
|
||||||
$hash = hash_hmac( 'sha1', $binary_counter, $secret, true );
|
*
|
||||||
$offset = ord( substr( $hash, -1 ) ) & 0x0F;
|
* @param string $secret Binary secret key.
|
||||||
$segment = substr( $hash, $offset, 4 );
|
* @param int $counter Time-based counter value.
|
||||||
$value = unpack( 'N', $segment )[1] & 0x7FFFFFFF;
|
*
|
||||||
$code = $value % ( 10 ** self::CODE_DIGITS );
|
* @return string
|
||||||
|
*/
|
||||||
return str_pad( (string) $code, self::CODE_DIGITS, '0', STR_PAD_LEFT );
|
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
|
<?php
|
||||||
/**
|
/**
|
||||||
* Manage generation and validation of recovery codes.
|
* Manage generation and validation of recovery codes.
|
||||||
*
|
*
|
||||||
* @package Robotstxt_2FA
|
* @package Robotstxt_2FA
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace Robotstxt\TwoFA\User;
|
namespace Robotstxt\TwoFA\User;
|
||||||
|
|
||||||
use WP_User;
|
use WP_User;
|
||||||
|
|
||||||
if ( ! defined( 'ABSPATH' ) ) {
|
if ( ! defined( 'ABSPATH' ) ) {
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles creation, storage, and consumption of recovery codes.
|
* Handles creation, storage, and consumption of recovery codes.
|
||||||
*/
|
*/
|
||||||
class Recovery_Codes {
|
class Recovery_Codes {
|
||||||
/**
|
/**
|
||||||
* User meta key storing recovery code hashes.
|
* User meta key storing recovery code hashes.
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
private const META_KEY = 'robotstxt_2fa_recovery_codes';
|
private const META_KEY = 'robotstxt_2fa_recovery_codes';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Number of codes generated per batch.
|
* Number of codes generated per batch.
|
||||||
*/
|
*/
|
||||||
private const CODES_PER_BATCH = 10;
|
private const CODES_PER_BATCH = 10;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Number of digits per recovery code.
|
* Number of digits per recovery code.
|
||||||
*/
|
*/
|
||||||
private const CODE_LENGTH = 8;
|
private const CODE_LENGTH = 8;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Admin-post action slug used to request new recovery codes.
|
* Admin-post action slug used to request new recovery codes.
|
||||||
*/
|
*/
|
||||||
public const ACTION_GENERATE = 'robotstxt_2fa_generate_recovery_codes';
|
public const ACTION_GENERATE = 'robotstxt_2fa_generate_recovery_codes';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Nonce action securing recovery code generation.
|
* Nonce action securing recovery code generation.
|
||||||
*/
|
*/
|
||||||
public const NONCE_ACTION = 'robotstxt_2fa_generate_recovery_codes';
|
public const NONCE_ACTION = 'robotstxt_2fa_generate_recovery_codes';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Nonce field key embedded in recovery code forms.
|
* Nonce field key embedded in recovery code forms.
|
||||||
*/
|
*/
|
||||||
public const NONCE_FIELD = 'robotstxt_2fa_recovery_nonce';
|
public const NONCE_FIELD = 'robotstxt_2fa_recovery_nonce';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register hooks required by the recovery code workflow.
|
* Register hooks required by the recovery code workflow.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function register_hooks(): void {
|
public function register_hooks(): void {
|
||||||
add_action( 'wp_ajax_' . self::ACTION_GENERATE, array( $this, 'handle_ajax_generate_request' ) );
|
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' ) );
|
add_action( 'wp_ajax_nopriv_' . self::ACTION_GENERATE, array( $this, 'reject_unauthenticated_requests' ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Block unauthenticated requests attempting to generate recovery codes.
|
* Block unauthenticated requests attempting to generate recovery codes.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function reject_unauthenticated_requests(): void {
|
public function reject_unauthenticated_requests(): void {
|
||||||
$message = esc_html__( 'You must be logged in to manage recovery codes.', 'robotstxt-2fa' );
|
$message = esc_html__( 'You must be logged in to manage recovery codes.', 'robotstxt-2fa' );
|
||||||
|
|
||||||
if ( wp_doing_ajax() ) {
|
if ( wp_doing_ajax() ) {
|
||||||
wp_send_json_error(
|
wp_send_json_error(
|
||||||
array(
|
array(
|
||||||
'message' => $message,
|
'message' => $message,
|
||||||
),
|
),
|
||||||
403
|
403
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
wp_die( $message, '', array( 'response' => 403 ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $message is escaped via esc_html__().
|
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.
|
* Handle AJAX requests to generate recovery codes without reloading the page.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function handle_ajax_generate_request(): void {
|
public function handle_ajax_generate_request(): void {
|
||||||
check_ajax_referer( self::NONCE_ACTION, self::NONCE_FIELD );
|
check_ajax_referer( self::NONCE_ACTION, self::NONCE_FIELD );
|
||||||
|
|
||||||
$user_id = isset( $_POST['user_id'] ) ? absint( wp_unslash( $_POST['user_id'] ) ) : 0;
|
$raw_user_id = isset( $_POST['user_id'] ) && is_string( $_POST['user_id'] ) ? wp_unslash( $_POST['user_id'] ) : '';
|
||||||
|
$user_id = absint( $raw_user_id );
|
||||||
if ( $user_id <= 0 ) {
|
|
||||||
wp_send_json_error(
|
if ( $user_id <= 0 ) {
|
||||||
array(
|
wp_send_json_error(
|
||||||
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
|
array(
|
||||||
),
|
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
|
||||||
400
|
),
|
||||||
);
|
400
|
||||||
}
|
);
|
||||||
|
}
|
||||||
if ( ! current_user_can( 'edit_user', $user_id ) ) {
|
|
||||||
wp_send_json_error(
|
if ( ! current_user_can( 'edit_user', $user_id ) ) {
|
||||||
array(
|
wp_send_json_error(
|
||||||
'message' => esc_html__( 'You are not allowed to modify recovery codes for this account.', 'robotstxt-2fa' ),
|
array(
|
||||||
),
|
'message' => esc_html__( 'You are not allowed to modify recovery codes for this account.', 'robotstxt-2fa' ),
|
||||||
403
|
),
|
||||||
);
|
403
|
||||||
}
|
);
|
||||||
|
}
|
||||||
$user = get_user_by( 'ID', $user_id );
|
|
||||||
|
$user = get_user_by( 'ID', $user_id );
|
||||||
if ( ! $user instanceof WP_User ) {
|
|
||||||
wp_send_json_error(
|
if ( ! $user instanceof WP_User ) {
|
||||||
array(
|
wp_send_json_error(
|
||||||
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
|
array(
|
||||||
),
|
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
|
||||||
400
|
),
|
||||||
);
|
400
|
||||||
}
|
);
|
||||||
|
}
|
||||||
try {
|
|
||||||
$result = $this->regenerate_codes_for_user( $user );
|
try {
|
||||||
} catch ( \Throwable $exception ) {
|
$result = $this->regenerate_codes_for_user( $user );
|
||||||
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
|
} catch ( \Throwable $exception ) {
|
||||||
wp_send_json_error(
|
/**
|
||||||
array(
|
* Fires when recovery code generation fails.
|
||||||
'message' => esc_html__( 'We could not generate recovery codes. Please try again.', 'robotstxt-2fa' ),
|
*
|
||||||
),
|
* @since 0.2.0
|
||||||
500
|
*
|
||||||
);
|
* @param \Throwable $exception The caught exception.
|
||||||
}
|
*/
|
||||||
|
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
|
||||||
wp_send_json_success(
|
wp_send_json_error(
|
||||||
array(
|
array(
|
||||||
'codes' => $result['codes'],
|
'message' => esc_html__( 'We could not generate recovery codes. Please try again.', 'robotstxt-2fa' ),
|
||||||
'unused_count' => $result['unused_count'],
|
),
|
||||||
'last_generated' => $result['generated_at'],
|
500
|
||||||
'last_generated_formatted' => $this->format_generated_timestamp( $result['generated_at'] ),
|
);
|
||||||
)
|
}
|
||||||
);
|
|
||||||
}
|
wp_send_json_success(
|
||||||
|
array(
|
||||||
/**
|
'codes' => $result['codes'],
|
||||||
* Generate and persist a new batch of recovery codes for a user.
|
'unused_count' => $result['unused_count'],
|
||||||
*
|
'last_generated' => $result['generated_at'],
|
||||||
* @param WP_User $user User whose recovery codes are being regenerated.
|
'last_generated_formatted' => $this->format_generated_timestamp( $result['generated_at'] ),
|
||||||
*
|
)
|
||||||
* @throws \Exception If secure randomness cannot be generated.
|
);
|
||||||
*
|
}
|
||||||
* @return array<string, mixed>
|
|
||||||
*/
|
/**
|
||||||
public function regenerate_codes_for_user( WP_User $user ): array {
|
* Generate and persist a new batch of recovery codes for a user.
|
||||||
$codes = $this->generate_codes();
|
*
|
||||||
|
* @param WP_User $user User whose recovery codes are being regenerated.
|
||||||
$this->store_codes( $user->ID, $codes );
|
*
|
||||||
|
* @throws \Exception If secure randomness cannot be generated.
|
||||||
return array(
|
*
|
||||||
'codes' => $codes,
|
* @return array{codes: array<int, string>, generated_at: int, unused_count: int}
|
||||||
'generated_at' => $this->get_last_generated_timestamp( $user->ID ),
|
*/
|
||||||
'unused_count' => $this->count_unused_codes( $user->ID ),
|
public function regenerate_codes_for_user( WP_User $user ): array {
|
||||||
);
|
$codes = $this->generate_codes();
|
||||||
}
|
|
||||||
|
$this->store_codes( $user->ID, $codes );
|
||||||
/**
|
|
||||||
* Retrieve the number of digits expected for each recovery code.
|
return array(
|
||||||
*
|
'codes' => $codes,
|
||||||
* @return int
|
'generated_at' => $this->get_last_generated_timestamp( $user->ID ),
|
||||||
*/
|
'unused_count' => $this->count_unused_codes( $user->ID ),
|
||||||
public function get_code_length(): int {
|
);
|
||||||
return self::CODE_LENGTH;
|
}
|
||||||
}
|
|
||||||
|
/**
|
||||||
/**
|
* Retrieve the number of digits expected for each recovery code.
|
||||||
* Retrieve the number of recovery codes generated per batch.
|
*
|
||||||
*
|
* @return int
|
||||||
* @return int
|
*/
|
||||||
*/
|
public function get_code_length(): int {
|
||||||
public function get_codes_per_batch(): int {
|
return self::CODE_LENGTH;
|
||||||
return self::CODES_PER_BATCH;
|
}
|
||||||
}
|
|
||||||
|
/**
|
||||||
/**
|
* Retrieve the number of recovery codes generated per batch.
|
||||||
* Count the amount of unused recovery codes available for the user.
|
*
|
||||||
*
|
* @return int
|
||||||
* @param int $user_id User identifier.
|
*/
|
||||||
*
|
public function get_codes_per_batch(): int {
|
||||||
* @return int
|
return self::CODES_PER_BATCH;
|
||||||
*/
|
}
|
||||||
public function count_unused_codes( int $user_id ): int {
|
|
||||||
$record = $this->get_stored_codes( $user_id );
|
/**
|
||||||
|
* Count the amount of unused recovery codes available for the user.
|
||||||
if ( empty( $record['codes'] ) ) {
|
*
|
||||||
return 0;
|
* @param int $user_id User identifier.
|
||||||
}
|
*
|
||||||
|
* @return int
|
||||||
$unused = 0;
|
*/
|
||||||
|
public function count_unused_codes( int $user_id ): int {
|
||||||
foreach ( $record['codes'] as $entry ) {
|
$record = $this->get_stored_codes( $user_id );
|
||||||
if ( empty( $entry['used_at'] ) ) {
|
|
||||||
++$unused;
|
if ( empty( $record['codes'] ) ) {
|
||||||
}
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $unused;
|
$unused = 0;
|
||||||
}
|
|
||||||
|
foreach ( $record['codes'] as $entry ) {
|
||||||
/**
|
if ( empty( $entry['used_at'] ) ) {
|
||||||
* Determine whether the user currently has any unused recovery codes.
|
++$unused;
|
||||||
*
|
}
|
||||||
* @param int $user_id User identifier.
|
}
|
||||||
*
|
|
||||||
* @return bool
|
return $unused;
|
||||||
*/
|
}
|
||||||
public function has_active_codes( int $user_id ): bool {
|
|
||||||
return $this->count_unused_codes( $user_id ) > 0;
|
/**
|
||||||
}
|
* Determine whether the user currently has any unused recovery codes.
|
||||||
|
*
|
||||||
/**
|
* @param int $user_id User identifier.
|
||||||
* Consume a recovery code if it matches one of the stored hashes.
|
*
|
||||||
*
|
* @return bool
|
||||||
* @param WP_User $user User attempting to validate a recovery code.
|
*/
|
||||||
* @param string $code Submitted plain-text code.
|
public function has_active_codes( int $user_id ): bool {
|
||||||
*
|
return $this->count_unused_codes( $user_id ) > 0;
|
||||||
* @return bool
|
}
|
||||||
*/
|
|
||||||
public function consume_code( WP_User $user, string $code ): bool {
|
/**
|
||||||
$normalized_code = $this->normalize_code( $code );
|
* Consume a recovery code if it matches one of the stored hashes.
|
||||||
|
*
|
||||||
if ( '' === $normalized_code ) {
|
* @param WP_User $user User attempting to validate a recovery code.
|
||||||
return false;
|
* @param string $code Submitted plain-text code.
|
||||||
}
|
*
|
||||||
|
* @return bool
|
||||||
$record = $this->get_stored_codes( $user->ID );
|
*/
|
||||||
|
public function consume_code( WP_User $user, string $code ): bool {
|
||||||
if ( empty( $record['codes'] ) ) {
|
$normalized_code = $this->normalize_code( $code );
|
||||||
return false;
|
|
||||||
}
|
if ( '' === $normalized_code ) {
|
||||||
|
return false;
|
||||||
$updated = false;
|
}
|
||||||
|
|
||||||
foreach ( $record['codes'] as $index => $entry ) {
|
$record = $this->get_stored_codes( $user->ID );
|
||||||
if ( ! empty( $entry['used_at'] ) || empty( $entry['hash'] ) ) {
|
|
||||||
continue;
|
if ( empty( $record['codes'] ) ) {
|
||||||
}
|
return false;
|
||||||
|
}
|
||||||
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
|
|
||||||
$record['codes'][ $index ]['used_at'] = time();
|
$updated = false;
|
||||||
$updated = true;
|
|
||||||
break;
|
foreach ( $record['codes'] as $index => $entry ) {
|
||||||
}
|
if ( ! empty( $entry['used_at'] ) || empty( $entry['hash'] ) ) {
|
||||||
}
|
continue;
|
||||||
|
}
|
||||||
if ( $updated ) {
|
|
||||||
update_user_meta( $user->ID, self::META_KEY, $record );
|
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
|
||||||
|
$record['codes'][ $index ]['used_at'] = time();
|
||||||
return true;
|
$updated = true;
|
||||||
}
|
break;
|
||||||
|
}
|
||||||
return false;
|
}
|
||||||
}
|
|
||||||
|
if ( $updated ) {
|
||||||
/**
|
update_user_meta( $user->ID, self::META_KEY, $record );
|
||||||
* Fetch the timestamp of the last generation batch.
|
|
||||||
*
|
return true;
|
||||||
* @param int $user_id User identifier.
|
}
|
||||||
*
|
|
||||||
* @return int
|
return false;
|
||||||
*/
|
}
|
||||||
public function get_last_generated_timestamp( int $user_id ): int {
|
|
||||||
$record = $this->get_stored_codes( $user_id );
|
/**
|
||||||
|
* Fetch the timestamp of the last generation batch.
|
||||||
return (int) ( $record['generated_at'] ?? 0 );
|
*
|
||||||
}
|
* @param int $user_id User identifier.
|
||||||
|
*
|
||||||
/**
|
* @return int
|
||||||
* Format the provided timestamp using the site's date and time preferences.
|
*/
|
||||||
*
|
public function get_last_generated_timestamp( int $user_id ): int {
|
||||||
* @param int $timestamp Unix timestamp representing the generation time.
|
$record = $this->get_stored_codes( $user_id );
|
||||||
*
|
|
||||||
* @return string
|
return $record['generated_at'];
|
||||||
*/
|
}
|
||||||
private function format_generated_timestamp( int $timestamp ): string {
|
|
||||||
if ( $timestamp <= 0 ) {
|
/**
|
||||||
return '';
|
* Format the provided timestamp using the site's date and time preferences.
|
||||||
}
|
*
|
||||||
|
* @param int $timestamp Unix timestamp representing the generation time.
|
||||||
$date_format = get_option( 'date_format' );
|
*
|
||||||
$time_format = get_option( 'time_format' );
|
* @return string
|
||||||
|
*/
|
||||||
$format = trim( (string) $date_format . ' ' . (string) $time_format );
|
private function format_generated_timestamp( int $timestamp ): string {
|
||||||
|
if ( $timestamp <= 0 ) {
|
||||||
return '' !== $format ? wp_date( $format, $timestamp ) : wp_date( 'c', $timestamp );
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
$date_format = get_option( 'date_format' );
|
||||||
* Generate a batch of unique recovery codes.
|
$time_format = get_option( 'time_format' );
|
||||||
*
|
|
||||||
* @throws \Exception If randomness cannot be generated.
|
$format = trim( ( is_string( $date_format ) ? $date_format : '' ) . ' ' . ( is_string( $time_format ) ? $time_format : '' ) );
|
||||||
*
|
|
||||||
* @return array<int, string>
|
$formatted = wp_date( '' !== $format ? $format : 'c', $timestamp );
|
||||||
*/
|
return false !== $formatted ? $formatted : '';
|
||||||
private function generate_codes(): array {
|
}
|
||||||
$codes = array();
|
|
||||||
$attempts = 0;
|
/**
|
||||||
$target_count = self::CODES_PER_BATCH;
|
* Generate a batch of unique recovery codes.
|
||||||
$max_attempts = $target_count * 3;
|
*
|
||||||
$unique_count = 0;
|
* @throws \Exception If randomness cannot be generated.
|
||||||
|
*
|
||||||
while ( $unique_count < $target_count && $attempts < $max_attempts ) {
|
* @return array<int, string>
|
||||||
++$attempts;
|
*/
|
||||||
|
private function generate_codes(): array {
|
||||||
$code = $this->generate_single_code();
|
$codes = array();
|
||||||
|
$attempts = 0;
|
||||||
if ( in_array( $code, $codes, true ) ) {
|
$target_count = self::CODES_PER_BATCH;
|
||||||
continue;
|
$max_attempts = $target_count * 3;
|
||||||
}
|
$unique_count = 0;
|
||||||
|
|
||||||
$codes[] = $code;
|
while ( $unique_count < $target_count && $attempts < $max_attempts ) {
|
||||||
++$unique_count;
|
++$attempts;
|
||||||
}
|
|
||||||
|
$code = $this->generate_single_code();
|
||||||
return $codes;
|
|
||||||
}
|
if ( in_array( $code, $codes, true ) ) {
|
||||||
|
continue;
|
||||||
/**
|
}
|
||||||
* Create a single recovery code.
|
|
||||||
*
|
$codes[] = $code;
|
||||||
* @throws \Exception If secure randomness cannot be generated.
|
++$unique_count;
|
||||||
*
|
}
|
||||||
* @return string
|
|
||||||
*/
|
return $codes;
|
||||||
private function generate_single_code(): string {
|
}
|
||||||
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
|
||||||
$number = random_int( 0, $max_value );
|
/**
|
||||||
|
* Create a single recovery code.
|
||||||
return str_pad( (string) $number, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
*
|
||||||
}
|
* @throws \Exception If secure randomness cannot be generated.
|
||||||
|
*
|
||||||
/**
|
* @return string
|
||||||
* Normalize user-submitted recovery codes.
|
*/
|
||||||
*
|
private function generate_single_code(): string {
|
||||||
* @param string $code Submitted code.
|
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
|
||||||
*
|
$number = random_int( 0, $max_value );
|
||||||
* @return string
|
|
||||||
*/
|
return str_pad( (string) $number, self::CODE_LENGTH, '0', STR_PAD_LEFT );
|
||||||
private function normalize_code( string $code ): string {
|
}
|
||||||
$code = preg_replace( '/[^0-9]/', '', $code );
|
|
||||||
|
/**
|
||||||
if ( null === $code ) {
|
* Normalize user-submitted recovery codes.
|
||||||
return '';
|
*
|
||||||
}
|
* @param string $code Submitted code.
|
||||||
|
*
|
||||||
$code = substr( $code, 0, self::CODE_LENGTH );
|
* @return string
|
||||||
|
*/
|
||||||
if ( strlen( $code ) !== self::CODE_LENGTH ) {
|
private function normalize_code( string $code ): string {
|
||||||
return '';
|
$code = preg_replace( '/[^0-9]/', '', $code );
|
||||||
}
|
|
||||||
|
if ( null === $code ) {
|
||||||
return $code;
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
$code = substr( $code, 0, self::CODE_LENGTH );
|
||||||
* Store recovery codes and metadata for a user.
|
|
||||||
*
|
if ( strlen( $code ) !== self::CODE_LENGTH ) {
|
||||||
* @param int $user_id User identifier.
|
return '';
|
||||||
* @param array<int, string> $codes Plain-text recovery codes.
|
}
|
||||||
*
|
|
||||||
* @return void
|
return $code;
|
||||||
*/
|
}
|
||||||
private function store_codes( int $user_id, array $codes ): void {
|
|
||||||
$stored_codes = array();
|
/**
|
||||||
|
* Store recovery codes and metadata for a user.
|
||||||
foreach ( $codes as $code ) {
|
*
|
||||||
$stored_codes[] = array(
|
* @param int $user_id User identifier.
|
||||||
'hash' => wp_hash_password( $this->normalize_code( $code ) ),
|
* @param array<int, string> $codes Plain-text recovery codes.
|
||||||
'used_at' => 0,
|
*
|
||||||
);
|
* @return void
|
||||||
}
|
*/
|
||||||
|
private function store_codes( int $user_id, array $codes ): void {
|
||||||
$record = array(
|
$stored_codes = array();
|
||||||
'generated_at' => time(),
|
|
||||||
'codes' => $stored_codes,
|
foreach ( $codes as $code ) {
|
||||||
);
|
$stored_codes[] = array(
|
||||||
|
'hash' => wp_hash_password( $this->normalize_code( $code ) ),
|
||||||
update_user_meta( $user_id, self::META_KEY, $record );
|
'used_at' => 0,
|
||||||
}
|
);
|
||||||
|
}
|
||||||
/**
|
|
||||||
* Retrieve and sanitize stored recovery code metadata.
|
$record = array(
|
||||||
*
|
'generated_at' => time(),
|
||||||
* @param int $user_id User identifier.
|
'codes' => $stored_codes,
|
||||||
*
|
);
|
||||||
* @return array<string, mixed>
|
|
||||||
*/
|
update_user_meta( $user_id, self::META_KEY, $record );
|
||||||
private function get_stored_codes( int $user_id ): array {
|
}
|
||||||
$record = get_user_meta( $user_id, self::META_KEY, true );
|
|
||||||
|
/**
|
||||||
if ( ! is_array( $record ) ) {
|
* Retrieve and sanitize stored recovery code metadata.
|
||||||
$record = array();
|
*
|
||||||
}
|
* @param int $user_id User identifier.
|
||||||
|
*
|
||||||
$record['generated_at'] = isset( $record['generated_at'] ) ? (int) $record['generated_at'] : 0;
|
* @return array{generated_at: int, codes: array<int, array{hash: string, used_at: int}>}
|
||||||
$record['codes'] = isset( $record['codes'] ) && is_array( $record['codes'] ) ? $record['codes'] : array();
|
*/
|
||||||
|
private function get_stored_codes( int $user_id ): array {
|
||||||
foreach ( $record['codes'] as $index => $entry ) {
|
$record = get_user_meta( $user_id, self::META_KEY, true );
|
||||||
if ( ! is_array( $entry ) ) {
|
|
||||||
$record['codes'][ $index ] = array(
|
if ( ! is_array( $record ) ) {
|
||||||
'hash' => '',
|
$record = array();
|
||||||
'used_at' => 0,
|
}
|
||||||
);
|
|
||||||
continue;
|
$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();
|
||||||
|
|
||||||
$record['codes'][ $index ]['hash'] = isset( $entry['hash'] ) && is_string( $entry['hash'] ) ? $entry['hash'] : '';
|
$codes = array();
|
||||||
$record['codes'][ $index ]['used_at'] = isset( $entry['used_at'] ) ? (int) $entry['used_at'] : 0;
|
|
||||||
}
|
foreach ( $raw_codes as $entry ) {
|
||||||
|
$codes[] = array(
|
||||||
return $record;
|
'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,
|
||||||
|
);
|
||||||
/**
|
}
|
||||||
* Verify whether the provided recovery code matches a stored hash without consuming it.
|
|
||||||
*
|
return array(
|
||||||
* @param WP_User $user User attempting to validate a recovery code.
|
'generated_at' => $generated_at,
|
||||||
* @param string $code Submitted plain-text code.
|
'codes' => $codes,
|
||||||
*
|
);
|
||||||
* @return bool
|
}
|
||||||
*/
|
|
||||||
public function verify_code_without_consuming( WP_User $user, string $code ): bool {
|
/**
|
||||||
$normalized_code = $this->normalize_code( $code );
|
* Verify whether the provided recovery code matches a stored hash without consuming it.
|
||||||
|
*
|
||||||
if ( '' === $normalized_code ) {
|
* @param WP_User $user User attempting to validate a recovery code.
|
||||||
return false;
|
* @param string $code Submitted plain-text code.
|
||||||
}
|
*
|
||||||
|
* @return bool
|
||||||
$record = $this->get_stored_codes( $user->ID );
|
*/
|
||||||
|
public function verify_code_without_consuming( WP_User $user, string $code ): bool {
|
||||||
if ( empty( $record['codes'] ) ) {
|
$normalized_code = $this->normalize_code( $code );
|
||||||
return false;
|
|
||||||
}
|
if ( '' === $normalized_code ) {
|
||||||
|
return false;
|
||||||
foreach ( $record['codes'] as $entry ) {
|
}
|
||||||
if ( empty( $entry['hash'] ) ) {
|
|
||||||
continue;
|
$record = $this->get_stored_codes( $user->ID );
|
||||||
}
|
|
||||||
|
if ( empty( $record['codes'] ) ) {
|
||||||
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
|
return false;
|
||||||
return true;
|
}
|
||||||
}
|
|
||||||
}
|
foreach ( $record['codes'] as $entry ) {
|
||||||
|
if ( empty( $entry['hash'] ) ) {
|
||||||
return false;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,130 +1,113 @@
|
||||||
<?php
|
<?php
|
||||||
/**
|
/**
|
||||||
* Resolve two-factor configuration from global settings.
|
* Resolve two-factor configuration from global settings.
|
||||||
*
|
*
|
||||||
* @package Robotstxt_2FA
|
* @package Robotstxt_2FA
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace Robotstxt\TwoFA\User;
|
namespace Robotstxt\TwoFA\User;
|
||||||
|
|
||||||
use Robotstxt\TwoFA\Admin\Settings_Page;
|
use Robotstxt\TwoFA\Admin\Settings_Page;
|
||||||
use Robotstxt\TwoFA\Frequency_Options;
|
use Robotstxt\TwoFA\Frequency_Options;
|
||||||
|
|
||||||
if ( ! defined( 'ABSPATH' ) ) {
|
if ( ! defined( 'ABSPATH' ) ) {
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exposes helpers to read plugin-level two-factor configuration.
|
* Exposes helpers to read plugin-level two-factor configuration.
|
||||||
*/
|
*/
|
||||||
class Two_Factor_Config {
|
class Two_Factor_Config {
|
||||||
/**
|
/**
|
||||||
* Retrieve global two-factor settings with multisite support.
|
* Retrieve global two-factor settings with multisite support.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool}
|
||||||
*/
|
*/
|
||||||
public function get_settings(): array {
|
public function get_settings(): array {
|
||||||
$settings = array();
|
$settings_page = new Settings_Page();
|
||||||
|
return $settings_page->get_settings();
|
||||||
if ( is_multisite() ) {
|
}
|
||||||
$network_settings = get_site_option( Settings_Page::OPTION_NAME, array() );
|
|
||||||
|
/**
|
||||||
if ( is_array( $network_settings ) && ! empty( $network_settings ) ) {
|
* Retrieve the per-role method map.
|
||||||
$settings = $network_settings;
|
*
|
||||||
}
|
* @return array<string, array<int, string>>
|
||||||
}
|
*/
|
||||||
|
public function get_role_methods(): array {
|
||||||
if ( empty( $settings ) ) {
|
return $this->get_settings()['role_methods'];
|
||||||
$site_settings = get_option( Settings_Page::OPTION_NAME, array() );
|
}
|
||||||
|
|
||||||
if ( is_array( $site_settings ) ) {
|
/**
|
||||||
$settings = $site_settings;
|
* Retrieve the list of roles that have at least one required method configured.
|
||||||
}
|
*
|
||||||
}
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
return wp_parse_args(
|
public function get_forced_roles(): array {
|
||||||
$settings,
|
return array_keys( $this->get_role_methods() );
|
||||||
array(
|
}
|
||||||
'force_roles' => array(),
|
|
||||||
'default_method' => 'email',
|
/**
|
||||||
'frequency' => Frequency_Options::FREQUENCY_SESSION,
|
* Retrieve the required verification methods for a specific role.
|
||||||
'force_frequency' => false,
|
*
|
||||||
)
|
* @param string $role Role slug.
|
||||||
);
|
*
|
||||||
}
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
/**
|
public function get_methods_for_role( string $role ): array {
|
||||||
* Retrieve the list of roles that must enable two-factor authentication.
|
$role_methods = $this->get_role_methods();
|
||||||
*
|
return $role_methods[ $role ] ?? array();
|
||||||
* @return array<int, string>
|
}
|
||||||
*/
|
|
||||||
public function get_forced_roles(): array {
|
/**
|
||||||
$settings = $this->get_settings();
|
* Retrieve the union of required methods across all of a user's roles.
|
||||||
|
*
|
||||||
if ( empty( $settings['force_roles'] ) || ! is_array( $settings['force_roles'] ) ) {
|
* Returns an empty array when none of the user's roles have required methods.
|
||||||
return array();
|
*
|
||||||
}
|
* @param \WP_User $user User object currently being authenticated.
|
||||||
|
*
|
||||||
return array_values(
|
* @return array<int, string>
|
||||||
array_filter(
|
*/
|
||||||
array_map( 'sanitize_key', $settings['force_roles'] )
|
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 ] ) ) {
|
||||||
* Determine if two-factor authentication is enforced for the provided user.
|
foreach ( $role_methods[ $role ] as $method ) {
|
||||||
*
|
$required[] = $method;
|
||||||
* @param \WP_User $user User object currently being authenticated.
|
}
|
||||||
*
|
}
|
||||||
* @return bool
|
}
|
||||||
*/
|
|
||||||
public function is_two_factor_forced_for_user( \WP_User $user ): bool {
|
return array_values( array_unique( $required ) );
|
||||||
$forced_roles = $this->get_forced_roles();
|
}
|
||||||
|
|
||||||
if ( empty( $forced_roles ) ) {
|
/**
|
||||||
return false;
|
* Determine if two-factor authentication is enforced for the provided user.
|
||||||
}
|
*
|
||||||
|
* @param \WP_User $user User object currently being authenticated.
|
||||||
foreach ( $user->roles as $role ) {
|
*
|
||||||
if ( in_array( $role, $forced_roles, true ) ) {
|
* @return bool
|
||||||
return true;
|
*/
|
||||||
}
|
public function is_two_factor_forced_for_user( \WP_User $user ): bool {
|
||||||
}
|
return ! empty( $this->get_required_methods_for_user( $user ) );
|
||||||
|
}
|
||||||
return false;
|
|
||||||
}
|
/**
|
||||||
|
* Retrieve the globally configured verification frequency.
|
||||||
/**
|
*
|
||||||
* Retrieve the default two-factor authentication method.
|
* @return string
|
||||||
*
|
*/
|
||||||
* @return string
|
public function get_frequency(): string {
|
||||||
*/
|
return $this->get_settings()['frequency'];
|
||||||
public function get_default_method(): string {
|
}
|
||||||
$settings = $this->get_settings();
|
|
||||||
|
/**
|
||||||
return sanitize_key( $settings['default_method'] ?? 'email' );
|
* Determine whether the global frequency must be enforced for all users.
|
||||||
}
|
*
|
||||||
|
* @return bool
|
||||||
/**
|
*/
|
||||||
* Retrieve the globally configured verification frequency.
|
public function is_frequency_forced(): bool {
|
||||||
*
|
return $this->get_settings()['force_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'] );
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,259 +1,257 @@
|
||||||
<?php
|
<?php
|
||||||
/**
|
/**
|
||||||
* Manage persistence of user two-factor settings.
|
* Manage persistence of user two-factor settings.
|
||||||
*
|
*
|
||||||
* @package Robotstxt_2FA
|
* @package Robotstxt_2FA
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace Robotstxt\TwoFA\User;
|
namespace Robotstxt\TwoFA\User;
|
||||||
|
|
||||||
use Robotstxt\TwoFA\Frequency_Options;
|
use Robotstxt\TwoFA\Frequency_Options;
|
||||||
|
|
||||||
if ( ! defined( 'ABSPATH' ) ) {
|
if ( ! defined( 'ABSPATH' ) ) {
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Provides CRUD helpers for user 2FA preferences and challenges.
|
* Provides CRUD helpers for user 2FA preferences and challenges.
|
||||||
*/
|
*/
|
||||||
class User_Settings_Repository {
|
class User_Settings_Repository {
|
||||||
/**
|
/**
|
||||||
* User meta key storing 2FA settings.
|
* User meta key storing 2FA settings.
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
private const USER_SETTINGS_META = 'robotstxt_2fa_user_settings';
|
private const USER_SETTINGS_META = 'robotstxt_2fa_user_settings';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* User meta key storing email challenges.
|
* User meta key storing email challenges.
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
private const EMAIL_CHALLENGE_META = 'robotstxt_2fa_email_challenge';
|
private const EMAIL_CHALLENGE_META = 'robotstxt_2fa_email_challenge';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* User meta key storing last successful verifications per context.
|
* User meta key storing last successful verifications per context.
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
private const LAST_VERIFICATIONS_META = 'robotstxt_2fa_last_verifications';
|
private const LAST_VERIFICATIONS_META = 'robotstxt_2fa_last_verifications';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Maximum number of device contexts stored per verification method.
|
* Maximum number of device contexts stored per verification method.
|
||||||
*/
|
*/
|
||||||
private const CONTEXT_LIMIT = 20;
|
private const CONTEXT_LIMIT = 20;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve stored 2FA settings for a user.
|
* Retrieve stored 2FA settings for a user.
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @param int $user_id User identifier.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>
|
* @return array{enabled: bool, methods: array<int, string>, frequency: string}
|
||||||
*/
|
*/
|
||||||
public function get_user_settings( int $user_id ): array {
|
public function get_user_settings( int $user_id ): array {
|
||||||
$raw_settings = get_user_meta( $user_id, self::USER_SETTINGS_META, true );
|
$raw_settings = get_user_meta( $user_id, self::USER_SETTINGS_META, true );
|
||||||
|
|
||||||
if ( ! is_array( $raw_settings ) ) {
|
if ( ! is_array( $raw_settings ) ) {
|
||||||
$raw_settings = array();
|
$raw_settings = array();
|
||||||
}
|
}
|
||||||
|
|
||||||
$defaults = array(
|
$raw_methods = isset( $raw_settings['methods'] ) && is_array( $raw_settings['methods'] ) ? $raw_settings['methods'] : array();
|
||||||
'enabled' => false,
|
|
||||||
'methods' => array(),
|
return array(
|
||||||
'frequency' => Frequency_Options::FREQUENCY_SESSION,
|
'enabled' => ! empty( $raw_settings['enabled'] ),
|
||||||
);
|
'methods' => array_values(
|
||||||
|
array_unique(
|
||||||
$settings = wp_parse_args( $raw_settings, $defaults );
|
array_filter(
|
||||||
|
array_map(
|
||||||
$settings['enabled'] = (bool) $settings['enabled'];
|
static function ( mixed $v ): string {
|
||||||
|
return sanitize_key( is_string( $v ) ? $v : '' );
|
||||||
$settings['methods'] = array_values(
|
},
|
||||||
array_unique(
|
$raw_methods
|
||||||
array_filter(
|
)
|
||||||
array_map( 'sanitize_key', (array) $settings['methods'] )
|
)
|
||||||
)
|
)
|
||||||
)
|
),
|
||||||
);
|
'frequency' => Frequency_Options::sanitize( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ? $raw_settings['frequency'] : '' ),
|
||||||
|
);
|
||||||
$settings['frequency'] = Frequency_Options::sanitize( (string) $settings['frequency'] );
|
}
|
||||||
|
|
||||||
return $settings;
|
/**
|
||||||
}
|
* Persist 2FA settings for a user.
|
||||||
|
*
|
||||||
/**
|
* @param int $user_id User identifier.
|
||||||
* Persist 2FA settings for a user.
|
* @param array<string, mixed> $settings Settings to store.
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @return void
|
||||||
* @param array $settings Settings to store.
|
*/
|
||||||
*
|
public function save_user_settings( int $user_id, array $settings ): void {
|
||||||
* @return void
|
$raw_methods = isset( $settings['methods'] ) && is_array( $settings['methods'] ) ? $settings['methods'] : array();
|
||||||
*/
|
$prepared = array(
|
||||||
public function save_user_settings( int $user_id, array $settings ): void {
|
'enabled' => ! empty( $settings['enabled'] ),
|
||||||
$prepared = array(
|
'methods' => array_values(
|
||||||
'enabled' => ! empty( $settings['enabled'] ),
|
array_unique(
|
||||||
'methods' => array_values(
|
array_filter(
|
||||||
array_unique(
|
array_map(
|
||||||
array_filter(
|
static function ( mixed $v ): string {
|
||||||
array_map( 'sanitize_key', $settings['methods'] ?? array() )
|
return sanitize_key( is_string( $v ) ? $v : '' );
|
||||||
)
|
},
|
||||||
)
|
$raw_methods
|
||||||
),
|
)
|
||||||
'frequency' => Frequency_Options::sanitize( (string) ( $settings['frequency'] ?? Frequency_Options::FREQUENCY_SESSION ) ),
|
)
|
||||||
);
|
)
|
||||||
|
),
|
||||||
update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared );
|
'frequency' => Frequency_Options::sanitize( isset( $settings['frequency'] ) && is_string( $settings['frequency'] ) ? $settings['frequency'] : Frequency_Options::FREQUENCY_SESSION ),
|
||||||
|
);
|
||||||
if ( empty( $prepared['enabled'] ) ) {
|
|
||||||
$this->delete_email_challenge( $user_id );
|
update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared );
|
||||||
$this->delete_last_verifications( $user_id );
|
|
||||||
}
|
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.
|
* Store email challenge details for a user.
|
||||||
* @param int $expires Expiration timestamp.
|
*
|
||||||
*
|
* @param int $user_id User identifier.
|
||||||
* @return void
|
* @param string $code Plain-text verification code.
|
||||||
*/
|
* @param int $expires Expiration timestamp.
|
||||||
public function store_email_challenge( int $user_id, string $code, int $expires ): void {
|
*
|
||||||
$record = array(
|
* @return void
|
||||||
'hash' => wp_hash_password( $code ),
|
*/
|
||||||
'expires' => $expires,
|
public function store_email_challenge( int $user_id, string $code, int $expires ): void {
|
||||||
'sent_at' => time(),
|
$record = array(
|
||||||
);
|
'hash' => wp_hash_password( $code ),
|
||||||
|
'expires' => $expires,
|
||||||
update_user_meta( $user_id, self::EMAIL_CHALLENGE_META, $record );
|
'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.
|
/**
|
||||||
*
|
* Retrieve email challenge details for a user.
|
||||||
* @return array<string, int|string>
|
*
|
||||||
*/
|
* @param int $user_id User identifier.
|
||||||
public function get_email_challenge( int $user_id ): array {
|
*
|
||||||
$record = get_user_meta( $user_id, self::EMAIL_CHALLENGE_META, true );
|
* @return array{hash: string, expires: int, sent_at: int}
|
||||||
|
*/
|
||||||
if ( ! is_array( $record ) ) {
|
public function get_email_challenge( int $user_id ): array {
|
||||||
$record = array();
|
$record = get_user_meta( $user_id, self::EMAIL_CHALLENGE_META, true );
|
||||||
}
|
|
||||||
|
if ( ! is_array( $record ) ) {
|
||||||
$record = wp_parse_args(
|
$record = array();
|
||||||
$record,
|
}
|
||||||
array(
|
|
||||||
'hash' => '',
|
return array(
|
||||||
'expires' => 0,
|
'hash' => isset( $record['hash'] ) && is_string( $record['hash'] ) ? $record['hash'] : '',
|
||||||
'sent_at' => 0,
|
'expires' => isset( $record['expires'] ) && is_numeric( $record['expires'] ) ? (int) $record['expires'] : 0,
|
||||||
)
|
'sent_at' => isset( $record['sent_at'] ) && is_numeric( $record['sent_at'] ) ? (int) $record['sent_at'] : 0,
|
||||||
);
|
);
|
||||||
|
}
|
||||||
$record['hash'] = is_string( $record['hash'] ) ? $record['hash'] : '';
|
|
||||||
$record['expires'] = (int) $record['expires'];
|
/**
|
||||||
$record['sent_at'] = (int) $record['sent_at'];
|
* Remove stored email challenge details.
|
||||||
|
*
|
||||||
return $record;
|
* @param int $user_id User identifier.
|
||||||
}
|
*
|
||||||
|
* @return void
|
||||||
/**
|
*/
|
||||||
* Remove stored email challenge details.
|
public function delete_email_challenge( int $user_id ): void {
|
||||||
*
|
delete_user_meta( $user_id, self::EMAIL_CHALLENGE_META );
|
||||||
* @param int $user_id User identifier.
|
}
|
||||||
*
|
|
||||||
* @return void
|
/**
|
||||||
*/
|
* Record a successful verification timestamp for a method and device context.
|
||||||
public function delete_email_challenge( int $user_id ): void {
|
*
|
||||||
delete_user_meta( $user_id, self::EMAIL_CHALLENGE_META );
|
* @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.
|
||||||
* Record a successful verification timestamp for a method and device context.
|
*
|
||||||
*
|
* @return void
|
||||||
* @param int $user_id User identifier.
|
*/
|
||||||
* @param string $method Verification method identifier.
|
public function record_last_verification( int $user_id, string $method, string $context_key, int $timestamp ): void {
|
||||||
* @param string $context_key Normalized device context key.
|
$method = sanitize_key( $method );
|
||||||
* @param int $timestamp Verification timestamp.
|
$context_key = sanitize_text_field( $context_key );
|
||||||
*
|
$timestamp = max( 0, $timestamp );
|
||||||
* @return void
|
|
||||||
*/
|
if ( '' === $method || '' === $context_key || 0 === $timestamp ) {
|
||||||
public function record_last_verification( int $user_id, string $method, string $context_key, int $timestamp ): void {
|
return;
|
||||||
$method = sanitize_key( $method );
|
}
|
||||||
$context_key = sanitize_text_field( $context_key );
|
|
||||||
$timestamp = max( 0, $timestamp );
|
$record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true );
|
||||||
|
|
||||||
if ( '' === $method || '' === $context_key || 0 === $timestamp ) {
|
if ( ! is_array( $record ) ) {
|
||||||
return;
|
$record = array();
|
||||||
}
|
}
|
||||||
|
|
||||||
$record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true );
|
if ( ! isset( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) {
|
||||||
|
$record[ $method ] = array();
|
||||||
if ( ! is_array( $record ) ) {
|
}
|
||||||
$record = array();
|
|
||||||
}
|
$record[ $method ][ $context_key ] = array(
|
||||||
|
'verified_at' => $timestamp,
|
||||||
if ( ! isset( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) {
|
);
|
||||||
$record[ $method ] = array();
|
|
||||||
}
|
if ( count( $record[ $method ] ) > self::CONTEXT_LIMIT ) {
|
||||||
|
uasort(
|
||||||
$record[ $method ][ $context_key ] = array(
|
$record[ $method ],
|
||||||
'verified_at' => $timestamp,
|
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;
|
||||||
if ( count( $record[ $method ] ) > self::CONTEXT_LIMIT ) {
|
return $a_ts <=> $b_ts;
|
||||||
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 );
|
||||||
$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.
|
||||||
* Retrieve the last verification timestamp for a method and context.
|
* @param string $context_key Normalized device context key.
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @return int
|
||||||
* @param string $method Verification method identifier.
|
*/
|
||||||
* @param string $context_key Normalized device context key.
|
public function get_last_verification_timestamp( int $user_id, string $method, string $context_key ): int {
|
||||||
*
|
$method = sanitize_key( $method );
|
||||||
* @return int
|
$context_key = sanitize_text_field( $context_key );
|
||||||
*/
|
|
||||||
public function get_last_verification_timestamp( int $user_id, string $method, string $context_key ): int {
|
if ( '' === $method || '' === $context_key ) {
|
||||||
$method = sanitize_key( $method );
|
return 0;
|
||||||
$context_key = sanitize_text_field( $context_key );
|
}
|
||||||
|
|
||||||
if ( '' === $method || '' === $context_key ) {
|
$record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true );
|
||||||
return 0;
|
|
||||||
}
|
if ( ! is_array( $record ) || empty( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) {
|
||||||
|
return 0;
|
||||||
$record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true );
|
}
|
||||||
|
|
||||||
if ( ! is_array( $record ) || empty( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) {
|
$entry = $record[ $method ][ $context_key ] ?? null;
|
||||||
return 0;
|
|
||||||
}
|
if ( ! is_array( $entry ) || empty( $entry['verified_at'] ) || ! is_int( $entry['verified_at'] ) ) {
|
||||||
|
return 0;
|
||||||
if ( empty( $record[ $method ][ $context_key ]['verified_at'] ) ) {
|
}
|
||||||
return 0;
|
|
||||||
}
|
return $entry['verified_at'];
|
||||||
|
}
|
||||||
return (int) $record[ $method ][ $context_key ]['verified_at'];
|
|
||||||
}
|
/**
|
||||||
|
* Remove stored verification timestamps.
|
||||||
/**
|
*
|
||||||
* Remove stored verification timestamps.
|
* @param int $user_id User identifier.
|
||||||
*
|
*
|
||||||
* @param int $user_id User identifier.
|
* @return void
|
||||||
*
|
*/
|
||||||
* @return void
|
public function delete_last_verifications( int $user_id ): void {
|
||||||
*/
|
delete_user_meta( $user_id, self::LAST_VERIFICATIONS_META );
|
||||||
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) ===
|
=== 2FA (by ROBOTSTXT) ===
|
||||||
Contributors: robotstxt
|
Contributors: robotstxt
|
||||||
Tags: security, two-factor authentication, login, otp
|
Tags: security, two-factor authentication, login, otp
|
||||||
Requires at least: 6.4
|
Requires at least: 6.4
|
||||||
Tested up to: 6.4
|
Tested up to: 7.0
|
||||||
Requires PHP: 8.2
|
Requires PHP: 8.2
|
||||||
Stable tag: 0.2.0
|
Stable tag: 0.3.0
|
||||||
License: GPLv3 or later
|
License: GPLv3 or later
|
||||||
License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
||||||
|
|
||||||
Security plugin that adds a two-factor authentication flow to the WordPress login screen.
|
Security plugin that adds per-role two-factor authentication to the WordPress login flow.
|
||||||
|
|
||||||
== Description ==
|
== Description ==
|
||||||
|
|
||||||
This plugin lets administrators enforce two-factor authentication per role and already delivers email verification codes during the login flow. After the username and password are validated, the login screen redirects to a dedicated verification step flagged with its own query parameter. The screen hides the username and password controls, automatically prioritizes authenticator apps when they are enabled, offers links to switch between authenticator, email, or recovery-code challenges, lets email users trigger an additional delivery when they need a fresh code, and auto-submits once the active method reaches its expected length (six digits for OTP, seven for email, eight for recovery codes). Users can manage their preferences from their profile, where every method starts unchecked until it is explicitly confirmed. The authenticator section now keeps the QR code and setup key visible until a valid six-digit code is entered, regenerates the secret whenever the option is disabled, and surfaces a dedicated button to issue a replacement secret. Recovery codes are shown in a two-column grid, expose the remaining count out of ten, require entering one code before activation, and automatically reset when the stored batch is exhausted so a fresh list is always available without extra clicks.
|
2FA (by ROBOTSTXT) enforces two-factor authentication on the WordPress login screen. Administrators configure a per-role matrix that specifies exactly which verification methods are required for each role: email codes, authenticator apps (TOTP), or recovery codes.
|
||||||
|
|
||||||
Administrators can remember successful verifications for a configurable duration—per login, daily, weekly, or every 28 days—and even lock the schedule so profiles inherit the global requirement. Device and IP fingerprints are stored securely to decide when a fresh challenge is needed, ensuring suspicious logins must re-validate regardless of the remembered interval.
|
After the username and password are validated, the login screen redirects to a dedicated verification step. The screen hides the username and password controls, prioritises authenticator apps when enabled, and offers links to switch between methods without restarting the login. Email users can request a fresh code from the same screen.
|
||||||
|
|
||||||
== Installation ==
|
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.
|
||||||
|
|
||||||
1. Upload the `robotstxt-2fa` directory to `/wp-content/plugins/`.
|
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.
|
||||||
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.
|
Multisite is fully supported: network administrators can set and lock enforcement settings across all sites.
|
||||||
|
|
||||||
== Frequently Asked Questions ==
|
== Installation ==
|
||||||
|
|
||||||
= Is this plugin production ready? =
|
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).
|
||||||
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.
|
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.
|
||||||
= How do I enable the authenticator QR code? =
|
|
||||||
|
== Frequently Asked Questions ==
|
||||||
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.
|
|
||||||
|
= Is this plugin production ready? =
|
||||||
== Changelog ==
|
|
||||||
|
Yes. Email codes, authenticator apps with on-site QR codes, and recovery codes are all available and tested.
|
||||||
Review the `changelog.txt` file for additional details.
|
|
||||||
|
= How do I enable the authenticator QR code? =
|
||||||
== Upgrade Notice ==
|
|
||||||
|
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.
|
||||||
= 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.
|
= Can I enforce 2FA for specific roles only? =
|
||||||
|
|
||||||
= 0.1.0 =
|
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.
|
||||||
Initial version containing the basic plugin structure.
|
|
||||||
|
= 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
|
<?php
|
||||||
/**
|
/**
|
||||||
* Plugin Name: 2FA (by ROBOTSTXT)
|
* Plugin Name: 2FA (by ROBOTSTXT)
|
||||||
* Plugin URI: https://www.robotstxt.es/plugins/robotstxt-2fa/
|
* Plugin URI: https://www.robotstxt.es/plugins/robotstxt-2fa/
|
||||||
* Description: Adds two-factor authentication to the WordPress login flow.
|
* Description: Adds two-factor authentication to the WordPress login flow.
|
||||||
* Version: 0.2.0
|
* Version: 0.3.0
|
||||||
* Author: ROBOTSTXT
|
* Author: ROBOTSTXT
|
||||||
* Author URI: https://www.robotstxt.es/
|
* Author URI: https://www.robotstxt.es/
|
||||||
* Text Domain: robotstxt-2fa
|
* Text Domain: robotstxt-2fa
|
||||||
* Requires at least: 6.4
|
* Requires at least: 6.4
|
||||||
* Requires PHP: 8.2
|
* Requires PHP: 8.2
|
||||||
* License: GPLv2 or later
|
* Network: true
|
||||||
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
|
* License: GPLv3 or later
|
||||||
*
|
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
||||||
* @package Robotstxt_2FA
|
*
|
||||||
*/
|
* @package Robotstxt_2FA
|
||||||
|
*/
|
||||||
use Robotstxt\TwoFA\Plugin;
|
|
||||||
|
use Robotstxt\TwoFA\Plugin;
|
||||||
if ( ! defined( 'ABSPATH' ) ) {
|
|
||||||
exit;
|
if ( ! defined( 'ABSPATH' ) ) {
|
||||||
}
|
exit;
|
||||||
|
}
|
||||||
if ( ! defined( 'ROBOTSTXT_2FA_VERSION' ) ) {
|
|
||||||
define( 'ROBOTSTXT_2FA_VERSION', '0.2.0' );
|
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_FILE' ) ) {
|
||||||
}
|
define( 'ROBOTSTXT_2FA_FILE', __FILE__ );
|
||||||
|
}
|
||||||
if ( ! defined( 'ROBOTSTXT_2FA_PATH' ) ) {
|
|
||||||
define( 'ROBOTSTXT_2FA_PATH', plugin_dir_path( __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__ ) );
|
if ( ! defined( 'ROBOTSTXT_2FA_URL' ) ) {
|
||||||
}
|
define( 'ROBOTSTXT_2FA_URL', plugin_dir_url( __FILE__ ) );
|
||||||
|
}
|
||||||
$autoload = ROBOTSTXT_2FA_PATH . 'vendor/autoload.php';
|
|
||||||
|
$robotstxt_2fa_autoload = ROBOTSTXT_2FA_PATH . 'vendor/autoload.php';
|
||||||
if ( file_exists( $autoload ) ) {
|
|
||||||
require_once $autoload;
|
if ( file_exists( $robotstxt_2fa_autoload ) ) {
|
||||||
}
|
require_once $robotstxt_2fa_autoload;
|
||||||
|
}
|
||||||
/**
|
|
||||||
* Simple autoloader for the plugin classes.
|
/**
|
||||||
*
|
* Simple autoloader for the plugin classes.
|
||||||
* @param string $class Fully qualified class name requested by PHP.
|
*
|
||||||
*
|
* @param string $class_name Fully qualified class name requested by PHP.
|
||||||
* @return void
|
*
|
||||||
*/
|
* @return void
|
||||||
function robotstxt_2fa_autoload( string $class ): void {
|
*/
|
||||||
$prefix = 'Robotstxt\\TwoFA\\';
|
function robotstxt_2fa_autoload( string $class_name ): void {
|
||||||
|
$prefix = 'Robotstxt\\TwoFA\\';
|
||||||
if ( strncmp( $prefix, $class, strlen( $prefix ) ) !== 0 ) {
|
|
||||||
return;
|
if ( strncmp( $prefix, $class_name, strlen( $prefix ) ) !== 0 ) {
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
$relative_class = substr( $class, strlen( $prefix ) );
|
|
||||||
$relative_parts = explode( '\\', $relative_class );
|
$relative_class = substr( $class_name, strlen( $prefix ) );
|
||||||
$filename = array_pop( $relative_parts );
|
$relative_parts = explode( '\\', $relative_class );
|
||||||
|
$filename = array_pop( $relative_parts );
|
||||||
$directories = '';
|
|
||||||
|
$directories = '';
|
||||||
if ( ! empty( $relative_parts ) ) {
|
|
||||||
$relative_parts = array_map(
|
if ( ! empty( $relative_parts ) ) {
|
||||||
static function ( string $part ): string {
|
$relative_parts = array_map(
|
||||||
return strtolower( str_replace( '_', '-', $part ) );
|
static function ( string $part ): string {
|
||||||
},
|
return strtolower( str_replace( '_', '-', $part ) );
|
||||||
$relative_parts
|
},
|
||||||
);
|
$relative_parts
|
||||||
|
);
|
||||||
$directories = trailingslashit( implode( '/', $relative_parts ) );
|
|
||||||
}
|
$directories = trailingslashit( implode( '/', $relative_parts ) );
|
||||||
|
}
|
||||||
$filename = 'class-' . strtolower( str_replace( '_', '-', $filename ) ) . '.php';
|
|
||||||
$path = trailingslashit( ROBOTSTXT_2FA_PATH . 'includes' ) . $directories . $filename;
|
$filename = 'class-' . strtolower( str_replace( '_', '-', $filename ) ) . '.php';
|
||||||
|
$path = trailingslashit( ROBOTSTXT_2FA_PATH . 'includes' ) . $directories . $filename;
|
||||||
if ( file_exists( $path ) ) {
|
|
||||||
require_once $path;
|
if ( file_exists( $path ) ) {
|
||||||
}
|
require_once $path;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
spl_autoload_register( 'robotstxt_2fa_autoload' );
|
|
||||||
|
spl_autoload_register( 'robotstxt_2fa_autoload' );
|
||||||
/**
|
|
||||||
* Bootstrap the plugin once all plugins are loaded.
|
/**
|
||||||
*
|
* Bootstrap the plugin once all plugins are loaded.
|
||||||
* @return void
|
*
|
||||||
*/
|
* @return void
|
||||||
function robotstxt_2fa_bootstrap() {
|
*/
|
||||||
Plugin::get_instance()->init();
|
function robotstxt_2fa_bootstrap() {
|
||||||
}
|
Plugin::get_instance()->init();
|
||||||
add_action( 'plugins_loaded', 'robotstxt_2fa_bootstrap' );
|
}
|
||||||
|
add_action( 'plugins_loaded', 'robotstxt_2fa_bootstrap' );
|
||||||
register_activation_hook( __FILE__, array( Plugin::class, 'activate' ) );
|
|
||||||
register_deactivation_hook( __FILE__, array( Plugin::class, 'deactivate' ) );
|
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