feat(auth): add token-bound step-up elevations for second-factor management

Second-factor management has been cookie-only since v1.23. The gate is right:
a Bearer token is a credential whose provenance the server cannot see, and
tearing down a second factor must not be reachable from the weaker of an
interactive login and a value pasted into a script. What was missing was never
Bearer access to those routes — it was a way to say, over a transport with no
session row, that the human holding this device just re-proved a factor.

An elevation is that proof. It is minted only against a re-proved account
password or primary passkey, bound to the exact token that re-proved, single-use
via a conditional UPDATE, five-minute-lived to match the cookie path's step-up
window, and stored hashed. A stolen token mints nothing; a second token cannot
redeem another's elevation; a password change drops every one the account holds.

requireMfaManagementAuth is the one gate the management routes share. On a
cookie session it delegates to the original helpers unchanged, so the web flow
runs the code it always did. requireAdmin stays cookie-only and out of reach.
This commit is contained in:
Marc-André Bombeck committed 2026-07-19 12:42:00 +02:00
1 parent 571e415eaa
commit e557d9e9e6
19 files changed
+808 -51

No files matched your search

+7 -5
View File
@@ -2,8 +2,9 @@
* POST /api/auth/me/mfa/disable
*
* Tear down the second factor. Double-gated:
* 1. `requireFreshMfa` — a cookie session that completed a second factor
* within the step-up window (Bearer can never satisfy this).
* 1. `requireMfaManagementAuth({ freshFactor: true })` — a cookie session that
* completed a second factor within the step-up window, OR a Bearer token
* presenting a single-use elevation it minted by re-proving a factor.
* 2. A current TOTP or recovery code in the body — proves live possession at
* the moment of the destructive action, not just a stale fresh-session.
*
@@ -12,9 +13,8 @@
*/
import {
apiHandler,
requireFreshMfa,
requireMfaManagementAuth,
HttpError,
MFA_STEP_UP_MAX_AGE_SECONDS,
} from "@/lib/api-handler";
import {
apiError,
@@ -38,7 +38,9 @@ const DISABLE_WINDOW_MS = 15 * 60 * 1000;
export const POST = apiHandler(async (req: Request) => {
// Step-up gate first — throws StepUpRequiredError (401 + errorCode) if the
// session is not freshly second-factor-verified.
const { user, session } = await requireFreshMfa(MFA_STEP_UP_MAX_AGE_SECONDS);
const { user, session } = await requireMfaManagementAuth({
freshFactor: true,
});
const rl = await checkRateLimit(
`mfa:disable:${user.id}`,
@@ -2,15 +2,15 @@
* POST /api/auth/me/mfa/recovery-codes/regenerate
*
* Issue a fresh recovery-code batch, invalidating the entire prior set in one
* transaction. Step-up gated (`requireFreshMfa`) — a recovery-code rotation is
* a sensitive action; Bearer can never satisfy the gate. The new codes are
* returned **once**.
* transaction. Step-up gated (`requireMfaManagementAuth({ freshFactor: true })`)
* — a recovery-code rotation is sensitive, so it takes either a freshly
* second-factor-verified cookie session or a single-use step-up elevation minted
* by the calling token. The new codes are returned **once**.
*/
import {
apiHandler,
requireFreshMfa,
requireMfaManagementAuth,
HttpError,
MFA_STEP_UP_MAX_AGE_SECONDS,
} from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
@@ -24,7 +24,7 @@ const REGEN_RATE_LIMIT = 5;
const REGEN_WINDOW_MS = 15 * 60 * 1000;
export const POST = apiHandler(async (req: Request) => {
const { user } = await requireFreshMfa(MFA_STEP_UP_MAX_AGE_SECONDS);
const { user } = await requireMfaManagementAuth({ freshFactor: true });
// Defence in depth — regeneration only makes sense for an active factor.
if (!user.totpConfirmedAt) {
+4 -3
View File
@@ -3,11 +3,12 @@
*
* Second-factor status for the security settings hub: whether TOTP is active,
* how many recovery codes remain, and the registered WebAuthn security keys.
* Cookie-only (`requireCookieAuth`) — managing MFA is never a Bearer surface.
* Gated by `requireMfaManagementAuth`: a cookie session, or a Bearer token
* presenting a single-use step-up elevation. A token alone is not enough.
*
* Returns only metadata: no secret, no recovery-code plaintext, no public key.
*/
import { apiHandler, requireCookieAuth } from "@/lib/api-handler";
import { apiHandler, requireMfaManagementAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { prisma } from "@/lib/db";
@@ -16,7 +17,7 @@ import { countRemainingRecoveryCodes } from "@/lib/auth/mfa/recovery-codes";
export const dynamic = "force-dynamic";
export const GET = apiHandler(async () => {
const { user } = await requireCookieAuth();
const { user } = await requireMfaManagementAuth();
const [recoveryCodesRemaining, webauthn] = await Promise.all([
countRemainingRecoveryCodes(user.id),
+14 -6
View File
@@ -6,13 +6,21 @@
* the accepted time-step (replay guard), generates + persists the Argon2id-
* hashed recovery codes, and returns the codes **once** for the user to save.
*
* The completing session is also stamped `mfaVerifiedAt = now()` so the user
* can immediately manage the freshly-enabled factor (disable / regenerate
* codes) without an extra step-up round-trip.
* On the cookie path the completing session is stamped `mfaVerifiedAt = now()`
* so the user can immediately manage the freshly-enabled factor (disable /
* regenerate codes) without an extra step-up round-trip. A Bearer caller has no
* session row to stamp — the stamping `updateMany` simply matches nothing — and
* mints a fresh elevation per action instead.
*
* Cookie-only (`requireCookieAuth`): an API token can never enrol MFA.
* Gated by `requireMfaManagementAuth`: a cookie session, or a Bearer token
* presenting a single-use step-up elevation. A token on its own can still never
* enrol MFA.
*/
import { apiHandler, requireCookieAuth, HttpError } from "@/lib/api-handler";
import {
apiHandler,
requireMfaManagementAuth,
HttpError,
} from "@/lib/api-handler";
import {
apiError,
apiSuccess,
@@ -38,7 +46,7 @@ const CONFIRM_RATE_LIMIT = 10;
const CONFIRM_WINDOW_MS = 15 * 60 * 1000;
export const POST = apiHandler(async (req: Request) => {
const { user, session } = await requireCookieAuth();
const { user, session } = await requireMfaManagementAuth();
const rl = await checkRateLimit(
`mfa:confirm:${user.id}`,
+11 -5
View File
@@ -8,11 +8,17 @@
* not active until `/confirm` verifies a code, so `totpConfirmedAt` stays
* null here.
*
* Cookie-only (`requireCookieAuth`): an API token can never enrol MFA. The
* recovery-code batch is issued at `/confirm` (after the factor is proven),
* not here, so an abandoned setup never persists codes.
* Gated by `requireMfaManagementAuth`: a cookie session, or a Bearer token
* presenting a single-use step-up elevation minted against a re-proved factor.
* A token on its own can still never enrol MFA. The recovery-code batch is
* issued at `/confirm` (after the factor is proven), not here, so an abandoned
* setup never persists codes.
*/
import { apiHandler, requireCookieAuth, HttpError } from "@/lib/api-handler";
import {
apiHandler,
requireMfaManagementAuth,
HttpError,
} from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
@@ -27,7 +33,7 @@ const SETUP_RATE_LIMIT = 5;
const SETUP_WINDOW_MS = 15 * 60 * 1000;
export const POST = apiHandler(async (req: Request) => {
const { user } = await requireCookieAuth();
const { user } = await requireMfaManagementAuth();
const rl = await checkRateLimit(
`mfa:setup:${user.id}`,
+8 -11
View File
@@ -2,17 +2,14 @@
* PATCH /api/auth/me/mfa/webauthn/[id] — rename a registered security key.
* DELETE /api/auth/me/mfa/webauthn/[id] — remove one (step-up gated).
*
* Rename is cookie-authenticated (non-destructive). Removal is a sensitive
* action: it is gated on a fresh second-factor step-up (`requireFreshMfa`,
* cookie-only — a Bearer token can never satisfy it).
* Both go through `requireMfaManagementAuth`: a cookie session, or a Bearer
* token presenting a single-use step-up elevation. Removal additionally demands
* the fresh-factor arm (`freshFactor: true`) — on the cookie path a session that
* completed a second factor inside the step-up window, on the Bearer path an
* elevation minted against a re-proved factor.
*/
import { NextRequest } from "next/server";
import {
apiHandler,
requireCookieAuth,
requireFreshMfa,
MFA_STEP_UP_MAX_AGE_SECONDS,
} from "@/lib/api-handler";
import { apiHandler, requireMfaManagementAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
@@ -31,7 +28,7 @@ export const PATCH = apiHandler(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const { user } = await requireCookieAuth();
const { user } = await requireMfaManagementAuth();
const { id } = await params;
const { data: body, error: jsonError } = await safeJson(request, {
@@ -70,7 +67,7 @@ export const DELETE = apiHandler(
) => {
// Step-up gate first — throws StepUpRequiredError (401 + errorCode) if the
// session is not freshly second-factor-verified.
const { user } = await requireFreshMfa(MFA_STEP_UP_MAX_AGE_SECONDS);
const { user } = await requireMfaManagementAuth({ freshFactor: true });
const { id } = await params;
const existing = await prisma.webauthnMfaCredential.findUnique({
@@ -1,11 +1,12 @@
/**
* POST /api/auth/me/mfa/webauthn/register/options
*
* Begin registering a WebAuthn security key as a second factor. Cookie-only —
* an API token can never enrol MFA. Returns the SimpleWebAuthn creation
* options + the server-issued challenge id to present back at /register/verify.
* Begin registering a WebAuthn security key as a second factor. Takes a cookie
* session or a Bearer token presenting a single-use step-up elevation; a token
* on its own can never enrol MFA. Returns the SimpleWebAuthn creation options +
* the server-issued challenge id to present back at /register/verify.
*/
import { apiHandler, requireCookieAuth } from "@/lib/api-handler";
import { apiHandler, requireMfaManagementAuth } from "@/lib/api-handler";
import { apiError, apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
@@ -14,7 +15,7 @@ import { createMfaRegistrationOptions } from "@/lib/auth/mfa/webauthn";
export const dynamic = "force-dynamic";
export const POST = apiHandler(async () => {
const { user } = await requireCookieAuth();
const { user } = await requireMfaManagementAuth();
const rl = await checkRateLimit(
`mfa:webauthn:register:${user.id}`,
@@ -1,12 +1,13 @@
/**
* POST /api/auth/me/mfa/webauthn/register/verify
*
* Finish registering a WebAuthn security key as a second factor. Cookie-only.
* Verifies the attestation against the user-bound challenge and stores the
* credential in `WebauthnMfaCredential` (kept separate from primary passkeys).
* Finish registering a WebAuthn security key as a second factor. Takes a cookie
* session or a Bearer token presenting a single-use step-up elevation. Verifies
* the attestation against the user-bound challenge and stores the credential in
* `WebauthnMfaCredential` (kept separate from primary passkeys).
*/
import { NextRequest } from "next/server";
import { apiHandler, requireCookieAuth } from "@/lib/api-handler";
import { apiHandler, requireMfaManagementAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
@@ -23,7 +24,7 @@ import { setMfaEnrollCookie } from "@/lib/auth/mfa-enrollment";
export const dynamic = "force-dynamic";
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireCookieAuth();
const { user } = await requireMfaManagementAuth();
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 64 * 1024,