Merge branch 'fix/auth-takeover-hardening' into release/v1.39.3

# Conflicts:
#	docs/api/openapi.yaml
#	messages/de.json
#	messages/en.json
#	messages/es.json
#	messages/fr.json
#	messages/it.json
#	messages/ko.json
#	messages/pl.json
This commit is contained in:
Marc-André Bombeck committed 2026-09-26 19:14:05 +02:00
commit 42d47e0877
67 files changed
+3631 -778

No files matched your search

+20 -4
View File
@@ -31,6 +31,7 @@
import { Readable } from "node:stream";
import { createGunzip } from "node:zlib";
import { BodyTooLargeError, readBoundedBody } from "@/lib/labs/ocr-upload";
import { NextRequest } from "next/server";
import { ZodError } from "zod/v4";
import { prisma } from "@/lib/db";
@@ -64,11 +65,13 @@ export const dynamic = "force-dynamic";
* is sent as the raw request body, which is read as a stream.
*/
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
/** Room for the multipart boundaries and part headers around the file. */
const MULTIPART_OVERHEAD_BYTES = 64 * 1024;
/**
* Cap on a file sent as the raw request body, compressed or not. The same
* ceiling the app sets for any request body (`middlewareClientMaxBodySize` in
* `next.config.ts`), beyond which the body would arrive truncated. A
* Cap on a file sent as the raw request body, compressed or not, counted
* while the body streams. The route is left out of the proxy matcher
* (`src/lib/http/proxy-bypass-routes.ts`), so this is the only ceiling. A
* disaster-recovery file of 1.25 million measurements is 662 MB as plain
* JSON and 64 MB compressed, so large files go up compressed.
*/
@@ -179,10 +182,23 @@ export const POST = apiHandler(async (request: NextRequest) => {
let source: AsyncIterable<Uint8Array>;
if (multipart) {
// The multipart parser holds the whole form and counts nothing, so the
// bytes are counted first and the form is parsed from what was kept. The
// route is outside the proxy matcher, so nothing else bounds this read.
let formData: FormData;
try {
formData = await request.formData();
const bytes = await readBoundedBody(
request.body,
MAX_UPLOAD_BYTES + MULTIPART_OVERHEAD_BYTES,
);
formData = await new Response(new Blob([bytes]), {
headers: { "content-type": contentType },
}).formData();
} catch (err) {
if (err instanceof BodyTooLargeError) {
await denied("stream_size_exceeded");
return apiError("Upload exceeds 10 MB limit", 413);
}
return apiError(
`Invalid multipart body: ${err instanceof Error ? err.message : "unknown"}`,
400,
+14 -1
View File
@@ -19,12 +19,19 @@ import { createMfaChallenge } from "@/lib/auth/mfa/challenge";
import { consumeTrustedDevice } from "@/lib/auth/trusted-device";
import { syncMfaEnrollCookie } from "@/lib/auth/mfa-enrollment";
import { isOidcOnly } from "@/lib/auth/oidc";
import { readPendingLink } from "@/lib/auth/oidc-pending-link";
export const POST = apiHandler(async (request: NextRequest) => {
// OIDC_ONLY means password login must be a dead end, not just a hidden
// button — otherwise a pre-existing password (or a leaked/reused one)
// stays a live bypass of the operator's SSO-only policy.
if (isOidcOnly()) {
//
// One exception, and only for one account: a browser the SSO callback sent
// here to confirm an existing account carries a sealed pending link naming
// that account. It may prove that account's password (checked again once
// the account is resolved) so the link can be made; nothing else opens.
const pendingLink = isOidcOnly() ? await readPendingLink() : null;
if (isOidcOnly() && !pendingLink) {
return apiError("Password login is disabled. Sign in with SSO.", 403, {
errorCode: "oidc_only",
});
@@ -119,6 +126,12 @@ export const POST = apiHandler(async (request: NextRequest) => {
return apiError("Invalid credentials", 401);
}
if (pendingLink && pendingLink.userId !== user.id) {
return apiError("Password login is disabled. Sign in with SSO.", 403, {
errorCode: "oidc_only",
});
}
const ua = request.headers.get("user-agent");
await auditLog("auth.login.password", {
+20 -1
View File
@@ -10,7 +10,14 @@
*
* 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
* A token on its own can still never enrol MFA.
*
* A cookie session on its own cannot either. Enrolling hands the caller a
* factor that later satisfies every step-up gate, so a stolen session must not
* be able to mint one: the cookie arm also passes `checkCookieEnrollmentProof`
* — a sign-in or second factor inside the last five minutes, or a password /
* factor proof in the body (the step-up mint's shapes). The Bearer arm already
* carries that proof in its elevation. The recovery-code batch is
* issued at `/confirm` (after the factor is proven), not here, so an abandoned
* setup never persists codes.
*/
@@ -26,6 +33,7 @@ import { prisma } from "@/lib/db";
import { encrypt } from "@/lib/crypto";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { generateTotpSecret, buildOtpauthUri } from "@/lib/auth/mfa/totp";
import { checkCookieEnrollmentProof } from "@/lib/auth/existing-factor-proof";
export const dynamic = "force-dynamic";
@@ -57,6 +65,17 @@ export const POST = apiHandler(async (req: Request) => {
throw new HttpError(409, "A second factor is already active");
}
if (auth.transport === "cookie") {
const refusal = await checkCookieEnrollmentProof({
user,
sessionId: auth.session.id,
request: req,
ipAddress: getClientIp(req),
stage: "totp_enroll",
});
if (refusal) return refusal;
}
// Rate limit and the already-active check have passed; the write is next.
await auth.commitElevation();
@@ -31,11 +31,16 @@ vi.mock("@/lib/auth/audit", () => ({
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
vi.mock("@/lib/auth/existing-factor-proof", () => ({
checkCookieEnrollmentProof: vi.fn(),
}));
import { POST as REGISTER_OPTIONS } from "../options/route";
import { POST as REGISTER_VERIFY } from "../verify/route";
import { requireMfaManagementAuth } from "@/lib/api-handler";
import { prisma } from "@/lib/db";
import { checkRateLimit } from "@/lib/rate-limit";
import { checkCookieEnrollmentProof } from "@/lib/auth/existing-factor-proof";
import {
createMfaRegistrationOptions,
verifyMfaRegistration,
@@ -63,8 +68,16 @@ beforeEach(() => {
commitElevation: vi.fn().mockResolvedValue(undefined),
} as never);
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(checkCookieEnrollmentProof).mockResolvedValue(null);
});
function optionsRequest(): NextRequest {
return new NextRequest(
"http://localhost/api/auth/me/mfa/webauthn/register/options",
{ method: "POST" },
);
}
describe("POST /api/auth/me/mfa/webauthn/register/options", () => {
it("returns ceremony options + challenge id", async () => {
vi.mocked(createMfaRegistrationOptions).mockResolvedValue({
@@ -72,7 +85,7 @@ describe("POST /api/auth/me/mfa/webauthn/register/options", () => {
challengeId: "ch-1",
} as never);
const res = await REGISTER_OPTIONS();
const res = await REGISTER_OPTIONS(optionsRequest());
const body = (await res.json()) as {
data: { options: unknown; challengeId: string };
};
@@ -86,6 +99,40 @@ describe("POST /api/auth/me/mfa/webauthn/register/options", () => {
});
});
describe("security-key enrollment needs a fresh proof on the cookie arm", () => {
it("stops before any challenge exists when the session cannot show one", async () => {
vi.mocked(checkCookieEnrollmentProof).mockResolvedValue(
new Response(null, { status: 401 }),
);
const res = await REGISTER_OPTIONS(optionsRequest());
expect(res.status).toBe(401);
expect(createMfaRegistrationOptions).not.toHaveBeenCalled();
expect(checkCookieEnrollmentProof).toHaveBeenCalledWith(
expect.objectContaining({
sessionId: "sess-1",
stage: "security_key_enroll",
}),
);
});
it("leaves the Bearer arm to its elevation", async () => {
vi.mocked(requireMfaManagementAuth).mockResolvedValue({
transport: "bearer",
user: USER,
apiTokenId: "tok-1",
accessTokenHash: "h",
commitElevation: vi.fn().mockResolvedValue(undefined),
} as never);
vi.mocked(createMfaRegistrationOptions).mockResolvedValue({
options: {},
challengeId: "ch-2",
} as never);
const res = await REGISTER_OPTIONS(optionsRequest());
expect(res.status).toBe(200);
expect(checkCookieEnrollmentProof).not.toHaveBeenCalled();
});
});
describe("POST /api/auth/me/mfa/webauthn/register/verify", () => {
const credential = {
id: "cred-1",
@@ -5,16 +5,21 @@
* 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.
*
* The cookie arm additionally passes `checkCookieEnrollmentProof`: a session
* alone cannot add a security key, for the same reason it cannot enroll TOTP —
* the new key would satisfy every step-up gate from then on.
*/
import { apiHandler, requireMfaManagementAuth } from "@/lib/api-handler";
import { apiError, apiSuccess } from "@/lib/api-response";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { checkCookieEnrollmentProof } from "@/lib/auth/existing-factor-proof";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { createMfaRegistrationOptions } from "@/lib/auth/mfa/webauthn";
export const dynamic = "force-dynamic";
export const POST = apiHandler(async () => {
export const POST = apiHandler(async (req: Request) => {
const auth = await requireMfaManagementAuth();
const { user } = auth;
@@ -31,6 +36,17 @@ export const POST = apiHandler(async () => {
return res;
}
if (auth.transport === "cookie") {
const refusal = await checkCookieEnrollmentProof({
user,
sessionId: auth.session.id,
request: req,
ipAddress: getClientIp(req),
stage: "security_key_enroll",
});
if (refusal) return refusal;
}
await auth.commitElevation();
const { options, challengeId } = await createMfaRegistrationOptions(
+9
View File
@@ -32,6 +32,7 @@ import { checkAuthSurfaceRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { finishLogin } from "@/lib/auth/login-response";
import {
loadActiveChallenge,
reserveChallengeAttempt,
recordChallengeFailure,
claimChallenge,
} from "@/lib/auth/mfa/challenge";
@@ -90,6 +91,14 @@ export const POST = apiHandler(async (request: NextRequest) => {
return apiError("Invalid or expired challenge", 401);
}
// Count this attempt before anything is verified. The reservation is one
// guarded UPDATE, so concurrent guesses cannot all slip under the cap the
// way a read-then-increment let them.
if (!(await reserveChallengeAttempt(challenge.id))) {
annotate({ action: { name: "auth.mfa.verify.attempts_exhausted" } });
return apiError("Invalid or expired challenge", 401);
}
const user = await prisma.user.findUnique({
where: { id: challenge.userId },
select: {
@@ -25,6 +25,7 @@ vi.mock("@/lib/rate-limit", () => ({
vi.mock("@/lib/auth/mfa/challenge", () => ({
loadActiveChallenge: vi.fn(),
reserveChallengeAttempt: vi.fn().mockResolvedValue(true),
recordChallengeFailure: vi.fn().mockResolvedValue({ exhausted: false }),
claimChallenge: vi.fn(),
}));
@@ -50,6 +51,7 @@ import { prisma } from "@/lib/db";
import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
import {
loadActiveChallenge,
reserveChallengeAttempt,
claimChallenge,
recordChallengeFailure,
} from "@/lib/auth/mfa/challenge";
@@ -93,6 +95,7 @@ beforeEach(() => {
username: "u",
onboardingCompletedAt: new Date(),
} as never);
vi.mocked(reserveChallengeAttempt).mockResolvedValue(true);
vi.mocked(recordChallengeFailure).mockResolvedValue({
exhausted: false,
attempts: 1,
@@ -126,6 +129,14 @@ describe("POST /api/auth/mfa/webauthn/verify", () => {
);
});
it("refuses before the assertion runs when no attempt can be reserved", async () => {
vi.mocked(reserveChallengeAttempt).mockResolvedValue(false);
const res = await POST(makeRequest(VALID_BODY));
expect(res.status).toBe(401);
expect(verifyMfaAuthentication).not.toHaveBeenCalled();
expect(finishLogin).not.toHaveBeenCalled();
});
it("rejects with 401 and burns an attempt when the assertion fails", async () => {
vi.mocked(verifyMfaAuthentication).mockResolvedValue(false as never);
@@ -30,6 +30,7 @@ import { checkAuthSurfaceRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { finishLogin } from "@/lib/auth/login-response";
import {
loadActiveChallenge,
reserveChallengeAttempt,
recordChallengeFailure,
claimChallenge,
} from "@/lib/auth/mfa/challenge";
@@ -86,6 +87,14 @@ export const POST = apiHandler(async (request: NextRequest) => {
return apiError("Invalid or expired challenge", 401);
}
// Count this attempt before anything is verified. The reservation is one
// guarded UPDATE, so concurrent guesses cannot all slip under the cap the
// way a read-then-increment let them.
if (!(await reserveChallengeAttempt(challenge.id))) {
annotate({ action: { name: "auth.mfa.verify.attempts_exhausted" } });
return apiError("Invalid or expired challenge", 401);
}
const user = await prisma.user.findUnique({
where: { id: challenge.userId },
select: { id: true, username: true, onboardingCompletedAt: true },
@@ -16,6 +16,7 @@ vi.mock("@/lib/rate-limit", () => ({
vi.mock("@/lib/crypto", () => ({
decrypt: vi.fn((s: string) => s.replace(/^enc\(/, "").replace(/\)$/, "")),
encrypt: vi.fn((s: string) => `enc(${s})`),
}));
vi.mock("@/lib/db", () => ({
@@ -321,26 +322,34 @@ describe("GET /api/auth/oidc/callback", () => {
expect(res.status).toBe(307);
});
it("links an existing email-matched account ONCE, stamping (issuer, sub)", async () => {
// Inverted in v1.39.3. This used to pin the auto-link: an existing account
// with the same (unverified) local email was bound on the spot and signed
// in. Whoever set that address first owned the account the SSO user landed
// in, so the callback now links nothing and signs nobody in; it leaves a
// sealed pending link and sends the browser to confirm the account with its
// own credential (`oidc-pending-link.test.ts` covers the completion).
it("does not link an email-matched account on the email alone", async () => {
mockIdentity();
mockUserLookups({ byIdentity: null, byEmail: userRow() });
vi.mocked(prisma.user.update).mockResolvedValue(
userRow({ oidcIssuer: METADATA.issuer, oidcSub: "sub-1" }) as never,
);
const res = await GET(validRequest("/dashboard"));
expect(prisma.user.create).not.toHaveBeenCalled();
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: "user-1" },
data: { oidcIssuer: METADATA.issuer, oidcSub: "sub-1" },
});
expect(auditLog).toHaveBeenCalledWith(
expect(prisma.user.update).not.toHaveBeenCalled();
expect(createSession).not.toHaveBeenCalled();
expect(auditLog).not.toHaveBeenCalledWith(
"auth.oidc.linked",
expect.anything(),
);
expect(auditLog).toHaveBeenCalledWith(
"auth.oidc.link_pending",
expect.objectContaining({ userId: "user-1" }),
);
expect(createSession).toHaveBeenCalled();
expect(res.headers.get("location")).toContain("/dashboard");
expect(res.headers.get("location")).toContain("error=oidc_link_required");
const setCookie = res.headers.get("set-cookie") ?? "";
expect(setCookie).toContain("hl_oidc_link=");
expect(setCookie.toLowerCase()).toContain("httponly");
expect(setCookie).toContain("Path=/api/auth");
});
it("rejects a login whose email matches an account bound to a DIFFERENT identity", async () => {
@@ -505,10 +514,9 @@ describe("GET /api/auth/oidc/callback", () => {
it("never stamps the session step-up fresh — the 5th createSession arg is null", async () => {
mockIdentity();
mockUserLookups({ byIdentity: null, byEmail: userRow() });
vi.mocked(prisma.user.update).mockResolvedValue(
userRow({ oidcIssuer: METADATA.issuer, oidcSub: "sub-1" }) as never,
);
mockUserLookups({
byIdentity: userRow({ oidcIssuer: METADATA.issuer, oidcSub: "sub-1" }),
});
await GET(validRequest());
+22 -6
View File
@@ -37,6 +37,7 @@ import {
buildNativeCallbackUrl,
mintNativeHandoff,
} from "@/lib/auth/oidc-native-handoff";
import { setPendingLinkCookie } from "@/lib/auth/oidc-pending-link";
const LOGIN_ERROR_URL = "/auth/login";
@@ -340,14 +341,29 @@ export const GET = apiHandler(async (req: NextRequest) => {
annotate({ meta: { reason: "identity_conflict" } });
return failRedirect("oidc_identity_conflict");
}
user = await prisma.user.update({
where: { id: byEmail.id },
data: { oidcIssuer: metadata.issuer, oidcSub: identity.sub },
});
await auditLog("auth.oidc.linked", {
userId: user.id,
// (2b) Never link on the email alone. The local address was never
// verified — anyone can register with it or type it into a profile —
// so matching it proves nothing about who owns the account. Record
// the link this login would make and send the browser to sign in to
// the account with its own credential; the link is made there
// (`completePendingOidcLink`), and only for this account.
await auditLog("auth.oidc.link_pending", {
userId: byEmail.id,
ipAddress: ip,
});
annotate({ meta: { reason: "link_confirmation_required" } });
if (isNative) {
// The native sign-in sheet cannot run the confirmation; the person
// signs in on the web once, after which the app's SSO works.
return failRedirect("oidc_link_required");
}
const response = errorRedirect("oidc_link_required");
setPendingLinkCookie(response, {
userId: byEmail.id,
issuer: metadata.issuer,
sub: identity.sub,
});
return response;
} else {
// (3) Provision.
const userCount = await prisma.user.count();
@@ -18,6 +18,7 @@ import {
} from "@/lib/auth/native-client";
import { issueAccessAndRefresh } from "@/lib/auth/refresh-token";
import { isOidcOnly } from "@/lib/auth/oidc";
import { completePendingOidcLink } from "@/lib/auth/oidc-pending-link";
export const POST = apiHandler(async (request: NextRequest) => {
// OIDC_ONLY must block passkey login too, not just password login — a
@@ -87,6 +88,10 @@ export const POST = apiHandler(async (request: NextRequest) => {
// meets an MFA-enforcement policy AND passes `requireFreshMfa` step-up,
// exactly like a completed password+TOTP login. (The password+TOTP path is
// unchanged — it stamps the session at `/api/auth/mfa/verify`.)
// The passkey proved this account's own credential, so a single sign-on
// identity this browser was sent here to confirm may now be linked to it.
await completePendingOidcLink(user.id, ip ?? null);
const ua = request.headers.get("user-agent");
await createSession(
user.id,
@@ -2,16 +2,20 @@ import { NextRequest } from "next/server";
import {
createAuthenticationOptions,
createRegistrationOptions,
verifyAuthentication,
} from "@/lib/auth/passkey";
import { createMfaAuthenticationOptions } from "@/lib/auth/mfa/webauthn";
import {
createMfaAuthenticationOptions,
verifyMfaAuthentication,
} from "@/lib/auth/mfa/webauthn";
import { verifyMfaFactor } from "@/lib/auth/mfa/verify-factor";
import { verifyPassword } from "@/lib/auth/password";
recordReproofFailure,
throttleReproof,
verifyExistingFactorProof,
} from "@/lib/auth/existing-factor-proof";
import { prisma } from "@/lib/db";
import { apiError, apiSuccess, safeJson } from "@/lib/api-response";
import {
apiError,
apiSuccess,
getClientIp,
safeJson,
} from "@/lib/api-response";
import { apiHandler, requireCookieAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { stepUpMintSchema } from "@/lib/validations/step-up";
@@ -51,50 +55,25 @@ export const POST = apiHandler(async (request: NextRequest) => {
const parsed = stepUpMintSchema.safeParse(body);
if (!parsed.success) return proofRequired();
let proved = false;
// Every proof counts against the account's shared re-proof bucket and every
// refusal is audited. Without both, a stolen session could guess the account
// password or a TOTP code here as fast as it could send requests.
const ip = getClientIp(request);
const limited = await throttleReproof(user.id, ip, "passkey_enroll");
if (limited) return limited;
if (parsed.data.method === "password") {
proved = Boolean(
user.passwordHash &&
(await verifyPassword(user.passwordHash, parsed.data.password)),
const outcome = await verifyExistingFactorProof(user, parsed.data);
if (!outcome.ok) {
await recordReproofFailure(
user.id,
ip,
"passkey_enroll",
parsed.data.method,
outcome.reason,
);
} else if (parsed.data.method === "totp") {
const result = await verifyMfaFactor(user, "totp", parsed.data.code);
proved = result.ok;
} else {
const expectedType =
parsed.data.method === "passkey"
? "authentication"
: "mfa_authentication";
const challenge = await prisma.authChallenge.findUnique({
where: { id: parsed.data.challengeId },
select: { userId: true, type: true },
});
if (challenge?.userId === user.id && challenge.type === expectedType) {
try {
if (parsed.data.method === "passkey") {
const result = await verifyAuthentication(
parsed.data.challengeId,
parsed.data.credential,
);
proved =
result.verification.verified && result.passkey.userId === user.id;
} else {
proved = await verifyMfaAuthentication(
parsed.data.challengeId,
user.id,
parsed.data.credential,
);
}
} catch {
proved = false;
}
}
return proofRequired();
}
if (!proved) return proofRequired();
// A strong existing factor refreshes the session's MFA stamp. Password proof
// deliberately clears it: registration is authorized by this single-use,
// session-bound challenge but cannot upgrade password-only authentication.
+17 -9
View File
@@ -14,7 +14,10 @@ import {
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { checkRateLimit } from "@/lib/rate-limit";
import {
recordReproofFailure,
throttleReproof,
} from "@/lib/auth/existing-factor-proof";
import {
apiHandler,
requireFreshMfaIfEnrolled,
@@ -35,14 +38,12 @@ export const POST = apiHandler(async (request: NextRequest) => {
// contract. Mirrors the step-up on MFA-disable + recovery-code regen.
const { user } = await requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS);
const rl = await checkRateLimit(
`auth:password:${user.id}`,
5,
15 * 60 * 1000,
);
if (!rl.allowed) {
return apiError("Too many attempts. Please wait 15 minutes.", 429);
}
// The current-password check below is a guessing oracle, so it draws on the
// account's shared re-proof budget: a guess spent here is one the step-up
// mint and the enrollment proofs cannot spend again.
const ip = getClientIp(request);
const limited = await throttleReproof(user.id, ip, "password_change");
if (limited) return limited;
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 64 * 1024,
@@ -62,6 +63,13 @@ export const POST = apiHandler(async (request: NextRequest) => {
const currentValid = await verifyPassword(user.passwordHash, currentPassword);
if (!currentValid) {
await recordReproofFailure(
user.id,
ip,
"password_change",
"password",
"bad_password",
);
return apiError("Current password is incorrect", 401);
}
+16 -2
View File
@@ -9,16 +9,30 @@ import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { applyProfileUpdate } from "@/lib/auth/profile-update";
import { authorizeSensitiveChange } from "@/lib/auth/existing-factor-proof";
export const PUT = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const auth = await requireAuth();
const { user } = auth;
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 64 * 1024,
});
if (jsonError) return jsonError;
const result = await applyProfileUpdate(user.id, body, getClientIp(request));
const ip = getClientIp(request);
const result = await applyProfileUpdate(user.id, body, ip, {
// A new email address needs a fresh proof: the address is what single
// sign-on links an existing account by.
authorizeEmailChange: (currentPassword) =>
authorizeSensitiveChange({
user,
cookieSessionId: auth.authMethod === "cookie" ? auth.session.id : null,
currentPassword,
ipAddress: ip,
stage: "email_change",
}),
});
if (!result.ok) {
const meta = result.errorCode ? { errorCode: result.errorCode } : undefined;
return result.issues
+18 -79
View File
@@ -40,16 +40,17 @@ import {
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import {
checkAuthSurfaceRateLimit,
checkRateLimit,
rateLimitHeaders,
} 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 {
REPROOF_LIMIT,
REPROOF_WINDOW_MS,
reproofBucket,
verifyExistingFactorProof,
} from "@/lib/auth/existing-factor-proof";
import {
mintStepUpElevation,
isFreshFactorMethod,
@@ -65,8 +66,8 @@ export const dynamic = "force-dynamic";
* against a user-supplied string — the same 5-per-15-minutes the password-change
* route uses, for the same reason.
*/
const MINT_LIMIT = 5;
const MINT_WINDOW_MS = 15 * 60 * 1000;
const MINT_LIMIT = REPROOF_LIMIT;
const MINT_WINDOW_MS = REPROOF_WINDOW_MS;
export const POST = apiHandler(async (request: NextRequest) => {
const auth = await requireBearerAuth();
@@ -91,8 +92,10 @@ export const POST = apiHandler(async (request: NextRequest) => {
});
}
// The account's shared re-proof bucket: a guess spent here is a guess the
// web enrollment surfaces cannot spend again, and the other way round.
const userRl = await checkRateLimit(
`auth:step-up:${user.id}`,
reproofBucket(user.id),
MINT_LIMIT,
MINT_WINDOW_MS,
);
@@ -122,78 +125,14 @@ export const POST = apiHandler(async (request: NextRequest) => {
}
const method: StepUpMethod = parsed.data.method;
let proved = false;
// The shared verifier: the same challenge ownership and ceremony checks, and
// the same confirmed-secret rule for TOTP, as every other re-proof surface.
// The replay guard and the accepted-step burn behave exactly as they do at
// login and at MFA-disable, so a code spent here cannot be replayed there.
const outcome = await verifyExistingFactorProof(user, parsed.data);
const proved = outcome.ok;
// 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 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 {
if (!(await challengeBelongsToCaller(parsed.data.challengeId))) {
failure = "foreign_challenge";
} else {
try {
const result = await verifyAuthentication(
parsed.data.challengeId,
parsed.data.credential,
);
// Both halves matter: a verified assertion against SOMEONE ELSE'S
// passkey proves possession of a factor, just not of this account's.
proved =
result.verification.verified && result.passkey.userId === user.id;
if (!proved) failure = "bad_assertion";
} catch {
failure = "bad_assertion";
}
}
}
const failure = outcome.ok ? "" : outcome.reason;
if (!proved) {
await auditLog("auth.stepup.mint.failed", {
+11 -5
View File
@@ -2,7 +2,12 @@ import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
import {
apiSuccess,
apiError,
getClientIp,
readBodyText,
} from "@/lib/api-response";
import { encryptNote } from "@/lib/crypto/note-cipher";
import { checkRateLimit } from "@/lib/rate-limit";
import { NextRequest } from "next/server";
@@ -65,15 +70,16 @@ export const POST = apiHandler(async (request: NextRequest) => {
if (Number.isFinite(declaredLength) && declaredLength > MAX_CSV_BYTES) {
return apiError("CSV exceeds the 16 MB limit", 413);
}
// Counted while it is read, so a body without a Content-Length cannot run
// past the cap before the check.
let text: string;
try {
text = await request.text();
const read = await readBodyText(request, MAX_CSV_BYTES);
if (read.tooLarge) return apiError("CSV exceeds the 16 MB limit", 413);
text = read.text;
} catch {
return apiError("Could not read the request body", 400);
}
if (Buffer.byteLength(text, "utf8") > MAX_CSV_BYTES) {
return apiError("CSV exceeds the 16 MB limit", 413);
}
const parsed = parseCsvMeasurements(text);
if (parsed.fatal) {
@@ -30,7 +30,12 @@
import { NextRequest } from "next/server";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import {
apiError,
apiSuccess,
getClientIp,
readBodyText,
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import {
@@ -133,15 +138,16 @@ export const POST = apiHandler(async (request: NextRequest) => {
if (Number.isFinite(declaredLength) && declaredLength > MAX_BYTES) {
return apiError("File exceeds the 16 MB limit", 413);
}
// Counted while it is read, so a body without a Content-Length cannot run
// past the cap before the check.
let text: string;
try {
text = await request.text();
const read = await readBodyText(request, MAX_BYTES);
if (read.tooLarge) return apiError("File exceeds the 16 MB limit", 413);
text = read.text;
} catch {
return apiError("Could not read the request body", 400);
}
if (Buffer.byteLength(text, "utf8") > MAX_BYTES) {
return apiError("File exceeds the 16 MB limit", 413);
}
const parsed = isJson ? parseAutoExportJson(text) : parseAutoExportCsv(text);
if (parsed.fatal) {
+16 -2
View File
@@ -17,6 +17,7 @@ import {
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { applyProfileUpdate } from "@/lib/auth/profile-update";
import { authorizeSensitiveChange } from "@/lib/auth/existing-factor-proof";
import { prisma } from "@/lib/db";
import { decrypt } from "@/lib/crypto";
import { resolveModuleMap } from "@/lib/modules/gate";
@@ -97,14 +98,27 @@ export const GET = apiHandler(async () => {
});
export const PATCH = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const auth = await requireAuth();
const { user } = auth;
const { data: body, error } = await safeJson(request, {
maxBytes: 64 * 1024,
});
if (error) return error;
const result = await applyProfileUpdate(user.id, body, getClientIp(request));
const ip = getClientIp(request);
const result = await applyProfileUpdate(user.id, body, ip, {
// A new email address needs a fresh proof: the address is what single
// sign-on links an existing account by.
authorizeEmailChange: (currentPassword) =>
authorizeSensitiveChange({
user,
cookieSessionId: auth.authMethod === "cookie" ? auth.session.id : null,
currentPassword,
ipAddress: ip,
stage: "email_change",
}),
});
if (!result.ok) {
const meta = result.errorCode ? { errorCode: result.errorCode } : undefined;
return result.issues