// Zero-dependency static file server + WebSocket proxy for the spike. // node serve.mjs [--port 8090] [--host 0.0.0.0] [--pipelines 127.0.0.1:8080] // // Serves this directory and proxies GET/Upgrade /connect to the Pipelines // server, so the page and the WebSocket share one origin. // // Why the proxy exists: internal/server/websocket.go calls // `websocket.Accept(w, r, nil)` (github.com/coder/websocket), which rejects an // upgrade whose Origin host does not match the request Host — a browser would // get 403 from a cross-origin page (a Node/curl client sends no Origin and is // unaffected, which is why the smoke test passes). Proxying makes the page // same-origin, and the Origin header is dropped on the way through because the // server has no authentication and needs none. // // The default host is 127.0.0.1. Use --host 0.0.0.0 only on a trusted LAN/VPN. import { createServer } from "node:http"; import { readFile, stat } from "node:fs/promises"; import { extname, join, normalize, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import net from "node:net"; const ROOT = resolve(fileURLToPath(new URL(".", import.meta.url))); 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; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".map": "application/json; charset=utf-8", }; function flag(argv, name, fallback) { const i = argv.indexOf(name); if (i !== -1 && argv[i + 1]) return argv[i + 1]; return fallback; } function parsePort(argv) { return Number(flag(argv, "--port", process.env.PORT ?? 8090)); } /** Resolve a request path to a file inside ROOT, or null if it escapes. */ function resolvePath(urlPath) { const decoded = decodeURIComponent(urlPath.split("?")[0]); const rel = normalize(decoded).replace(/^([/\\])+/, ""); const target = resolve(join(ROOT, rel || "index.html")); if (target !== ROOT && !target.startsWith(ROOT + sep)) return null; return target; } const server = createServer(async (req, res) => { const pathname = (req.url ?? "/").split("?")[0]; if (pathname === "/favicon.ico") { res.writeHead(204).end(); // no icon; keeps the console free of a 404 return; } const target = resolvePath(req.url ?? "/"); if (!target) { res.writeHead(403).end("Forbidden"); return; } try { let path = target; const info = await stat(path).catch(() => null); if (info?.isDirectory()) path = join(path, "index.html"); const body = await readFile(path); res.writeHead(200, { "Content-Type": MIME[extname(path)] ?? "application/octet-stream", "Cache-Control": "no-store", }); res.end(body); } catch { res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found"); } }); // --------------------------------------------------------------------------- // WebSocket proxy for /connect // --------------------------------------------------------------------------- const pipelinesTarget = flag( process.argv, "--pipelines", process.env.PIPELINES_TARGET ?? "127.0.0.1:8080", ); const targetPort = Number(pipelinesTarget.split(":").at(-1)); const targetHost = pipelinesTarget.slice(0, pipelinesTarget.lastIndexOf(":")) || "127.0.0.1"; function proxyUpgrade(req, clientSocket, clientHead) { const upstream = net.connect(targetPort, targetHost, () => { const headers = { ...req.headers }; delete headers.origin; // see the header comment: the server forbids a mismatched Origin headers.host = `${targetHost}:${targetPort}`; const block = Object.entries(headers) .filter(([, v]) => v != null) .map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(", ") : v}`) .join("\r\n"); upstream.write(`GET ${req.url} HTTP/1.1\r\n${block}\r\n\r\n`); if (clientHead?.length) upstream.write(clientHead); upstream.pipe(clientSocket); clientSocket.pipe(upstream); }); upstream.on("error", () => clientSocket.destroy()); clientSocket.on("error", () => upstream.destroy()); } server.on("upgrade", (req, clientSocket, clientHead) => { const pathname = (req.url ?? "").split("?")[0]; if (pathname !== "/connect") { clientSocket.destroy(); return; } proxyUpgrade(req, clientSocket, clientHead); }); const port = parsePort(process.argv); const host = flag(process.argv, "--host", "127.0.0.1"); server.listen(port, host, () => { const shown = host === "0.0.0.0" ? "127.0.0.1" : host; console.log(`web spike: http://${shown}:${port}/ (bound ${host}:${port})`); console.log(`proxying /connect -> ws://${targetHost}:${targetPort}/connect`); });