Elffuss BraidHub

utopia-ia/elffuss-code public

2df00d521f0c · 48.2 KiBRawPermalink
1// Nivel 2 (código de extensiones en el recinto): pruebas sin navegador.
2//
3// node tests/x2_unit.mjs
4//
5// Protocolo (validadores, datos planos), texto de las extensiones (markdown
6// canónico sobre un corpus hostil, texto plano, ${CLIPBOARD}), conversión de
7// resultados a Monaco, atajos y combinaciones reservadas, selectores y glob en
8// tiempo lineal, cabeceras del recinto (ningún host en ninguna directiva de
9// red, hashes que cuadran), manifiesto del bundle y manifiesto que ve el
10// recinto.
11import fs from 'node:fs';
12import path from 'node:path';
13import { fileURLToPath } from 'node:url';
14import { validate, isPlainData, LIMITS } from '../web/js/ext2/protocol.js';
15import { canonicalMarkdown, plainText, markdownFromText, stripClipboard, segments } from '../web/js/ext2/sanitize.js';
16import * as convert from '../web/js/ext2/convert.js';
17import { parseKeybinding, reservedChords } from '../web/js/ext2/keys.js';
18import { commandsOf } from '../web/js/ext2/commands.js';
19import { globMatch, compileSelector, selectorMatches } from '../web/js/ext2/features.js';
20import { validManifest, ROLES } from '../web/js/ext2/vendor.js';
21import { sandboxOrigin, sameSite, siteOf } from '../web/js/ext2/config.js';
22import { check as checkHeaders, loadSpec, cspFor, queryAllowed, originsFor, expectedMeta } from '../sandbox/x2/headers.mjs';
23
24const HERE = path.dirname(fileURLToPath(import.meta.url));
25const REPO = path.resolve(HERE, '..');
26let fails = 0, n = 0;
27const ok = (name, c, extra = '') => { n++; console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
28
29// ── un Monaco mínimo para convert.js ──
30class Range { constructor(a, b, c, d) { this.startLineNumber = a; this.startColumn = b; this.endLineNumber = c; this.endColumn = d; } }
31const monaco = { Range, KeyCode: {}, KeyMod: { chord: (a, b) => (a | (b << 16)) >>> 0 } };
32// KeyCode de Monaco 0.52 (los que usa keys.js)
33Object.assign(monaco.KeyCode, { Backspace: 1, Tab: 2, Enter: 3, Escape: 9, Space: 10, PageUp: 11, PageDown: 12, End: 13, Home: 14, LeftArrow: 15, UpArrow: 16, RightArrow: 17, DownArrow: 18, Insert: 19, Delete: 20,
34 Digit0: 21, Digit1: 22, Digit2: 23, Digit3: 24, Digit4: 25, Digit5: 26, Digit6: 27, Digit7: 28, Digit8: 29, Digit9: 30,
35 ...Object.fromEntries('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map((c, i) => ['Key' + c, 31 + i])),
36 ...Object.fromEntries(Array.from({ length: 19 }, (_, i) => ['F' + (i + 1), 59 + i])),
37 Semicolon: 85, Equal: 86, Comma: 87, Minus: 88, Period: 89, Slash: 90, Backquote: 91, BracketLeft: 92, Backslash: 93, BracketRight: 94, Quote: 95 });
38function model(text) {
39 const lines = text.split('\n');
40 return {
41 validateRange(r) {
42 const cl = l => Math.min(Math.max(1, l), lines.length);
43 const sl = cl(r.startLineNumber), el = cl(r.endLineNumber);
44 const cc = (l, c) => Math.min(Math.max(1, c), lines[l - 1].length + 1);
45 return new Range(sl, cc(sl, r.startColumn), el, cc(el, r.endColumn));
46 },
47 getWordUntilPosition: p => ({ startColumn: p.column, endColumn: p.column, word: '' }),
48 uri: { toString: () => 'inmemory://model/1' },
49 };
50}
51
52// ── 1. protocolo ──
53ok('ready válido', validate({ t: 'ready', protocol: 1, vscode: '1.138.0' }).ok);
54ok('tipo desconocido se rechaza', !validate({ t: 'eval', code: 'x' }).ok);
55ok('protocolo distinto se rechaza', !validate({ t: 'ready', protocol: 2, vscode: '1' }).ok);
56ok('doc.edit con URI que no es file:///', !validate({ t: 'doc.edit', uri: 'https://x.test/a', base: 1, steps: [] }).ok);
57ok('doc.edit con rango malo', !validate({ t: 'doc.edit', uri: 'file:///a.js', base: 1, steps: [[{ range: [0, 1, 1, 1], text: '' }]] }).ok);
58ok('doc.edit bueno', validate({ t: 'doc.edit', uri: 'file:///a.js', base: 3, steps: [[{ range: [1, 1, 1, 2], text: 'x' }]] }).ok);
59ok('ctx.set con clave rara', !validate({ t: 'ctx.set', key: 'a b<script>', value: true }).ok);
60ok('ctx.set con objeto', !validate({ t: 'ctx.set', key: 'k', value: { a: 1 } }).ok);
61ok('providers.add con tipo desconocido', !validate({ t: 'providers.add', handle: 1, kind: 'webview', selector: [], meta: {} }).ok);
62ok('mensaje de más de 1 MB', !validate({ t: 'log', level: 'info', text: 'x'.repeat(10), pad: 'y'.repeat(LIMITS.message) }).ok);
63ok('prototipo raro no pasa', !validate(Object.create({ t: 'ready' })).ok);
64ok('ui.notify: texto y botones como cadenas; severidad conocida', validate({ t: 'ui.notify', req: 1, sev: 'warning', text: '<b>x</b>', actions: ['Yes', 'No'], source: 'pub.ext' }).ok
65 && !validate({ t: 'ui.notify', req: 1, sev: 'html', text: 'x', actions: [] }).ok && !validate({ t: 'ui.notify', req: 1, sev: 'info', text: 'x', actions: ['1', '2', '3', '4', '5', '6'] }).ok
66 && !validate({ t: 'ui.notify', req: 1, sev: 'info', text: 'x', actions: [{ label: 'x' }] }).ok);
67ok('ui.pick: separadores solos, opciones con texto', validate({ t: 'ui.pick', req: 2, items: [{ sep: 'g' }, { label: 'a', description: 'd', picked: true }], options: { canPickMany: false } }).ok
68 && !validate({ t: 'ui.pick', req: 2, items: [{ sep: 'g', label: 'x' }], options: { canPickMany: false } }).ok && !validate({ t: 'ui.pick', req: 2, items: [{ label: 1 }], options: { canPickMany: false } }).ok);
69ok('open.request: dirección con tope de 8 KB', validate({ t: 'open.request', req: 3, url: 'https://x.test/' }).ok && !validate({ t: 'open.request', req: 3, url: 'https://x.test/' + 'a'.repeat(9000) }).ok);
70ok('clipboard.write con tope; selección y desplazamiento con rangos válidos', !validate({ t: 'clipboard.write', text: 'x'.repeat(500001) }).ok && validate({ t: 'clipboard.write', text: 'x' }).ok
71 && validate({ t: 'editor.selection', uri: 'file:///a.js', selections: [[1, 1, 1, 3]] }).ok && !validate({ t: 'editor.selection', uri: 'file:///a.js', selections: [] }).ok
72 && !validate({ t: 'editor.reveal', uri: 'https://x.test/a', range: [1, 1, 1, 1] }).ok);
73ok('resultados y ediciones pueden traer un documento entero; el resto, 1 MB', validate({ t: 'result', req: 1, ok: true, value: 'x'.repeat(3 << 20) }).ok
74 && !validate({ t: 'result', req: 1, ok: true, value: 'x'.repeat(9 << 20) }).ok && !validate({ t: 'log', level: 'info', text: 'x', pad: 'x'.repeat(1 << 20) }).ok);
75const { fit, externalString } = await import('../web/js/ext2/sandbox-relay.js');
76// un vscode.Uri de mentira con las dos formas de VS Code: toString() codifica «=», «&» y «+»; toString(true), no
77const fakeUri = { toString: skip => (skip ? 'https://github.com/search?q=word+word&type=code&p=a b' : 'https://github.com/search?q%3Dword%2Bword%26type%3Dcode%26p%3Da%20b') };
78ok('abrir una dirección: un URI se abre como VS Code (encodeURI(toString(true))) y un texto, tal cual', externalString(fakeUri) === 'https://github.com/search?q=word+word&type=code&p=a%20b'
79 && externalString('https://x.test/?a=1&b=2') === 'https://x.test/?a=1&b=2' && externalString({ toString: () => 'https://y.test/' }) === 'https://y.test/' && externalString(null) === '', externalString(fakeUri));
80const bigDeco = { t: 'deco.set', key: 'k', uri: 'file:///a.js', ranges: Array.from({ length: 10000 }, () => ({ range: [1, 1, 1, 2], hover: [{ md: 'x'.repeat(4000) }] })) };
81const fitted = fit(bigDeco);
82ok('el recinto recorta antes de mandar: decoraciones sin sus textos largos, resultados enormes como error', validate(fitted).ok && fitted.ranges.length === 10000 && !fitted.ranges[0].hover
83 && fit({ t: 'result', req: 2, ok: true, value: 'x'.repeat(9 << 20) }).ok === false && fit({ t: 'log', level: 'info', text: 'x'.repeat(1 << 20) }) === null);
84ok('isPlainData: objetos y ArrayBuffer', isPlainData({ a: [1, 'x', null, { b: new ArrayBuffer(2) }] }));
85ok('isPlainData: rechaza funciones, Map y objetos con prototipo', !isPlainData({ f() {} }) && !isPlainData(new Map()) && !isPlainData({ d: new Date() }));
86ok('isPlainData: rechaza NaN', !isPlainData({ n: NaN }));
87
88// ── 2. markdown canónico sobre un corpus hostil ──
89const HOSTIL = [
90 '![i](https://beacon.test/a.png)', '[l](https://beacon.test/b)', '<img src=https://beacon.test/c.png>', '<a href="https://beacon.test">x</a>',
91 'https://beacon.test/auto', 'www.beacon.test', '<https://beacon.test/angle>', '[ref][1]\n\n[1]: https://beacon.test/ref', '![i][r]\n[r]: https://beacon.test/r.png',
92 '<style>@import url(https://beacon.test/s.css)</style>', 'javascript:alert(1)', '[x](command:workbench.action.reloadWindow)', '# título\n*em* _em_ **b**',
93 '&lt;img src=x&gt;', '<!-- c -->', '<svg onload=alert(1)>', 'text‮bidi', '`code` and ``co`de``', '```\n<img src=https://beacon.test/f.png>\n```',
94 '~~~html\n<script>x</script>\n~~~', ' indented <img src=https://beacon.test/i.png>', '>quote [l](https://beacon.test/q)',
95];
96// La propiedad que importa, comprobada sobre el markdown que sale (como lo
97// lee CommonMark): fuera del código (en línea o vallado) y de los escapes con
98// barra, no queda ningún carácter que pueda abrir un enlace, una imagen, un
99// autoenlace, HTML, énfasis o un título.
100const unescapedDangerous = md => {
101 let i = 0;
102 while (i < md.length) {
103 if (i === 0 || md[i - 1] === '\n') {
104 const f = /^(`{3,})[^\n`]*\n/.exec(md.slice(i));
105 if (f) {
106 const close = md.indexOf('\n' + f[1], i + f[0].length - 1);
107 if (close < 0) return 'unclosed fence';
108 i = close + 1 + f[1].length;
109 continue;
110 }
111 }
112 const c = md[i];
113 if (c === '\\') { i += 2; continue; }
114 if (c === '`') {
115 let n = 0; while (md[i + n] === '`') n++;
116 let j = i + n, close = -1;
117 while ((j = md.indexOf('`'.repeat(n), j)) !== -1) { if (md[j + n] !== '`' && md[j - 1] !== '`') { close = j; break; } j += n; }
118 if (close < 0) return 'unclosed code span at ' + i;
119 i = close + n;
120 continue;
121 }
122 if ('[]()<>!:*_#&~|'.includes(c)) return md.slice(Math.max(0, i - 10), i + 10);
123 i++;
124 }
125 return null;
126};
127let hostilOk = true;
128for (const src of HOSTIL) {
129 const out = canonicalMarkdown(src);
130 const bad = unescapedDangerous(out.value);
131 if (bad || out.isTrusted || out.supportHtml || out.supportThemeIcons) { hostilOk = false; console.log(' ✗', JSON.stringify(src), '→', JSON.stringify(out.value), bad); }
132}
133ok(`markdown canónico: ${HOSTIL.length} entradas hostiles sin puntuación sin escapar`, hostilOk);
134// generadas: mezclas aleatorias de piezas peligrosas
135let seed = 7;
136const rnd = k => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed % k; };
137const PIEZAS = ['![', '](', ')', '[', ']', '<', '>', 'http://', 'https://beacon.test/', '`', '```', '\n', ' ', 'a', '*', '_', '#', '&', ';', '\\', '~~~', '!', ':'];
138let genOk = true;
139for (let k = 0; k < 2000; k++) {
140 let src = '';
141 for (let j = 0, len = 1 + rnd(30); j < len; j++) src += PIEZAS[rnd(PIEZAS.length)];
142 const out = canonicalMarkdown(src).value;
143 if (unescapedDangerous(out)) { genOk = false; console.log(' ✗ generado', JSON.stringify(src), '→', JSON.stringify(out)); break; }
144}
145ok('markdown canónico: 2000 entradas generadas', genOk);
146ok('el código se conserva como código', canonicalMarkdown('use `<b>` here').value.includes('`<b>`'));
147ok('bloque vallado con lenguaje raro → sin lenguaje', /^```\n/m.test(canonicalMarkdown('```js onload=x\na\n```').value) || canonicalMarkdown('```j$\na\n```').value.includes('```\na'));
148ok('markdownFromText escapa todo', markdownFromText('[a](b) <c>').value === '\\[a\\]\\(b\\) \\<c\\>');
149ok('texto plano: imagen → alt, enlace → «t (u)»', plainText('x ![alt](https://beacon.test/i.png) [docs](https://d.test/x) <b>y</b>') === 'x alt docs (https://d.test/x) y');
150ok('CLIPBOARD fuera del snippet', stripClipboard('a$CLIPBOARD b${CLIPBOARD} c${CLIPBOARD:${1:x}} d${1:$CLIPBOARD}') === 'a b c d${1:}');
151ok('CLIPBOARD escapado se queda', stripClipboard('\\$CLIPBOARD') === '\\$CLIPBOARD' && stripClipboard('$CLIPBOARDS') === '$CLIPBOARDS');
152
153// ── 3. conversión a Monaco ──
154const m1 = model('const a = 1;\nfunction f() {}\n');
155const te = convert.textEdits(monaco, m1, [{ range: [1, 1, 1, 99], text: 'x' }, { range: [0, 1, 1, 1], text: 'bad' }, { range: [1, 1, 1, 1] }, null]);
156ok('ediciones: rango recortado, inválidas fuera', te.length === 1 && te[0].range.endColumn === 14);
157const hv = convert.hover(monaco, m1, { contents: [{ md: '![x](https://beacon.test/h.png)' }, { text: '<b>t</b>' }, { evil: 1 }], range: [1, 1, 1, 3] });
158ok('hover: markdown canónico, sin confianza ni HTML', hv.contents.length === 2 && hv.contents.every(c => c.isTrusted === false && c.supportHtml === false) && !/\]\(/.test(hv.contents[0].value.replace(/\\./g, '')));
159const ci = convert.completionItem(monaco, m1, { lineNumber: 1, column: 3 }, { h: 5, label: 'foo', kind: 99, insertText: 'x${CLIPBOARD}y', insertTextRules: 4 | 2, documentation: { md: '[d](https://beacon.test/d)' }, command: { handle: 9, title: 't' }, extra: 'nope', range: [1, 1, 1, 3] });
160ok('autocompletado: campos validados y reconstruidos', ci.label === 'foo' && ci.kind === 18 && ci.insertText === 'xy' && ci.insertTextRules === 4 && ci.documentation === 'd (https://beacon.test/d)' && !('extra' in ci) && ci.command.id === convert.HANDLE_COMMAND && convert.handleOfItem(ci) === 5);
161const sy = convert.symbols(monaco, m1, [{ name: 'f', kind: 11, range: [2, 1, 2, 16], selectionRange: [2, 10, 2, 11], children: [{ name: 'g', kind: 99, range: [2, 1, 2, 2] }] }, { name: 'bad' }]);
162ok('símbolos: válidos con hijos, kind fuera de rango → 0', sy.length === 1 && sy[0].children.length === 1 && sy[0].children[0].kind === 0);
163const mk = convert.markers(monaco, m1, [{ severity: 4, message: 'x ![i](https://beacon.test/m.png)', code: 'C1', range: [1, 1, 1, 2], target: 'https://beacon.test/t' }, { severity: 99, message: 'y', range: [1, 1, 1, 2] }]);
164ok('marcadores: mensaje en texto plano, sin destino del código, severidad saneada', mk.length === 2 && mk[0].message === 'x i' && !('target' in mk[0]) && mk[1].severity === 8);
165const uriOf = () => 'file:///a.js';
166ok('acción de código que toca otro fichero queda desactivada', !!convert.codeAction(monaco, m1, uriOf, { title: 'fix', edit: { edits: [{ uri: 'file:///other.js', range: [1, 1, 1, 2], text: 'x' }] } }).disabled);
167ok('acción de código sobre el activo se aplica', !!convert.codeAction(monaco, m1, uriOf, { title: 'fix', edit: { edits: [{ uri: 'file:///a.js', range: [1, 1, 1, 2], text: 'x' }] } }).edit);
168ok('ubicaciones: solo documentos abiertos', convert.locations(monaco, [{ uri: 'file:///a.js', range: [1, 1, 1, 2] }, { uri: 'file:///b.js', range: [1, 1, 1, 2] }], u => (u === 'file:///a.js' ? m1 : null)).length === 1);
169
170// ── 4. atajos ──
171const kb = (o, plat) => parseKeybinding(monaco, { command: 'c', ...o }, plat);
172ok('f9 → F9', kb({ key: 'f9' }, 'linux').keybinding === monaco.KeyCode.F9);
173ok('ctrl+shift+k en Linux = CtrlCmd|Shift|K', kb({ key: 'ctrl+shift+k' }, 'linux').keybinding === (2048 | 1024 | monaco.KeyCode.KeyK));
174ok('mac: cmd → CtrlCmd y ctrl → WinCtrl', kb({ key: 'ctrl+k', mac: 'cmd+k' }, 'mac').keybinding === (2048 | monaco.KeyCode.KeyK) && kb({ key: 'x', mac: 'ctrl+k' }, 'mac').keybinding === (256 | monaco.KeyCode.KeyK));
175ok('acordes de dos teclas', kb({ key: 'ctrl+k ctrl+c' }, 'linux').chord.length === 2);
176ok('Cmd/Ctrl+P reservado', !!kb({ key: 'ctrl+p' }, 'linux').skip && !!kb({ mac: 'cmd+p', key: 'x' }, 'mac').skip);
177ok('reservados: guardar, F1, ir a símbolo, terminal, deshacer, buscar, cerrar pestaña, 1-9',
178 ['ctrl+s', 'f1', 'ctrl+shift+o', 'ctrl+`', 'ctrl+z', 'ctrl+f', 'ctrl+w', 'ctrl+5', 'ctrl+shift+p'].every(k => kb({ key: k }, 'linux').skip));
179ok('tecla desconocida se salta', !!kb({ key: 'ctrl+fooo' }, 'linux').skip);
180ok('cada atajo saltado trae su código, para decirlo en el idioma de la interfaz', kb({ key: 'ctrl+p' }, 'linux').code === 'reserved' && kb({ key: 'ctrl+fooo' }, 'linux').code === 'unknown'
181 && kb({ key: 'a b c' }, 'linux').code === 'chords' && kb({ mac: 'cmd+k' }, 'linux').code === 'platform' && parseKeybinding(monaco, null).code === 'invalid' && kb({ key: 'ctrl+k' }, 'linux').code === undefined);
182ok('reservedChords no vacío', reservedChords(monaco).size > 20);
183const co = commandsOf({ contributes: { commands: [{ command: 'a.b', title: 'B', category: 'A' }, { command: 'a.hidden', title: 'H' }, { command: 'bad cmd', title: 'x' }], menus: { commandPalette: [{ command: 'a.hidden', when: 'false' }], 'editor/context': [{ command: 'a.b', group: 'nav' }] } } });
184ok('comandos: ocultos marcados, ids raros fuera, menú contextual', co.commands.length === 2 && co.commands.find(c => c.id === 'a.hidden').hidden && co.commands[0].contextGroup === 'nav');
185
186// ── 5. selectores y glob ──
187ok('glob **/*.json', globMatch('**/*.json', '/a/b/c.json') && !globMatch('**/*.json', '/a/b/c.js'));
188ok('glob {a,b} y [..]', globMatch('**/*.{ts,js}', '/x/y.ts') && globMatch('**/[a-c]x.md', '/q/bx.md') && !globMatch('**/[!a-c]x.md', '/q/bx.md'));
189ok('glob * no cruza carpetas', !globMatch('/src/*.js', '/src/a/b.js') && globMatch('/src/*.js', '/src/b.js'));
190const t0 = process.hrtime.bigint();
191const evil = 'a'.repeat(400);
192globMatch('*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*b', evil);
193const ms = Number(process.hrtime.bigint() - t0) / 1e6;
194ok('glob en tiempo lineal con un patrón patológico', ms < 1000);
195const cs = compileSelector([{ language: 'javascript', scheme: 'file' }, { language: 'json', scheme: 'vscode-userdata' }, { scheme: 'untitled', pattern: '**/*.txt' }]);
196ok('selector: esquemas file/untitled valen, otros no', cs.filters.length === 2 && Array.isArray(cs.monacoSelector) === false && cs.monacoSelector === '*');
197ok('selector: patrón contra la ruta del proyecto', selectorMatches(cs.filters, 'notes/a.txt', 'plaintext') && !selectorMatches(cs.filters, 'notes/a.md', 'markdown') && selectorMatches(cs.filters, 'x.js', 'javascript'));
198
199// ── 6. cabeceras del recinto ──
200const problems = checkHeaders();
201ok('sandbox/x2: documentos y headers.json cuadran', problems.length === 0, problems.join('; '));
202const spec = loadSpec();
203const FETCH = ['default-src', 'script-src', 'worker-src', 'child-src', 'connect-src', 'img-src', 'font-src', 'style-src', 'media-src', 'object-src', 'manifest-src'];
204const dev = originsFor('dev', { port: 1234 });
205let noHost = true;
206for (const name of Object.keys(spec.documents)) {
207 for (const d of cspFor(name, dev).split(';').map(x => x.trim())) {
208 const [dir, ...srcs] = d.split(/\s+/);
209 if (FETCH.includes(dir) && srcs.some(src => /^(https?:|wss?:|\*|[a-z0-9.-]+\.[a-z]{2,})/i.test(src) || src === "'self'")) { noHost = false; console.log(' ✗', name, d); }
210 }
211}
212ok('ninguna directiva de red nombra un host (ni \'self\')', noHost);
213// producción: lo que pondrá nginx en x2.utopiaia.com
214const prodO = originsFor('production');
215const cspS = cspFor('sandbox.html', prodO), cspE = cspFor('exthost-iframe.html', prodO);
216const uuid0 = '0123abcd-0123-4abc-8abc-0123456789ab';
217ok('producción: el recinto solo enmarca su documento del host de extensiones, y solo Code enmarca el recinto',
218 prodO.sandbox === 'https://x2.utopiaia.com' && / frame-src https:\/\/x2\.utopiaia\.com\/x2\/v1\/exthost-iframe\.html;/.test(cspS)
219 && /frame-ancestors https:\/\/code\.elffuss\.com$/.test(cspS) && /frame-ancestors 'self' https:\/\/code\.elffuss\.com$/.test(cspE), cspS.slice(-160));
220ok('producción: el host de extensiones solo con la consulta exacta, con x2.utopiaia.com como padre',
221 queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent('https://x2.utopiaia.com')}&vscodeWebWorkerExtHostId=${uuid0}`, prodO)
222 && !queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent('https://x2.utopiaiaXcom')}&vscodeWebWorkerExtHostId=${uuid0}`, prodO)
223 && !queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent('https://code.elffuss.com')}&vscodeWebWorkerExtHostId=${uuid0}`, prodO));
224ok('frame-ancestors del host de extensiones incluye \'self\' y Code', /frame-ancestors 'self' http:\/\/127\.0\.0\.1:1234/.test(cspFor('exthost-iframe.html', dev)));
225ok('frame-src del recinto: solo su documento', /frame-src http:\/\/localhost:1234\/x2\/v1\/exthost-iframe\.html(;|$)/.test(cspFor('sandbox.html', dev)));
226ok('meta CSP sin frame-ancestors', !/frame-ancestors/.test(expectedMeta('sandbox.html')));
227ok('consulta exacta del host de extensiones', queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent(dev.sandbox)}&vscodeWebWorkerExtHostId=0d6f2c3a-1b2c-4d5e-8f90-123456789abc`, dev)
228 && !queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent('https://evil.test')}&vscodeWebWorkerExtHostId=0d6f2c3a-1b2c-4d5e-8f90-123456789abc`, dev)
229 && !queryAllowed('sandbox.html', '?x=1', dev) && queryAllowed('sandbox.html', '', dev));
230ok('sin informes CSP (report-uri / report-to)', !Object.values(spec.documents).some(d => d.csp.some(x => /report-(uri|to)/.test(x))) && !('Reporting-Endpoints' in spec.common));
231
232// ── 7. manifiesto del bundle y dónde vive el recinto ──
233const vm = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8'));
234ok('vendor-manifest.json válido para la página', validManifest(vm) && vm.files.map(f => f.role).sort().join() === [...ROLES].sort().join());
235ok('vendor-manifest.json dentro del presupuesto', vm.totalGz === vm.files.reduce((a, f) => a + f.gz, 0) && vm.totalGz <= vm.budgetGz);
236ok('manifiesto con buildId de contenido', /^[0-9a-f]{16}$/.test(vm.buildId));
237ok('manifiesto roto no pasa', !validManifest({ ...vm, files: vm.files.slice(1) }) && !validManifest({ ...vm, buildId: '../x' }));
238ok('config: 127.0.0.1 → localhost del mismo puerto', sandboxOrigin({ hostname: '127.0.0.1', port: '8000', origin: 'http://127.0.0.1:8000' }) === 'http://localhost:8000');
239ok('config: localhost y hosts desconocidos → nada', sandboxOrigin({ hostname: 'localhost', port: '8000', origin: 'http://localhost:8000' }) === null && sandboxOrigin({ hostname: 'evil.test', port: '', origin: 'https://evil.test' }) === null);
240ok('config: producción → x2.utopiaia.com, otro sitio que code.elffuss.com', sandboxOrigin({ hostname: 'code.elffuss.com', port: '', origin: 'https://code.elffuss.com' }) === 'https://x2.utopiaia.com'
241 && !sameSite('https://x2.utopiaia.com', 'https://code.elffuss.com'));
242// el mismo origen en los dos sitios que lo nombran: config.js (la página) y headers.json (cabeceras y nginx)
243ok('config: headers.json nombra el mismo recinto de producción que config.js, para cada origen de Code',
244 !!spec.environments.production.sandbox && spec.environments.production.code.every(o => { const u = new URL(o); return sandboxOrigin({ hostname: u.hostname, port: u.port, origin: u.origin }) === spec.environments.production.sandbox; }),
245 JSON.stringify(spec.environments.production));
246ok('config: el dominio viejo de Code (code.elffuss.utopiaia.com, mismo sitio que el recinto) no tiene recinto',
247 sandboxOrigin({ hostname: 'code.elffuss.utopiaia.com', port: '', origin: 'https://code.elffuss.utopiaia.com' }) === null
248 && sandboxOrigin({ hostname: 'code.elffuss.utopiaia.com', port: '', origin: 'https://code.elffuss.utopiaia.com' }, { 'code.elffuss.utopiaia.com': 'https://x2.utopiaia.com' }) === null);
249// el recinto tiene que ser OTRO SITIO: un subdominio del mismo dominio registrable (otro origen) no vale
250const prod = { hostname: 'code.elffuss.com', port: '', origin: 'https://code.elffuss.com' };
251ok('config: un recinto del mismo sitio que Code (x2.elffuss.com, también por http) se rechaza; otro dominio, no',
252 sandboxOrigin(prod, { 'code.elffuss.com': 'https://x2.elffuss.com' }) === null && sandboxOrigin(prod, { 'code.elffuss.com': 'http://x2.elffuss.com' }) === null
253 && sandboxOrigin(prod, { 'code.elffuss.com': 'https://elffuss.com' }) === null && sandboxOrigin(prod, { 'code.elffuss.com': 'https://x2.elffuss-usercontent.org' }) === 'https://x2.elffuss-usercontent.org');
254ok('config: el sitio va por lo alto (nunca da por distintos dos del mismo dominio registrable)', siteOf('a.b.example.co.uk') === 'co.uk' && siteOf('127.0.0.1') === '127.0.0.1' && siteOf('localhost') === 'localhost'
255 && sameSite('https://a.x.example', 'http://b.x.example') && !sameSite('https://a.x.example', 'https://b.example') && !sameSite('http://127.0.0.1:9', 'http://localhost:9') && sameSite('not a url', 'https://x.example'));
256
257// sandboxManifest vive en bridge.js, que importa módulos de navegador: se
258// comprueba aparte con un import dinámico que no ejecuta nada de la página
259const { sandboxManifest } = await import('../web/js/ext2/bridge.js');
260const sm = sandboxManifest({ name: 'n', publisher: 'p', version: '1.0.0', main: './node.js', browser: './web.js', activationEvents: ['onCommand:x'], extensionDependencies: ['p.dep', 'p.missing'],
261 contributes: { commands: [{ command: 'x', title: 'X' }], keybindings: [{ key: 'f9', command: 'x' }], menus: {}, themes: [{}], languages: [{ id: 'toml' }], configuration: { properties: {} }, views: {} } }, new Set(['p.dep']));
262ok('manifiesto del recinto: sin main, atajos, menús, temas ni vistas', !('main' in sm) && Object.keys(sm.contributes).sort().join() === 'commands,configuration');
263ok('manifiesto del recinto: dependencias solo instaladas, onLanguage de sus lenguajes', sm.extensionDependencies.join() === 'p.dep' && sm.activationEvents.includes('onLanguage:toml') && sm.activationEvents.includes('onCommand:x'));
264
265// ── 7b. cortafuegos de RPC: lista de llamadas permitidas ──
266const { validAllowlist, allowedCalls } = await import('../web/js/ext2/bridge.js');
267const rpcList = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/rpc-allowlist.json'), 'utf8'));
268const surfaceSnap = JSON.parse(fs.readFileSync(path.join(HERE, 'x2-surface.json'), 'utf8'));
269ok('rpc-allowlist.json válido', validAllowlist(rpcList));
270const calls = allowedCalls(rpcList);
271const outside = Object.entries(calls).flatMap(([a, ms]) => ms.filter(x => !(surfaceSnap.actors[a] || []).includes(x)).map(x => a + '.' + x));
272ok('cada llamada permitida existe en la foto de la superficie (subconjunto)', outside.length === 0, outside.join(', '));
273ok('solo métodos «$…»', Object.values(calls).flat().every(x => /^\$\w+$/.test(x)));
274const classified = new Set([...Object.keys(rpcList.actors), ...rpcList.deniedActors]);
275const unclassified = Object.keys(surfaceSnap.actors).filter(a => !classified.has(a));
276ok('cada actor de la superficie está permitido o denegado (nada sin revisar)', unclassified.length === 0, unclassified.join(', '));
277ok('ningún actor está a la vez permitido y denegado', rpcList.deniedActors.every(a => !(a in rpcList.actors)));
278const MUST_DENY = ['MainThreadWebviews', 'MainThreadWebviewPanels', 'MainThreadWebviewViews', 'MainThreadCustomEditors', 'MainThreadEditorInsets', 'MainThreadTerminalService',
279 'MainThreadDebugService', 'MainThreadSCM', 'MainThreadTask', 'MainThreadAuthentication', 'MainThreadLanguageModels', 'MainThreadChatAgents2', 'MainThreadTunnelService',
280 'MainThreadNotebook', 'MainThreadNotebookKernels', 'MainThreadComments', 'MainThreadTimeline', 'MainThreadDownloadService', 'MainThreadManagedSockets', 'MainThreadUriOpeners'];
281ok('denegados: webviews, terminal, depurador, SCM, tareas, autenticación, modelos, chat, túneles, notebooks, comentarios, línea de tiempo, descargas, sockets',
282 MUST_DENY.every(a => rpcList.deniedActors.includes(a) && !(a in rpcList.actors)), MUST_DENY.filter(a => !rpcList.deniedActors.includes(a)).join(', '));
283ok('de los denegados solo pasan las llamadas de arranque del propio host (hostSetup)', Object.keys(rpcList.hostSetup).every(a => rpcList.deniedActors.includes(a))
284 && Object.values(rpcList.hostSetup).flat().every(x => /^\$(register|get)\w+$/.test(x)));
285ok('ni guardar ni tocar el espacio de trabajo ni la red', !calls.MainThreadDocuments.includes('$trySaveDocument') && ['$save', '$saveAll', '$updateWorkspaceFolders', '$resolveProxy', '$loadCertificates'].every(x => !calls.MainThreadWorkspace.includes(x)));
286ok('lista rota no pasa', !validAllowlist({ schema: 1, actors: { MainThreadX: ['dispose'] } }) && !validAllowlist({ schema: 1, actors: [] }) && !validAllowlist(null));
287
288// ── 7c. puertas: cómo se enseña una dirección, qué órdenes del agente preguntan ──
289const gates = await import('../web/js/ext2/gates.js');
290const RLO = String.fromCodePoint(0x202E), ZWSP = String.fromCodePoint(0x200B), BEL = String.fromCodePoint(7), A_CYR = String.fromCodePoint(0x430);
291ok('dirección: los caracteres bidi y de control se ven', gates.visibleText('https://a.test/' + RLO + 'txt.exe') === 'https://a.test/<U+202E>txt.exe' && gates.visibleText('a' + ZWSP + 'b' + BEL) === 'a<U+200B>b<U+0007>');
292const cyr = new URL('https://' + A_CYR + 'pple.com/').hostname; // «а» cirílica
293ok('punycode → Unicode', gates.unicodeHost('xn--mnchen-3ya.de') === 'münchen.de' && gates.unicodeHost(cyr) === A_CYR + 'pple.com' && gates.unicodeHost('plain.test') === 'plain.test', cyr);
294const d1 = gates.describeUrl('https://' + A_CYR + 'pple.com/login');
295ok('describeUrl: host en punycode y en Unicode cuando difieren', d1.openable && d1.host === cyr && d1.hostUnicode === A_CYR + 'pple.com' && d1.href === `https://${cyr}/login`);
296ok('describeUrl: solo http, https y mailto se pueden abrir', !gates.describeUrl('javascript:alert(1)').openable && !gates.describeUrl('command:workbench.action.reloadWindow').openable
297 && gates.describeUrl('mailto:a@b.test').openable && gates.describeUrl('mailto:a@b.test').site === 'b.test' && !gates.describeUrl('no es una url').ok);
298ok('agente: un runtime del Bridge en cualquier tramo de la orden pregunta', gates.runsRuntime('ls && node x.js') && gates.runsRuntime('cat a | python3 -') && gates.runsRuntime('echo a; npm i')
299 && !gates.runsRuntime('ls -la; cat node.txt') && !gates.runsRuntime('echo "node; npm"'));
300ok('agente: la búsqueda enseña las dos direcciones que puede pedir', gates.searchUrls('a b').length === 2 && gates.searchUrls('a b')[0] === 'https://html.duckduckgo.com/html/?q=a%20b');
301const fakeTools = { 'web.fetch': { run: async a => 'fetched ' + a.url }, 'web.search': { run: async () => 'searched' }, 'terminal.run': { run: async a => 'ran ' + a.command } };
302const asked = [];
303const restore = gates.installAgentGate(fakeTools, { ask: async (kind, lines) => { asked.push([kind, lines]); return lines[0].includes('ok'); } });
304const r1 = await fakeTools['web.fetch'].run({ url: 'https://x.test/no' }), r2 = await fakeTools['web.fetch'].run({ url: 'https://x.test/ok' });
305const r3 = await fakeTools['terminal.run'].run({ command: 'ls' }), r4 = await fakeTools['terminal.run'].run({ command: 'npm test' });
306restore();
307const r5 = await fakeTools['web.fetch'].run({ url: 'https://x.test/no' });
308ok('agente: denegar devuelve el aviso, permitir ejecuta; al quitar la puerta todo vuelve', r1 === gates.AGENT_DENIED && r2 === 'fetched https://x.test/ok' && r3 === 'ran ls' && r4 === gates.AGENT_DENIED
309 && r5 === 'fetched https://x.test/no' && asked.length === 3, JSON.stringify({ r1, r2, r3, r4, r5, asked }));
310
311// ── 7d. decoraciones: lista blanca de CSS ──
312const deco = await import('../web/js/ext2/decorations.js');
313ok('colores válidos', ['#fff', '#ff000080', 'rgba(1, 2, 3, 0.5)', 'rgb(1 2 3 / 50%)', 'hsl(120deg 50% 50%)', 'Red', 'transparent'].every(c => deco.color(c))
314 && deco.color({ themeColor: 'editorError.foreground' }) === 'var(--vscode-editorError-foreground)');
315const HOSTILE_CSS = ['url(http://beacon.test/x)', 'red;background:url(http://beacon.test/x)', 'expression(alert(1))', 'var(--x)', 'red }', '#fff;', 'rgb(1,2,3);x:url(y)',
316 'image-set(url(a) 1x)', '\\75 rl(x)', 'attr(x)', 'calc(1px+2px)'];
317ok('colores hostiles fuera', HOSTILE_CSS.every(c => deco.color(c) === null) && deco.color({ themeColor: 'a;b' }) === null);
318ok('textDecoration: tokens conocidos sí, inyecciones no', deco.textDecoration('underline wavy red') === 'underline wavy red' && deco.textDecoration('line-through 2px') === 'line-through 2px'
319 && deco.textDecoration('none; display: none') === null && deco.textDecoration('underline url(x)') === null);
320ok('border: solo si se parte en anchura, estilo y color', deco.borderShorthand('1px solid red') === '1px solid red' && deco.borderShorthand('thin dashed #fff') === 'thin dashed #fff'
321 && deco.borderShorthand('1px solid red; background:url(x)') === null && deco.borderShorthand('1px solid red red red') === null);
322const dHostile = deco.declarations({ backgroundColor: 'url(http://beacon.test/a)', color: 'red', fontFamily: 'x', cursor: 'url(x), pointer', textDecoration: 'none;a:b', opacity: '0.5', letterSpacing: '1px' }, 'inline')
323 + deco.declarations({ backgroundColor: 'url(http://beacon.test/a)', border: 'url(x)', borderRadius: '3px', outline: '1px solid blue' }, 'block');
324ok('declaraciones: lo hostil no llega, lo válido sí', !/url|font-family|beacon|cursor|text-decoration/.test(dHostile) && /color: red;/.test(dHostile) && /opacity: 0\.5;/.test(dHostile)
325 && /border-radius: 3px;/.test(dHostile) && /outline: 1px solid blue;/.test(dHostile), dHostile);
326
327// ── 7e. qué funcionará (classify.js) y ajustes ──
328const cl = await import('../web/js/ext2/classify.js');
329ok('engines.vscode contra 1.138.0', cl.engineOk('^1.80.0') && !cl.engineOk('^1.200.0') && cl.engineOk('>=1.0.0') && cl.engineOk('*') && !cl.engineOk('^2.0.0')
330 && cl.engineOk('~1.138.0') && !cl.engineOk('~1.137.0') && cl.engineOk('1.90.x') && cl.engineOk(undefined));
331const base2 = { name: 'w', publisher: 'p', version: '1.0.0', engines: { vscode: '^1.80.0' } };
332const nodeOnly = cl.classify({ ...base2, main: './x.js', contributes: { commands: [{}] } });
333ok('Node: no corre aquí y no «funciona»', nodeOnly.runtime === 'node' && !nodeOnly.works && !nodeOnly.eligible);
334const webExt = cl.classify({ ...base2, browser: './w.js', contributes: { commands: [{}, {}], keybindings: [{}], configuration: { properties: { 'w.a': { type: 'boolean' } } }, views: { x: [{}] }, debuggers: [{}] } });
335ok('web: corre, con sus comandos y ajustes, y dice lo que no saldrá', webExt.eligible && webExt.works && webExt.counts.commands === 2 && webExt.counts.keybindings === 1
336 && webExt.counts.settings === 1 && webExt.unavailable.includes('views') && webExt.unavailable.includes('debuggers'));
337ok('web que no puede correr: motor nuevo, solo eventos que nunca llegan', !cl.classify({ ...base2, browser: './w.js', engines: { vscode: '^1.200.0' } }).eligible
338 && cl.classify({ ...base2, browser: './w.js', activationEvents: ['onView:x', 'workspaceContains:**/a'] }).startsNever && !cl.classify({ ...base2, browser: './w.js', activationEvents: ['onView:x'] }).eligible);
339// las APIs propuestas son un aviso, no un veto (el censo vio arrancar a muchas que las declaran)
340const prop = cl.classify({ ...base2, browser: './w.js', enabledApiProposals: ['x'] });
341ok('APIs propuestas: puede correr, con un aviso', prop.eligible && prop.works && prop.warnings.includes('proposals') && !prop.reasons.includes('proposals'), JSON.stringify({ e: prop.eligible, w: prop.warnings, r: prop.reasons }));
342const vivo = id => ({ results: { [id]: { state: 'active', commands: 1, providers: {} } } });
343ok('lo que el censo vio arrancar puede correr aunque la regla estática dijera que no', cl.classify({ ...base2, browser: './w.js', activationEvents: ['onView:x'] }, { tested: vivo('p.w@1.0.0') }).eligible
344 && cl.classify({ ...base2, browser: './w.js', engines: { vscode: '^1.200.0' } }, { tested: vivo('p.w@1.0.0') }).eligible);
345// las mismas reglas que el «Aplica» del panel: un lenguaje de serie de Monaco no cuenta, ni la gramática de uno de serie sin Monarch
346const monacoLangs = JSON.parse(fs.readFileSync(path.join(HERE, 'lib/monaco-languages.json'), 'utf8')).languages;
347const deSerie = new Set(monacoLangs.map(l => l.id)), monarch = new Set(monacoLangs.filter(l => l.monarch).map(l => l.id));
348const reglas = { builtinLanguage: id => deSerie.has(id), grammarSkippedFor: id => deSerie.has(id) && !monarch.has(id) };
349ok('monaco-languages.json: la lista de serie de Monaco 0.52.2 (python, json…; json y plaintext sin Monarch)', monacoLangs.length > 50 && deSerie.has('python') && deSerie.has('json') && !monarch.has('json') && monarch.has('python'));
350const pyrefly = cl.classify({ ...base2, main: './x.js', contributes: { languages: [{ id: 'python', extensions: ['.py'] }] } }, reglas);
351ok('Node con solo un lenguaje de serie (como Pyrefly): nada se aplica, nada funciona', !pyrefly.hasDeclarative && !pyrefly.works && pyrefly.declarative.languages === 0, JSON.stringify(pyrefly.declarative));
352const mezcla = cl.classify({ ...base2, browser: './w.js', contributes: { languages: [{ id: 'json' }, { id: 'graphql' }, { id: 'toml-x' }], grammars: [{ language: 'json', path: 'j' }, { language: 'python', path: 'p' }, { path: 'inj' }] } }, reglas);
353ok('lenguajes y gramáticas: cuentan solo los que se aplicarían (como en el panel)', mezcla.declarative.languages === 1 && mezcla.declarative.grammars === 2, JSON.stringify(mezcla.declarative));
354// donde el nivel 2 no puede arrancar (sitio, navegador), su código no cuenta como «funciona»
355const aquiNo = cl.classify({ ...base2, browser: './w.js', contributes: { commands: [{}] } }, { canRun: false });
356ok('donde el código no puede correr, una que solo trae código no «funciona» (el filtro la esconde)', aquiNo.eligible && !aquiNo.works
357 && cl.classify({ ...base2, browser: './w.js', contributes: { themes: [{ path: 't' }] } }, { canRun: false }).works);
358ok('lo declarativo cuenta como «funciona» aunque sea de Node', cl.classify({ ...base2, main: './x.js', contributes: { themes: [{ path: 't.json' }] } }).works);
359ok('dependencias que faltan se dicen', cl.classify({ ...base2, browser: './w.js', extensionDependencies: ['a.b'] }, { installed: new Set() }).deps.missing.join() === 'a.b');
360const tested = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/tested.json'), 'utf8'));
361const pret = cl.classify({ name: 'prettier-vscode', publisher: 'esbenp', version: '12.4.0', browser: './dist/browser.js', engines: { vscode: '^1.80.0' } }, { tested });
362ok('el resultado del censo se encuentra por id@versión', pret.census?.state === 'active' && !!pret.census.providers?.format);
363const failedOne = Object.entries(tested.results).find(([, v]) => v.state === 'error');
364const [fid, fver] = failedOne[0].split('@');
365const fcls = cl.classify({ name: fid.split('.').slice(1).join('.'), publisher: fid.split('.')[0], version: fver, browser: './w.js' }, { tested });
366ok('una que falló en el censo no se ofrece para ejecutar', !fcls.eligible && fcls.reasons.includes('census'), failedOne[0]);
367const man = { contributes: { configuration: [{ properties: { 'p.semi': { type: 'boolean' }, 'p.width': { type: 'integer' }, 'p.mode': { type: 'string', enum: ['a', 'b'] }, 'p.any': {} } }] } };
368const vs = (t) => cl.validateSettings(man, t);
369ok('ajustes: los que declara, del tipo que dice', vs('{"p.semi": false, "p.width": 80, "p.mode": "b", "p.any": [1]}').ok && vs('').ok);
370ok('ajustes: desconocidos, de otro tipo, fuera de la lista, JSON roto y no-objeto, rechazados',
371 vs('{"p.nope": 1}').errors[0].code === 'unknown' && vs('{"p.semi": "no"}').errors[0].code === 'type' && vs('{"p.width": 1.5}').errors[0].code === 'type'
372 && vs('{"p.mode": "c"}').errors[0].code === 'enum' && vs('{').errors[0].code === 'json' && vs('[1]').errors[0].code === 'object' && vs('{"__proto__": {"x": 1}}').ok === false);
373
374// ── 8. ningún fichero del nivel 2 lleva rutas de máquina ──
375// ── textos: los del nivel 2 en js/ext2/strings.js, los del panel en js/ext/i18n.js ──
376const { STRINGS } = await import('../web/js/ext/i18n.js');
377const { STRINGS2 } = await import('../web/js/ext2/strings.js');
378const sameKeys = t => JSON.stringify(Object.keys(t.es).sort()) === JSON.stringify(Object.keys(t.en).sort());
379ok('textos del nivel 2: ES y EN con las mismas claves', sameKeys(STRINGS2), Object.keys(STRINGS2.en).filter(k => !(k in STRINGS2.es)).join(' '));
380ok('textos del nivel 2: ninguno vacío ni con {var} sin cerrar', ['es', 'en'].every(l => Object.values(STRINGS2[l]).every(v => typeof v === 'string' && v.trim() && !/\{[^}]*$/.test(v))));
381// toda clave literal tx('…') de los módulos que la usan existe en algún idioma
382const usados = [];
383for (const f of [...fs.readdirSync(path.join(REPO, 'web/js/ext2')).filter(f => f.endsWith('.js')).map(f => 'web/js/ext2/' + f), 'web/js/ext/panel.js', 'web/js/ext/host.js']) {
384 for (const m of fs.readFileSync(path.join(REPO, f), 'utf8').matchAll(/\btx\(\s*'([A-Za-z0-9_]+)'\s*[,)]/g)) usados.push([f, m[1]]);
385}
386const faltan = usados.filter(([, k]) => !(k in STRINGS.en)).map(([f, k]) => `${path.basename(f)}:${k}`);
387ok(`cada tx('…') literal tiene su texto (${usados.length} usos)`, usados.length > 100 && !faltan.length, faltan.slice(0, 6).join(' '));
388// (y las que se arman: la razón del recinto, el error de un ajuste, la parte de VS Code que no saldrá)
389const prefijos = {
390 x2Unavail_: ['site', 'browser', 'off', 'url', 'manifest'],
391 x2Err_: ['network', 'integrity', 'timeout', 'editor', 'violations', 'fatal', 'navigated', 'csp', 'other'],
392 keySkip_: ['reserved', 'invalid', 'platform', 'chords', 'unknown'],
393 set_: ['json', 'object', 'unknown', 'type', 'enum', 'big'],
394 wb_: ['views', 'custom_editors', 'notebooks', 'walkthroughs', 'debugger', 'terminal', 'tasks', 'sign_in', 'chat', 'MCP_servers', 'file_labels', 'menus', 'status_bar', 'remote', 'TypeScript_plugins', 'other'],
395};
396ok('las familias de claves que se arman en tiempo de ejecución están completas', Object.entries(prefijos).every(([p, xs]) => xs.every(x => (p + x) in STRINGS.en && (p + x) in STRINGS.es)));
397// los fallos del recinto se dicen en el idioma de la interfaz (sus mensajes técnicos, en español o inglés, no salen)
398const mg = await import('../web/js/ext2/manage.js');
399const integ = mg.runtimeErrorText({ code: 'integrity', message: 'sandbox-main.js: no se pudo bajar o no coincide con su SRI', file: 'sandbox-main.js' });
400ok('fallos del recinto: un texto por código, sin el mensaje técnico', integ === 'the sandbox is not running: one of its files does not match its checksum (sandbox-main.js), so nothing was started'
401 && mg.runtimeErrorText({ code: 'site' }) === STRINGS.en.x2Unavail_site && mg.runtimeErrorText({ code: 'x2-browser' }) === STRINGS.en.x2Unavail_browser
402 && mg.runtimeErrorText({ code: 'disabled' }) === STRINGS.en.x2Unavail_off && /something went wrong \(weird\)/.test(mg.runtimeErrorText({ code: 'weird', message: 'raro' }))
403 && mg.isRuntimeError({ code: 'timeout' }) && !mg.isRuntimeError({ code: 'missing' }), integ);
404
405// ── host2.js: el código del paquete, sin salir de él ──
406const { zip } = await import('./ext_fixtures.mjs');
407const h2 = await import('../web/js/ext2/host2.js');
408const paquete = zip([
409 ['extension/package.json', '{"name":"e","publisher":"p","version":"1.0.0","browser":"./dist/web"}'],
410 ['extension/dist/web.js', 'exports.activate = () => {};'],
411 ['extension/dist/web.js.map', '{}'],
412 ['extension/node_modules/x/index.js', 'x'],
413 ['extension/../escape.js', 'no'],
414 ['extension//abs.js', 'no'],
415 ['extension/./dot.js', 'no'],
416 ['other/outside.js', 'no'],
417]);
418const raw = await h2.readVsixRaw(paquete);
419const names = [...raw.files.keys()].sort();
420ok('readVsixRaw: solo lo de extension/, sin node_modules, sin .map y sin rutas que salgan del paquete', JSON.stringify(names) === JSON.stringify(['dist/web.js', 'package.json']), names.join(' '));
421ok('readVsixRaw: cuenta lo descomprimido', raw.bytes === [...raw.files.values()].reduce((n, b) => n + b.length, 0));
422let big = null;
423try { await h2.readVsixRaw(zip([['extension/a.js', 'x'.repeat(2048)]]), { maxEntry: 1024 }); } catch (e) { big = e; }
424ok('readVsixRaw: un fichero por encima del tope se rechaza', !!big, String(big?.message));
425ok('browserEntry: «./dist/web» → dist/web.js; ausente → null', h2.browserEntry({ browser: './dist/web' }, raw.files) === 'dist/web.js'
426 && h2.browserEntry({ browser: './dist/missing' }, raw.files) === null && h2.browserEntry({}, raw.files) === null);
427
428// ── el censo que se publica (web/js/ext2/tested.json) ──
429const results = Object.entries(tested.results);
430const by = st => results.filter(([, v]) => v.state === st).length;
431ok('censo: cada entrada es id@versión en minúsculas, con su estado', results.length === tested.counts.browserEntry && results.every(([k, v]) => /^[a-z0-9-]+\.[a-z0-9._-]+@[\w.+-]+$/.test(k) && typeof v.state === 'string'), String(results.length));
432ok('censo: los recuentos cuadran con las entradas y la baliza a 0', tested.counts.active === by('active') && tested.counts.error === by('error') && tested.counts.beaconHits === 0
433 && tested.counts.installFailed === by('install-failed'), JSON.stringify(tested.counts));
434ok('censo: sin tiempos', !JSON.stringify(tested).match(/"(ms|millis|seconds|duration|elapsed|time)[A-Za-z]*"\s*:/i));
435// ninguna que el censo vio arrancar se dice «no puede correr» ni la esconde el filtro
436const activas = results.filter(([, v]) => v.state === 'active');
437const mal = activas.filter(([k, v]) => {
438 const [id, version] = k.split('@');
439 const [publisher, ...rest] = id.split('.');
440 const c = cl.classify({ name: rest.join('.'), publisher, version, browser: './web.js', ...(v.apiProposals ? { enabledApiProposals: Array.from({ length: v.apiProposals }, (_, i) => 'p' + i) } : {}),
441 activationEvents: ['onView:x'], engines: { vscode: '^1.999.0' } }, { tested });
442 return !c.eligible || !c.works;
443}).map(([k]) => k);
444ok(`censo: las ${activas.length} que arrancaron pueden correr y el filtro las enseña, aunque declaren APIs propuestas`, activas.length > 30 && !mal.length, mal.join(' '));
445// …y con sus manifiestos de verdad, si están en tests/.cache/census (los guarda x2_census)
446const cacheDir = path.join(HERE, '.cache/census');
447const reales = activas.map(([k]) => {
448 const id = k.split('@')[0];
449 const f = fs.existsSync(cacheDir) ? fs.readdirSync(cacheDir).find(x => x.toLowerCase() === id + '.json') : null;
450 const c = f ? JSON.parse(fs.readFileSync(path.join(cacheDir, f), 'utf8')) : null;
451 return c?.manifest && c.version === k.split('@')[1] ? [k, c.manifest] : null;
452}).filter(Boolean);
453if (!reales.length) console.log('⏭️ NOT RUN (part) — the census manifests are not in tests/.cache/census; the check above used the census entries');
454else {
455 const malR = reales.filter(([, m]) => { const c = cl.classify(m, { tested, ...reglas }); return !c.eligible || !c.works || c.reasons.some(r => r !== 'deps'); }).map(([k]) => k);
456 ok(`censo, con sus manifiestos reales (${reales.length}): ninguna que arrancó sale como «no puede correr» ni escondida`, !malR.length, malR.join(' '));
457}
458
459// ── el censo estático del catálogo entero (tests/catalog-census/): cada recuento sale de sus líneas ──
460const cat = JSON.parse(fs.readFileSync(path.join(HERE, 'catalog-census/summary.json'), 'utf8'));
461const tsv = fs.readFileSync(path.join(HERE, 'catalog-census/extensions.tsv'), 'utf8').split('\n').filter(Boolean);
462const [head, ...lineas] = tsv;
463const cols = head.split('\t');
464const filas = lineas.map(l => Object.fromEntries(l.split('\t').map((v, i) => [cols[i], v])));
465const leidas = filas.filter(r => r.runtime !== 'unreadable');
466const cuenta = f => leidas.filter(f).length;
467const recount = {
468 read: leidas.length, unreadable: filas.length - leidas.length,
469 browserEntry: cuenta(r => r.runtime === 'browser'), runsInSandbox: cuenta(r => r.runs_in_sandbox === '1'), nodeOnly: cuenta(r => r.runtime === 'node'), noCode: cuenta(r => r.runtime === 'none'),
470 declarativeApplies: cuenta(r => r.declarative === '1'), worksInCode: cuenta(r => r.works === '1'), worksOnlyThroughCode: cuenta(r => r.works === '1' && r.declarative === '0'), nothingWorks: cuenta(r => r.works === '0'),
471};
472const top = n => leidas.filter(r => r.rank !== '-' && Number(r.rank) <= n);
473ok('catálogo: cada recuento del resumen sale de extensions.tsv (una línea por extensión), también el del top 500', Object.entries(recount).every(([k, v]) => cat[k] === v)
474 && cat.bands.top500.browserEntry === top(500).filter(r => r.runtime === 'browser').length && cat.bands.top100.worksInCode === top(100).filter(r => r.works === '1').length,
475 JSON.stringify(Object.fromEntries(Object.entries(recount).filter(([k, v]) => cat[k] !== v).map(([k, v]) => [k, [cat[k], v]]))));
476ok('catálogo: con fecha y tamaño, todo listado, sin tiempos', /^\d{4}-\d\d-\d\d$/.test(cat.date) && cat.listed === filas.length && cat.listed >= cat.catalog && cat.notReachableBySearch === 0
477 && !JSON.stringify(cat).match(/"(ms|millis|seconds|duration|elapsed|time)[A-Za-z]*"\s*:/i), JSON.stringify({ date: cat.date, catalog: cat.catalog, listed: cat.listed, lines: filas.length }));
478ok('catálogo y censo en ejecución: las del top 500 con entrada de navegador son las mismas 89', top(500).filter(r => r.runtime === 'browser').length === results.length
479 && top(500).filter(r => r.runtime === 'browser').every(r => results.some(([k]) => k.split('@')[0] === r.id.toLowerCase())));
480
481const files = [...fs.readdirSync(path.join(REPO, 'web/js/ext2')).map(f => 'web/js/ext2/' + f), 'sandbox/x2/headers.json', 'sandbox/x2/headers.mjs', 'sandbox/x2/v1/sandbox.html', 'sandbox/x2/v1/exthost-iframe.html'];
482const home = ['/', 'Users', '/'].join(''), linuxHome = ['/', 'home', '/'].join('');
483ok('ni rutas de usuario ni prefijos de home en el nivel 2', files.every(f => { const t = fs.readFileSync(path.join(REPO, f), 'utf8'); return !t.includes(home) && !t.includes(linuxHome); }));
484
485console.log(`\n${n - fails}/${n} ok`);
486process.exit(fails ? 1 : 0);