Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/lib/auth/webauthn.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *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: support@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 { cookies } from "next/headers";44import {45 generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse,46 type AuthenticationResponseJSON, type AuthenticatorTransport, type RegistrationResponseJSON,47} from "@simplewebauthn/server";48import { db, now, tx } from "../database/db";49import { env } from "../env";50import { audit } from "../audit";51import { randomToken, safeEqual, sha256 } from "../security/crypto";52import { ApiError, clientIp } from "../security/http";53import { startSession } from "./session";54import { OWNER, validToken } from "./enroll";5556const RP_NAME = "ORIX Admin";57const PREAUTH_COOKIE = "orix_preauth";58const origin = () => new URL(env.appUrl).origin;5960export { credentialCount, enrollTokenInfo, issueEnrollToken, type TokenPurpose } from "./enroll";6162// ── Challenge binding ───────────────────────────────────────────────────────────────────────────────6364/** Anonymous ceremonies are tied to the browser that started them through a random HttpOnly cookie. */65async function binding(create: boolean): Promise<string | null> {66 const jar = await cookies();67 let v = jar.get(PREAUTH_COOKIE)?.value;68 if (!v && create) {69 v = randomToken(24);70 jar.set(PREAUTH_COOKIE, v, { httpOnly: true, secure: env.secureCookies, sameSite: "strict", path: "/api/auth", maxAge: 600 });71 }72 return v ? sha256("preauth:" + v) : null;73}7475function storeChallenge(challenge: string, kind: "registration" | "authentication", bind: string): string {76 const id = randomToken(16);77 db().prepare("DELETE FROM challenges WHERE expires_at <= ?").run(now());78 db().prepare("INSERT INTO challenges (id, challenge, kind, binding, expires_at) VALUES (?, ?, ?, ?, ?)").run(id, challenge, kind, bind, new Date(Date.now() + 5 * 60_000).toISOString());79 return id;80}81function consumeChallenge(id: string, kind: string, bind: string | null): string | null {82 // Single use: deleted as it is read, whatever happens next.83 const r = db().prepare("DELETE FROM challenges WHERE id = ? AND kind = ? AND expires_at > ? RETURNING challenge, binding").get(id, kind, now()) as { challenge: string; binding: string } | undefined;84 return r && bind && safeEqual(r.binding, bind) ? r.challenge : null;85}8687// ── Lock-out (derived from the audit trail, so it survives restarts) ────────────────────────────────8889export function assertNotLockedOut(ip: string): void {90 const r = db().prepare("SELECT count(*) AS n, max(at) AS last FROM audit WHERE action = 'login.failed' AND ip = ? AND at > ?").get(ip, new Date(Date.now() - 3_600_000).toISOString()) as { n: number; last: string | null };91 if (!r.last || r.n < 5) return;92 const wait = r.n >= 20 ? 3600 : r.n >= 10 ? 300 : 60;93 const left = Math.ceil(wait - (Date.now() - Date.parse(r.last)) / 1000);94 if (left > 0) throw new ApiError(429, "locked_out", "Too many failed attempts, try again later", { retryAfterSeconds: left });95}9697// ── Registration ────────────────────────────────────────────────────────────────────────────────────9899type CredRow = { id: string; public_key: Uint8Array; counter: number; transports: string };100101export async function registrationOptions(rawToken: string | undefined) {102 if (!validToken(rawToken)) throw new ApiError(403, "invalid_enroll_token", "This enrolment link is invalid, expired or already used");103 const existing = db().prepare("SELECT id, transports FROM credentials").all() as unknown as CredRow[];104 const options = await generateRegistrationOptions({105 rpName: RP_NAME, rpID: env.rpId, userName: "owner@orix", userDisplayName: "ORIX Owner",106 userID: new TextEncoder().encode(OWNER), attestationType: "none",107 excludeCredentials: existing.map((c) => ({ id: c.id, transports: JSON.parse(c.transports) as AuthenticatorTransport[] })),108 // Discoverable credential + user verification: Touch ID / Face ID / device passcode.109 authenticatorSelection: { residentKey: "required", userVerification: "required" },110 supportedAlgorithmIDs: [-7, -8, -257],111 });112 return { challengeId: storeChallenge(options.challenge, "registration", (await binding(true))!), options };113}114115export async function verifyRegistration(input: { challengeId: string; response: RegistrationResponseJSON; name?: string; token?: string }, req: Request) {116 const challenge = consumeChallenge(input.challengeId, "registration", await binding(false));117 if (!challenge) throw new ApiError(400, "challenge_expired", "The enrolment challenge has expired, start again");118 const token = validToken(input.token);119 if (!token) throw new ApiError(403, "invalid_enroll_token", "This enrolment link is invalid, expired or already used");120 let v;121 try { v = await verifyRegistrationResponse({ response: input.response, expectedChallenge: challenge, expectedOrigin: origin(), expectedRPID: env.rpId, requireUserVerification: true }); }122 catch { throw new ApiError(400, "registration_failed", "The passkey could not be verified"); }123 if (!v.verified || !v.registrationInfo) throw new ApiError(400, "registration_failed", "The passkey could not be verified");124 const { credential, credentialDeviceType, credentialBackedUp } = v.registrationInfo;125 tx(() => {126 const used = db().prepare("UPDATE enroll_tokens SET used_at = ? WHERE token_hash = ? AND used_at IS NULL").run(now(), token.token_hash);127 if (used.changes !== 1) throw new ApiError(403, "invalid_enroll_token", "This enrolment link was already used");128 if (token.purpose === "recovery") { // a recovery replaces every earlier passkey and signs every device out129 db().prepare("DELETE FROM credentials").run();130 db().prepare("DELETE FROM sessions").run();131 }132 db().prepare("INSERT INTO credentials (id, admin_id, public_key, counter, transports, name, device_type, backed_up, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")133 .run(credential.id, OWNER, Buffer.from(credential.publicKey), credential.counter, JSON.stringify(credential.transports ?? []),134 (input.name ?? "").trim().slice(0, 60) || "Passkey", credentialDeviceType, credentialBackedUp ? 1 : 0, now());135 });136 audit(`passkey.enrolled.${token.purpose}`, { actor: OWNER, ip: clientIp(req) });137 await startSession(OWNER, req);138}139140// ── Authentication ──────────────────────────────────────────────────────────────────────────────────141142export async function authenticationOptions() {143 const options = await generateAuthenticationOptions({ rpID: env.rpId, userVerification: "required" });144 return { challengeId: storeChallenge(options.challenge, "authentication", (await binding(true))!), options };145}146147export async function verifyAuthentication(input: { challengeId: string; response: AuthenticationResponseJSON }, req: Request) {148 const ip = clientIp(req);149 assertNotLockedOut(ip);150 const fail = (why: string): never => { audit("login.failed", { ip, detail: { why } }); throw new ApiError(401, "login_failed", "Sign-in refused"); };151 const challenge = consumeChallenge(input.challengeId, "authentication", await binding(false));152 if (!challenge) throw new ApiError(400, "challenge_expired", "The sign-in challenge has expired, start again");153 const cred = db().prepare("SELECT id, public_key, counter, transports FROM credentials WHERE id = ?").get(input.response?.id ?? "") as CredRow | undefined;154 if (!cred) return fail("unknown_credential");155 let v;156 try {157 v = await verifyAuthenticationResponse({158 response: input.response, expectedChallenge: challenge, expectedOrigin: origin(), expectedRPID: env.rpId, requireUserVerification: true,159 credential: { id: cred.id, publicKey: new Uint8Array(cred.public_key), counter: cred.counter, transports: JSON.parse(cred.transports) },160 });161 } catch { return fail("verification_error"); }162 if (!v.verified) return fail("not_verified");163 db().prepare("UPDATE credentials SET counter = ?, last_used_at = ? WHERE id = ?").run(v.authenticationInfo.newCounter, now(), cred.id);164 audit("login.ok", { actor: OWNER, ip });165 await startSession(OWNER, req);166}167168export type PasskeyInfo = { id: string; name: string; device_type: string | null; backed_up: number | null; created_at: string; last_used_at: string | null };169export const listPasskeys = () => db().prepare("SELECT id, name, device_type, backed_up, created_at, last_used_at FROM credentials ORDER BY created_at").all() as unknown as PasskeyInfo[];170