| 1 | // Nivel 2 (código de extensiones en un recinto aparte): prueba de aceptación |
| 2 | // de la parte B1. |
| 3 | // |
| 4 | // node tests/x2_smoke.mjs (arranca su propio servidor: tests/lib/x2-server.mjs) |
| 5 | // node tests/x2_smoke.mjs --update (reescribe la foto tests/x2-surface.json) |
| 6 | // |
| 7 | // A. Camino por defecto: sin extensiones, con solo nivel 1 y con una |
| 8 | // extensión de código instalada pero apagada, NO se pide nada del nivel 2. |
| 9 | // B. Encender: el tamaño se enseña ANTES de bajar nada; cancelar no baja nada. |
| 10 | // C. Con extensiones sintéticas: arranque en el otro sitio, integridad (cada |
| 11 | // fichero una vez), comandos (API de la paleta, F1, atajo F9, atajos |
| 12 | // reservados), formateo, hover sin imágenes ni enlaces, símbolos (Ir a |
| 13 | // símbolo), diagnósticos, activeTextEditor definido, el agente sigue |
| 14 | // escribiendo, Cmd+P/Cmd+S/Ctrl+` de Code siguen siendo de Code, canario |
| 15 | // básico a 0 visitas, foto de la superficie de la API, y del recinto solo se |
| 16 | // piden sus dos documentos. |
| 17 | // D. Bundle manipulado: se niega, sin iframe. |
| 18 | // E. ?noext2, ?noext y el interruptor del manifiesto: 0 peticiones del nivel 2. |
| 19 | // F. Apagar la última extensión de código desmonta el recinto y lo que puso. |
| 20 | // G. Controles positivos: sin ninguna CSP el recinto no arranca (autoprueba); |
| 21 | // sin la del host de extensiones, el mismo canario SÍ llega a la baliza. |
| 22 | import fs from 'node:fs'; |
| 23 | import path from 'node:path'; |
| 24 | import { fileURLToPath } from 'node:url'; |
| 25 | import { chromium } from 'playwright'; |
| 26 | import { startServer } from './lib/x2-server.mjs'; |
| 27 | import { startBeacon } from './lib/beacon.mjs'; |
| 28 | import { seed, recordFor, SORT, FMT, HOVER, SYM, DIAG, DECO, UI, DENY, NOOP, CANARY } from './lib/x2-fixtures.mjs'; |
| 29 | |
| 30 | const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| 31 | const UPDATE = process.argv.includes('--update'); |
| 32 | const MOD = process.platform === 'darwin' ? 'Meta' : 'Control'; |
| 33 | let fails = 0, lastStep = 'start'; |
| 34 | const ok = (name, c, extra = '') => { lastStep = name.split(' ')[0]; console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; }; |
| 35 | const sleep = ms => new Promise(r => setTimeout(r, ms)); |
| 36 | async function until(fn, { timeout = 20000, every = 150 } = {}) { |
| 37 | const end = Date.now() + timeout; |
| 38 | let v; |
| 39 | while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); } |
| 40 | return v; |
| 41 | } |
| 42 | const L2 = u => /\/vendor\/x2\/|\/js\/ext2\//.test(u); |
| 43 | |
| 44 | const srv = await startServer(); |
| 45 | const beacon = await startBeacon(); |
| 46 | const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] }); |
| 47 | const manifest = JSON.parse(fs.readFileSync(path.join(HERE, '../web/js/ext2/vendor-manifest.json'), 'utf8')); |
| 48 | |
| 49 | async function freshPage(server = srv) { |
| 50 | const ctx = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] }); |
| 51 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } }); |
| 52 | const page = await ctx.newPage(); |
| 53 | const requests = []; |
| 54 | const errors = []; |
| 55 | ctx.on('request', r => requests.push(r.url())); |
| 56 | page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(String(e.message) + ' @ ' + String(e.stack || '').slice(0, 300) + ' (after ' + lastStep + ')'); }); |
| 57 | await page.goto(server.codeOrigin + '/', { waitUntil: 'domcontentloaded' }); |
| 58 | await page.evaluate(async () => { |
| 59 | const o = await navigator.storage.getDirectory(); |
| 60 | const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); }; |
| 61 | await w('app.js', 'function zeta() {}\nfunction alpha() {}\n// TODO fix\nconst a = 1;\n'); |
| 62 | await w('fruits.txt', 'pear\napple\nfig\n'); |
| 63 | await w('page.html', '<p id="z">z</p>\n<p id="a">a</p>\n'); |
| 64 | await w('bad.js', 'let q = ;\n'); |
| 65 | }); |
| 66 | return { ctx, page, requests, errors }; |
| 67 | } |
| 68 | const openIde = async (page, server = srv, query = '?test-opfs') => { |
| 69 | await page.goto(server.codeOrigin + '/' + query, { waitUntil: 'domcontentloaded' }); |
| 70 | await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 }); |
| 71 | }; |
| 72 | const open = (page, p) => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p); |
| 73 | const value = page => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue()); |
| 74 | const bridgeState = page => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state()); |
| 75 | const waitRunning = page => until(async () => { const s = await bridgeState(page); return s.state === 'running' || s.state === 'error' ? s : null; }, { timeout: 60000 }); |
| 76 | const sandboxRequests = (server, since = 0) => server.requests.slice(since).filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]); |
| 77 | |
| 78 | // Lo que pide la extensión UI, contestado como lo haría una persona: un clic |
| 79 | // en «Yes», Escape en el modal, «b» en el selector, dos marcadas en el de |
| 80 | // varios, y un texto que la validación rechaza antes del bueno. |
| 81 | async function uiFlow(page) { |
| 82 | await page.evaluate(() => { window.__x2ask = import('/js/ext2/bridge.js').then(b => b.runCommand('x2ui.ask')); }); |
| 83 | const toast = await until(() => page.evaluate(() => { |
| 84 | const t = [...document.querySelectorAll('#x2-toasts .x2-toast')].find(x => x.textContent.includes('x2 asks')); |
| 85 | return t ? { text: t.querySelector('.x2-toast-text').textContent, from: t.querySelector('.x2-toast-from').textContent, els: t.querySelectorAll('.x2-toast-text *').length, buttons: [...t.querySelectorAll('.x2-toast-buttons button')].map(b => b.textContent) } : null; |
| 86 | })); |
| 87 | ok('U1 aviso con botones: el HTML y el enlace quedan en texto; dice qué extensión pide', !!toast && toast.text === 'x2 asks <b>bold</b> [link](https://toast.beacon.test/t)' && toast.els === 0 |
| 88 | && toast.from.includes('X2 ui') && toast.buttons.includes('Yes') && toast.buttons.includes('No'), JSON.stringify(toast)); |
| 89 | await page.click('#x2-toasts .x2-toast .x2-toast-buttons button:has-text("Yes")'); |
| 90 | const dlg = await until(() => page.evaluate(() => { |
| 91 | const d = document.querySelector('#x2-dialog [role="dialog"]'); |
| 92 | return d ? { modal: d.getAttribute('aria-modal'), text: d.textContent, focused: document.activeElement?.textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null; |
| 93 | })); |
| 94 | ok('U2 aviso modal: diálogo con su detalle; el foco empieza en Cancelar', !!dlg && dlg.modal === 'true' && dlg.text.includes('x2 modal') && dlg.text.includes('x2 detail') |
| 95 | && dlg.buttons.join() === 'OK,Cancel' && dlg.focused === 'Cancel', JSON.stringify(dlg)); |
| 96 | await page.keyboard.press('Escape'); |
| 97 | const pick = await until(() => page.evaluate(() => { |
| 98 | const p = document.getElementById('x2-pick'); |
| 99 | return p && !p.classList.contains('x2-inputbox') ? { items: [...p.querySelectorAll('.x2-pick-item .x2-pick-label')].map(x => x.textContent), ph: p.querySelector('input').placeholder, role: p.querySelector('input').getAttribute('role') } : null; |
| 100 | })); |
| 101 | ok('U3 selector: sus opciones como texto, combobox con su lista', !!pick && pick.items.join() === 'a,b,c' && pick.ph === 'x2 pick' && pick.role === 'combobox', JSON.stringify(pick)); |
| 102 | await page.keyboard.type('b'); |
| 103 | await page.keyboard.press('Enter'); |
| 104 | const many = await until(() => page.evaluate(() => { |
| 105 | const p = document.getElementById('x2-pick'); |
| 106 | const rows = p ? [...p.querySelectorAll('.x2-pick-item')] : []; |
| 107 | return rows.length === 3 ? rows.map(r => [r.querySelector('.x2-pick-label').textContent, r.getAttribute('aria-checked')]) : null; |
| 108 | })); |
| 109 | ok('U4 selector de varios: la marcada de antemano llega marcada', !!many && JSON.stringify(many) === JSON.stringify([['one', 'false'], ['two', 'true'], ['three', 'false']]), JSON.stringify(many)); |
| 110 | await page.click('#x2-pick .x2-pick-item:has-text("three")'); |
| 111 | await page.click('#x2-pick .x2-pick-foot .x2-primary'); |
| 112 | await until(() => page.evaluate(() => !!document.querySelector('#x2-input input'))); |
| 113 | await page.keyboard.type('bad'); |
| 114 | await page.keyboard.press('Enter'); |
| 115 | const invalid = await until(() => page.evaluate(() => { const e = document.querySelector('#x2-input .x2-input-error'); return e && !e.hidden ? e.textContent : null; })); |
| 116 | ok('U5 cuadro de texto: la validación de la extensión se enseña y se vuelve a pedir', invalid === 'x2 not that', String(invalid)); |
| 117 | await page.fill('#x2-input input', 'good'); |
| 118 | await page.keyboard.press('Enter'); |
| 119 | const res = JSON.parse(await page.evaluate(() => window.__x2ask) || '{}'); |
| 120 | ok('U6 la extensión recibe lo elegido: Yes, nada (Escape), b, [two, three], good', res.info === 'Yes' && res.modal === undefined && res.pick === 'b' |
| 121 | && JSON.stringify(res.many) === '["two","three"]' && res.input === 'good', JSON.stringify(res)); |
| 122 | // progreso en la barra de estado |
| 123 | await page.evaluate(() => { window.__x2prog = import('/js/ext2/bridge.js').then(b => b.runCommand('x2ui.progress')); }); |
| 124 | const prog = await until(() => page.evaluate(() => { const p = document.getElementById('x2-progress'); return p && p.textContent.includes('half') ? p.textContent : null; })); |
| 125 | ok('U7 progreso de la extensión en la barra de estado', !!prog && prog.includes('x2 working: half'), String(prog)); |
| 126 | await page.evaluate(() => window.__x2prog); |
| 127 | ok('U8 y se va al terminar', !!(await until(() => page.evaluate(() => !document.getElementById('x2-progress'))))); |
| 128 | } |
| 129 | |
| 130 | // ── A. camino por defecto ── |
| 131 | { |
| 132 | const { ctx, page, requests } = await freshPage(); |
| 133 | const since = srv.requests.length; |
| 134 | requests.length = 0; |
| 135 | await openIde(page); |
| 136 | await open(page, 'app.js'); |
| 137 | await sleep(800); |
| 138 | ok('A1 sin extensiones: 0 peticiones del nivel 2 y 0 al recinto', !requests.some(L2) && sandboxRequests(srv, since).length === 0, requests.filter(L2).join(' ')); |
| 139 | |
| 140 | // A2: solo nivel 1 (una extensión activa sin código) |
| 141 | const lvl1 = recordFor(NOOP, { runs: false }); |
| 142 | delete lvl1.rec.code; |
| 143 | await page.evaluate(async rec => { const store = await import('/js/ext/store.js'); await store.put(rec, new Map()); }, lvl1.rec); |
| 144 | requests.length = 0; |
| 145 | await openIde(page); |
| 146 | await open(page, 'app.js'); |
| 147 | await sleep(800); |
| 148 | ok('A2 solo nivel 1: carga js/ext/host.js y nada del nivel 2', requests.some(u => u.includes('/js/ext/host.js')) && !requests.some(L2), requests.filter(L2).join(' ')); |
| 149 | |
| 150 | // A3: una extensión de código instalada con su código apagado |
| 151 | await seed(page, [SORT], { runs: false }); |
| 152 | requests.length = 0; |
| 153 | const since3 = srv.requests.length; |
| 154 | await openIde(page); |
| 155 | await open(page, 'app.js'); |
| 156 | await sleep(800); |
| 157 | ok('A3 extensión de código apagada: 0 peticiones del nivel 2', !requests.some(L2) && sandboxRequests(srv, since3).length === 0, requests.filter(L2).join(' ')); |
| 158 | |
| 159 | // ── B. encender enseña el tamaño ANTES de bajar nada ── |
| 160 | requests.length = 0; |
| 161 | const cancel = await page.evaluate(async () => { |
| 162 | const host = await (await import('/js/ide.js')).loadExt(); |
| 163 | let info = null; |
| 164 | const r = await host.setRuns('elffuss-test.sort', true, { confirm: i => { info = i; return false; } }); |
| 165 | return { r, info }; |
| 166 | }); |
| 167 | ok('B1 el diálogo recibe el tamaño del bundle (los .gz del manifiesto)', cancel.info && cancel.info.runtimeBytes === manifest.totalGz && cancel.info.runtimeBytes > 1e6, JSON.stringify(cancel.info)); |
| 168 | ok('B2 cancelar: no se enciende y no se baja el bundle', cancel.r === false && !requests.some(u => u.includes('/vendor/x2/')), requests.filter(L2).join(' ')); |
| 169 | const kvRuns = await page.evaluate(async () => (await (await import('/js/db.js')).get('kv', 'extensions')).find(e => e.id === 'elffuss-test.sort')?.runs); |
| 170 | ok('B3 cancelar deja runs:false en kv', kvRuns === false); |
| 171 | const since4 = srv.requests.length; |
| 172 | requests.length = 0; |
| 173 | const yes = await page.evaluate(async () => { const host = await (await import('/js/ide.js')).loadExt(); return host.setRuns('elffuss-test.sort', true, { confirm: () => true }); }); |
| 174 | const s1 = await waitRunning(page); |
| 175 | ok('B4 aceptar: el recinto arranca sin recargar', yes === true && s1?.state === 'running', JSON.stringify(s1?.error)); |
| 176 | const vendorReqs = requests.filter(u => u.includes('/vendor/x2/')); |
| 177 | ok('B5 cada fichero del bundle se pide una vez, del buildId del manifiesto', vendorReqs.length === 3 && manifest.files.every(f => vendorReqs.filter(u => u.endsWith(`/vendor/x2/${manifest.buildId}/${f.name}.gz`)).length === 1), vendorReqs.join(' ')); |
| 178 | ok('B6 del recinto solo sus dos documentos', JSON.stringify([...new Set(sandboxRequests(srv, since4))].sort()) === JSON.stringify(['/x2/v1/exthost-iframe.html', '/x2/v1/sandbox.html']), sandboxRequests(srv, since4).join(' ')); |
| 179 | await ctx.close(); |
| 180 | } |
| 181 | |
| 182 | // ── C. extensiones sintéticas ── |
| 183 | { |
| 184 | const { ctx, page, requests, errors } = await freshPage(); |
| 185 | await seed(page, [SORT, FMT, HOVER, SYM, DIAG, DECO, UI, DENY, NOOP, CANARY]); |
| 186 | const since = srv.requests.length; |
| 187 | requests.length = 0; |
| 188 | await openIde(page); |
| 189 | await open(page, 'app.js'); |
| 190 | const s = await waitRunning(page); |
| 191 | ok('C1 arranca solo con extensiones de código encendidas', s?.state === 'running', JSON.stringify(s?.error)); |
| 192 | const st = await until(async () => { const x = await bridgeState(page); return x.extensions.filter(e => e.state === 'active').length >= 4 ? x : null; }, { timeout: 30000 }); |
| 193 | ok('C2 las extensiones arrancan en el recinto sin errores', st && !st.extensions.some(e => e.state === 'error'), JSON.stringify(st?.extensions.map(e => [e.id, e.state, e.text]))); |
| 194 | // portapapeles: se lee vacío; escribir solo con un gesto reciente. (Cada |
| 195 | // page.evaluate de Playwright cuenta como gesto, así que la escritura «sin |
| 196 | // gesto» se lanza desde la página pasados 6 s, cuando ya caducó.) |
| 197 | const ui0 = await until(async () => { const x = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2ui.report')); return x ? JSON.parse(x) : null; }, { timeout: 30000 }); |
| 198 | await page.evaluate(() => { setTimeout(() => import('/js/ext2/bridge.js').then(b => b.runCommand('x2ui.clip')), 6000); }); |
| 199 | await sleep(6500); |
| 200 | const uiSt = await until(async () => { const s = await bridgeState(page); return s.ui?.dropped?.clipboard ? s : null; }, { timeout: 10000 }); |
| 201 | const clipNoGesture = await page.evaluate(() => navigator.clipboard.readText().catch(e => 'ERR ' + e.message)); |
| 202 | ok('C2b portapapeles: se lee vacío y escribir sin gesto se descarta', !!ui0 && ui0.clipboardRead === '' && uiSt?.ui.dropped.clipboard === 1 && clipNoGesture !== 'x2 clipboard 1', JSON.stringify({ ui0, dropped: uiSt?.ui?.dropped, clipNoGesture })); |
| 203 | await page.click('#statusbar'); |
| 204 | await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2ui.clip')); |
| 205 | const clipGesture = await until(() => page.evaluate(() => navigator.clipboard.readText().then(t => (t === 'x2 clipboard 2' ? t : null)).catch(() => null)), { timeout: 5000 }); |
| 206 | ok('C2c control positivo: con un gesto reciente, sí se escribe', clipGesture === 'x2 clipboard 2', String(clipGesture)); |
| 207 | await uiFlow(page); |
| 208 | ok('C3 iframe del recinto en el otro sitio, invisible y sin foco', await page.evaluate(o => { const f = document.getElementById('x2-sandbox'); return !!f && f.src.startsWith(o) && f.getAttribute('sandbox') === 'allow-scripts allow-same-origin' && f.inert && f.getAttribute('allow') === '' && getComputedStyle(f).opacity === '0'; }, srv.sandboxOrigin)); |
| 209 | ok('C4 el recinto no es del sitio de Code', new URL(srv.sandboxOrigin).hostname !== new URL(srv.codeOrigin).hostname); |
| 210 | |
| 211 | // diagnósticos |
| 212 | const marks = await until(() => page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; const m = window.monaco.editor.getModelMarkers({ resource: ed.getModel().uri }).filter(x => x.owner.startsWith('x2:')); return m.length ? m.map(x => ({ owner: x.owner, message: x.message, code: x.code, line: x.startLineNumber })) : null; })); |
| 213 | ok('C5 diagnósticos de la extensión: texto plano, sin destino del código', marks && marks[0].owner === 'x2:x2diag' && marks[0].message === 'x2: TODO found x' && marks[0].code === 'X2001' && marks[0].line === 3, JSON.stringify(marks)); |
| 214 | |
| 215 | // decoraciones: lo válido llega, lo hostil se queda fuera |
| 216 | const deco = await until(() => page.evaluate(() => { |
| 217 | const ed = window.monaco.editor.getEditors()[0]; |
| 218 | const ds = ed.getModel().getAllDecorations().filter(d => d.options.description === 'x2-extension-decoration'); |
| 219 | const style = document.getElementById('x2-deco')?.textContent || ''; |
| 220 | const view = document.querySelector('#editor .view-lines')?.textContent || ''; |
| 221 | return ds.length && view.includes('x2deco>') ? { n: ds.length, line: ds[0].range.startLineNumber, cls: ds[0].options.className, inline: ds[0].options.inlineClassName, before: ds[0].options.before?.content, ruler: ds[0].options.overviewRuler?.color, style } : null; |
| 222 | })); |
| 223 | ok('C5b decoraciones de la extensión en el editor de Code, con su texto «antes» como texto', !!deco && deco.line === 3 && deco.before === 'x2deco>' && !!deco.cls && !!deco.inline && deco.ruler === 'red', JSON.stringify(deco)); |
| 224 | ok('C5c su CSS sale de la lista blanca: colores y márgenes sí; url(), fontFamily y los valores inyectados no', !!deco && !/url\(|beacon|font-family|;\s*background|cursor/.test(deco.style) |
| 225 | && /background-color: rgba\(255, 0, 0, 0\.25\);/.test(deco.style) && /color: var\(--vscode-editorError-foreground\);/.test(deco.style) && /margin: 0 4px 0 0;/.test(deco.style) |
| 226 | && /\.monaco-editor\.vs-dark \.x2d-\d+[^{]*\{ background-color: #0000ff33; \}/.test(deco.style), deco?.style); |
| 227 | // los diagnósticos de la página (el TS de Monaco) llegan a las extensiones |
| 228 | await open(page, 'bad.js'); |
| 229 | const pageDiag = await until(async () => { |
| 230 | const r = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2diag.pageMarkers')); |
| 231 | const a = r ? JSON.parse(r) : []; |
| 232 | return a.some(x => /expected/i.test(x)) ? a : null; |
| 233 | }, { timeout: 30000 }); |
| 234 | ok('C5d las extensiones ven los diagnósticos de la propia página (TS de Monaco)', !!pageDiag, JSON.stringify(pageDiag)); |
| 235 | await open(page, 'app.js'); |
| 236 | |
| 237 | // formateo (Format Document) y un solo paso de deshacer |
| 238 | await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); }); |
| 239 | // el formateador de la extensión junta también los espacios del comentario; |
| 240 | // el de JavaScript de Monaco no toca los comentarios |
| 241 | const formatted = await until(async () => { const v = await value(page); return v.includes('// TODO fix') && v.includes('const a = 1;') ? v : null; }); |
| 242 | ok('C6 Format Document usa el formateador de la extensión', !!formatted, JSON.stringify(await value(page))); |
| 243 | await page.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'undo')); |
| 244 | ok('C7 deshacer el formateo es un solo paso', (await value(page)).includes('// TODO fix\nconst a = 1;')); |
| 245 | await page.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'redo')); |
| 246 | |
| 247 | // hover hostil |
| 248 | await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setPosition({ lineNumber: 1, column: 12 }); ed.focus(); ed.trigger('t', 'editor.action.showHover', {}); }); |
| 249 | const hover = await until(() => page.evaluate(() => { const h = [...document.querySelectorAll('.monaco-hover:not(.hidden)')].find(x => x.textContent.includes('x2 hover')); return h ? { text: h.textContent, imgs: h.querySelectorAll('img').length, links: h.querySelectorAll('a[href]').length } : null; })); |
| 250 | ok('C8 hover: el markdown hostil sale como texto, sin <img> ni enlaces', hover && hover.imgs === 0 && hover.links === 0 && hover.text.includes(''), JSON.stringify(hover)); |
| 251 | await page.keyboard.press('Escape'); |
| 252 | |
| 253 | // símbolos: Ir a símbolo (Cmd+Shift+O y «@» de la paleta usan quickOutline) |
| 254 | await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.quickOutline').run(); }); |
| 255 | const outline = await until(() => page.evaluate(() => { const r = [...document.querySelectorAll('.quick-input-list .monaco-list-row')].map(x => x.textContent); return r.some(t => t.includes('x2:zeta')) ? r : null; })); |
| 256 | ok('C9 Ir a símbolo incluye los símbolos de la extensión', !!outline, JSON.stringify(outline)); |
| 257 | await page.keyboard.press('Escape'); |
| 258 | |
| 259 | // comandos: API de la paleta, F1, atajo y reservados |
| 260 | await open(page, 'fruits.txt'); |
| 261 | await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 3, endColumn: 4 }); }); |
| 262 | const entries = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).commands().map(e => ({ id: e.id, label: e.label, hint: e.hint }))); |
| 263 | ok('C10 entradas para la paleta de Code', entries.some(e => e.label === 'X2: Sort Lines (fixture)' && e.hint === 'X2 sort') && entries.some(e => e.label === 'X2: Hello (fixture)'), JSON.stringify(entries)); |
| 264 | const live = await page.evaluate(() => (window.elffussClaw?.commands || []).filter(c => c.x2).map(c => ({ label: c.label, hint: c.hint }))); |
| 265 | ok('C10b están en la lista viva de la paleta (window.elffussClaw.commands)', live.some(e => e.label === 'X2: Sort Lines (fixture)' && e.hint === 'X2 sort'), JSON.stringify(live)); |
| 266 | const ran = await page.evaluate(async () => { await new Promise(r => setTimeout(r, 200)); const e = (await import('/js/ext2/bridge.js')).commands().find(x => x.id === 'x2sort.sortLines'); return e.run(); }); |
| 267 | ok('C11 el comando corre con activeTextEditor definido', ran === 'sorted:3', JSON.stringify(ran)); |
| 268 | ok('C12 el texto queda ordenado y la pestaña sin guardar', await until(async () => (await value(page)) === 'apple\nfig\npear\n') && await page.evaluate(() => !!document.querySelector('#tabs-bar .tab.active .tab-x')?.classList.contains('dirty'))); |
| 269 | await page.evaluate(() => window.monaco.editor.getEditors()[0].focus()); |
| 270 | await page.keyboard.press(`${MOD}+s`); |
| 271 | const saved = await until(() => page.evaluate(async () => { const o = await navigator.storage.getDirectory(); const t = await (await (await o.getFileHandle('fruits.txt')).getFile()).text(); return t === 'apple\nfig\npear\n' ? t : null; })); |
| 272 | ok('C13 Cmd+S guarda por el camino de siempre (code.write)', !!saved); |
| 273 | const f1 = await page.evaluate(() => window.monaco.editor.getEditors()[0].getSupportedActions().filter(a => /:x2:/.test(a.id)).map(a => a.label)); |
| 274 | ok('C14 los comandos salen en F1', f1.includes('X2: Sort Lines (fixture)') && f1.includes('X2: Hello (fixture)'), JSON.stringify(f1)); |
| 275 | await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue('zz\nyy\nxx\n'); ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 3, endColumn: 3 }); ed.focus(); }); |
| 276 | await sleep(200); |
| 277 | await page.keyboard.press('F9'); |
| 278 | ok('C15 el atajo F9 de la extensión funciona con el foco en el editor', !!(await until(async () => (await value(page)) === 'xx\nyy\nzz\n'))); |
| 279 | // desde la paleta de Code («>»): la fila lleva el nombre de la extensión y al |
| 280 | // elegirla se cierra la paleta y el comando actúa sobre el editor |
| 281 | await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue('b\na\n'); ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 2 }); }); |
| 282 | await page.evaluate(() => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'p', ctrlKey: true, shiftKey: true, bubbles: true }))); |
| 283 | await page.fill('#pal-input', '>sort lines (fixture)'); |
| 284 | const row = await until(() => page.evaluate(() => { const r = [...document.querySelectorAll('#pal-list .pal-item')]; return r.length === 1 ? [r[0].querySelector('.pi-name').textContent, r[0].querySelector('.pi-hint').textContent] : null; })); |
| 285 | ok('C15b la paleta de Code lista el comando con el nombre de la extensión', !!row && row[0] === 'X2: Sort Lines (fixture)' && row[1] === 'X2 sort', JSON.stringify(row)); |
| 286 | await page.keyboard.press('Enter'); |
| 287 | ok('C15c elegirlo en la paleta la cierra y ordena el editor', !!(await until(async () => (await value(page)) === 'a\nb\n')) && await page.evaluate(() => document.getElementById('palette').hidden), JSON.stringify(await value(page))); |
| 288 | const skipped = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).state().extensions.find(e => e.id === 'elffuss-test.sort').log.map(l => l.text).join(' | ')); |
| 289 | ok('C16 el atajo reservado Cmd/Ctrl+P de la extensión se salta y se informa', /reserved/.test(skipped), skipped); |
| 290 | await page.evaluate(() => window.monaco.editor.getEditors()[0].focus()); |
| 291 | await page.keyboard.press(`${MOD}+p`); |
| 292 | ok('C17 Cmd+P con el foco en el editor abre la paleta de Code', !!(await until(() => page.evaluate(() => !document.getElementById('palette').hidden)))); |
| 293 | await page.keyboard.press('Escape'); |
| 294 | await page.evaluate(() => window.monaco.editor.getEditors()[0].focus()); |
| 295 | await page.keyboard.press('Control+`'); |
| 296 | ok('C18 Ctrl+` sigue abriendo el terminal de Code', !!(await until(() => page.evaluate(() => !document.getElementById('terminal-panel').hidden), { timeout: 5000 }))); |
| 297 | await page.evaluate(() => { document.getElementById('terminal-panel').hidden = true; }); |
| 298 | |
| 299 | // el agente escribe: el editor se actualiza y el recinto sigue al día |
| 300 | await open(page, 'app.js'); |
| 301 | await page.evaluate(async () => { const { TOOLS } = await import('/js/tools/index.js'); await TOOLS['code.write'].run({ path: 'app.js', content: 'function beta() {}\n// b c\nlet b = 2;\n' }); }); |
| 302 | ok('C19 code.write del agente sigue reflejándose en el editor', !!(await until(async () => (await value(page)) === 'function beta() {}\n// b c\nlet b = 2;\n'))); |
| 303 | await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); }); |
| 304 | ok('C20 tras escribir el agente, la extensión trabaja sobre el texto nuevo', !!(await until(async () => (await value(page)) === 'function beta() {}\n// b c\nlet b = 2;\n')), JSON.stringify(await value(page))); |
| 305 | const readBack = await page.evaluate(async () => (await import('/js/tools/code.js')).read({ path: 'app.js' })); |
| 306 | ok('C21 code.read lee el fichero, no el editor', readBack === 'function beta() {}\n// b c\nlet b = 2;\n'); |
| 307 | |
| 308 | // ── H. puertas: vista previa de un fichero tocado, el agente, enlaces del editor ── |
| 309 | beacon.hits.length = 0; |
| 310 | await open(page, 'page.html'); |
| 311 | await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 17 }); }); |
| 312 | await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2sort.sortLines')); |
| 313 | const marked = await until(() => page.evaluate(async () => ((await (await import('/js/db.js')).get('kv', 'x2.touched')) || {})['page.html'] === true)); |
| 314 | ok('H1 el texto de una extensión marca el fichero (kv x2.touched)', !!marked); |
| 315 | // el menú sigue el idioma del navegador desde 7d5e790: se busca en los dos |
| 316 | const previewVia = async (label = /^(Vista previa|Preview)$/) => { |
| 317 | await page.click('#tabs-bar .tab.active', { button: 'right' }); |
| 318 | await page.locator('#tab-menu .tm-item').filter({ hasText: label }).click(); |
| 319 | }; |
| 320 | await previewVia(); |
| 321 | const gateDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-preview [role="dialog"]'); return d ? { text: d.textContent, focused: document.activeElement?.textContent } : null; })); |
| 322 | ok('H2 la vista previa de un fichero tocado pregunta antes (Cancelar por defecto)', !!gateDlg && gateDlg.text.includes('page.html') && gateDlg.focused === 'Cancel', JSON.stringify(gateDlg)); |
| 323 | await page.keyboard.press('Escape'); |
| 324 | await sleep(300); |
| 325 | const after = await page.evaluate(() => ({ frames: document.querySelectorAll('#md-preview-pane iframe').length, preview: !!document.querySelector('#tabs-bar .tab.tab-preview'), editor: getComputedStyle(document.getElementById('editor')).display })); |
| 326 | ok('H3 Cancelar: sin vista previa, se queda el código fuente', after.frames === 0 && !after.preview && after.editor !== 'none', JSON.stringify(after)); |
| 327 | await previewVia(); |
| 328 | await until(() => page.evaluate(() => !!document.querySelector('#x2-preview'))); |
| 329 | await page.click('#x2-preview button:has-text("Preview anyway")'); |
| 330 | const shown = await until(() => page.evaluate(() => document.querySelectorAll('#md-preview-pane iframe').length === 1 && !!document.querySelector('#tabs-bar .tab.tab-preview'))); |
| 331 | const cleared = await page.evaluate(async () => !((await (await import('/js/db.js')).get('kv', 'x2.touched')) || {})['page.html']); |
| 332 | ok('H4 «Previsualizar igualmente» la enseña y quita la marca', !!shown && cleared); |
| 333 | await previewVia(/^(Ver código fuente|View source)$/); // vuelve al código |
| 334 | // el agente: web.fetch y un runtime del Bridge preguntan; Denegar por defecto |
| 335 | await page.evaluate(() => { window.__x2fetch = import('/js/tools/index.js').then(m => m.TOOLS['web.fetch'].run({ url: 'https://agent.beacon.test/leak?d=1' })); }); |
| 336 | const agentDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-agent [role="dialog"]'); return d ? { code: d.querySelector('.x2-code').textContent, focused: document.activeElement?.textContent } : null; })); |
| 337 | ok('H5 web.fetch del agente pregunta enseñando la URL entera (Denegar por defecto)', !!agentDlg && agentDlg.code === 'https://agent.beacon.test/leak?d=1' && agentDlg.focused === 'Deny', JSON.stringify(agentDlg)); |
| 338 | await page.keyboard.press('Escape'); |
| 339 | ok('H6 denegado: el agente recibe que el usuario no lo permitió', (await page.evaluate(() => window.__x2fetch)) === 'The user did not allow this request.'); |
| 340 | await page.evaluate(() => { window.__x2run = import('/js/tools/index.js').then(m => m.TOOLS['terminal.run'].run({ command: 'ls && node -e "1"' })); }); |
| 341 | const runDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-agent [role="dialog"]'); return d ? d.querySelector('.x2-code').textContent : null; })); |
| 342 | ok('H7 una orden con un runtime del Bridge (aunque no vaya primero) pregunta con la orden entera', runDlg === 'ls && node -e "1"', String(runDlg)); |
| 343 | await page.keyboard.press('Escape'); |
| 344 | ok('H8 denegada', (await page.evaluate(() => window.__x2run)) === 'The user did not allow this request.'); |
| 345 | const ls = await page.evaluate(async () => (await import('/js/tools/index.js')).TOOLS['terminal.run'].run({ command: 'ls' })); |
| 346 | ok('H9 una orden del shell de Code sin runtime no pregunta', /app\.js/.test(ls) && !(await page.evaluate(() => !!document.querySelector('#x2-agent'))), String(ls).slice(0, 80)); |
| 347 | // Cmd+clic en un enlace del editor, en modo extensiones: el mismo diálogo |
| 348 | await open(page, 'fruits.txt'); |
| 349 | await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue('see https://link.beacon.test/p?q=1 now\n'); ed.setPosition({ lineNumber: 1, column: 12 }); ed.focus(); }); |
| 350 | await sleep(400); |
| 351 | await page.evaluate(() => window.monaco.editor.getEditors()[0].getAction('editor.action.openLink').run()); |
| 352 | const linkDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-open [role="dialog"]'); return d ? { code: d.querySelector('.x2-code').textContent, text: d.textContent } : null; })); |
| 353 | ok('H10 un enlace del editor pregunta con la dirección entera', !!linkDlg && linkDlg.code === 'https://link.beacon.test/p?q=1' && /links in the editor ask first/.test(linkDlg.text), JSON.stringify(linkDlg)); |
| 354 | await page.keyboard.press('Escape'); |
| 355 | await page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().setValue('pear\napple\nfig\n')); |
| 356 | await sleep(500); |
| 357 | ok('H11 nada de esto llegó a la baliza', beacon.hits.length === 0, JSON.stringify(beacon.hits)); |
| 358 | await open(page, 'app.js'); |
| 359 | |
| 360 | // antes del canario: sus intentos fallidos a propósito sí dejan errores |
| 361 | const realErrors = errors.slice(); |
| 362 | ok('C22 sin errores de página en todo lo anterior', realErrors.length === 0, realErrors.slice(0, 3).join(' | ')); |
| 363 | // canario básico: desde el worker de extensiones, ningún canal sale. Su |
| 364 | // openExternal abre el diálogo de la dirección: enseña la URL entera y se cancela |
| 365 | beacon.hits.length = 0; |
| 366 | await page.evaluate(port => { window.__x2canary = import('/js/ext2/bridge.js').then(b => b.runCommand('x2canary.report', port)); }, beacon.port); |
| 367 | const openDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-open [role="dialog"]'); return d ? { code: d.querySelector('.x2-code')?.textContent, focused: document.activeElement?.textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null; })); |
| 368 | ok('C22b openExternal: diálogo con la dirección entera, Cancelar con el foco', !!openDlg && openDlg.code === `http://open.beacon.test:${beacon.port}/x2-canary/open` && openDlg.focused === 'Cancel' |
| 369 | && openDlg.buttons.join() === 'Cancel,Copy address,Open in new tab,Block requests for this session', JSON.stringify(openDlg)); |
| 370 | await page.keyboard.press('Escape'); |
| 371 | const report = JSON.parse(await page.evaluate(() => window.__x2canary) || '[]'); |
| 372 | await sleep(1500); |
| 373 | const allowed = report.filter(r => r.outcome === 'ALLOWED' && !/^own: /.test(r.detail) && !['caches', 'asExternalUri', 'openExternal', 'clipboard-api'].includes(r.channel)); |
| 374 | ok('C23 canario: cada canal de red del worker bloqueado', report.length >= 15 && allowed.length === 0, JSON.stringify(allowed)); |
| 375 | ok('C24 canario: no ve el almacenamiento de Code (IndexedDB, OPFS)', report.filter(r => ['indexedDB', 'opfs'].includes(r.channel)).every(r => !/SAW CODE/.test(r.detail)), JSON.stringify(report.filter(r => ['indexedDB', 'opfs'].includes(r.channel)))); |
| 376 | ok('C25 canario: openExternal no abre nada; el portapapeles se lee vacío', report.find(r => r.channel === 'openExternal')?.detail === 'refused' && /read 0 chars/.test(report.find(r => r.channel === 'clipboard-api')?.detail || ''), JSON.stringify(report.filter(r => /open|clip/.test(r.channel)))); |
| 377 | ok('C26 baliza: 0 visitas', beacon.hits.length === 0, JSON.stringify(beacon.hits)); |
| 378 | |
| 379 | // cortafuegos de RPC: lo que no está en la lista se rechaza, la extensión |
| 380 | // recibe el error y la página lo cuenta |
| 381 | const deny = JSON.parse(await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2deny.report')) || '{}'); |
| 382 | ok('C26b guardar desde una extensión: rechazado por el cortafuegos', /does not let extensions call MainThreadWorkspace\.\$saveAll/.test(deny.saveAll || ''), JSON.stringify(deny)); |
| 383 | const dn = await until(async () => { const d = (await bridgeState(page)).denials; return d.top.some(([k]) => k === 'MainThreadWebviewPanels.$createWebviewPanel') ? d : null; }); |
| 384 | ok('C26c la página cuenta los rechazos (webview incluida)', !!dn && dn.n >= 2 && dn.top.some(([k]) => k === 'MainThreadWorkspace.$saveAll'), JSON.stringify(dn)); |
| 385 | |
| 386 | // foto de la superficie de la API |
| 387 | const surface = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).surface()); |
| 388 | const snapFile = path.join(HERE, 'x2-surface.json'); |
| 389 | // fuera los comandos de las pruebas y los internos con nombre aleatorio (__vsc<uuid>) |
| 390 | const snap = surface ? { actors: surface.actors, overridden: surface.overridden, commands: surface.commands.filter(c => !/^(x2|elffuss)/.test(c) && !/^__vsc[0-9a-f-]{36}$/.test(c)) } : null; |
| 391 | if (UPDATE && snap) fs.writeFileSync(snapFile, JSON.stringify(snap, null, 1) + '\n'); |
| 392 | const prev = fs.existsSync(snapFile) ? JSON.parse(fs.readFileSync(snapFile, 'utf8')) : null; |
| 393 | ok('C27 la superficie de la API coincide con tests/x2-surface.json', !!snap && !!prev && JSON.stringify(prev) === JSON.stringify(snap), |
| 394 | !prev ? 'no snapshot (run with --update)' : snap ? `actors ${Object.keys(snap.actors).length} vs ${Object.keys(prev.actors).length}, commands ${snap.commands.length} vs ${prev.commands.length}` : 'no surface'); |
| 395 | ok('C28 del recinto solo se pidieron sus dos documentos', [...new Set(sandboxRequests(srv, since))].every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sandboxRequests(srv, since).join(' ')); |
| 396 | |
| 397 | // ── F. apagar la última extensión de código lo desmonta todo ── |
| 398 | await page.evaluate(async () => { |
| 399 | const host = await (await import('/js/ide.js')).loadExt(); |
| 400 | for (const e of host.list()) if (e.runs) await host.setRuns(e.id, false); |
| 401 | }); |
| 402 | const gone = await until(() => page.evaluate(() => !document.getElementById('x2-sandbox'))); |
| 403 | ok('F1 sin extensiones de código, el iframe desaparece', !!gone); |
| 404 | const leftovers = await page.evaluate(() => { |
| 405 | const ed = window.monaco.editor.getEditors()[0]; |
| 406 | return { actions: ed.getSupportedActions().filter(a => /:x2:/.test(a.id)).length, markers: window.monaco.editor.getModelMarkers({}).filter(m => m.owner.startsWith('x2:')).length, palette: (window.elffussClaw?.commands || []).filter(c => c.x2).length }; |
| 407 | }); |
| 408 | ok('F2 sin acciones, diagnósticos ni entradas de paleta de extensiones', leftovers.actions === 0 && leftovers.markers === 0 && leftovers.palette === 0, JSON.stringify(leftovers)); |
| 409 | const toolsBack = await page.evaluate(async () => { const { TOOLS } = await import('/js/tools/index.js'); return ['web.fetch', 'web.search', 'terminal.run'].map(n => String(TOOLS[n].run)); }); |
| 410 | ok('F2b las herramientas del agente vuelven a ser las de siempre', /fetchUrl/.test(toolsBack[0]) && /web\.search/.test(toolsBack[1]) && /runForAgent/.test(toolsBack[2]), toolsBack.map(s => s.slice(0, 40)).join(' | ')); |
| 411 | await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue('// c d\nlet c = 3;\n'); await ed.getAction('editor.action.formatDocument').run(); }); |
| 412 | await sleep(1500); |
| 413 | ok('F3 vuelve el formateador de serie (el de la extensión ya no actúa)', (await value(page)) === '// c d\nlet c = 3;\n', JSON.stringify(await value(page))); |
| 414 | await ctx.close(); |
| 415 | } |
| 416 | |
| 417 | // ── D. bundle manipulado ── |
| 418 | { |
| 419 | const bad = await startServer({ tamper: true }); |
| 420 | const { ctx, page } = await freshPage(bad); |
| 421 | await seed(page, [NOOP]); |
| 422 | const since = bad.requests.length; |
| 423 | await openIde(page, bad); |
| 424 | const s = await waitRunning(page); |
| 425 | ok('D1 un .gz manipulado: el nivel 2 se niega (integridad)', s?.state === 'error' && s.error?.code === 'integrity', JSON.stringify(s)); |
| 426 | ok('D2 sin iframe y sin una sola petición al recinto', !(await page.evaluate(() => !!document.getElementById('x2-sandbox'))) && sandboxRequests(bad, since).length === 0); |
| 427 | await ctx.close(); |
| 428 | await bad.close(); |
| 429 | } |
| 430 | |
| 431 | // ── E. interruptores ── |
| 432 | for (const q of ['?test-opfs&noext2', '?test-opfs&noext']) { |
| 433 | const { ctx, page, requests } = await freshPage(); |
| 434 | await seed(page, [NOOP]); |
| 435 | requests.length = 0; |
| 436 | await openIde(page, srv, q); |
| 437 | await open(page, 'app.js'); |
| 438 | await sleep(1500); |
| 439 | ok(`E ${q.split('&')[1]}: 0 peticiones del nivel 2`, !requests.some(L2), requests.filter(L2).join(' ')); |
| 440 | await ctx.close(); |
| 441 | } |
| 442 | { |
| 443 | const { ctx, page, requests } = await freshPage(); |
| 444 | await ctx.route('**/js/ext2/vendor-manifest.json', async route => { |
| 445 | const r = await route.fetch(); |
| 446 | const j = await r.json(); |
| 447 | await route.fulfill({ response: r, body: JSON.stringify({ ...j, enabled: false }) }); |
| 448 | }); |
| 449 | await seed(page, [NOOP]); |
| 450 | requests.length = 0; |
| 451 | await openIde(page); |
| 452 | const s = await waitRunning(page); |
| 453 | ok('E interruptor del manifiesto: parado y sin bajar el bundle', s?.state === 'error' && s.error?.code === 'off' && !requests.some(u => u.includes('/vendor/x2/')), JSON.stringify(s?.error)); |
| 454 | await ctx.close(); |
| 455 | } |
| 456 | |
| 457 | // ── G. controles positivos: la prueba sabe ver una fuga ── |
| 458 | { |
| 459 | // sin ninguna CSP, el propio recinto se niega a arrancar (autoprueba) |
| 460 | const naked = await startServer({ insecure: 'all' }); |
| 461 | const { ctx, page } = await freshPage(naked); |
| 462 | await seed(page, [NOOP]); |
| 463 | await openIde(page, naked); |
| 464 | const s = await waitRunning(page); |
| 465 | ok('G1 sin CSP en el recinto, su autoprueba no le deja arrancar', s?.state === 'error' && s.error?.code === 'csp', JSON.stringify(s?.error)); |
| 466 | await ctx.close(); |
| 467 | await naked.close(); |
| 468 | } |
| 469 | { |
| 470 | // sin la CSP del host de extensiones, el mismo canario SÍ llega a la baliza |
| 471 | const open2 = await startServer({ insecure: 'exthost' }); |
| 472 | const { ctx, page } = await freshPage(open2); |
| 473 | await seed(page, [CANARY]); |
| 474 | await openIde(page, open2); |
| 475 | await open(page, 'app.js'); |
| 476 | const s = await waitRunning(page); |
| 477 | beacon.hits.length = 0; |
| 478 | let report = []; |
| 479 | if (s?.state === 'running') { |
| 480 | await until(async () => (await bridgeState(page)).extensions.some(e => e.state === 'active'), { timeout: 20000 }); |
| 481 | await page.evaluate(port => { window.__x2canary = import('/js/ext2/bridge.js').then(b => b.runCommand('x2canary.report', port)); }, beacon.port); |
| 482 | if (await until(() => page.evaluate(() => !!document.querySelector('#x2-open')))) await page.keyboard.press('Escape'); |
| 483 | report = JSON.parse(await page.evaluate(() => window.__x2canary) || '[]'); |
| 484 | await sleep(1500); |
| 485 | } |
| 486 | ok('G2 sin la CSP del host de extensiones, el canario llega a la baliza', beacon.hits.length > 0 && report.some(r => r.outcome === 'ALLOWED' && r.channel === 'fetch'), `hits ${beacon.hits.length}, state ${s?.state}`); |
| 487 | await ctx.close(); |
| 488 | await open2.close(); |
| 489 | } |
| 490 | |
| 491 | await browser.close(); |
| 492 | await beacon.close(); |
| 493 | await srv.close(); |
| 494 | console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed'); |
| 495 | process.exit(fails ? 1 : 0); |