Elffuss BraidHub

utopia-ia/elffuss-code public

main · 8.6 KiBRawPermalink
1// Test server for level 2: ONE loopback server, routed by the Host header.
2//
3// 127.0.0.1:<port> Code: web/ with server/serve.py's semantics (static files
4// with no-store, /v1 forwarding, /proxy), plus the vendor
5// bundle under /vendor/x2/ with its production headers
6// localhost:<port> the sandbox site: only its two documents, with the
7// headers from sandbox/x2/headers.json and only for the
8// exact query shape; 404 for anything else, no log
9//
10// The two hosts are different sites, as Code and the sandbox are in
11// production. Test-only switches, as positive controls:
12// insecure: 'exthost' (X2_INSECURE=1 or =exthost) serves the extension-host
13// document without its CSP, so extension code CAN reach the network: the
14// canary must then hit the beacon; 'all' (X2_INSECURE=all) drops the CSP of
15// both documents, and the sandbox's own self-test must refuse to start;
16// tamper (X2_TAMPER=1) flips one byte in the middle of sandbox-main.js.gz.
17//
18// node tests/lib/x2-server.mjs [--port N] serve until killed
19// import { startServer } from './lib/x2-server.mjs'
20import http from 'node:http';
21import fs from 'node:fs';
22import path from 'node:path';
23import { fileURLToPath } from 'node:url';
24import { headersFor, queryAllowed, originsFor, loadSpec, DOCS_DIR } from '../../sandbox/x2/headers.mjs';
25
26const HERE = path.dirname(fileURLToPath(import.meta.url));
27const REPO = path.resolve(HERE, '../..');
28const MAX_PROXY_BYTES = 2_000_000;
29const LM_UPSTREAM = process.env.ELFFUSS_LM || 'https://elffuss.com';
30
31const TYPES = {
32 '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
33 '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
34 '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon',
35 '.wasm': 'application/wasm', '.txt': 'text/plain; charset=utf-8', '.md': 'text/markdown; charset=utf-8',
36 '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.mp4': 'video/mp4', '.webm': 'video/webm',
37 '.webmanifest': 'application/manifest+json', '.map': 'application/json', '.gz': 'application/octet-stream',
38};
39
40function safeJoin(root, urlPath) {
41 let p;
42 try { p = decodeURIComponent(urlPath); } catch { return null; }
43 const full = path.resolve(root, '.' + path.posix.normalize('/' + p));
44 return full === root || full.startsWith(root + path.sep) ? full : null;
45}
46
47const envInsecure = () => { const v = process.env.X2_INSECURE; return v === 'all' ? 'all' : v === '1' || v === 'exthost' ? 'exthost' : false; };
48
49// codeAliases: other host names that also get Code (with the browser told to
50// resolve them to 127.0.0.1), to see Code on a host config.js gives no sandbox.
51export async function startServer({ port = 0, webRoot = path.join(REPO, 'web'), insecure = envInsecure(), tamper = process.env.X2_TAMPER === '1', quiet = true, codeAliases = [] } = {}) {
52 const requests = []; // { host, method, url }
53 let codeHost = null, sandboxHost = null, origins = null;
54
55 function sendFile(res, file, extraHeaders = {}) {
56 let st;
57 try { st = fs.statSync(file); } catch { return notFound(res); }
58 if (st.isDirectory()) return sendFile(res, path.join(file, 'index.html'), extraHeaders);
59 let body = fs.readFileSync(file);
60 if (tamper && file.includes(path.sep + 'vendor' + path.sep + 'x2' + path.sep) && path.basename(file) === 'sandbox-main.js.gz') {
61 body = Buffer.from(body);
62 body[body.length >> 1] ^= 0xff;
63 }
64 res.writeHead(200, { 'Content-Type': TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream', 'Content-Length': body.length, ...extraHeaders });
65 res.end(body);
66 }
67 const notFound = res => { res.writeHead(404, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' }); res.end('not found'); };
68
69 async function proxy(req, res, u) {
70 const target = u.searchParams.get('url');
71 if (!target || !/^https?:\/\//.test(target)) { res.writeHead(400); return res.end('url invalida'); }
72 try {
73 const r = await fetch(target, { headers: { 'User-Agent': 'Mozilla/5.0 (Elffuss Code)' }, signal: AbortSignal.timeout(20000) });
74 const reader = r.body.getReader();
75 const chunks = []; let n = 0;
76 while (n < MAX_PROXY_BYTES) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); n += value.length; }
77 reader.cancel().catch(() => {});
78 const body = Buffer.concat(chunks).subarray(0, MAX_PROXY_BYTES);
79 res.writeHead(200, { 'Content-Type': r.headers.get('content-type') || 'text/html', 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' });
80 res.end(body);
81 } catch (e) { res.writeHead(502); res.end('proxy: ' + (e?.message || e)); }
82 }
83
84 async function forwardLm(req, res) {
85 const body = await new Promise(r => { const c = []; req.on('data', d => c.push(d)); req.on('end', () => r(Buffer.concat(c))); });
86 try {
87 const r = await fetch(LM_UPSTREAM + req.url, { method: req.method, body: body.length ? body : undefined, headers: { 'Content-Type': req.headers['content-type'] || 'application/json' } });
88 res.writeHead(r.status, { 'Content-Type': r.headers.get('content-type') || 'application/json', 'Cache-Control': 'no-store' });
89 for await (const chunk of r.body) res.write(chunk);
90 res.end();
91 } catch (e) { res.writeHead(502); res.end('lm: ' + (e?.message || e)); }
92 }
93
94 function code(req, res, u) {
95 if (u.pathname.startsWith('/x2/')) return notFound(res); // Code's host never serves the sandbox
96 if (u.pathname === '/proxy') return proxy(req, res, u);
97 if (u.pathname.startsWith('/v1/')) return forwardLm(req, res);
98 if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(404); return res.end(); }
99 const file = safeJoin(webRoot, u.pathname);
100 if (!file) return notFound(res);
101 if (u.pathname.startsWith('/vendor/x2/')) {
102 return sendFile(res, file, { 'Content-Type': 'application/octet-stream', 'Cache-Control': 'public, max-age=31536000, immutable', 'X-Content-Type-Options': 'nosniff' });
103 }
104 return sendFile(res, file, { 'Cache-Control': 'no-store' });
105 }
106
107 function sandbox(req, res, u) {
108 const spec = loadSpec();
109 const name = Object.keys(spec.documents).find(n => spec.documents[n].path === u.pathname);
110 if (!name || req.method !== 'GET' || !queryAllowed(name, u.search, origins)) return notFound(res);
111 const body = fs.readFileSync(path.join(DOCS_DIR, name));
112 const open = insecure === 'all' || (insecure === 'exthost' && name === 'exthost-iframe.html');
113 const h = headersFor(name, origins, { insecure: open });
114 // the positive control drops the meta CSP as well as the header
115 const out = open ? Buffer.from(body.toString('utf8').replace(/<meta http-equiv="Content-Security-Policy" content="[^"]*"\/?>/, '')) : body;
116 res.writeHead(200, { ...h, 'Content-Length': out.length });
117 res.end(out);
118 }
119
120 const server = http.createServer((req, res) => {
121 const host = String(req.headers.host || '');
122 requests.push({ host, method: req.method, url: req.url });
123 let u;
124 try { u = new URL(req.url, 'http://' + host); } catch { res.writeHead(400); return res.end(); }
125 if (host === codeHost || codeAliases.some(a => host === `${a}:${server.address().port}`)) return code(req, res, u);
126 if (host === sandboxHost) return sandbox(req, res, u);
127 res.writeHead(421, { 'Content-Type': 'text/plain' }); res.end('unknown host');
128 });
129 await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
130 const actual = server.address().port;
131 // localhost may resolve to ::1 first; serve it there too when the stack allows
132 const server6 = http.createServer(server.listeners('request')[0]);
133 await new Promise(resolve => { server6.once('error', () => resolve()); server6.listen(actual, '::1', resolve); });
134 codeHost = '127.0.0.1:' + actual;
135 sandboxHost = 'localhost:' + actual;
136 origins = originsFor('dev', { port: actual });
137 if (!quiet) console.log(`Code http://${codeHost}/\nsandbox http://${sandboxHost}/x2/v1/sandbox.html`);
138 return {
139 port: actual,
140 codeOrigin: 'http://' + codeHost,
141 sandboxOrigin: 'http://' + sandboxHost,
142 requests,
143 close: () => Promise.all([new Promise(r => server.close(r)), new Promise(r => (server6.listening ? server6.close(r) : r()))]),
144 };
145}
146
147if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
148 const i = process.argv.indexOf('--port');
149 await startServer({ port: i > 0 ? Number(process.argv[i + 1]) : 0, quiet: false });
150}