mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
feat(auth): add TOTP second factor and recovery codes
Add the TOTP enroll/confirm/disable surface and Argon2id-hashed recovery codes as the v1.23 second factor. - totp.ts wraps otpauth (zero-dep) pinned to the interop floor (SHA-1, 6 digits, 30 s) with a +/-1 drift window. Replay protection persists the last accepted time-step per account (User.totpLastStep, migration 0202_v123_totp_laststep) and rejects any step that is not strictly newer, so a captured code dies the instant it is accepted once. - recovery-codes.ts issues ten single-use, high-entropy codes, Argon2id- hashed at rest, shown once; regeneration replaces the entire prior set in a transaction and verification burns the matched code with a guarded update. - The TOTP secret is stored AES-256-GCM encrypted (already registered in the encrypted-columns registry + rotation script); decrypt is fail-closed. - Routes: setup (pending secret), confirm (activate + issue recovery codes), disable (step-up + current factor), recovery-codes/regenerate (step-up). Setup/confirm are cookie-only; disable/regenerate add requireFreshMfa. - scripts/disable-mfa.ts is the operator escape hatch for a locked-out self-hoster, audited, run via pnpm dlx tsx.
This commit is contained in:
1 parent
3d3018b12e
commit
b446a66753
15 files changed
+1086
No files matched your search
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* 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).
|
||||
* 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.
|
||||
*
|
||||
* On success it clears `totpSecretEncrypted` / `totpConfirmedAt` /
|
||||
* `totpLastStep` and deletes every recovery code in one transaction.
|
||||
*/
|
||||
import {
|
||||
apiHandler,
|
||||
requireFreshMfa,
|
||||
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";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { verifyMfaFactor } from "@/lib/auth/mfa/verify-factor";
|
||||
import { mfaDisableSchema } from "@/lib/validations/mfa";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const DISABLE_RATE_LIMIT = 5;
|
||||
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 } = await requireFreshMfa(MFA_STEP_UP_MAX_AGE_SECONDS);
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`mfa:disable:${user.id}`,
|
||||
DISABLE_RATE_LIMIT,
|
||||
DISABLE_WINDOW_MS,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
const res = apiError("Too many requests", 429);
|
||||
for (const [k, v] of Object.entries(rateLimitHeaders(rl))) {
|
||||
res.headers.set(k, v);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
throw new HttpError(400, "Invalid JSON body");
|
||||
}
|
||||
const parsed = mfaDisableSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError("Invalid request", 422);
|
||||
}
|
||||
|
||||
const factor = await verifyMfaFactor(
|
||||
user,
|
||||
parsed.data.method,
|
||||
parsed.data.code,
|
||||
);
|
||||
if (!factor.ok) {
|
||||
await auditLog("auth.mfa.failed", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(req),
|
||||
details: {
|
||||
stage: "disable",
|
||||
method: parsed.data.method,
|
||||
replay: factor.replay,
|
||||
},
|
||||
});
|
||||
annotate({ action: { name: "auth.mfa.disable.invalid_factor" } });
|
||||
throw new HttpError(401, "Invalid code");
|
||||
}
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
totpSecretEncrypted: null,
|
||||
totpConfirmedAt: null,
|
||||
totpLastStep: null,
|
||||
},
|
||||
});
|
||||
await tx.mfaRecoveryCode.deleteMany({ where: { userId: user.id } });
|
||||
});
|
||||
|
||||
await auditLog("auth.mfa.disabled", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(req),
|
||||
details: { factor: parsed.data.method },
|
||||
});
|
||||
annotate({ action: { name: "auth.mfa.disabled" } });
|
||||
|
||||
return apiSuccess({ enabled: false });
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 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**.
|
||||
*/
|
||||
import {
|
||||
apiHandler,
|
||||
requireFreshMfa,
|
||||
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";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { regenerateRecoveryCodes } from "@/lib/auth/mfa/recovery-codes";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
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);
|
||||
|
||||
// Defence in depth — regeneration only makes sense for an active factor.
|
||||
if (!user.totpConfirmedAt) {
|
||||
throw new HttpError(409, "No second factor is active");
|
||||
}
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`mfa:recovery-regen:${user.id}`,
|
||||
REGEN_RATE_LIMIT,
|
||||
REGEN_WINDOW_MS,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
const res = apiError("Too many requests", 429);
|
||||
for (const [k, v] of Object.entries(rateLimitHeaders(rl))) {
|
||||
res.headers.set(k, v);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
const recoveryCodes = await regenerateRecoveryCodes(user.id);
|
||||
|
||||
await auditLog("auth.mfa.recovery_regenerated", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(req),
|
||||
details: { count: recoveryCodes.length },
|
||||
});
|
||||
annotate({ action: { name: "auth.mfa.recovery_regenerated" } });
|
||||
|
||||
return apiSuccess({
|
||||
recoveryCodes,
|
||||
recoveryCodesRemaining: recoveryCodes.length,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* POST /api/auth/me/mfa/totp/confirm
|
||||
*
|
||||
* Finish TOTP enrollment. Verifies a code against the pending secret; on
|
||||
* success it promotes pending → active (`totpConfirmedAt = now()`), records
|
||||
* 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.
|
||||
*
|
||||
* Cookie-only (`requireCookieAuth`): an API token can never enrol MFA.
|
||||
*/
|
||||
import { apiHandler, requireCookieAuth, 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";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { verifyTotp } from "@/lib/auth/mfa/totp";
|
||||
import {
|
||||
generateRecoveryCodes,
|
||||
persistRecoveryCodes,
|
||||
} from "@/lib/auth/mfa/recovery-codes";
|
||||
import { totpConfirmSchema } from "@/lib/validations/mfa";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
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 rl = await checkRateLimit(
|
||||
`mfa:confirm:${user.id}`,
|
||||
CONFIRM_RATE_LIMIT,
|
||||
CONFIRM_WINDOW_MS,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
const res = apiError("Too many requests", 429);
|
||||
for (const [k, v] of Object.entries(rateLimitHeaders(rl))) {
|
||||
res.headers.set(k, v);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
if (user.totpConfirmedAt) {
|
||||
throw new HttpError(409, "A second factor is already active");
|
||||
}
|
||||
if (!user.totpSecretEncrypted) {
|
||||
throw new HttpError(409, "Start enrollment before confirming");
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
throw new HttpError(400, "Invalid JSON body");
|
||||
}
|
||||
const parsed = totpConfirmSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError("Invalid code", 422);
|
||||
}
|
||||
|
||||
// Decrypt is fail-closed — a missing/rotated key throws rather than
|
||||
// confirming against junk.
|
||||
const secret = decrypt(user.totpSecretEncrypted);
|
||||
const result = verifyTotp(
|
||||
secret,
|
||||
parsed.data.code,
|
||||
user.totpLastStep === null ? null : Number(user.totpLastStep),
|
||||
);
|
||||
|
||||
if (!result.valid) {
|
||||
await auditLog("auth.mfa.failed", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(req),
|
||||
details: { stage: "confirm", replay: result.replay },
|
||||
});
|
||||
annotate({
|
||||
action: { name: "auth.mfa.totp.confirm.invalid" },
|
||||
meta: { replay: result.replay },
|
||||
});
|
||||
throw new HttpError(401, "Invalid code");
|
||||
}
|
||||
|
||||
const recoveryCodes = generateRecoveryCodes();
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
totpConfirmedAt: new Date(),
|
||||
totpLastStep: BigInt(result.step as number),
|
||||
},
|
||||
});
|
||||
// A fresh enrollment starts from a clean recovery set.
|
||||
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() },
|
||||
});
|
||||
});
|
||||
|
||||
await auditLog("auth.mfa.enabled", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(req),
|
||||
details: { factor: "totp" },
|
||||
});
|
||||
annotate({ action: { name: "auth.mfa.enabled" } });
|
||||
|
||||
// `recoveryCodes` is redaction-denylisted (`/recovery.?code/i`).
|
||||
return apiSuccess({
|
||||
enabled: true,
|
||||
recoveryCodes,
|
||||
recoveryCodesRemaining: recoveryCodes.length,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* POST /api/auth/me/mfa/totp/setup
|
||||
*
|
||||
* Begin TOTP enrollment. Generates a 160-bit secret, stores it **encrypted**
|
||||
* (AES-256-GCM, the same at-rest envelope as every other credential), and
|
||||
* returns the `otpauth://` URI + the raw Base32 secret so the client can
|
||||
* render the QR and offer manual entry. The secret is **pending** — MFA is
|
||||
* 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.
|
||||
*/
|
||||
import { apiHandler, requireCookieAuth, 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";
|
||||
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";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const SETUP_RATE_LIMIT = 5;
|
||||
const SETUP_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
export const POST = apiHandler(async (req: Request) => {
|
||||
const { user } = await requireCookieAuth();
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`mfa:setup:${user.id}`,
|
||||
SETUP_RATE_LIMIT,
|
||||
SETUP_WINDOW_MS,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
const res = apiError("Too many requests", 429);
|
||||
for (const [k, v] of Object.entries(rateLimitHeaders(rl))) {
|
||||
res.headers.set(k, v);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// An already-active factor must be disabled (step-up gated) before a new
|
||||
// secret can be enrolled — re-running setup must not silently rotate the
|
||||
// live secret out from under the user's authenticator.
|
||||
if (user.totpConfirmedAt) {
|
||||
annotate({ action: { name: "auth.mfa.totp.setup.already_active" } });
|
||||
throw new HttpError(409, "A second factor is already active");
|
||||
}
|
||||
|
||||
const secret = generateTotpSecret();
|
||||
const account = user.email ?? user.username;
|
||||
const otpauthUri = buildOtpauthUri(secret, account);
|
||||
|
||||
// Store the pending secret encrypted; leave `totpConfirmedAt` null.
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
totpSecretEncrypted: encrypt(secret),
|
||||
// A re-setup resets the replay counter — the new secret starts fresh.
|
||||
totpLastStep: null,
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("auth.mfa.totp.setup", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(req),
|
||||
});
|
||||
annotate({ action: { name: "auth.mfa.totp.setup" } });
|
||||
|
||||
// `totpSecret` / `otpauthUri` are redaction-denylisted (`/totp/i`,
|
||||
// `/otp/i`, `/secret/i`) so they never surface in a wide-event excerpt.
|
||||
return apiSuccess({ otpauthUri, totpSecret: secret });
|
||||
});
|
||||
Reference in new issue
Block a user