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/session.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// One persistent Chromium per navigator session. The profile directory never leaves this Mac and is never read by this code.43import { chromium, type BrowserContext, type CDPSession, type FileChooser, type Page } from 'playwright';44import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';45import { join } from 'node:path';46import type { ViewerMsg } from '@mls/contracts';47import { checkNavigation, classifyUrl, isAddressBarUrlAllowed, type PolicyDocument } from '@mls/policy-engine';4849export type SessionHooks = { sendJson: (m: object) => void; sendFrame: (sessionId: string, n: number, w: number, h: number, jpeg: Buffer) => void; event: (sessionId: string, event: string, detail?: Record<string, string | number | boolean>) => void };50const MOD = { Alt: 1, Control: 2, Meta: 4, Shift: 8 } as const;51const BUTTONS = { none: 0, left: 1, right: 2, middle: 4 } as const;52const MAX_TABS = 6;5354export class BrowserSession {55 ctx: BrowserContext | null = null; active: Page | null = null; private cdp: CDPSession | null = null; private pages = new Map<Page, string>();56 private tabSeq = 0; private frameNo = 0; private viewers = 0; private casting = false; private chooser: FileChooser | null = null;57 private buttons = 0; private lastBlocked = 0; private lastCursor = 0; private cursorCss = ''; private lock = ''; private viewport = { w: 1280, h: 800 };58 /** Highest fencing token ever seen: anything lower is a stale holder and is ignored. */59 maxToken = 0; humanToken: number | null = null; agentToken: number | null = null; agentAbort: AbortController | null = null;60 state = 'UNINITIALIZED'; starting = false;61 constructor(public id: string, private profileRef: string, private profilesDir: string, private headed: boolean, public policy: PolicyDocument['navigator'], private hooks: SessionHooks) {}62 get running() { return !!this.ctx; }63 private get dir() { return join(this.profilesDir, this.profileRef); }6465 /** Never two processes on one profile: an exclusive lock file holds our pid; a lock left by a dead process is cleared. */66 private acquireLock() {67 mkdirSync(this.profilesDir, { recursive: true, mode: 0o700 }); const f = `${this.dir}.lock`;68 if (existsSync(f)) { const pid = Number(readFileSync(f, 'utf8')); let alive = false; try { if (pid) { process.kill(pid, 0); alive = pid !== process.pid; } } catch { alive = false; } if (alive) throw new Error(`profil déjà ouvert par le processus ${pid}`); unlinkSync(f); }69 closeSync(openSync(f, 'wx', 0o600)); writeFileSync(f, String(process.pid)); this.lock = f;70 }71 async start(startUrl: string | null) {72 if (this.ctx || this.starting) return; this.starting = true;73 try {74 this.acquireLock(); mkdirSync(this.dir, { recursive: true, mode: 0o700 });75 // A plain, visible Chromium. No evasion flags, no user-agent or fingerprint changes, no proxy.76 this.ctx = await chromium.launchPersistentContext(this.dir, { headless: !this.headed, viewport: { width: this.viewport.w, height: this.viewport.h }, acceptDownloads: false, serviceWorkers: 'block', locale: 'fr-CA', timezoneId: 'America/Toronto', chromiumSandbox: true,77 args: ['--no-first-run', '--no-default-browser-check', '--disable-sync', '--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding', '--disable-background-timer-throttling', '--password-store=basic', '--disable-features=Translate,MediaRouter'] });78 const ctx = this.ctx;79 await ctx.route('**/*', (route) => {80 const req = route.request(); const d = checkNavigation({ navigator: this.policy } as PolicyDocument, req.url());81 if (d.allow) return route.continue();82 if (req.isNavigationRequest() && req.frame() === req.frame().page().mainFrame() && Date.now() - this.lastBlocked > 1500) { this.lastBlocked = Date.now(); let host = ''; try { host = new URL(req.url()).hostname; } catch { /* */ } this.hooks.sendJson({ t: 'blocked', sessionId: this.id, reason: d.reason }); this.hooks.event(this.id, 'nav_blocked', { reason: d.reason, host }); }83 return route.abort('blockedbyclient');84 });85 await ctx.routeWebSocket(/.*/, (ws) => { if (checkNavigation({ navigator: this.policy } as PolicyDocument, ws.url()).allow) ws.connectToServer(); else ws.close({ code: 1008, reason: 'policy' }); });86 ctx.on('page', (p) => this.adopt(p)); ctx.on('close', () => { this.ctx = null; this.cleanup(); });87 for (const p of ctx.pages()) this.adopt(p);88 if (!this.active) this.adopt(await ctx.newPage());89 if (startUrl && isAddressBarUrlAllowed({ navigator: this.policy } as PolicyDocument, startUrl).allow && this.active!.url() === 'about:blank') await this.active!.goto(startUrl, { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});90 this.hooks.event(this.id, 'browser_started', { headed: this.headed });91 } catch (e) { await this.stop(); this.hooks.event(this.id, 'browser_failed', { reason: String((e as Error).message).slice(0, 180) }); throw e; } finally { this.starting = false; }92 }93 private adopt(p: Page) {94 if (this.pages.has(p)) return;95 if (this.pages.size >= MAX_TABS) { this.hooks.event(this.id, 'popup_blocked', { reason: 'max_tabs' }); p.close().catch(() => {}); return; }96 this.pages.set(p, `t${++this.tabSeq}`);97 p.on('close', () => { this.pages.delete(p); if (this.active === p) { this.active = null; const next = [...this.pages.keys()].pop(); if (next) this.activate(next).catch(() => {}); } this.emitTabs(); });98 p.on('framenavigated', (f) => { if (f === p.mainFrame()) { this.emitTabs(); if (p === this.active) this.emitUrl(); } });99 p.on('filechooser', (fc) => { this.chooser = fc; this.hooks.sendJson({ t: 'chooser', sessionId: this.id, open: true, multiple: fc.isMultiple() }); });100 p.on('download', (d) => { d.cancel().catch(() => {}); this.hooks.event(this.id, 'download_blocked', {}); this.hooks.sendJson({ t: 'notice', sessionId: this.id, code: 'download_blocked' }); });101 p.on('dialog', (d) => { this.hooks.sendJson({ t: 'notice', sessionId: this.id, code: 'dialog', message: d.type() }); (d.type() === 'beforeunload' ? d.accept() : d.dismiss()).catch(() => {}); });102 p.on('crash', () => this.hooks.event(this.id, 'browser_failed', { reason: 'page_crash' }));103 this.activate(p).catch(() => {});104 }105 private async activate(p: Page) {106 if (this.cdp) { await this.cdp.detach().catch(() => {}); this.cdp = null; this.casting = false; }107 this.active = p; await p.bringToFront().catch(() => {});108 this.cdp = await p.context().newCDPSession(p);109 this.cdp.on('Page.screencastFrame', (f: any) => {110 this.cdp?.send('Page.screencastFrameAck', { sessionId: f.sessionId }).catch(() => {});111 if (this.viewers > 0) this.hooks.sendFrame(this.id, ++this.frameNo, Math.round(f.metadata.deviceWidth), Math.round(f.metadata.deviceHeight), Buffer.from(f.data, 'base64'));112 });113 this.emitTabs(); this.emitUrl(); await this.syncCast(true);114 }115 private emitTabs() { this.hooks.sendJson({ t: 'tabs', sessionId: this.id, tabs: [...this.pages.entries()].map(([p, id]) => ({ id, title: '', url: safeUrl(p.url()), active: p === this.active })) }); this.titles(); }116 private async titles() { const tabs = await Promise.all([...this.pages.entries()].map(async ([p, id]) => ({ id, title: (await p.title().catch(() => '')).slice(0, 120), url: safeUrl(p.url()), active: p === this.active }))); this.hooks.sendJson({ t: 'tabs', sessionId: this.id, tabs }); }117 private async emitUrl() { if (this.active) this.hooks.sendJson({ t: 'url', sessionId: this.id, url: safeUrl(this.active.url()), title: (await this.active.title().catch(() => '')).slice(0, 160) }); }118 /** Frames are produced only while someone is watching; nothing is stored. */119 async setViewers(n: number) { this.viewers = n; await this.syncCast(n > 0); if (n > 0) { this.emitTabs(); this.emitUrl(); } }120 private async syncCast(restart = false) {121 if (!this.cdp) return;122 if (this.casting && (restart || this.viewers === 0)) { await this.cdp.send('Page.stopScreencast').catch(() => {}); this.casting = false; }123 if (this.viewers > 0 && !this.casting) { await this.cdp.send('Page.startScreencast', { format: 'jpeg', quality: 72, maxWidth: 2560, maxHeight: 1600, everyNthFrame: 1 }).catch(() => {}); this.casting = true; }124 }125 observed(): { observed: 'stopped' | 'login_required' | 'security_challenge' | 'ok'; url?: string } {126 if (!this.ctx || !this.active) return { observed: 'stopped' };127 const url = this.active.url(); return { observed: classifyUrl(url), url: safeUrl(url) };128 }129130 /* ── Lease / fencing ── */131 onLease(holderKind: 'human' | 'agent' | null, token: number | null) {132 if (token !== null && token < this.maxToken) return; // stale news133 if (token !== null) this.maxToken = token;134 if (holderKind === 'human') { this.humanToken = token; this.interruptAgent('prise de contrôle humaine'); }135 else if (holderKind === null) { this.humanToken = null; this.releaseInputs(); }136 else this.humanToken = null;137 }138 interruptAgent(reason: string) { if (this.agentAbort && !this.agentAbort.signal.aborted) { this.agentAbort.abort(new Error(reason)); this.hooks.event(this.id, 'agent_interrupted', { reason }); } this.agentToken = null; }139 private async releaseInputs() { if (this.buttons && this.active) { await this.active.mouse.up().catch(() => {}); this.buttons = 0; } }140141 /* ── Human input (only with the live human fencing token) ── */142 private chain: Promise<void> = Promise.resolve();143 /** Inputs are applied strictly in arrival order (a slow key must not be overtaken by the next one). */144 input(token: number, m: ViewerMsg): Promise<void> { this.chain = this.chain.then(() => this.apply(token, m)).catch(() => {}); return this.chain; }145 private async apply(token: number, m: ViewerMsg) {146 if (!this.active || !this.cdp || this.humanToken === null || token !== this.humanToken || token < this.maxToken) return;147 const p = this.active, cdp = this.cdp;148 switch (m.t) {149 case 'mouse': {150 const type = ({ move: 'mouseMoved', down: 'mousePressed', up: 'mouseReleased', wheel: 'mouseWheel' } as const)[m.type];151 if (m.type === 'down') this.buttons |= BUTTONS[m.button]; if (m.type === 'up') this.buttons &= ~BUTTONS[m.button];152 await cdp.send('Input.dispatchMouseEvent', { type, x: m.x, y: m.y, button: m.type === 'move' || m.type === 'wheel' ? 'none' : m.button, buttons: this.buttons, clickCount: m.type === 'down' || m.type === 'up' ? Math.max(1, m.clicks) : 0, modifiers: m.mods, deltaX: m.dx, deltaY: m.dy }).catch(() => {});153 if (m.type === 'move' && Date.now() - this.lastCursor > 150) { this.lastCursor = Date.now(); this.cursorAt(m.x, m.y).catch(() => {}); }154 break;155 }156 case 'key': {157 const k = m.key === ' ' ? 'Space' : m.key;158 try { if (m.type === 'down') await p.keyboard.down(k); else await p.keyboard.up(k); }159 catch { if (m.type === 'down' && [...m.key].length === 1) await p.keyboard.insertText(m.key).catch(() => {}); } // key outside the US layout (é, ç…)160 break;161 }162 case 'text': await p.keyboard.insertText(m.text).catch(() => {}); break;163 case 'touch': await cdp.send('Input.dispatchTouchEvent', { type: ({ start: 'touchStart', move: 'touchMove', end: 'touchEnd', cancel: 'touchCancel' } as const)[m.type], touchPoints: m.type === 'end' || m.type === 'cancel' ? [] : m.points.map((t) => ({ x: t.x, y: t.y, id: t.id })) }).catch(() => {}); break;164 case 'nav':165 if (m.op === 'back') await p.goBack({ timeout: 15000 }).catch(() => {}); else if (m.op === 'forward') await p.goForward({ timeout: 15000 }).catch(() => {}); else if (m.op === 'reload') await p.reload({ timeout: 30000 }).catch(() => {});166 else if (m.url) { const d = isAddressBarUrlAllowed({ navigator: this.policy } as PolicyDocument, m.url); if (!d.allow) this.hooks.sendJson({ t: 'blocked', sessionId: this.id, reason: d.reason }); else await p.goto(m.url, { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {}); }167 break;168 case 'tab': { const hit = [...this.pages.entries()].find(([, id]) => id === m.tabId)?.[0]; if (!hit) break; if (m.op === 'activate') await this.activate(hit); else if (this.pages.size > 1) await hit.close().catch(() => {}); break; }169 case 'zoom': await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: m.factor }).catch(() => {}); break;170 case 'cancelChooser': if (this.chooser) { await this.chooser.setFiles([]).catch(() => {}); this.chooser = null; this.hooks.sendJson({ t: 'chooser', sessionId: this.id, open: false, multiple: false }); } break;171 default: break;172 }173 }174 /** Cursor shape under the pointer, read in an isolated world: page scripts are not touched and cannot observe it. */175 private async cursorAt(x: number, y: number) {176 if (!this.cdp || !this.active) return;177 const tree = await this.cdp.send('Page.getFrameTree'); const w = await this.cdp.send('Page.createIsolatedWorld', { frameId: tree.frameTree.frame.id, worldName: 'mls-cursor' });178 const r = await this.cdp.send('Runtime.evaluate', { contextId: w.executionContextId, returnByValue: true, expression: `(()=>{const e=document.elementFromPoint(${Number(x)},${Number(y)});return e?getComputedStyle(e).cursor:'default'})()` });179 const css = String(r.result?.value ?? 'default').split(',').pop()!.trim().replace(/[^a-z-]/g, '') || 'default';180 if (css !== this.cursorCss) { this.cursorCss = css; this.hooks.sendJson({ t: 'cursor', sessionId: this.id, css }); }181 }182 async resize(w: number, h: number, dpr: number, mobile: boolean) {183 if (!this.cdp || !this.active || (this.agentToken !== null)) return; // never resize under an agent184 this.viewport = { w, h };185 if (mobile) { await this.cdp.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: dpr, mobile: true }).catch(() => {}); await this.cdp.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }).catch(() => {}); }186 else { await this.cdp.send('Emulation.clearDeviceMetricsOverride').catch(() => {}); await this.cdp.send('Emulation.setTouchEmulationEnabled', { enabled: false }).catch(() => {}); await this.active.setViewportSize({ width: w, height: h }).catch(() => {}); }187 await this.syncCast(true);188 }189 /** Human-triggered insertion of the approved text into whatever the human focused. */190 assistText(token: number, text: string): Promise<void> { this.chain = this.chain.then(async () => { if (this.active && this.humanToken !== null && token === this.humanToken) await this.active.keyboard.insertText(text); }).catch(() => {}); return this.chain; }191 async assistMedia(token: number, files: string[]) {192 if (this.humanToken === null || token !== this.humanToken) return;193 if (!this.chooser) return void this.hooks.sendJson({ t: 'notice', sessionId: this.id, code: 'no_file_chooser' });194 await this.chooser.setFiles(files).catch(() => {}); this.chooser = null; this.hooks.sendJson({ t: 'chooser', sessionId: this.id, open: false, multiple: false });195 }196 async stop() {197 this.interruptAgent('arrêt du navigateur'); const c = this.ctx; this.ctx = null;198 if (c) { await c.close().catch(() => {}); this.hooks.event(this.id, 'browser_stopped', {}); }199 this.cleanup();200 }201 private cleanup() { this.active = null; this.cdp = null; this.pages.clear(); this.casting = false; this.chooser = null; if (this.lock) { try { unlinkSync(this.lock); } catch { /* */ } this.lock = ''; } }202 /** Revocation: the profile (cookies, storage) is destroyed on disk. */203 async wipe() { await this.stop(); if (existsSync(this.dir)) { rmSync(this.dir, { recursive: true, force: true }); this.hooks.event(this.id, 'profile_wiped', {}); } }204 profileExists() { return existsSync(this.dir); }205}206/** URLs shown to the viewer or reported to the control plane lose their query string and fragment (they can carry tokens). */207export function safeUrl(u: string): string { try { const x = new URL(u); return `${x.origin}${x.pathname}`; } catch { return ''; } }208