File size: 8,236 Bytes
4bd8362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// Protocolo entre la página de Code y el recinto de extensiones (PROTOCOL = 1).
//
// Todo lo que llega del recinto se valida aquí ANTES de tocar nada: tipo
// conocido, campos con su forma y tamaños con tope. Lo desconocido o mal
// formado se descarta y se cuenta; demasiadas faltas desmontan el recinto.
// Lo que la página manda al recinto tiene que ser «datos planos» (isPlainData):
// nunca un FileSystemHandle ni ningún otro objeto del navegador.
export const PROTOCOL = 1;

export const LIMITS = {
  message: 1 << 20,          // 1 MB por mensaje (los documentos, aparte)
  large: 16 << 20,           // resultados y ediciones: pueden traer un documento entero (≤ 5 MB, ×2 al contar)
  document: 64 << 20,
  label: 4096,
  markdown: 65536,
  url: 8192,
  completions: 5000,
  symbols: 10000,
  markers: 5000,
  violations: 20,
};

export const KINDS = new Set(['format', 'formatRange', 'formatOnType', 'completion', 'hover', 'signature', 'codeAction', 'symbols',
  'definition', 'declaration', 'typeDefinition', 'implementation', 'references', 'rename', 'highlights']);
const STATES = new Set(['installed', 'activating', 'active', 'error', 'stopped', 'unsupported']);
const LEVELS = new Set(['info', 'warn', 'error']);

const isStr = (v, max) => typeof v === 'string' && v.length <= max;
const optStr = (v, max) => v === undefined || v === null || isStr(v, max);
const isInt = v => Number.isSafeInteger(v);
const isPos = v => Number.isSafeInteger(v) && v >= 0;
export const isRange = r => Array.isArray(r) && r.length === 4 && r.every(n => Number.isSafeInteger(n) && n >= 1 && n <= 1e8);
export const isUri = u => isStr(u, LIMITS.url) && u.startsWith('file:///');
const isExtId = v => isStr(v, 300) && /^[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9._-]*$/i.test(v);
export const isPlainObject = v => v !== null && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype;

const isFilter = f => isPlainObject(f) && optStr(f.language, 100) && optStr(f.scheme, 50) && optStr(f.pattern, 500);
const SEVS = new Set(['info', 'warning', 'error']);
const isDecoKey = k => isStr(k, 100) && /^[\w.-]{1,100}$/.test(k);
const isHover = h => isPlainObject(h) && (h.md !== undefined ? isStr(h.md, 4096) && h.text === undefined : isStr(h.text, 4096));
const isDecoRange = r => isPlainObject(r) && isRange(r.range) && (r.hover === undefined || (Array.isArray(r.hover) && r.hover.length <= 10 && r.hover.every(isHover)))
  && (r.ro === undefined || isPlainObject(r.ro));
const isPickItem = it => isPlainObject(it) && (it.sep !== undefined
  ? isStr(it.sep, 200) && Object.keys(it).length === 1
  : isStr(it.label, 500) && optStr(it.description, 500) && optStr(it.detail, 1000) && (it.picked === undefined || typeof it.picked === 'boolean'));
const isEditStep = s => Array.isArray(s) && s.length <= 100000 && s.every(c => isPlainObject(c) && isRange(c.range) && typeof c.text === 'string');

// tamaño aproximado (para no aceptar mensajes enormes); corta al pasarse
export function approxSize(v, limit = Infinity) {
  let n = 0;
  const stack = [v];
  while (stack.length) {
    const x = stack.pop();
    if (typeof x === 'string') n += x.length * 2;
    else if (typeof x === 'number' || typeof x === 'boolean' || x == null) n += 8;
    else if (x instanceof ArrayBuffer) n += x.byteLength;
    else if (ArrayBuffer.isView(x)) n += x.byteLength;
    else if (Array.isArray(x)) { n += 8; for (const y of x) stack.push(y); }
    else if (typeof x === 'object') { for (const [k, y] of Object.entries(x)) { n += k.length * 2; stack.push(y); } }
    if (n > limit) return n;
  }
  return n;
}

// Mensajes del recinto → la página: cada tipo con su forma exacta.
const FROM_SANDBOX = {
  ready: m => m.protocol === PROTOCOL && isStr(m.vscode, 32),
  fatal: m => isStr(m.reason, 50) && optStr(m.text, 1000),
  'ext.status': m => isExtId(m.id) && STATES.has(m.state) && optStr(m.text, 4096),
  log: m => LEVELS.has(m.level) && isStr(m.text, LIMITS.label) && (m.id === undefined || isExtId(m.id)),
  '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),
  'providers.remove': m => isInt(m.handle),
  result: m => isInt(m.req) && typeof m.ok === 'boolean' && (m.ok || isStr(m.error, 1000)),
  'doc.edit': m => isUri(m.uri) && isInt(m.base) && Array.isArray(m.steps) && m.steps.length <= 1000 && m.steps.every(isEditStep),
  'doc.need': m => isUri(m.uri),
  markers: m => isUri(m.uri) && isStr(m.owner, 200) && Array.isArray(m.markers) && m.markers.length <= LIMITS.markers,
  '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),
  pong: m => isInt(m.n),
  'rpc.denied': m => isPos(m.n) && Array.isArray(m.top) && m.top.length <= 10
    && m.top.every(x => Array.isArray(x) && x.length === 2 && isStr(x[0], 200) && isPos(x[1])),
  // lo que la extensión le pide al usuario (la página contesta con ui.result)
  'ui.notify': m => isInt(m.req) && SEVS.has(m.sev) && isStr(m.text, 4096) && Array.isArray(m.actions) && m.actions.length <= 5
    && m.actions.every(a => isStr(a, 200)) && (m.source === undefined || isExtId(m.source)),
  'ui.dialog': m => isInt(m.req) && SEVS.has(m.sev) && isStr(m.text, 4096) && optStr(m.detail, 4096) && Array.isArray(m.buttons)
    && m.buttons.length <= 10 && m.buttons.every(b => isStr(b, 200)) && optStr(m.cancel, 200),
  'ui.pick': m => isInt(m.req) && Array.isArray(m.items) && m.items.length <= 1000 && m.items.every(isPickItem) && isPlainObject(m.options)
    && optStr(m.options.title, 200) && optStr(m.options.placeHolder, 200) && typeof m.options.canPickMany === 'boolean',
  'ui.input': m => isInt(m.req) && isPlainObject(m.options) && optStr(m.options.title, 200) && optStr(m.options.prompt, 1000)
    && optStr(m.options.placeHolder, 200) && optStr(m.options.value, 10000) && optStr(m.options.validation, 500),
  'ui.cancel': m => isInt(m.req),
  'ui.progress': m => isInt(m.id) && isStr(m.text, 500) && typeof m.done === 'boolean',
  'clipboard.write': m => isStr(m.text, 500000),
  'open.request': m => isInt(m.req) && isStr(m.url, LIMITS.url) && m.url.length > 0,
  'editor.show': m => isUri(m.uri),
  'editor.reveal': m => isUri(m.uri) && isRange(m.range),
  'editor.selection': m => isUri(m.uri) && Array.isArray(m.selections) && m.selections.length >= 1 && m.selections.length <= 100 && m.selections.every(isRange),
  // decoraciones: la página reconstruye el CSS con su lista blanca (decorations.js)
  'deco.type': m => isDecoKey(m.key) && isPlainObject(m.options) && approxSize(m.options, 40000) < 40000,
  'deco.set': m => isDecoKey(m.key) && isUri(m.uri) && Array.isArray(m.ranges) && m.ranges.length <= 10000 && m.ranges.every(isDecoRange),
  'deco.remove': m => isDecoKey(m.key),
};

// Tope por tipo: los resultados (p. ej. las ediciones de un formateador) y
// las ediciones de una extensión pueden traer un documento entero; el resto, 1 MB.
export const maxSize = t => (t === 'result' || t === 'doc.edit' ? LIMITS.large : LIMITS.message);

export function validate(msg) {
  if (!isPlainObject(msg) || typeof msg.t !== 'string') return { ok: false, why: 'shape' };
  const check = Object.hasOwn(FROM_SANDBOX, msg.t) ? FROM_SANDBOX[msg.t] : null;
  if (!check) return { ok: false, why: 'unknown type' };
  const cap = maxSize(msg.t);
  if (approxSize(msg, cap) > cap) return { ok: false, why: 'too large' };
  try { return check(msg) ? { ok: true } : { ok: false, why: 'fields' }; }
  catch { return { ok: false, why: 'fields' }; }
}

// Página → recinto: solo datos planos (y ArrayBuffer para los ficheros).
export function isPlainData(v, depth = 0) {
  if (depth > 64) return false;
  if (v === null || v === undefined || typeof v === 'boolean' || typeof v === 'string') return true;
  if (typeof v === 'number') return Number.isFinite(v);
  if (v instanceof ArrayBuffer) return true;
  if (Array.isArray(v)) return v.every(x => isPlainData(x, depth + 1));
  if (isPlainObject(v)) return Object.values(v).every(x => isPlainData(x, depth + 1));
  return false;
}

export { isStr, isInt, isPos };