Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/audit.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *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 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Audit trail (contract §7): sign-ins, device and passkey revocations, deletions, exports, shares, bulk memory47 * deletions. One row per event in vq_audit; a person reads only their own events (GET /api/v2/audit).48 *49 * `audit()` never throws and never blocks a request: an event that cannot be written is logged and dropped.50 */51import type { Express, Request, Response } from "express";52import type Database from "better-sqlite3";53import { isSqlite, pool } from "../db";54import { logger } from "../utils/logger";55import { nativeDeviceId } from "../native";5657export interface AuditEvent {58 id: number;59 at: number;60 device: string | null;61 action: string;62 target: string | null;63 ip: string | null;64 detail: unknown;65}6667/** "web" for a cookie session, the vq_devices.id for a native session (set by the gate). */68export function requestDevice(req: Request): string {69 return nativeDeviceId(req) ?? "web";70}7172function ownerOf(req: Request | null): string | null {73 return (req as (Request & { vqUser?: { id: string } }) | null)?.vqUser?.id ?? null;74}7576/**77 * Records an event. `req` gives the person, the device and the address; pass `as` when the request is not (yet)78 * signed in — a sign-in route runs before the gate — or when the server acts on its own (`req` null).79 * `detail` must never carry a secret: it is shown back to the person.80 */81export function audit(req: Request | null, action: string, target?: string | null, detail?: unknown, as?: { owner?: string; device?: string }): void {82 try {83 if (!isSqlite) return;84 const owner = as?.owner ?? ownerOf(req);85 const device = as?.device ?? (req ? requestDevice(req) : "server");86 const ip = req ? req.ip || req.socket?.remoteAddress || null : null;87 const text = detail === undefined || detail === null ? null : (typeof detail === "string" ? detail : JSON.stringify(detail)).slice(0, 2000);88 (pool as Database.Database)89 .prepare("INSERT INTO vq_audit (at, owner, device, action, target, ip, detail) VALUES (?, ?, ?, ?, ?, ?, ?)")90 .run(Date.now(), owner, device, action.slice(0, 80), target ? String(target).slice(0, 300) : null, ip, text);91 } catch (e) {92 logger.warn(`[audit] ${action} not recorded: ${(e as Error).message}`);93 }94}9596function parseDetail(text: string | null): unknown {97 if (text === null) return null;98 try {99 return JSON.parse(text);100 } catch {101 return text;102 }103}104105/** The person's own events, newest first. */106export function listAudit(owner: string, limit = 100, before?: number): AuditEvent[] {107 const n = Math.min(500, Math.max(1, Math.floor(limit) || 100));108 const rows = (pool as Database.Database)109 .prepare(`SELECT id, at, device, action, target, ip, detail FROM vq_audit WHERE owner = ? ${before ? "AND id < ?" : ""} ORDER BY id DESC LIMIT ?`)110 .all(...(before ? [owner, before, n] : [owner, n])) as Array<Omit<AuditEvent, "detail"> & { detail: string | null }>;111 return rows.map((r) => ({ ...r, detail: parseDetail(r.detail) }));112}113114export function registerAuditRoutes(app: Express): void {115 app.get("/api/v2/audit", (req: Request, res: Response) => {116 const owner = ownerOf(req);117 if (!owner) return res.status(401).json({ error: "Accès verrouillé" });118 const limit = Number.parseInt(String(req.query.limit ?? "100"), 10);119 const before = Number.parseInt(String(req.query.before ?? ""), 10);120 try {121 res.set("Cache-Control", "private, no-store").json({ events: listAudit(owner, limit, Number.isFinite(before) && before > 0 ? before : undefined) });122 } catch (e) {123 logger.error(`[audit] list: ${(e as Error).message}`);124 res.status(500).json({ error: "Audit log unavailable" });125 }126 });127}128