feat(auth): branch login through a second-factor challenge

When a password is accepted for an account with a confirmed TOTP factor, the
login route no longer mints a session or token. It creates a single-use,
~5-minute MfaChallenge (the opaque ticket is stored only as a hash) and
returns HTTP 200 with data:null, error:null and meta.mfaRequired + mfaTicket +
methods. The client completes the login at POST /api/auth/mfa/verify with the
ticket + a TOTP or recovery code, receiving the exact same token bundle the
password path issues, with the session stamped second-factor-verified.

- The ticket is claimed once, atomically, only after the factor verifies, so
  two concurrent submissions can mint at most one session; no session ever
  exists before factor two.
- Wrong codes increment the ticket attempt counter and burn it at the cap
  (throttle, not an account lock); the anonymous verify surface is also
  rate-limited per IP.
- meta.mfaRequired is returned only after a valid password and the
  invalid-credentials response is identical regardless of MFA state, so an
  attacker without the password cannot enumerate MFA.
- The session/token tail is extracted to login-response.ts and shared by both
  the password path and the verify path, keeping the transport contract
  identical. OpenAPI registers the verify endpoint, the MFA management
  endpoints, and the mfaRequired login variant.
This commit is contained in:
Marc-André Bombeck committed 2026-06-27 19:56:30 +02:00
1 parent b446a66753
commit 6b3d3fd840
10 files changed
+1508 -91

No files matched your search

@@ -0,0 +1,131 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: { user: { findFirst: vi.fn() } },
}));
vi.mock("@/lib/auth/password", () => ({
verifyPassword: vi.fn().mockResolvedValue(true),
}));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/auth/hmac", () => ({ hashToken: vi.fn(() => "h") }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/rate-limit", () => ({
checkAuthSurfaceRateLimit: vi.fn().mockResolvedValue({
allowed: true,
remaining: 4,
resetAt: Date.now() + 1e6,
ip: "203.0.113.7",
}),
rateLimitHeaders: vi.fn(() => ({})),
}));
vi.mock("@/lib/auth/login-response", () => ({
finishLogin: vi.fn().mockResolvedValue(
new Response(
JSON.stringify({ data: { user: { id: "user-1" } }, error: null }),
{
status: 200,
headers: { "content-type": "application/json" },
},
),
),
}));
vi.mock("@/lib/auth/mfa/challenge", () => ({
createMfaChallenge: vi.fn().mockResolvedValue({
ticket: "opaque-ticket-value",
expiresAt: new Date(Date.now() + 5 * 60_000),
}),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { POST } from "@/app/api/auth/login/route";
import { prisma } from "@/lib/db";
import { finishLogin } from "@/lib/auth/login-response";
import { createMfaChallenge } from "@/lib/auth/mfa/challenge";
function loginRequest() {
return new Request("http://localhost/api/auth/login", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
email: "user@example.com",
password: "correct-horse-battery",
}),
}) as unknown as Parameters<typeof POST>[0];
}
const BASE_USER = {
id: "user-1",
username: "u",
email: "user@example.com",
passwordHash: "argon2-hash",
onboardingCompletedAt: new Date(),
};
beforeEach(() => {
vi.clearAllMocks();
});
describe("login MFA branch", () => {
it("MFA user → returns mfaRequired + ticket and issues NO session", async () => {
vi.mocked(prisma.user.findFirst).mockResolvedValue({
...BASE_USER,
totpConfirmedAt: new Date(),
} as never);
const res = await POST(loginRequest());
expect(res.status).toBe(200);
const body = await res.json();
expect(body.data).toBeNull();
expect(body.error).toBeNull();
expect(body.meta.mfaRequired).toBe(true);
expect(body.meta.mfaTicket).toBe("opaque-ticket-value");
expect(body.meta.methods).toEqual(["totp", "recovery"]);
expect(createMfaChallenge).toHaveBeenCalledWith("user-1", "login");
// The session/token tail is never reached.
expect(finishLogin).not.toHaveBeenCalled();
});
it("non-MFA user → issues the session via finishLogin, no challenge", async () => {
vi.mocked(prisma.user.findFirst).mockResolvedValue({
...BASE_USER,
totpConfirmedAt: null,
} as never);
const res = await POST(loginRequest());
expect(res.status).toBe(200);
expect(finishLogin).toHaveBeenCalledTimes(1);
expect(createMfaChallenge).not.toHaveBeenCalled();
const arg = vi.mocked(finishLogin).mock.calls[0][0];
expect(arg.source).toBe("login.password");
expect(arg.mfaVerified).toBeUndefined();
});
it("wrong password never reaches the MFA branch", async () => {
const { verifyPassword } = await import("@/lib/auth/password");
vi.mocked(verifyPassword).mockResolvedValueOnce(false);
vi.mocked(prisma.user.findFirst).mockResolvedValue({
...BASE_USER,
totpConfirmedAt: new Date(),
} as never);
const res = await POST(loginRequest());
expect(res.status).toBe(401);
expect(createMfaChallenge).not.toHaveBeenCalled();
expect(finishLogin).not.toHaveBeenCalled();
});
});
+156
View File
@@ -0,0 +1,156 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: { user: { findUnique: vi.fn() } },
}));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/rate-limit", () => ({
checkAuthSurfaceRateLimit: vi.fn().mockResolvedValue({
allowed: true,
remaining: 9,
resetAt: Date.now() + 1e6,
ip: "203.0.113.9",
}),
rateLimitHeaders: vi.fn(() => ({})),
}));
vi.mock("@/lib/auth/login-response", () => ({
finishLogin: vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({ data: { user: { id: "user-1" } }, error: null }),
{ status: 200, headers: { "content-type": "application/json" } },
),
),
}));
vi.mock("@/lib/auth/mfa/challenge", () => ({
loadActiveChallenge: vi.fn(),
recordChallengeFailure: vi
.fn()
.mockResolvedValue({ exhausted: false, attempts: 1 }),
claimChallenge: vi.fn(),
}));
vi.mock("@/lib/auth/mfa/verify-factor", () => ({
verifyMfaFactor: vi.fn(),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { POST } from "@/app/api/auth/mfa/verify/route";
import { prisma } from "@/lib/db";
import { finishLogin } from "@/lib/auth/login-response";
import {
loadActiveChallenge,
recordChallengeFailure,
claimChallenge,
} from "@/lib/auth/mfa/challenge";
import { verifyMfaFactor } from "@/lib/auth/mfa/verify-factor";
function verifyRequest(body: unknown) {
return new Request("http://localhost/api/auth/mfa/verify", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
const GOOD_BODY = { mfaTicket: "tkt", method: "totp", code: "123456" };
const ACTIVE_CHALLENGE = {
id: "ch-1",
userId: "user-1",
kind: "login",
attempts: 0,
expiresAt: new Date(Date.now() + 60_000),
};
const MFA_USER = {
id: "user-1",
username: "u",
email: "user@example.com",
onboardingCompletedAt: new Date(),
totpConfirmedAt: new Date(),
totpSecretEncrypted: "v2.cipher",
totpLastStep: null,
};
beforeEach(() => {
vi.clearAllMocks();
});
describe("POST /api/auth/mfa/verify", () => {
it("happy path: valid factor → claims ticket and issues the bundle", async () => {
vi.mocked(loadActiveChallenge).mockResolvedValue(ACTIVE_CHALLENGE as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue(MFA_USER as never);
vi.mocked(verifyMfaFactor).mockResolvedValue({ ok: true, replay: false });
vi.mocked(claimChallenge).mockResolvedValue(true);
const res = await POST(verifyRequest(GOOD_BODY));
expect(res.status).toBe(200);
expect(claimChallenge).toHaveBeenCalledWith("ch-1");
expect(finishLogin).toHaveBeenCalledTimes(1);
const arg = vi.mocked(finishLogin).mock.calls[0][0];
expect(arg.mfaVerified).toBe(true);
expect(arg.source).toBe("mfa.verify");
});
it("invalid ticket → 401, no session", async () => {
vi.mocked(loadActiveChallenge).mockResolvedValue(null);
const res = await POST(verifyRequest(GOOD_BODY));
expect(res.status).toBe(401);
expect(finishLogin).not.toHaveBeenCalled();
});
it("wrong code → records failure, 401, no session", async () => {
vi.mocked(loadActiveChallenge).mockResolvedValue(ACTIVE_CHALLENGE as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue(MFA_USER as never);
vi.mocked(verifyMfaFactor).mockResolvedValue({ ok: false, replay: false });
const res = await POST(verifyRequest(GOOD_BODY));
expect(res.status).toBe(401);
expect(recordChallengeFailure).toHaveBeenCalledWith("ch-1");
expect(claimChallenge).not.toHaveBeenCalled();
expect(finishLogin).not.toHaveBeenCalled();
});
it("factor valid but claim lost (race) → 401, no session", async () => {
vi.mocked(loadActiveChallenge).mockResolvedValue(ACTIVE_CHALLENGE as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue(MFA_USER as never);
vi.mocked(verifyMfaFactor).mockResolvedValue({ ok: true, replay: false });
vi.mocked(claimChallenge).mockResolvedValue(false);
const res = await POST(verifyRequest(GOOD_BODY));
expect(res.status).toBe(401);
expect(finishLogin).not.toHaveBeenCalled();
});
it("factor disabled between password and verify → failure, 401", async () => {
vi.mocked(loadActiveChallenge).mockResolvedValue(ACTIVE_CHALLENGE as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
...MFA_USER,
totpConfirmedAt: null,
} as never);
const res = await POST(verifyRequest(GOOD_BODY));
expect(res.status).toBe(401);
expect(recordChallengeFailure).toHaveBeenCalledWith("ch-1");
expect(verifyMfaFactor).not.toHaveBeenCalled();
expect(finishLogin).not.toHaveBeenCalled();
});
it("malformed body → 422", async () => {
const res = await POST(verifyRequest({ mfaTicket: "", code: "x" }));
expect(res.status).toBe(422);
});
});