Repository Public
1import { createHmac, randomBytes } from "node:crypto";2import {3 generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse,4 type AuthenticationResponseJSON, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialRequestOptionsJSON, type RegistrationResponseJSON,5} from "@simplewebauthn/server";6import { sql } from "./db";7import { env } from "./env";8import { sha256 } from "./hash";9import { audit } from "./jobs";10import { log } from "./log";11import { createSession, loginEvent, markReauth, revokeUserSessions, type ClientCtx, type Role, type SessionInfo, type User } from "./auth";1213/**14 * Cérémonies WebAuthn (passkeys). Le serveur ne stocke que la clé publique, l'identifiant et le compteur du justificatif :15 * aucune donnée biométrique ne quitte l'appareil. Chaque challenge vit en base 5 min et ne sert qu'une fois.16 */17export const CHALLENGE_TTL_SECONDS = 5 * 60;18const ALGS = [-8, -7, -257]; // EdDSA, ES256, RS2561920export class AuthError extends Error {21 constructor(public status: number, public code: string, message: string) { super(message); this.name = "AuthError"; }22}23const expectedOrigin = () => new URL(env.publicUrl).origin;24const bytes = (b64url: string) => new Uint8Array(Buffer.from(b64url, "base64url"));2526type Purpose = "register" | "login" | "reauth";27interface ChallengeRow { id: string; challenge: string; purpose: Purpose; user_id: string | null; invitation_hash: string | null }28interface InvitationRow { token_hash: string; email: string; name: string; role: Role; purpose: "enroll" | "recovery"; expires_at: Date; used_at: Date | null }29interface PasskeyRow {30 id: string; user_id: string; credential_id: string; public_key: Buffer; counter: string | number; transports: string[]; device_type: string;31 backed_up: boolean; aaguid: string | null; label: string; created_at: Date; last_used_at: Date | null;32}33export interface PasskeyInfo { id: string; label: string; deviceType: "singleDevice" | "multiDevice"; backedUp: boolean; transports: string[]; createdAt: string; lastUsedAt: string | null }3435const cleanLabel = (s: string | undefined, fallback: string) => (s ?? "").replace(/\s+/g, " ").trim().slice(0, 60) || fallback;3637// ───────────── challenges ─────────────38async function storeChallenge(purpose: Purpose, challenge: string, userId: string | null, invitationHash: string | null) {39 await sql`DELETE FROM webauthn_challenges WHERE expires_at < now() - interval '1 day'`;40 await sql`INSERT INTO webauthn_challenges (challenge, purpose, user_id, invitation_hash, expires_at)41 VALUES (${challenge}, ${purpose}, ${userId}, ${invitationHash}, now() + ${`${CHALLENGE_TTL_SECONDS} seconds`}::interval)`;42}43/** Lit le challenge signé dans clientDataJSON et le consomme de façon atomique : un second passage ne trouve plus rien. */44async function consumeChallenge(purpose: Purpose, response: { response?: { clientDataJSON?: string } }): Promise<ChallengeRow> {45 let challenge: unknown;46 try { challenge = JSON.parse(Buffer.from(String(response?.response?.clientDataJSON ?? ""), "base64url").toString("utf8")).challenge; } catch { /* réponse illisible */ }47 if (typeof challenge !== "string" || !challenge) throw new AuthError(400, "bad_request", "Réponse de l'authentificateur illisible.");48 const [row] = await sql<ChallengeRow[]>`49 UPDATE webauthn_challenges SET used_at = now()50 WHERE challenge = ${challenge} AND purpose = ${purpose} AND used_at IS NULL AND expires_at > now()51 RETURNING id, challenge, purpose, user_id, invitation_hash`;52 if (!row) throw new AuthError(400, "challenge_invalid", "Demande expirée ou déjà utilisée. Recommencez.");53 return row;54}5556// ───────────── invitations ─────────────57async function validInvitation(token: string): Promise<InvitationRow> {58 const [inv] = await sql<InvitationRow[]>`SELECT * FROM invitations WHERE token_hash = ${sha256(token)} AND used_at IS NULL AND expires_at > now()`;59 if (!inv) throw new AuthError(403, "invitation_invalid", "Invitation invalide, expirée ou déjà utilisée.");60 return inv;61}62/** Crée une invitation à usage unique. Le jeton n'est renvoyé qu'ici ; la base ne garde que son SHA-256. */63export async function createInvitation(o: { email: string; name?: string; role: Role; purpose?: "enroll" | "recovery"; ttlMinutes?: number }): Promise<{ token: string; expiresAt: Date }> {64 const token = randomBytes(32).toString("base64url");65 const ttl = Math.min(Math.max(Math.round(o.ttlMinutes ?? 30), 1), 7 * 24 * 60);66 const [r] = await sql<{ expires_at: Date }[]>`67 INSERT INTO invitations (token_hash, email, name, role, purpose, expires_at)68 VALUES (${sha256(token)}, ${o.email.trim().toLowerCase()}, ${o.name ?? ""}, ${o.role}, ${o.purpose ?? "enroll"}, now() + ${`${ttl} minutes`}::interval)69 RETURNING expires_at`;70 return { token, expiresAt: r.expires_at };71}72/** Identifiant WebAuthn du futur utilisateur : dérivé de l'invitation, donc identique entre options et verify. */73const enrollUserHandle = (invitationHash: string) => createHmac("sha256", env.appSecret).update(`webauthn-user:${invitationHash}`).digest().subarray(0, 32).toString("base64url");7475// ───────────── enregistrement ─────────────76export async function registrationOptions(o: { token?: string | null; session?: SessionInfo | null }): Promise<PublicKeyCredentialCreationOptionsJSON> {77 let email: string, name: string, userHandle: string, userId: string | null = null, invitationHash: string | null = null;78 if (o.token) {79 const inv = await validInvitation(o.token);80 invitationHash = inv.token_hash; email = inv.email; name = inv.name;81 const [u] = await sql<{ id: string; name: string; webauthn_user_id: string; disabled: boolean }[]>`SELECT id, name, webauthn_user_id, disabled FROM users WHERE email = ${inv.email}`;82 if (inv.purpose === "enroll") {83 if (u) throw new AuthError(409, "user_exists", "Ce compte existe déjà : demandez une invitation de récupération.");84 userHandle = enrollUserHandle(inv.token_hash);85 } else {86 if (!u || u.disabled) throw new AuthError(403, "invitation_invalid", "Invitation invalide, expirée ou déjà utilisée.");87 userId = u.id; userHandle = u.webauthn_user_id; name = u.name || inv.name;88 }89 } else if (o.session) {90 const [u] = await sql<{ webauthn_user_id: string }[]>`SELECT webauthn_user_id FROM users WHERE id = ${o.session.user.id}`;91 userId = o.session.user.id; email = o.session.user.email; name = o.session.user.name; userHandle = u.webauthn_user_id;92 } else {93 // Aucune auto-inscription.94 throw new AuthError(403, "invitation_required", "L'inscription n'est possible que sur invitation.");95 }96 const existing = userId ? await sql<{ credential_id: string; transports: string[] }[]>`SELECT credential_id, transports FROM passkeys WHERE user_id = ${userId}` : [];97 const options = await generateRegistrationOptions({98 rpName: env.rpName, rpID: env.rpId, userName: email, userDisplayName: name || email, userID: bytes(userHandle),99 attestationType: "none", timeout: 60_000, supportedAlgorithmIDs: ALGS,100 excludeCredentials: existing.map((p) => ({ id: p.credential_id, transports: p.transports })),101 authenticatorSelection: { residentKey: "required", requireResidentKey: true, userVerification: "required" },102 });103 await storeChallenge("register", options.challenge, userId, invitationHash);104 return options;105}106107export interface RegistrationResult { user: User; passkey: PasskeyInfo; /** Présent après une invitation : nouvelle session à poser en cookie. */ sessionToken?: string }108109export async function registrationVerify(o: { token?: string | null; session?: SessionInfo | null; response: RegistrationResponseJSON; label?: string; ctx: ClientCtx }): Promise<RegistrationResult> {110 if (!o.token && !o.session) throw new AuthError(403, "invitation_required", "L'inscription n'est possible que sur invitation.");111 const ch = await consumeChallenge("register", o.response);112 // Le challenge est lié à l'invitation ou à l'utilisateur qui l'a demandé.113 if (o.token ? ch.invitation_hash !== sha256(o.token) : ch.invitation_hash !== null || ch.user_id !== o.session!.user.id)114 throw new AuthError(403, "challenge_invalid", "Demande expirée ou déjà utilisée. Recommencez.");115 if (o.token) await validInvitation(o.token);116117 let info;118 try {119 const v = await verifyRegistrationResponse({120 response: o.response, expectedChallenge: ch.challenge, expectedOrigin: expectedOrigin(), expectedRPID: env.rpId,121 requireUserPresence: true, requireUserVerification: true, supportedAlgorithmIDs: ALGS,122 });123 if (!v.verified || !v.registrationInfo) throw new Error("non vérifié");124 info = v.registrationInfo;125 } catch (e) {126 log("warn", "webauthn.register.refus", { raison: (e as Error).message });127 throw new AuthError(400, "verification_failed", "L'enregistrement de la passkey a été refusé (origine, domaine ou vérification utilisateur).");128 }129 const cred = info.credential;130 const transports = (o.response.response.transports ?? cred.transports ?? []).map(String).slice(0, 8);131 const label = cleanLabel(o.label, info.credentialDeviceType === "multiDevice" ? "Passkey synchronisée" : "Passkey");132133 let user!: User, pk!: PasskeyRow, purpose: "enroll" | "recovery" | "add" = "add";134 try {135 await sql.begin(async (tx) => {136 if (o.token) {137 // Usage unique : seule la première transaction obtient la ligne.138 const [inv] = await tx<InvitationRow[]>`UPDATE invitations SET used_at = now() WHERE token_hash = ${sha256(o.token)} AND used_at IS NULL AND expires_at > now() RETURNING *`;139 if (!inv) throw new AuthError(403, "invitation_invalid", "Invitation invalide, expirée ou déjà utilisée.");140 purpose = inv.purpose;141 if (inv.purpose === "enroll") {142 [user] = await tx<User[]>`INSERT INTO users (email, name, role, webauthn_user_id) VALUES (${inv.email}, ${inv.name}, ${inv.role}, ${enrollUserHandle(inv.token_hash)}) RETURNING id, email, name, role`;143 } else {144 [user] = await tx<User[]>`SELECT id, email, name, role FROM users WHERE email = ${inv.email} AND NOT disabled`;145 if (!user) throw new AuthError(403, "invitation_invalid", "Invitation invalide, expirée ou déjà utilisée.");146 // Récupération : toutes les sessions existantes tombent.147 await tx`UPDATE sessions SET revoked_at = now() WHERE user_id = ${user.id} AND revoked_at IS NULL`;148 }149 } else user = o.session!.user;150 [pk] = await tx<PasskeyRow[]>`151 INSERT INTO passkeys (user_id, credential_id, public_key, counter, transports, device_type, backed_up, aaguid, label)152 VALUES (${user.id}, ${cred.id}, ${Buffer.from(cred.publicKey)}, ${cred.counter}, ${transports}, ${info.credentialDeviceType}, ${info.credentialBackedUp}, ${info.aaguid}, ${label})153 RETURNING *`;154 });155 } catch (e) {156 if (e instanceof AuthError) throw e;157 if ((e as { code?: string }).code === "23505") throw new AuthError(409, "already_registered", "Cette passkey ou ce compte est déjà enregistré.");158 throw e;159 }160 await loginEvent({ userId: user.id, passkeyId: pk.id, kind: "register", ctx: o.ctx, detail: { purpose, deviceType: pk.device_type } });161 await audit(user.id, purpose === "add" ? "passkey.add" : purpose === "enroll" ? "user.enroll" : "user.recover", "passkey", pk.id, { label, deviceType: pk.device_type });162 const result: RegistrationResult = { user, passkey: toInfo(pk) };163 if (o.token) {164 result.sessionToken = (await createSession(user.id, pk.id, o.ctx)).token;165 await sql`UPDATE users SET last_login_at = now() WHERE id = ${user.id}`;166 }167 return result;168}169170// ───────────── connexion et réauthentification ─────────────171/** Connexion sans identifiant : `allowCredentials` vide, l'authentificateur propose ses passkeys du domaine. */172export async function loginOptions(): Promise<PublicKeyCredentialRequestOptionsJSON> {173 const options = await generateAuthenticationOptions({ rpID: env.rpId, userVerification: "required", allowCredentials: [], timeout: 60_000 });174 await storeChallenge("login", options.challenge, null, null);175 return options;176}177export async function reauthOptions(session: SessionInfo): Promise<PublicKeyCredentialRequestOptionsJSON> {178 const own = await sql<{ credential_id: string; transports: string[] }[]>`SELECT credential_id, transports FROM passkeys WHERE user_id = ${session.user.id}`;179 const options = await generateAuthenticationOptions({180 rpID: env.rpId, userVerification: "required", timeout: 60_000, allowCredentials: own.map((p) => ({ id: p.credential_id, transports: p.transports })),181 });182 await storeChallenge("reauth", options.challenge, session.user.id, null);183 return options;184}185186/** Vérifie une assertion (signature, origine, RP ID, UV, compteur) et met la passkey à jour. Journalise tout refus. */187async function verifyAssertion(purpose: "login" | "reauth", response: AuthenticationResponseJSON, ctx: ClientCtx, sessionUserId?: string): Promise<{ user: User; passkeyId: string }> {188 const refuse = async (reason: string, userId: string | null = null, passkeyId: string | null = null): Promise<never> => {189 await loginEvent({ userId, passkeyId, kind: "login_fail", ctx, detail: { purpose, reason } });190 throw new AuthError(401, "auth_failed", "Authentification refusée.");191 };192 let ch: ChallengeRow;193 try { ch = await consumeChallenge(purpose, response); }194 catch (e) { if (e instanceof AuthError) await loginEvent({ kind: "login_fail", ctx, userId: sessionUserId ?? null, detail: { purpose, reason: e.code } }); throw e; }195 if (purpose === "reauth" && ch.user_id !== sessionUserId) return refuse("challenge_user_mismatch", sessionUserId);196197 const [pk] = await sql<(PasskeyRow & { email: string; name: string; role: Role; disabled: boolean; webauthn_user_id: string })[]>`198 SELECT p.*, u.email, u.name, u.role, u.disabled, u.webauthn_user_id FROM passkeys p JOIN users u ON u.id = p.user_id WHERE p.credential_id = ${String(response?.id ?? "")}`;199 if (!pk) return refuse("unknown_credential");200 if (pk.disabled) return refuse("user_disabled", pk.user_id, pk.id);201 if (sessionUserId && pk.user_id !== sessionUserId) return refuse("credential_user_mismatch", sessionUserId, pk.id);202 const handle = response.response?.userHandle;203 if (handle && handle !== pk.webauthn_user_id) return refuse("user_handle_mismatch", pk.user_id, pk.id);204205 let auth;206 try {207 // Compteur passé à 0 : la bibliothèque vérifie la signature, la régression est traitée (et journalisée) juste après.208 const v = await verifyAuthenticationResponse({209 response, expectedChallenge: ch.challenge, expectedOrigin: expectedOrigin(), expectedRPID: env.rpId, requireUserVerification: true,210 credential: { id: pk.credential_id, publicKey: new Uint8Array(pk.public_key), counter: 0, transports: pk.transports },211 });212 if (!v.verified || !v.authenticationInfo.userVerified) throw new Error("non vérifié");213 auth = v.authenticationInfo;214 } catch (e) {215 log("warn", "webauthn.assertion.refus", { purpose, raison: (e as Error).message });216 return refuse("verification_failed", pk.user_id, pk.id);217 }218 const stored = Number(pk.counter);219 if (stored > 0 && auth.newCounter <= stored) {220 // Signature valide mais compteur en recul : justificatif possiblement cloné.221 await loginEvent({ userId: pk.user_id, passkeyId: pk.id, kind: "counter_anomaly", ctx, detail: { purpose, stored, received: auth.newCounter } });222 await audit(pk.user_id, "passkey.counter_anomaly", "passkey", pk.id, { stored, received: auth.newCounter });223 throw new AuthError(401, "auth_failed", "Authentification refusée.");224 }225 await sql`UPDATE passkeys SET counter = ${auth.newCounter}, last_used_at = now(), device_type = ${auth.credentialDeviceType}, backed_up = ${auth.credentialBackedUp} WHERE id = ${pk.id}`;226 return { user: { id: pk.user_id, email: pk.email, name: pk.name, role: pk.role }, passkeyId: pk.id };227}228229export async function loginVerify(o: { response: AuthenticationResponseJSON; ctx: ClientCtx }): Promise<{ user: User; sessionToken: string }> {230 const { user, passkeyId } = await verifyAssertion("login", o.response, o.ctx);231 const { token } = await createSession(user.id, passkeyId, o.ctx);232 await sql`UPDATE users SET last_login_at = now() WHERE id = ${user.id}`;233 await loginEvent({ userId: user.id, passkeyId, kind: "login_ok", ctx: o.ctx });234 return { user, sessionToken: token };235}236export async function reauthVerify(o: { session: SessionInfo; response: AuthenticationResponseJSON; ctx: ClientCtx }): Promise<{ reauthAt: Date }> {237 const { passkeyId } = await verifyAssertion("reauth", o.response, o.ctx, o.session.user.id);238 const reauthAt = await markReauth(o.session.tokenHash);239 await loginEvent({ userId: o.session.user.id, passkeyId, kind: "reauth", ctx: o.ctx });240 return { reauthAt };241}242243// ───────────── gestion des passkeys ─────────────244const toInfo = (p: PasskeyRow): PasskeyInfo => ({245 id: p.id, label: p.label, deviceType: p.device_type === "multiDevice" ? "multiDevice" : "singleDevice", backedUp: p.backed_up, transports: p.transports,246 createdAt: p.created_at.toISOString(), lastUsedAt: p.last_used_at?.toISOString() ?? null,247});248export async function listPasskeys(userId: string): Promise<PasskeyInfo[]> {249 return (await sql<PasskeyRow[]>`SELECT * FROM passkeys WHERE user_id = ${userId} ORDER BY created_at`).map(toInfo);250}251const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;252export async function renamePasskey(user: User, id: string, label: string): Promise<PasskeyInfo> {253 const clean = cleanLabel(label, "");254 if (!clean) throw new AuthError(400, "bad_request", "Le libellé ne peut pas être vide.");255 const [pk] = UUID.test(id) ? await sql<PasskeyRow[]>`UPDATE passkeys SET label = ${clean} WHERE id = ${id} AND user_id = ${user.id} RETURNING *` : [];256 if (!pk) throw new AuthError(404, "not_found", "Passkey introuvable.");257 await audit(user.id, "passkey.rename", "passkey", pk.id, { label: clean });258 return toInfo(pk);259}260/** Supprime une passkey de son propriétaire ; jamais la dernière. Les sessions ouvertes avec elle sont révoquées (sauf la session courante). */261export async function deletePasskey(session: SessionInfo, id: string, ctx: ClientCtx): Promise<void> {262 const user = session.user;263 if (!UUID.test(id)) throw new AuthError(404, "not_found", "Passkey introuvable.");264 let label = "";265 await sql.begin(async (tx) => {266 // Verrou sur l'utilisateur : deux suppressions simultanées ne peuvent pas vider le compte.267 await tx`SELECT id FROM users WHERE id = ${user.id} FOR UPDATE`;268 const all = await tx<{ id: string; label: string }[]>`SELECT id, label FROM passkeys WHERE user_id = ${user.id}`;269 const target = all.find((p) => p.id === id);270 if (!target) throw new AuthError(404, "not_found", "Passkey introuvable.");271 if (all.length <= 1) throw new AuthError(409, "last_passkey", "Impossible de supprimer votre dernière passkey : ajoutez-en une autre d'abord.");272 label = target.label;273 await tx`UPDATE sessions SET revoked_at = now() WHERE passkey_id = ${id} AND revoked_at IS NULL AND token_hash <> ${session.tokenHash}`;274 await tx`DELETE FROM passkeys WHERE id = ${id}`;275 });276 await loginEvent({ userId: user.id, kind: "revoke", ctx, detail: { what: "passkey", label } });277 await audit(user.id, "passkey.delete", "passkey", id, { label });278}279export { revokeUserSessions };280