2503a38f50
The page resolves artifact URLs against the configured server. In a proxied deployment that is the page's own origin, and serve.mjs only proxied /connect, so every artifact request 404'd: broken gallery thumbnails, a blank viewer and no session.html. Forward GET/HEAD /artifacts/ to the same upstream and stream the reply (status, headers, body). Verified: 10/10 thumbnails load on run 430 and the viewer's image has naturalWidth > 0.
224 lines
8.6 KiB
JavaScript
224 lines
8.6 KiB
JavaScript
// 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, proxies GET/Upgrade /connect and GET/HEAD /artifacts/ to
|
|
// the Pipelines server, so the page, the WebSocket and artifact files share one
|
|
// origin. The API and its artifacts live on the server's port; the page is served
|
|
// from another, so artifact URLs resolved against the page would 404 without this.
|
|
//
|
|
// 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, request } 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",
|
|
};
|
|
|
|
// A path is asset-looking when its last segment ends in a known file type, and a
|
|
// page route when its first segment names one of the client's destinations. A
|
|
// stage key may itself end in an extension (`plan.js`): under a page prefix the
|
|
// route still serves the shell, while an asset-looking path elsewhere (`/nope.js`)
|
|
// stays an honest 404 and a real file (`/src/app.js`) is still served.
|
|
const ASSET_EXTENSIONS = new Set([...Object.keys(MIME), ".woff", ".woff2", ".txt"]);
|
|
const PAGE_PREFIXES = new Set(["pipelines", "runs", "chat", "settings", "templates"]);
|
|
|
|
/** The decoded first path segment, or "" for the root. */
|
|
function firstSegment(pathname) {
|
|
const raw = pathname.split("/").filter(Boolean)[0] ?? "";
|
|
try {
|
|
return decodeURIComponent(raw);
|
|
} catch {
|
|
return raw;
|
|
}
|
|
}
|
|
|
|
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. Returns null when the percent
|
|
* escapes are malformed (a guarded decode, so a bad `%` cannot throw out of the
|
|
* request handler) and false when the path escapes ROOT; the caller treats the
|
|
* first as an unknown page route and the second as forbidden.
|
|
*/
|
|
function resolvePath(urlPath) {
|
|
let decoded;
|
|
try {
|
|
decoded = decodeURIComponent(urlPath.split("?")[0]);
|
|
} catch {
|
|
return null;
|
|
}
|
|
const rel = normalize(decoded).replace(/^([/\\])+/, "");
|
|
const target = resolve(join(ROOT, rel || "index.html"));
|
|
if (target !== ROOT && !target.startsWith(ROOT + sep)) return false;
|
|
return target;
|
|
}
|
|
|
|
/** Send index.html (the page shell). The router reads the real URL in the browser. */
|
|
async function serveIndex(res) {
|
|
const html = await readFile(join(ROOT, "index.html"), "utf8");
|
|
// A deep URL such as /runs/440 would otherwise resolve the shell's relative
|
|
// `./src/app.js` against /runs/. A root <base> keeps the shell's own asset URLs
|
|
// absolute without changing the address bar (and without editing index.html).
|
|
const body = html.replace(/<head>/i, '<head>\n <base href="/" />');
|
|
res.writeHead(200, {
|
|
"Content-Type": MIME[".html"],
|
|
"Cache-Control": "no-store",
|
|
});
|
|
res.end(body);
|
|
}
|
|
|
|
/**
|
|
* Proxy one artifact request to the Pipelines server. Artifact URLs are resolved
|
|
* against the configured server, which in a proxied deployment is the page's own
|
|
* origin, so without this the gallery's thumbnails, the viewer and the session
|
|
* export would all 404 while the WebSocket worked.
|
|
*/
|
|
function proxyArtifact(req, res) {
|
|
const headers = { ...req.headers };
|
|
delete headers.origin;
|
|
headers.host = `${targetHost}:${targetPort}`;
|
|
const upstream = request(
|
|
{ host: targetHost, port: targetPort, method: req.method, path: req.url, headers },
|
|
(reply) => {
|
|
res.writeHead(reply.statusCode ?? 502, reply.headers);
|
|
reply.pipe(res);
|
|
},
|
|
);
|
|
upstream.on("error", () => {
|
|
if (!res.headersSent) res.writeHead(502, { "Content-Type": "text/plain; charset=utf-8" });
|
|
res.end("Artifact unavailable");
|
|
});
|
|
req.pipe(upstream);
|
|
}
|
|
|
|
const server = createServer(async (req, res) => {
|
|
const pathname = (req.url ?? "/").split("?")[0];
|
|
if (pathname.startsWith("/artifacts/")) {
|
|
proxyArtifact(req, res);
|
|
return;
|
|
}
|
|
if (pathname === "/favicon.ico") {
|
|
res.writeHead(204).end(); // no icon; keeps the console free of a 404
|
|
return;
|
|
}
|
|
// SPA fallback: a page route (`/runs/440`, `/pipelines/24/5/stage/plan.js`) or a
|
|
// non-asset GET serves the shell, so a hard navigation deep-links and the client
|
|
// router opens the destination. A path that looks like an asset outside a page
|
|
// prefix (`.js`, `.css`, `.png`, …) stays an honest 404, and a malformed escape
|
|
// is handled like any other unknown path rather than rejecting the handler.
|
|
const assetLike = ASSET_EXTENSIONS.has(extname(pathname).toLowerCase());
|
|
const pageLike = PAGE_PREFIXES.has(firstSegment(pathname));
|
|
const serveShell = pageLike || !assetLike;
|
|
const target = resolvePath(req.url ?? "/");
|
|
if (target === null) {
|
|
// A malformed percent escape is an unknown page route, not a handler throw.
|
|
if (serveShell) {
|
|
await serveIndex(res).catch(() => {
|
|
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
|
|
});
|
|
return;
|
|
}
|
|
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
|
|
return;
|
|
}
|
|
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 {
|
|
if (serveShell) {
|
|
await serveIndex(res).catch(() => {
|
|
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
|
|
});
|
|
return;
|
|
}
|
|
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) and /artifacts/ (http) -> ${targetHost}:${targetPort}`);
|
|
});
|