You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/AccountSecurityService.php

219 lines
7.9 KiB
PHP

<?php
namespace App\Services;
use App\Models\EmailVerify;
use App\Models\User;
use App\Utils\Totp;
/** Account security helpers shared by the account drawer and password API. */
class AccountSecurityService
{
private const SEND_COOLDOWN_SECONDS = 60;
private const ACTIVE_CODE_LIMIT = 3;
private const FACTOR_FAIL_LIMIT = 8;
private const FACTOR_FAIL_TTL = 600;
public static function hasTotp(User $user): bool
{
return (int) $user->ga_enable === 1
&& Totp::normalizeSecret($user->ga_token) !== '';
}
/** @return array{ok:bool,msg:string,retry_after:int} */
public static function sendPasswordEmailCode(User $user, $clientIp = ''): array
{
$email = strtolower(trim((string) $user->email));
if ($email === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return ['ok' => false, 'msg' => '账户邮箱无效', 'retry_after' => 0];
}
if (Mail::isRecipientBlacklisted($email)) {
return ['ok' => false, 'msg' => '当前邮箱暂时无法接收验证邮件', 'retry_after' => 0];
}
$ip = is_scalar($clientIp) ? trim((string) $clientIp) : '';
$redis = new RedisClient();
// Scope the send gate to the authenticated account. Binding it to a
// client IP lets a requester evade the cooldown by rotating proxies.
$key = self::sendCooldownKey($user);
if (!self::acquireCooldown($redis, $key)) {
$retryAfter = self::ttl($redis, $key);
return ['ok' => false, 'msg' => '请求过于频繁,请稍后再试', 'retry_after' => $retryAfter];
}
$now = time();
$ttl = (int) CaptchaConfig::get('email_verify_ttl');
$active = EmailVerify::where('email', $email)
->where('code', 'like', 'password_change:%')
->where('expire_in', '>', $now)
->count();
if ((int) $active >= self::ACTIVE_CODE_LIMIT) {
return ['ok' => false, 'msg' => '验证码请求次数过多,请稍后再试', 'retry_after' => self::SEND_COOLDOWN_SECONDS];
}
$verification = new EmailVerify();
$verification->email = $email;
$verification->ip = $ip === '' ? '0.0.0.0' : $ip;
$plainCode = (string) random_int(100000, 999999);
$verification->code = 'password_change:' . $plainCode;
$verification->expire_in = $now + $ttl;
if (!$verification->save()) {
return ['ok' => false, 'msg' => '验证码发送失败,请稍后重试', 'retry_after' => 0];
}
try {
$sent = Mail::send(
$email,
'Password Change Verification',
'auth/verify.tpl',
[
'code' => $plainCode,
'expire' => date('Y-m-d H:i:s', $verification->expire_in),
'language' => 'false',
'scene' => 'password_change',
],
[],
'修改密码验证'
);
} catch (\Throwable $exception) {
$sent = false;
}
if (!$sent) {
$verification->delete();
return ['ok' => false, 'msg' => '验证码发送失败,请稍后重试', 'retry_after' => 0];
}
return ['ok' => true, 'msg' => '验证码已发送,请检查邮箱', 'retry_after' => self::SEND_COOLDOWN_SECONDS];
}
/** Consume one accepted password-change factor. */
public static function consumePasswordFactor(User $user, $emailCode = '', $totpCode = '', $clientIp = ''): ?string
{
$emailCode = is_scalar($emailCode) ? trim((string) $emailCode) : '';
$totpCode = is_scalar($totpCode) ? trim((string) $totpCode) : '';
$hasTotp = self::hasTotp($user);
$email = strtolower(trim((string) $user->email));
// Empty or structurally impossible input is not an authentication
// attempt. Reject it before constructing the optional Redis abuse
// limiter so validation remains deterministic even when Redis is not
// configured (for example during a fresh install health check).
if (!$hasTotp && ($emailCode === '' || !preg_match('/^\d{6}$/D', $emailCode))) {
return null;
}
if (!$hasTotp && ($email === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false)) {
return null;
}
$redis = new RedisClient();
$failKey = self::factorFailKey($user);
if (self::factorFailures($redis, $failKey) >= self::FACTOR_FAIL_LIMIT) {
return null;
}
if ($hasTotp) {
if (Totp::verify($user->ga_token, $totpCode)) {
self::clearFactorFailures($redis, $failKey);
return 'totp';
}
}
if ($emailCode === '' || !preg_match('/^\d{6}$/D', $emailCode)
|| $email === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false
|| Mail::isRecipientBlacklisted($email)) {
self::recordFactorFailure($redis, $failKey);
return null;
}
$connection = (new EmailVerify())->getConnection();
$consumed = false;
$connection->transaction(function () use ($email, $emailCode, &$consumed) {
$verification = EmailVerify::where('email', $email)
->where('code', 'password_change:' . $emailCode)
->where('expire_in', '>', time())
->lockForUpdate()
->first();
if ($verification !== null) {
$verification->delete();
$consumed = true;
}
}, 3);
if ($consumed) {
self::clearFactorFailures($redis, $failKey);
return 'email';
}
self::recordFactorFailure($redis, $failKey);
return null;
}
private static function sendCooldownKey(User $user): string
{
return 'account_password_verify_send:' . (int) $user->id;
}
private static function ttl(RedisClient $redis, string $key): int
{
try {
$ttl = $redis->getClient()->ttl($key);
return $ttl > 0 ? (int) $ttl : 0;
} catch (\Throwable $exception) {
return 0;
}
}
private static function acquireCooldown(RedisClient $redis, string $key): bool
{
try {
$result = $redis->getClient()->set(
$key,
'1',
'EX',
self::SEND_COOLDOWN_SECONDS,
'NX'
);
return $result === true || strtoupper((string) $result) === 'OK';
} catch (\Throwable $exception) {
// Redis is an abuse-control accelerator. The database active-code
// limit still bounds outstanding codes when it is unavailable.
return true;
}
}
private static function factorFailKey(User $user): string
{
return 'account_password_verify_fail:' . (int) $user->id;
}
private static function factorFailures(RedisClient $redis, string $key): int
{
try {
$value = $redis->getClient()->get($key);
return is_numeric($value) ? (int) $value : 0;
} catch (\Throwable $exception) {
return 0;
}
}
private static function recordFactorFailure(RedisClient $redis, string $key): void
{
try {
$client = $redis->getClient();
$value = (int) $client->incr($key);
if ($value === 1) {
$client->expire($key, self::FACTOR_FAIL_TTL);
}
} catch (\Throwable $exception) {
// Continue with database verification when Redis is unavailable.
}
}
private static function clearFactorFailures(RedisClient $redis, string $key): void
{
try {
$redis->del($key);
} catch (\Throwable $exception) {
// A stale failure counter only affects abuse throttling.
}
}
}