diff --git a/scripts/gpu-bench.js b/scripts/gpu-bench.js index 52cfd8a..b2e45ff 100644 --- a/scripts/gpu-bench.js +++ b/scripts/gpu-bench.js @@ -29,14 +29,29 @@ const save = (() => { const d = JSON.parse(fs.readFileSync(SAVE, 'utf8')); retur const client = fs.readFileSync(path.join(__dirname, 'lib', 'gpu-bench-client.js'), 'utf8'); const page = () => assemble().html.replace('', ``); +/* Only the page this server hands out may talk to it. Any other site open in the same browser could otherwise + POST results (printed to this terminal, written to --out) or, through DNS rebinding, read the save. So the Host + header must name this server, and a POST must come from its own origin. */ +const HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', HOST.includes(':') ? `[${HOST}]` : HOST]); +if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4') HOSTS.add(l.address); +const hostOk = (h) => { const m = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(h || ''); return !!m && HOSTS.has(m[1].toLowerCase()) && (m[2] ? +m[2] : 80) === PORT; }; +const MAX_BODY = 2 * 1048576; +// What the page sends is printed and written as text: no terminal escape sequences or other control characters. +const plain = (s) => String(s ?? '').replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u2028\u2029]/g, ''); + http.createServer((req, res) => { const url = new URL(req.url, 'http://localhost'); try { + if (!hostOk(req.headers.host)) { res.writeHead(421); return res.end(); } if (url.pathname === '/' || url.pathname === '/index.html') { res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' }); return res.end(page()); } if (url.pathname === '/__bench/save.json') { res.writeHead(200, { 'content-type': TYPES['.json'], 'cache-control': 'no-store' }); return res.end(save); } if (url.pathname === '/__bench/results' && req.method === 'POST') { - let body = ''; req.on('data', (c) => { body += c; }); req.on('end', () => { - try { const r = JSON.parse(body); console.log('\n' + r.md + '\n'); if (OUT) { fs.writeFileSync(OUT, r.md + '\n\n```json\n' + JSON.stringify(r, null, 1) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results', e); } + if (req.headers.origin !== `http://${req.headers.host}`) { res.writeHead(403); return res.end(); } + let body = '', size = 0, over = false; + req.on('data', (c) => { size += c.length; if (size > MAX_BODY) { over = true; req.destroy(); return; } body += c; }); + req.on('end', () => { + if (over) return; + try { const r = JSON.parse(body), md = plain(r && r.md); console.log('\n' + md + '\n'); if (OUT) { fs.writeFileSync(OUT, md + '\n\n```json\n' + plain(JSON.stringify(r, null, 1)) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results:', e.message); } res.writeHead(204); res.end(); }); return; } @@ -46,7 +61,11 @@ http.createServer((req, res) => { if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) { res.writeHead(404); return res.end(); } res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' }); fs.createReadStream(file).pipe(res); - } catch (e) { res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); res.end(String(e && e.stack || e)); } + } catch (e) { + // A malformed address (decodeURIComponent) or a missing file: the details stay in this terminal. + console.error('bench server:', e && e.message || e); + res.writeHead(e instanceof URIError ? 400 : 500); res.end(); + } }).listen(PORT, HOST, () => { const s = JSON.parse(save).S; console.log(`GPU benchmark: ${path.basename(SAVE)} (${Object.keys(s.pops || {}).length} POPs, ${(s.links || []).length} links), ${SECS}s per scenario`); diff --git a/scripts/lib/gpu-bench-client.js b/scripts/lib/gpu-bench-client.js index 690fbb3..0d85b4b 100644 --- a/scripts/lib/gpu-bench-client.js +++ b/scripts/lib/gpu-bench-client.js @@ -130,7 +130,7 @@ mapGl(want0, false); await reset(); MD = table(res, env); st(glOk ? 'Done. The results are also in the terminal.' : 'Done (no WebGL2 here: 2D only).'); - box.querySelector('#bout').innerHTML = '
' + MD.replace(/&/g, '&').replace(/';
+    box.querySelector('#bout').innerHTML = '
' + MD.replace(/<\/?sub>/g, '').replace(/&/g, '&').replace(/';
     box.querySelector('#bcp').hidden = false; go.disabled = false; go.textContent = 'Run again';
     try { await fetch('/__bench/results', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ env, res, md: MD }) }); } catch (e) { /* the panel has them */ }
   }
diff --git a/tests/gpu-bench-server.test.js b/tests/gpu-bench-server.test.js
new file mode 100644
index 0000000..4187738
--- /dev/null
+++ b/tests/gpu-bench-server.test.js
@@ -0,0 +1,50 @@
+// npm run bench:gpu serves the game on this machine: only its own page may talk to it (no other site in the
+// browser, no DNS rebinding), and what it prints or writes holds no terminal control characters.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const http = require('node:http');
+const { spawn } = require('node:child_process');
+
+const ROOT = path.join(__dirname, '..');
+
+function req(port, { method = 'GET', p = '/', host, headers = {}, body } = {}) {
+  return new Promise((resolve, reject) => {
+    const r = http.request({ host: '127.0.0.1', port, method, path: p, headers: { host: host || `localhost:${port}`, ...headers } }, (res) => {
+      let d = ''; res.on('data', (c) => { d += c; }); res.on('end', () => resolve({ status: res.statusCode, body: d }));
+    });
+    r.on('error', reject); if (body !== undefined) r.write(body); r.end();
+  });
+}
+
+test('the benchmark server answers only its own page', async (t) => {
+  const port = 20000 + Math.floor(Math.random() * 20000), out = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'bench-')), 'out.md');
+  const srv = spawn(process.execPath, [path.join(ROOT, 'scripts', 'gpu-bench.js'), '--port', String(port), '--out', out], { stdio: ['ignore', 'pipe', 'pipe'] });
+  let log = ''; srv.stdout.on('data', (c) => { log += c; }); srv.stderr.on('data', (c) => { log += c; });
+  t.after(() => srv.kill());
+  for (let i = 0; i < 100 && !/Ctrl\+C/.test(log); i++) await new Promise((r) => setTimeout(r, 100));
+  assert.match(log, /Ctrl\+C/, 'the server started');
+
+  // DNS rebinding: a request for another host name gets nothing.
+  assert.equal((await req(port, { p: '/__bench/save.json', host: `evil.example:${port}` })).status, 421);
+  assert.equal((await req(port, { p: '/__bench/save.json' })).status, 200);
+
+  // A POST from another site, or with no origin at all, is refused and writes nothing.
+  const md = 'ok\u001b]52;c;Zm9v\u0007\u001b[2Jdone';
+  const post = (origin) => req(port, { method: 'POST', p: '/__bench/results', headers: { 'content-type': 'text/plain', ...(origin ? { origin } : {}) }, body: JSON.stringify({ md }) });
+  assert.equal((await post('https://evil.example')).status, 403);
+  assert.equal((await post(null)).status, 403);
+  assert.equal(fs.existsSync(out), false);
+
+  // Its own page may send results; control characters are dropped before printing and writing.
+  assert.equal((await post(`http://localhost:${port}`)).status, 204);
+  const written = fs.readFileSync(out, 'utf8');
+  assert.match(written, /^ok\]52;c;Zm9v\[2Jdone/);
+  assert.doesNotMatch(written + log, /[\u001b\u0007]/);
+
+  // A malformed address is a plain 400: no stack trace or paths in the answer.
+  const bad = await req(port, { p: '/%E0' });
+  assert.equal(bad.status, 400); assert.equal(bad.body, '');
+});