SPB Git

Repository Public

auth.ts 23.9 KB 368 lines typescript

1import { randomBytes } from "node:crypto";2import { cookies } from "next/headers";3import {4  generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse,5  type AuthenticationResponseJSON, type AuthenticatorTransport, type RegistrationResponseJSON,6} from "@simplewebauthn/server";7import { sql } from "./db";8import { env } from "./env";9import { ApiError, clientIp } from "./http";10import { randomToken, safeEqual, sha256 } from "./crypto";11import { audit } from "./audit";12import { PREAUTH_COOKIE, SESSION_COOKIE, userFromToken, type SessionMethod, type UserContext } from "./session-store";1314export { SESSION_COOKIE, userFromToken };15export type { UserContext };1617const SESSION_DAYS = 14;18const RECENT_AUTH_MINUTES = 10;19const RP_NAME = "Sheet";2021export const rpId = () => env.rpId;22export const origin = () => new URL(env.appUrl).origin;2324// ── Sessions ────────────────────────────────────────────────────────────────────────────────────────2526/** A new session (new random identifier) is issued at every authentication; the previous one is revoked. */27export async function createSession(userId: string, method: SessionMethod, req: Request): Promise<void> {28  const jar = await cookies();29  const previous = jar.get(SESSION_COOKIE)?.value;30  if (previous) await sql`UPDATE sessions SET revoked_at = now() WHERE token_hash = ${sha256(previous)} AND revoked_at IS NULL`;31  const token = randomToken(32);32  const csrf = randomToken(24);33  // A recovery-code session only exists to enrol a passkey: it is short.34  const expires = new Date(Date.now() + (method === "recovery_code" ? 30 * 60_000 : SESSION_DAYS * 86_400_000));35  await sql`INSERT INTO sessions (user_id, token_hash, csrf_token, method, user_agent, ip, expires_at, reauth_at)36            VALUES (${userId}, ${sha256(token)}, ${csrf}, ${method}, ${(req.headers.get("user-agent") ?? "").slice(0, 300)}, ${clientIp(req)}, ${expires}, ${method === "recovery_code" ? null : new Date()})`;37  // Host-only cookie (no Domain attribute): never sent to another spboucher.ai sub-domain. Lax: top-level38  // navigations from a bookmark keep the session; every state-changing request also needs the CSRF header.39  jar.set(SESSION_COOKIE, token, { httpOnly: true, secure: env.isProd, sameSite: "lax", path: "/", expires });40  jar.delete(PREAUTH_COOKIE);41}4243export async function currentUser(): Promise<UserContext | null> {44  return userFromToken((await cookies()).get(SESSION_COOKIE)?.value);45}4647export function assertSameOrigin(req: Request): void {48  const o = req.headers.get("origin");49  if (o && o !== origin()) throw new ApiError(403, "bad_origin", "Cross-origin request refused");50  const site = req.headers.get("sec-fetch-site");51  if (site && site !== "same-origin" && site !== "none") throw new ApiError(403, "bad_origin", "Cross-site request refused");52}5354export function assertCsrf(req: Request, user: UserContext): void {55  assertSameOrigin(req);56  if (!safeEqual(req.headers.get("x-csrf-token") ?? "", user.csrfToken)) throw new ApiError(403, "csrf", "Invalid CSRF token");57}5859/**60 * Guard of the whole /api/admin surface. State-changing requests must come from our own origin AND carry the61 * session's CSRF token in a header. A session opened with a recovery code cannot use the studio: it may only62 * enrol a new passkey (see authroutes).63 */64export async function requireAdmin(req: Request): Promise<UserContext> {65  const user = await currentUser();66  if (!user) throw new ApiError(401, "unauthenticated", "Sign in required");67  if (user.method === "recovery_code") throw new ApiError(403, "passkey_required", "Enrol a passkey to continue");68  if (req.method !== "GET" && req.method !== "HEAD") assertCsrf(req, user);69  return user;70}7172/** Sensitive actions (passkey management, recovery codes) need a passkey verification made a few minutes ago. */73export function requireRecentAuth(user: UserContext): void {74  if (!user.reauthAt || Date.now() - new Date(user.reauthAt).getTime() > RECENT_AUTH_MINUTES * 60_000) throw new ApiError(403, "reauth_required", "Confirm with your passkey to continue");75}7677export async function revokeSession(sessionId: string, userId: string): Promise<boolean> {78  const r = await sql`UPDATE sessions SET revoked_at = now() WHERE id = ${sessionId} AND user_id = ${userId} AND revoked_at IS NULL RETURNING id`;79  return r.length > 0;80}8182export async function clearSessionCookie(): Promise<void> {83  (await cookies()).set(SESSION_COOKIE, "", { httpOnly: true, secure: env.isProd, sameSite: "lax", path: "/", maxAge: 0 });84}8586// ── Abuse control ───────────────────────────────────────────────────────────────────────────────────8788/**89 * Progressive lock-out per client address, computed from the audit trail (so it survives restarts):90 * 5 failures in an hour → 1 minute, 10 → 5 minutes, 20 → 1 hour since the last failure.91 */92export async function assertNotLockedOut(ip: string): Promise<void> {93  const [r] = await sql<{ n: number; last: Date | null }[]>`SELECT count(*)::int AS n, max(at) AS last FROM audit_events WHERE action = 'login.failed' AND ip = ${ip} AND at > now() - interval '1 hour'`;94  if (!r.last || r.n < 5) return;95  const waitSec = r.n >= 20 ? 3600 : r.n >= 10 ? 300 : 60;96  const left = Math.ceil(waitSec - (Date.now() - new Date(r.last).getTime()) / 1000);97  if (left > 0) throw new ApiError(429, "locked_out", "Too many failed attempts, try again later", { retryAfterSeconds: left });98}99100// ── Challenge binding ───────────────────────────────────────────────────────────────────────────────101102/** Anonymous ceremonies are tied to the browser that started them through a random HttpOnly cookie. */103async function preauthBinding(create: boolean): Promise<string | null> {104  const jar = await cookies();105  let v = jar.get(PREAUTH_COOKIE)?.value;106  if (!v && create) {107    v = randomToken(24);108    jar.set(PREAUTH_COOKIE, v, { httpOnly: true, secure: env.isProd, sameSite: "strict", path: "/api/auth", maxAge: 600 });109  }110  return v ? sha256("preauth:" + v) : null;111}112const sessionBinding = (u: UserContext) => sha256("session:" + u.sessionId);113114async function consumeChallenge(id: string, kind: "registration" | "authentication" | "reauthentication", binding: string | null) {115  // Single use: the row is deleted as it is read, whatever happens next.116  const [ch] = await sql<{ challenge: string; user_id: string | null; binding: string }[]>`117    DELETE FROM webauthn_challenges WHERE id = ${id} AND kind = ${kind} AND expires_at > now() RETURNING challenge, user_id, binding`;118  if (!ch || !binding || !safeEqual(ch.binding, binding)) return null;119  return ch;120}121122// ── Enrolment tokens (shell only) ───────────────────────────────────────────────────────────────────123124export async function passkeyCount(userId: string): Promise<number> {125  const [r] = await sql<{ n: number }[]>`SELECT count(*)::int AS n FROM passkey_credentials WHERE user_id = ${userId} AND revoked_at IS NULL`;126  return r.n;127}128129type TokenRow = { id: string; user_id: string; purpose: "setup" | "recovery" };130async function validSetupToken(raw: string): Promise<TokenRow | null> {131  const [t] = await sql<TokenRow[]>`132    SELECT t.id, t.user_id, t.purpose FROM setup_tokens t JOIN users u ON u.id = t.user_id133    WHERE t.token_hash = ${sha256(raw)} AND t.used_at IS NULL AND t.expires_at > now() AND u.disabled_at IS NULL`;134  return t ?? null;135}136137/** True while the system waits for its first passkey: the only time /admin/setup shows anything. */138export async function setupPending(): Promise<boolean> {139  const [r] = await sql<{ n: number }[]>`SELECT count(*)::int AS n FROM setup_tokens WHERE used_at IS NULL AND expires_at > now()`;140  return r.n > 0;141}142143export async function setupTokenInfo(raw: string) {144  const t = await validSetupToken(raw);145  if (!t) throw new ApiError(403, "invalid_setup_token", "This enrolment link is invalid or has expired");146  const [u] = await sql<{ display_name: string }[]>`SELECT display_name FROM users WHERE id = ${t.user_id}`;147  return { purpose: t.purpose, displayName: u.display_name };148}149150/** Issues a one-time enrolment token and returns the raw value once (only its SHA-256 is stored). Shell only. */151export async function issueSetupToken(userId: string, purpose: "setup" | "recovery", ttlMinutes: number): Promise<string> {152  const raw = randomToken(32);153  await sql`UPDATE setup_tokens SET used_at = now() WHERE user_id = ${userId} AND used_at IS NULL`;154  await sql`INSERT INTO setup_tokens (user_id, token_hash, purpose, expires_at) VALUES (${userId}, ${sha256(raw)}, ${purpose}, now() + ${ttlMinutes} * interval '1 minute')`;155  await audit({ userId, actor: "system", action: `setup_token.issued.${purpose}` });156  return raw;157}158159const newRecoveryCodes = () => Array.from({ length: 10 }, () => randomBytes(8).toString("hex").replace(/(.{4})(.{4})(.{4})(.{4})/, "$1-$2-$3-$4"));160161// ── WebAuthn registration ───────────────────────────────────────────────────────────────────────────162163/**164 * A passkey can be enrolled in three cases only: with a one-time token issued from the server's shell (first165 * setup, recovery), from a session opened with a recovery code, or from a session re-verified a moment ago.166 */167export async function registrationOptions(input: { setupToken?: string; user?: UserContext | null }) {168  let userId: string, binding: string;169  if (input.user) {170    if (input.user.method !== "recovery_code") requireRecentAuth(input.user);171    userId = input.user.userId; binding = sessionBinding(input.user);172  } else {173    const t = input.setupToken ? await validSetupToken(input.setupToken) : null;174    if (!t) throw new ApiError(403, "invalid_setup_token", "This enrolment link is invalid or has expired");175    userId = t.user_id; binding = (await preauthBinding(true))!;176  }177  const [user] = await sql<{ id: string; email: string; display_name: string }[]>`SELECT id, email, display_name FROM users WHERE id = ${userId}`;178  const existing = await sql<{ credential_id: string; transports: string[] }[]>`SELECT credential_id, transports FROM passkey_credentials WHERE user_id = ${userId} AND revoked_at IS NULL`;179  const options = await generateRegistrationOptions({180    rpName: RP_NAME, rpID: rpId(),181    userName: user.email, userDisplayName: user.display_name,182    userID: new TextEncoder().encode(user.id),183    attestationType: "none",184    excludeCredentials: existing.map((c) => ({ id: c.credential_id, transports: c.transports as AuthenticatorTransport[] })),185    // Discoverable credential + user verification: Face ID / Touch ID / device PIN / security-key PIN.186    authenticatorSelection: { residentKey: "required", userVerification: "required" },187    supportedAlgorithmIDs: [-7, -8, -257],188  });189  const [ch] = await sql<{ id: string }[]>`INSERT INTO webauthn_challenges (challenge, kind, user_id, binding, expires_at)190    VALUES (${options.challenge}, 'registration', ${userId}, ${binding}, now() + interval '5 minutes') RETURNING id`;191  return { challengeId: ch.id, options };192}193194export async function verifyRegistration(input: { challengeId: string; response: RegistrationResponseJSON; name?: string; setupToken?: string; user?: UserContext | null }, req: Request) {195  const binding = input.user ? sessionBinding(input.user) : await preauthBinding(false);196  const ch = await consumeChallenge(input.challengeId, "registration", binding);197  if (!ch || !ch.user_id) throw new ApiError(400, "challenge_expired", "The enrolment challenge has expired, start again");198  let token: TokenRow | null = null;199  if (input.user) { if (input.user.userId !== ch.user_id) throw new ApiError(403, "forbidden"); }200  else {201    token = input.setupToken ? await validSetupToken(input.setupToken) : null;202    if (!token || token.user_id !== ch.user_id) throw new ApiError(403, "invalid_setup_token", "This enrolment link is invalid or has expired");203  }204  let verification;205  try {206    verification = await verifyRegistrationResponse({ response: input.response, expectedChallenge: ch.challenge, expectedOrigin: origin(), expectedRPID: rpId(), requireUserVerification: true });207  } catch { throw new ApiError(400, "registration_failed", "The passkey could not be verified"); }208  if (!verification.verified || !verification.registrationInfo) throw new ApiError(400, "registration_failed", "The passkey could not be verified");209  const { credential, credentialDeviceType, credentialBackedUp, aaguid } = verification.registrationInfo;210  const name = (input.name ?? "").trim().slice(0, 60) || "Passkey";211  const userId = ch.user_id;212  const replaceAll = token?.purpose === "recovery" || input.user?.method === "recovery_code";213  const firstCodes = token !== null || input.user?.method === "recovery_code";214215  let recoveryCodes: string[] | null = null;216  await sql.begin(async (tx) => {217    if (token) {218      const used = await tx`UPDATE setup_tokens SET used_at = now() WHERE id = ${token.id} AND used_at IS NULL RETURNING id`;219      if (used.length === 0) throw new ApiError(403, "invalid_setup_token", "This enrolment link was already used");220    }221    if (replaceAll) {222      // Recovery replaces every credential and signs out every device.223      await tx`UPDATE passkey_credentials SET revoked_at = now() WHERE user_id = ${userId} AND revoked_at IS NULL`;224      await tx`UPDATE sessions SET revoked_at = now() WHERE user_id = ${userId} AND revoked_at IS NULL`;225    }226    await tx`INSERT INTO passkey_credentials (user_id, credential_id, public_key, counter, transports, device_type, backed_up, aaguid, name)227             VALUES (${userId}, ${credential.id}, ${Buffer.from(credential.publicKey)}, ${credential.counter}, ${credential.transports ?? []}, ${credentialDeviceType}, ${credentialBackedUp}, ${aaguid ?? null}, ${name})`;228    if (firstCodes) {229      await tx`DELETE FROM recovery_codes WHERE user_id = ${userId}`;230      recoveryCodes = newRecoveryCodes();231      for (const c of recoveryCodes) await tx`INSERT INTO recovery_codes (user_id, code_hash) VALUES (${userId}, ${sha256(c)})`;232    }233  });234  await audit({ userId, actor: "system", action: token ? `passkey.enrolled.${token.purpose}` : replaceAll ? "passkey.enrolled.recovery_code" : "passkey.added", ip: clientIp(req), meta: { deviceType: credentialDeviceType, backedUp: credentialBackedUp } });235  if (token || replaceAll) await createSession(userId, "setup", req);236  return { ok: true, recoveryCodes };237}238239// ── WebAuthn authentication ─────────────────────────────────────────────────────────────────────────240241export async function authenticationOptions(req: Request) {242  await assertNotLockedOut(clientIp(req));243  // Discoverable credentials: no allowCredentials list, so the response reveals nothing about the account.244  const options = await generateAuthenticationOptions({ rpID: rpId(), userVerification: "required" });245  const binding = (await preauthBinding(true))!;246  const [ch] = await sql<{ id: string }[]>`INSERT INTO webauthn_challenges (challenge, kind, binding, expires_at)247    VALUES (${options.challenge}, 'authentication', ${binding}, now() + interval '5 minutes') RETURNING id`;248  return { challengeId: ch.id, options };249}250251type CredRow = { id: string; user_id: string; credential_id: string; public_key: Buffer; counter: string; transports: string[] };252async function verifyAssertion(response: AuthenticationResponseJSON, challenge: string, onlyUser?: string): Promise<{ cred: CredRow } | { why: string; userId?: string }> {253  const [cred] = await sql<CredRow[]>`254    SELECT a.id, a.user_id, a.credential_id, a.public_key, a.counter, a.transports255    FROM passkey_credentials a JOIN users u ON u.id = a.user_id256    WHERE a.credential_id = ${String(response.id ?? "")} AND a.revoked_at IS NULL AND u.disabled_at IS NULL`;257  if (!cred || (onlyUser && cred.user_id !== onlyUser)) return { why: "unknown_credential" };258  let v;259  try {260    v = await verifyAuthenticationResponse({261      response, expectedChallenge: challenge, expectedOrigin: origin(), expectedRPID: rpId(), requireUserVerification: true, expectedType: "webauthn.get",262      credential: { id: cred.credential_id, publicKey: new Uint8Array(cred.public_key), counter: Number(cred.counter), transports: cred.transports as AuthenticatorTransport[] },263    });264  } catch { v = null; }265  if (!v?.verified) return { why: "bad_assertion", userId: cred.user_id };266  // Synchronised passkeys report a counter of 0 forever; the library already refuses a counter that goes backwards.267  await sql`UPDATE passkey_credentials SET counter = ${v.authenticationInfo.newCounter}, last_used_at = now(), backed_up = ${v.authenticationInfo.credentialBackedUp} WHERE id = ${cred.id}`;268  return { cred };269}270271export async function verifyAuthentication(input: { challengeId: string; response: AuthenticationResponseJSON }, req: Request) {272  const ip = clientIp(req);273  await assertNotLockedOut(ip);274  const denied = new ApiError(401, "login_failed", "Sign-in failed");275  const ch = await consumeChallenge(input.challengeId, "authentication", await preauthBinding(false));276  if (!ch) { await audit({ actor: "anonymous", action: "login.failed", meta: { why: "challenge" }, ip }); throw denied; }277  const r = await verifyAssertion(input.response, ch.challenge);278  if (!("cred" in r)) { await audit({ userId: r.userId ?? null, actor: "anonymous", action: "login.failed", meta: { why: r.why }, ip }); throw denied; }279  await createSession(r.cred.user_id, "passkey", req);280  await audit({ userId: r.cred.user_id, actor: "admin", action: "login.passkey", ip });281  return { ok: true };282}283284/** Strong re-verification inside a session, before a sensitive action. */285export async function reauthOptions(user: UserContext) {286  const creds = await sql<{ credential_id: string; transports: string[] }[]>`SELECT credential_id, transports FROM passkey_credentials WHERE user_id = ${user.userId} AND revoked_at IS NULL`;287  const options = await generateAuthenticationOptions({ rpID: rpId(), userVerification: "required", allowCredentials: creds.map((c) => ({ id: c.credential_id, transports: c.transports as AuthenticatorTransport[] })) });288  const [ch] = await sql<{ id: string }[]>`INSERT INTO webauthn_challenges (challenge, kind, user_id, binding, expires_at)289    VALUES (${options.challenge}, 'reauthentication', ${user.userId}, ${sessionBinding(user)}, now() + interval '5 minutes') RETURNING id`;290  return { challengeId: ch.id, options };291}292293export async function verifyReauth(user: UserContext, input: { challengeId: string; response: AuthenticationResponseJSON }, req: Request) {294  const ch = await consumeChallenge(input.challengeId, "reauthentication", sessionBinding(user));295  const denied = new ApiError(401, "reauth_failed", "Verification failed");296  if (!ch) throw denied;297  const r = await verifyAssertion(input.response, ch.challenge, user.userId);298  if (!("cred" in r)) { await audit({ userId: user.userId, actor: "admin", action: "reauth.failed", meta: { why: r.why }, ip: clientIp(req) }); throw denied; }299  await sql`UPDATE sessions SET reauth_at = now() WHERE id = ${user.sessionId}`;300  await audit({ userId: user.userId, actor: "admin", action: "reauth.ok", ip: clientIp(req) });301  return { ok: true };302}303304/**305 * Recovery: a one-use code opens a 30-minute session that can do exactly one thing — enrol a new passkey (which306 * requires the device's own user verification, revokes the old passkeys and signs out every other session).307 */308export async function loginWithRecoveryCode(code: string, req: Request) {309  const ip = clientIp(req);310  await assertNotLockedOut(ip);311  const normalized = code.trim().toLowerCase().replace(/\s+/g, "");312  const [row] = await sql<{ id: string; user_id: string }[]>`313    UPDATE recovery_codes r SET used_at = now() FROM users u314    WHERE r.code_hash = ${sha256(normalized)} AND r.used_at IS NULL AND u.id = r.user_id AND u.disabled_at IS NULL RETURNING r.id, r.user_id`;315  if (!row) { await audit({ actor: "anonymous", action: "login.failed", meta: { why: "bad_recovery_code" }, ip }); throw new ApiError(401, "login_failed", "Sign-in failed"); }316  await createSession(row.user_id, "recovery_code", req);317  await audit({ userId: row.user_id, actor: "admin", action: "login.recovery_code", ip });318  return { ok: true };319}320321// ── Passkey and session management (settings) ───────────────────────────────────────────────────────322323export async function listPasskeys(userId: string) {324  const rows = await sql<{ id: string; name: string; device_type: string | null; backed_up: boolean; transports: string[]; created_at: Date; last_used_at: Date | null }[]>`325    SELECT id, name, device_type, backed_up, transports, created_at, last_used_at FROM passkey_credentials WHERE user_id = ${userId} AND revoked_at IS NULL ORDER BY created_at`;326  return rows.map((r) => ({ id: r.id, name: r.name, deviceType: r.device_type, backedUp: r.backed_up, transports: r.transports, createdAt: r.created_at.toISOString(), lastUsedAt: r.last_used_at?.toISOString() ?? null }));327}328329export async function renamePasskey(user: UserContext, id: string, name: string) {330  const r = await sql`UPDATE passkey_credentials SET name = ${name.trim().slice(0, 60) || "Passkey"} WHERE id = ${id} AND user_id = ${user.userId} AND revoked_at IS NULL RETURNING id`;331  if (!r.length) throw new ApiError(404, "not_found");332  return { ok: true };333}334335export async function revokePasskey(user: UserContext, id: string, req: Request) {336  requireRecentAuth(user);337  await sql.begin(async (tx) => {338    const [n] = await tx<{ n: number }[]>`SELECT count(*)::int AS n FROM passkey_credentials WHERE user_id = ${user.userId} AND revoked_at IS NULL`;339    if (n.n <= 1) throw new ApiError(409, "last_passkey", "The last passkey cannot be removed");340    const r = await tx`UPDATE passkey_credentials SET revoked_at = now() WHERE id = ${id} AND user_id = ${user.userId} AND revoked_at IS NULL RETURNING id`;341    if (!r.length) throw new ApiError(404, "not_found");342  });343  await audit({ userId: user.userId, actor: "admin", action: "passkey.revoked", entity: "passkey", entityId: id, ip: clientIp(req) });344  return { ok: true };345}346347export async function regenerateRecoveryCodes(user: UserContext, req: Request) {348  requireRecentAuth(user);349  const codes = newRecoveryCodes();350  await sql.begin(async (tx) => {351    await tx`DELETE FROM recovery_codes WHERE user_id = ${user.userId}`;352    for (const c of codes) await tx`INSERT INTO recovery_codes (user_id, code_hash) VALUES (${user.userId}, ${sha256(c)})`;353  });354  await audit({ userId: user.userId, actor: "admin", action: "recovery_codes.regenerated", ip: clientIp(req) });355  return { recoveryCodes: codes };356}357358export async function recoveryCodesLeft(userId: string): Promise<number> {359  const [r] = await sql<{ n: number }[]>`SELECT count(*)::int AS n FROM recovery_codes WHERE user_id = ${userId} AND used_at IS NULL`;360  return r.n;361}362363export async function listSessions(user: UserContext) {364  const rows = await sql<{ id: string; method: string; user_agent: string; ip: string | null; created_at: Date; last_seen_at: Date }[]>`365    SELECT id, method, user_agent, ip, created_at, last_seen_at FROM sessions WHERE user_id = ${user.userId} AND revoked_at IS NULL AND expires_at > now() ORDER BY last_seen_at DESC`;366  return rows.map((r) => ({ id: r.id, method: r.method, userAgent: r.user_agent, ip: r.ip, createdAt: r.created_at.toISOString(), lastSeenAt: r.last_seen_at.toISOString(), current: r.id === user.sessionId }));367}368
Files main
Menu

Theme