Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Use libraries for local proxy and static serving (#1543)

Graham Neubig74f06866ecc0
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 977cb8b0c8..99a164b4a2 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -104,8 +104,14 @@ RUN uv pip install --system "openhands-automation==${AUTOMATION_VERSION}" 2>/dev
# react-router.config.ts unpacks build/client/ into build/ for non-Vercel builds.
COPY --from=frontend-build /build/build /opt/agent-canvas/frontend
-# Copy the static-server script (serves frontend + proxies to backends)
+# Copy the static-server scripts and their production runtime deps.
COPY scripts/static-server.mjs /opt/agent-canvas/static-server.mjs
+COPY scripts/proxy-utils.mjs /opt/agent-canvas/proxy-utils.mjs
+COPY --from=frontend-build /build/node_modules/httpxy /opt/agent-canvas/node_modules/httpxy
+COPY --from=frontend-build /build/node_modules/sirv /opt/agent-canvas/node_modules/sirv
+COPY --from=frontend-build /build/node_modules/@polka /opt/agent-canvas/node_modules/@polka
+COPY --from=frontend-build /build/node_modules/mrmime /opt/agent-canvas/node_modules/mrmime
+COPY --from=frontend-build /build/node_modules/totalist /opt/agent-canvas/node_modules/totalist
# Copy the runtime-services-info builder (entrypoint.sh runs it as a CLI to
# emit the agent's <RUNTIME_SERVICES> block; same builder the dev stack uses).
diff --git a/package-lock.json b/package-lock.json
index b6269ce4b5..7e34c00e81 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -27,6 +27,7 @@
"clsx": "2.1.1",
"downshift": "9.3.2",
"framer-motion": "12.38.0",
+ "httpxy": "0.5.3",
"i18next": "26.0.8",
"i18next-browser-languagedetector": "8.2.1",
"i18next-http-backend": "4.0.0",
@@ -47,6 +48,7 @@
"remark-breaks": "4.0.0",
"remark-gfm": "4.0.1",
"shell-quote": "1.8.4",
+ "sirv": "3.0.2",
"sirv-cli": "3.0.1",
"socket.io-client": "4.8.3",
"tailwind-merge": "3.5.0",
@@ -11858,6 +11860,12 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/httpxy": {
+ "version": "0.5.3",
+ "resolved": "https://registry.npmjs.org/httpxy/-/httpxy-0.5.3.tgz",
+ "integrity": "sha512-SMS9V6Sn7VWaS11lYhoAr0ceoaiolTWf4jYdJn0NJhCdKMu9R2H9Fh0LBDWBHQF6HRLI1PmaePYsjanSpE5PEw==",
+ "license": "MIT"
+ },
"node_modules/husky": {
"version": "9.1.7",
"resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz",
diff --git a/package.json b/package.json
index 965cb32a71..b2a98c537d 100644
--- a/package.json
+++ b/package.json
@@ -38,6 +38,7 @@
"clsx": "2.1.1",
"downshift": "9.3.2",
"framer-motion": "12.38.0",
+ "httpxy": "0.5.3",
"i18next": "26.0.8",
"i18next-browser-languagedetector": "8.2.1",
"i18next-http-backend": "4.0.0",
@@ -58,6 +59,7 @@
"remark-breaks": "4.0.0",
"remark-gfm": "4.0.1",
"shell-quote": "1.8.4",
+ "sirv": "3.0.2",
"sirv-cli": "3.0.1",
"socket.io-client": "4.8.3",
"tailwind-merge": "3.5.0",
diff --git a/scripts/ingress.mjs b/scripts/ingress.mjs
index d32dfea090..1c8da36985 100644
--- a/scripts/ingress.mjs
+++ b/scripts/ingress.mjs
@@ -19,8 +19,15 @@
* - More specific routes take precedence (e.g., /api/automation before /api)
*/
-import { createServer, request as httpRequest } from "node:http";
+import { createServer } from "node:http";
import process from "node:process";
+import { pathToFileURL } from "node:url";
+
+import {
+ createProxyHandlers,
+ createRouter,
+ isBenignSocketError,
+} from "./proxy-utils.mjs";
// ═══════════════════════════════════════════════════════════════════════════
// Configuration
@@ -121,197 +128,17 @@ function buildConfig(args, env = process.env) {
};
}
-// ═══════════════════════════════════════════════════════════════════════════
-// Router
-// ═══════════════════════════════════════════════════════════════════════════
-
-function createRouter(routes, defaultBackend) {
- // Sort routes by path length (longest first) for most-specific matching
- const sortedRoutes = Object.entries(routes).sort(
- ([a], [b]) => b.length - a.length
- );
-
- return function route(url) {
- for (const [prefix, backend] of sortedRoutes) {
- if (url === prefix || url.startsWith(prefix + "/") || url.startsWith(prefix + "?")) {
- return backend;
- }
- }
- return defaultBackend;
- };
-}
-
-function parseBackendUrl(backendUrl) {
- const url = new URL(backendUrl);
- return {
- hostname: url.hostname,
- port: parseInt(url.port, 10) || (url.protocol === "https:" ? 443 : 80),
- protocol: url.protocol,
- };
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// Proxy
-// ═══════════════════════════════════════════════════════════════════════════
-
-// Errors that are normal during connection teardown and should not be logged
-// at error level (clients/upstreams routinely reset long-lived connections).
-const BENIGN_SOCKET_ERRORS = new Set([
- "ECONNRESET",
- "EPIPE",
- "ECONNABORTED",
- "ERR_STREAM_PREMATURE_CLOSE",
-]);
-
-function isBenignSocketError(err) {
- return Boolean(err && BENIGN_SOCKET_ERRORS.has(err.code));
-}
-
-function proxyRequest(req, res, backendUrl) {
- const backend = parseBackendUrl(backendUrl);
-
- const options = {
- hostname: backend.hostname,
- port: backend.port,
- path: req.url,
- method: req.method,
- headers: {
- ...req.headers,
- host: `${backend.hostname}:${backend.port}`,
- },
- };
-
- const proxyReq = httpRequest(options, (proxyRes) => {
- proxyRes.on("error", (err) => {
- if (!isBenignSocketError(err)) {
- console.error(`Upstream response error for ${req.url}:`, err.message);
- }
- if (!res.headersSent) {
- res.writeHead(502);
- res.end(`Bad Gateway: ${err.message}`);
- } else {
- res.destroy();
- }
- });
-
- res.writeHead(proxyRes.statusCode, proxyRes.headers);
- proxyRes.pipe(res, { end: true });
- });
-
- proxyReq.on("error", (err) => {
- if (!isBenignSocketError(err)) {
- console.error(`Proxy error for ${req.url}:`, err.message);
- }
- if (!res.headersSent) {
- res.writeHead(502);
- res.end(`Bad Gateway: ${err.message}`);
- } else {
- res.destroy();
- }
- });
-
- // If the client disconnects mid-request, abort the upstream call so we
- // don't leak connections or emit unhandled 'error' events.
- req.on("error", (err) => {
- if (!isBenignSocketError(err)) {
- console.error(`Client request error for ${req.url}:`, err.message);
- }
- proxyReq.destroy();
- });
-
- // The outbound HTTP response object can also emit 'error' (e.g. EPIPE if
- // the client socket is gone). Without a listener Node would crash.
- res.on("error", (err) => {
- if (!isBenignSocketError(err)) {
- console.error(`Client response error for ${req.url}:`, err.message);
- }
- proxyReq.destroy();
- });
-
- req.pipe(proxyReq, { end: true });
-}
-
-function proxyWebSocket(req, socket, head, backendUrl) {
- const backend = parseBackendUrl(backendUrl);
-
- const options = {
- hostname: backend.hostname,
- port: backend.port,
- path: req.url,
- method: req.method,
- headers: {
- ...req.headers,
- host: `${backend.hostname}:${backend.port}`,
- },
- };
-
- const proxyReq = httpRequest(options);
-
- // Always attach an 'error' handler to the client socket immediately. The
- // client can drop the connection before the upstream upgrade completes
- // (e.g. during a slow DNS / connect), and an unhandled 'error' on the raw
- // TCP socket would crash the entire ingress process.
- socket.on("error", (err) => {
- if (!isBenignSocketError(err)) {
- console.error(`WebSocket client socket error for ${req.url}:`, err.message);
- }
- proxyReq.destroy();
- });
-
- proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
- // Once the upgrade is established, errors on either raw TCP socket must
- // be handled or Node will throw. ECONNRESET / EPIPE on long-lived
- // WebSocket connections is routine (browser tab closed, NAT timeout,
- // mobile network handoff, …) and should never crash the proxy.
- const teardown = (label) => (err) => {
- if (err && !isBenignSocketError(err)) {
- console.error(`WebSocket ${label} error for ${req.url}:`, err.message);
- }
- socket.destroy();
- proxySocket.destroy();
- };
- proxySocket.on("error", teardown("upstream socket"));
- // Note: socket already has an 'error' listener from above; add a second
- // one that also destroys proxySocket so we don't leak the upstream half.
- socket.on("error", () => proxySocket.destroy());
- socket.on("close", () => proxySocket.destroy());
- proxySocket.on("close", () => socket.destroy());
-
- socket.write(
- `HTTP/${proxyRes.httpVersion} ${proxyRes.statusCode} ${proxyRes.statusMessage}\r\n`
- );
- for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
- socket.write(`${proxyRes.rawHeaders[i]}: ${proxyRes.rawHeaders[i + 1]}\r\n`);
- }
- socket.write("\r\n");
-
- if (proxyHead.length > 0) {
- socket.write(proxyHead);
- }
-
- proxySocket.pipe(socket, { end: true });
- socket.pipe(proxySocket, { end: true });
- });
-
- proxyReq.on("error", (err) => {
- if (!isBenignSocketError(err)) {
- console.error(`WebSocket proxy error for ${req.url}:`, err.message);
- }
- socket.destroy();
- });
-
- proxyReq.end();
-}
-
// ═══════════════════════════════════════════════════════════════════════════
// Server
// ═══════════════════════════════════════════════════════════════════════════
-function startIngress(config) {
+export function startIngress(config) {
const route = createRouter(config.routes, config.defaultBackend);
+ const proxy = createProxyHandlers({ label: `ingress:${config.port}` });
+ const uninstallDiagnostics = proxy.installDiagnostics();
const server = createServer((req, res) => {
- const backend = route(req.url);
+ const backend = route(req.url ?? "/");
if (!backend) {
res.writeHead(503);
@@ -319,19 +146,19 @@ function startIngress(config) {
return;
}
- proxyRequest(req, res, backend);
+ proxy.proxyHttp(req, res, backend);
});
// Handle WebSocket upgrades
server.on("upgrade", (req, socket, head) => {
- const backend = route(req.url);
+ const backend = route(req.url ?? "/");
if (!backend) {
socket.destroy();
return;
}
- proxyWebSocket(req, socket, head, backend);
+ proxy.proxyWebSocket(req, socket, head, backend);
});
// Built-in protection against malformed client requests that can otherwise
@@ -346,18 +173,31 @@ function startIngress(config) {
socket.destroy();
}
});
+ server.on("close", uninstallDiagnostics);
server.listen(config.port, () => {
console.log("");
- console.log("╔═══════════════════════════════════════════════════════════════╗");
- console.log("β•‘ Ingress Proxy β•‘");
- console.log("╠═══════════════════════════════════════════════════════════════╣");
- console.log(`β•‘ Listening on: http://localhost:${config.port}/`.padEnd(66) + "β•‘");
- console.log("╠═══════════════════════════════════════════════════════════════╣");
- console.log("β•‘ Routes: β•‘");
+ console.log(
+ "╔═══════════════════════════════════════════════════════════════╗",
+ );
+ console.log(
+ "β•‘ Ingress Proxy β•‘",
+ );
+ console.log(
+ "╠═══════════════════════════════════════════════════════════════╣",
+ );
+ console.log(
+ `β•‘ Listening on: http://localhost:${config.port}/`.padEnd(66) + "β•‘",
+ );
+ console.log(
+ "╠═══════════════════════════════════════════════════════════════╣",
+ );
+ console.log(
+ "β•‘ Routes: β•‘",
+ );
const sortedRoutes = Object.entries(config.routes).sort(
- ([a], [b]) => b.length - a.length
+ ([a], [b]) => b.length - a.length,
);
for (const [path, backend] of sortedRoutes) {
const line = ` ${path} β†’ ${backend}`;
@@ -369,8 +209,12 @@ function startIngress(config) {
console.log(`β•‘ ${line.padEnd(61)}β•‘`);
}
- console.log("β•‘ β•‘");
- console.log("β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•");
+ console.log(
+ "β•‘ β•‘",
+ );
+ console.log(
+ "β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•",
+ );
console.log("");
});
@@ -381,35 +225,31 @@ function startIngress(config) {
// Main
// ═══════════════════════════════════════════════════════════════════════════
-const args = parseArgs();
-const config = buildConfig(args);
+const isMainModule =
+ process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
-if (Object.keys(config.routes).length === 0 && !config.defaultBackend) {
- console.error("Error: No routes configured. Use --route or --default options.");
- console.error("Run with --help for usage information.");
- process.exit(1);
-}
-
-startIngress(config);
+if (isMainModule) {
+ const args = parseArgs();
+ const config = buildConfig(args);
-// Last-resort safety net: a benign socket reset on a stream we forgot to wire
-// up should never crash the proxy. Anything else is re-thrown so real bugs
-// stay visible.
-process.on("uncaughtException", (err) => {
- if (isBenignSocketError(err)) {
- console.warn(`Ignoring socket reset: ${err.code} ${err.message}`);
- return;
+ if (Object.keys(config.routes).length === 0 && !config.defaultBackend) {
+ console.error(
+ "Error: No routes configured. Use --route or --default options.",
+ );
+ console.error("Run with --help for usage information.");
+ process.exit(1);
}
- throw err;
-});
-
-// Handle graceful shutdown
-process.on("SIGINT", () => {
- console.log("\nShutting down...");
- process.exit(0);
-});
-
-process.on("SIGTERM", () => {
- console.log("\nShutting down...");
- process.exit(0);
-});
+
+ startIngress(config);
+
+ // Handle graceful shutdown
+ process.on("SIGINT", () => {
+ console.log("\nShutting down...");
+ process.exit(0);
+ });
+
+ process.on("SIGTERM", () => {
+ console.log("\nShutting down...");
+ process.exit(0);
+ });
+}
diff --git a/scripts/proxy-utils.mjs b/scripts/proxy-utils.mjs
new file mode 100644
index 0000000000..04d308fd59
--- /dev/null
+++ b/scripts/proxy-utils.mjs
@@ -0,0 +1,171 @@
+import { createProxyServer } from "httpxy";
+
+const DEFAULT_PROXY_TIMEOUT_MS = 120_000;
+const BENIGN_SOCKET_ERRORS = new Set([
+ "ECONNRESET",
+ "EPIPE",
+ "ECONNABORTED",
+ "ERR_STREAM_PREMATURE_CLOSE",
+]);
+
+export function matchesPathPrefix(url, prefix) {
+ return (
+ url === prefix ||
+ url.startsWith(prefix + "/") ||
+ url.startsWith(prefix + "?")
+ );
+}
+
+export function createRouter(routes, defaultBackend = null) {
+ const sortedRoutes = Object.entries(routes).sort(
+ ([a], [b]) => b.length - a.length,
+ );
+
+ return function route(url) {
+ for (const [prefix, backend] of sortedRoutes) {
+ if (matchesPathPrefix(url, prefix)) {
+ return backend;
+ }
+ }
+ return defaultBackend;
+ };
+}
+
+export function isBenignSocketError(err) {
+ return Boolean(err && BENIGN_SOCKET_ERRORS.has(err.code));
+}
+
+function once(fn) {
+ let called = false;
+ return (...args) => {
+ if (called) return;
+ called = true;
+ fn(...args);
+ };
+}
+
+function writeProxyError(res, message) {
+ if (res.destroyed) return;
+ if (!res.headersSent) {
+ res.writeHead(502, { "Content-Type": "text/plain; charset=utf-8" });
+ res.end(`Bad Gateway: ${message}`);
+ return;
+ }
+ res.destroy();
+}
+
+export function createProxyHandlers({
+ label = "proxy",
+ timeout = DEFAULT_PROXY_TIMEOUT_MS,
+ proxyTimeout = DEFAULT_PROXY_TIMEOUT_MS,
+} = {}) {
+ const proxy = createProxyServer({
+ ws: true,
+ changeOrigin: true,
+ xfwd: true,
+ timeout,
+ proxyTimeout,
+ });
+ const metrics = {
+ activeHttpRequests: 0,
+ activeWebSockets: 0,
+ totalHttpRequests: 0,
+ totalWebSockets: 0,
+ totalErrors: 0,
+ };
+
+ proxy.on("error", (err, _req, resOrSocket, target) => {
+ metrics.totalErrors += 1;
+ const targetText = target ? ` -> ${target}` : "";
+ if (!isBenignSocketError(err)) {
+ console.error(`[${label}] Proxy error${targetText}: ${err.message}`);
+ }
+ if (resOrSocket && typeof resOrSocket.writeHead === "function") {
+ writeProxyError(resOrSocket, err.message);
+ } else if (resOrSocket && typeof resOrSocket.destroy === "function") {
+ resOrSocket.destroy();
+ }
+ });
+
+ function proxyHttp(req, res, target) {
+ metrics.activeHttpRequests += 1;
+ metrics.totalHttpRequests += 1;
+ const finish = once(() => {
+ metrics.activeHttpRequests = Math.max(0, metrics.activeHttpRequests - 1);
+ });
+ res.on("close", finish);
+ res.on("finish", finish);
+ res.on("error", finish);
+
+ proxy.web(req, res, { target }).catch((err) => {
+ metrics.totalErrors += 1;
+ if (!isBenignSocketError(err)) {
+ console.error(
+ `[${label}] Proxy error for ${req.url} -> ${target}:`,
+ err,
+ );
+ }
+ writeProxyError(res, err instanceof Error ? err.message : String(err));
+ finish();
+ });
+ }
+
+ function proxyWebSocket(req, socket, head, target) {
+ metrics.activeWebSockets += 1;
+ metrics.totalWebSockets += 1;
+ const finish = once(() => {
+ metrics.activeWebSockets = Math.max(0, metrics.activeWebSockets - 1);
+ });
+ socket.on("close", finish);
+ socket.on("error", finish);
+
+ try {
+ proxy.ws(req, socket, { target }, head).catch((err) => {
+ metrics.totalErrors += 1;
+ if (!isBenignSocketError(err)) {
+ console.error(
+ `[${label}] WebSocket proxy error for ${req.url} -> ${target}:`,
+ err,
+ );
+ }
+ socket.destroy();
+ finish();
+ });
+ } catch (err) {
+ metrics.totalErrors += 1;
+ if (!isBenignSocketError(err)) {
+ console.error(
+ `[${label}] WebSocket proxy error for ${req.url} -> ${target}:`,
+ err,
+ );
+ }
+ socket.destroy();
+ finish();
+ }
+ }
+
+ function dumpMetrics() {
+ console.log(
+ `[${label}] active_http=${metrics.activeHttpRequests} ` +
+ `active_ws=${metrics.activeWebSockets} ` +
+ `total_http=${metrics.totalHttpRequests} ` +
+ `total_ws=${metrics.totalWebSockets} ` +
+ `total_errors=${metrics.totalErrors}`,
+ );
+ }
+
+ function installDiagnostics(signal = "SIGUSR1") {
+ process.on(signal, dumpMetrics);
+ return () => {
+ process.off(signal, dumpMetrics);
+ };
+ }
+
+ return {
+ proxyHttp,
+ proxyWebSocket,
+ dumpMetrics,
+ installDiagnostics,
+ metrics,
+ };
+}
diff --git a/scripts/static-server.mjs b/scripts/static-server.mjs
index 1582852e1e..87aacad68f 100644
--- a/scripts/static-server.mjs
+++ b/scripts/static-server.mjs
@@ -27,40 +27,49 @@
* --route "/sockets=http://localhost:18000"
*/
-import { createServer, request as httpRequest } from "node:http";
-import { createReadStream } from "node:fs";
-import { readFile, stat } from "node:fs/promises";
-import { extname, isAbsolute, normalize, relative, resolve } from "node:path";
+import { createServer } from "node:http";
+import { readFile } from "node:fs/promises";
+import { extname, resolve } from "node:path";
import process from "node:process";
import { pathToFileURL } from "node:url";
+import sirv from "sirv";
+
+import {
+ createProxyHandlers,
+ createRouter,
+ matchesPathPrefix,
+} from "./proxy-utils.mjs";
// ─────────────────────────────────────────────────────────────────────────────
-// MIME types
+// SPA fallback helpers
// ─────────────────────────────────────────────────────────────────────────────
-const MIME = {
- ".html": "text/html; charset=utf-8",
- ".js": "application/javascript; charset=utf-8",
- ".mjs": "application/javascript; charset=utf-8",
- ".css": "text/css; charset=utf-8",
- ".json": "application/json; charset=utf-8",
- ".svg": "image/svg+xml",
- ".png": "image/png",
- ".jpg": "image/jpeg",
- ".jpeg": "image/jpeg",
- ".gif": "image/gif",
- ".ico": "image/x-icon",
- ".webp": "image/webp",
- ".woff": "font/woff",
- ".woff2": "font/woff2",
- ".ttf": "font/ttf",
- ".wav": "audio/wav",
- ".mp3": "audio/mpeg",
- ".webmanifest": "application/manifest+json",
- ".txt": "text/plain; charset=utf-8",
- ".xml": "application/xml",
- ".map": "application/json",
-};
+const ASSET_LIKE_EXTENSIONS = new Set([
+ ".br",
+ ".css",
+ ".gif",
+ ".gz",
+ ".html",
+ ".htm",
+ ".ico",
+ ".jpeg",
+ ".jpg",
+ ".js",
+ ".json",
+ ".map",
+ ".mjs",
+ ".mp3",
+ ".png",
+ ".svg",
+ ".ttf",
+ ".txt",
+ ".wav",
+ ".webmanifest",
+ ".webp",
+ ".woff",
+ ".woff2",
+ ".xml",
+]);
// ─────────────────────────────────────────────────────────────────────────────
// Args
@@ -329,294 +338,119 @@ async function serveInjectedIndexHtml(
"Content-Length": buf.length,
"Cache-Control": "no-cache",
});
- if (req.method !== "HEAD") res.end(buf);
+ if (req.method === "HEAD") {
+ res.end();
+ } else {
+ res.end(buf);
+ }
return true;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Router (kept structurally identical to scripts/ingress.mjs)
-// ─────────────────────────────────────────────────────────────────────────────
-
-export function createRouter(routes) {
- const sortedRoutes = Object.entries(routes).sort(
- ([a], [b]) => b.length - a.length,
- );
-
- return function route(url) {
- for (const [prefix, backend] of sortedRoutes) {
- if (
- url === prefix ||
- url.startsWith(prefix + "/") ||
- url.startsWith(prefix + "?")
- ) {
- return backend;
- }
- }
- return null;
- };
-}
-
-function parseBackendUrl(backendUrl) {
- const url = new URL(backendUrl);
- return {
- hostname: url.hostname,
- port:
- Number.parseInt(url.port, 10) || (url.protocol === "https:" ? 443 : 80),
- protocol: url.protocol,
- };
-}
-
-function proxyRequest(req, res, backendUrl) {
- const backend = parseBackendUrl(backendUrl);
-
- const proxyReq = httpRequest(
- {
- hostname: backend.hostname,
- port: backend.port,
- path: req.url,
- method: req.method,
- headers: {
- ...req.headers,
- host: `${backend.hostname}:${backend.port}`,
- },
- },
- (proxyRes) => {
- res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
- proxyRes.pipe(res, { end: true });
- },
- );
-
- // Absorb client-disconnect errors (EPIPE/ECONNRESET) so the server
- // process survives abrupt navigations and health-check probes.
- req.on("error", () => {});
- res.on("error", () => {});
-
- proxyReq.on("error", (err) => {
- console.error(`Proxy error for ${req.url} -> ${backendUrl}:`, err.message);
- if (!res.headersSent) {
- res.writeHead(502);
- res.end(`Bad Gateway: ${err.message}`);
- }
- });
-
- req.pipe(proxyReq, { end: true });
-}
-
-function proxyWebSocket(req, socket, head, backendUrl) {
- const backend = parseBackendUrl(backendUrl);
-
- const proxyReq = httpRequest({
- hostname: backend.hostname,
- port: backend.port,
- path: req.url,
- method: req.method,
- headers: {
- ...req.headers,
- host: `${backend.hostname}:${backend.port}`,
- },
- });
-
- // Absorb socket errors so the process survives mid-flight disconnects.
- socket.on("error", () => socket.destroy());
-
- proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
- proxySocket.on("error", () => proxySocket.destroy());
-
- socket.write(
- `HTTP/${proxyRes.httpVersion} ${proxyRes.statusCode} ${proxyRes.statusMessage}\r\n`,
- );
- for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
- socket.write(
- `${proxyRes.rawHeaders[i]}: ${proxyRes.rawHeaders[i + 1]}\r\n`,
- );
- }
- socket.write("\r\n");
- if (proxyHead.length > 0) {
- socket.write(proxyHead);
- }
- // Handle errors on both sockets so an abrupt disconnect (ECONNRESET,
- // EPIPE) during test cleanup doesn't crash the process with an
- // uncaught 'error' event.
- proxySocket.on("error", (err) => {
- console.error(
- `WebSocket proxy backend socket error (${req.url}):`,
- err.message,
- );
- socket.destroy();
- });
- socket.on("error", (err) => {
- console.error(
- `WebSocket proxy client socket error (${req.url}):`,
- err.message,
- );
- proxySocket.destroy();
- });
- proxySocket.pipe(socket, { end: true });
- socket.pipe(proxySocket, { end: true });
- });
-
- proxyReq.on("error", (err) => {
- console.error(
- `WebSocket proxy error for ${req.url} -> ${backendUrl}:`,
- err.message,
- );
- socket.destroy();
- });
-
- proxyReq.end();
-}
-
// ─────────────────────────────────────────────────────────────────────────────
// Static file serving
// ─────────────────────────────────────────────────────────────────────────────
-async function tryStat(path) {
+function parseUrlPath(req, res) {
+ const rawPath = (req.url ?? "/").split("?")[0];
try {
- const result = await stat(path);
- return result.isFile() ? result : null;
+ return decodeURIComponent(rawPath);
} catch {
+ res.writeHead(400);
+ res.end("Bad Request");
return null;
}
}
-function makeEtag(stats) {
- // Match sirv's weak-ETag format: W/"<size>-<mtime ms>"
- return `W/"${stats.size}-${Math.floor(stats.mtimeMs)}"`;
+function isGetOrHead(req) {
+ return req.method === "GET" || req.method === "HEAD";
}
-function pickContentType(filePath) {
- return MIME[extname(filePath).toLowerCase()] || "application/octet-stream";
-}
-
-function pickCacheControl(urlPath) {
- // Vite/react-router builds emit content-hashed assets under /assets/.
- // Those are safe to cache forever; everything else (index.html, public/
- // copies, locales) should revalidate so a rebuild is picked up.
- if (urlPath.startsWith("/assets/")) {
- return "public, max-age=31536000, immutable";
- }
- return "no-cache";
+function needsRuntimeInjection(injectionOpts) {
+ return Boolean(
+ injectionOpts.sessionApiKey ||
+ injectionOpts.authRequired ||
+ injectionOpts.runtimeServicesInfo ||
+ injectionOpts.lockToCloud,
+ );
}
function looksLikeAssetRequest(urlPath) {
- // If the last path segment has a known file extension, treat 404s as 404
- // instead of falling back to the SPA shell. Avoids serving index.html for
- // missing /favicon.ico, missing source maps, etc.
const last = urlPath.split("/").pop() ?? "";
- const ext = extname(last).toLowerCase();
- return Boolean(ext) && ext in MIME;
+ return ASSET_LIKE_EXTENSIONS.has(extname(last).toLowerCase());
}
-function isPathInsideDir(dirAbs, filePath) {
- const relativePath = relative(dirAbs, filePath);
- return (
- relativePath === "" ||
- (!relativePath.startsWith("..") && !isAbsolute(relativePath))
- );
+function matchesAnyPrefix(urlPath, prefixes) {
+ return prefixes.some((prefix) => matchesPathPrefix(urlPath, prefix));
}
-async function serveFile(req, res, filePath, urlPath) {
- const stats = await tryStat(filePath);
- if (!stats) return false;
+function rejectUnavailable(res) {
+ res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" });
+ res.end("Service Unavailable (no backend configured for this route)");
+}
- const etag = makeEtag(stats);
- if (req.headers["if-none-match"] === etag) {
- res.writeHead(304, { ETag: etag });
- res.end();
- return true;
- }
+function notFound(res) {
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
+ res.end("Not Found");
+}
- res.writeHead(200, {
- "Content-Type": pickContentType(filePath),
- "Content-Length": stats.size,
- "Cache-Control": pickCacheControl(urlPath),
- ETag: etag,
- });
+function setStaticHeaders(res, pathname) {
+ const extension = extname(pathname).toLowerCase();
+ if (extension === ".js" || extension === ".mjs") {
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
+ }
- if (req.method === "HEAD") {
- res.end();
- return true;
+ if (pathname.startsWith("/assets/")) {
+ res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
+ return;
}
+ res.setHeader("Cache-Control", "no-cache");
+}
- createReadStream(filePath).pipe(res);
- return true;
+function createStaticMiddleware(dirAbs) {
+ return sirv(dirAbs, {
+ etag: true,
+ single: false,
+ setHeaders: setStaticHeaders,
+ });
}
async function handleStatic(
req,
res,
dirAbs,
+ staticMiddleware,
injectionOpts = {},
rejectPrefixes = [],
) {
- const rawPath = req.url.split("?")[0];
- let urlPath;
- try {
- urlPath = decodeURIComponent(rawPath);
- } catch {
- res.writeHead(400);
- res.end("Bad Request");
- return;
- }
+ const urlPath = parseUrlPath(req, res);
+ if (urlPath === null) return;
- const safe = normalize(urlPath);
- let filePath = resolve(dirAbs, "." + safe);
- if (!isPathInsideDir(dirAbs, filePath)) {
- res.writeHead(403);
- res.end("Forbidden");
- return;
- }
+ const injectRuntimeConfig = needsRuntimeInjection(injectionOpts);
+ const indexPath = resolve(dirAbs, "index.html");
- // Directory request -> /index.html
- if (urlPath.endsWith("/")) {
- filePath = resolve(filePath, "index.html");
+ if (
+ injectRuntimeConfig &&
+ isGetOrHead(req) &&
+ (urlPath === "/" || urlPath === "/index.html")
+ ) {
+ if (await serveInjectedIndexHtml(req, res, indexPath, injectionOpts))
+ return;
}
- const needsInjection =
- injectionOpts.sessionApiKey ||
- injectionOpts.authRequired ||
- injectionOpts.runtimeServicesInfo ||
- injectionOpts.lockToCloud;
-
- // Serve index.html with runtime config injection when configured.
- if (needsInjection && filePath.endsWith("index.html")) {
- if (await serveInjectedIndexHtml(req, res, filePath, injectionOpts)) return;
- // Fall through to regular serveFile (handles 404 path correctly).
- }
+ staticMiddleware(req, res, async () => {
+ if (matchesAnyPrefix(urlPath, rejectPrefixes)) {
+ rejectUnavailable(res);
+ return;
+ }
- if (await serveFile(req, res, filePath, urlPath)) return;
-
- // Reject prefixes: return 503 for known API paths that have no backend
- // configured (e.g. in --frontend-only mode). Checked before SPA fallback
- // so these paths never silently serve index.html.
- if (rejectPrefixes.length > 0) {
- for (const prefix of rejectPrefixes) {
- if (
- urlPath === prefix ||
- urlPath.startsWith(prefix + "/") ||
- urlPath.startsWith(prefix + "?")
- ) {
- res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" });
- res.end("Service Unavailable (no backend configured for this route)");
+ if (isGetOrHead(req) && !looksLikeAssetRequest(urlPath)) {
+ if (await serveInjectedIndexHtml(req, res, indexPath, injectionOpts)) {
return;
}
}
- }
- // SPA fallback: only for non-asset requests, and not for non-GET/HEAD.
- if (
- (req.method === "GET" || req.method === "HEAD") &&
- !looksLikeAssetRequest(urlPath)
- ) {
- const indexPath = resolve(dirAbs, "index.html");
- if (needsInjection) {
- if (await serveInjectedIndexHtml(req, res, indexPath, injectionOpts))
- return;
- } else if (await serveFile(req, res, indexPath, "/")) return;
- }
-
- res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
- res.end("Not Found");
+ notFound(res);
+ });
}
// ─────────────────────────────────────────────────────────────────────────────
@@ -625,6 +459,7 @@ async function handleStatic(
export function startStaticServer(config) {
const route = createRouter(config.routes);
+ const proxy = createProxyHandlers({ label: `static:${config.port}` });
const dirAbs = resolve(config.dir);
const injectionOpts = {
sessionApiKey: config.sessionApiKey || null,
@@ -633,32 +468,41 @@ export function startStaticServer(config) {
lockToCloud: config.lockToCloud || null,
};
const rejectPrefixes = config.rejectPrefixes ?? [];
+ const staticMiddleware = createStaticMiddleware(dirAbs);
+
+ const uninstallDiagnostics = proxy.installDiagnostics();
const server = createServer((req, res) => {
- const backend = route(req.url);
+ const backend = route(req.url ?? "/");
if (backend) {
- proxyRequest(req, res, backend);
+ proxy.proxyHttp(req, res, backend);
return;
}
- handleStatic(req, res, dirAbs, injectionOpts, rejectPrefixes).catch(
- (err) => {
- console.error(`Static handler error for ${req.url}:`, err);
- if (!res.headersSent) {
- res.writeHead(500);
- res.end("Internal Server Error");
- }
- },
- );
+ handleStatic(
+ req,
+ res,
+ dirAbs,
+ staticMiddleware,
+ injectionOpts,
+ rejectPrefixes,
+ ).catch((err) => {
+ console.error(`Static handler error for ${req.url}:`, err);
+ if (!res.headersSent) {
+ res.writeHead(500);
+ res.end("Internal Server Error");
+ }
+ });
});
server.on("upgrade", (req, socket, head) => {
- const backend = route(req.url);
+ const backend = route(req.url ?? "/");
if (backend) {
- proxyWebSocket(req, socket, head, backend);
+ proxy.proxyWebSocket(req, socket, head, backend);
return;
}
socket.destroy();
});
+ server.on("close", uninstallDiagnostics);
return new Promise((resolveListen) => {
server.listen(config.port, config.host, () => {