SPB Git

Repository Public

navigator.test.ts 32.9 KB 290 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : tests/e2e/navigator.test.ts9 * Module           : tests10 * 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// End-to-end on a real Chromium (headless by default; MLS_E2E_HEADED=1 for a visible window), a real gateway,43// a real worker and the synthetic fixture platform. No third-party site is contacted.44import { afterAll, beforeAll, describe, expect, it } from 'vitest';45import { existsSync, readdirSync, readFileSync } from 'node:fs';46import { join } from 'node:path';47import WebSocket from 'ws';48import sharp from 'sharp';49import type { Page } from 'playwright';50import { approvedContent, fixturePage, inMinutes, type TestUser } from '../helpers.ts';51import { makeStack, sleep, until, type Stack, type Viewer } from './harness.ts';52import { sweep } from '../../services/control-api/src/core/jobs.ts';5354let S: Stack; let owner: TestUser; let W: Awaited<ReturnType<Stack['startWorker']>>; let sid: string; let V: Viewer; let brand: string, pageId: string; const PASSWORD = 'Atelier-2026-zq'; const measures: Record<string, unknown> = {};55const st = async (id = sid) => (await S.env.db.one('SELECT state FROM navigator_sessions WHERE id=$1', [id]))!.state as string;56const job = async (id: string) => (await S.env.db.one('SELECT state, state_reason, mode FROM publication_jobs WHERE id=$1', [id]))!;57const page = (id = sid): Page => W.worker.sessions.get(id)!.active!;58/** Centre of an element in viewport pixels — used only to know WHERE to click; the click itself travels viewer → gateway → worker. */59const centre = async (p: Page, sel: string) => { const b = (await p.locator(sel).boundingBox())!; return { x: Math.round(b.x + b.width / 2), y: Math.round(b.y + b.height / 2) }; };60const click = async (v: Viewer, p: Page, sel: string) => { const c = await centre(p, sel); v.send({ t: 'mouse', type: 'move', ...c }); v.send({ t: 'mouse', type: 'down', ...c, button: 'left', clicks: 1 }); v.send({ t: 'mouse', type: 'up', ...c, button: 'left', clicks: 1 }); await sleep(120); };61const type = async (v: Viewer, text: string) => { for (const ch of text) { v.send({ t: 'key', type: 'down', key: ch, code: '' }); v.send({ t: 'key', type: 'up', key: ch, code: '' }); } await sleep(150); };62let seq = 0;63async function newJob(mode: string, body?: string) { const text = body ?? `Publication de démonstration ${++seq}.`; const ok = await approvedContent(S.env, owner, await approver(), brand, pageId, text); const j = await S.env.call(owner, 'POST', '/v1/jobs', { contentId: ok.contentId, scheduledAt: inMinutes(-1), mode }); if (j.status !== 200) throw new Error(JSON.stringify(j.json)); return { id: j.json.job.id as string, text, ...ok }; }64let _ap: TestUser | null = null; const approver = async () => (_ap ??= await S.env.user('admin'));6566beforeAll(async () => {67  S = await makeStack(); owner = S.owner; ({ brandId: brand, pageId } = await fixturePage(S.env, owner, 'maclustr', 'page-1001', 'Atelier Démo'));68  await S.env.call(owner, 'PATCH', `/v1/brands/${brand}`, { frequency: { maxPerDay: 20, minIntervalMinutes: 0 } });69  const pol = (await S.env.call(owner, 'GET', '/v1/policy')).json.active; delete pol._version; pol.frequency = { hardMaxPerPagePerDay: 20, hardMinIntervalMinutes: 0 };70  expect((await S.env.call(owner, 'POST', '/v1/policy', { document: pol, note: 'Essais bout en bout : limites de fréquence levées sur la fixture.' })).status).toBe(200);71  W = await S.startWorker('mac-e2e');72}, 120000);73afterAll(async () => { console.log('MESURES E2E', JSON.stringify(measures)); await S?.close(); }, 60000);7475describe('P1 — navigateur distant et contrôle manuel', () => {76  it('la poignée WebSocket refuse : origine absente ou étrangère, pas de cookie, cookie invalide, session inconnue', async () => {77    const s = (await S.nav(owner, 'POST', '/v1/navigator/sessions', { label: 'Principale', workerId: W.id, startUrl: `${S.site.url}/pages/page-1001` })).json; sid = s.id; expect(s.state).toBe('UNINITIALIZED');78    await expect(S.viewer(owner, sid, { origin: null })).rejects.toThrow('HTTP 403'); await expect(S.viewer(owner, sid, { origin: 'https://evil.example' })).rejects.toThrow('HTTP 403');79    await expect(S.viewer(null, sid)).rejects.toThrow('HTTP 401'); await expect(S.viewer(owner, sid, { cookie: 'mls=forged' })).rejects.toThrow('HTTP 401');80    await expect(S.viewer(owner, '00000000-0000-4000-8000-000000000000')).rejects.toThrow('HTTP 404');81    const editor = await S.env.user('editor'); await expect(S.viewer(editor, sid)).rejects.toThrow('HTTP 401'); // role too low82    // the worker socket: not from a browser origin, not without a token83    const tryWorker = (headers: Record<string, string>) => new Promise<string>((res) => { const w = new WebSocket(`ws://127.0.0.1:${S.gwInternal}/worker`, { headers }); w.on('open', () => { w.close(); res('open'); }); w.on('unexpected-response', (_q, r) => res(`HTTP ${r.statusCode}`)); w.on('error', () => res('error')); });84    expect(await tryWorker({})).toBe('HTTP 401'); expect(await tryWorker({ authorization: 'Bearer ' + 'x'.repeat(50) })).toBe('HTTP 401'); expect(await tryWorker({ authorization: `Bearer ${W.token}`, origin: S.navOrigin })).toBe('HTTP 401');85    // the public port does not expose the worker endpoint or the internal API at all86    expect((await fetch(`${S.navOrigin}/internal/notify`, { method: 'POST' })).status).toBe(404); expect((await fetch(`${S.navOrigin}/worker`)).status).toBe(404);87  });88  it('le worker ouvre le navigateur ; le site demande une connexion → LOGIN_REQUIRED', async () => {89    await until(async () => (await st()) === 'LOGIN_REQUIRED', 'LOGIN_REQUIRED', 30000); expect(page().url()).toContain('/login');90  });91  it('sans le contrôle, un spectateur voit l’écran mais aucune entrée n’est transmise', async () => {92    V = await S.viewer(owner, sid); const hello = await V.wait((m) => m.t === 'hello', 'hello'); expect(hello.lease.mine).toBe(false); expect(hello.policy).toEqual({ clipboard: false, insertApprovedText: true });93    await until(() => V.frames.length > 0, 'première trame'); expect(V.frames[0].w).toBe(1280); expect(V.frames[0].h).toBe(800);94    const before = await page().locator('#u').inputValue(); await click(V, page(), '#u'); await type(V, 'intrus'); await V.wait((m) => m.t === 'error' && m.code === 'no_control', 'refus no_control');95    expect(await page().locator('#u').inputValue()).toBe(before);96  });97  it('connexion manuelle par l’administrateur dans le vrai site, au clavier et à la souris, à travers la passerelle', async () => {98    const t = await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/takeover`, {}); expect(t.status).toBe(200); expect(t.json.state).toBe('MANUAL_CONTROL');99    await V.wait((m) => m.t === 'lease' && m.mine === true, 'bail obtenu');100    const f0 = V.frames.length; await click(V, page(), '#u'); await type(V, 'admin-démo'); await click(V, page(), '#p'); await type(V, PASSWORD);101    expect(await page().locator('#u').inputValue()).toBe('admin-démo'); // includes a key outside the US layout102    V.send({ t: 'key', type: 'down', key: 'Enter', code: 'Enter' }); V.send({ t: 'key', type: 'up', key: 'Enter', code: 'Enter' });103    await until(() => page().url().endsWith('/pages/page-1001'), 'connecté'); expect(V.frames.length).toBeGreaterThan(f0);104    await V.wait((m) => m.t === 'url' && m.url.endsWith('/pages/page-1001'), 'URL annoncée au spectateur');105  });106  it('le mot de passe saisi n’apparaît nulle part : ni audit, ni journaux du worker, ni base', async () => {107    const dump = JSON.stringify((await S.env.db.query('SELECT * FROM audit_events')).rows) + JSON.stringify(S.logs) + JSON.stringify((await S.env.db.query('SELECT * FROM navigator_sessions')).rows) + JSON.stringify((await S.env.db.query('SELECT * FROM outbox_events')).rows) + JSON.stringify(S.env.notified);108    expect(dump).not.toContain(PASSWORD); expect(dump).not.toContain('admin-démo'); expect(dump).not.toMatch(/fx_session/);109    const evidence = join(S.env.cfg.dataDir, 'evidence'); expect(existsSync(evidence) ? readdirSync(evidence) : []).toEqual([]); // nothing was captured during login110  });111  it('défilement, molette, redimensionnement, zoom, onglets et navigation', async () => {112    V.send({ t: 'resize', w: 390, h: 760, dpr: 2, mobile: true }); await until(() => V.frames.some((f) => f.w === 390), 'trame mobile 390 px'); expect(await page().evaluate(() => window.innerWidth)).toBe(390);113    V.send({ t: 'touch', type: 'start', points: [{ x: 100, y: 400, id: 0 }] }); V.send({ t: 'touch', type: 'end', points: [] });114    V.send({ t: 'resize', w: 1280, h: 800, dpr: 1, mobile: false }); await until(async () => (await page().evaluate(() => window.innerWidth)) === 1280, 'retour bureau');115    V.send({ t: 'zoom', factor: 1.5 }); V.send({ t: 'zoom', factor: 1 });116    V.send({ t: 'nav', op: 'goto', url: `${S.site.url}/pages/page-1001/insights` }); await until(() => page().url().endsWith('/insights'), 'goto'); V.send({ t: 'nav', op: 'back' }); await until(() => page().url().endsWith('/pages/page-1001'), 'back');117    V.send({ t: 'mouse', type: 'wheel', x: 600, y: 400, dy: 300 }); V.send({ t: 'nav', op: 'reload' }); await sleep(300);118    expect(V.last('tabs').tabs).toHaveLength(1);119  });120  it('domaines : hors liste refusé à la barre d’adresse ; réseau interne bloqué dans le navigateur ; presse-papiers et téléchargements fermés', async () => {121    const n0 = V.msgs.filter((m) => m.t === 'blocked').length;122    for (const u of ['https://example.org/', 'http://169.254.169.254/latest/meta-data/', `${S.ctlUrl}/v1/me`, 'file:///etc/passwd']) V.send({ t: 'nav', op: 'goto', url: u });123    await until(() => V.msgs.filter((m) => m.t === 'blocked').length >= n0 + 4, '4 refus'); expect(page().url()).toContain('/pages/page-1001');124    // a link inside the page pointing at the control API (loopback) is aborted by the browser-side policy, not just by the address bar125    const r = await page().evaluate(async (u) => { try { const x = await fetch(u, { mode: 'no-cors' }); return `ok ${x.status}`; } catch (e) { return 'blocked'; } }, `${S.ctlUrl}/health/live`); expect(r).toBe('blocked');126    await page().evaluate((u) => { location.href = u; }, 'https://example.org/sortie'); await until(async () => (await S.env.db.one("SELECT count(*)::int AS n FROM audit_events WHERE action='worker.nav_blocked'"))!.n >= 1, 'blocage journalisé');127    expect(page().url()).not.toContain('example.org');128    expect(await page().evaluate(() => (navigator.clipboard ? navigator.clipboard.readText().then(() => 'read', () => 'denied') : 'denied'))).toBe('denied');129    expect((await S.env.db.one("SELECT count(*)::int AS n FROM audit_events WHERE action='viewer.nav_refused'"))!.n).toBeGreaterThanOrEqual(4);130    await page().goto(`${S.site.url}/pages/page-1001`);131  });132  it('confirmation explicite de la session et des pages ; libération → READY', async () => {133    expect((await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/confirm`, { pageIds: [pageId], attest: true })).status).toBe(200);134    expect((await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/release`, {})).json.state).toBe('READY'); await V.wait((m) => m.t === 'lease' && m.mine === false, 'bail rendu');135    click(V, page(), 'a[href$="/composer"]'); await V.wait((m) => m.t === 'error' && m.code === 'no_control' && V.msgs.indexOf(m) > V.msgs.findIndex((x) => x.t === 'lease' && x.mine === false), 'entrée refusée après libération');136  });137  it('latence aller-retour et débit d’images mesurés (réseau local de test)', async () => {138    const rt: number[] = []; for (let i = 0; i < 10; i++) { const t0 = performance.now(); V.send({ t: 'ping', n: 1000 + i }); await V.wait((m) => m.t === 'pong' && m.n === 1000 + i, 'pong'); rt.push(performance.now() - t0); }139    measures.pingMsMedian = Number(rt.sort((a, b) => a - b)[5].toFixed(1)); measures.framesReceived = V.frames.length; measures.frameKbMedian = Math.round(V.frames.map((f) => f.bytes).sort((a, b) => a - b)[Math.floor(V.frames.length / 2)] / 1024);140    expect(measures.pingMsMedian as number).toBeLessThan(500);141  });142});143144describe('P3/P6 — recettes, approbation et publication sur la page de test', () => {145  it('une seule publication approuvée : préparation → confirmation humaine → soumission → vérification visible', async () => {146    const j = await newJob('auto_submit', 'MacLustr Social : première publication de démonstration.\nUne seule, approuvée.');147    await until(async () => (await job(j.id)).state === 'AWAITING_CONFIRMATION', 'compositeur prêt', 30000);148    expect(S.site.posts).toHaveLength(0); expect(S.site.publishRequests).toBe(0); // prepared, NOT published149    expect(await page().getByLabel('Texte de la publication').inputValue()).toBe(j.text); expect(await st()).toBe('READY');150    const d1 = (await S.env.call(owner, 'GET', `/v1/jobs/${j.id}`)).json; const ev = d1.receipts.find((r: any) => r.kind === 'evidence'); expect(ev.label).toBe('compositeur');151    const png = await S.env.call(owner, 'GET', ev.evidence_url); expect(png.status).toBe(200); expect((await sharp(png.raw).metadata()).format).toBe('png');152    await sleep(1200); expect((await job(j.id)).state).toBe('AWAITING_CONFIRMATION'); expect(S.site.publishRequests).toBe(0); // still waiting: nothing happens without a human153    expect((await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/confirm`, { action: 'authorize_submit' })).status).toBe(200);154    await until(async () => (await job(j.id)).state === 'VERIFIED', 'vérifiée', 30000);155    expect(S.site.posts).toHaveLength(1); expect(S.site.posts[0]).toMatchObject({ pageId: 'page-1001', text: j.text }); expect(S.site.publishRequests).toBe(1);156    const d2 = (await S.env.call(owner, 'GET', `/v1/jobs/${j.id}`)).json; expect(d2.attempts.map((a: any) => a.phase)).toEqual(['prepare', 'submitting', 'verify']);157    expect(d2.receipts.find((r: any) => r.kind === 'observed').external_url).toContain('/pages/page-1001'); expect(d2.receipts.filter((r: any) => r.kind === 'evidence').map((r: any) => r.label)).toEqual(['compositeur', 'resultat']);158    await sleep(1500); expect(S.site.publishRequests).toBe(1); // and it is never submitted again159  }, 90000);160  it('avec image : seul le média approuvé, vérifié par son hash, est joint', async () => {161    const b = '----x'; const img = await sharp({ create: { width: 640, height: 400, channels: 3, background: '#aa5500' } }).jpeg().toBuffer();162    const body = Buffer.concat([Buffer.from(`--${b}\r\nContent-Disposition: form-data; name="brandId"\r\n\r\n${brand}\r\n--${b}\r\nContent-Disposition: form-data; name="file"; filename="a.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`), img, Buffer.from(`\r\n--${b}--\r\n`)]);163    const m = await S.env.call(owner, 'POST', '/v1/media', body, { headers: { 'content-type': `multipart/form-data; boundary=${b}` } }); expect(m.status).toBe(200);164    await S.env.call(owner, 'POST', `/v1/media/${m.json.id}/rights`, { owner: 'SP Boucher', license: 'Création interne', source: 'Essai', thirdPartyListing: false, attest: true, altText: 'Rectangle orange.' });165    const c = await S.env.call(owner, 'POST', '/v1/content', { brandId: brand, pageId, title: 'Image', payload: { lang: 'fr', body: 'Publication avec image.', mediaSha256: [m.json.sha256], altText: 'Rectangle orange.' } }); await S.env.call(owner, 'POST', `/v1/content/${c.json.id}/submit`, {});166    await S.env.call(await approver(), 'POST', `/v1/content/${c.json.id}/approve`, { versionId: c.json.version.id, contentHash: c.json.version.content_hash, pageId, decision: 'approve' });167    const j = (await S.env.call(owner, 'POST', '/v1/jobs', { contentId: c.json.id, scheduledAt: inMinutes(-1), mode: 'auto_submit' })).json.job;168    await until(async () => (await job(j.id)).state === 'AWAITING_CONFIRMATION', 'prêt avec média', 30000); expect(await page().getByTestId('media-ready').innerText()).toBe('1 média(s) prêt(s)');169    await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/confirm`, { action: 'authorize_submit' }); await until(async () => (await job(j.id)).state === 'VERIFIED', 'vérifiée', 30000).catch(async (e) => { throw new Error(e.message + JSON.stringify(await job(j.id)) + JSON.stringify(S.logs.slice(-5)) + JSON.stringify(S.site.posts.at(-1))); });170    expect(S.site.posts.at(-1)!.media).toEqual([{ name: `${m.json.sha256}.jpg`, bytes: expect.any(Number) }]);171  }, 90000);172  it('prise de contrôle humaine pendant le travail de l’agent : interruption immédiate, rien de publié', async () => {173    S.site.knobs.slowMs = 1500; const before = S.site.publishRequests; const j = await newJob('auto_submit');174    await until(async () => (await st()) === 'BUSY', 'agent au travail', 20000);175    const t0 = Date.now(); const t = await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/takeover`, {}); expect(t.json.state).toBe('MANUAL_CONTROL');176    await until(() => S.logs.some((l: any) => l.msg === 'agent_interrupted' && l.sessionId === sid), 'agent interrompu', 5000); measures.takeoverInterruptMs = Date.now() - t0;177    await until(async () => (await job(j.id)).state === 'QUEUED', 'tâche remise en file', 15000);178    expect(S.site.publishRequests).toBe(before); expect(await st()).toBe('MANUAL_CONTROL'); expect((await S.env.db.one("SELECT count(*)::int AS n FROM job_attempts WHERE job_id=$1 AND phase='submitting'", [j.id]))!.n).toBe(0);179    await sleep(1500); expect((await job(j.id)).state).toBe('QUEUED'); // while the human holds the session, the agent does not come back180    S.site.knobs.slowMs = 0; await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/cancel`, {}); await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/release`, {});181  }, 90000);182  it('changement de DOM (bouton renommé) : aucun clic, aucune soumission, la tâche attend un humain', async () => {183    const j = await newJob('auto_submit'); await until(async () => (await job(j.id)).state === 'AWAITING_CONFIRMATION', 'prêt', 30000); const before = S.site.publishRequests;184    S.site.knobs.variant = 'renamed_button'; const text = await page().getByLabel('Texte de la publication').inputValue(); await page().reload(); await page().getByLabel('Texte de la publication').fill(text); // the site changed under us185    await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/confirm`, { action: 'authorize_submit' });186    await until(async () => /soumission non tentée/.test((await job(j.id)).state_reason), 'soumission non tentée', 30000);187    expect((await job(j.id)).state).toBe('AWAITING_CONFIRMATION'); expect(S.site.publishRequests).toBe(before); expect((await S.env.db.one("SELECT count(*)::int AS n FROM job_attempts WHERE job_id=$1 AND phase='submitting'", [j.id]))!.n).toBe(0);188    S.site.knobs.variant = 'a'; await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/cancel`, {});189  }, 90000);190  it('changement de DOM (champ renommé) et modale : préparation en échec borné, puis lettre morte — jamais d’improvisation', async () => {191    S.site.knobs.variant = 'moved_composer'; const j = await newJob('auto_submit');192    await until(async () => { await S.env.db.query("UPDATE publication_jobs SET next_run_at=now() WHERE id=$1 AND state='QUEUED'", [j.id]); return (await job(j.id)).state === 'FAILED'; }, 'lettre morte', 60000, 300);193    const d = (await S.env.call(owner, 'GET', `/v1/jobs/${j.id}`)).json; expect(d.job.dead_letter).toBe(true); expect(d.attempts).toHaveLength(3); expect(d.attempts[0].steps.find((s: any) => s.id === 'texte').status).toBe('failed');194    S.site.knobs.variant = 'a'; S.site.knobs.modal = true; const k = await newJob('auto_submit'); // a modal covers the form: Playwright's actionability check still fills the labelled field; the capture shows the modal195    await until(async () => ['AWAITING_CONFIRMATION', 'FAILED'].includes((await job(k.id)).state), 'modale traitée', 30000); S.site.knobs.modal = false; await S.env.call(owner, 'POST', `/v1/jobs/${k.id}/cancel`, {});196    await until(async () => (await S.env.db.one("SELECT count(*)::int AS n FROM alerts WHERE kind='dead_letter' AND status='open'"))!.n >= 1, 'alerte lettre morte', 15000);197  }, 120000);198  it('résultat ambigu (la plateforme accepte puis rien n’apparaît) : UNKNOWN_OUTCOME, alerte, aucune republication', async () => {199    S.site.knobs.publishMode = 'silent_drop'; const j = await newJob('auto_submit'); await until(async () => (await job(j.id)).state === 'AWAITING_CONFIRMATION', 'prêt', 30000); const before = S.site.publishRequests;200    await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/confirm`, { action: 'authorize_submit' }); await until(async () => (await job(j.id)).state === 'UNKNOWN_OUTCOME', 'résultat inconnu', 40000);201    expect(S.site.publishRequests).toBe(before + 1); await sleep(2500); for (let i = 0; i < 3; i++) await S.env.db.tx((tx) => sweep(tx)); await sleep(1500);202    expect(S.site.publishRequests).toBe(before + 1); expect((await job(j.id)).state).toBe('UNKNOWN_OUTCOME'); S.site.knobs.publishMode = 'ok';203    await until(async () => (await S.env.db.one("SELECT count(*)::int AS n FROM alerts WHERE kind='unknown_outcome' AND status='open'"))!.n >= 1, 'alerte', 15000);204    expect((await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/reconcile`, { outcome: 'not_published', note: 'Absente de la page après vérification manuelle.' })).json.state).toBe('FAILED');205  }, 120000);206  it('erreur réseau/serveur à la soumission : pas de nouvel essai automatique', async () => {207    S.site.knobs.publishMode = 'error500'; const j = await newJob('auto_submit'); await until(async () => (await job(j.id)).state === 'AWAITING_CONFIRMATION', 'prêt', 30000); const before = S.site.publishRequests;208    await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/confirm`, { action: 'authorize_submit' }); await until(async () => (await job(j.id)).state === 'UNKNOWN_OUTCOME', 'résultat inconnu', 40000);209    await sleep(2000); expect(S.site.publishRequests).toBe(before + 1); S.site.knobs.publishMode = 'ok'; await page().goto(`${S.site.url}/pages/page-1001`);210  }, 120000);211  it('mode « préparer seulement » : l’humain clique lui-même Publier dans le navigateur distant, puis la machine vérifie', async () => {212    const j = await newJob('prepare_only'); await until(async () => (await job(j.id)).state === 'AWAITING_CONFIRMATION', 'prêt', 30000);213    expect((await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/confirm`, { action: 'authorize_submit' })).status).toBe(403); // the machine may not click here214    await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/takeover`, {}); await V.wait((m) => m.t === 'lease' && m.mine === true && V.msgs.indexOf(m) > V.msgs.length - 6, 'bail'); const before = S.site.posts.length;215    await page().getByRole('button', { name: 'Publier' }).scrollIntoViewIfNeeded(); await click(V, page(), 'button[type=submit]'); await until(() => S.site.posts.length === before + 1, 'publié par l’humain');216    await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/release`, {}); expect((await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/confirm`, { action: 'human_published' })).json.state).toBe('SUBMITTED');217    await until(async () => (await job(j.id)).state === 'VERIFIED', 'vérifiée par la machine', 30000); expect(S.site.posts.at(-1)!.text).toBe(j.text);218  }, 90000);219  it('flux manuel assisté (celui de Facebook) : insertion du texte approuvé et du média à la demande de l’humain, attestation humaine', async () => {220    const j = await newJob('manual_assisted', 'Texte approuvé à insérer à la main.'); await until(async () => (await job(j.id)).state === 'AWAITING_CONFIRMATION', 'créneau atteint', 20000);221    await sleep(800); expect(page().url()).not.toContain('/composer'); // no automation ran for this job222    const assist = (await S.nav(owner, 'GET', `/v1/navigator/sessions/${sid}/assist`)).json.jobs; expect(assist.map((a: any) => a.id)).toContain(j.id);223    await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/takeover`, {}); await until(() => W.worker.sessions.get(sid)!.humanToken !== null, 'bail côté worker');224    V.send({ t: 'nav', op: 'goto', url: `${S.site.url}/pages/page-1001/composer` }); await until(() => page().url().endsWith('/composer'), 'compositeur');225    await click(V, page(), '#t'); V.send({ t: 'insertApproved', jobId: j.id }); await until(async () => (await page().locator('#t').inputValue()) === j.text, 'texte inséré');226    V.send({ t: 'insertApproved', jobId: '00000000-0000-4000-8000-000000000000' }); await V.wait((m) => m.t === 'error' && m.code === 'not_found', 'tâche inconnue refusée');227    await click(V, page(), '#f'); await V.wait((m) => m.t === 'chooser' && m.open === true, 'sélecteur de fichiers intercepté'); V.send({ t: 'cancelChooser' }); await V.wait((m) => m.t === 'chooser' && m.open === false, 'sélecteur annulé');228    const before = S.site.posts.length; await click(V, page(), 'button[type=submit]'); await until(() => S.site.posts.length === before + 1, 'publié à la main');229    await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/release`, {});230    expect((await S.nav(owner, 'POST', `/v1/jobs/${j.id}/confirm`, { action: 'human_published', externalUrl: `${S.site.url}/pages/page-1001` })).json.state).toBe('VERIFIED');231    const d = (await S.env.call(owner, 'GET', `/v1/jobs/${j.id}`)).json; expect(d.receipts.map((r: any) => r.kind)).toEqual(['human_attested']); expect(d.attempts.map((a: any) => a.phase)).toEqual(['manual']);232    expect((await S.env.db.one("SELECT count(*)::int AS n FROM audit_events WHERE action='assist.insert_text' AND target_id=$1", [j.id]))!.n).toBe(1);233  }, 90000);234});235236describe('P2 — persistance, baux, sécurité des sessions', () => {237  it('perte du bail : les entrées cessent aussitôt', async () => {238    await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/takeover`, {}); await until(() => W.worker.sessions.get(sid)!.humanToken !== null, 'bail');239    await page().goto(`${S.site.url}/pages/page-1001/composer`); await click(V, page(), '#t'); await type(V, 'abc'); expect(await page().locator('#t').inputValue()).toBe('abc');240    await S.env.db.query("UPDATE worker_leases SET expires_at=now()-interval '1 second' WHERE session_id=$1", [sid]); // e.g. the tab was left open and idle241    await until(async () => (await st()) === 'READY', 'bail expiré → READY', 15000);242    await sleep(8500); const n = V.msgs.length; V.send({ t: 'ping', n: 77 }); await type(V, 'XYZ'); await until(() => V.msgs.slice(n).some((m) => m.t === 'lease' && m.mine === false) || V.msgs.slice(n).some((m) => m.t === 'error' && m.code === 'no_control'), 'refus après perte du bail');243    expect(await page().locator('#t').inputValue()).toBe('abc');244  }, 60000);245  it('vérification en deux étapes : l’agent s’arrête, la capture est refusée, un humain doit agir', async () => {246    const j = await newJob('auto_submit'); S.site.knobs.challenge = true;247    await until(async () => (await st()) === 'SECURITY_CHALLENGE', 'SECURITY_CHALLENGE', 30000); expect(page().url()).toContain('/checkpoint/');248    await sleep(1500); expect(['QUEUED', 'PREPARING', 'FAILED']).toContain((await job(j.id)).state); expect((await S.env.db.one("SELECT count(*)::int AS n FROM publication_receipts r WHERE r.job_id=$1", [j.id]))!.n).toBe(0);249    // the worker refuses to hand any task out and the code field is never typed by the machine250    expect(await page().locator('#c').inputValue()).toBe('');251    await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/takeover`, {}); await until(() => W.worker.sessions.get(sid)!.humanToken !== null, 'bail');252    await click(V, page(), '#c'); await type(V, '123456'); await click(V, page(), 'button[type=submit]'); await until(() => page().url().endsWith('/pages/page-1001'), 'défi résolu par l’humain');253    expect(JSON.stringify((await S.env.db.query('SELECT detail FROM audit_events')).rows) + JSON.stringify(S.logs)).not.toContain('123456');254    await S.env.call(owner, 'POST', `/v1/jobs/${j.id}/cancel`, {}); expect((await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/release`, {})).json.state).toBe('READY');255  }, 90000);256  it('isolation des profils : une seconde session part d’un profil vierge, sans la connexion de la première', async () => {257    const s2 = (await S.nav(owner, 'POST', '/v1/navigator/sessions', { label: 'Seconde', workerId: W.id, startUrl: `${S.site.url}/pages/page-2002` })).json;258    await until(async () => (await st(s2.id)) === 'LOGIN_REQUIRED', 'seconde session demande une connexion', 30000);259    expect(page(s2.id).url()).toContain('/login'); expect(page().url()).not.toContain('/login');260    const dirs = readdirSync(S.profilesDir).filter((f) => !f.endsWith('.lock')); expect(dirs).toHaveLength(2); expect(new Set(dirs).size).toBe(2);261    expect((await page(s2.id).context().cookies()).length).toBe(0); expect((await page().context().cookies()).some((c) => c.name === 'fx_session')).toBe(true);262    // one process per profile: a second launch on the same directory is refused by the lock263    const lock = readdirSync(S.profilesDir).find((f) => f.endsWith('.lock'))!; expect(Number(readFileSync(join(S.profilesDir, lock), 'utf8'))).toBe(process.pid);264    const r = await S.nav(owner, 'POST', `/v1/navigator/sessions/${s2.id}/revoke`, {}); expect(r.json.state).toBe('REVOKED');265    await until(() => readdirSync(S.profilesDir).filter((f) => !f.endsWith('.lock')).length === 1, 'profil révoqué effacé du disque', 15000);266    expect(W.worker.sessions.get(s2.id)?.running ?? false).toBe(false);267  }, 90000);268  it('fermeture puis réouverture : la session du site persiste dans le profil ; si le site a expiré la session, une connexion est redemandée', async () => {269    expect((await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/close`, {})).json.state).toBe('PAUSED'); await until(() => !W.worker.sessions.get(sid)!.running, 'navigateur fermé', 15000);270    expect((await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/resume`, {})).json.state).toBe('READY'); await until(() => W.worker.sessions.get(sid)!.running && !!W.worker.sessions.get(sid)!.active, 'navigateur rouvert', 30000);271    await until(() => page().url().endsWith('/pages/page-1001'), 'page de départ rechargée sans connexion', 15000); expect(await page().getByTestId('page-name').innerText()).toBe('Atelier Démo'); expect(await st()).toBe('READY');272    S.site.knobs.sessionValid = false; await page().goto(`${S.site.url}/pages/page-1001`); expect(page().url()).toContain('/login'); // the platform ended the session on its side273    await until(async () => (await st()) === 'EXPIRED', 'EXPIRED', 15000); expect((await S.env.db.one('SELECT confirmed_at FROM navigator_sessions WHERE id=$1', [sid]))!.confirmed_at).toBeNull();274    S.site.knobs.sessionValid = true;275  }, 90000);276  it('arrêt d’urgence : navigateurs fermés, spectateur averti, plus aucune entrée ni tâche', async () => {277    const n = V.msgs.length; expect((await S.env.call(owner, 'POST', '/v1/emergency-stop', { engage: true, reason: 'Essai bout en bout' })).json.engaged).toBe(true);278    await until(() => V.msgs.slice(n).some((m) => m.t === 'emergency' && m.engaged), 'spectateur averti'); await until(() => [...W.worker.sessions.values()].every((s) => !s.running), 'navigateurs fermés', 15000);279    expect((await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/takeover`, {})).status).toBe(403);280    await S.env.call(owner, 'POST', '/v1/emergency-stop', { engage: false, reason: 'Fin de l’essai' });281  }, 60000);282  it('révocation : état terminal, profil détruit, le spectateur est coupé', async () => {283    expect((await S.nav(owner, 'POST', `/v1/navigator/sessions/${sid}/revoke`, {})).json.state).toBe('REVOKED');284    await until(() => readdirSync(S.profilesDir).filter((f) => !f.endsWith('.lock')).length === 0, 'profil effacé', 15000);285    expect((await S.env.db.one("SELECT status FROM navigator_profiles p JOIN navigator_sessions s ON s.profile_id=p.id WHERE s.id=$1", [sid]))!.status).toBe('wiped');286    const log = (await S.env.db.query("SELECT action FROM audit_events WHERE target_id=$1 AND action IN ('worker.profile_wiped','session.takeover','session.confirm')", [sid])).rows.map((r) => r.action); expect(log).toContain('worker.profile_wiped');287    V.close();288  }, 60000);289});290
Files main
Menu

Theme