SPB Git

Repository Public

policy.ts 3.9 KB 74 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : services/control-api/src/core/policy.ts9 * Module           : core10 * 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 } from 'node:crypto';43import { PolicyDocument, defaultPolicy } from '@mls/policy-engine';44import type { Tx } from '../db.ts';45import { audit, type Actor } from '../audit.ts';46import { bad } from './errors.ts';4748export async function activePolicy(tx: Tx): Promise<PolicyDocument & { _version: number }> {49  const r = (await tx.query('SELECT version, document FROM policy_versions WHERE active')).rows[0];50  if (!r) throw new Error('aucune politique active');51  return { ...PolicyDocument.parse(r.document), _version: r.version };52}53export async function ensurePolicy(tx: Tx, fixtureHost?: string) {54  const has = (await tx.query('SELECT 1 FROM policy_versions LIMIT 1')).rowCount;55  if (has) return;56  const doc = defaultPolicy(fixtureHost);57  await tx.query('INSERT INTO policy_versions(version, document, sha256, note, active) VALUES (1,$1,$2,$3,true)', [JSON.stringify(doc), sha(doc), 'Politique initiale : automatisation Meta verrouillée (manuel assisté).']);58}59const sha = (d: unknown) => createHash('sha256').update(JSON.stringify(d)).digest('hex');60/** Only a human owner reaches this (enforced by the route). Agents have no code path to it. */61export async function activatePolicy(tx: Tx, actor: Actor & { kind: 'user' }, document: unknown, note: string, correlationId: string) {62  const doc = PolicyDocument.safeParse(document);63  if (!doc.success) throw bad('policy_invalid', 'Politique invalide', doc.error.issues);64  if (note.trim().length < 10) throw bad('note_required', 'Une justification écrite est requise.');65  const v = ((await tx.query('SELECT coalesce(max(version),0) AS v FROM policy_versions')).rows[0].v as number) + 1;66  await tx.query('UPDATE policy_versions SET active=false WHERE active');67  await tx.query('INSERT INTO policy_versions(version, document, sha256, note, created_by, active) VALUES ($1,$2,$3,$4,$5,true)', [v, JSON.stringify(doc.data), sha(doc.data), note, actor.id]);68  await audit(tx, { correlationId, actor, action: 'policy.activate', targetKind: 'policy', targetId: String(v), result: 'ok', detail: { note, sha256: sha(doc.data) } });69  return v;70}71export async function emergencyState(tx: Tx): Promise<{ emergency_stop: boolean; reason: string; changed_at: string }> {72  return (await tx.query('SELECT emergency_stop, reason, changed_at FROM system_state')).rows[0];73}74
Files main
Menu

Theme