Files
top-tickets/src/app/api/auth/verify-totp/route.ts
T
ogrechkoandClaude Sonnet 5 4ecb0e7698 Add opt-in TOTP 2FA for local accounts
New card in Настройки → Аккаунт: scan a QR code (otplib + qrcode), confirm
with a live code, get 8 one-time recovery codes shown once. Only offered
for authSource="local" — LDAP accounts already have their own MFA story at
the directory level and are turned away with a clear message if they somehow
hit the setup endpoint directly.

Login flow: a 2FA account's password check now creates a short-lived
"login challenge" (separate table from `sessions`, 5-minute TTL, capped at
6 verify attempts) instead of a real session, and the login page swaps to a
second screen asking for a code — TOTP or a recovery code, either works.
The LDAP branch of the login route is untouched; it returns before ever
reaching the 2FA check.

totpSecret is encrypted at rest via the existing lib/crypto/credentials.ts
helper (same one already used for mailbox/LDAP bind passwords) rather than
adding a second encryption scheme. Recovery codes are hashed, not stored
plaintext, and each is single-use (marked usedAt, not deleted).

Verified against the real deployment end-to-end with Playwright against a
throwaway test account (created via the real admin-users API, fully
deleted after): setup → confirm → recovery-code issuance → second login
correctly prompted for a code → wrong code rejected → correct code and a
recovery code both worked → a reused recovery code was correctly rejected
→ disable (password-gated) → subsequent login went straight through again.
Also added unit tests for the TOTP/recovery-code helpers.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GteWhnWKTmnXcsd5jx6H7u
2026-08-20 08:25:15 +00:00

62 lines
2.6 KiB
TypeScript

export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { eq, and, isNull } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { users, totpRecoveryCodes } from "@/lib/db/schema";
import { createSession, setSessionCookie } from "@/lib/auth/session";
import { consumeLoginChallengeAttempt, deleteLoginChallenge, clearLoginChallengeCookie } from "@/lib/auth/login-challenge";
import { decryptTotpSecret, verifyTotpCode, hashRecoveryCode } from "@/lib/auth/totp";
const schema = z.object({ code: z.string().min(6).max(16) });
// Second step of login for a 2FA account — reads the pending-login cookie
// set by /api/auth/login, so the client never has to carry the challenge
// token itself. Accepts either a live 6-digit TOTP code or a recovery code.
export async function POST(request: Request) {
const parsed = schema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
// Burns one attempt regardless of whether the code below turns out to be
// right — the whole point is capping brute-force *tries*, not just wrong ones.
const challenge = await consumeLoginChallengeAttempt();
if (!challenge) {
return NextResponse.json({ error: "Сессия входа истекла — войдите заново" }, { status: 401 });
}
const user = await db.query.users.findFirst({ where: eq(users.id, challenge.userId) });
if (!user || !user.totpEnabled || !user.totpSecret) {
await deleteLoginChallenge(challenge.tokenHash);
return NextResponse.json({ error: "2FA не настроена для этого аккаунта" }, { status: 400 });
}
const code = parsed.data.code.trim();
let verified = /^\d{6}$/.test(code) && (await verifyTotpCode(decryptTotpSecret(user.totpSecret), code));
if (!verified) {
const codeHash = hashRecoveryCode(code);
const match = await db.query.totpRecoveryCodes.findFirst({
where: and(eq(totpRecoveryCodes.userId, user.id), eq(totpRecoveryCodes.codeHash, codeHash), isNull(totpRecoveryCodes.usedAt)),
});
if (match) {
await db.update(totpRecoveryCodes).set({ usedAt: new Date() }).where(eq(totpRecoveryCodes.id, match.id));
verified = true;
}
}
if (!verified) {
return NextResponse.json({ error: "Неверный код" }, { status: 401 });
}
await deleteLoginChallenge(challenge.tokenHash);
await clearLoginChallengeCookie();
const token = await createSession(user.id);
await setSessionCookie(token);
return NextResponse.json({ ok: true, user: { id: user.id, name: user.name, role: user.role } });
}