robotstxt-2fa/includes/login/class-email-code-sender.php
2026-11-04 14:36:03 +00:00

288 lines
7.8 KiB
PHP

<?php
/**
* Email verification code sender.
*
* @package Robotstxt_2FA
*/
namespace Robotstxt\TwoFA\Login;
use Robotstxt\TwoFA\User\User_Settings_Repository;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles generation and delivery of email-based verification codes.
*/
class Email_Code_Sender {
/**
* Option key recording the last failed delivery attempt. Kept while mail
* delivery fails so administrators can see why forced-email users cannot
* sign in; cleared automatically once a code is delivered successfully.
*/
public const MAIL_FAILURE_OPTION = 'robotstxt_2fa_last_mail_failure';
/**
* Default length of the generated numeric code.
*/
private const CODE_LENGTH = 7;
/**
* Default number of seconds the generated code remains valid.
*/
private const EXPIRATION_SECONDS = 600;
/**
* Default minimum delay between email deliveries in seconds.
*/
private const RESEND_INTERVAL = 60;
/**
* User settings repository.
*
* @var User_Settings_Repository
*/
private User_Settings_Repository $user_settings_repository;
/**
* Constructor.
*/
public function __construct() {
$this->user_settings_repository = new User_Settings_Repository();
}
/**
* Retrieve the expected code length.
*
* Filterable via {@see 'robotstxt_2fa_code_length'}.
*
* @since 1.0.0
*
* @return int
*/
public function get_code_length(): int {
/**
* Filter the length (digit count) of the email verification code.
*
* @since 1.0.0
*
* @param int $length Default code length.
*/
return max( 1, absint( apply_filters( 'robotstxt_2fa_code_length', self::CODE_LENGTH ) ) );
}
/**
* Retrieve the minimum seconds that must elapse between resends.
*
* Filterable via {@see 'robotstxt_2fa_resend_interval'}.
*
* @since 1.0.0
*
* @return int
*/
public function get_resend_interval(): int {
/**
* Filter the minimum seconds between email code resend requests.
*
* @since 1.0.0
*
* @param int $seconds Default resend cooldown in seconds.
*/
return max( 1, absint( apply_filters( 'robotstxt_2fa_resend_interval', self::RESEND_INTERVAL ) ) );
}
/**
* Retrieve the code expiry duration in seconds.
*
* Filterable via {@see 'robotstxt_2fa_code_ttl'}.
*
* @since 1.0.0
*
* @return int
*/
public function get_code_ttl(): int {
/**
* Filter how long (in seconds) an email verification code stays valid.
*
* @since 1.0.0
*
* @param int $seconds Default TTL in seconds.
*/
return max( 60, absint( apply_filters( 'robotstxt_2fa_code_ttl', self::EXPIRATION_SECONDS ) ) );
}
/**
* Send a verification code to the provided user.
*
* @param \WP_User $user User who is requesting authentication.
*
* @return bool True when the email was sent or throttled successfully, false on failure.
*/
public function send_code( \WP_User $user ): bool {
if ( empty( $user->user_email ) || ! is_email( $user->user_email ) ) {
return false;
}
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
$current_time = time();
$resend_interval = $this->get_resend_interval();
if ( ! empty( $challenge['hash'] ) && $challenge['expires'] > $current_time && $challenge['sent_at'] >= ( $current_time - $resend_interval ) ) {
return true;
}
$code = $this->generate_code();
$expires = $current_time + $this->get_code_ttl();
$raw_blogname = get_option( 'blogname', '' );
$blog_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES );
$display_name = wp_strip_all_tags( ! empty( $user->display_name ) ? $user->display_name : $user->user_login );
/* translators: %s: site name. */
$email_subject = sprintf( __( '[%s] Your verification code', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'WordPress', 'robotstxt-2fa' ) );
/**
* Filter the subject line of the email verification code message.
*
* @since 1.0.0
*
* @param string $subject Default subject line.
* @param \WP_User $user User the code is being sent to.
*/
$email_subject = (string) apply_filters( 'robotstxt_2fa_email_subject', $email_subject, $user );
$message_lines = array(
/* translators: %s: user display name. */
sprintf( __( 'Hi %s,', 'robotstxt-2fa' ), $display_name ),
'',
/* translators: %s: site name. */
sprintf( __( 'Use the following verification code to finish signing in to %s:', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'your site', 'robotstxt-2fa' ) ),
'',
$code,
'',
__( 'The code expires in 10 minutes.', 'robotstxt-2fa' ),
'',
__( 'If you did not request this code you can ignore this email.', 'robotstxt-2fa' ),
);
$message = implode( "\n", $message_lines );
/**
* Filter the body of the email verification code message.
*
* @since 1.0.0
*
* @param string $message Plain-text message body.
* @param \WP_User $user User the code is being sent to.
* @param string $code Plain-text verification code.
*/
$message = (string) apply_filters( 'robotstxt_2fa_email_message', $message, $user, $code );
/**
* Fires just before the verification code email is delivered.
*
* @since 1.0.0
*
* @param int $user_id User ID the code is being sent to.
* @param string $code Plain-text verification code.
* @param int $expires Unix timestamp when the code expires.
*/
do_action( 'robotstxt_2fa_before_send_email', $user->ID, $code, $expires );
$headers = array( 'Content-Type: text/plain; charset=UTF-8' );
if ( ! wp_mail( $user->user_email, $email_subject, $message, $headers ) ) {
$this->record_mail_failure( $user->user_email );
return false;
}
$this->clear_mail_failure();
$this->user_settings_repository->store_email_challenge( $user->ID, $code, $expires );
return true;
}
/**
* Record a failed verification-code delivery for administrator visibility.
*
* When a role forces email verification, a failing wp_mail() locks users
* out of their accounts with no site-side signal. Store the failure so an
* admin notice can explain the root cause.
*
* @since 1.6.8
*
* @param string $to Intended recipient.
*
* @return void
*/
private function record_mail_failure( string $to ): void {
$existing = get_option( self::MAIL_FAILURE_OPTION, array() );
$record = is_array( $existing ) ? $existing : array();
update_option(
self::MAIL_FAILURE_OPTION,
array(
'at' => time(),
'to' => $to,
'count' => ( isset( $record['count'] ) && is_numeric( $record['count'] ) ? (int) $record['count'] : 0 ) + 1,
),
false
);
}
/**
* Clear the delivery failure marker after a successful delivery.
*
* @since 1.6.8
*
* @return void
*/
private function clear_mail_failure(): void {
delete_option( self::MAIL_FAILURE_OPTION );
}
/**
* Verify a submitted code against the stored challenge.
*
* @param \WP_User $user User attempting to authenticate.
* @param string $code Submitted verification code.
*
* @return bool
*/
public function verify_code( \WP_User $user, string $code ): bool {
$challenge = $this->user_settings_repository->get_email_challenge( $user->ID );
$code = preg_replace( '/[^0-9]/', '', $code ) ?? '';
$code_length = $this->get_code_length();
if ( '' === $challenge['hash'] ) {
return false;
}
if ( $challenge['expires'] <= time() ) {
return false;
}
if ( '' === $code || strlen( $code ) !== $code_length ) {
return false;
}
return wp_check_password( $code, $challenge['hash'] );
}
/**
* Generate a random numeric verification code.
*
* @return string
*/
private function generate_code(): string {
$length = $this->get_code_length();
$max_value = ( 10 ** $length ) - 1;
$code = (string) random_int( 0, $max_value );
return str_pad( $code, $length, '0', STR_PAD_LEFT );
}
}