SPB Git

Repository Public

grants.ts 7.8 KB 130 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Chat SPBoucher AI8 * File             : src/lib/auth/grants.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 { createHash, randomBytes } from "node:crypto";44import { newCode, normalizeCode } from "./codes";45import { sql } from "../db";46import { authConfig } from "./config";4748/**49 * Setup grants = the only two ways to register a passkey without an existing passkey:50 *   bootstrap  one code, created on the node by the administrator (scripts/auth.ts), valid a few minutes, single use,51 *              only accepted while no passkey exists (or when created with --recover);52 *   recovery   a batch of offline codes generated by the owner, each single use, rotated as a whole.53 * Only SHA-256 hashes of the codes are stored (codes carry 100 random bits, so a fast hash is appropriate).54 * A correct code never opens the app: it opens a short window to register a passkey, which then signs in normally.55 */56export { newCode, normalizeCode } from "./codes";57const hashCode = (c: string) => createHash("sha256").update("csa-grant-v1:" + normalizeCode(c)).digest("hex");58const hashToken = (t: string) => createHash("sha256").update(t).digest("hex");59const gid = () => "gr_" + randomBytes(9).toString("hex");6061export async function activeCredentialCount(): Promise<number> {62  return (await sql<{ n: number }[]>`SELECT count(*)::int AS n FROM webauthn_credentials`)[0].n;63}6465/** Administrator only (CLI on the node). Refuses when passkeys already exist unless `recover` is set. */66export async function createBootstrap(o: { ttlMin?: number; recover?: boolean } = {}): Promise<{ code: string; expiresAt: Date }> {67  const n = await activeCredentialCount();68  if (n > 0 && !o.recover) throw new Error(`${n} passkey(s) already registered: bootstrap is closed. Use --recover to open a recovery enrolment explicitly.`);69  const ttl = Math.min(Math.max(o.ttlMin ?? authConfig.bootstrapTtlMin, 1), 24 * 60); // default 15 min; up to 24 h for a planned hand-off70  await sql`UPDATE auth_grants SET revoked_at = now() WHERE kind = 'bootstrap' AND used_at IS NULL AND revoked_at IS NULL`; // one live bootstrap code at a time71  const code = newCode(5);72  const rows = await sql<{ expires_at: Date }[]>`INSERT INTO auth_grants (id, kind, code_hash, expires_at, note) VALUES (${gid()}, 'bootstrap', ${hashCode(code)}, now() + make_interval(mins => ${ttl}), ${o.recover ? "recover" : "initial"}) RETURNING expires_at`;73  return { code, expiresAt: rows[0].expires_at };74}7576/** New batch of recovery codes; every unused code of previous batches is revoked. Codes are returned once and never stored. */77export async function rotateRecoveryCodes(count = 8): Promise<{ codes: string[]; batch: string }> {78  const batch = "rb_" + randomBytes(6).toString("hex"); const codes = Array.from({ length: count }, () => newCode(5));79  await sql.begin(async tx => {80    await tx`UPDATE auth_grants SET revoked_at = now() WHERE kind = 'recovery' AND used_at IS NULL AND revoked_at IS NULL`;81    for (const c of codes) await tx`INSERT INTO auth_grants (id, kind, code_hash, batch) VALUES (${gid()}, 'recovery', ${hashCode(c)}, ${batch})`;82  });83  return { codes, batch };84}8586export async function recoveryStatus(): Promise<{ remaining: number; generatedAt: Date | null }> {87  const r = await sql<{ n: number; at: Date | null }[]>`SELECT count(*)::int AS n, max(created_at) AS at FROM auth_grants WHERE kind = 'recovery' AND used_at IS NULL AND revoked_at IS NULL`;88  return { remaining: r[0].n, generatedAt: r[0].at };89}9091export interface Grant { id: string; kind: "bootstrap" | "recovery" | "transition"; note: string | null }9293/** Checks a typed code. On success opens the enrolment window and returns the token to place in the setup cookie. */94export async function redeemCode(code: string): Promise<{ token: string; grant: Grant } | null> {95  const norm = normalizeCode(code);96  if (norm.length !== 20) { await noteFailure(); return null; }97  const token = randomBytes(32).toString("base64url");98  const rows = await sql<Grant[]>`UPDATE auth_grants SET redeemed_at = now(), redeem_token_hash = ${hashToken(token)}, redeem_expires_at = now() + make_interval(secs => ${authConfig.setupWindowSec})99    WHERE code_hash = ${hashCode(norm)} AND used_at IS NULL AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > now())100      AND (kind <> 'bootstrap' OR note = 'recover' OR (SELECT count(*) FROM webauthn_credentials) = 0)101    RETURNING id, kind, note`;102  if (!rows[0]) { await noteFailure(); return null; }103  return { token, grant: rows[0] };104}105/** A wrong code counts against the live bootstrap code; after 10 misses it is burned (the administrator must issue a new one). */106async function noteFailure() {107  await sql`UPDATE auth_grants SET failed_attempts = failed_attempts + 1, revoked_at = CASE WHEN failed_attempts + 1 >= 10 THEN now() ELSE revoked_at END108    WHERE kind = 'bootstrap' AND used_at IS NULL AND revoked_at IS NULL`;109}110111/** Transition grant (legacy access cookie of 0.2 → first passkey): created already redeemed, see transition.ts. */112export async function createTransitionGrant(): Promise<{ token: string; grant: Grant }> {113  const token = randomBytes(32).toString("base64url"); const id = gid();114  await sql`INSERT INTO auth_grants (id, kind, code_hash, redeemed_at, redeem_token_hash, redeem_expires_at, expires_at, note)115    VALUES (${id}, 'transition', ${"transition:" + id}, now(), ${hashToken(token)}, now() + make_interval(secs => ${authConfig.setupWindowSec}), now() + make_interval(secs => ${authConfig.setupWindowSec}), 'legacy-cookie')`;116  return { token, grant: { id, kind: "transition", note: "legacy-cookie" } };117}118119export async function grantForSetupToken(token: string | undefined | null): Promise<Grant | null> {120  if (!token || !/^[A-Za-z0-9_-]{43}$/.test(token)) return null;121  const rows = await sql<Grant[]>`SELECT id, kind, note FROM auth_grants WHERE redeem_token_hash = ${hashToken(token)} AND used_at IS NULL AND revoked_at IS NULL AND redeem_expires_at > now()`;122  return rows[0] ?? null;123}124125/** Marks the grant as used (a passkey was registered). Returns false when it was already consumed. */126export async function consumeGrant(id: string): Promise<boolean> {127  const r = await sql`UPDATE auth_grants SET used_at = now(), redeem_token_hash = NULL WHERE id = ${id} AND used_at IS NULL AND revoked_at IS NULL RETURNING id`;128  return r.length > 0;129}130
Files main
Menu

Theme