Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : studio/server/auth.ts9 * Module : studio10 * Repository : https://git.spboucher.ai/ka-maps-engine11 * Created : 2026-12-0112 * Last Modified : 2026-12-0113 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Authentification : clés d'accès WebAuthn seulement (aucun mot de passe), invitations à usage43// unique créées en ligne de commande, sessions à témoin sécurisé, protection CSRF.44import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';45import type { IncomingMessage } from 'node:http';46import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from '@simplewebauthn/server';47import { audit, type Db, HttpError, tx } from './db.ts';4849export type AuthConfig = { rpId: string; rpName: string; origin: string; cookieName: string; secureCookie: boolean; sessionHours: number; idleMinutes: number };50export type Admin = { id: string; name: string; email: string };51export type Session = { admin: Admin; csrf: string; idHash: Buffer };5253const hash = (s: string) => createHash('sha256').update(s).digest();54const token = () => randomBytes(32).toString('base64url');5556export function authConfigFromEnv(env = process.env): AuthConfig {57 const origin = env.STUDIO_ORIGIN ?? 'https://maps-admin.spboucher.ai';58 const secure = origin.startsWith('https://');59 return {60 rpId: env.STUDIO_RP_ID ?? new URL(origin).hostname,61 rpName: 'KA Maps Studio',62 origin,63 cookieName: secure ? '__Host-kms' : 'kms',64 secureCookie: secure,65 sessionHours: Number(env.STUDIO_SESSION_HOURS ?? 12),66 idleMinutes: Number(env.STUDIO_IDLE_MINUTES ?? 120),67 };68}6970// ---------- invitations (ligne de commande)7172export async function createInvite(db: Db, name: string, email: string, days = 7): Promise<{ token: string; admin: Admin; expiresAt: Date; created: boolean }> {73 name = name.trim();74 email = email.trim().toLowerCase();75 if (name.length < 2 || name.length > 80) throw new Error('nom : 2 à 80 caractères');76 if (!/^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/.test(email)) throw new Error('courriel invalide');77 return tx(db, async (c) => {78 const ex = await c.query(`SELECT id, name, email FROM ${db.schema}.admin WHERE email = $1`, [email]);79 let admin: Admin = ex.rows[0];80 const created = !admin;81 if (!admin) admin = (await c.query(`INSERT INTO ${db.schema}.admin (name, email) VALUES ($1, $2) RETURNING id, name, email`, [name, email])).rows[0];82 const t = token();83 const r = await c.query(`INSERT INTO ${db.schema}.invite (token_hash, admin_id, expires_at) VALUES ($1, $2, now() + make_interval(days => $3)) RETURNING expires_at`, [hash(t), admin.id, days]);84 await audit(c, db.schema, { id: null, name: 'cli' }, 'admin.invite', admin.email, { created, days });85 return { token: t, admin, expiresAt: r.rows[0].expires_at, created };86 });87}8889async function findInvite(db: Db, t: unknown) {90 if (typeof t !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(t)) return null;91 const r = await db.pool.query(92 `SELECT i.token_hash, a.id, a.name, a.email FROM ${db.schema}.invite i JOIN ${db.schema}.admin a ON a.id = i.admin_id93 WHERE i.token_hash = $1 AND i.used_at IS NULL AND i.expires_at > now() AND a.disabled_at IS NULL`,94 [hash(t)],95 );96 return r.rows[0] ? { tokenHash: r.rows[0].token_hash as Buffer, admin: { id: r.rows[0].id, name: r.rows[0].name, email: r.rows[0].email } as Admin } : null;97}9899export async function inviteInfo(db: Db, t: unknown) {100 const inv = await findInvite(db, t);101 if (!inv) throw new HttpError(404, "lien d'activation invalide, expiré ou déjà utilisé");102 return { name: inv.admin.name, email: inv.admin.email };103}104105// ---------- enregistrement d'une clé d'accès106107export async function registerOptions(db: Db, cfg: AuthConfig, t: unknown) {108 const inv = await findInvite(db, t);109 if (!inv) throw new HttpError(404, "lien d'activation invalide, expiré ou déjà utilisé");110 const existing = await db.pool.query(`SELECT id, transports FROM ${db.schema}.credential WHERE admin_id = $1`, [inv.admin.id]);111 const options = await generateRegistrationOptions({112 rpName: cfg.rpName,113 rpID: cfg.rpId,114 userName: inv.admin.email,115 userDisplayName: inv.admin.name,116 userID: new TextEncoder().encode(inv.admin.id),117 attestationType: 'none',118 excludeCredentials: existing.rows.map((r) => ({ id: r.id, transports: r.transports })),119 authenticatorSelection: { residentKey: 'required', userVerification: 'required' },120 });121 const f = await db.pool.query(`INSERT INTO ${db.schema}.challenge (kind, challenge, admin_id, expires_at) VALUES ('register', $1, $2, now() + interval '5 minutes') RETURNING id`, [options.challenge, inv.admin.id]);122 return { flow: f.rows[0].id, options };123}124125async function takeChallenge(db: Db, flow: unknown, kind: 'register' | 'login') {126 if (typeof flow !== 'string' || !/^[0-9a-f-]{36}$/.test(flow)) throw new HttpError(400, 'défi inconnu');127 const r = await db.pool.query(`DELETE FROM ${db.schema}.challenge WHERE id = $1 AND kind = $2 RETURNING challenge, admin_id, expires_at > now() AS live`, [flow, kind]);128 if (!r.rows[0] || !r.rows[0].live) throw new HttpError(400, 'défi expiré, recommencer');129 return r.rows[0] as { challenge: string; admin_id: string | null };130}131132export async function registerVerify(db: Db, cfg: AuthConfig, body: any, req: IncomingMessage, ip: string) {133 const inv = await findInvite(db, body?.token);134 if (!inv) throw new HttpError(404, "lien d'activation invalide, expiré ou déjà utilisé");135 const ch = await takeChallenge(db, body?.flow, 'register');136 if (ch.admin_id !== inv.admin.id) throw new HttpError(400, 'défi inconnu');137 let v;138 try {139 v = await verifyRegistrationResponse({ response: body.response, expectedChallenge: ch.challenge, expectedOrigin: cfg.origin, expectedRPID: cfg.rpId, requireUserVerification: true });140 } catch (e: any) {141 throw new HttpError(400, `clé d'accès refusée : ${e.message}`);142 }143 if (!v.verified || !v.registrationInfo) throw new HttpError(400, "clé d'accès refusée");144 const info = v.registrationInfo;145 return tx(db, async (c) => {146 const used = await c.query(`UPDATE ${db.schema}.invite SET used_at = now() WHERE token_hash = $1 AND used_at IS NULL RETURNING admin_id`, [inv.tokenHash]);147 if (!used.rows[0]) throw new HttpError(409, "lien d'activation déjà utilisé");148 await c.query(149 `INSERT INTO ${db.schema}.credential (id, admin_id, public_key, counter, transports, device_type, backed_up, label) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,150 [info.credential.id, inv.admin.id, Buffer.from(info.credential.publicKey), info.credential.counter, info.credential.transports ?? body.response?.response?.transports ?? [], info.credentialDeviceType, info.credentialBackedUp, String(req.headers['user-agent'] ?? '').slice(0, 120)],151 );152 await audit(c, db.schema, { id: inv.admin.id, name: inv.admin.name, ip }, 'auth.register', inv.admin.email, { credential: info.credential.id.slice(0, 12), deviceType: info.credentialDeviceType });153 return openSession(c, db, cfg, inv.admin, req);154 });155}156157// ---------- connexion158159export async function loginOptions(db: Db, cfg: AuthConfig) {160 const options = await generateAuthenticationOptions({ rpID: cfg.rpId, userVerification: 'required', allowCredentials: [] });161 const f = await db.pool.query(`INSERT INTO ${db.schema}.challenge (kind, challenge, expires_at) VALUES ('login', $1, now() + interval '5 minutes') RETURNING id`, [options.challenge]);162 return { flow: f.rows[0].id, options };163}164165export async function loginVerify(db: Db, cfg: AuthConfig, body: any, req: IncomingMessage, ip: string) {166 const ch = await takeChallenge(db, body?.flow, 'login');167 const credId = body?.response?.id;168 const refused = new HttpError(401, "clé d'accès inconnue ou refusée");169 if (typeof credId !== 'string' || credId.length > 1024) throw refused;170 const r = await db.pool.query(171 `SELECT c.id AS cid, c.public_key, c.counter, c.transports, a.id, a.name, a.email FROM ${db.schema}.credential c JOIN ${db.schema}.admin a ON a.id = c.admin_id WHERE c.id = $1 AND a.disabled_at IS NULL`,172 [credId],173 );174 const row = r.rows[0];175 if (!row) {176 await audit(db.pool, db.schema, { id: null, name: 'inconnu', ip }, 'auth.login.refused', null, { reason: 'credential' });177 throw refused;178 }179 let v;180 try {181 v = await verifyAuthenticationResponse({182 response: body.response, expectedChallenge: ch.challenge, expectedOrigin: cfg.origin, expectedRPID: cfg.rpId, requireUserVerification: true,183 credential: { id: row.cid, publicKey: new Uint8Array(row.public_key), counter: Number(row.counter), transports: row.transports },184 });185 } catch {186 v = { verified: false } as any;187 }188 if (!v.verified) {189 await audit(db.pool, db.schema, { id: row.id, name: row.name, ip }, 'auth.login.refused', row.email, { reason: 'signature' });190 throw refused;191 }192 const admin: Admin = { id: row.id, name: row.name, email: row.email };193 return tx(db, async (c) => {194 await c.query(`UPDATE ${db.schema}.credential SET counter = $2, last_used_at = now() WHERE id = $1`, [row.cid, v.authenticationInfo.newCounter]);195 await audit(c, db.schema, { id: admin.id, name: admin.name, ip }, 'auth.login', admin.email, {});196 return openSession(c, db, cfg, admin, req);197 });198}199200// ---------- sessions201202async function openSession(c: any, db: Db, cfg: AuthConfig, admin: Admin, req: IncomingMessage) {203 const id = token();204 const csrf = token();205 await c.query(`INSERT INTO ${db.schema}.session (id_hash, admin_id, csrf, expires_at, user_agent) VALUES ($1, $2, $3, now() + make_interval(hours => $4), $5)`, [hash(id), admin.id, csrf, cfg.sessionHours, String(req.headers['user-agent'] ?? '').slice(0, 200)]);206 return { admin, csrf, cookie: sessionCookie(cfg, id, cfg.sessionHours * 3600) };207}208209export function sessionCookie(cfg: AuthConfig, value: string, maxAge: number): string {210 return `${cfg.cookieName}=${value}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAge}${cfg.secureCookie ? '; Secure' : ''}`;211}212213function readCookie(req: IncomingMessage, name: string): string | null {214 for (const part of String(req.headers.cookie ?? '').split(';')) {215 const i = part.indexOf('=');216 if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();217 }218 return null;219}220221export async function currentSession(db: Db, cfg: AuthConfig, req: IncomingMessage): Promise<Session | null> {222 const id = readCookie(req, cfg.cookieName);223 if (!id || !/^[A-Za-z0-9_-]{43}$/.test(id)) return null;224 const h = hash(id);225 const r = await db.pool.query(226 `UPDATE ${db.schema}.session s SET last_seen = now() FROM ${db.schema}.admin a227 WHERE s.id_hash = $1 AND a.id = s.admin_id AND a.disabled_at IS NULL AND s.expires_at > now() AND s.last_seen > now() - make_interval(mins => $2)228 RETURNING a.id, a.name, a.email, s.csrf`,229 [h, cfg.idleMinutes],230 );231 const row = r.rows[0];232 return row ? { admin: { id: row.id, name: row.name, email: row.email }, csrf: row.csrf, idHash: h } : null;233}234235export async function closeSession(db: Db, s: Session) {236 await db.pool.query(`DELETE FROM ${db.schema}.session WHERE id_hash = $1`, [s.idHash]);237}238239export function csrfOk(s: Session, req: IncomingMessage): boolean {240 const got = Buffer.from(String(req.headers['x-csrf-token'] ?? ''));241 const want = Buffer.from(s.csrf);242 return got.length === want.length && timingSafeEqual(got, want);243}244245/** Une requête qui modifie doit venir de l'interface elle-même. */246export function originOk(cfg: AuthConfig, req: IncomingMessage): boolean {247 const site = req.headers['sec-fetch-site'];248 if (site && site !== 'same-origin') return false;249 const origin = req.headers.origin;250 return origin === cfg.origin;251}252253export async function sweep(db: Db) {254 await db.pool.query(`DELETE FROM ${db.schema}.session WHERE expires_at < now()`);255 await db.pool.query(`DELETE FROM ${db.schema}.challenge WHERE expires_at < now()`);256}257