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/routes/ops.ts9 * Module : routes10 * 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 { z, Uuid } from '@mls/contracts';43import { parseRepairProposal, recipeSha256, validateRecipe, RecipeValidationError } from '@mls/workflow-engine';44import type { Ctx, Req } from '../app.ts';45import { audit, verifyAuditChain } from '../audit.ts';46import { bad, conflict, notFound } from '../core/errors.ts';47import { activatePolicy, activePolicy, emergencyState } from '../core/policy.ts';4849export function registerOpsRoutes(ctx: Ctx) {50 const { db, route } = ctx;51 const P = (req: Req) => req.params as Record<string, string>;52 const E = z.object({}).strict();5354 /** Dashboard: every number is a live count from the database. Nothing is estimated. */55 route({ method: 'GET', path: '/v1/overview', summary: 'Tableau de bord (comptes réels)', tag: 'ops', auth: 'user' }, async (req) => {56 const vis = await ctx.visibleBrandIds(req); const p = vis === 'all' ? [] : [vis]; const w = (c: string) => (vis === 'all' ? 'true' : `${c} = ANY($1::uuid[])`);57 const one = async (sql: string) => (await db.query(sql, p)).rows;58 return {59 generatedAt: new Date().toISOString(), emergency: await emergencyState(db),60 content: await one(`SELECT state, count(*)::int AS n FROM content_items WHERE ${w('brand_id')} GROUP BY state`),61 jobs: await one(`SELECT state, count(*)::int AS n FROM publication_jobs WHERE ${w('brand_id')} GROUP BY state`),62 upcoming: await one(`SELECT j.id, j.scheduled_at, j.state, j.mode, c.title, b.name AS brand_name, b.timezone FROM publication_jobs j JOIN content_items c ON c.id=j.content_id JOIN brands b ON b.id=j.brand_id WHERE ${w('j.brand_id')} AND j.state IN ('QUEUED','PREPARING','AWAITING_CONFIRMATION') ORDER BY j.scheduled_at LIMIT 8`),63 needsHuman: await one(`SELECT j.id, j.state, j.state_reason, c.title FROM publication_jobs j JOIN content_items c ON c.id=j.content_id WHERE ${w('j.brand_id')} AND j.state IN ('AWAITING_CONFIRMATION','UNKNOWN_OUTCOME') ORDER BY j.updated_at`),64 pendingApprovals: (await one(`SELECT count(*)::int AS n FROM content_items WHERE ${w('brand_id')} AND state='REVIEW'`))[0].n,65 comments: await one(`SELECT status, count(*)::int AS n FROM comments WHERE ${w('brand_id')} GROUP BY status`),66 sessions: vis === 'all' ? (await db.query("SELECT state, count(*)::int AS n FROM navigator_sessions WHERE state <> 'REVOKED' GROUP BY state")).rows : null,67 workers: vis === 'all' ? (await db.query('SELECT status, count(*)::int AS n FROM workers GROUP BY status')).rows : null,68 alerts: (await db.query(`SELECT * FROM alerts WHERE status='open' AND (brand_id IS NULL OR ${w('brand_id')}) ORDER BY created_at DESC LIMIT 20`, p)).rows,69 };70 });71 route({ method: 'GET', path: '/v1/alerts', summary: 'Alertes', tag: 'ops', auth: 'user' }, async (req) => { const vis = await ctx.visibleBrandIds(req); return { alerts: (await db.query(`SELECT * FROM alerts WHERE ${vis === 'all' ? 'true' : 'brand_id = ANY($1::uuid[])'} ORDER BY created_at DESC LIMIT 200`, vis === 'all' ? [] : [vis])).rows }; });72 route({ method: 'POST', path: '/v1/alerts/:id/ack', summary: 'Prend acte d’une alerte', tag: 'ops', auth: 'user', role: 'admin', body: E }, async (req) => { await db.query("UPDATE alerts SET status='acked', acked_by=$2, updated_at=now() WHERE id=$1 AND status='open'", [P(req).id, req.session!.user.id]); });7374 route({ method: 'GET', path: '/v1/audit', summary: 'Journal d’audit (ajout seulement)', tag: 'ops', auth: 'user', role: 'admin', query: z.object({ targetKind: z.string().max(40).optional(), targetId: z.string().max(80).optional(), action: z.string().max(60).optional(), before: z.coerce.number().int().optional() }).strict() }, async (req) => {75 const q = (req as any).q; const p: unknown[] = []; const w: string[] = [];76 for (const [col, v] of [['target_kind', q.targetKind], ['target_id', q.targetId], ['action', q.action]] as const) if (v) { p.push(v); w.push(`${col} = $${p.length}`); }77 if (q.before) { p.push(q.before); w.push(`id < $${p.length}`); }78 return { events: (await db.query(`SELECT id, at, correlation_id, actor_kind, actor_id, action, target_kind, target_id, brand_id, result, detail, hash FROM audit_events ${w.length ? 'WHERE ' + w.join(' AND ') : ''} ORDER BY id DESC LIMIT 200`, p)).rows };79 });80 route({ method: 'GET', path: '/v1/audit/verify', summary: 'Vérifie la chaîne de hachage du journal', tag: 'ops', auth: 'user', role: 'admin' }, async () => verifyAuditChain(db));8182 route({ method: 'GET', path: '/v1/policy', summary: 'Politique active et historique', tag: 'safety', auth: 'user', role: 'admin' }, async () => ({ active: await activePolicy(db), versions: (await db.query('SELECT version, sha256, note, created_by, created_at, active FROM policy_versions ORDER BY version DESC')).rows }));83 route({ method: 'POST', path: '/v1/policy', summary: 'Active une nouvelle version de politique (propriétaire humain, justification écrite)', tag: 'safety', auth: 'user', role: 'owner', body: z.object({ document: z.unknown(), note: z.string().min(10).max(2000) }).strict() }, async (req) => ({ version: await db.tx((tx) => activatePolicy(tx, ctx.actor(req), req.data.document, req.data.note, req.cid)) }));8485 /* ── Recipes: versioned, human-validated before use ── */86 route({ method: 'GET', path: '/v1/recipes', summary: 'Recettes et versions', tag: 'recipes', auth: 'user', role: 'admin' }, async () => ({ recipes: (await db.query("SELECT r.*, (SELECT json_agg(json_build_object('id', v.id, 'version', v.version, 'status', v.status, 'origin', v.origin, 'sha256', v.sha256, 'validated_at', v.validated_at, 'created_at', v.created_at) ORDER BY v.version DESC) FROM recipe_versions v WHERE v.recipe_id=r.id) AS versions FROM workflow_recipes r ORDER BY r.slug")).rows }));87 route({ method: 'GET', path: '/v1/recipe-versions/:id', summary: 'Définition d’une version', tag: 'recipes', auth: 'user', role: 'admin' }, async (req) => { const v = await db.one('SELECT * FROM recipe_versions WHERE id=$1', [P(req).id]); if (!v) throw notFound(); return v; });88 route({ method: 'POST', path: '/v1/recipes/:id/versions', summary: 'Nouvelle version en brouillon (validation structurelle stricte)', tag: 'recipes', auth: 'user', role: 'admin', body: z.object({ definition: z.unknown(), origin: z.enum(['human', 'vision_proposal']).default('human') }).strict() }, async (req) => {89 const rec = await db.one('SELECT * FROM workflow_recipes WHERE id=$1', [P(req).id]); if (!rec) throw notFound();90 const last = await db.one("SELECT definition FROM recipe_versions WHERE recipe_id=$1 AND status='validated' ORDER BY version DESC LIMIT 1", [rec.id]);91 let def; try { def = req.data.origin === 'vision_proposal' && last ? parseRepairProposal(req.data.definition, last.definition) : validateRecipe(req.data.definition); } catch (e) { if (e instanceof RecipeValidationError) throw bad('recipe_invalid', 'Recette refusée', e.issues); throw e; }92 if (def.slug !== rec.slug) throw bad('recipe_invalid', 'Le slug ne correspond pas.');93 return db.tx(async (tx) => { const n = ((await tx.query('SELECT coalesce(max(version),0) AS v FROM recipe_versions WHERE recipe_id=$1', [rec.id])).rows[0].v as number) + 1;94 const v = (await tx.query("INSERT INTO recipe_versions(recipe_id, version, definition, sha256, origin) VALUES ($1,$2,$3,$4,$5) RETURNING id, version, status", [rec.id, n, JSON.stringify(def), recipeSha256(def), req.data.origin])).rows[0];95 await audit(tx, { correlationId: req.cid, actor: ctx.actor(req), action: 'recipe.draft', targetKind: 'recipe_version', targetId: v.id, result: 'ok', detail: { origin: req.data.origin } }); return v; });96 });97 route({ method: 'POST', path: '/v1/recipe-versions/:id/validate', summary: 'Valide une version (humain) ; retire la précédente', tag: 'recipes', auth: 'user', role: 'admin', body: z.object({ attest: z.literal(true) }).strict() }, async (req) => db.tx(async (tx) => {98 const v = (await tx.query('SELECT * FROM recipe_versions WHERE id=$1 FOR UPDATE', [P(req).id])).rows[0]; if (!v) throw notFound(); if (v.status !== 'draft') throw conflict('not_draft');99 validateRecipe(v.definition);100 await tx.query("UPDATE recipe_versions SET status='retired' WHERE recipe_id=$1 AND status='validated'", [v.recipe_id]);101 await tx.query("UPDATE recipe_versions SET status='validated', validated_by=$2, validated_at=now() WHERE id=$1", [v.id, req.session!.user.id]);102 await audit(tx, { correlationId: req.cid, actor: ctx.actor(req), action: 'recipe.validate', targetKind: 'recipe_version', targetId: v.id, result: 'ok', detail: { sha256: v.sha256 } }); return { ok: true };103 }));104 void Uuid;105}106