SPB Git

Repository Public

auth.ts 19.3 KB 297 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 { SESSION_COOKIE, userFromToken, type Role, type UserContext } from "./session-store";1314export { SESSION_COOKIE, userFromToken };15export type { Role, UserContext };1617const SESSION_DAYS = 30;18const RP_NAME = "Music SP";1920export const rpId = () => env.rpId;21export const origin = () => new URL(env.appUrl).origin;222324// ── Sessions ────────────────────────────────────────────────────────────────────────────────────────2526/** Inserts the session row and returns the raw token (only its SHA-256 is stored). */27async function insertSession(userId: string, method: string, req: Request, days = SESSION_DAYS) {28  const token = randomToken(32);29  const csrf = randomToken(24);30  const expires = new Date(Date.now() + days * 86_400_000);31  await sql`INSERT INTO sessions (user_id, token_hash, csrf_token, method, user_agent, ip, expires_at)32            VALUES (${userId}, ${sha256(token)}, ${csrf}, ${method}, ${(req.headers.get("user-agent") ?? "").slice(0, 300)}, ${clientIp(req)}, ${expires})`;33  return { token, csrf, expires };34}3536/** A new session (new random token) is issued at every authentication: the identifier is never reused. */37export async function createSession(userId: string, method: "passkey" | "recovery_code" | "setup", req: Request): Promise<void> {38  const { token, expires } = await insertSession(userId, method, req);39  const jar = await cookies();40  // Host-only cookie (no Domain attribute): it is never sent to another spboucher.ai sub-domain.41  jar.set(SESSION_COOKIE, token, { httpOnly: true, secure: env.isProd, sameSite: "lax", path: "/", expires });42}4344export async function currentUser(): Promise<UserContext | null> {45  return userFromToken((await cookies()).get(SESSION_COOKIE)?.value);46}4748/**49 * Guard of every authenticated API route. State-changing requests must come from our own origin AND carry the50 * session's CSRF token in a header (a cross-site form cannot set it).51 */52export async function requireUser(req: Request): Promise<UserContext> {53  const user = await currentUser();54  if (!user) throw new ApiError(401, "unauthenticated", "Sign in required");55  if (req.method !== "GET" && req.method !== "HEAD") {56    assertSameOrigin(req);57    const sent = req.headers.get("x-csrf-token") ?? "";58    if (!safeEqual(sent, user.csrfToken)) throw new ApiError(403, "csrf", "Invalid CSRF token");59  }60  return user;61}6263/** Guard of the whole /api/v1/admin surface: the role is read from the database on every request. */64export async function requireAdmin(req: Request): Promise<UserContext> {65  const user = await requireUser(req);66  if (user.role !== "admin") throw new ApiError(403, "forbidden", "Administrator role required");67  return user;68}6970export function assertSameOrigin(req: Request): void {71  const o = req.headers.get("origin");72  if (o && o !== origin()) throw new ApiError(403, "bad_origin", "Cross-origin request refused");73  const site = req.headers.get("sec-fetch-site");74  if (site && site !== "same-origin" && site !== "none") throw new ApiError(403, "bad_origin", "Cross-site request refused");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// ── Enrolment tokens ────────────────────────────────────────────────────────────────────────────────8788export async function passkeyCount(userId: string): Promise<number> {89  const [r] = await sql<{ n: number }[]>`SELECT count(*)::int AS n FROM authenticators WHERE user_id = ${userId}`;90  return r.n;91}9293type TokenRow = { id: string; user_id: string; purpose: "setup" | "recovery" | "invite" };94async function validSetupToken(raw: string): Promise<TokenRow | null> {95  const [t] = await sql<TokenRow[]>`96    SELECT t.id, t.user_id, t.purpose FROM setup_tokens t JOIN users u ON u.id = t.user_id97    WHERE t.token_hash = ${sha256(raw)} AND t.used_at IS NULL AND t.expires_at > now() AND u.disabled_at IS NULL`;98  return t ?? null;99}100101/** What an enrolment link is for, so the setup page can explain itself. Says nothing when the token is invalid. */102export async function setupTokenInfo(raw: string) {103  const t = await validSetupToken(raw);104  if (!t) throw new ApiError(403, "invalid_setup_token", "This enrolment link is invalid or has expired");105  const [u] = await sql<{ display_name: string; role: Role }[]>`SELECT display_name, role FROM users WHERE id = ${t.user_id}`;106  return { purpose: t.purpose, displayName: u.display_name, role: u.role };107}108109/**110 * Issues a one-time enrolment token and returns the raw value once (only its SHA-256 is stored).111 * 'setup' and 'recovery' are issued from the server's shell only; 'invite' by an administrator.112 */113export async function issueSetupToken(userId: string, purpose: "setup" | "recovery" | "invite", ttlMinutes: number): Promise<string> {114  const raw = randomToken(32);115  await sql`UPDATE setup_tokens SET used_at = now() WHERE user_id = ${userId} AND used_at IS NULL`;116  await sql`INSERT INTO setup_tokens (user_id, token_hash, purpose, expires_at) VALUES (${userId}, ${sha256(raw)}, ${purpose}, now() + ${ttlMinutes} * interval '1 minute')`;117  await audit({ userId, actor: "system", action: `setup_token.issued.${purpose}` });118  return raw;119}120121// ── WebAuthn registration ───────────────────────────────────────────────────────────────────────────122123/**124 * A passkey can be enrolled in two cases only: with a one-time token (owner setup, recovery, invitation), or from125 * an authenticated session (adding another device to one's own account).126 */127export async function registrationOptions(input: { setupToken?: string; user?: UserContext | null }) {128  let userId: string;129  if (input.user) userId = input.user.userId;130  else {131    const t = input.setupToken ? await validSetupToken(input.setupToken) : null;132    if (!t) throw new ApiError(403, "invalid_setup_token", "This enrolment link is invalid or has expired");133    userId = t.user_id;134  }135  const [user] = await sql<{ id: string; email: string; display_name: string }[]>`SELECT id, email, display_name FROM users WHERE id = ${userId}`;136  const existing = await sql<{ credential_id: string; transports: string[] }[]>`SELECT credential_id, transports FROM authenticators WHERE user_id = ${userId}`;137  const options = await generateRegistrationOptions({138    rpName: RP_NAME, rpID: rpId(),139    userName: user.email, userDisplayName: user.display_name,140    userID: new TextEncoder().encode(user.id),141    attestationType: "none",142    excludeCredentials: existing.map((c) => ({ id: c.credential_id, transports: c.transports as AuthenticatorTransport[] })),143    authenticatorSelection: { residentKey: "required", userVerification: "required" },144  });145  const [ch] = await sql<{ id: string }[]>`INSERT INTO webauthn_challenges (challenge, kind, user_id, expires_at)146    VALUES (${options.challenge}, 'registration', ${userId}, now() + interval '5 minutes') RETURNING id`;147  return { challengeId: ch.id, options };148}149150export async function verifyRegistration(input: { challengeId: string; response: RegistrationResponseJSON; name?: string; setupToken?: string; user?: UserContext | null }, req: Request) {151  // Single use: the challenge row is deleted as it is read, whatever the outcome.152  const [ch] = await sql<{ challenge: string; user_id: string }[]>`153    DELETE FROM webauthn_challenges WHERE id = ${input.challengeId} AND kind = 'registration' AND expires_at > now() RETURNING challenge, user_id`;154  if (!ch) throw new ApiError(400, "challenge_expired", "The enrolment challenge has expired, start again");155  let token: TokenRow | null = null;156  if (input.user) { if (input.user.userId !== ch.user_id) throw new ApiError(403, "forbidden"); }157  else {158    token = input.setupToken ? await validSetupToken(input.setupToken) : null;159    if (!token || token.user_id !== ch.user_id) throw new ApiError(403, "invalid_setup_token", "This enrolment link is invalid or has expired");160  }161  let verification;162  try {163    verification = await verifyRegistrationResponse({ response: input.response, expectedChallenge: ch.challenge, expectedOrigin: origin(), expectedRPID: rpId(), requireUserVerification: true });164  } catch { throw new ApiError(400, "registration_failed", "The passkey could not be verified"); }165  if (!verification.verified || !verification.registrationInfo) throw new ApiError(400, "registration_failed", "The passkey could not be verified");166  const { credential, credentialDeviceType, credentialBackedUp } = verification.registrationInfo;167  const name = (input.name ?? "").trim().slice(0, 60) || "Passkey";168169  let recoveryCodes: string[] | null = null;170  await sql.begin(async (tx) => {171    if (token) {172      const used = await tx`UPDATE setup_tokens SET used_at = now() WHERE id = ${token.id} AND used_at IS NULL RETURNING id`;173      if (used.length === 0) throw new ApiError(403, "invalid_setup_token", "This enrolment link was already used");174      if (token.purpose === "recovery") {175        // Recovery replaces every credential and signs out every device.176        await tx`DELETE FROM authenticators WHERE user_id = ${ch.user_id}`;177        await tx`UPDATE sessions SET revoked_at = now() WHERE user_id = ${ch.user_id} AND revoked_at IS NULL`;178      }179    }180    await tx`INSERT INTO authenticators (user_id, credential_id, public_key, counter, transports, device_type, backed_up, name)181             VALUES (${ch.user_id}, ${credential.id}, ${Buffer.from(credential.publicKey)}, ${credential.counter}, ${credential.transports ?? []}, ${credentialDeviceType}, ${credentialBackedUp}, ${name})`;182    if (token) {183      await tx`DELETE FROM recovery_codes WHERE user_id = ${ch.user_id}`;184      recoveryCodes = Array.from({ length: 8 }, () => randomBytes(6).toString("hex").replace(/(.{4})(.{4})(.{4})/, "$1-$2-$3"));185      for (const c of recoveryCodes) await tx`INSERT INTO recovery_codes (user_id, code_hash) VALUES (${ch.user_id}, ${sha256(c)})`;186    }187  });188  await audit({ userId: ch.user_id, actor: "system", action: token ? `passkey.enrolled.${token.purpose}` : "passkey.added", ip: clientIp(req) });189  if (token) await createSession(ch.user_id, "setup", req);190  return { ok: true, recoveryCodes };191}192193// ── WebAuthn authentication ─────────────────────────────────────────────────────────────────────────194195export async function authenticationOptions() {196  // Discoverable credentials: no allowCredentials list, so the response says nothing about which accounts exist.197  const options = await generateAuthenticationOptions({ rpID: rpId(), userVerification: "required" });198  const [ch] = await sql<{ id: string }[]>`INSERT INTO webauthn_challenges (challenge, kind, expires_at)199    VALUES (${options.challenge}, 'authentication', now() + interval '5 minutes') RETURNING id`;200  return { challengeId: ch.id, options };201}202203export async function verifyAuthentication(input: { challengeId: string; response: AuthenticationResponseJSON }, req: Request) {204  const [ch] = await sql<{ challenge: string }[]>`205    DELETE FROM webauthn_challenges WHERE id = ${input.challengeId} AND kind = 'authentication' AND expires_at > now() RETURNING challenge`;206  const denied = new ApiError(401, "login_failed", "Sign-in failed");207  if (!ch) { await audit({ actor: "system", action: "login.failed", meta: { why: "challenge" }, ip: clientIp(req) }); throw denied; }208  const [cred] = await sql<{ id: string; user_id: string; credential_id: string; public_key: Buffer; counter: string; transports: string[]; role: Role }[]>`209    SELECT a.id, a.user_id, a.credential_id, a.public_key, a.counter, a.transports, u.role210    FROM authenticators a JOIN users u ON u.id = a.user_id211    WHERE a.credential_id = ${String(input.response.id ?? "")} AND u.disabled_at IS NULL`;212  if (!cred) { await audit({ actor: "system", action: "login.failed", meta: { why: "unknown_credential" }, ip: clientIp(req) }); throw denied; }213  let v;214  try {215    v = await verifyAuthenticationResponse({216      response: input.response, expectedChallenge: ch.challenge, expectedOrigin: origin(), expectedRPID: rpId(), requireUserVerification: true,217      credential: { id: cred.credential_id, publicKey: new Uint8Array(cred.public_key), counter: Number(cred.counter), transports: cred.transports as AuthenticatorTransport[] },218    });219  } catch { v = null; }220  if (!v?.verified) { await audit({ userId: cred.user_id, actor: "system", action: "login.failed", meta: { why: "bad_assertion" }, ip: clientIp(req) }); throw denied; }221  await sql`UPDATE authenticators SET counter = ${v.authenticationInfo.newCounter}, last_used_at = now(), backed_up = ${v.authenticationInfo.credentialBackedUp} WHERE id = ${cred.id}`;222  await createSession(cred.user_id, "passkey", req);223  await audit({ userId: cred.user_id, actor: cred.role, action: "login.passkey", ip: clientIp(req) });224  return { ok: true };225}226227/** Recovery: a one-use code opens a session, from which a new passkey can be enrolled. */228export async function loginWithRecoveryCode(code: string, req: Request) {229  const normalized = code.trim().toLowerCase();230  const [row] = await sql<{ id: string; user_id: string }[]>`231    UPDATE recovery_codes r SET used_at = now() FROM users u232    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`;233  if (!row) { await audit({ actor: "system", action: "login.failed", meta: { why: "bad_recovery_code" }, ip: clientIp(req) }); throw new ApiError(401, "login_failed", "Sign-in failed"); }234  await createSession(row.user_id, "recovery_code", req);235  await audit({ userId: row.user_id, actor: "system", action: "login.recovery_code", ip: clientIp(req) });236  return { ok: true };237}238239// ── Device linking (native apps) ────────────────────────────────────────────────────────────────────240// The app asks for a pairing and shows a short code; a browser that is already signed in (with a passkey) approves241// it; the app, which polls with its own secret, then receives a session of its own. The browser never sees the242// app's secret and the app never sees the browser's session.243244const DEVICE_TTL_MIN = 10;245const DEVICE_SESSION_DAYS = 90;246const CODE_ALPHABET = "ABCDEFGHJKMNPQRSTVWXYZ23456789";       // no 0/O, 1/I/L, U247const newUserCode = () => { const b = randomBytes(8); let c = ""; for (let i = 0; i < 8; i++) c += CODE_ALPHABET[b[i] % CODE_ALPHABET.length]; return `${c.slice(0, 4)}-${c.slice(4)}`; };248export const normalizeUserCode = (raw: string) => { const c = raw.toUpperCase().replace(/[^A-Z0-9]/g, ""); return c.length === 8 ? `${c.slice(0, 4)}-${c.slice(4)}` : ""; };249250export async function startDeviceLink(deviceName: string, req: Request) {251  const deviceCode = randomToken(32);252  await sql`DELETE FROM device_links WHERE expires_at < now() - interval '1 day'`;253  for (let attempt = 0; ; attempt++) {254    const userCode = newUserCode();255    try {256      await sql`INSERT INTO device_links (device_hash, user_code, device_name, ip, expires_at)257                VALUES (${sha256(deviceCode)}, ${userCode}, ${deviceName.trim().slice(0, 80)}, ${clientIp(req)}, now() + ${DEVICE_TTL_MIN} * interval '1 minute')`;258      return { deviceCode, userCode, verificationUrl: `${env.appUrl}/appareil?code=${userCode}`, expiresIn: DEVICE_TTL_MIN * 60, interval: 2 };259    } catch (e) { if ((e as { code?: string }).code !== "23505" || attempt >= 4) throw e; }260  }261}262263/** What the approving browser is shown. Says the same thing for an unknown, expired or already decided code. */264export async function deviceLinkInfo(userCode: string) {265  const [d] = await sql<{ device_name: string; created_at: Date; ip: string | null }[]>`266    SELECT device_name, created_at, ip FROM device_links WHERE user_code = ${normalizeUserCode(userCode)} AND expires_at > now() AND decided_at IS NULL`;267  if (!d) throw new ApiError(404, "unknown_code", "This code is unknown or has expired");268  return { deviceName: d.device_name, createdAt: d.created_at, ip: d.ip };269}270271export async function decideDeviceLink(user: UserContext, userCode: string, approve: boolean, req: Request) {272  const [d] = await sql<{ id: string; device_name: string }[]>`273    UPDATE device_links SET approved_by = ${approve ? user.userId : null}, denied = ${!approve}, decided_at = now()274    WHERE user_code = ${normalizeUserCode(userCode)} AND expires_at > now() AND decided_at IS NULL RETURNING id, device_name`;275  if (!d) throw new ApiError(404, "unknown_code", "This code is unknown or has expired");276  await audit({ userId: user.userId, actor: user.role, action: approve ? "device.approved" : "device.denied", entity: "device", entityId: d.id, meta: { name: d.device_name }, ip: clientIp(req) });277  return { ok: true, approved: approve };278}279280/** Polled by the app with its secret. An approved link is consumed exactly once and becomes a session. */281export async function pollDeviceLink(deviceCode: string, req: Request) {282  const hash = sha256(deviceCode);283  const [d] = await sql<{ id: string; expired: boolean; denied: boolean; approved_by: string | null; consumed_at: Date | null }[]>`284    SELECT id, expires_at <= now() AS expired, denied, approved_by, consumed_at FROM device_links WHERE device_hash = ${hash}`;285  if (!d || d.consumed_at) throw new ApiError(404, "unknown_device", "Unknown pairing request");286  if (d.denied) throw new ApiError(403, "denied", "The pairing request was refused");287  if (d.expired) throw new ApiError(410, "expired", "The pairing request has expired");288  if (!d.approved_by) return { status: "pending" as const };289  const [claimed] = await sql<{ approved_by: string }[]>`290    UPDATE device_links l SET consumed_at = now() FROM users u291    WHERE l.id = ${d.id} AND l.consumed_at IS NULL AND u.id = l.approved_by AND u.disabled_at IS NULL RETURNING l.approved_by`;292  if (!claimed) throw new ApiError(404, "unknown_device", "Unknown pairing request");293  const s = await insertSession(claimed.approved_by, "device", req, DEVICE_SESSION_DAYS);294  await audit({ userId: claimed.approved_by, actor: "system", action: "login.device", entity: "device", entityId: d.id, ip: clientIp(req) });295  return { status: "approved" as const, sessionToken: s.token, csrfToken: s.csrf, expiresAt: s.expires };296}297
Files main
Menu

Theme