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
This commit is contained in:
ogrechkoandClaude Sonnet 5 committed 2026-08-20 08:25:15 +00:00
1 parent 95522fdedd
commit 4ecb0e7698
17 files changed
+2285 -55

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { eq } from "drizzle-orm";
import { requireSession } from "@/lib/auth/require";
import { db } from "@/lib/db/client";
import { users, totpRecoveryCodes } from "@/lib/db/schema";
import { decryptTotpSecret, verifyTotpCode, generateRecoveryCodes, hashRecoveryCode } from "@/lib/auth/totp";
const schema = z.object({ code: z.string().min(6).max(6) });
/** Flips totpEnabled on after the user proves they can generate a live code, and issues recovery codes — shown once, never retrievable again. */
export async function POST(request: Request) {
const { session, response } = await requireSession();
if (!session) return response;
const parsed = schema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json({ error: "Введите 6-значный код" }, { status: 400 });
}
const user = await db.query.users.findFirst({ where: eq(users.id, session.user.id) });
if (!user?.totpSecret) {
return NextResponse.json({ error: "Сначала начните настройку 2FA" }, { status: 400 });
}
const ok = await verifyTotpCode(decryptTotpSecret(user.totpSecret), parsed.data.code);
if (!ok) {
return NextResponse.json({ error: "Неверный код" }, { status: 401 });
}
await db.update(users).set({ totpEnabled: true }).where(eq(users.id, user.id));
// Replace any codes from a previous enable/disable cycle.
await db.delete(totpRecoveryCodes).where(eq(totpRecoveryCodes.userId, user.id));
const recoveryCodes = generateRecoveryCodes();
await db.insert(totpRecoveryCodes).values(recoveryCodes.map((code) => ({ userId: user.id, codeHash: hashRecoveryCode(code) })));
return NextResponse.json({ ok: true, recoveryCodes });
}
+37
View File
@@ -0,0 +1,37 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { eq } from "drizzle-orm";
import { requireSession } from "@/lib/auth/require";
import { verifyPassword } from "@/lib/auth/password";
import { db } from "@/lib/db/client";
import { users, totpRecoveryCodes } from "@/lib/db/schema";
const schema = z.object({ password: z.string().min(1) });
/** Requires the current password (not a TOTP code) — matches change-password's confirmation pattern, and means a stolen live session alone still can't turn off 2FA. */
export async function POST(request: Request) {
const { session, response } = await requireSession();
if (!session) return response;
const parsed = schema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
const user = await db.query.users.findFirst({ where: eq(users.id, session.user.id) });
if (!user?.passwordHash) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
const ok = await verifyPassword(user.passwordHash, parsed.data.password);
if (!ok) {
return NextResponse.json({ error: "Неверный пароль" }, { status: 401 });
}
await db.update(users).set({ totpSecret: null, totpEnabled: false }).where(eq(users.id, user.id));
await db.delete(totpRecoveryCodes).where(eq(totpRecoveryCodes.userId, user.id));
return NextResponse.json({ ok: true });
}
+35
View File
@@ -0,0 +1,35 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { eq } from "drizzle-orm";
import { requireSession } from "@/lib/auth/require";
import { db } from "@/lib/db/client";
import { users } from "@/lib/db/schema";
import { generateTotpSecret, encryptTotpSecret, buildTotpQrCode } from "@/lib/auth/totp";
/**
* Starts (or restarts) 2FA setup — generates a fresh secret and stores it
* encrypted, but leaves totpEnabled false until /confirm proves the user
* actually scanned it (see users.totpEnabled comment in schema.ts). Safe to
* call again if the user abandons setup partway — it just overwrites the
* unconfirmed secret with a new one.
*/
export async function POST() {
const { session, response } = await requireSession();
if (!session) return response;
const user = await db.query.users.findFirst({ where: eq(users.id, session.user.id) });
if (!user) return NextResponse.json({ error: "User not found" }, { status: 404 });
if (user.authSource !== "local") {
return NextResponse.json(
{ error: "2FA доступна только для локальных аккаунтов — вход через LDAP защищён на уровне домена" },
{ status: 400 },
);
}
const secret = generateTotpSecret();
await db.update(users).set({ totpSecret: encryptTotpSecret(secret), totpEnabled: false }).where(eq(users.id, user.id));
const qrDataUrl = await buildTotpQrCode(secret, user.email);
return NextResponse.json({ secret, qrDataUrl });
}