feat(auth): complete registration anti-spam and quota hardening

This commit is contained in:
2026-02-21 12:13:01 +01:00
parent 4fb95c872b
commit b239af9619
33 changed files with 1288 additions and 142 deletions

View File

@@ -2,24 +2,26 @@
namespace App\Http\Controllers\Auth;
use App\Jobs\SendVerificationEmailJob;
use App\Http\Controllers\Controller;
use App\Mail\RegistrationVerificationMail;
use App\Models\EmailSendEvent;
use App\Models\User;
use App\Services\Security\RecaptchaVerifier;
use Carbon\CarbonImmutable;
use App\Services\Auth\DisposableEmailService;
use App\Services\Auth\RegistrationVerificationTokenService;
use App\Services\Security\TurnstileVerifier;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\View\View;
class RegisteredUserController extends Controller
{
public function __construct(
private readonly RecaptchaVerifier $recaptchaVerifier
private readonly TurnstileVerifier $turnstileVerifier,
private readonly DisposableEmailService $disposableEmailService,
private readonly RegistrationVerificationTokenService $verificationTokenService,
)
{
}
@@ -31,6 +33,8 @@ class RegisteredUserController extends Controller
{
return view('auth.register', [
'prefillEmail' => (string) $request->query('email', ''),
'requiresTurnstile' => $this->shouldRequireTurnstile($request->ip()),
'turnstileSiteKey' => (string) config('services.turnstile.site_key', ''),
]);
}
@@ -53,54 +57,77 @@ class RegisteredUserController extends Controller
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255'],
'website' => ['nullable', 'max:0'],
'cf-turnstile-response' => ['nullable', 'string'],
]);
if ($this->recaptchaVerifier->isEnabled()) {
$request->validate([
'g-recaptcha-response' => ['required', 'string'],
]);
$email = strtolower(trim((string) $validated['email']));
$ip = $request->ip();
$verified = $this->recaptchaVerifier->verify(
(string) $request->input('g-recaptcha-response', ''),
$request->ip()
$this->trackRegisterAttempt($ip);
if ($this->shouldRequireTurnstile($ip)) {
$verified = $this->turnstileVerifier->verify(
(string) $request->input('cf-turnstile-response', ''),
$ip
);
if (! $verified) {
return back()
->withInput($request->except('website'))
->withErrors(['captcha' => 'reCAPTCHA verification failed. Please try again.']);
->withErrors(['captcha' => 'Captcha verification failed. Please try again.']);
}
}
$user = User::create([
'username' => null,
'name' => Str::before((string) $validated['email'], '@'),
'email' => $validated['email'],
'password' => Hash::make(Str::random(64)),
'is_active' => false,
'onboarding_step' => 'email',
'username_changed_at' => now(),
]);
if ($this->disposableEmailService->isDisposableEmail($email)) {
$this->logEmailEvent($email, $ip, null, 'blocked', 'disposable');
$token = Str::random(64);
DB::table('user_verification_tokens')->insert([
'user_id' => $user->id,
'token' => $token,
'expires_at' => now()->addDay(),
'created_at' => now(),
'updated_at' => now(),
]);
return back()
->withInput($request->except('website'))
->withErrors(['email' => 'Please use a real email provider.']);
}
Mail::to($user->email)->queue(new RegistrationVerificationMail($token));
$user = User::query()->where('email', $email)->first();
$cooldown = $this->resendCooldownSeconds();
$this->setResendCooldown((string) $validated['email'], $cooldown);
if ($user && $user->email_verified_at !== null) {
$this->logEmailEvent($email, $ip, (int) $user->id, 'blocked', 'already-verified');
return redirect(route('register.notice', absolute: false))
->with('status', 'Verification email sent. Please check your inbox.')
->with('registration_email', (string) $validated['email']);
return $this->redirectToRegisterNotice($email);
}
if (! $user) {
$user = User::query()->create([
'username' => null,
'name' => Str::before($email, '@'),
'email' => $email,
'password' => Hash::make(Str::random(64)),
'is_active' => false,
'onboarding_step' => 'email',
'username_changed_at' => now(),
]);
}
if ($this->isWithinEmailCooldown($user)) {
$this->logEmailEvent($email, $ip, (int) $user->id, 'blocked', 'cooldown');
return $this->redirectToRegisterNotice($email);
}
$token = $this->verificationTokenService->createForUser((int) $user->id);
$event = $this->logEmailEvent($email, $ip, (int) $user->id, 'queued', null);
SendVerificationEmailJob::dispatch(
emailEventId: (int) $event->id,
email: $email,
token: $token,
userId: (int) $user->id,
ip: $ip
);
$this->markVerificationEmailSent($user);
return $this->redirectToRegisterNotice($email);
}
public function resendVerification(Request $request): RedirectResponse
@@ -109,13 +136,8 @@ class RegisteredUserController extends Controller
'email' => ['required', 'string', 'lowercase', 'email', 'max:255'],
]);
$email = (string) $validated['email'];
$remaining = $this->resendRemainingSeconds($email);
if ($remaining > 0) {
return back()
->with('registration_email', $email)
->withErrors(['email' => "Please wait {$remaining} seconds before resending."]);
}
$email = strtolower(trim((string) $validated['email']));
$ip = $request->ip();
$user = User::query()
->where('email', $email)
@@ -124,55 +146,162 @@ class RegisteredUserController extends Controller
->first();
if (! $user) {
return back()
->with('registration_email', $email)
->withErrors(['email' => 'No pending verification found for this email.']);
$this->logEmailEvent($email, $ip, null, 'blocked', 'missing');
return $this->redirectToRegisterNotice($email);
}
DB::table('user_verification_tokens')->where('user_id', $user->id)->delete();
if ($this->isWithinEmailCooldown($user)) {
$this->logEmailEvent($email, $ip, (int) $user->id, 'blocked', 'cooldown');
$token = Str::random(64);
DB::table('user_verification_tokens')->insert([
'user_id' => $user->id,
'token' => $token,
'expires_at' => now()->addDay(),
'created_at' => now(),
'updated_at' => now(),
]);
return $this->redirectToRegisterNotice($email);
}
Mail::to($user->email)->queue(new RegistrationVerificationMail($token));
$token = $this->verificationTokenService->createForUser((int) $user->id);
$event = $this->logEmailEvent($email, $ip, (int) $user->id, 'queued', null);
$cooldown = $this->resendCooldownSeconds();
$this->setResendCooldown($email, $cooldown);
SendVerificationEmailJob::dispatch(
emailEventId: (int) $event->id,
email: $email,
token: $token,
userId: (int) $user->id,
ip: $ip
);
$this->markVerificationEmailSent($user);
return $this->redirectToRegisterNotice($email);
}
private function redirectToRegisterNotice(string $email): RedirectResponse
{
return redirect(route('register.notice', absolute: false))
->with('registration_email', $email)
->with('status', 'Verification email resent. Please check your inbox.');
->with('status', $this->genericSuccessMessage())
->with('registration_email', $email);
}
private function genericSuccessMessage(): string
{
return (string) config('registration.generic_success_message', 'If that email is valid, we sent a verification link.');
}
private function logEmailEvent(string $email, ?string $ip, ?int $userId, string $status, ?string $reason): EmailSendEvent
{
return EmailSendEvent::query()->create([
'type' => 'verify_email',
'email' => $email,
'ip' => $ip,
'user_id' => $userId,
'status' => $status,
'reason' => $reason,
'created_at' => now(),
]);
}
private function shouldRequireTurnstile(?string $ip): bool
{
if (! $this->turnstileVerifier->isEnabled()) {
return false;
}
if ($ip === null || $ip === '') {
return false;
}
$threshold = max(1, (int) config('registration.turnstile_suspicious_attempts', 2));
$attempts = (int) cache()->get($this->registerAttemptCacheKey($ip), 0);
if ($attempts >= $threshold) {
return true;
}
$minuteLimit = max(1, (int) config('registration.ip_per_minute_limit', 3));
$dailyLimit = max(1, (int) config('registration.ip_per_day_limit', 20));
if (RateLimiter::tooManyAttempts($this->registerIpRateKey($ip), $minuteLimit)) {
return true;
}
return RateLimiter::tooManyAttempts($this->registerIpDailyRateKey($ip), $dailyLimit);
}
private function trackRegisterAttempt(?string $ip): void
{
if ($ip === null || $ip === '') {
return;
}
$key = $this->registerAttemptCacheKey($ip);
$windowMinutes = max(1, (int) config('registration.turnstile_attempt_window_minutes', 30));
$seconds = $windowMinutes * 60;
$attempts = (int) cache()->get($key, 0);
cache()->put($key, $attempts + 1, $seconds);
}
private function registerAttemptCacheKey(string $ip): string
{
return 'register:attempts:' . sha1($ip);
}
private function registerIpRateKey(string $ip): string
{
return 'register:ip:' . $ip;
}
private function registerIpDailyRateKey(string $ip): string
{
return 'register:ip:daily:' . $ip;
}
private function isWithinEmailCooldown(User $user): bool
{
if ($user->last_verification_sent_at === null) {
return false;
}
$cooldownMinutes = max(1, (int) config('registration.email_cooldown_minutes', 30));
return $user->last_verification_sent_at->gt(now()->subMinutes($cooldownMinutes));
}
private function markVerificationEmailSent(User $user): void
{
$now = now();
$windowStartedAt = $user->verification_send_window_started_at;
if (! $windowStartedAt || $windowStartedAt->lt($now->copy()->subDay())) {
$user->verification_send_window_started_at = $now;
$user->verification_send_count_24h = 1;
} else {
$user->verification_send_count_24h = ((int) $user->verification_send_count_24h) + 1;
}
$user->last_verification_sent_at = $now;
$user->save();
}
private function resendCooldownSeconds(): int
{
return max(5, (int) config('antispam.register.resend_cooldown_seconds', 60));
}
private function resendCooldownCacheKey(string $email): string
{
return 'register:resend:cooldown:' . sha1(strtolower(trim($email)));
}
private function setResendCooldown(string $email, int $seconds): void
{
$until = CarbonImmutable::now()->addSeconds($seconds)->timestamp;
Cache::put($this->resendCooldownCacheKey($email), $until, $seconds + 5);
return max(60, ((int) config('registration.email_cooldown_minutes', 30)) * 60);
}
private function resendRemainingSeconds(string $email): int
{
$until = (int) Cache::get($this->resendCooldownCacheKey($email), 0);
if ($until <= 0) {
$user = User::query()
->where('email', strtolower(trim($email)))
->whereNull('email_verified_at')
->first();
if (! $user || $user->last_verification_sent_at === null) {
return 0;
}
return max(0, $until - time());
$remaining = $user->last_verification_sent_at
->copy()
->addSeconds($this->resendCooldownSeconds())
->diffInSeconds(now(), false);
return $remaining >= 0 ? 0 : abs((int) $remaining);
}
}

View File

@@ -4,30 +4,28 @@ namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Auth\RegistrationVerificationTokenService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class RegistrationVerificationController extends Controller
{
public function __construct(
private readonly RegistrationVerificationTokenService $tokenService
)
{
}
public function __invoke(string $token): RedirectResponse
{
$record = DB::table('user_verification_tokens')
->where('token', $token)
->first();
$record = $this->tokenService->findValidRecord($token);
if (! $record) {
return redirect(route('login', absolute: false))
->withErrors(['email' => 'Verification link is invalid.']);
}
if (now()->greaterThan($record->expires_at)) {
DB::table('user_verification_tokens')->where('id', $record->id)->delete();
return redirect(route('login', absolute: false))
->withErrors(['email' => 'Verification link has expired.']);
}
$user = User::query()->find((int) $record->user_id);
if (! $user) {
DB::table('user_verification_tokens')->where('id', $record->id)->delete();

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Jobs;
use App\Mail\RegistrationVerificationMail;
use App\Services\Auth\RegistrationEmailQuotaService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\RateLimiter;
class SendVerificationEmailJob implements ShouldQueue
{
use Queueable;
public int $tries = 5;
public function __construct(
public readonly int $emailEventId,
public readonly string $email,
public readonly string $token,
public readonly ?int $userId,
public readonly ?string $ip
) {
$this->onQueue('mail');
}
public function handle(RegistrationEmailQuotaService $quotaService): void
{
$key = 'registration:verification-email:global';
$maxPerMinute = max(1, (int) config('registration.email_global_send_per_minute', 30));
$allowed = RateLimiter::attempt($key, $maxPerMinute, static fn () => true, 60);
if (! $allowed) {
$this->release(10);
return;
}
if ($quotaService->isExceeded()) {
$this->updateEvent('blocked', 'quota');
return;
}
Mail::to($this->email)->queue(new RegistrationVerificationMail($this->token));
$quotaService->incrementSentCount();
$this->updateEvent('sent', null);
}
private function updateEvent(string $status, ?string $reason): void
{
DB::table('email_send_events')
->where('id', $this->emailEventId)
->update([
'status' => $status,
'reason' => $reason,
]);
}
}

View File

@@ -40,7 +40,7 @@ class RegistrationVerificationMail extends Mailable implements ShouldQueue
view: 'emails.registration-verification',
with: [
'verificationUrl' => url('/verify/'.$this->token),
'expiresInHours' => 24,
'expiresInHours' => max(1, (int) config('registration.verify_token_ttl_hours', 24)),
'supportUrl' => $appUrl . '/support',
],
);

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class EmailSendEvent extends Model
{
protected $table = 'email_send_events';
public $timestamps = false;
protected $fillable = [
'type',
'email',
'ip',
'user_id',
'status',
'reason',
'created_at',
];
protected $casts = [
'created_at' => 'datetime',
];
public function user()
{
return $this->belongsTo(User::class);
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SystemEmailQuota extends Model
{
protected $table = 'system_email_quota';
public $timestamps = false;
protected $fillable = [
'period',
'sent_count',
'limit_count',
'updated_at',
];
protected $casts = [
'updated_at' => 'datetime',
'sent_count' => 'integer',
'limit_count' => 'integer',
];
}

View File

@@ -26,6 +26,9 @@ class User extends Authenticatable
'onboarding_step',
'name',
'email',
'last_verification_sent_at',
'verification_send_count_24h',
'verification_send_window_started_at',
'is_active',
'needs_password_reset',
'password',
@@ -51,6 +54,9 @@ class User extends Authenticatable
{
return [
'email_verified_at' => 'datetime',
'last_verification_sent_at' => 'datetime',
'verification_send_window_started_at' => 'datetime',
'verification_send_count_24h' => 'integer',
'username_changed_at' => 'datetime',
'deleted_at' => 'datetime',
'password' => 'hashed',

View File

@@ -91,10 +91,22 @@ class AppServiceProvider extends ServiceProvider
private function configureAuthRateLimiters(): void
{
RateLimiter::for('register-ip', function (Request $request): Limit {
$limit = max(1, (int) config('registration.ip_per_minute_limit', 3));
return Limit::perMinute($limit)->by('register:ip:' . $request->ip());
});
RateLimiter::for('register-ip-daily', function (Request $request): Limit {
$limit = max(1, (int) config('registration.ip_per_day_limit', 20));
return Limit::perDay($limit)->by('register:ip:daily:' . $request->ip());
});
RateLimiter::for('register', function (Request $request): array {
$emailKey = strtolower((string) $request->input('email', 'unknown'));
$ipLimit = (int) config('antispam.register.ip_per_minute', 20);
$emailLimit = (int) config('antispam.register.email_per_minute', 6);
$ipLimit = (int) config('registration.ip_per_minute_limit', 3);
$emailLimit = (int) config('registration.email_per_minute_limit', 6);
return [
Limit::perMinute($ipLimit)->by('register:ip:' . $request->ip()),

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Services\Auth;
class DisposableEmailService
{
public function isEnabled(): bool
{
return (bool) config('registration.disposable_domains_enabled', true);
}
public function isDisposableEmail(string $email): bool
{
if (! $this->isEnabled()) {
return false;
}
$domain = $this->extractDomain($email);
if ($domain === null) {
return false;
}
$blocked = (array) config('disposable_email_domains.domains', []);
foreach ($blocked as $entry) {
$pattern = strtolower(trim((string) $entry));
if ($pattern === '') {
continue;
}
if ($this->matchesPattern($domain, $pattern)) {
return true;
}
}
return false;
}
private function extractDomain(string $email): ?string
{
$normalized = strtolower(trim($email));
if ($normalized === '' || ! str_contains($normalized, '@')) {
return null;
}
$parts = explode('@', $normalized);
$domain = trim((string) end($parts));
return $domain !== '' ? $domain : null;
}
private function matchesPattern(string $domain, string $pattern): bool
{
if ($pattern === $domain) {
return true;
}
if (! str_contains($pattern, '*')) {
return false;
}
$quoted = preg_quote($pattern, '#');
$regex = '#^' . str_replace('\\*', '.*', $quoted) . '$#i';
return (bool) preg_match($regex, $domain);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Services\Auth;
use App\Models\SystemEmailQuota;
class RegistrationEmailQuotaService
{
public function isExceeded(): bool
{
$quota = $this->getCurrentPeriodQuota();
return $quota->sent_count >= $quota->limit_count;
}
public function incrementSentCount(): void
{
$quota = $this->getCurrentPeriodQuota();
$quota->sent_count = (int) $quota->sent_count + 1;
$quota->updated_at = now();
$quota->save();
}
private function getCurrentPeriodQuota(): SystemEmailQuota
{
$period = now()->format('Y-m');
return SystemEmailQuota::query()->firstOrCreate(
['period' => $period],
[
'sent_count' => 0,
'limit_count' => max(1, (int) config('registration.monthly_email_limit', 10000)),
'updated_at' => now(),
]
);
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Services\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class RegistrationVerificationTokenService
{
public function createForUser(int $userId): string
{
DB::table('user_verification_tokens')->where('user_id', $userId)->delete();
$rawToken = Str::random(64);
$tokenHash = $this->hashToken($rawToken);
// Support environments where the migration hasn't renamed the column yet
$column = \Illuminate\Support\Facades\Schema::hasColumn('user_verification_tokens', 'token_hash') ? 'token_hash' : 'token';
DB::table('user_verification_tokens')->insert([
'user_id' => $userId,
$column => $tokenHash,
'expires_at' => now()->addHours($this->ttlHours()),
'created_at' => now(),
'updated_at' => now(),
]);
return $rawToken;
}
public function findValidRecord(string $rawToken): ?object
{
$tokenHash = $this->hashToken($rawToken);
$column = \Illuminate\Support\Facades\Schema::hasColumn('user_verification_tokens', 'token_hash') ? 'token_hash' : 'token';
$record = DB::table('user_verification_tokens')
->where($column, $tokenHash)
->first();
if (! $record) {
return null;
}
if (! hash_equals((string) ($record->{$column} ?? ''), $tokenHash)) {
return null;
}
if (now()->greaterThan($record->expires_at)) {
DB::table('user_verification_tokens')->where('id', $record->id)->delete();
return null;
}
return $record;
}
private function ttlHours(): int
{
return max(1, (int) config('registration.verify_token_ttl_hours', 24));
}
private function hashToken(string $rawToken): string
{
return hash('sha256', $rawToken);
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Services\Security;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class TurnstileVerifier
{
public function isEnabled(): bool
{
return (bool) config('registration.enable_turnstile', true)
&& (string) config('services.turnstile.site_key', '') !== ''
&& (string) config('services.turnstile.secret_key', '') !== '';
}
public function verify(string $token, ?string $ip = null): bool
{
if (! $this->isEnabled()) {
return true;
}
if (trim($token) === '') {
return false;
}
try {
$response = Http::asForm()
->timeout((int) config('services.turnstile.timeout', 5))
->post((string) config('services.turnstile.verify_url', 'https://challenges.cloudflare.com/turnstile/v0/siteverify'), [
'secret' => (string) config('services.turnstile.secret_key', ''),
'response' => $token,
'remoteip' => $ip,
]);
if ($response->failed()) {
return false;
}
$payload = $response->json();
return (bool) data_get($payload, 'success', false);
} catch (\Throwable $exception) {
Log::warning('turnstile verification request failed', [
'message' => $exception->getMessage(),
]);
return false;
}
}
}