From 5c5d1c35248bc74a5bce37379c5cf4fd5b6a8684 Mon Sep 17 00:00:00 2001 From: "Rudy B." Date: Sat, 25 Apr 2026 17:28:29 +0200 Subject: [PATCH] fix(2FA): use serializable transaction for failed attempts recording --- src/app/api/2fa/disable/route.ts | 3 +- src/app/api/2fa/setup/confirm/route.ts | 3 +- src/app/api/2fa/verify/route.ts | 6 ++-- src/lib/two-factor/rate-limit.ts | 39 ++++++++++++++++++++------ 4 files changed, 38 insertions(+), 13 deletions(-) diff --git a/src/app/api/2fa/disable/route.ts b/src/app/api/2fa/disable/route.ts index 566a0d592..667cc3ceb 100644 --- a/src/app/api/2fa/disable/route.ts +++ b/src/app/api/2fa/disable/route.ts @@ -88,10 +88,11 @@ export async function POST(request: Request) { // Verify TOTP const secret = decryptSecret(twoFactor.secret); if (!(await verifyTotp(token, secret))) { - await recordFailedAttempt(userId); + const { lockedUntil } = await recordFailedAttempt(userId); return badRequest({ code: 'two-factor-error-invalid-code', message: 'Invalid verification code', + ...(lockedUntil && { lockedUntil }), }); } diff --git a/src/app/api/2fa/setup/confirm/route.ts b/src/app/api/2fa/setup/confirm/route.ts index f693e5b59..629a15c86 100644 --- a/src/app/api/2fa/setup/confirm/route.ts +++ b/src/app/api/2fa/setup/confirm/route.ts @@ -48,10 +48,11 @@ export async function POST(request: Request) { // Verify TOTP const secret = decryptSecret(twoFactor.secret); if (!(await verifyTotp(token, secret))) { - await recordFailedAttempt(userId); + const { lockedUntil } = await recordFailedAttempt(userId); return badRequest({ code: 'two-factor-error-invalid-code', message: 'Invalid verification code', + ...(lockedUntil && { lockedUntil }), }); } diff --git a/src/app/api/2fa/verify/route.ts b/src/app/api/2fa/verify/route.ts index f7db0c8ff..636af3caa 100644 --- a/src/app/api/2fa/verify/route.ts +++ b/src/app/api/2fa/verify/route.ts @@ -73,10 +73,11 @@ export async function POST(request: Request) { const matchIndex = await verifyBackupCode(body.backupCode, hashes); if (matchIndex === null) { - await recordFailedAttempt(userId); + const { lockedUntil } = await recordFailedAttempt(userId); return badRequest({ code: 'two-factor-error-invalid-backup-code', message: 'Invalid backup code', + ...(lockedUntil && { lockedUntil }), }); } @@ -95,10 +96,11 @@ export async function POST(request: Request) { const decryptedSecret = decryptSecret(twoFactor.secret); if (!(await verifyTotp(token, decryptedSecret))) { - await recordFailedAttempt(userId); + const { lockedUntil } = await recordFailedAttempt(userId); return badRequest({ code: 'two-factor-error-invalid-code', message: 'Invalid verification code', + ...(lockedUntil && { lockedUntil }), }); } diff --git a/src/lib/two-factor/rate-limit.ts b/src/lib/two-factor/rate-limit.ts index 9671549df..ad2ad3b4c 100644 --- a/src/lib/two-factor/rate-limit.ts +++ b/src/lib/two-factor/rate-limit.ts @@ -1,7 +1,9 @@ +import { Prisma } from '@/generated/prisma/client'; import prisma from '@/lib/prisma'; const MAX_ATTEMPTS = 5; const LOCKOUT_MINUTES = 15; +const MAX_RETRIES = 3; export async function checkRateLimit( userId: string, @@ -14,16 +16,35 @@ export async function checkRateLimit( return { allowed: true }; } -export async function recordFailedAttempt(userId: string): Promise { - const record = await prisma.client.twoFactorRateLimit.upsert({ - where: { userId }, - update: { attempts: { increment: 1 }, updatedAt: new Date() }, - create: { userId, attempts: 1, updatedAt: new Date() }, - }); - if (record.attempts >= MAX_ATTEMPTS) { - const lockedUntil = new Date(Date.now() + LOCKOUT_MINUTES * 60 * 1000); - await prisma.client.twoFactorRateLimit.update({ where: { userId }, data: { lockedUntil } }); +export async function recordFailedAttempt(userId: string) { + let retries = 0; + while (retries < MAX_RETRIES) { + try { + return await prisma.transaction( + async (tx: Prisma.TransactionClient) => { + const record = await tx.twoFactorRateLimit.upsert({ + where: { userId }, + update: { attempts: { increment: 1 } }, + create: { userId, attempts: 1 }, + }); + if (record.attempts >= MAX_ATTEMPTS) { + const lockedUntil = new Date(Date.now() + LOCKOUT_MINUTES * 60 * 1000); + await tx.twoFactorRateLimit.update({ where: { userId }, data: { lockedUntil } }); + return { lockedUntil }; + } + return {}; + }, + { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, + ); + } catch (err: any) { + if (err.code === 'P2034') { + retries++; + continue; + } + throw err; + } } + throw new Error('recordFailedAttempt: max retries exceeded'); } export async function resetRateLimit(userId: string): Promise {