SPB Git

Repository Public

auth.ts 9.5 KB 207 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : server/src/auth.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/maclustr-vision11 * Project Website  : https://camera.spboucher.ai12 * Created          : 2026-11-3013 * Last Modified    : 2026-11-3014 *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: admin@spboucher.ai23 * Technical Contact: dev@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// Accès privé : une seule clé active (≥ 256 bits), stockée sous forme de vérificateur HMAC-SHA-256,43// sessions opaques révocables côté serveur, limitation progressive des tentatives.44import crypto from 'node:crypto';45import fs from 'node:fs';46import path from 'node:path';47import type { Config } from './config.ts';48import { getSetting, setSetting, tx, type DB } from './db.ts';4950export const COOKIE = '__Host-mlv';51const KEY_PREFIX = 'mlv_';5253export function loadServerSecret(cfg: Config): Buffer {54  const file = path.join(cfg.configDir, 'server-secret');55  const st = fs.statSync(file);56  if ((st.mode & 0o077) !== 0) throw new Error(`${file} doit être en mode 0600`);57  const s = fs.readFileSync(file, 'utf8').trim();58  if (s.length < 32) throw new Error('secret serveur trop court');59  return Buffer.from(s, 'utf8');60}6162export function generateKey(): string {63  return KEY_PREFIX + crypto.randomBytes(32).toString('base64url'); // 256 bits64}6566function verifier(secret: Buffer, key: string): Buffer {67  return crypto.createHmac('sha256', secret).update(key, 'utf8').digest();68}6970/** Crée la clé active : révoque l'ancienne clé ET toutes les sessions. Retourne la clé en clair (une seule fois). */71export function rotateKey(db: DB, secret: Buffer, label = 'propriétaire'): string {72  const key = generateKey();73  const now = Date.now();74  tx(db, () => {75    db.prepare('UPDATE access_keys SET revoked_ms = ? WHERE revoked_ms IS NULL').run(now);76    db.prepare('UPDATE sessions SET revoked_ms = ? WHERE revoked_ms IS NULL').run(now);77    db.prepare('INSERT INTO access_keys (verifier, label, created_ms) VALUES (?, ?, ?)').run(verifier(secret, key), label, now);78  });79  return key;80}8182export function hasActiveKey(db: DB): boolean {83  return !!db.prepare('SELECT 1 AS x FROM access_keys WHERE revoked_ms IS NULL').get();84}8586/** Comparaison en temps constant ; un calcul factice est fait s'il n'existe aucune clé active. */87export function checkKey(db: DB, secret: Buffer, candidate: unknown): boolean {88  const cand = typeof candidate === 'string' ? candidate.trim() : '';89  const row = db.prepare('SELECT verifier FROM access_keys WHERE revoked_ms IS NULL ORDER BY id DESC LIMIT 1').get() as { verifier: Uint8Array } | undefined;90  const expected = row ? Buffer.from(row.verifier) : crypto.randomBytes(32);91  const got = verifier(secret, cand.slice(0, 512));92  const same = crypto.timingSafeEqual(expected, got);93  return !!row && same && cand.length >= 40;94}9596export type Session = { id: string; createdMs: number; expiresMs: number; lastSeenMs: number; ip: string | null; userAgent: string | null; trusted: boolean };9798const hashToken = (t: string) => crypto.createHash('sha256').update(t, 'utf8').digest();99100export function createSession(db: DB, cfg: Config, opts: { ip: string | null; userAgent: string | null; trusted: boolean }): { token: string; session: Session } {101  const token = crypto.randomBytes(32).toString('base64url');102  const id = crypto.randomBytes(9).toString('base64url');103  const now = Date.now();104  const ttl = opts.trusted ? cfg.session.trustedDays * 86400000 : cfg.session.defaultHours * 3600000;105  const session: Session = { id, createdMs: now, expiresMs: now + ttl, lastSeenMs: now, ip: opts.ip, userAgent: (opts.userAgent || '').slice(0, 300) || null, trusted: opts.trusted };106  db.prepare('INSERT INTO sessions (id, token_hash, created_ms, expires_ms, last_seen_ms, ip, user_agent, trusted) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(107    id,108    hashToken(token),109    now,110    session.expiresMs,111    now,112    session.ip,113    session.userAgent,114    opts.trusted ? 1 : 0,115  );116  return { token, session };117}118119export function findSession(db: DB, token: string | undefined): Session | null {120  if (!token || token.length < 20 || token.length > 100) return null;121  const r = db.prepare('SELECT * FROM sessions WHERE token_hash = ?').get(hashToken(token)) as Record<string, any> | undefined;122  if (!r || r.revoked_ms || r.expires_ms < Date.now()) return null;123  const now = Date.now();124  if (now - r.last_seen_ms > 60000) db.prepare('UPDATE sessions SET last_seen_ms = ? WHERE id = ?').run(now, r.id);125  return { id: r.id, createdMs: r.created_ms, expiresMs: r.expires_ms, lastSeenMs: r.last_seen_ms, ip: r.ip, userAgent: r.user_agent, trusted: !!r.trusted };126}127128export function revokeSession(db: DB, id: string): boolean {129  return db.prepare('UPDATE sessions SET revoked_ms = ? WHERE id = ? AND revoked_ms IS NULL').run(Date.now(), id).changes > 0;130}131132export function listSessions(db: DB): Session[] {133  const rows = db.prepare('SELECT * FROM sessions WHERE revoked_ms IS NULL AND expires_ms > ? ORDER BY last_seen_ms DESC').all(Date.now()) as Record<string, any>[];134  return rows.map((r) => ({ id: r.id, createdMs: r.created_ms, expiresMs: r.expires_ms, lastSeenMs: r.last_seen_ms, ip: r.ip, userAgent: r.user_agent, trusted: !!r.trusted }));135}136137export function sessionCookie(token: string, maxAgeS: number): string {138  return `${COOKIE}=${token}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${Math.floor(maxAgeS)}`;139}140export const clearCookie = `${COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0`;141142/**143 * Limitation des tentatives : temporisation progressive par adresse IP et frein global.144 * Jamais de verrouillage permanent : chaque blocage expire seul (plafond 15 min par IP,145 * et le frein global ne fait qu'espacer les tentatives), ce qui évite un déni de service durable.146 */147export class LoginLimiter {148  private perIp = new Map<string, { fails: number; lockedUntil: number; last: number }>();149  private globalFails: number[] = [];150  private globalNext = 0;151  private now: () => number;152  constructor(now: () => number = Date.now) {153    this.now = now;154  }155156  /** Délai d'attente imposé (ms) avant une nouvelle tentative ; 0 = autorisée. */157  check(ip: string): number {158    const now = this.now();159    const e = this.perIp.get(ip);160    let wait = e && e.lockedUntil > now ? e.lockedUntil - now : 0;161    this.globalFails = this.globalFails.filter((t) => now - t < 10 * 60000);162    if (this.globalFails.length >= 40 && this.globalNext > now) wait = Math.max(wait, this.globalNext - now);163    return wait;164  }165166  fail(ip: string): void {167    const now = this.now();168    const e = this.perIp.get(ip) || { fails: 0, lockedUntil: 0, last: now };169    if (now - e.last > 3600000) e.fails = 0;170    e.fails++;171    e.last = now;172    if (e.fails >= 3) e.lockedUntil = now + Math.min(15 * 60000, 2000 * 2 ** (e.fails - 3));173    this.perIp.set(ip, e);174    this.globalFails.push(now);175    if (this.globalFails.length >= 40) this.globalNext = now + 3000;176    if (this.perIp.size > 5000) for (const [k, v] of this.perIp) if (now - v.last > 3600000) this.perIp.delete(k);177  }178179  success(ip: string): void {180    this.perIp.delete(ip);181  }182}183184/**185 * Lien d'activation à usage unique : un jeton aléatoire de courte durée, placé dans le fragment de l'URL186 * (jamais transmis dans la requête ni journalisé). Ce n'est pas la clé : il sert une seule fois à en créer une.187 */188export function createEnrollToken(db: DB, ttlMinutes = 15): { token: string; expiresMs: number } {189  const token = crypto.randomBytes(32).toString('base64url');190  const expiresMs = Date.now() + Math.max(1, Math.min(60, ttlMinutes)) * 60000;191  setSetting(db, 'enroll_token', { hash: hashToken(token).toString('hex'), expiresMs });192  return { token, expiresMs };193}194195/** Consomme le jeton (une seule fois) ; retourne true s'il était valide. */196export function consumeEnrollToken(db: DB, candidate: unknown): boolean {197  const cand = typeof candidate === 'string' ? candidate : '';198  return tx(db, () => {199    const cur = getSetting<{ hash?: string; expiresMs?: number }>(db, 'enroll_token', {});200    const expected = cur.hash && /^[a-f0-9]{64}$/.test(cur.hash) ? Buffer.from(cur.hash, 'hex') : crypto.randomBytes(32);201    const same = crypto.timingSafeEqual(expected, hashToken(cand.slice(0, 200)));202    const valid = !!cur.hash && same && (cur.expiresMs || 0) > Date.now();203    if (valid) db.prepare("DELETE FROM settings WHERE key = 'enroll_token'").run();204    return valid;205  });206}207
Files main
Menu

Theme