robotstxt-2fa/includes/user/class-recovery-codes.php
2026-06-05 14:06:16 +00:00

462 lines
11 KiB
PHP

<?php
/**
* Manage generation and validation of recovery codes.
*
* @package Robotstxt_2FA
*/
namespace Robotstxt\TwoFA\User;
use WP_User;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles creation, storage, and consumption of recovery codes.
*/
class Recovery_Codes {
/**
* User meta key storing recovery code hashes.
*
* @var string
*/
private const META_KEY = 'robotstxt_2fa_recovery_codes';
/**
* Number of codes generated per batch.
*/
private const CODES_PER_BATCH = 10;
/**
* Number of digits per recovery code.
*/
private const CODE_LENGTH = 8;
/**
* Admin-post action slug used to request new recovery codes.
*/
public const ACTION_GENERATE = 'robotstxt_2fa_generate_recovery_codes';
/**
* Nonce action securing recovery code generation.
*/
public const NONCE_ACTION = 'robotstxt_2fa_generate_recovery_codes';
/**
* Nonce field key embedded in recovery code forms.
*/
public const NONCE_FIELD = 'robotstxt_2fa_recovery_nonce';
/**
* Register hooks required by the recovery code workflow.
*
* @return void
*/
public function register_hooks(): void {
add_action( 'wp_ajax_' . self::ACTION_GENERATE, array( $this, 'handle_ajax_generate_request' ) );
add_action( 'wp_ajax_nopriv_' . self::ACTION_GENERATE, array( $this, 'reject_unauthenticated_requests' ) );
}
/**
* Block unauthenticated requests attempting to generate recovery codes.
*
* @return void
*/
public function reject_unauthenticated_requests(): void {
$message = esc_html__( 'You must be logged in to manage recovery codes.', 'robotstxt-2fa' );
if ( wp_doing_ajax() ) {
wp_send_json_error(
array(
'message' => $message,
),
403
);
}
wp_die( $message, '', array( 'response' => 403 ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $message is escaped via esc_html__().
}
/**
* Handle AJAX requests to generate recovery codes without reloading the page.
*
* @return void
*/
public function handle_ajax_generate_request(): void {
check_ajax_referer( self::NONCE_ACTION, self::NONCE_FIELD );
$raw_user_id = isset( $_POST['user_id'] ) && is_string( $_POST['user_id'] ) ? wp_unslash( $_POST['user_id'] ) : '';
$user_id = absint( $raw_user_id );
if ( $user_id <= 0 ) {
wp_send_json_error(
array(
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
),
400
);
}
if ( ! current_user_can( 'edit_user', $user_id ) ) {
wp_send_json_error(
array(
'message' => esc_html__( 'You are not allowed to modify recovery codes for this account.', 'robotstxt-2fa' ),
),
403
);
}
$user = get_user_by( 'ID', $user_id );
if ( ! $user instanceof WP_User ) {
wp_send_json_error(
array(
'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ),
),
400
);
}
try {
$result = $this->regenerate_codes_for_user( $user );
} catch ( \Throwable $exception ) {
/**
* Fires when recovery code generation fails.
*
* @since 0.2.0
*
* @param \Throwable $exception The caught exception.
*/
do_action( 'robotstxt_2fa_recovery_generation_failed', $exception );
wp_send_json_error(
array(
'message' => esc_html__( 'We could not generate recovery codes. Please try again.', 'robotstxt-2fa' ),
),
500
);
}
wp_send_json_success(
array(
'codes' => $result['codes'],
'unused_count' => $result['unused_count'],
'last_generated' => $result['generated_at'],
'last_generated_formatted' => $this->format_generated_timestamp( $result['generated_at'] ),
)
);
}
/**
* Generate and persist a new batch of recovery codes for a user.
*
* @param WP_User $user User whose recovery codes are being regenerated.
*
* @throws \Exception If secure randomness cannot be generated.
*
* @return array{codes: array<int, string>, generated_at: int, unused_count: int}
*/
public function regenerate_codes_for_user( WP_User $user ): array {
$codes = $this->generate_codes();
$this->store_codes( $user->ID, $codes );
return array(
'codes' => $codes,
'generated_at' => $this->get_last_generated_timestamp( $user->ID ),
'unused_count' => $this->count_unused_codes( $user->ID ),
);
}
/**
* Retrieve the number of digits expected for each recovery code.
*
* @return int
*/
public function get_code_length(): int {
return self::CODE_LENGTH;
}
/**
* Retrieve the number of recovery codes generated per batch.
*
* @return int
*/
public function get_codes_per_batch(): int {
return self::CODES_PER_BATCH;
}
/**
* Count the amount of unused recovery codes available for the user.
*
* @param int $user_id User identifier.
*
* @return int
*/
public function count_unused_codes( int $user_id ): int {
$record = $this->get_stored_codes( $user_id );
if ( empty( $record['codes'] ) ) {
return 0;
}
$unused = 0;
foreach ( $record['codes'] as $entry ) {
if ( empty( $entry['used_at'] ) ) {
++$unused;
}
}
return $unused;
}
/**
* Determine whether the user currently has any unused recovery codes.
*
* @param int $user_id User identifier.
*
* @return bool
*/
public function has_active_codes( int $user_id ): bool {
return $this->count_unused_codes( $user_id ) > 0;
}
/**
* Consume a recovery code if it matches one of the stored hashes.
*
* @param WP_User $user User attempting to validate a recovery code.
* @param string $code Submitted plain-text code.
*
* @return bool
*/
public function consume_code( WP_User $user, string $code ): bool {
$normalized_code = $this->normalize_code( $code );
if ( '' === $normalized_code ) {
return false;
}
$record = $this->get_stored_codes( $user->ID );
if ( empty( $record['codes'] ) ) {
return false;
}
$updated = false;
foreach ( $record['codes'] as $index => $entry ) {
if ( ! empty( $entry['used_at'] ) || empty( $entry['hash'] ) ) {
continue;
}
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
$record['codes'][ $index ]['used_at'] = time();
$updated = true;
break;
}
}
if ( $updated ) {
update_user_meta( $user->ID, self::META_KEY, $record );
return true;
}
return false;
}
/**
* Fetch the timestamp of the last generation batch.
*
* @param int $user_id User identifier.
*
* @return int
*/
public function get_last_generated_timestamp( int $user_id ): int {
$record = $this->get_stored_codes( $user_id );
return $record['generated_at'];
}
/**
* Format the provided timestamp using the site's date and time preferences.
*
* @param int $timestamp Unix timestamp representing the generation time.
*
* @return string
*/
private function format_generated_timestamp( int $timestamp ): string {
if ( $timestamp <= 0 ) {
return '';
}
$date_format = get_option( 'date_format' );
$time_format = get_option( 'time_format' );
$format = trim( ( is_string( $date_format ) ? $date_format : '' ) . ' ' . ( is_string( $time_format ) ? $time_format : '' ) );
$formatted = wp_date( '' !== $format ? $format : 'c', $timestamp );
return false !== $formatted ? $formatted : '';
}
/**
* Generate a batch of unique recovery codes.
*
* @throws \Exception If randomness cannot be generated.
*
* @return array<int, string>
*/
private function generate_codes(): array {
$codes = array();
$attempts = 0;
$target_count = self::CODES_PER_BATCH;
$max_attempts = $target_count * 3;
$unique_count = 0;
while ( $unique_count < $target_count && $attempts < $max_attempts ) {
++$attempts;
$code = $this->generate_single_code();
if ( in_array( $code, $codes, true ) ) {
continue;
}
$codes[] = $code;
++$unique_count;
}
return $codes;
}
/**
* Create a single recovery code.
*
* @throws \Exception If secure randomness cannot be generated.
*
* @return string
*/
private function generate_single_code(): string {
$max_value = ( 10 ** self::CODE_LENGTH ) - 1;
$number = random_int( 0, $max_value );
return str_pad( (string) $number, self::CODE_LENGTH, '0', STR_PAD_LEFT );
}
/**
* Normalize user-submitted recovery codes.
*
* @param string $code Submitted code.
*
* @return string
*/
private function normalize_code( string $code ): string {
$code = preg_replace( '/[^0-9]/', '', $code );
if ( null === $code ) {
return '';
}
$code = substr( $code, 0, self::CODE_LENGTH );
if ( strlen( $code ) !== self::CODE_LENGTH ) {
return '';
}
return $code;
}
/**
* Store recovery codes and metadata for a user.
*
* @param int $user_id User identifier.
* @param array<int, string> $codes Plain-text recovery codes.
*
* @return void
*/
private function store_codes( int $user_id, array $codes ): void {
$stored_codes = array();
foreach ( $codes as $code ) {
$stored_codes[] = array(
'hash' => wp_hash_password( $this->normalize_code( $code ) ),
'used_at' => 0,
);
}
$record = array(
'generated_at' => time(),
'codes' => $stored_codes,
);
update_user_meta( $user_id, self::META_KEY, $record );
}
/**
* Retrieve and sanitize stored recovery code metadata.
*
* @param int $user_id User identifier.
*
* @return array{generated_at: int, codes: array<int, array{hash: string, used_at: int}>}
*/
private function get_stored_codes( int $user_id ): array {
$record = get_user_meta( $user_id, self::META_KEY, true );
if ( ! is_array( $record ) ) {
$record = array();
}
$generated_at = isset( $record['generated_at'] ) && is_int( $record['generated_at'] ) ? $record['generated_at'] : 0;
$raw_codes = isset( $record['codes'] ) && is_array( $record['codes'] ) ? $record['codes'] : array();
$codes = array();
foreach ( $raw_codes as $entry ) {
$codes[] = array(
'hash' => is_array( $entry ) && isset( $entry['hash'] ) && is_string( $entry['hash'] ) ? $entry['hash'] : '',
'used_at' => is_array( $entry ) && isset( $entry['used_at'] ) && is_int( $entry['used_at'] ) ? $entry['used_at'] : 0,
);
}
return array(
'generated_at' => $generated_at,
'codes' => $codes,
);
}
/**
* Verify whether the provided recovery code matches a stored hash without consuming it.
*
* @param WP_User $user User attempting to validate a recovery code.
* @param string $code Submitted plain-text code.
*
* @return bool
*/
public function verify_code_without_consuming( WP_User $user, string $code ): bool {
$normalized_code = $this->normalize_code( $code );
if ( '' === $normalized_code ) {
return false;
}
$record = $this->get_stored_codes( $user->ID );
if ( empty( $record['codes'] ) ) {
return false;
}
foreach ( $record['codes'] as $entry ) {
if ( empty( $entry['hash'] ) ) {
continue;
}
if ( wp_check_password( $normalized_code, $entry['hash'] ) ) {
return true;
}
}
return false;
}
}