Elffuss BraidHub

utopia-ia/elffuss-code public

main · 13.0 KiBRawPermalink
1// Puertas de Code ante lo que sale de una extensión con código.
2//
3// · Abrir una dirección externa (open.request del recinto, y Cmd+clic en un
4// enlace del editor mientras corren extensiones): un diálogo enseña la
5// dirección ENTERA, con los caracteres de control y bidi visibles, el host
6// en Unicode y en punycode si difieren y el sitio aparte. Cancelar es lo
7// que hay por defecto; solo http, https y mailto se pueden abrir, y solo
8// con window.open(…, 'noopener,noreferrer'). Uno a la vez.
9// · Vista previa HTML de un fichero que una extensión tocó (su texto entró
10// en el documento): la vista previa ejecuta scripts con red e incrusta
11// ficheros del proyecto, así que se pregunta antes.
12// · El agente, mientras corren extensiones: sus peticiones web y los
13// runtimes del Bridge preguntan antes, con la URL o la orden entera, para
14// que un texto escrito por una extensión no pueda sacar datos por él.
15import { modal, userActive } from './ui.js';
16import { tx } from '../ext/i18n.js';
17import './strings.js';
18import * as db from '../db.js';
19
20const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
21
22// ── direcciones: lo invisible, visible ──
23// Controles C0/C1, marcas bidi y de ancho cero, separadores de línea y BOM.
24// (rangos de puntos de código, sin escribir los caracteres: algunos ni se ven)
25const INVISIBLE = [[0x0, 0x1F], [0x7F, 0x9F], [0xAD, 0xAD], [0x61C, 0x61C], [0x115F, 0x1160], [0x17B4, 0x17B5], [0x180E, 0x180E], [0x200B, 0x200F],
26 [0x2028, 0x202E], [0x2060, 0x206F], [0x3164, 0x3164], [0xFE00, 0xFE0F], [0xFEFF, 0xFEFF], [0xFFA0, 0xFFA0], [0xFFF9, 0xFFFB], [0xE0000, 0xE007F]];
27const invisible = cp => INVISIBLE.some(([a, b]) => cp >= a && cp <= b);
28const hex = c => '<U+' + c.codePointAt(0).toString(16).toUpperCase().padStart(4, '0') + '>';
29export function visibleParts(s) {
30 const out = [];
31 let txt = '';
32 for (const ch of String(s)) {
33 if (invisible(ch.codePointAt(0))) { if (txt) { out.push({ t: txt }); txt = ''; } out.push({ cc: hex(ch) }); }
34 else txt += ch;
35 }
36 if (txt) out.push({ t: txt });
37 return out;
38}
39export const visibleText = s => visibleParts(s).map(p => p.t ?? p.cc).join('');
40
41// punycode (RFC 3492): solo decodificar, para enseñar el host en Unicode
42function punyDecode(input) {
43 const base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700;
44 let n = 128, i = 0, bias = 72;
45 const out = [];
46 let b = input.lastIndexOf('-');
47 if (b < 0) b = 0;
48 for (let j = 0; j < b; j++) { if (input.charCodeAt(j) >= 0x80) return null; out.push(input.charCodeAt(j)); }
49 const digit = c => (c >= 48 && c <= 57 ? c - 22 : c >= 65 && c <= 90 ? c - 65 : c >= 97 && c <= 122 ? c - 97 : base);
50 const adapt = (delta, num, first) => {
51 let k = 0;
52 delta = first ? Math.floor(delta / damp) : delta >> 1;
53 delta += Math.floor(delta / num);
54 for (; delta > ((base - tMin) * tMax) >> 1; k += base) delta = Math.floor(delta / (base - tMin));
55 return Math.floor(k + (base - tMin + 1) * delta / (delta + skew));
56 };
57 for (let idx = b > 0 ? b + 1 : 0; idx < input.length;) {
58 const oldi = i;
59 for (let w = 1, k = base; ; k += base) {
60 if (idx >= input.length) return null;
61 const d = digit(input.charCodeAt(idx++));
62 if (d >= base) return null;
63 i += d * w;
64 const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
65 if (d < t) break;
66 w *= base - t;
67 if (w > 1e9) return null;
68 }
69 bias = adapt(i - oldi, out.length + 1, oldi === 0);
70 n += Math.floor(i / (out.length + 1));
71 i %= out.length + 1;
72 if (n > 0x10FFFF) return null;
73 out.splice(i++, 0, n);
74 }
75 try { return String.fromCodePoint(...out); } catch { return null; }
76}
77export function unicodeHost(host) {
78 return String(host).split('.').map(l => {
79 if (!/^xn--/i.test(l)) return l;
80 const d = punyDecode(l.slice(4).toLowerCase());
81 return d == null ? l : d;
82 }).join('.');
83}
84
85// Lo que el diálogo enseña de una dirección. `href` es lo que se abriría: la
86// dirección ya normalizada por el navegador, que es exactamente lo que llega.
87export function describeUrl(s) {
88 let u;
89 try { u = new URL(String(s)); } catch { return { ok: false, href: String(s), scheme: '', openable: false }; }
90 const scheme = u.protocol.replace(/:$/, '').toLowerCase();
91 const openable = scheme === 'http' || scheme === 'https' || scheme === 'mailto';
92 const host = u.hostname;
93 const uni = host ? unicodeHost(host) : '';
94 let site = host;
95 if (scheme === 'mailto') {
96 let path = u.pathname;
97 try { path = decodeURIComponent(path); } catch { /* codificación rota: tal cual */ }
98 site = (/@([^?&#]+)/.exec(path) || [])[1] || '';
99 }
100 return { ok: true, href: u.href, scheme, openable, host, hostUnicode: uni !== host ? uni : null, site, original: String(s) };
101}
102
103// «Sitio: ejemplo.org» (en Unicode, y en punycode si difiere)
104function siteLine(info, cls) {
105 const site = el('p', cls, tx('x2OpenSite') + ' ');
106 site.appendChild(el('b', null, visibleText(info.hostUnicode || info.site)));
107 if (info.hostUnicode) site.appendChild(document.createTextNode(' ' + tx('x2OpenPuny', { host: info.host })));
108 return site;
109}
110
111function addressBox(href) {
112 const box = el('div', 'x2-code x2-address');
113 for (const p of visibleParts(href)) {
114 if (p.t !== undefined) box.appendChild(document.createTextNode(p.t));
115 else box.appendChild(el('span', 'x2-cc', p.cc));
116 }
117 return box;
118}
119
120// ── abrir una dirección ──
121export class OpenGate {
122 constructor({ log = () => {}, opener = (url) => window.open(url, '_blank', 'noopener,noreferrer'), onDropped = () => {}, onChange = () => {} } = {}) {
123 this.log = log;
124 this.opener = opener;
125 this.onDropped = onDropped; // una petición bloqueada: se dice (barra de estado)
126 this.onChange = onChange; // bloqueado o no (el panel lo enseña)
127 this.busy = false;
128 this.blocked = false;
129 this.dropped = 0;
130 this.opened = 0;
131 this.shown = []; // lo que enseñó el diálogo (para las pruebas y el registro)
132 }
133
134 // «Bloquear» es para lo que piden las extensiones: un enlace que el propio
135 // usuario abre con Cmd+clic en el editor sigue preguntando.
136 unblock() { if (this.blocked) { this.blocked = false; this.log('info', 'address requests from extensions are allowed to ask again'); this.onChange(); } }
137
138 async request(url, { fromEditor = false } = {}) {
139 if (this.blocked && !fromEditor) {
140 this.dropped++;
141 this.log('warn', 'an address was not opened: requests are blocked for this session');
142 this.onDropped(this.dropped);
143 return false;
144 }
145 if (this.busy) { this.dropped++; this.log('warn', 'an address was not opened: another one is waiting for an answer'); return false; }
146 const info = describeUrl(url);
147 const clicked = userActive();
148 this.busy = true;
149 this.shown.push({ href: info.href, original: info.original, clicked });
150 if (this.shown.length > 50) this.shown.shift();
151 try {
152 const body = [el('p', 'x2-modal-text', fromEditor ? tx('x2OpenBodyLink') : tx('x2OpenBody'))];
153 if (info.ok && info.site) body.push(siteLine(info, 'x2-site'));
154 if (!clicked) body.push(el('p', 'x2-note', tx('x2OpenNoClick')));
155 if (!info.ok) body.push(el('p', 'x2-note', tx('x2OpenInvalid')));
156 else if (!info.openable) body.push(el('p', 'x2-note', tx('x2OpenScheme', { scheme: info.scheme })));
157 const buttons = [
158 { label: tx('x2Cancel'), value: 'cancel' },
159 { label: tx('x2OpenCopy'), value: 'copy', onClick: async b => { try { await navigator.clipboard.writeText(info.href); b.textContent = tx('x2OpenCopied'); } catch { b.textContent = tx('x2OpenCopyFailed'); } return true; } },
160 ];
161 if (info.ok && info.openable) buttons.push({ label: tx('x2OpenOpen'), value: 'open', primary: true });
162 // (un enlace del propio usuario no se bloquea: ese botón es para las extensiones)
163 if (!fromEditor) buttons.push({ label: tx('x2OpenBlock'), value: 'block', className: 'x2-block' });
164 // en un teléfono la dirección larga no empuja el título ni el sitio fuera
165 // de la vista: tiene su propio scroll, y el sitio se repite junto a los botones
166 const after = info.ok && info.site ? [siteLine(info, 'x2-site x2-site-again')] : [];
167 const v = await modal({ id: 'x2-open', title: tx('x2OpenTitle'), body, code: addressBox(info.href), after, buttons, cancelValue: 'cancel', focus: 0 });
168 if (v === 'block') { this.blocked = true; this.log('info', 'address requests from extensions are blocked for this session'); this.onChange(); return false; }
169 if (v !== 'open' || !info.openable) return false;
170 this.opener(info.href);
171 this.opened++;
172 return true;
173 } finally { this.busy = false; }
174 }
175}
176
177// ── vista previa de un fichero que tocó una extensión ──
178const TOUCHED = 'x2.touched';
179let marcas = null, guardando = null;
180async function leeMarcas() {
181 if (!marcas) { try { marcas = (await db.get('kv', TOUCHED)) || {}; } catch { marcas = {}; } }
182 return marcas;
183}
184function guarda() {
185 guardando ??= Promise.resolve().then(async () => { guardando = null; try { await db.set('kv', TOUCHED, { ...marcas }); } catch { /* sin almacenamiento */ } });
186 return guardando;
187}
188export async function markTouched(path) {
189 if (typeof path !== 'string' || !path) return;
190 const m = await leeMarcas();
191 if (m[path]) return;
192 m[path] = true;
193 await guarda();
194}
195export async function isTouched(path) { return !!(await leeMarcas())[path]; }
196// «Previsualizar igualmente»: la marca se va hasta la próxima edición de una extensión
197export async function clearTouched(path) {
198 const m = await leeMarcas();
199 if (!m[path]) return;
200 delete m[path];
201 await guarda();
202}
203
204let previewOpen = null;
205export function previewDialog(path) {
206 previewOpen ??= (async () => {
207 try {
208 const v = await modal({
209 id: 'x2-preview', title: tx('x2PreviewTitle'),
210 body: [tx('x2PreviewBody')], code: path,
211 buttons: [{ label: tx('x2Cancel'), value: false }, { label: tx('x2PreviewAnyway'), value: true, primary: true }],
212 cancelValue: false, focus: 0,
213 });
214 if (v === true) { await clearTouched(path); return true; }
215 return false;
216 } finally { previewOpen = null; }
217 })();
218 return previewOpen;
219}
220// El guardián que pone host.js: sin marca no carga nada más; con marca pregunta.
221export async function allowPreview(path) {
222 if (!(await isTouched(path))) return true;
223 return previewDialog(path);
224}
225
226// ── el agente, mientras corren extensiones ──
227export const RUNTIMES = new Set(['node', 'npm', 'npx', 'python', 'python3', 'pip', 'yarn', 'pnpm', 'bun', 'deno', 'cargo', 'go']);
228export const AGENT_DENIED = 'The user did not allow this request.';
229// Primera palabra de cada orden de la línea (&&, ;, |), como la parte shell.js
230export function commandHeads(line) {
231 const heads = [];
232 let cur = '', q = '';
233 const flush = () => { const t = cur.trim().split(/\s+/)[0]; if (t) heads.push(t.replace(/^["']|["']$/g, '')); cur = ''; };
234 const s = String(line);
235 for (let i = 0; i < s.length; i++) {
236 const ch = s[i];
237 if (q) { cur += ch; if (ch === q) q = ''; continue; }
238 if (ch === '"' || ch === "'") { q = ch; cur += ch; continue; }
239 if (ch === ';' || ch === '|' || (ch === '&' && s[i + 1] === '&')) { flush(); if (ch === '&' || (ch === '|' && s[i + 1] === '|')) i++; continue; }
240 cur += ch;
241 }
242 flush();
243 return heads;
244}
245export const runsRuntime = line => commandHeads(line).some(h => RUNTIMES.has(h));
246export const searchUrls = q => ['https://html.duckduckgo.com/html/?q=', 'https://lite.duckduckgo.com/lite/?q='].map(e => e + encodeURIComponent(String(q ?? '')));
247
248async function agentAsk(kind, lines) {
249 const v = await modal({
250 id: 'x2-agent', title: tx(kind === 'run' ? 'x2AgentRunTitle' : 'x2AgentWebTitle'),
251 body: [tx('x2AgentBody')],
252 code: lines.join('\n'),
253 buttons: [{ label: tx('x2AgentDeny'), value: false }, { label: tx('x2AgentAllow'), value: true, primary: true }],
254 cancelValue: false, focus: 0,
255 });
256 return v === true;
257}
258
259// Envuelve web.fetch, web.search y terminal.run (solo si lanza un runtime
260// del Bridge). Devuelve la función que lo deja todo como estaba.
261export function installAgentGate(tools, { ask = agentAsk, log = () => {} } = {}) {
262 const orig = {};
263 const wrap = (name, fn) => {
264 const t = tools[name];
265 if (!t || typeof t.run !== 'function') return;
266 orig[name] = t.run;
267 t.run = async a => fn(a || {}, orig[name]);
268 };
269 const deny = what => { log('info', 'the user did not allow ' + what); return AGENT_DENIED; };
270 wrap('web.fetch', async (a, run) => ((await ask('web', [String(a.url ?? '')])) ? run(a) : deny('a web request')));
271 wrap('web.search', async (a, run) => ((await ask('web', searchUrls(a.query))) ? run(a) : deny('a web search')));
272 wrap('terminal.run', async (a, run) => (!runsRuntime(a.command) || (await ask('run', [String(a.command ?? '')])) ? run(a) : deny('a local runtime')));
273 return () => { for (const [name, fn] of Object.entries(orig)) if (tools[name]) tools[name].run = fn; };
274}