Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : scripts/staging-demo.mjs9 * Module : scripts10 * 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 */4142// Preproduction acceptance run over the REAL network path (laptop → Caddy/TLS on BHS64 → WireGuard → dedicated Mac):43// manual login typed through the viewer WebSocket, session confirmation, ONE approved publication on the synthetic44// test page, redacted evidence saved, latency and frame rate measured. Never run against production.45// usage: node scripts/staging-demo.mjs <cookieA-social> <csrfA> <cookieB-social> <csrfB> <cookieA-navigator>46import WebSocket from 'ws';47import { writeFileSync } from 'node:fs';48const SOCIAL = 'https://social-staging.51-161-112-61.sslip.io', NAV = 'https://navigator-staging.51-161-112-61.sslip.io', FX = 'http://127.0.0.1:8893';49const [cA, xA, cB, xB, cN] = process.argv.slice(2); const out = { at: new Date().toISOString(), steps: [], measures: {} };50const sleep = (ms) => new Promise((r) => setTimeout(r, ms));51const call = async (base, who, method, path, body) => { const [c, x] = who === 'A' ? [base === NAV ? cN : cA, xA] : [cB, xB]; const r = await fetch(base + path, { method, headers: { cookie: `__Host-mls=${c}`, 'x-csrf': x, origin: base, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) }); const j = await r.json().catch(() => null); if (!r.ok) throw new Error(`${method} ${path} → ${r.status} ${JSON.stringify(j)}`); return j; };52const until = async (fn, what, ms = 40000) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) throw new Error(`attente expirée : ${what}`); await sleep(300); } };53const step = (name, detail = {}) => { out.steps.push({ name, ok: true, ...detail }); console.log('✓', name, JSON.stringify(detail)); };5455const me = await call(SOCIAL, 'A', 'GET', '/v1/me'); step('session sur social (TLS public)', { role: me.user.role, env: me.env });56const sessions = (await call(NAV, 'A', 'GET', '/v1/navigator/sessions')).sessions; const s = sessions.find((x) => x.state !== 'PAUSED') ?? sessions[0]; if (!s) throw new Error('aucune session de préproduction');57step('session navigateur trouvée', { state: s.state, worker: s.worker_name, workerStatus: s.worker_status });58const msgs = []; const frames = [];59const ws = new WebSocket(NAV.replace('https', 'wss') + `/nav/ws?session=${s.id}`, { headers: { origin: NAV, cookie: `__Host-mls=${cN}` } });60ws.on('message', (raw, bin) => { if (bin) { frames.push({ at: Date.now(), w: raw.readUInt16BE(4), h: raw.readUInt16BE(6), bytes: raw.length - 8 }); ws.send(JSON.stringify({ t: 'ack', frame: raw.readUInt32BE(0) })); } else msgs.push(JSON.parse(raw.toString())); });61await new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej); ws.on('unexpected-response', (_q, r) => rej(new Error('WS HTTP ' + r.statusCode))); });62const send = (m) => ws.send(JSON.stringify(m)); const key = async (k) => { send({ t: 'key', type: 'down', key: k, code: '' }); send({ t: 'key', type: 'up', key: k, code: '' }); await sleep(25); }; const type = async (txt) => { for (const ch of txt) await key(ch); };63const lastUrl = () => msgs.filter((m) => m.t === 'url').at(-1)?.url ?? '';64await until(() => msgs.find((m) => m.t === 'hello'), 'hello'); await until(() => frames.length > 0, 'première image'); step('WebSocket authentifié, première image reçue', { w: frames[0].w, h: frames[0].h, kB: Math.round(frames[0].bytes / 1024) });65// a second socket without a cookie / with a foreign origin must be refused by the public edge66for (const [label, headers] of [['sans cookie', { origin: NAV }], ['origine étrangère', { origin: 'https://evil.example', cookie: `__Host-mls=${cN}` }], ['cookie de l’autre domaine', { origin: NAV, cookie: `__Host-mls=${cA}` }]]) { const code = await new Promise((res) => { const w = new WebSocket(NAV.replace('https', 'wss') + `/nav/ws?session=${s.id}`, { headers }); w.on('open', () => { w.close(); res(101); }); w.on('unexpected-response', (_q, r) => res(r.statusCode)); w.on('error', () => res(0)); }); if (code === 101) throw new Error(`WebSocket accepté ${label}`); step(`WebSocket refusé : ${label}`, { http: code }); }6768const t = await call(NAV, 'A', 'POST', `/v1/navigator/sessions/${s.id}/takeover`, {}); await until(() => msgs.find((m) => m.t === 'lease' && m.mine), 'bail'); step('prise de contrôle manuelle', { state: t.state });69if (!lastUrl().includes('/pages/')) { // manual login in the real page, by keyboard only, through the gateway70 send({ t: 'nav', op: 'goto', url: `${FX}/login?next=/pages/page-1001` }); await until(() => lastUrl().endsWith('/login'), 'page de connexion');71 await key('Tab'); await type('operateur-demo'); await key('Tab'); await type(process.env.MLS_FIXTURE_PASSWORD ?? 'Atelier-2026-zq'); await key('Enter');72 await until(() => lastUrl().endsWith('/pages/page-1001'), 'connecté'); step('connexion manuelle saisie au clavier dans le site (aucune capture, aucun enregistrement)');73} else step('session du site déjà ouverte dans le profil persistant');74// latency + frame rate over the real path75const rts = []; for (let i = 0; i < 20; i++) { const t0 = performance.now(); send({ t: 'ping', n: 5000 + i }); await until(() => msgs.find((m) => m.t === 'pong' && m.n === 5000 + i), 'pong', 5000); rts.push(performance.now() - t0); await sleep(50); }76rts.sort((a, b) => a - b); const f0 = frames.length, t0 = Date.now(); for (let i = 0; i < 40; i++) { send({ t: 'mouse', type: 'wheel', x: 600, y: 400, dy: i % 2 ? -160 : 160 }); send({ t: 'mouse', type: 'move', x: 300 + i * 10, y: 300 + (i % 5) * 20 }); await sleep(50); }77await sleep(500); const got = frames.slice(f0); out.measures = { pingMs: { p50: +rts[10].toFixed(1), p90: +rts[18].toFixed(1), max: +rts[19].toFixed(1) }, framesPerSecondWhileScrolling: +(got.length / ((Date.now() - t0) / 1000)).toFixed(1), frameKB: { median: got.length ? Math.round(got.map((f) => f.bytes).sort((a, b) => a - b)[got.length >> 1] / 1024) : null }, networkPath: 'laptop → BHS64 (Caddy TLS) → WireGuard → m4ml' };78step('latence et débit mesurés sur le réseau réel', out.measures);79send({ t: 'nav', op: 'goto', url: 'https://example.org/' }); await until(() => msgs.find((m) => m.t === 'blocked'), 'refus de domaine'); step('domaine hors liste refusé', { reason: msgs.find((m) => m.t === 'blocked').reason });8081const brand = (await call(SOCIAL, 'A', 'GET', '/v1/brands')).brands.find((b) => b.slug === 'maclustr');82let page = (await call(SOCIAL, 'A', 'GET', `/v1/pages?brandId=${brand.id}`)).pages.find((p) => p.platform === 'fixture');83if (!page) { page = await call(SOCIAL, 'A', 'POST', '/v1/pages', { brandId: brand.id, platform: 'fixture', displayName: 'Atelier Démo', url: `${FX}/pages/page-1001`, composerUrl: `${FX}/pages/page-1001/composer`, externalPageId: 'page-1001' }); await call(SOCIAL, 'A', 'POST', `/v1/pages/${page.id}/confirm`, { typedName: 'Atelier Démo', attest: true }); }84step('page de test confirmée à la main', { automation: 'fixture synthétique' });85await call(NAV, 'A', 'POST', `/v1/navigator/sessions/${s.id}/confirm`, { pageIds: [page.id], attest: true }); const rel = await call(NAV, 'A', 'POST', `/v1/navigator/sessions/${s.id}/release`, {}); step('session confirmée pour cette page, contrôle libéré', { state: rel.state });86const text = `Démonstration MacLustr Social du ${new Date().toISOString().slice(0, 16)}Z.\nUne seule publication approuvée, sur la page de test.`;87const c = await call(SOCIAL, 'B', 'POST', '/v1/content', { brandId: brand.id, pageId: page.id, title: 'Démonstration de préproduction', payload: { lang: 'fr', body: text } }); await call(SOCIAL, 'B', 'POST', `/v1/content/${c.id}/submit`, {});88let selfDenied = false; try { await call(SOCIAL, 'B', 'POST', `/v1/content/${c.id}/approve`, { versionId: c.version.id, contentHash: c.version.content_hash, pageId: page.id, decision: 'approve' }); } catch (e) { selfDenied = /self_approval_forbidden/.test(e.message); } if (!selfDenied) throw new Error('auto-approbation acceptée'); step('auto-approbation refusée');89await call(SOCIAL, 'A', 'POST', `/v1/content/${c.id}/approve`, { versionId: c.version.id, contentHash: c.version.content_hash, pageId: page.id, decision: 'approve' }); step('approbation par un second administrateur', { hash: c.version.content_hash.slice(0, 12) });90const j = (await call(SOCIAL, 'A', 'POST', '/v1/jobs', { contentId: c.id, scheduledAt: new Date(Date.now() + 2000).toISOString(), mode: 'auto_submit' })).job;91const job = async () => (await call(SOCIAL, 'A', 'GET', `/v1/jobs/${j.id}`));92await until(async () => (await job()).job.state === 'AWAITING_CONFIRMATION', 'compositeur prêt', 60000); step('compositeur préparé par la recette ; attente de la confirmation humaine');93const save = async (label, file) => { const r = (await job()).receipts.find((x) => x.kind === 'evidence' && x.label === label); const img = await fetch(SOCIAL + r.evidence_url, { headers: { cookie: `__Host-mls=${cA}` } }); const buf = Buffer.from(await img.arrayBuffer()); writeFileSync(`docs/evidence/${file}`, buf); return { sha256: r.evidence_sha256.slice(0, 16), bytes: buf.length }; };94step('preuve expurgée du compositeur enregistrée', await save('compositeur', 'preprod-compositeur.png'));95await call(SOCIAL, 'A', 'POST', `/v1/jobs/${j.id}/confirm`, { action: 'authorize_submit' }); await until(async () => ['VERIFIED', 'UNKNOWN_OUTCOME', 'FAILED'].includes((await job()).job.state), 'issue', 60000);96const fin = await job(); if (fin.job.state !== 'VERIFIED') throw new Error(`issue ${fin.job.state} : ${fin.job.state_reason}`);97step('publication soumise après confirmation, puis vérifiée visible', { state: fin.job.state, attempts: fin.attempts.map((a) => a.phase), url: fin.receipts.find((r) => r.kind === 'observed').external_url }); step('preuve expurgée du résultat enregistrée', await save('resultat', 'preprod-resultat.png'));98await sleep(4000); const again = await job(); step('aucune seconde soumission', { submittingAttempts: again.attempts.filter((a) => a.phase === 'submitting').length });99const chain = await call(SOCIAL, 'A', 'GET', '/v1/audit/verify'); step('chaîne d’audit vérifiée', chain);100ws.close(); writeFileSync('docs/evidence/preprod-run.json', JSON.stringify(out, null, 1)); console.log('TERMINÉ');101