/** * Minimal static server for the headed tools' control pages, with the same * cross-origin isolation headers the app requires (SharedArrayBuffer parity). */ import fs from "node:fs"; import http from "node:http"; import path from "node:path"; const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".png": "image/png", }; export function serveStatic(root, { port = 0 } = {}) { const resolvedRoot = path.resolve(root); const server = http.createServer((request, response) => { const url = new URL(request.url ?? "/", "http://127.0.0.1"); const relative = decodeURIComponent(url.pathname === "/" ? "/index.html" : url.pathname); const file = path.join(resolvedRoot, relative); if (!file.startsWith(resolvedRoot)) { response.writeHead(403).end(); return; } let body; try { body = fs.readFileSync(file); } catch { response.writeHead(404).end(); return; } response.writeHead(200, { "Content-Type": MIME[path.extname(file)] ?? "application/octet-stream", "Cache-Control": "no-cache", "Cross-Origin-Opener-Policy": "same-origin", "Cross-Origin-Embedder-Policy": "require-corp", "Cross-Origin-Resource-Policy": "same-origin", }); response.end(body); }); return new Promise((resolve, reject) => { server.on("error", reject); server.listen(port, "127.0.0.1", () => { const actual = server.address().port; resolve({ port: actual, url: `http://127.0.0.1:${actual}/`, close: () => new Promise((done) => server.close(() => done())), }); }); }); }