Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : services/control-api/src/audit.ts9 * Module : services10 * Repository : https://git.spboucher.ai/maclustr-social11 * Project Website : https://social.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *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 */4142import { createHash, randomUUID } from 'node:crypto';43import type { Tx } from './db.ts';44export type Actor = { kind: 'user' | 'agent' | 'worker' | 'system'; id: string };45export type AuditInput = { correlationId?: string; actor: Actor; action: string; targetKind: string; targetId?: string; brandId?: string | null; result: 'ok' | 'denied' | 'failed' | 'refused'; detail?: Record<string, unknown> };46const FORBIDDEN_KEYS = /pass(word)?|cookie|token|secret|otp|code2fa|recovery|authorization/i;47/** Drops any key that could carry a secret; audit detail is for facts, not payloads. */48export function scrub(v: unknown, depth = 0): unknown {49 if (depth > 4) return '[…]';50 if (typeof v === 'string') return v.length > 500 ? v.slice(0, 500) + '…' : v;51 if (Array.isArray(v)) return v.slice(0, 50).map((x) => scrub(x, depth + 1));52 if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).filter(([k]) => !FORBIDDEN_KEYS.test(k)).map(([k, x]) => [k, scrub(x, depth + 1)]));53 return v;54}55/** Append-only, hash-chained. Runs inside the caller's transaction so the fact and its trace commit together. */56export async function audit(tx: Tx, a: AuditInput): Promise<void> {57 await tx.query("SELECT pg_advisory_xact_lock(hashtext('mls_audit_chain'))");58 const prev = (await tx.query('SELECT hash FROM audit_events ORDER BY id DESC LIMIT 1')).rows[0]?.hash ?? 'genesis';59 const at = new Date().toISOString(); const cid = a.correlationId ?? randomUUID();60 const detail = scrub(a.detail ?? {}) as object;61 const body = JSON.stringify([at, cid, a.actor.kind, a.actor.id, a.action, a.targetKind, a.targetId ?? '', a.brandId ?? null, a.result, detail]);62 const hash = createHash('sha256').update(prev).update(body).digest('hex');63 await tx.query('INSERT INTO audit_events(at, correlation_id, actor_kind, actor_id, action, target_kind, target_id, brand_id, result, detail, prev_hash, hash) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)',64 [at, cid, a.actor.kind, a.actor.id, a.action, a.targetKind, a.targetId ?? '', a.brandId ?? null, a.result, JSON.stringify(detail), prev, hash]);65}66export async function verifyAuditChain(tx: Tx): Promise<{ ok: boolean; count: number; brokenAt?: number }> {67 const rows = (await tx.query('SELECT * FROM audit_events ORDER BY id')).rows;68 let prev = 'genesis';69 for (const r of rows) {70 const body = JSON.stringify([new Date(r.at).toISOString(), r.correlation_id, r.actor_kind, r.actor_id, r.action, r.target_kind, r.target_id, r.brand_id ?? null, r.result, r.detail]);71 const h = createHash('sha256').update(prev).update(body).digest('hex');72 if (r.prev_hash !== prev || r.hash !== h) return { ok: false, count: rows.length, brokenAt: r.id };73 prev = r.hash;74 }75 return { ok: true, count: rows.length };76}77