Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : workers/navigator-worker/src/worker.ts9 * Module : workers10 * 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// Navigator worker: runs on the dedicated Mac, in a graphical user session. It only makes OUTBOUND, authenticated43// connections (HTTP to the control API, WebSocket to the gateway's loopback listener). It listens on no port.44import WebSocket from 'ws';45import { createHash } from 'node:crypto';46import { execFile } from 'node:child_process';47import { existsSync, mkdirSync, mkdtempSync, rmSync, statfsSync, writeFileSync } from 'node:fs';48import { tmpdir } from 'node:os';49import { join } from 'node:path';50import { ViewerMsg } from '@mls/contracts';51import type { PolicyDocument } from '@mls/policy-engine';52import { runRecipe, type RunOutcome } from '@mls/workflow-engine';53import { BrowserSession } from './session.ts';54import { PlaywrightDriver } from './driver.ts';5556export type WorkerConfig = { controlUrl: string; gatewayWsUrl: string; token: string; profilesDir: string; headed: boolean; version: string; heartbeatMs?: number; claimMs?: number; axBridge?: string; log?: (o: object) => void };57type Desired = { sessionId: string; profileRef: string; state: string; wanted: 'running' | 'stopped'; wipe: boolean; startUrl: string | null; lease: { holderKind: 'human' | 'agent'; fencingToken: number } | null };5859export class NavigatorWorker {60 sessions = new Map<string, BrowserSession>(); private ws: WebSocket | null = null; private timers: NodeJS.Timeout[] = []; private stopped = false; private busy = false; private beating = false;61 private emergency = false; private navigator: PolicyDocument['navigator'] | null = null; private wiped = new Set<string>(); private mediaDirs = new Map<string, string>(); private ax: { ax?: boolean; screen?: boolean } = {};62 constructor(private cfg: WorkerConfig) {}63 private log(o: object) { (this.cfg.log ?? ((x) => console.log(JSON.stringify({ at: new Date().toISOString(), ...x }))))(o); }64 private async http<T = any>(path: string, body: unknown, raw?: Buffer): Promise<{ status: number; json: T }> {65 const r = await fetch(`${this.cfg.controlUrl}${path}`, { method: 'POST', headers: { authorization: `Bearer ${this.cfg.token}`, 'content-type': raw ? 'application/octet-stream' : 'application/json' }, body: raw ? new Uint8Array(raw) : JSON.stringify(body), signal: AbortSignal.timeout(15000) });66 return { status: r.status, json: (await r.json().catch(() => ({}))) as T };67 }68 private hooks = {69 sendJson: (m: object) => { if (this.ws?.readyState === 1) this.ws.send(JSON.stringify(m)); },70 sendFrame: (sid: string, n: number, w: number, h: number, jpeg: Buffer) => { if (this.ws?.readyState !== 1 || this.ws.bufferedAmount > 3_000_000) return; const head = Buffer.alloc(44); head.write(sid, 0, 36, 'latin1'); head.writeUInt32BE(n >>> 0, 36); head.writeUInt16BE(w, 40); head.writeUInt16BE(h, 42); this.ws.send(Buffer.concat([head, jpeg]), { binary: true }); },71 event: (sessionId: string, event: string, detail: Record<string, string | number | boolean> = {}) => { this.http('/internal/worker/session-event', { sessionId, event, detail }).catch(() => {}); this.log({ msg: event, sessionId, ...detail }); },72 };7374 async start() {75 this.probeAx(); this.connect();76 // At boot the control API may not be up yet: keep going, the interval below retries every few seconds.77 await this.heartbeat().catch((e) => this.log({ msg: 'heartbeat_error', error: String(e?.message ?? e) }));78 this.timers.push(setInterval(() => this.heartbeat().catch((e) => this.log({ msg: 'heartbeat_error', error: String(e?.message ?? e) })), this.cfg.heartbeatMs ?? 3000));79 this.timers.push(setInterval(() => this.claim().catch((e) => this.log({ msg: 'claim_error', error: String(e?.message ?? e) })), this.cfg.claimMs ?? 3000));80 }81 async stop() { this.stopped = true; this.timers.forEach(clearInterval); this.ws?.terminate(); for (const s of this.sessions.values()) await s.stop(); for (const j of [...this.mediaDirs.keys()]) this.dropMedia(j); }8283 /** Level 3: the Swift Accessibility bridge is only asked for permission status here. Fixed argv, no shell. */84 private probeAx() { const b = this.cfg.axBridge; if (!b || !existsSync(b)) return; execFile(b, ['check'], { timeout: 5000 }, (err, out) => { if (!err) try { const j = JSON.parse(out); this.ax = { ax: !!j.accessibility, screen: !!j.screenRecording }; } catch { /* */ } }); }8586 private connect() {87 if (this.stopped) return;88 const ws = new WebSocket(this.cfg.gatewayWsUrl, { headers: { authorization: `Bearer ${this.cfg.token}` }, perMessageDeflate: false, maxPayload: 256 * 1024 });89 this.ws = ws;90 ws.on('message', (raw, isBinary) => { if (!isBinary) this.onGateway(raw.toString()).catch(() => {}); });91 ws.on('close', () => { if (this.ws === ws) this.ws = null; // without the gateway no human input can arrive; held buttons are released by lease expiry92 if (!this.stopped) setTimeout(() => this.connect(), 2000); });93 ws.on('error', () => ws.terminate());94 }95 private async onGateway(raw: string) {96 let m: any; try { m = JSON.parse(raw); } catch { return; }97 if (m.t === 'emergency') { if (m.engaged) { this.emergency = true; for (const s of this.sessions.values()) await s.stop(); } else this.emergency = false; return; }98 const s = this.sessions.get(m.sessionId); if (!s) return;99 switch (m.t) {100 case 'viewers': await s.setViewers(Number(m.count) || 0); break;101 case 'lease': s.onLease(m.holderKind ?? null, typeof m.fencingToken === 'number' ? m.fencingToken : null); break;102 case 'state': s.state = String(m.state); if (m.state !== 'BUSY') s.interruptAgent(`état ${m.state}`); if (m.wanted === 'stopped' || m.state === 'REVOKED') await s.stop(); break;103 case 'resize': await s.resize(m.w, m.h, m.dpr, m.mobile); break;104 case 'input': { const p = ViewerMsg.safeParse(m.msg); if (p.success && typeof m.fencingToken === 'number') await s.input(m.fencingToken, p.data); break; } // re-validated here: the worker does not trust the relay blindly105 case 'assist':106 if (m.kind === 'text' && typeof m.text === 'string') await s.assistText(m.fencingToken, m.text);107 else if (m.kind === 'media' && Array.isArray(m.media)) { const { files, dir } = await this.fetchMedia(m.media); try { await s.assistMedia(m.fencingToken, files); } finally { setTimeout(() => rmSync(dir, { recursive: true, force: true }), 120_000); } }108 break;109 }110 }111 /** Approved media only, fetched by short-lived signed URL, and checked against the approved SHA-256 before use. */112 private async fetchMedia(media: { sha256: string; name: string; url: string }[]) {113 const dir = mkdtempSync(join(tmpdir(), 'mls-media-')); const files: string[] = [];114 for (const m of media) {115 if (!/^[a-f0-9]{64}\.(jpg|png|webp)$/.test(m.name) || !m.url.startsWith('/media/s/')) throw new Error('media_ref_invalide');116 const r = await fetch(`${this.cfg.controlUrl}${m.url}`, { signal: AbortSignal.timeout(30000) }); if (!r.ok) throw new Error(`media_http_${r.status}`);117 const buf = Buffer.from(await r.arrayBuffer());118 if (createHash('sha256').update(buf).digest('hex') !== m.sha256) throw new Error('media_hash_different');119 const f = join(dir, m.name); writeFileSync(f, buf, { mode: 0o600 }); files.push(f);120 }121 return { files, dir };122 }123124 async heartbeat() {125 if (this.beating) return; this.beating = true;126 try {127 let freeDiskGb: number | undefined; try { const st = statfsSync(this.cfg.profilesDir); freeDiskGb = Math.round((st.bavail * st.bsize) / 1e9); } catch { mkdirSync(this.cfg.profilesDir, { recursive: true, mode: 0o700 }); }128 const obs = [...this.sessions.values()].filter((s) => !this.wiped.has(s.id)).map((s) => ({ sessionId: s.id, ...s.observed() }));129 const r = await this.http<{ emergencyStop: boolean; navigator: PolicyDocument['navigator']; sessions: Desired[] }>('/v1/workers/heartbeat', { sessions: obs, info: { version: this.cfg.version, headed: this.cfg.headed, freeDiskGb, axPermission: this.ax.ax, screenPermission: this.ax.screen } });130 if (r.status !== 200) { this.log({ msg: 'heartbeat_refused', status: r.status }); return; }131 this.emergency = r.json.emergencyStop; this.navigator = r.json.navigator;132 const seen = new Set<string>();133 for (const d of r.json.sessions) {134 seen.add(d.sessionId);135 let s = this.sessions.get(d.sessionId);136 if (!s) { s = new BrowserSession(d.sessionId, d.profileRef, this.cfg.profilesDir, this.cfg.headed, r.json.navigator, this.hooks); this.sessions.set(d.sessionId, s); }137 s.policy = r.json.navigator; s.state = d.state;138 s.onLease(d.lease?.holderKind ?? null, d.lease?.fencingToken ?? null);139 if (d.state !== 'BUSY') s.interruptAgent(`état ${d.state}`);140 if (d.wipe) { if (!this.wiped.has(d.sessionId)) { await s.wipe(); this.wiped.add(d.sessionId); } continue; }141 if (d.wanted === 'running' && !this.emergency) { if (!s.running && !s.starting) s.start(d.startUrl).catch((e) => this.log({ msg: 'start_failed', sessionId: d.sessionId, error: String(e?.message ?? e) })); }142 else if (s.running) await s.stop();143 }144 for (const [id, s] of this.sessions) if (!seen.has(id)) { await s.stop(); this.sessions.delete(id); }145 } finally { this.beating = false; }146 }147148 private dropMedia(jobId: string, only?: string) { const d = this.mediaDirs.get(jobId); if (d && (!only || only === d)) { rmSync(d, { recursive: true, force: true }); this.mediaDirs.delete(jobId); } }149150 /* ── Agent tasks ── */151 private async claim() {152 if (this.busy || this.emergency || this.stopped) return;153 if (![...this.sessions.values()].some((s) => s.running && s.state === 'READY')) return;154 this.busy = true;155 try { const r = await this.http<{ task: any }>('/internal/worker/claim', {}); if (r.status === 200 && r.json.task) await this.runTask(r.json.task); } finally { this.busy = false; }156 }157 private async runTask(t: { kind: 'prepare' | 'submit' | 'verify'; jobId: string; sessionId: string; fencingToken: number; recipe: any; vars: Record<string, string>; flags: Record<string, boolean>; media: { sha256: string; name: string; url: string }[] }) {158 const s = this.sessions.get(t.sessionId);159 const report = (event: string, extra: object = {}) => this.http(`/internal/worker/jobs/${t.jobId}/report`, { event, fencingToken: t.fencingToken, ...extra });160 if (!s || !s.active || t.fencingToken < s.maxToken || s.humanToken !== null) { await report(t.kind === 'prepare' ? 'aborted' : 'aborted', { error: 'session indisponible ou contrôlée par un humain' }); return; }161 s.maxToken = t.fencingToken; s.agentToken = t.fencingToken; s.state = 'BUSY';162 const abort = new AbortController(); s.agentAbort = abort;163 let out: RunOutcome | null = null; let submittingReported = false;164 try {165 const fetched = t.kind === 'prepare' && t.media.length ? await this.fetchMedia(t.media) : { files: [], dir: null as string | null };166 // The browser reads the files when the form is submitted, so they must outlive the preparation task.167 if (fetched.dir) { this.dropMedia(t.jobId); this.mediaDirs.set(t.jobId, fetched.dir); setTimeout(() => this.dropMedia(t.jobId, fetched.dir!), 6 * 3600_000).unref(); }168 const page = s.active;169 const driver = new PlaywrightDriver(page, async (png) => { const r = await this.http<{ ref: string; sha256: string }>('/internal/worker/evidence', null, png); if (r.status !== 200) throw new Error('depot_preuve_refuse'); return r.json; });170 out = await runRecipe(t.recipe, driver, {171 vars: t.vars as any, flags: t.flags as any, approvedMediaPaths: fetched.files, signal: abort.signal,172 guard: async () => { // local fencing first (instant), then the authoritative check173 if (abort.signal.aborted || s.agentToken !== t.fencingToken || s.humanToken !== null || this.emergency) return { ok: false, reason: 'bail_perdu_localement' };174 const r = await this.http<{ ok: boolean; reason?: string }>('/internal/worker/lease-check', { sessionId: t.sessionId, fencingToken: t.fencingToken, jobId: t.jobId }).catch(() => ({ status: 0, json: { ok: false, reason: 'controle_injoignable' } }));175 return r.json.ok ? { ok: true } : { ok: false, reason: r.json.reason ?? 'refus' };176 },177 beforeExternalEffect: async () => { const r = await report('submitting'); if (r.status !== 200) throw new Error('marqueur_de_soumission_refuse'); submittingReported = true; if (abort.signal.aborted) throw new Error('interrompu_avant_le_clic'); },178 afterExternalEffect: async () => { await report('submitted').catch(() => {}); },179 });180 } catch (e) { out = out ?? { status: 'failed', externalEffectAttempted: submittingReported, steps: [], inspected: {}, evidence: [], reason: String((e as Error).message).slice(0, 280) }; }181 finally { if (s.agentAbort === abort) { s.agentAbort = null; s.agentToken = null; } if (t.kind === 'verify') this.dropMedia(t.jobId); }182 const base = { steps: out.steps, evidence: out.evidence, error: out.reason };183 this.log({ msg: 'task_done', kind: t.kind, jobId: t.jobId, status: out.status, failedStep: out.failedStep, reason: out.reason });184 try {185 if (t.kind === 'prepare') await report(out.status === 'awaiting_approval' ? 'prepared' : out.status === 'aborted' ? 'aborted' : 'prepare_failed', base);186 else if (t.kind === 'submit') {187 // After the durable "submitting" marker nothing is reported as a failure: an unclear result is left for the188 // sweeper to mark UNKNOWN_OUTCOME. Before it, nothing was clicked and saying so is safe.189 if (!submittingReported) await report(out.status === 'aborted' ? 'aborted' : 'submit_failed_before_click', base);190 } else await report(out.status === 'completed' ? 'verified' : 'not_found', { ...base, externalUrl: out.status === 'completed' && out.finalUrl ? out.finalUrl : null });191 } catch (e) { this.log({ msg: 'report_error', jobId: t.jobId, error: String((e as Error).message) }); }192 }193}194