Elffuss BraidHub

utopia-ia/elffuss-code public

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