Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Chat SPBoucher AI8 * File : src/lib/auth/webauthn.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/chat-spboucher-ai11 * Project Website : https://chat.spboucher.ai12 * Created : 2026-11-1713 * Last Modified : 2026-11-1714 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { randomBytes } from "node:crypto";44import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse, type AuthenticationResponseJSON, type RegistrationResponseJSON, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialRequestOptionsJSON } from "@simplewebauthn/server";45import { sql } from "../db";46import { authConfig } from "./config";47import { deviceLabel } from "./device";4849/**50 * WebAuthn ceremonies. All cryptography is done by @simplewebauthn/server; this module only51 * - issues random challenges, stores them server-side and consumes each exactly once,52 * - pins origin, RP id, ceremony type, user presence AND user verification on every verification,53 * - never trusts options or flags coming back from the browser.54 * The server stores the credential id and the public key. Biometric data never leaves the device.55 */56export interface CredentialRow { id: string; public_key: Buffer; counter: number; transports: string[] | null; label: string | null; created_at: Date; device_type: string | null; backed_up: boolean; aaguid: string | null; last_used_at: Date | null; created_via: string; user_agent: string | null }57export type Purpose = "login" | "reauth" | "register:session" | "register:bootstrap" | "register:recovery" | "register:transition";5859export async function listCredentials(): Promise<CredentialRow[]> { return sql<CredentialRow[]>`SELECT * FROM webauthn_credentials ORDER BY created_at`; }6061async function ownerHandle(): Promise<Uint8Array<ArrayBuffer>> {62 const r = await sql<{ user_handle: string | null }[]>`SELECT user_handle FROM owner WHERE id = 1`;63 let h = r[0]?.user_handle;64 if (!h) { h = randomBytes(32).toString("hex"); await sql`INSERT INTO owner (id, username, user_handle) VALUES (1, 'owner', ${h}) ON CONFLICT (id) DO UPDATE SET user_handle = COALESCE(owner.user_handle, EXCLUDED.user_handle)`; h = (await sql<{ user_handle: string }[]>`SELECT user_handle FROM owner WHERE id = 1`)[0].user_handle; }65 return new Uint8Array(Buffer.from(h, "hex"));66}6768async function storeChallenge(o: { challenge: string; kind: "registration" | "authentication"; purpose: Purpose; sessionId?: string | null; grantId?: string | null; ip?: string | null }): Promise<string> {69 const id = randomBytes(24).toString("base64url");70 await sql`INSERT INTO auth_challenges (id, challenge, kind, purpose, session_id, grant_id, ip, expires_at)71 VALUES (${id}, ${o.challenge}, ${o.kind}, ${o.purpose}, ${o.sessionId ?? null}, ${o.grantId ?? null}, ${o.ip ?? null}, now() + make_interval(secs => ${authConfig.challengeTtlSec}))`;72 if (Math.random() < 0.05) void sql`DELETE FROM auth_challenges WHERE expires_at < now() - interval '1 day'`.catch(() => {});73 return id;74}7576/** Atomically takes a challenge out of circulation. A second call with the same id returns null (replay). */77async function consumeChallenge(id: string | undefined | null, kind: "registration" | "authentication"): Promise<{ challenge: string; purpose: Purpose; session_id: string | null; grant_id: string | null } | null> {78 if (!id || !/^[A-Za-z0-9_-]{32}$/.test(id)) return null;79 const r = await sql<{ challenge: string; purpose: Purpose; session_id: string | null; grant_id: string | null }[]>`UPDATE auth_challenges SET consumed_at = now()80 WHERE id = ${id} AND kind = ${kind} AND consumed_at IS NULL AND expires_at > now() RETURNING challenge, purpose, session_id, grant_id`;81 return r[0] ?? null;82}8384export class CeremonyError extends Error { constructor(public reason: string) { super("Vérification refusée"); } }8586// ---------------------------------------------------------------- authentication87export async function beginAuthentication(o: { purpose: "login" | "reauth"; sessionId?: string | null; ip?: string | null }): Promise<{ options: PublicKeyCredentialRequestOptionsJSON; ceremonyId: string }> {88 // login: discoverable credentials only (empty allowCredentials) — the response is identical whether or not a passkey89 // exists, so it reveals nothing. reauth: the caller already holds a session, so its passkeys can be listed.90 const allow = o.purpose === "reauth" ? (await listCredentials()).map(c => ({ id: c.id, transports: (c.transports ?? undefined) as never })) : [];91 const options = await generateAuthenticationOptions({ rpID: authConfig.rpID, userVerification: "required", allowCredentials: allow, timeout: authConfig.challengeTtlSec * 1000 });92 const ceremonyId = await storeChallenge({ challenge: options.challenge, kind: "authentication", purpose: o.purpose, sessionId: o.sessionId, ip: o.ip });93 return { options, ceremonyId };94}9596export async function finishAuthentication(o: { response: AuthenticationResponseJSON; ceremonyId: string | undefined | null; expectPurpose: "login" | "reauth"; sessionId?: string | null }): Promise<{ credential: CredentialRow }> {97 const ch = await consumeChallenge(o.ceremonyId, "authentication");98 if (!ch) throw new CeremonyError("challenge-missing-expired-or-replayed");99 if (ch.purpose !== o.expectPurpose) throw new CeremonyError("challenge-purpose-mismatch");100 if (o.expectPurpose === "reauth" && ch.session_id !== (o.sessionId ?? null)) throw new CeremonyError("challenge-session-mismatch");101 if (typeof o.response?.id !== "string" || o.response.id.length > 1024) throw new CeremonyError("malformed-response");102 const cred = (await sql<CredentialRow[]>`SELECT * FROM webauthn_credentials WHERE id = ${o.response.id}`)[0];103 if (!cred) throw new CeremonyError("unknown-credential");104 const handle = o.response.response?.userHandle;105 if (handle && Buffer.from(handle, "base64url").toString("hex") !== Buffer.from(await ownerHandle()).toString("hex")) throw new CeremonyError("user-handle-mismatch");106 let v: Awaited<ReturnType<typeof verifyAuthenticationResponse>>;107 try {108 v = await verifyAuthenticationResponse({109 response: o.response, expectedChallenge: ch.challenge, expectedOrigin: authConfig.origins, expectedRPID: authConfig.rpID, expectedType: "webauthn.get",110 requireUserVerification: true, // user presence is always enforced by the library111 credential: { id: cred.id, publicKey: new Uint8Array(cred.public_key), counter: Number(cred.counter), transports: (cred.transports ?? undefined) as never },112 });113 } catch (e) { throw new CeremonyError("verification-error:" + String((e as Error).message).slice(0, 80)); }114 if (!v.verified || !v.authenticationInfo.userVerified) throw new CeremonyError("not-verified");115 await sql`UPDATE webauthn_credentials SET counter = ${v.authenticationInfo.newCounter}, last_used_at = now(), backed_up = ${v.authenticationInfo.credentialBackedUp} WHERE id = ${cred.id}`;116 return { credential: cred };117}118119// ---------------------------------------------------------------- registration120export async function beginRegistration(o: { purpose: Exclude<Purpose, "login" | "reauth">; sessionId?: string | null; grantId?: string | null; ip?: string | null }): Promise<{ options: PublicKeyCredentialCreationOptionsJSON; ceremonyId: string }> {121 const existing = await listCredentials();122 const options = await generateRegistrationOptions({123 rpName: authConfig.rpName, rpID: authConfig.rpID, userID: await ownerHandle(), userName: "proprietaire", userDisplayName: "Propriétaire",124 attestationType: "none", timeout: authConfig.challengeTtlSec * 1000,125 excludeCredentials: existing.map(c => ({ id: c.id, transports: (c.transports ?? undefined) as never })),126 // discoverable credential (so sign-in needs no identifier) with mandatory user verification: Face ID / Touch ID /127 // device unlock. No authenticatorAttachment: platform passkeys, cross-device (QR) and security keys are all allowed.128 authenticatorSelection: { residentKey: "required", userVerification: "required" },129 });130 const ceremonyId = await storeChallenge({ challenge: options.challenge, kind: "registration", purpose: o.purpose, sessionId: o.sessionId, grantId: o.grantId, ip: o.ip });131 return { options, ceremonyId };132}133134export async function finishRegistration(o: { response: RegistrationResponseJSON; ceremonyId: string | undefined | null; expectPurpose: Exclude<Purpose, "login" | "reauth">; sessionId?: string | null; grantId?: string | null; label?: string | null; userAgent?: string | null }): Promise<{ credential: CredentialRow }> {135 const ch = await consumeChallenge(o.ceremonyId, "registration");136 if (!ch) throw new CeremonyError("challenge-missing-expired-or-replayed");137 if (ch.purpose !== o.expectPurpose || ch.session_id !== (o.sessionId ?? null) || ch.grant_id !== (o.grantId ?? null)) throw new CeremonyError("challenge-context-mismatch");138 let v: Awaited<ReturnType<typeof verifyRegistrationResponse>>;139 try {140 v = await verifyRegistrationResponse({ response: o.response, expectedChallenge: ch.challenge, expectedOrigin: authConfig.origins, expectedRPID: authConfig.rpID, expectedType: "webauthn.create", requireUserPresence: true, requireUserVerification: true });141 } catch (e) { throw new CeremonyError("verification-error:" + String((e as Error).message).slice(0, 80)); }142 if (!v.verified || !v.registrationInfo?.userVerified) throw new CeremonyError("not-verified");143 const info = v.registrationInfo; const c = info.credential;144 const via = o.expectPurpose.split(":")[1];145 const label = (o.label?.trim() || deviceLabel(o.userAgent)).slice(0, 60);146 const rows = await sql<CredentialRow[]>`INSERT INTO webauthn_credentials (id, public_key, counter, transports, label, device_type, backed_up, aaguid, created_via, user_agent)147 VALUES (${c.id}, ${Buffer.from(c.publicKey)}, ${c.counter}, ${(o.response.response?.transports ?? c.transports ?? []) as string[]}, ${label}, ${info.credentialDeviceType}, ${info.credentialBackedUp}, ${info.aaguid}, ${via}, ${o.userAgent?.slice(0, 300) ?? null})148 ON CONFLICT (id) DO NOTHING RETURNING *`;149 if (!rows[0]) throw new CeremonyError("credential-already-registered");150 return { credential: rows[0] };151}152