Elffuss BraidHub

utopia-ia/elffuss-code public

main · 10.2 KiBRawPermalink
1#!/usr/bin/env node
2// Headers of the two sandbox documents, generated from headers.json (the only
3// source). Used by the test server (tests/lib/x2-server.mjs), by the unit
4// tests, and to print the nginx snippets for production.
5//
6// node sandbox/x2/headers.mjs --check
7// the documents' inline scripts match their pinned hashes, the meta CSPs
8// match headers.json, no fetch directive names a host, and (when the
9// vendor build folder is installed) exthost-iframe.html equals the
10// library's copy apart from its CSP meta
11// node sandbox/x2/headers.mjs --pin
12// recompute sandbox.html's bootstrap hash and write it to headers.json
13// and to the document's meta CSP
14// node sandbox/x2/headers.mjs --nginx [--sandbox https://x2.<domain>]
15// print snippets/x2-sandbox.conf and snippets/x2-exthost.conf for the
16// production sandbox of headers.json (https://x2.utopiaia.com), or for
17// the one given (refused when it is not the one headers.json and
18// config.js name, or is the same site as Code)
19// node sandbox/x2/headers.mjs --site-check [https://x2.<domain>]
20// that sandbox origin (by default headers.json's) is another registrable
21// domain than every Code origin, and both headers.json and
22// web/js/ext2/config.js name it (deploy-sandbox.sh)
23import fs from 'node:fs';
24import path from 'node:path';
25import crypto from 'node:crypto';
26import { fileURLToPath } from 'node:url';
27
28const HERE = path.dirname(fileURLToPath(import.meta.url));
29const REPO = path.resolve(HERE, '../..');
30export const DOCS_DIR = path.join(HERE, 'v1');
31// fetch directives: none of them may carry a host or a scheme that reaches one
32const FETCH_DIRECTIVES = ['default-src', 'script-src', 'worker-src', 'child-src', 'connect-src', 'img-src', 'font-src', 'style-src', 'media-src', 'object-src', 'manifest-src'];
33const ALLOWED_SOURCES = new Set(["'none'", "'self'", 'blob:', 'data:', "'unsafe-inline'", "'unsafe-eval'", "'wasm-unsafe-eval'"]);
34
35export function loadSpec() {
36 return JSON.parse(fs.readFileSync(path.join(HERE, 'headers.json'), 'utf8'));
37}
38
39export const inlineScripts = html => [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m => m[1]);
40export const sha256Source = text => "'sha256-" + crypto.createHash('sha256').update(text, 'utf8').digest('base64') + "'";
41
42const fill = (s, vars) => s.replace(/\{(sandbox|code|self-script|sandbox-uri)\}/g, (_, k) => vars[k]);
43
44function vars(doc, { sandbox, code }) {
45 if (!sandbox) throw new Error('the sandbox origin is not set');
46 return {
47 sandbox,
48 code: code.join(' '),
49 'self-script': "'" + doc.inlineScript + "'",
50 'sandbox-uri': encodeURIComponent(sandbox).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
51 };
52}
53
54export function cspFor(name, origins, { meta = false } = {}) {
55 const spec = loadSpec();
56 const doc = spec.documents[name];
57 const v = vars(doc, origins);
58 return doc.csp
59 .filter(d => !(meta && d.startsWith('frame-ancestors')))
60 .map(d => (meta && d.startsWith('frame-src') && doc.metaFrameSrc ? 'frame-src ' + doc.metaFrameSrc : fill(d, v)))
61 .join('; ');
62}
63
64export function headersFor(name, origins, { insecure = false } = {}) {
65 const spec = loadSpec();
66 const h = { ...spec.common };
67 if (!insecure) h['Content-Security-Policy'] = cspFor(name, origins);
68 return h;
69}
70
71export function queryAllowed(name, search, origins) {
72 const spec = loadSpec();
73 const doc = spec.documents[name];
74 const q = search.startsWith('?') ? search.slice(1) : search;
75 return new RegExp(fill(doc.query, vars(doc, origins))).test(q);
76}
77
78export function originsFor(env, { port, sandbox } = {}) {
79 const e = loadSpec().environments[env];
80 if (!e) throw new Error('unknown environment ' + env);
81 const p = s => s && s.replace('{port}', String(port));
82 return { code: e.code.map(p), sandbox: sandbox || p(e.sandbox) };
83}
84
85// The meta CSP each document must carry: the header policy without
86// frame-ancestors (a meta tag cannot carry it), with frame-src 'self' where
87// the header names the exact document of the sandbox origin.
88export function expectedMeta(name) {
89 return cspFor(name, { sandbox: 'https://sandbox.invalid', code: ['https://code.invalid'] }, { meta: true });
90}
91export const metaOf = html => /<meta http-equiv="Content-Security-Policy" content="([^"]*)"/.exec(html)?.[1] ?? null;
92
93export function check() {
94 const spec = loadSpec();
95 const problems = [];
96 for (const [name, doc] of Object.entries(spec.documents)) {
97 const html = fs.readFileSync(path.join(DOCS_DIR, name), 'utf8');
98 const scripts = inlineScripts(html);
99 if (scripts.length !== 1) problems.push(`${name}: expected exactly one inline script, found ${scripts.length}`);
100 else if (sha256Source(scripts[0]) !== "'" + doc.inlineScript + "'") problems.push(`${name}: inline script hash ${sha256Source(scripts[0])} is not the pinned ${doc.inlineScript}`);
101 if (/<script[^>]+src=/i.test(html)) problems.push(`${name}: loads a script by URL`);
102 if (metaOf(html) !== expectedMeta(name)) problems.push(`${name}: meta CSP differs from headers.json`);
103 for (const d of doc.csp) {
104 const [dir, ...srcs] = d.split(/\s+/);
105 if (!FETCH_DIRECTIVES.includes(dir)) continue;
106 for (const s of srcs) if (!ALLOWED_SOURCES.has(s) && !s.startsWith('{self-script}')) problems.push(`${name}: ${dir} names ${s}`);
107 }
108 }
109 // exthost-iframe.html = the library's document apart from the CSP meta
110 const lib = path.join(REPO, 'vendor/vscode-ext2/node_modules', spec.documents['exthost-iframe.html'].library);
111 if (fs.existsSync(lib)) {
112 const strip = h => h.replace(/<meta http-equiv="Content-Security-Policy" content="[^"]*"\/?>/, '<meta CSP>');
113 const ours = fs.readFileSync(path.join(DOCS_DIR, 'exthost-iframe.html'), 'utf8');
114 if (strip(ours) !== strip(fs.readFileSync(lib, 'utf8'))) problems.push('exthost-iframe.html: differs from the library copy beyond the CSP meta');
115 }
116 return problems;
117}
118
119function pin() {
120 const spec = loadSpec();
121 const file = path.join(DOCS_DIR, 'sandbox.html');
122 let html = fs.readFileSync(file, 'utf8');
123 const [script] = inlineScripts(html);
124 spec.documents['sandbox.html'].inlineScript = sha256Source(script).slice(1, -1);
125 fs.writeFileSync(path.join(HERE, 'headers.json'), JSON.stringify(spec, null, 2) + '\n');
126 html = html.replace(/(<meta http-equiv="Content-Security-Policy" content=")[^"]*(")/, `$1${expectedMeta('sandbox.html')}$2`);
127 fs.writeFileSync(file, html);
128 console.log('pinned ' + spec.documents['sandbox.html'].inlineScript);
129}
130
131// The nginx snippets. Content-Type comes from nginx's own mime types (the
132// documents are .html): `charset utf-8;` adds "; charset=utf-8" to it, as
133// headers.json asks. (`default_type` would only apply to unknown extensions.)
134export function nginx(sandbox) {
135 const spec = loadSpec();
136 const code = spec.environments.production.code;
137 const out = [];
138 for (const [name, file] of [['sandbox.html', 'x2-sandbox.conf'], ['exthost-iframe.html', 'x2-exthost.conf']]) {
139 out.push(`# snippets/${file} (generated by sandbox/x2/headers.mjs from headers.json)`);
140 for (const [k, v] of Object.entries(headersFor(name, { sandbox, code }))) {
141 if (k === 'Content-Type') {
142 if (!/^text\/html; charset=utf-8$/i.test(v)) throw new Error('headers.json: Content-Type must be text/html; charset=utf-8');
143 out.push('charset utf-8;');
144 } else out.push(`add_header ${k} "${v.replace(/"/g, '\\"')}" always;`);
145 }
146 out.push('');
147 }
148 return out.join('\n');
149}
150
151// The sandbox must be ANOTHER SITE than every Code origin (another
152// registrable domain), or it would share cookies and a process with Code.
153// web/js/ext2/config.js refuses a same-site sandbox at run time; this refuses
154// it before anything is deployed.
155export const productionSandbox = () => loadSpec().environments.production.sandbox || null;
156
157export async function siteProblems(sandbox) {
158 const { sameSite, sandboxOrigin } = await import('../../web/js/ext2/config.js');
159 const problems = [];
160 let u;
161 try { u = new URL(sandbox); } catch { return ['not a URL: ' + sandbox]; }
162 if (u.protocol !== 'https:' || u.origin !== sandbox.replace(/\/$/, '')) problems.push('the sandbox origin must be https://host, with nothing after it: ' + sandbox);
163 const named = productionSandbox();
164 if (named !== u.origin) problems.push(`sandbox/x2/headers.json names ${named || 'no sandbox'} for production, not ${u.origin}`);
165 for (const code of loadSpec().environments.production.code) {
166 if (sameSite(code, u.origin)) problems.push(`${u.origin} is the same site as ${code}: use another registrable domain`);
167 const c = new URL(code);
168 const configured = sandboxOrigin({ hostname: c.hostname, origin: c.origin, port: c.port });
169 if (configured !== u.origin) problems.push(`web/js/ext2/config.js names ${configured || 'no sandbox'} for ${c.hostname}, not ${u.origin}`);
170 }
171 return problems;
172}
173
174if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
175 const args = process.argv.slice(2);
176 if (args.includes('--pin')) pin();
177 // the origin after a flag, or headers.json's production sandbox when none is given
178 const after = flag => { const v = args[args.indexOf(flag) + 1]; return v && !v.startsWith('--') ? v : null; };
179 if (args.includes('--site-check')) {
180 const s = after('--site-check') || productionSandbox() || '';
181 const problems = await siteProblems(s);
182 for (const p of problems) console.error(' ✗ ' + p);
183 console.log(problems.length ? `${problems.length} problems` : `${s} is another site than Code`);
184 process.exit(problems.length ? 1 : 0);
185 }
186 if (args.includes('--nginx')) {
187 const s = (args.includes('--sandbox') ? after('--sandbox') : productionSandbox()) || '';
188 if (!/^https:\/\/[a-z0-9.-]+$/.test(s)) { console.error('--nginx needs a sandbox origin https://x2.<domain> (headers.json or --sandbox)'); process.exit(2); }
189 const problems = await siteProblems(s);
190 if (problems.length) { for (const p of problems) console.error(' ✗ ' + p); process.exit(1); }
191 process.stdout.write(nginx(s));
192 }
193 if (args.includes('--check') || !args.length) {
194 const problems = check();
195 for (const p of problems) console.error(' ✗ ' + p);
196 console.log(problems.length ? `${problems.length} problems` : 'sandbox documents match headers.json');
197 process.exit(problems.length ? 1 : 0);
198 }
199}