SPB Git

Repository Public

auth.ts 17.7 KB 248 lines typescript

1/**2 * Studio identity: editors, passkeys (WebAuthn), one-time enrolment tokens and server-side sessions.3 * Nothing here depends on Next.js, so the operator's command-line scripts and the tests use the same code.4 * There is no password anywhere, and no learner account: these tables only ever hold the instructor and5 * the editors he explicitly authorised.6 */7import {8  generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse,9  type AuthenticationResponseJSON, type AuthenticatorTransport, type RegistrationResponseJSON,10} from "@simplewebauthn/server";11import { env } from "../lib/env";12import { audit } from "./audit";13import { randomId, randomToken, safeEqual, sha256 } from "./crypto";14import { all, get, now, run, tx } from "./db";15import { ApiError } from "./http";1617export const ROLES = ["owner", "publisher", "author"] as const;18export type Role = (typeof ROLES)[number];19export type Permission = "edit" | "publish" | "admin";20/** Least privilege: an author writes drafts, a publisher also decides what goes public, the owner also manages access. */21const GRANTS: Record<Role, Permission[]> = { owner: ["edit", "publish", "admin"], publisher: ["edit", "publish"], author: ["edit"] };22export const can = (role: Role, permission: Permission) => GRANTS[role].includes(permission);23export const ROLE_LABEL: Record<Role, string> = { owner: "Propriétaire", publisher: "Éditeur-publieur", author: "Auteur" };2425export const SESSION_COOKIE = "atlas_studio", PREAUTH_COOKIE = "atlas_preauth";26export const SESSION_HOURS = 12, IDLE_MINUTES = 120;27const RP_NAME = "ATLAS IA — studio";2829/* ---- Editors ---- */3031export interface Editor { id: string; name: string; role: Role; created_at: string; disabled_at: string | null }32export const listEditors = () => all<Editor & { passkeys: number; sessions: number }>(33  `SELECT e.*, (SELECT count(*) FROM credentials c WHERE c.editor_id = e.id) AS passkeys,34          (SELECT count(*) FROM auth_sessions s WHERE s.editor_id = e.id AND s.expires_at > ?) AS sessions35   FROM editors e ORDER BY e.created_at`, now());36export const getEditor = (id: string) => get<Editor>("SELECT * FROM editors WHERE id = ?", id) ?? null;37const activeOwners = () => get<{ n: number }>("SELECT count(*) AS n FROM editors e WHERE role = 'owner' AND disabled_at IS NULL AND EXISTS (SELECT 1 FROM credentials c WHERE c.editor_id = e.id)")!.n;3839export function createEditor(name: string, role: Role, actor: string): Editor {40  const clean = name.trim().replace(/\s+/g, " ").slice(0, 80);41  if (clean.length < 2) throw new ApiError(400, "bad_name", "Le nom doit compter au moins deux caractères.");42  if (!ROLES.includes(role)) throw new ApiError(400, "bad_role", "Rôle inconnu.");43  const editor: Editor = { id: `ed_${randomId(6)}`, name: clean, role, created_at: now(), disabled_at: null };44  run("INSERT INTO editors (id, name, role, created_at) VALUES (?, ?, ?, ?)", editor.id, editor.name, editor.role, editor.created_at);45  audit("editor.created", { actor, target: `editor:${editor.id}`, after: { name: editor.name, role: editor.role } });46  return editor;47}4849/** Changes a role or disables an editor. The last owner able to sign in can be neither demoted nor disabled. */50export function updateEditor(id: string, change: { role?: Role; disabled?: boolean; name?: string }, actor: string): Editor {51  return tx(() => {52    const before = getEditor(id);53    if (!before) throw new ApiError(404, "not_found", "Éditeur introuvable.");54    const role = change.role ?? before.role, disabled = change.disabled ?? Boolean(before.disabled_at);55    if (!ROLES.includes(role)) throw new ApiError(400, "bad_role", "Rôle inconnu.");56    const losesOwner = before.role === "owner" && !before.disabled_at && (role !== "owner" || disabled);57    if (losesOwner && activeOwners() <= 1 && get("SELECT 1 FROM credentials WHERE editor_id = ?", id)) throw new ApiError(409, "last_owner", "Impossible : c'est le dernier propriétaire capable de se connecter.");58    const name = change.name?.trim().replace(/\s+/g, " ").slice(0, 80) || before.name;59    run("UPDATE editors SET role = ?, name = ?, disabled_at = ? WHERE id = ?", role, name, disabled ? (before.disabled_at ?? now()) : null, id);60    if (disabled) run("DELETE FROM auth_sessions WHERE editor_id = ?", id); // a disabled editor is signed out everywhere, at once61    audit(disabled && !before.disabled_at ? "editor.disabled" : "editor.updated", { actor, target: `editor:${id}`, before: { name: before.name, role: before.role, disabled: Boolean(before.disabled_at) }, after: { name, role, disabled } });62    return getEditor(id)!;63  });64}6566/* ---- Enrolment tokens (first passkey from the server's shell; later ones from the studio, by the owner) ---- */6768export type TokenPurpose = "setup" | "recovery";6970/** Issues a single-use enrolment token. Only its SHA-256 is stored; the raw value is returned once. */71export function issueEnrollToken(editorId: string, purpose: TokenPurpose, actor: string, ttlMinutes = 30): { raw: string; expiresAt: string } {72  const editor = getEditor(editorId);73  if (!editor || editor.disabled_at) throw new ApiError(404, "not_found", "Éditeur introuvable ou désactivé.");74  const ttl = Math.min(1440, Math.max(5, Math.floor(ttlMinutes) || 30));75  const raw = randomToken(32), expiresAt = new Date(Date.now() + ttl * 60_000).toISOString();76  tx(() => {77    run("UPDATE enroll_tokens SET used_at = ? WHERE editor_id = ? AND used_at IS NULL", now(), editorId); // one live token per editor78    run("INSERT INTO enroll_tokens (token_hash, editor_id, purpose, created_at, created_by, expires_at) VALUES (?, ?, ?, ?, ?, ?)", sha256(raw), editorId, purpose, now(), actor, expiresAt);79    audit(`auth.enroll_token.issued.${purpose}`, { actor, target: `editor:${editorId}`, detail: { expiresAt } });80  });81  return { raw, expiresAt };82}8384interface TokenRow { token_hash: string; editor_id: string; purpose: TokenPurpose }85function validToken(raw: unknown): (TokenRow & { editor: Editor }) | null {86  if (typeof raw !== "string" || raw.length < 20 || raw.length > 200) return null;87  const t = get<TokenRow>("SELECT token_hash, editor_id, purpose FROM enroll_tokens WHERE token_hash = ? AND used_at IS NULL AND expires_at > ?", sha256(raw), now());88  const editor = t ? getEditor(t.editor_id) : null;89  return t && editor && !editor.disabled_at ? { ...t, editor } : null;90}91export const enrollTokenInfo = (raw: unknown) => { const t = validToken(raw); return t ? { purpose: t.purpose, name: t.editor.name, role: t.editor.role } : null; };92export const credentialCount = () => get<{ n: number }>("SELECT count(*) AS n FROM credentials")!.n;9394/* ---- Sessions (server-side; the cookie only carries a random token whose hash is the key) ---- */9596export interface StudioSession { editor: Editor; csrf: string; tokenHash: string; expiresAt: string }97interface SessionRow { token_hash: string; editor_id: string; csrf: string; expires_at: string; last_seen_at: string }9899/** Resolves a raw session token. Expired, idle or orphaned sessions are deleted as they are met. */100export function sessionFromToken(raw: string | undefined | null, at = Date.now()): StudioSession | null {101  if (!raw || raw.length > 200) return null;102  const hash = sha256(raw);103  const r = get<SessionRow>("SELECT token_hash, editor_id, csrf, expires_at, last_seen_at FROM auth_sessions WHERE token_hash = ?", hash);104  if (!r) return null;105  const editor = getEditor(r.editor_id);106  if (!editor || editor.disabled_at || Date.parse(r.expires_at) <= at || at - Date.parse(r.last_seen_at) > IDLE_MINUTES * 60_000) {107    run("DELETE FROM auth_sessions WHERE token_hash = ?", hash);108    return null;109  }110  if (at - Date.parse(r.last_seen_at) > 60_000) run("UPDATE auth_sessions SET last_seen_at = ? WHERE token_hash = ?", new Date(at).toISOString(), hash);111  return { editor, csrf: r.csrf, tokenHash: hash, expiresAt: r.expires_at };112}113114/** A new session identifier at every authentication; the one the browser held before is revoked (no fixation). */115export function issueSession(editorId: string, meta: { ip?: string; ua?: string; previous?: string | null } = {}): { token: string; expires: Date } {116  const token = randomToken(32), expires = new Date(Date.now() + SESSION_HOURS * 3_600_000);117  if (meta.previous) run("DELETE FROM auth_sessions WHERE token_hash = ?", sha256(meta.previous));118  run("DELETE FROM auth_sessions WHERE expires_at <= ?", now());119  run("INSERT INTO auth_sessions (token_hash, editor_id, csrf, created_at, expires_at, last_seen_at, ip, ua) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",120    sha256(token), editorId, randomToken(24), now(), expires.toISOString(), now(), meta.ip ?? null, (meta.ua ?? "").slice(0, 300));121  return { token, expires };122}123export const revokeSession = (raw: string | undefined | null) => { if (raw) run("DELETE FROM auth_sessions WHERE token_hash = ?", sha256(raw)); };124125export interface SessionInfo { id: string; editor_id: string; created_at: string; last_seen_at: string; expires_at: string; ip: string | null; ua: string | null }126/** Sessions are listed by a short prefix of their hash: enough to revoke one, useless to impersonate it. */127export const listSessions = () => all<SessionInfo>("SELECT substr(token_hash, 1, 16) AS id, editor_id, created_at, last_seen_at, expires_at, ip, ua FROM auth_sessions WHERE expires_at > ? ORDER BY last_seen_at DESC", now());128export function revokeSessions(o: { id?: string; editorId?: string }, actor: string): number {129  const r = o.id ? run("DELETE FROM auth_sessions WHERE substr(token_hash, 1, 16) = ?", o.id) : o.editorId ? run("DELETE FROM auth_sessions WHERE editor_id = ?", o.editorId) : { changes: 0 };130  audit("auth.sessions.revoked", { actor, target: o.editorId ? `editor:${o.editorId}` : `session:${o.id}`, detail: { count: Number(r.changes) } });131  return Number(r.changes);132}133134/* ---- Passkeys ---- */135136export interface Passkey { id: string; editor_id: string; name: string; device_type: string | null; backed_up: number | null; created_at: string; last_used_at: string | null }137export const listPasskeys = () => all<Passkey>("SELECT id, editor_id, name, device_type, backed_up, created_at, last_used_at FROM credentials ORDER BY created_at");138139export function revokePasskey(id: string, actor: string): void {140  tx(() => {141    const c = get<Passkey>("SELECT id, editor_id, name FROM credentials WHERE id = ?", id);142    if (!c) throw new ApiError(404, "not_found", "Clé d'accès introuvable.");143    const editor = getEditor(c.editor_id)!;144    const left = get<{ n: number }>("SELECT count(*) AS n FROM credentials WHERE editor_id = ?", c.editor_id)!.n - 1;145    if (editor.role === "owner" && !editor.disabled_at && left === 0 && activeOwners() <= 1) throw new ApiError(409, "last_owner", "Impossible : c'est la dernière clé du dernier propriétaire. Enrôlez-en une autre d'abord.");146    run("DELETE FROM credentials WHERE id = ?", id);147    run("DELETE FROM auth_sessions WHERE editor_id = ?", c.editor_id); // sessions opened with a revoked key do not survive it148    audit("auth.passkey.revoked", { actor, target: `editor:${c.editor_id}`, detail: { name: c.name } });149  });150}151152/* ---- Challenges: single use, short-lived, bound to the browser that asked ---- */153154export const bindingOf = (preauthCookie: string) => sha256(`preauth:${preauthCookie}`);155156function storeChallenge(challenge: string, kind: "registration" | "authentication", binding: string): string {157  const id = randomToken(16);158  run("DELETE FROM challenges WHERE expires_at <= ?", now());159  run("INSERT INTO challenges (id, challenge, kind, binding, expires_at) VALUES (?, ?, ?, ?, ?)", id, challenge, kind, binding, new Date(Date.now() + 5 * 60_000).toISOString());160  return id;161}162/** Deleted as it is read, whatever happens next: a captured ceremony answer cannot be replayed. */163function consumeChallenge(id: unknown, kind: string, binding: string | null): string | null {164  if (typeof id !== "string") return null;165  const r = get<{ challenge: string; binding: string }>("DELETE FROM challenges WHERE id = ? AND kind = ? AND expires_at > ? RETURNING challenge, binding", id, kind, now());166  return r && binding && safeEqual(r.binding, binding) ? r.challenge : null;167}168169/** Lock-out derived from the audit trail, so it survives restarts: 5 failures → 1 min, 10 → 5 min, 20 → 1 h. */170export function assertNotLockedOut(ip: string): void {171  const r = get<{ n: number; last: string | null }>("SELECT count(*) AS n, max(at) AS last FROM audit WHERE action = 'auth.login.failed' AND ip = ? AND at > ?", ip, new Date(Date.now() - 3_600_000).toISOString())!;172  if (!r.last || r.n < 5) return;173  const wait = r.n >= 20 ? 3600 : r.n >= 10 ? 300 : 60, left = Math.ceil(wait - (Date.now() - Date.parse(r.last)) / 1000);174  if (left > 0) throw new ApiError(429, "locked_out", "Trop de tentatives refusées. Réessayez plus tard.", { retryAfterSeconds: left });175}176177const BAD_TOKEN = () => new ApiError(403, "invalid_enroll_token", "Ce lien d'enrôlement est invalide, expiré ou déjà utilisé.");178interface CredRow { id: string; editor_id: string; public_key: Uint8Array; counter: number; transports: string }179180export async function registrationOptions(rawToken: unknown, binding: string) {181  const token = validToken(rawToken);182  if (!token) throw BAD_TOKEN();183  const existing = all<CredRow>("SELECT id, transports FROM credentials WHERE editor_id = ?", token.editor_id);184  const options = await generateRegistrationOptions({185    rpName: RP_NAME, rpID: env.rpId, userName: token.editor.name, userDisplayName: token.editor.name,186    userID: new TextEncoder().encode(token.editor_id), attestationType: "none",187    excludeCredentials: token.purpose === "recovery" ? [] : existing.map((c) => ({ id: c.id, transports: JSON.parse(c.transports) as AuthenticatorTransport[] })),188    // A discoverable credential with user verification: Touch ID, Face ID or the device passcode.189    authenticatorSelection: { residentKey: "required", userVerification: "required" },190    supportedAlgorithmIDs: [-7, -8, -257],191  });192  return { challengeId: storeChallenge(options.challenge, "registration", binding), options };193}194195export async function verifyRegistration(input: { challengeId?: unknown; response?: unknown; name?: unknown; token?: unknown }, binding: string | null, ip: string): Promise<Editor> {196  const challenge = consumeChallenge(input.challengeId, "registration", binding);197  if (!challenge) throw new ApiError(400, "challenge_expired", "La demande d'enrôlement a expiré. Recommencez.");198  const token = validToken(input.token);199  if (!token) throw BAD_TOKEN();200  const failed = () => new ApiError(400, "registration_failed", "La clé d'accès n'a pas pu être vérifiée.");201  let v;202  try { v = await verifyRegistrationResponse({ response: input.response as RegistrationResponseJSON, expectedChallenge: challenge, expectedOrigin: env.studioOrigin, expectedRPID: env.rpId, requireUserVerification: true }); }203  catch { throw failed(); }204  if (!v.verified || !v.registrationInfo) throw failed();205  const { credential, credentialDeviceType, credentialBackedUp } = v.registrationInfo;206  tx(() => {207    const used = run("UPDATE enroll_tokens SET used_at = ? WHERE token_hash = ? AND used_at IS NULL", now(), token.token_hash);208    if (Number(used.changes) !== 1) throw BAD_TOKEN();209    if (token.purpose === "recovery") { // a recovery replaces every earlier passkey of that editor and signs their devices out210      run("DELETE FROM credentials WHERE editor_id = ?", token.editor_id);211      run("DELETE FROM auth_sessions WHERE editor_id = ?", token.editor_id);212    }213    run("INSERT INTO credentials (id, editor_id, public_key, counter, transports, name, device_type, backed_up, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",214      credential.id, token.editor_id, Buffer.from(credential.publicKey), credential.counter, JSON.stringify(credential.transports ?? []),215      (typeof input.name === "string" ? input.name : "").trim().slice(0, 60) || "Clé d'accès", credentialDeviceType, credentialBackedUp ? 1 : 0, now());216    audit(`auth.passkey.enrolled.${token.purpose}`, { actor: token.editor_id, target: `editor:${token.editor_id}`, ip });217  });218  return token.editor;219}220221export async function authenticationOptions(binding: string) {222  const options = await generateAuthenticationOptions({ rpID: env.rpId, userVerification: "required" });223  return { challengeId: storeChallenge(options.challenge, "authentication", binding), options };224}225226export async function verifyAuthentication(input: { challengeId?: unknown; response?: unknown }, binding: string | null, ip: string): Promise<Editor> {227  assertNotLockedOut(ip);228  const fail = (why: string): never => { audit("auth.login.failed", { ip, detail: { why } }); throw new ApiError(401, "login_failed", "Connexion refusée."); };229  const challenge = consumeChallenge(input.challengeId, "authentication", binding);230  if (!challenge) throw new ApiError(400, "challenge_expired", "La demande de connexion a expiré. Recommencez.");231  const response = input.response as AuthenticationResponseJSON;232  const cred = get<CredRow>("SELECT id, editor_id, public_key, counter, transports FROM credentials WHERE id = ?", typeof response?.id === "string" ? response.id : "");233  if (!cred) return fail("unknown_credential");234  const editor = getEditor(cred.editor_id);235  if (!editor || editor.disabled_at) return fail("editor_disabled");236  let v;237  try {238    v = await verifyAuthenticationResponse({239      response, expectedChallenge: challenge, expectedOrigin: env.studioOrigin, expectedRPID: env.rpId, requireUserVerification: true,240      credential: { id: cred.id, publicKey: new Uint8Array(cred.public_key), counter: cred.counter, transports: JSON.parse(cred.transports) as AuthenticatorTransport[] },241    });242  } catch { return fail("verification_error"); }243  if (!v.verified) return fail("not_verified");244  run("UPDATE credentials SET counter = ?, last_used_at = ? WHERE id = ?", v.authenticationInfo.newCounter, now(), cred.id);245  audit("auth.login.ok", { actor: editor.id, ip });246  return editor;247}248
Files main
Menu

Theme