| 1 | // Bridge local: arranca el binario REAL compilado, conecta desde la UI (token |
| 2 | // pegado a mano, como haría el usuario), verifica los fuegos artificiales, y |
| 3 | // ejecuta un comando REAL (node/python) que solo un runtime de verdad puede |
| 4 | // producir — no algo que el shell emulado en JS pudiera fingir. |
| 5 | import { chromium } from 'playwright'; |
| 6 | import { spawn } from 'node:child_process'; |
| 7 | const OUT = (process.env.SCRATCH || '/tmp/elffuss-test'); |
| 8 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 9 | const BRIDGE_BIN = process.env.BRIDGE_BIN |
| 10 | || new URL('../web/bridge-dl/elffuss-bridge-mac-arm64', import.meta.url).pathname; |
| 11 | const PORT = 8765; // puerto real que usa bridge.js (fijo) |
| 12 | const TOKEN = 'test-token-e2e-' + Math.random().toString(36).slice(2); |
| 13 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 14 | |
| 15 | const bp = spawn(BRIDGE_BIN, ['-port', String(PORT), '-token', TOKEN], { stdio: 'pipe' }); |
| 16 | let bridgeLog = ''; |
| 17 | bp.stdout.on('data', d => bridgeLog += d.toString()); |
| 18 | bp.stderr.on('data', d => bridgeLog += d.toString()); |
| 19 | await new Promise(r => setTimeout(r, 800)); // que el bridge levante el puerto |
| 20 | |
| 21 | const b = await chromium.launch(); |
| 22 | const ctx = await b.newContext(); |
| 23 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); |
| 24 | const p = await ctx.newPage({ viewport: { width: 1300, height: 900 } }); |
| 25 | p.on('console', m => { if (m.type() === 'error' && !/allow-same-origin/.test(m.text())) console.log(' err:', m.text().slice(0, 160)); }); |
| 26 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1500); |
| 27 | |
| 28 | ok('el bridge real arrancó y escucha', /Escuchando SOLO en 127\.0\.0\.1/.test(bridgeLog), bridgeLog.slice(0, 80)); |
| 29 | const probed = await p.evaluate(async () => (await import('/js/bridge.js')).probe()); |
| 30 | ok('la web detecta el bridge escuchando (/ping)', probed); |
| 31 | |
| 32 | // abrir Ajustes, pegar el token real, conectar — flujo real de usuario |
| 33 | await p.click('#btn-settings'); await p.waitForTimeout(400); |
| 34 | await p.fill('#br-token', TOKEN); |
| 35 | await p.fill('#br-folder', '/tmp'); |
| 36 | await p.click('#br-connect'); |
| 37 | await p.waitForTimeout(1200); |
| 38 | ok('el punto de estado pasa a "conectado" (verde)', await p.evaluate(() => document.getElementById('br-dot')?.classList.contains('on'))); |
| 39 | ok('el texto de estado confirma la conexión', /conectado/.test(await p.locator('#br-status').innerText())); |
| 40 | ok('fuegos artificiales al conectar (canvas de celebración)', await p.locator('#fireworks-fx').count() > 0); |
| 41 | |
| 42 | // capabilities() ya refleja el bridge conectado |
| 43 | const caps = await p.evaluate(async () => (await import('/js/shell.js')).capabilities()); |
| 44 | ok('shell.capabilities() confirma bridge:true', caps.bridge === true, JSON.stringify(caps)); |
| 45 | |
| 46 | // EJECUCIÓN REAL: node -e con una marca única que solo un node real produce. |
| 47 | // (Aserción ESTRICTA: sin "syntax error" ni el eco del comando roto — antes |
| 48 | // un bug de comillas hacía que el propio mensaje de error "aprobara" el test |
| 49 | // por casualidad, al repetir la marca dentro de la línea rota.) |
| 50 | const MARK = 'REAL-NODE-' + Math.floor(Math.random() * 1e6); |
| 51 | const nodeOut = await p.evaluate(async (mark) => { |
| 52 | const s = await import('/js/shell.js'); |
| 53 | return s.stripAnsi(await s.exec(`node -e "console.log('${mark}')"`)); |
| 54 | }, MARK); |
| 55 | ok('node ejecuta de VERDAD en la máquina real (vía el bridge)', nodeOut.trim() === MARK, nodeOut); |
| 56 | |
| 57 | // python3 también, otra marca distinta |
| 58 | const MARK2 = 'REAL-PY-' + Math.floor(Math.random() * 1e6); |
| 59 | const pyOut = await p.evaluate(async (mark) => { |
| 60 | const s = await import('/js/shell.js'); |
| 61 | return s.stripAnsi(await s.exec(`python3 -c "print('${mark}')"`)); |
| 62 | }, MARK2); |
| 63 | ok('python3 ejecuta de VERDAD en la máquina real (vía el bridge)', pyOut.trim() === MARK2, pyOut); |
| 64 | |
| 65 | // el tool terminal.run del AGENTE también lo usa (mismo camino real) |
| 66 | const agentOut = await p.evaluate(async (mark) => { |
| 67 | const t = await import('/js/tools/index.js'); |
| 68 | return t.runTool('terminal.run', { command: `node -e "console.log('${mark}')"` }); |
| 69 | }, MARK + '-agent'); |
| 70 | ok('la elfa (terminal.run) también ejecuta de verdad vía el bridge', agentOut.trim() === MARK + '-agent', agentOut.slice(0, 60)); |
| 71 | |
| 72 | // origen NO permitido: el bridge debe rechazar conexiones de otro origen |
| 73 | const originCheck = await fetch(`http://127.0.0.1:${PORT}/ping`, { headers: { Origin: 'https://evil.example' } }).then(r => r.status).catch(() => 'err'); |
| 74 | ok('el bridge RECHAZA orígenes no permitidos (seguridad)', originCheck === 403, `status ${originCheck}`); |
| 75 | |
| 76 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ BRIDGE LOCAL OK — conexión real + ejecución real + seguridad de origen'); |
| 77 | await b.close(); |
| 78 | bp.kill(); |
| 79 | process.exit(fails ? 1 : 0); |