| 1 | // El bundle del nivel 2 (VS Code sin interfaz que corre el código de las |
| 2 | // extensiones): manifiesto, tamaño y descarga VERIFICADA. |
| 3 | // |
| 4 | // Cada fichero se baja con su SRI (el navegador rechaza un .gz distinto), se |
| 5 | // descomprime aquí con DecompressionStream y se comprueba la sha256 de los |
| 6 | // bytes crudos contra el manifiesto. Cualquier diferencia, o el interruptor |
| 7 | // «enabled: false» del manifiesto, para el nivel 2 sin arrancar nada a medias. |
| 8 | // Funciona aunque un proxy añada su propia compresión de transporte. |
| 9 | |
| 10 | import { sandboxOrigin } from './config.js'; |
| 11 | |
| 12 | const MANIFIESTO = new URL('./vendor-manifest.json', import.meta.url); |
| 13 | const BASE = new URL('../../vendor/x2/', import.meta.url); |
| 14 | export const ROLES = ['main', 'extensionHostWorkerMain', 'editorWorkerService']; |
| 15 | |
| 16 | const fallo = (code, msg, extra = {}) => Object.assign(new Error(msg), { code, ...extra }); |
| 17 | const hex = buf => [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join(''); |
| 18 | |
| 19 | export function validManifest(m) { |
| 20 | const ok = m && m.schema === 1 && typeof m.enabled === 'boolean' && /^[0-9a-f]{16}$/.test(m.buildId) && m.protocol === 1 |
| 21 | && Array.isArray(m.files) && m.files.length === ROLES.length |
| 22 | && m.files.every(f => f && /^[a-z-]+\.js$/.test(f.name) && ROLES.includes(f.role) |
| 23 | && Number.isSafeInteger(f.raw) && f.raw > 0 && Number.isSafeInteger(f.gz) && f.gz > 0 |
| 24 | && /^[0-9a-f]{64}$/.test(f.sha256Raw) && /^sha256-[A-Za-z0-9+/]{43}=$/.test(f.sriGz)) |
| 25 | && new Set(m.files.map(f => f.role)).size === ROLES.length; |
| 26 | return !!ok; |
| 27 | } |
| 28 | |
| 29 | let manifiesto = null; |
| 30 | export async function loadManifest({ signal } = {}) { |
| 31 | manifiesto ??= (async () => { |
| 32 | let r; |
| 33 | try { r = await fetch(MANIFIESTO, { cache: 'no-cache', credentials: 'same-origin', signal }); } |
| 34 | catch (e) { throw fallo('network', 'no pude leer el manifiesto del nivel 2: ' + (e?.message || e)); } |
| 35 | if (!r.ok) throw fallo('network', 'manifiesto del nivel 2: HTTP ' + r.status); |
| 36 | const m = await r.json().catch(() => null); |
| 37 | if (!validManifest(m)) throw fallo('manifest', 'manifiesto del nivel 2 no válido'); |
| 38 | return m; |
| 39 | })().catch(e => { manifiesto = null; throw e; }); |
| 40 | return manifiesto; |
| 41 | } |
| 42 | |
| 43 | // Lo que se bajaría la primera vez (los .gz juntos), para enseñarlo ANTES. |
| 44 | export const runtimeBytes = m => m.files.reduce((n, f) => n + f.gz, 0); |
| 45 | |
| 46 | async function inflar(gz) { |
| 47 | const flujo = new Blob([gz]).stream().pipeThrough(new DecompressionStream('gzip')); |
| 48 | return new Response(flujo).arrayBuffer(); |
| 49 | } |
| 50 | |
| 51 | // → [{ role, name, bytes: ArrayBuffer }] con los bytes crudos ya verificados |
| 52 | export async function loadVendor(m, { onProgress = () => {}, signal } = {}) { |
| 53 | if (!m.enabled) throw fallo('disabled', 'el nivel 2 está desactivado en este despliegue'); |
| 54 | const total = runtimeBytes(m); |
| 55 | let hecho = 0; |
| 56 | return Promise.all(m.files.map(async f => { |
| 57 | const url = new URL(`${m.buildId}/${f.name}.gz`, BASE); |
| 58 | let r; |
| 59 | try { r = await fetch(url, { integrity: f.sriGz, cache: 'default', credentials: 'same-origin', signal }); } |
| 60 | catch (e) { |
| 61 | if (e?.name === 'AbortError') throw e; |
| 62 | // un SRI que no cuadra también acaba aquí (TypeError): se trata como integridad |
| 63 | throw fallo('integrity', `${f.name}: no se pudo bajar o no coincide con su SRI`, { file: f.name }); |
| 64 | } |
| 65 | if (!r.ok) throw fallo('network', `${f.name}: HTTP ${r.status}`, { file: f.name }); |
| 66 | const gz = await r.arrayBuffer(); |
| 67 | hecho += f.gz; |
| 68 | onProgress(hecho, total); |
| 69 | let bytes; |
| 70 | try { bytes = await inflar(gz); } catch { throw fallo('integrity', `${f.name}: el .gz no se descomprime`, { file: f.name }); } |
| 71 | if (bytes.byteLength !== f.raw || hex(await crypto.subtle.digest('SHA-256', bytes)) !== f.sha256Raw) { |
| 72 | throw fallo('integrity', `${f.name}: la sha256 no coincide con el manifiesto`, { file: f.name }); |
| 73 | } |
| 74 | return { role: f.role, name: f.name, bytes }; |
| 75 | })); |
| 76 | } |
| 77 | |
| 78 | // ── ¿se puede aquí, y cuánto pesa? (lo que se enseña ANTES de encender nada) ── |
| 79 | export const RUNTIME_KEY = 'elffusscode.x2.runtime'; |
| 80 | |
| 81 | // v1: Chrome y Edge (ancestorOrigins para el apretón de manos, Navigation API |
| 82 | // para que el recinto no navegue, DecompressionStream para el bundle) |
| 83 | export function supported(w = globalThis) { |
| 84 | try { |
| 85 | return !!(w.location && 'ancestorOrigins' in w.location && w.navigation && typeof w.DecompressionStream === 'function' |
| 86 | && w.crypto?.subtle && typeof w.MessageChannel === 'function' && w.HTMLElement && 'inert' in w.HTMLElement.prototype); |
| 87 | } catch { return false; } |
| 88 | } |
| 89 | // ?noext apaga todas las extensiones; ?noext2, solo su código |
| 90 | export const disabledByUrl = (search = globalThis.location?.search || '') => /[?&]noext2?(?:[=&]|$)/.test(search); |
| 91 | |
| 92 | export async function runtimeInfo() { |
| 93 | if (disabledByUrl()) return { available: false, reason: 'url' }; |
| 94 | if (!supported()) return { available: false, reason: 'browser' }; |
| 95 | if (!sandboxOrigin()) return { available: false, reason: 'site' }; |
| 96 | const m = await loadManifest(); |
| 97 | if (!m.enabled) return { available: false, reason: 'off' }; |
| 98 | let cached = false; |
| 99 | try { cached = localStorage.getItem(RUNTIME_KEY) === m.buildId; } catch { /* sin almacenamiento */ } |
| 100 | return { available: true, bytes: runtimeBytes(m), buildId: m.buildId, cached }; |
| 101 | } |