mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
fix(auth): make the re-proved factor decide what an elevation reaches
A step-up elevation minted from the account password satisfied the fresh-factor routes. That is a second-factor bypass: a stolen token plus a known password could rotate the recovery codes — which take no factor in the body — and then spend one of them to disable the second factor outright. The web has never allowed that chain, because a password login does not stamp mfaVerifiedAt. The method is now an authorisation input. Only totp, webauthn, and passkey satisfy a fresh-factor gate, which is exactly the set of ceremonies the web stamps a session for; password reaches what a plain cookie session reaches and stops. The mint gains TOTP and security-key arms so a TOTP-only account can still manage its factor natively, and the response says which reach it bought. The gate also returns a discriminated context. session.id meant a session row on one arm and a token row on the other, and the disable route passed the token id to a session-scoped query — excluding nothing, so it deleted every browser session and revoked the caller's own device login. The transport is now in the type and the compiler refuses the confusion. Redemption splits into validate-then-commit so a 429, a 422, or a wrong code no longer burns a proof against a five-per-fifteen-minute mint ceiling. The claim is UPDATE ... RETURNING, so the statement that decides is the one that reports. The mint is transactional behind a partial unique index. Sign-out-everywhere and both password-reset paths clear elevations. The status read drops to plain requireAuth — it carries no credential material — and every mutation stays gated.
This commit is contained in:
1 parent
ba45a25cb0
commit
0991d754e4
24 files changed
+1496
-305
No files matched your search
@@ -38,9 +38,8 @@ 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 requireMfaManagementAuth({
|
||||
freshFactor: true,
|
||||
});
|
||||
const auth = await requireMfaManagementAuth({ freshFactor: true });
|
||||
const { user } = auth;
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`mfa:disable:${user.id}`,
|
||||
@@ -85,6 +84,11 @@ export const POST = apiHandler(async (req: Request) => {
|
||||
throw new HttpError(401, "Invalid code");
|
||||
}
|
||||
|
||||
// Every cheap check has passed and the teardown is next, so spend the
|
||||
// elevation now. Placing it here rather than at the gate means a wrong code or
|
||||
// a 429 above costs the caller nothing.
|
||||
await auth.commitElevation();
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: user.id },
|
||||
@@ -102,7 +106,12 @@ export const POST = apiHandler(async (req: Request) => {
|
||||
// every "remember this device" trusted device (all handled by
|
||||
// destroyOtherSessions), keeping only the caller's current session. A stale
|
||||
// session or a trusted-device cookie must not survive the factor's removal.
|
||||
await destroyOtherSessions(user.id, session.id);
|
||||
await destroyOtherSessions(
|
||||
user.id,
|
||||
auth.transport === "cookie"
|
||||
? { kind: "session", sessionId: auth.session.id }
|
||||
: { kind: "accessToken", accessTokenHash: auth.accessTokenHash },
|
||||
);
|
||||
|
||||
await auditLog("auth.mfa.disabled", {
|
||||
userId: user.id,
|
||||
|
||||
@@ -24,7 +24,8 @@ const REGEN_RATE_LIMIT = 5;
|
||||
const REGEN_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
export const POST = apiHandler(async (req: Request) => {
|
||||
const { user } = await requireMfaManagementAuth({ freshFactor: true });
|
||||
const auth = await requireMfaManagementAuth({ freshFactor: true });
|
||||
const { user } = auth;
|
||||
|
||||
// Defence in depth — regeneration only makes sense for an active factor.
|
||||
if (!user.totpConfirmedAt) {
|
||||
@@ -44,6 +45,8 @@ export const POST = apiHandler(async (req: Request) => {
|
||||
return res;
|
||||
}
|
||||
|
||||
await auth.commitElevation();
|
||||
|
||||
const recoveryCodes = await regenerateRecoveryCodes(user.id);
|
||||
|
||||
await auditLog("auth.mfa.recovery_regenerated", {
|
||||
|
||||
@@ -3,12 +3,21 @@
|
||||
*
|
||||
* Second-factor status for the security settings hub: whether TOTP is active,
|
||||
* how many recovery codes remain, and the registered WebAuthn security keys.
|
||||
* Gated by `requireMfaManagementAuth`: a cookie session, or a Bearer token
|
||||
* presenting a single-use step-up elevation. A token alone is not enough.
|
||||
* Plain `requireAuth()` — a cookie session or a cookie-equivalent token. This
|
||||
* read is NOT elevation-gated, and deliberately so: it returns metadata only
|
||||
* (whether TOTP is on, how many recovery codes remain, and each key's name and
|
||||
* dates) and no credential material at all — no secret, no code, no public key,
|
||||
* no credential id. The web shows the same screen to any authenticated session,
|
||||
* and `/api/auth/me` already exposes `totpConfirmedAt` over Bearer, so gating it
|
||||
* would only force a factor re-proof to render a screen and buy nothing.
|
||||
*
|
||||
* Every MUTATION on this surface stays behind `requireMfaManagementAuth`. The
|
||||
* argument-less `requireAuth()` keeps the fail-closed scope default, so a
|
||||
* narrow-scope token gains no reach here.
|
||||
*
|
||||
* Returns only metadata: no secret, no recovery-code plaintext, no public key.
|
||||
*/
|
||||
import { apiHandler, requireMfaManagementAuth } from "@/lib/api-handler";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { prisma } from "@/lib/db";
|
||||
@@ -17,7 +26,7 @@ import { countRemainingRecoveryCodes } from "@/lib/auth/mfa/recovery-codes";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireMfaManagementAuth();
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const [recoveryCodesRemaining, webauthn] = await Promise.all([
|
||||
countRemainingRecoveryCodes(user.id),
|
||||
|
||||
@@ -46,7 +46,8 @@ const CONFIRM_RATE_LIMIT = 10;
|
||||
const CONFIRM_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
export const POST = apiHandler(async (req: Request) => {
|
||||
const { user, session } = await requireMfaManagementAuth();
|
||||
const auth = await requireMfaManagementAuth();
|
||||
const { user } = auth;
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`mfa:confirm:${user.id}`,
|
||||
@@ -103,6 +104,10 @@ export const POST = apiHandler(async (req: Request) => {
|
||||
|
||||
const recoveryCodes = generateRecoveryCodes();
|
||||
|
||||
// The code verified and the activation is next — spend the elevation here so
|
||||
// a wrong code above costs the caller nothing.
|
||||
await auth.commitElevation();
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: user.id },
|
||||
@@ -115,11 +120,14 @@ export const POST = apiHandler(async (req: Request) => {
|
||||
await tx.mfaRecoveryCode.deleteMany({ where: { userId: user.id } });
|
||||
await persistRecoveryCodes(tx, user.id, recoveryCodes);
|
||||
// Stamp the completing session so the user can immediately manage the
|
||||
// factor under step-up without re-verifying.
|
||||
await tx.session.updateMany({
|
||||
where: { id: session.id },
|
||||
data: { mfaVerifiedAt: new Date() },
|
||||
});
|
||||
// factor under step-up without re-verifying. Cookie transport only — a
|
||||
// Bearer caller has no session row, and mints a fresh elevation per action.
|
||||
if (auth.transport === "cookie") {
|
||||
await tx.session.updateMany({
|
||||
where: { id: auth.session.id },
|
||||
data: { mfaVerifiedAt: new Date() },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// v1.23 — the account now has an active second factor, so any
|
||||
|
||||
@@ -33,7 +33,8 @@ const SETUP_RATE_LIMIT = 5;
|
||||
const SETUP_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
export const POST = apiHandler(async (req: Request) => {
|
||||
const { user } = await requireMfaManagementAuth();
|
||||
const auth = await requireMfaManagementAuth();
|
||||
const { user } = auth;
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`mfa:setup:${user.id}`,
|
||||
@@ -56,6 +57,9 @@ export const POST = apiHandler(async (req: Request) => {
|
||||
throw new HttpError(409, "A second factor is already active");
|
||||
}
|
||||
|
||||
// Rate limit and the already-active check have passed; the write is next.
|
||||
await auth.commitElevation();
|
||||
|
||||
const secret = generateTotpSecret();
|
||||
const account = user.email ?? user.username;
|
||||
const otpauthUri = buildOtpauthUri(secret, account);
|
||||
|
||||
@@ -28,7 +28,8 @@ export const PATCH = apiHandler(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const { user } = await requireMfaManagementAuth();
|
||||
const auth = await requireMfaManagementAuth();
|
||||
const { user } = auth;
|
||||
const { id } = await params;
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request, {
|
||||
@@ -49,6 +50,8 @@ export const PATCH = apiHandler(
|
||||
return apiError("Security key not found", 404);
|
||||
}
|
||||
|
||||
await auth.commitElevation();
|
||||
|
||||
const updated = await prisma.webauthnMfaCredential.update({
|
||||
where: { id },
|
||||
data: { name: parsed.data.name },
|
||||
@@ -67,7 +70,8 @@ export const DELETE = apiHandler(
|
||||
) => {
|
||||
// Step-up gate first — throws StepUpRequiredError (401 + errorCode) if the
|
||||
// session is not freshly second-factor-verified.
|
||||
const { user } = await requireMfaManagementAuth({ freshFactor: true });
|
||||
const auth = await requireMfaManagementAuth({ freshFactor: true });
|
||||
const { user } = auth;
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await prisma.webauthnMfaCredential.findUnique({
|
||||
@@ -78,6 +82,10 @@ export const DELETE = apiHandler(
|
||||
return apiError("Security key not found", 404);
|
||||
}
|
||||
|
||||
// Ownership resolved and the row is about to go — spend the elevation now,
|
||||
// so a 404 for someone else's key id does not burn it.
|
||||
await auth.commitElevation();
|
||||
|
||||
await prisma.webauthnMfaCredential.delete({ where: { id } });
|
||||
|
||||
await auditLog("auth.mfa.webauthn.remove", {
|
||||
|
||||
@@ -15,7 +15,8 @@ import { createMfaRegistrationOptions } from "@/lib/auth/mfa/webauthn";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireMfaManagementAuth();
|
||||
const auth = await requireMfaManagementAuth();
|
||||
const { user } = auth;
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`mfa:webauthn:register:${user.id}`,
|
||||
@@ -30,6 +31,8 @@ export const POST = apiHandler(async () => {
|
||||
return res;
|
||||
}
|
||||
|
||||
await auth.commitElevation();
|
||||
|
||||
const { options, challengeId } = await createMfaRegistrationOptions(
|
||||
user.id,
|
||||
user.email ?? user.username,
|
||||
|
||||
@@ -24,7 +24,8 @@ import { setMfaEnrollCookie } from "@/lib/auth/mfa-enrollment";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireMfaManagementAuth();
|
||||
const auth = await requireMfaManagementAuth();
|
||||
const { user } = auth;
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request, {
|
||||
maxBytes: 64 * 1024,
|
||||
@@ -46,6 +47,10 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
return apiError("Security key verification failed", 400);
|
||||
}
|
||||
|
||||
// The attestation verified and the credential is about to be stored — a
|
||||
// failed ceremony above must not have cost the caller their elevation.
|
||||
await auth.commitElevation();
|
||||
|
||||
const { registrationInfo } = verification;
|
||||
const created = await prisma.webauthnMfaCredential.create({
|
||||
data: {
|
||||
|
||||
@@ -88,7 +88,10 @@ export const GET = apiHandler(async () => {
|
||||
export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
const { user, session } = await requireAuth();
|
||||
|
||||
const { sessionsRevoked } = await destroyOtherSessions(user.id, session.id);
|
||||
const { sessionsRevoked } = await destroyOtherSessions(user.id, {
|
||||
kind: "session",
|
||||
sessionId: session.id,
|
||||
});
|
||||
|
||||
await auditLog("auth.session.revoke_others", {
|
||||
userId: user.id,
|
||||
|
||||
@@ -1,23 +1,30 @@
|
||||
/**
|
||||
* POST /api/auth/step-up/options
|
||||
*
|
||||
* Begin a primary-passkey assertion for the step-up mint below. Returns
|
||||
* SimpleWebAuthn assertion options scoped to the calling account's registered
|
||||
* passkeys, plus the server-issued challenge id to present back at
|
||||
* `POST /api/auth/step-up`.
|
||||
* Begin an assertion ceremony for the step-up mint. Two kinds:
|
||||
*
|
||||
* `passkey` — against the account's PRIMARY passkeys. At parity with
|
||||
* `/api/auth/passkey/login-verify`, which the web treats as a
|
||||
* second-factor-grade proof.
|
||||
* `webauthn` — against the account's registered SECOND-FACTOR security keys.
|
||||
*
|
||||
* Returns SimpleWebAuthn assertion options plus the server-issued challenge id
|
||||
* to present back at `POST /api/auth/step-up`.
|
||||
*
|
||||
* Bearer-only (`requireBearerAuth`) — a browser has no use for this surface; it
|
||||
* re-proves a factor at login and carries the result on its session row. The
|
||||
* allow-list is never empty by construction: an account with no passkey gets a
|
||||
* 409 telling the client to use the password arm instead.
|
||||
* allow-list is never empty by construction: an account with no credential of
|
||||
* the requested kind gets a 409 so the client can offer another arm.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireBearerAuth } from "@/lib/api-handler";
|
||||
import { apiError, apiSuccess } from "@/lib/api-response";
|
||||
import { apiError, apiSuccess, safeJson } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { checkAuthSurfaceRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { createAuthenticationOptions } from "@/lib/auth/passkey";
|
||||
import { createMfaAuthenticationOptions } from "@/lib/auth/mfa/webauthn";
|
||||
import { stepUpOptionsSchema } from "@/lib/validations/step-up";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -36,6 +43,29 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
});
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request, {
|
||||
maxBytes: 4 * 1024,
|
||||
});
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const parsed = stepUpOptionsSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError("Invalid request", 422);
|
||||
}
|
||||
|
||||
if (parsed.data.method === "webauthn") {
|
||||
const result = await createMfaAuthenticationOptions(user.id);
|
||||
if (!result) {
|
||||
annotate({ action: { name: "auth.stepup.webauthn.no_key" } });
|
||||
return apiError("No security key registered", 409);
|
||||
}
|
||||
annotate({ action: { name: "auth.stepup.webauthn.options" } });
|
||||
return apiSuccess({
|
||||
options: result.options,
|
||||
challengeId: result.challengeId,
|
||||
});
|
||||
}
|
||||
|
||||
const passkeyCount = await prisma.passkey.count({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
@@ -4,6 +4,15 @@
|
||||
* Re-prove a factor and receive a single-use, token-bound step-up elevation for
|
||||
* one second-factor-management call.
|
||||
*
|
||||
* WHICH factor is re-proved decides WHAT the elevation reaches. `password`
|
||||
* reaches exactly what a plain cookie session reaches. `totp`, `webauthn`, and
|
||||
* `passkey` additionally satisfy the fresh-factor routes — disable, recovery-code
|
||||
* rotation, security-key removal — and that set is precisely the set of
|
||||
* ceremonies for which the web stamps a session second-factor-verified. If a
|
||||
* password-proved elevation opened those routes, a stolen token plus the account
|
||||
* password would rotate the recovery codes (which take no factor in the body)
|
||||
* and then spend one of them to disable the second factor outright.
|
||||
*
|
||||
* This is the whole point of the mechanism, so it is worth being blunt about
|
||||
* what it is not: it is NOT a way to turn a token into a stronger credential.
|
||||
* Presenting the token gets you as far as this endpoint and no further — the
|
||||
@@ -37,8 +46,11 @@ import {
|
||||
} from "@/lib/rate-limit";
|
||||
import { verifyPassword } from "@/lib/auth/password";
|
||||
import { verifyAuthentication } from "@/lib/auth/passkey";
|
||||
import { verifyMfaAuthentication } from "@/lib/auth/mfa/webauthn";
|
||||
import { verifyMfaFactor } from "@/lib/auth/mfa/verify-factor";
|
||||
import {
|
||||
mintStepUpElevation,
|
||||
isFreshFactorMethod,
|
||||
STEP_UP_ELEVATION_TTL_SECONDS,
|
||||
type StepUpMethod,
|
||||
} from "@/lib/auth/step-up";
|
||||
@@ -103,32 +115,62 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
return apiError("Invalid request", 422);
|
||||
}
|
||||
|
||||
const method: StepUpMethod = parsed.data.method;
|
||||
let proved = false;
|
||||
let method: StepUpMethod = parsed.data.method;
|
||||
// Audit-only detail. Never reaches the response — see the file header.
|
||||
let failure = "invalid";
|
||||
|
||||
/**
|
||||
* Resolve a WebAuthn challenge and confirm it belongs to THIS account before
|
||||
* any verification runs. Both ceremony helpers resolve a challenge by id
|
||||
* alone, so without this a challenge minted for another account could be
|
||||
* carried into the ceremony.
|
||||
*/
|
||||
const challengeBelongsToCaller = async (id: string): Promise<boolean> => {
|
||||
const row = await prisma.authChallenge.findUnique({
|
||||
where: { id },
|
||||
select: { userId: true },
|
||||
});
|
||||
return Boolean(row && row.userId === user.id);
|
||||
};
|
||||
|
||||
if (parsed.data.method === "password") {
|
||||
if (!user.passwordHash) {
|
||||
// An SSO-provisioned account has no password to re-prove. Same refusal as
|
||||
// a wrong one: the account's credential shape is not a token holder's to
|
||||
// enumerate. `/api/auth/step-up/options` is the honest discovery path —
|
||||
// it 409s when there is no passkey either.
|
||||
// it 409s when there is no credential of the requested kind either.
|
||||
failure = "no_password";
|
||||
} else {
|
||||
proved = await verifyPassword(user.passwordHash, parsed.data.password);
|
||||
if (!proved) failure = "bad_password";
|
||||
}
|
||||
} else if (parsed.data.method === "totp") {
|
||||
// The shared factor verifier, so the replay guard and the accepted-step
|
||||
// burn behave exactly as they do at login and at MFA-disable. A code spent
|
||||
// here cannot be replayed there.
|
||||
const result = await verifyMfaFactor(user, "totp", parsed.data.code);
|
||||
proved = result.ok;
|
||||
if (!proved) failure = result.replay ? "totp_replay" : "bad_totp";
|
||||
} else if (parsed.data.method === "webauthn") {
|
||||
if (!(await challengeBelongsToCaller(parsed.data.challengeId))) {
|
||||
failure = "foreign_challenge";
|
||||
} else {
|
||||
try {
|
||||
// Scoped to the caller's own second-factor credentials by the verifier.
|
||||
proved = await verifyMfaAuthentication(
|
||||
parsed.data.challengeId,
|
||||
user.id,
|
||||
parsed.data.credential,
|
||||
);
|
||||
if (!proved) failure = "bad_assertion";
|
||||
} catch {
|
||||
// A malformed / expired challenge is a failed attempt, not a 500.
|
||||
failure = "bad_assertion";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
method = "passkey";
|
||||
// Bind the challenge to the caller BEFORE verifying. `verifyAuthentication`
|
||||
// resolves a challenge by id alone; pinning ownership here means a challenge
|
||||
// minted for another account cannot be carried into this ceremony.
|
||||
const challenge = await prisma.authChallenge.findUnique({
|
||||
where: { id: parsed.data.challengeId },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!challenge || challenge.userId !== user.id) {
|
||||
if (!(await challengeBelongsToCaller(parsed.data.challengeId))) {
|
||||
failure = "foreign_challenge";
|
||||
} else {
|
||||
try {
|
||||
@@ -142,7 +184,6 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
result.verification.verified && result.passkey.userId === user.id;
|
||||
if (!proved) failure = "bad_assertion";
|
||||
} catch {
|
||||
// A malformed / expired challenge is a failed attempt, not a 500.
|
||||
failure = "bad_assertion";
|
||||
}
|
||||
}
|
||||
@@ -184,5 +225,12 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
elevation: token,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
expiresInSeconds: STEP_UP_ELEVATION_TTL_SECONDS,
|
||||
method,
|
||||
// Whether this elevation reaches the fresh-factor routes (disable,
|
||||
// recovery-code rotation, security-key removal). A password-proved
|
||||
// elevation does not, exactly as a password login does not on the web.
|
||||
// Surfaced so the client can pick the right ceremony up front instead of
|
||||
// discovering the refusal after spending a proof.
|
||||
satisfiesFreshFactor: isFreshFactorMethod(method),
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user