Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Note SPBoucher AI8 * File : src/lib/auth/webauthn.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/note-spboucher-ai11 * Project Website : https://note.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 */4243/**44 * WebAuthn ceremonies (SimpleWebAuthn server 14). No hand-rolled crypto: the library checks the challenge, origin, RP ID hash,45 * ceremony type, signature, user presence and user verification; this file owns challenge storage (random, single use, 5 minutes,46 * bound to the requesting browser by an HttpOnly cookie) and the credential table.47 * Stored per passkey: credential id, COSE public key, signature counter, transports, device type, backup flag, AAGUID, label. Nothing biometric48 * ever reaches the server — the authenticator only asserts "user verified".49 */50import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";51import type { AuthenticationResponseJSON, RegistrationResponseJSON, WebAuthnCredential } from "@simplewebauthn/server";52type AuthenticatorTransportFuture = NonNullable<WebAuthnCredential["transports"]>[number];53import { and, eq, lt } from "drizzle-orm";54import { db, schema } from "../../db/index";55import { allowedOrigins, CHALLENGE_TTL_MS, RP_NAME, rpId } from "./config";5657export type CeremonyKind = "login" | "reauth" | "register" | "enroll";58export class CeremonyError extends Error { constructor(public code: string, message: string) { super(message); } }5960async function saveChallenge(kind: CeremonyKind, challenge: string, ctx: { userId?: string | null; sessionId?: string | null; enrollmentId?: string | null }) {61 if (Math.random() < 0.1) await db.delete(schema.webauthnChallenges).where(lt(schema.webauthnChallenges.expiresAt, new Date())).catch(() => {});62 const [row] = await db.insert(schema.webauthnChallenges).values({ kind, challenge, userId: ctx.userId ?? null, sessionId: ctx.sessionId ?? null, enrollmentId: ctx.enrollmentId ?? null, expiresAt: new Date(Date.now() + CHALLENGE_TTL_MS) }).returning({ id: schema.webauthnChallenges.id });63 return row.id;64}65/** Atomic single use: the row is deleted by the same statement that reads it. Expired, unknown, wrong-kind or replayed ids yield a CeremonyError. */66async function takeChallenge(id: string | null | undefined, kind: CeremonyKind) {67 if (!id || !/^[0-9a-f-]{36}$/.test(id)) throw new CeremonyError("challenge_missing", "No pending passkey request for this browser. Start again.");68 const [row] = await db.delete(schema.webauthnChallenges).where(and(eq(schema.webauthnChallenges.id, id), eq(schema.webauthnChallenges.kind, kind))).returning();69 if (!row) throw new CeremonyError("challenge_used", "This passkey request was already used or does not exist. Start again.");70 if (!row.expiresAt || row.expiresAt.getTime() < Date.now()) throw new CeremonyError("challenge_expired", "This passkey request expired. Start again.");71 return row;72}73const toUint8 = (b64url: string) => new Uint8Array(Buffer.from(b64url, "base64url"));7475// ---------- authentication (sign-in and step-up)76export async function authenticationOptions(kind: "login" | "reauth", ctx: { userId?: string | null; sessionId?: string | null }) {77 const creds = kind === "reauth" ? await db.select({ id: schema.webauthnCredentials.id, transports: schema.webauthnCredentials.transports }).from(schema.webauthnCredentials) : [];78 const options = await generateAuthenticationOptions({ rpID: rpId(), userVerification: "required", timeout: 120_000, allowCredentials: creds.map((c) => ({ id: c.id, transports: (c.transports ?? []) as AuthenticatorTransportFuture[] })) });79 const challengeId = await saveChallenge(kind, options.challenge, ctx);80 return { options, challengeId };81}82export async function verifyAuthentication(kind: "login" | "reauth", challengeId: string | null | undefined, response: AuthenticationResponseJSON, expect: { sessionId?: string | null } = {}) {83 const ch = await takeChallenge(challengeId, kind);84 if (kind === "reauth" && ch.sessionId !== (expect.sessionId ?? null)) throw new CeremonyError("challenge_mismatch", "This passkey request belongs to another session.");85 if (!response || typeof response.id !== "string") throw new CeremonyError("bad_response", "Malformed passkey response.");86 const [cred] = await db.select().from(schema.webauthnCredentials).where(eq(schema.webauthnCredentials.id, response.id)).limit(1);87 if (!cred) throw new CeremonyError("unknown_credential", "This passkey is not registered for this site.");88 let result;89 try {90 result = await verifyAuthenticationResponse({ response, expectedChallenge: ch.challenge, expectedOrigin: allowedOrigins(), expectedRPID: rpId(), expectedType: "webauthn.get", requireUserVerification: true, credential: { id: cred.id, publicKey: toUint8(cred.publicKey), counter: cred.counter, transports: (cred.transports ?? []) as AuthenticatorTransportFuture[] } });91 } catch (e) { throw new CeremonyError("verification_failed", (e as Error).message); }92 if (!result.verified || !result.authenticationInfo.userVerified) throw new CeremonyError("verification_failed", "The passkey signature could not be verified.");93 await db.update(schema.webauthnCredentials).set({ counter: result.authenticationInfo.newCounter, lastUsedAt: new Date(), backedUp: result.authenticationInfo.credentialBackedUp, deviceType: result.authenticationInfo.credentialDeviceType }).where(eq(schema.webauthnCredentials.id, cred.id));94 return { credentialId: cred.id, userId: cred.userId, label: cred.label };95}9697// ---------- registration (bootstrap / recovery window, or a signed-in owner with a fresh verification)98export async function registrationOptions(kind: "register" | "enroll", owner: { id: string; username: string; displayName: string }, ctx: { sessionId?: string | null; enrollmentId?: string | null }) {99 const existing = await db.select({ id: schema.webauthnCredentials.id, transports: schema.webauthnCredentials.transports }).from(schema.webauthnCredentials);100 const options = await generateRegistrationOptions({101 rpName: RP_NAME, rpID: rpId(), userName: owner.username, userDisplayName: owner.displayName, userID: new Uint8Array(Buffer.from(owner.id.replace(/-/g, ""), "hex")),102 attestationType: "none", timeout: 120_000,103 excludeCredentials: existing.map((c) => ({ id: c.id, transports: (c.transports ?? []) as AuthenticatorTransportFuture[] })),104 authenticatorSelection: { residentKey: "required", requireResidentKey: true, userVerification: "required" },105 });106 const challengeId = await saveChallenge(kind, options.challenge, { userId: owner.id, ...ctx });107 return { options, challengeId };108}109export async function verifyRegistration(kind: "register" | "enroll", challengeId: string | null | undefined, response: RegistrationResponseJSON, expect: { userId: string; sessionId?: string | null; enrollmentId?: string | null; label: string }) {110 const ch = await takeChallenge(challengeId, kind);111 if (ch.userId !== expect.userId) throw new CeremonyError("challenge_mismatch", "This passkey request belongs to another context.");112 if (kind === "register" && ch.sessionId !== (expect.sessionId ?? null)) throw new CeremonyError("challenge_mismatch", "This passkey request belongs to another session.");113 if (kind === "enroll" && ch.enrollmentId !== (expect.enrollmentId ?? null)) throw new CeremonyError("challenge_mismatch", "This passkey request belongs to another enrollment window.");114 let result;115 try {116 result = await verifyRegistrationResponse({ response, expectedChallenge: ch.challenge, expectedOrigin: allowedOrigins(), expectedRPID: rpId(), expectedType: "webauthn.create", requireUserPresence: true, requireUserVerification: true });117 } catch (e) { throw new CeremonyError("verification_failed", (e as Error).message); }118 if (!result.verified || !result.registrationInfo?.userVerified) throw new CeremonyError("verification_failed", "The new passkey could not be verified.");119 const info = result.registrationInfo;120 const row = { id: info.credential.id, userId: expect.userId, publicKey: Buffer.from(info.credential.publicKey).toString("base64url"), counter: info.credential.counter, transports: (info.credential.transports ?? response.response?.transports ?? []) as string[], deviceType: info.credentialDeviceType, backedUp: info.credentialBackedUp, aaguid: info.aaguid, label: expect.label.trim().slice(0, 60) || "Passkey" };121 const inserted = await db.insert(schema.webauthnCredentials).values(row).onConflictDoNothing().returning({ id: schema.webauthnCredentials.id });122 if (!inserted.length) throw new CeremonyError("duplicate_credential", "This passkey is already registered.");123 return { credentialId: row.id, label: row.label };124}125export async function listPasskeys(userId: string) {126 return db.select({ id: schema.webauthnCredentials.id, label: schema.webauthnCredentials.label, createdAt: schema.webauthnCredentials.createdAt, lastUsedAt: schema.webauthnCredentials.lastUsedAt, deviceType: schema.webauthnCredentials.deviceType, backedUp: schema.webauthnCredentials.backedUp, transports: schema.webauthnCredentials.transports }).from(schema.webauthnCredentials).where(eq(schema.webauthnCredentials.userId, userId)).orderBy(schema.webauthnCredentials.createdAt);127}128