| 1 | // Protocolo entre la página de Code y el recinto de extensiones (PROTOCOL = 1). |
| 2 | // |
| 3 | // Todo lo que llega del recinto se valida aquí ANTES de tocar nada: tipo |
| 4 | // conocido, campos con su forma y tamaños con tope. Lo desconocido o mal |
| 5 | // formado se descarta y se cuenta; demasiadas faltas desmontan el recinto. |
| 6 | // Lo que la página manda al recinto tiene que ser «datos planos» (isPlainData): |
| 7 | // nunca un FileSystemHandle ni ningún otro objeto del navegador. |
| 8 | export const PROTOCOL = 1; |
| 9 | |
| 10 | export const LIMITS = { |
| 11 | message: 1 << 20, // 1 MB por mensaje (los documentos, aparte) |
| 12 | large: 16 << 20, // resultados y ediciones: pueden traer un documento entero (≤ 5 MB, ×2 al contar) |
| 13 | document: 64 << 20, |
| 14 | label: 4096, |
| 15 | markdown: 65536, |
| 16 | url: 8192, |
| 17 | completions: 5000, |
| 18 | symbols: 10000, |
| 19 | markers: 5000, |
| 20 | violations: 20, |
| 21 | }; |
| 22 | |
| 23 | export const KINDS = new Set(['format', 'formatRange', 'formatOnType', 'completion', 'hover', 'signature', 'codeAction', 'symbols', |
| 24 | 'definition', 'declaration', 'typeDefinition', 'implementation', 'references', 'rename', 'highlights']); |
| 25 | const STATES = new Set(['installed', 'activating', 'active', 'error', 'stopped', 'unsupported']); |
| 26 | const LEVELS = new Set(['info', 'warn', 'error']); |
| 27 | |
| 28 | const isStr = (v, max) => typeof v === 'string' && v.length <= max; |
| 29 | const optStr = (v, max) => v === undefined || v === null || isStr(v, max); |
| 30 | const isInt = v => Number.isSafeInteger(v); |
| 31 | const isPos = v => Number.isSafeInteger(v) && v >= 0; |
| 32 | export const isRange = r => Array.isArray(r) && r.length === 4 && r.every(n => Number.isSafeInteger(n) && n >= 1 && n <= 1e8); |
| 33 | export const isUri = u => isStr(u, LIMITS.url) && u.startsWith('file:///'); |
| 34 | const isExtId = v => isStr(v, 300) && /^[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9._-]*$/i.test(v); |
| 35 | export const isPlainObject = v => v !== null && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype; |
| 36 | |
| 37 | const isFilter = f => isPlainObject(f) && optStr(f.language, 100) && optStr(f.scheme, 50) && optStr(f.pattern, 500); |
| 38 | const SEVS = new Set(['info', 'warning', 'error']); |
| 39 | const isDecoKey = k => isStr(k, 100) && /^[\w.-]{1,100}$/.test(k); |
| 40 | const isHover = h => isPlainObject(h) && (h.md !== undefined ? isStr(h.md, 4096) && h.text === undefined : isStr(h.text, 4096)); |
| 41 | const isDecoRange = r => isPlainObject(r) && isRange(r.range) && (r.hover === undefined || (Array.isArray(r.hover) && r.hover.length <= 10 && r.hover.every(isHover))) |
| 42 | && (r.ro === undefined || isPlainObject(r.ro)); |
| 43 | const isPickItem = it => isPlainObject(it) && (it.sep !== undefined |
| 44 | ? isStr(it.sep, 200) && Object.keys(it).length === 1 |
| 45 | : isStr(it.label, 500) && optStr(it.description, 500) && optStr(it.detail, 1000) && (it.picked === undefined || typeof it.picked === 'boolean')); |
| 46 | const isEditStep = s => Array.isArray(s) && s.length <= 100000 && s.every(c => isPlainObject(c) && isRange(c.range) && typeof c.text === 'string'); |
| 47 | |
| 48 | // tamaño aproximado (para no aceptar mensajes enormes); corta al pasarse |
| 49 | export function approxSize(v, limit = Infinity) { |
| 50 | let n = 0; |
| 51 | const stack = [v]; |
| 52 | while (stack.length) { |
| 53 | const x = stack.pop(); |
| 54 | if (typeof x === 'string') n += x.length * 2; |
| 55 | else if (typeof x === 'number' || typeof x === 'boolean' || x == null) n += 8; |
| 56 | else if (x instanceof ArrayBuffer) n += x.byteLength; |
| 57 | else if (ArrayBuffer.isView(x)) n += x.byteLength; |
| 58 | else if (Array.isArray(x)) { n += 8; for (const y of x) stack.push(y); } |
| 59 | else if (typeof x === 'object') { for (const [k, y] of Object.entries(x)) { n += k.length * 2; stack.push(y); } } |
| 60 | if (n > limit) return n; |
| 61 | } |
| 62 | return n; |
| 63 | } |
| 64 | |
| 65 | // Mensajes del recinto → la página: cada tipo con su forma exacta. |
| 66 | const FROM_SANDBOX = { |
| 67 | ready: m => m.protocol === PROTOCOL && isStr(m.vscode, 32), |
| 68 | fatal: m => isStr(m.reason, 50) && optStr(m.text, 1000), |
| 69 | 'ext.status': m => isExtId(m.id) && STATES.has(m.state) && optStr(m.text, 4096), |
| 70 | log: m => LEVELS.has(m.level) && isStr(m.text, LIMITS.label) && (m.id === undefined || isExtId(m.id)), |
| 71 | 'providers.add': m => isInt(m.handle) && KINDS.has(m.kind) && Array.isArray(m.selector) && m.selector.length <= 50 && m.selector.every(isFilter) && isPlainObject(m.meta), |
| 72 | 'providers.remove': m => isInt(m.handle), |
| 73 | result: m => isInt(m.req) && typeof m.ok === 'boolean' && (m.ok || isStr(m.error, 1000)), |
| 74 | 'doc.edit': m => isUri(m.uri) && isInt(m.base) && Array.isArray(m.steps) && m.steps.length <= 1000 && m.steps.every(isEditStep), |
| 75 | 'doc.need': m => isUri(m.uri), |
| 76 | markers: m => isUri(m.uri) && isStr(m.owner, 200) && Array.isArray(m.markers) && m.markers.length <= LIMITS.markers, |
| 77 | 'ctx.set': m => isStr(m.key, 100) && /^[\w.:-]{1,100}$/.test(m.key) && (m.value === null || ['string', 'number', 'boolean'].includes(typeof m.value)) && (typeof m.value !== 'string' || m.value.length <= 1000), |
| 78 | pong: m => isInt(m.n), |
| 79 | 'rpc.denied': m => isPos(m.n) && Array.isArray(m.top) && m.top.length <= 10 |
| 80 | && m.top.every(x => Array.isArray(x) && x.length === 2 && isStr(x[0], 200) && isPos(x[1])), |
| 81 | // lo que la extensión le pide al usuario (la página contesta con ui.result) |
| 82 | 'ui.notify': m => isInt(m.req) && SEVS.has(m.sev) && isStr(m.text, 4096) && Array.isArray(m.actions) && m.actions.length <= 5 |
| 83 | && m.actions.every(a => isStr(a, 200)) && (m.source === undefined || isExtId(m.source)), |
| 84 | 'ui.dialog': m => isInt(m.req) && SEVS.has(m.sev) && isStr(m.text, 4096) && optStr(m.detail, 4096) && Array.isArray(m.buttons) |
| 85 | && m.buttons.length <= 10 && m.buttons.every(b => isStr(b, 200)) && optStr(m.cancel, 200), |
| 86 | 'ui.pick': m => isInt(m.req) && Array.isArray(m.items) && m.items.length <= 1000 && m.items.every(isPickItem) && isPlainObject(m.options) |
| 87 | && optStr(m.options.title, 200) && optStr(m.options.placeHolder, 200) && typeof m.options.canPickMany === 'boolean', |
| 88 | 'ui.input': m => isInt(m.req) && isPlainObject(m.options) && optStr(m.options.title, 200) && optStr(m.options.prompt, 1000) |
| 89 | && optStr(m.options.placeHolder, 200) && optStr(m.options.value, 10000) && optStr(m.options.validation, 500), |
| 90 | 'ui.cancel': m => isInt(m.req), |
| 91 | 'ui.progress': m => isInt(m.id) && isStr(m.text, 500) && typeof m.done === 'boolean', |
| 92 | 'clipboard.write': m => isStr(m.text, 500000), |
| 93 | 'open.request': m => isInt(m.req) && isStr(m.url, LIMITS.url) && m.url.length > 0, |
| 94 | 'editor.show': m => isUri(m.uri), |
| 95 | 'editor.reveal': m => isUri(m.uri) && isRange(m.range), |
| 96 | 'editor.selection': m => isUri(m.uri) && Array.isArray(m.selections) && m.selections.length >= 1 && m.selections.length <= 100 && m.selections.every(isRange), |
| 97 | // decoraciones: la página reconstruye el CSS con su lista blanca (decorations.js) |
| 98 | 'deco.type': m => isDecoKey(m.key) && isPlainObject(m.options) && approxSize(m.options, 40000) < 40000, |
| 99 | 'deco.set': m => isDecoKey(m.key) && isUri(m.uri) && Array.isArray(m.ranges) && m.ranges.length <= 10000 && m.ranges.every(isDecoRange), |
| 100 | 'deco.remove': m => isDecoKey(m.key), |
| 101 | }; |
| 102 | |
| 103 | // Tope por tipo: los resultados (p. ej. las ediciones de un formateador) y |
| 104 | // las ediciones de una extensión pueden traer un documento entero; el resto, 1 MB. |
| 105 | export const maxSize = t => (t === 'result' || t === 'doc.edit' ? LIMITS.large : LIMITS.message); |
| 106 | |
| 107 | export function validate(msg) { |
| 108 | if (!isPlainObject(msg) || typeof msg.t !== 'string') return { ok: false, why: 'shape' }; |
| 109 | const check = Object.hasOwn(FROM_SANDBOX, msg.t) ? FROM_SANDBOX[msg.t] : null; |
| 110 | if (!check) return { ok: false, why: 'unknown type' }; |
| 111 | const cap = maxSize(msg.t); |
| 112 | if (approxSize(msg, cap) > cap) return { ok: false, why: 'too large' }; |
| 113 | try { return check(msg) ? { ok: true } : { ok: false, why: 'fields' }; } |
| 114 | catch { return { ok: false, why: 'fields' }; } |
| 115 | } |
| 116 | |
| 117 | // Página → recinto: solo datos planos (y ArrayBuffer para los ficheros). |
| 118 | export function isPlainData(v, depth = 0) { |
| 119 | if (depth > 64) return false; |
| 120 | if (v === null || v === undefined || typeof v === 'boolean' || typeof v === 'string') return true; |
| 121 | if (typeof v === 'number') return Number.isFinite(v); |
| 122 | if (v instanceof ArrayBuffer) return true; |
| 123 | if (Array.isArray(v)) return v.every(x => isPlainData(x, depth + 1)); |
| 124 | if (isPlainObject(v)) return Object.values(v).every(x => isPlainData(x, depth + 1)); |
| 125 | return false; |
| 126 | } |
| 127 | |
| 128 | export { isStr, isInt, isPos }; |