chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 13:39:12 +08:00
commit d8dcd5f6d1
8604 changed files with 2479390 additions and 0 deletions
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env node
/**
* OmniRoute — Dev-startup native SQLite ABI guard.
*
* `better-sqlite3` is a native addon compiled for a specific Node.js ABI
* (NODE_MODULE_VERSION). This project supports both Node 22 (ABI 127) and
* Node 24 (ABI 137); switching between them via nvm leaves the previously
* built `better_sqlite3.node` incompatible, so `npm run dev` crashes during
* bootstrap with:
*
* "The module '…/better_sqlite3.node' was compiled against a different
* Node.js version using NODE_MODULE_VERSION 127. This version of Node.js
* requires NODE_MODULE_VERSION 137."
*
* `postinstall.mjs` only fixes the published standalone bundle and only runs
* on `npm install` — it does NOT cover "cloned repo, switched Node, ran dev".
*
* This guard probes the root binary against the *current* Node ABI and, ONLY
* when it detects a genuine ABI mismatch, runs `npm rebuild better-sqlite3`
* once. The healthy path (matching ABI) does no work, so dev startup stays
* fast. Unrelated errors are NOT swallowed — they fall through so the normal
* bootstrap surfaces them.
*/
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, "..", "..");
export const SQLITE_BINARY = join(
ROOT,
"node_modules",
"better-sqlite3",
"build",
"Release",
"better_sqlite3.node"
);
/**
* Whether an error message indicates a native-addon ABI / load mismatch
* (as opposed to an unrelated runtime error such as a missing table).
* Mirrors the detection in src/lib/db/core.ts::isNativeSqliteLoadError.
* @param {unknown} message
* @returns {boolean}
*/
export function isNativeAbiMismatch(message) {
const m = String(message ?? "");
return (
m.includes("NODE_MODULE_VERSION") ||
m.includes("was compiled against a different Node.js version") ||
m.includes("Module did not self-register") ||
m.includes("ERR_DLOPEN_FAILED") ||
m.includes("Could not locate the bindings file")
);
}
/** Probe a native binary against the current Node ABI without polluting the require cache. */
function probeLoad(binaryPath) {
process.dlopen({ exports: {} }, binaryPath);
}
/** Default rebuild: `npm rebuild better-sqlite3` at the repo root (no shell interpolation). */
function defaultRebuild() {
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
const result = spawnSync(npm, ["rebuild", "better-sqlite3"], { cwd: ROOT, stdio: "inherit" });
return result.status === 0;
}
/**
* Ensure better-sqlite3 loads under the current Node. Rebuilds once on ABI
* mismatch. Returns a result object; never throws for the mismatch path.
*
* @param {{ logger?: Pick<Console,"warn"|"error"|"log">, rebuild?: () => boolean, probe?: (p: string) => void, binaryPath?: string }} [opts]
* @returns {{ ok: boolean, rebuilt: boolean, error?: unknown }}
*/
export function ensureNativeSqlite(opts = {}) {
const {
logger = console,
rebuild = defaultRebuild,
probe = probeLoad,
binaryPath = SQLITE_BINARY,
} = opts;
// Nothing built yet (fresh clone before install) — let install/bootstrap handle it.
if (!existsSync(binaryPath)) return { ok: true, rebuilt: false };
try {
probe(binaryPath);
return { ok: true, rebuilt: false };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (!isNativeAbiMismatch(message)) {
// Not an ABI problem — do not mask it; bootstrap will surface the real error.
return { ok: false, rebuilt: false, error };
}
logger.warn(
`[dev] better-sqlite3 was built for a different Node ABI than ${process.version}` +
"rebuilding (one-time)…"
);
if (!rebuild()) {
logger.error(
"[dev] Automatic 'npm rebuild better-sqlite3' failed. Run it manually:\n" +
" npm rebuild better-sqlite3"
);
return { ok: false, rebuilt: false };
}
logger.log("[dev] better-sqlite3 rebuilt for the current Node. Continuing startup.");
return { ok: true, rebuilt: true };
}
}
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env node
/**
* Docker healthcheck script for OmniRoute.
* Probes the /api/monitoring/health endpoint on the dashboard port.
* Used by Dockerfile and docker-compose files.
*
* #3151 — in some Docker network setups the server binds to a container IP and
* a probe against `127.0.0.1` is not reachable, while `localhost`/`::1` (or vice
* versa) is. The previous version probed ONLY `127.0.0.1` and swallowed every
* error, so the container was reported `unhealthy` with an empty, undiagnosable
* `State.Health[].Output`. We now try an ordered list of hosts and surface the
* last error on total failure.
*
* Bridge Network Fix: Also probes the container's internal bridge IP (e.g., 172.17.0.2)
* to handle Docker network setups that isolate loopback interfaces.
*/
import { pathToFileURL } from "node:url";
import { networkInterfaces } from "node:os";
const DEFAULT_HOSTS = ["127.0.0.1", "localhost", "::1"];
const DEFAULT_TIMEOUT_MS = 4000;
/**
* Get the primary non-loopback IPv4 address (container internal IP).
* Falls back to null if unable to determine.
*/
function getContainerInternalIP() {
try {
const interfaces = networkInterfaces();
for (const [name, addrs] of Object.entries(interfaces)) {
// Skip loopback and docker0, prioritize eth0/veth interfaces
if (name.startsWith("lo") || name === "docker0") continue;
const ipv4 = addrs?.find((a) => a.family === "IPv4" && !a.internal);
if (ipv4) return ipv4.address;
}
} catch {
// silently ignore if unable to read interfaces
}
return null;
}
/**
* Build the health URL for a host, bracketing IPv6 literals (e.g. `::1`).
* @param {string} host
* @param {string|number} port
*/
function healthUrl(host, port) {
const hostPart = host.includes(":") ? `[${host}]` : host;
return `http://${hostPart}:${port}/api/monitoring/health`;
}
/**
* Probe the health endpoint across an ordered list of hosts. Resolves with the
* first host that returns a 2xx response; rejects with the last error if every
* host fails. Each attempt is bounded by a per-host timeout so one unreachable
* host cannot hang the whole probe.
*
* @param {object} opts
* @param {string|number} opts.port
* @param {string[]} [opts.hosts]
* @param {typeof fetch} [opts.fetchImpl]
* @param {number} [opts.timeoutMs]
* @returns {Promise<string>} the host that succeeded
*/
export async function probeHealth({
port,
hosts = DEFAULT_HOSTS,
fetchImpl = fetch,
timeoutMs = DEFAULT_TIMEOUT_MS,
} = {}) {
let lastError = new Error("no hosts to probe");
for (const host of hosts) {
try {
const res = await fetchImpl(healthUrl(host, port), {
signal: AbortSignal.timeout(timeoutMs),
});
if (res.ok) return host;
lastError = new Error(`${host}: HTTP ${res.status}`);
} catch (err) {
lastError = new Error(`${host}: ${err instanceof Error ? err.message : String(err)}`);
}
}
throw lastError;
}
async function main() {
const port = process.env.DASHBOARD_PORT || process.env.PORT || "20128";
// Build host list: defaults + detected container bridge IP
const hosts = [...DEFAULT_HOSTS];
const containerIP = getContainerInternalIP();
if (containerIP && !hosts.includes(containerIP)) {
hosts.push(containerIP);
}
try {
await probeHealth({ port, hosts });
process.exit(0);
} catch (err) {
// Surface the failure so `docker inspect ... .State.Health[].Output` is
// diagnostic instead of empty (#3151).
process.stderr.write(`healthcheck failed: ${err instanceof Error ? err.message : err}\n`);
process.exit(1);
}
}
// Only auto-run when invoked as the entrypoint (so importing the helper in
// tests does not trigger a real probe + process.exit).
const isEntrypoint =
Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isEntrypoint) {
main();
}
+104
View File
@@ -0,0 +1,104 @@
"use strict";
const http = require("node:http");
const HIGH_RISK_METHOD_RULES = [
[/^\/api\/auth\/login\/?$/, ["POST"]],
[/^\/api\/auth\/logout\/?$/, ["POST"]],
[/^\/api\/keys\/?$/, ["GET", "POST"]],
[/^\/api\/keys\/[^/]+\/?$/, ["GET", "PATCH", "DELETE"]],
[/^\/api\/keys\/[^/]+\/devices\/?$/, ["GET"]],
];
let installed = false;
function getPathname(req) {
const rawUrl = typeof req?.url === "string" && req.url ? req.url : "/";
try {
return new URL(rawUrl, "http://localhost").pathname;
} catch {
return rawUrl.split("?")[0] || "/";
}
}
function getAllowedMethods(pathname) {
for (const [pattern, methods] of HIGH_RISK_METHOD_RULES) {
if (pattern.test(pathname)) return methods;
}
return null;
}
function getAllowHeader(pathname) {
const methods = getAllowedMethods(pathname);
return methods ? methods.join(", ") : null;
}
// Methods undici/fetch cannot represent: Next's middleware adapter throws
// `TypeError: 'TRACE' HTTP method is unsupported.` while building the Request,
// which surfaces as an unhandled 500 on EVERY route (caught by the dast-smoke
// Schemathesis negative tests). Reject them up-front with a clean 405.
const UNSUPPORTED_METHODS = new Set(["TRACE", "TRACK", "CONNECT"]);
function maybeHandleDisallowedMethod(req, res) {
const method = typeof req?.method === "string" ? req.method.toUpperCase() : "";
const pathname = getPathname(req);
if (UNSUPPORTED_METHODS.has(method)) {
res.statusCode = 405;
res.setHeader("Allow", getAllowHeader(pathname) || "GET, POST, OPTIONS");
res.setHeader("Cache-Control", "no-store");
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(
JSON.stringify({
error: {
code: "METHOD_NOT_ALLOWED",
message: `${method} is not allowed`,
},
})
);
return true;
}
const methods = getAllowedMethods(pathname);
if (!methods || method === "OPTIONS" || methods.includes(method)) return false;
res.statusCode = 405;
res.setHeader("Allow", methods.join(", "));
res.setHeader("Cache-Control", "no-store");
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(
JSON.stringify({
error: {
code: "METHOD_NOT_ALLOWED",
message: `${method || "Method"} is not allowed`,
},
})
);
return true;
}
function wrapRequestListenerWithMethodGuard(listener) {
return function methodGuardRequestHandler(req, res) {
if (maybeHandleDisallowedMethod(req, res)) return;
return listener.call(this, req, res);
};
}
function installHttpMethodGuard() {
if (installed) return;
installed = true;
const originalCreateServer = http.createServer.bind(http);
http.createServer = function createServerWithMethodGuard(...args) {
const lastFnIdx = args.map((arg) => typeof arg === "function").lastIndexOf(true);
if (lastFnIdx >= 0) {
args[lastFnIdx] = wrapRequestListenerWithMethodGuard(args[lastFnIdx]);
}
return originalCreateServer(...args);
};
}
module.exports = {
getAllowHeader,
maybeHandleDisallowedMethod,
wrapRequestListenerWithMethodGuard,
installHttpMethodGuard,
};
+76
View File
@@ -0,0 +1,76 @@
import { randomUUID } from "node:crypto";
/**
* Trusted peer-IP stamping for the custom Node HTTP servers.
*
* The Next.js middleware runtime (proxy.ts → runAuthzPipeline) exposes NO socket
* or peer IP — only request headers, ALL of which are client-controlled. The
* LOCAL_ONLY route guard (spawn-capable routes) must decide locality from the
* real TCP peer, never from the spoofable Host header.
*
* Our custom servers DO have the real `req.socket.remoteAddress`. They stamp it
* into PEER_IP_HEADER as `<token>|<ip>`, where <token> is a per-process secret
* (OMNIROUTE_PEER_STAMP_TOKEN). Any client-supplied value of PEER_IP_HEADER is
* deleted first, so a remote caller cannot pre-populate it. The middleware
* (src/server/authz/policies/management.ts → resolveStampedPeer) trusts the IP
* ONLY when the token matches this process's secret; otherwise it fails closed.
*
* Keep PEER_IP_HEADER in sync with PEER_IP_HEADER in
* src/server/authz/headers.ts (the TS side cannot import this .mjs).
*/
export const PEER_IP_HEADER = "x-omniroute-peer-ip";
/**
* Companion header to PEER_IP_HEADER: `<token>|1` when the inbound TCP request
* carried forwarding headers (`x-forwarded-for` / `x-real-ip`), `<token>|0`
* otherwise. Required so the middleware can tell that a loopback socket is the
* reverse-proxy hop (nginx / Caddy / Cloudflare Tunnel) and NOT trust it as
* local — without this, a leaked JWT over a public tunnel would reach the
* LOCAL_ONLY routes that spawn child processes (Hard Rules #15 + #17;
* port of upstream decolua/9router commit da667836).
*
* Keep VIA_PROXY_HEADER in sync with VIA_PROXY_HEADER in
* src/server/authz/headers.ts (the TS side cannot import this .mjs).
*/
export const VIA_PROXY_HEADER = "x-omniroute-via-proxy";
/** Generate (once) and return the per-process stamp token, persisting it in env
* so the middleware running in the same process reads the identical value. */
export function ensurePeerStampToken() {
process.env.OMNIROUTE_PEER_STAMP_TOKEN ||= randomUUID();
return process.env.OMNIROUTE_PEER_STAMP_TOKEN;
}
/** Strip any client-supplied PEER_IP_HEADER + VIA_PROXY_HEADER and stamp the
* real TCP peer IP plus a token-protected via-proxy marker. Never throws — a
* stamping failure must not block a request (it degrades to "locality
* unknown" → fail closed in the middleware). */
export function stampPeerIp(req) {
try {
if (!req || !req.headers) return;
// Node lowercases incoming header names; delete kills any client value.
delete req.headers[PEER_IP_HEADER];
delete req.headers[VIA_PROXY_HEADER];
const ip = req.socket && req.socket.remoteAddress;
if (ip) {
const token = ensurePeerStampToken();
req.headers[PEER_IP_HEADER] = `${token}|${ip}`;
// Forwarding headers present = request arrived via a reverse proxy; the
// loopback socket is the proxy hop, not the end-user, so it must not be
// trusted as local. Token-prefix the marker so a remote caller cannot
// forge it (or its absence) on a non-proxied request.
const viaProxy = !!(req.headers["x-forwarded-for"] || req.headers["x-real-ip"]);
req.headers[VIA_PROXY_HEADER] = `${token}|${viaProxy ? "1" : "0"}`;
}
} catch {
/* never block a request on peer stamping */
}
}
/** Wrap a Node request listener so every request is peer-stamped first. */
export function wrapRequestListenerWithPeerStamp(listener) {
return function peerStampingRequestHandler(req, res) {
stampPeerIp(req);
return listener.call(this, req, res);
};
}
+907
View File
@@ -0,0 +1,907 @@
import { createHash, randomUUID } from "node:crypto";
import { createRequire } from "node:module";
import { STATUS_CODES } from "node:http";
const _wreqRequire = createRequire(import.meta.url);
let _websocketFn = null;
let _wreqChecked = false;
function getWebSocketTransport() {
if (_wreqChecked) return _websocketFn;
_wreqChecked = true;
try {
const mod = _wreqRequire("wreq-js");
_websocketFn = typeof mod.websocket === "function" ? mod.websocket : null;
} catch {
_websocketFn = null;
}
return _websocketFn;
}
export const RESPONSES_WS_PUBLIC_PATHS = new Set([
"/responses",
"/v1/responses",
"/api/v1/responses",
]);
const INTERNAL_ROUTE = "/api/internal/codex-responses-ws";
const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
const WS_QUERY_TOKEN_KEYS = ["api_key", "token", "access_token"];
const textDecoder = new TextDecoder();
const DEFAULT_MAX_WS_BUFFER_BYTES = 16 * 1024 * 1024;
const DEFAULT_MAX_WS_MESSAGE_BYTES = 16 * 1024 * 1024;
class WebSocketInputTooLargeError extends Error {
constructor(message, reason = "message_too_large") {
super(message);
this.name = "WebSocketInputTooLargeError";
this.closeCode = 1009;
this.reason = reason;
}
}
function normalizePositiveInteger(value, fallback) {
const parsed = Number(value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
}
function isText(value) {
return typeof value === "string" && value.length > 0;
}
function isRecord(value) {
return value && typeof value === "object" && !Array.isArray(value);
}
function jsonStringifySafe(value) {
try {
return JSON.stringify(value);
} catch {
return JSON.stringify({
type: "response.failed",
response: {
status: "failed",
error: {
code: "serialization_failed",
message: "Failed to serialize WebSocket payload",
},
},
});
}
}
function parseJsonRecord(value) {
try {
const parsed = typeof value === "string" ? JSON.parse(value) : value;
return isRecord(parsed) ? parsed : null;
} catch {
return null;
}
}
function toFiniteNumber(value) {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : 0;
}
function toStringOrNull(value) {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function buildFailurePayload(code, message) {
return {
type: "response.failed",
response: {
id: null,
status: "failed",
error: {
code,
message,
},
},
};
}
function getResponseErrorStatus(error) {
if (!isRecord(error)) return null;
const candidates = [
error.status,
error.status_code,
error.statusCode,
error.code === "usage_limit_reached" ? 429 : null,
];
for (const candidate of candidates) {
const status = Number(candidate);
if (Number.isInteger(status) && status >= 400 && status <= 599) return status;
}
return null;
}
function getTerminalResponseEvent(rawData) {
const message = parseJsonRecord(rawData);
if (!message) return null;
const type = toStringOrNull(message.type) || "";
const response = isRecord(message.response) ? message.response : {};
const statusText = toStringOrNull(response.status) || "";
if (type === "response.completed" || type === "response.done" || statusText === "completed") {
return {
status: 200,
success: true,
terminalMessage: message,
responseBody: response,
};
}
if (type === "response.failed" || type === "response.error" || statusText === "failed") {
const error = isRecord(response.error)
? response.error
: isRecord(message.error)
? message.error
: null;
return {
status: getResponseErrorStatus(error) || 500,
success: false,
errorCode: toStringOrNull(error?.code) || "upstream_response_failed",
errorMessage:
toStringOrNull(error?.message) ||
toStringOrNull(response.error) ||
"Codex upstream response failed",
terminalMessage: message,
responseBody: response,
};
}
return null;
}
export function isResponsesWsPath(pathname) {
return RESPONSES_WS_PUBLIC_PATHS.has(pathname);
}
export function encodeWsFrame(opcode, payload = Buffer.alloc(0)) {
const payloadBuffer = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
const length = payloadBuffer.length;
let header;
if (length < 126) {
header = Buffer.allocUnsafe(2);
header[1] = length;
} else if (length <= 0xffff) {
header = Buffer.allocUnsafe(4);
header[1] = 126;
header.writeUInt16BE(length, 2);
} else {
header = Buffer.allocUnsafe(10);
header[1] = 127;
header.writeBigUInt64BE(BigInt(length), 2);
}
header[0] = 0x80 | (opcode & 0x0f);
return Buffer.concat([header, payloadBuffer]);
}
export function decodeClientFrames(
buffer,
{ maxPayloadBytes = DEFAULT_MAX_WS_MESSAGE_BYTES } = {}
) {
const frames = [];
let offset = 0;
while (buffer.length - offset >= 2) {
const byte1 = buffer[offset];
const byte2 = buffer[offset + 1];
const fin = (byte1 & 0x80) !== 0;
const opcode = byte1 & 0x0f;
const masked = (byte2 & 0x80) !== 0;
let payloadLength = byte2 & 0x7f;
let headerLength = 2;
if (!masked) {
throw new Error("Client WebSocket frames must be masked");
}
if (payloadLength === 126) {
if (buffer.length - offset < 4) break;
payloadLength = buffer.readUInt16BE(offset + 2);
headerLength = 4;
} else if (payloadLength === 127) {
if (buffer.length - offset < 10) break;
const bigLength = buffer.readBigUInt64BE(offset + 2);
if (bigLength > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new WebSocketInputTooLargeError("WebSocket payload too large");
}
payloadLength = Number(bigLength);
headerLength = 10;
}
if (payloadLength > maxPayloadBytes) {
throw new WebSocketInputTooLargeError("WebSocket payload exceeds configured limit");
}
const totalLength = headerLength + 4 + payloadLength;
if (buffer.length - offset < totalLength) break;
const mask = buffer.subarray(offset + headerLength, offset + headerLength + 4);
const payload = Buffer.from(buffer.subarray(offset + headerLength + 4, offset + totalLength));
for (let index = 0; index < payload.length; index += 1) {
payload[index] ^= mask[index % 4];
}
frames.push({ fin, opcode, payload });
offset += totalLength;
}
return {
frames,
remaining: buffer.subarray(offset),
};
}
const WRITE_ERROR_RESERVED_HEADERS = new Set([
// Framing — must never collide with our Content-Length default.
"transfer-encoding",
"content-length",
"content-type",
"connection",
"keep-alive",
// Next pipeline / security headers are meaningless on a raw JSON error socket
// and must not leak from a forwarded internal-fetch response.
"content-security-policy",
"x-frame-options",
"x-content-type-options",
"referrer-policy",
"permissions-policy",
"strict-transport-security",
"x-omniroute-route-class",
"x-request-id",
"date",
]);
export function writeHttpError(socket, status, body, headers = {}) {
if (!socket.writable || socket.destroyed) return;
const bodyBuffer = Buffer.from(body || "", "utf8");
const statusText = STATUS_CODES[status] || "Error";
// Strip any caller-supplied framing / duplicate-prone headers (case-insensitive)
// so our Content-Length/Connection/Content-Type defaults always win. Forwarding
// an upstream fetch's chunked Transfer-Encoding here would collide with
// Content-Length ("Transfer-Encoding can't be present with Content-Length") and
// break the client's HTTP parser on a raw upgrade socket.
const safeHeaders = {};
for (const [name, value] of Object.entries(headers || {})) {
if (!WRITE_ERROR_RESERVED_HEADERS.has(String(name).toLowerCase())) {
safeHeaders[name] = value;
}
}
const responseHeaders = {
Connection: "close",
"Content-Length": String(bodyBuffer.length),
"Content-Type": "application/json; charset=utf-8",
...safeHeaders,
};
const head = [
`HTTP/1.1 ${status} ${statusText}`,
...Object.entries(responseHeaders).map(([name, value]) => `${name}: ${value}`),
"",
"",
].join("\r\n");
socket.write(head);
socket.end(bodyBuffer);
}
function getAuthHeaders(requestUrl, requestHeaders) {
const headers = {};
if (isText(requestHeaders.authorization)) {
headers.authorization = requestHeaders.authorization;
} else {
const url = new URL(requestUrl, "http://omniroute.local");
for (const key of WS_QUERY_TOKEN_KEYS) {
const value = url.searchParams.get(key);
if (isText(value)) {
headers.authorization = `Bearer ${value.trim()}`;
break;
}
}
}
if (isText(requestHeaders.cookie)) headers.cookie = requestHeaders.cookie;
if (isText(requestHeaders.origin)) headers.origin = requestHeaders.origin;
if (isText(requestHeaders["x-forwarded-for"])) {
headers["x-forwarded-for"] = requestHeaders["x-forwarded-for"];
}
return headers;
}
function getResponseCreatePayload(message) {
if (!message || typeof message !== "object" || Array.isArray(message)) return null;
if (message.type !== "response.create") return null;
if (
message.response &&
typeof message.response === "object" &&
!Array.isArray(message.response)
) {
return message.response;
}
if (message.body && typeof message.body === "object" && !Array.isArray(message.body)) {
return message.body;
}
if (message.payload && typeof message.payload === "object" && !Array.isArray(message.payload)) {
return message.payload;
}
const { type, ...payload } = message;
return payload;
}
function withPreparedResponseCreate(message, preparedBody) {
const next = { ...message };
if (
message.response &&
typeof message.response === "object" &&
!Array.isArray(message.response)
) {
next.response = preparedBody;
} else if (message.body && typeof message.body === "object" && !Array.isArray(message.body)) {
next.body = preparedBody;
} else if (
message.payload &&
typeof message.payload === "object" &&
!Array.isArray(message.payload)
) {
next.payload = preparedBody;
} else {
return { type: "response.create", ...preparedBody };
}
return next;
}
async function callInternal(fetchImpl, baseUrl, bridgeSecret, action, payload) {
const response = await fetchImpl(new URL(INTERNAL_ROUTE, baseUrl), {
method: "POST",
headers: {
"content-type": "application/json",
"x-omniroute-ws-bridge-secret": bridgeSecret,
},
body: JSON.stringify({ action, ...payload }),
});
const text = await response.text();
let json = null;
try {
json = text ? JSON.parse(text) : null;
} catch {
json = null;
}
return { ok: response.ok, status: response.status, text, json, headers: response.headers };
}
class ResponsesWsSession {
constructor({
baseUrl,
bridgeSecret,
fetchImpl,
socket,
requestHeaders,
requestUrl,
wsFactory,
pingIntervalMs,
idleTimeoutMs,
maxBufferBytes,
maxMessageBytes,
}) {
this.baseUrl = baseUrl;
this.bridgeSecret = bridgeSecret;
this.fetchImpl = fetchImpl;
this.socket = socket;
this.requestHeaders = requestHeaders;
this.requestUrl = requestUrl;
this.wsFactory = wsFactory;
this.pingIntervalMs = pingIntervalMs;
this.idleTimeoutMs = idleTimeoutMs;
this.maxBufferBytes = normalizePositiveInteger(maxBufferBytes, DEFAULT_MAX_WS_BUFFER_BYTES);
this.maxMessageBytes = normalizePositiveInteger(maxMessageBytes, DEFAULT_MAX_WS_MESSAGE_BYTES);
this.sessionId = randomUUID();
this.startedAt = Date.now();
this.closed = false;
this.buffer = Buffer.alloc(0);
this.fragmentOpcode = null;
this.fragmentParts = [];
this.fragmentBytes = 0;
this.processing = Promise.resolve();
this.upstream = null;
this.upstreamReady = null;
this.firstResponseBody = null;
this.preparedContext = null;
this.historyLogged = false;
this.lastSeenAt = Date.now();
this.pingTimer = setInterval(() => {
if (this.closed) return;
const idleForMs = Date.now() - this.lastSeenAt;
if (idleForMs >= this.idleTimeoutMs) {
this.close(1001, "idle_timeout");
return;
}
this.sendFrame(0x9);
}, this.pingIntervalMs);
this.socket.setNoDelay(true);
this.socket.on("data", (chunk) => this.enqueueData(chunk));
this.socket.on("close", () => this.dispose());
this.socket.on("end", () => this.dispose());
this.socket.on("error", () => this.dispose());
}
enqueueData(chunk) {
this.processing = this.processing
.then(() => this.onData(chunk))
.catch((error) => {
if (this.closed) return;
const isTooLarge =
error instanceof WebSocketInputTooLargeError || error?.closeCode === 1009;
this.sendFailure(
isTooLarge ? "message_too_large" : "frame_decode_failed",
error instanceof Error ? error.message : String(error)
);
this.close(
isTooLarge ? 1009 : 1011,
isTooLarge ? error.reason || "message_too_large" : "frame_decode_failed"
);
});
}
cleanupBuffers() {
this.buffer = Buffer.alloc(0);
this.fragmentOpcode = null;
this.fragmentParts = [];
this.fragmentBytes = 0;
}
sendFrame(opcode, payload) {
if (this.closed || this.socket.destroyed) return;
this.socket.write(encodeWsFrame(opcode, payload));
}
sendJson(payload) {
this.sendFrame(0x1, Buffer.from(jsonStringifySafe(payload), "utf8"));
}
sendFailure(code, message) {
const payload = buildFailurePayload(code, message);
this.sendJson(payload);
return payload;
}
async onData(chunk) {
if (this.closed) return;
this.lastSeenAt = Date.now();
if (this.buffer.length + chunk.length > this.maxBufferBytes) {
throw new WebSocketInputTooLargeError("WebSocket input buffer exceeds configured limit");
}
this.buffer = Buffer.concat([this.buffer, chunk]);
const parsed = decodeClientFrames(this.buffer, { maxPayloadBytes: this.maxMessageBytes });
this.buffer = parsed.remaining;
if (this.buffer.length > this.maxBufferBytes) {
throw new WebSocketInputTooLargeError("WebSocket input buffer exceeds configured limit");
}
for (const frame of parsed.frames) {
if (this.closed) return;
await this.handleFrame(frame);
}
}
async handleFrame(frame) {
switch (frame.opcode) {
case 0x0:
if (this.fragmentOpcode === null) {
this.sendFailure("unexpected_continuation", "Unexpected continuation frame");
return;
}
this.fragmentBytes += frame.payload.length;
if (this.fragmentBytes > this.maxMessageBytes) {
throw new WebSocketInputTooLargeError(
"Fragmented WebSocket message exceeds configured limit"
);
}
this.fragmentParts.push(frame.payload);
if (frame.fin) {
const payload = Buffer.concat(this.fragmentParts);
const opcode = this.fragmentOpcode;
this.fragmentOpcode = null;
this.fragmentParts = [];
this.fragmentBytes = 0;
await this.handleDataFrame(opcode, payload);
}
return;
case 0x1:
case 0x2:
if (!frame.fin) {
this.fragmentOpcode = frame.opcode;
this.fragmentParts = [frame.payload];
this.fragmentBytes = frame.payload.length;
if (this.fragmentBytes > this.maxMessageBytes) {
throw new WebSocketInputTooLargeError(
"Fragmented WebSocket message exceeds configured limit"
);
}
return;
}
await this.handleDataFrame(frame.opcode, frame.payload);
return;
case 0x8:
this.close();
return;
case 0x9:
this.sendFrame(0xa, frame.payload);
return;
case 0xa:
this.lastSeenAt = Date.now();
return;
default:
this.sendFailure("unsupported_opcode", `Unsupported opcode ${frame.opcode}`);
}
}
async handleDataFrame(opcode, payload) {
if (payload.length > this.maxMessageBytes) {
throw new WebSocketInputTooLargeError("WebSocket message exceeds configured limit");
}
if (opcode !== 0x1) {
this.sendFailure("unsupported_payload", "Only UTF-8 text messages are supported");
return;
}
const raw = textDecoder.decode(payload);
let message;
try {
message = JSON.parse(raw);
} catch {
this.sendFailure("invalid_json", "WebSocket message must be valid JSON");
return;
}
await this.forwardClientMessage(message);
}
async ensureUpstream(firstMessage) {
if (this.upstreamReady) return this.upstreamReady;
this.upstreamReady = (async () => {
const responseBody = getResponseCreatePayload(firstMessage);
if (responseBody === null) {
throw new Error("First Responses WebSocket message must be response.create");
}
this.firstResponseBody ||= responseBody;
const prepared = await callInternal(
this.fetchImpl,
this.baseUrl,
this.bridgeSecret,
"prepare",
{
requestUrl: this.requestUrl,
headers: getAuthHeaders(this.requestUrl, this.requestHeaders),
message: firstMessage,
response: responseBody,
}
);
if (!prepared.ok) {
const message =
prepared.json?.error?.message ||
prepared.json?.message ||
prepared.text ||
"Codex WS prepare failed";
const code = prepared.json?.error?.code || "codex_ws_prepare_failed";
const error = new Error(message);
error.code = code;
error.status = prepared.status;
throw error;
}
this.preparedContext = {
upstreamUrl: toStringOrNull(prepared.json?.upstreamUrl),
connectionId: toStringOrNull(prepared.json?.connectionId),
account: toStringOrNull(prepared.json?.account),
provider: toStringOrNull(prepared.json?.provider) || "codex",
model: toStringOrNull(prepared.json?.model) || toStringOrNull(responseBody.model),
requestedModel: toStringOrNull(responseBody.model),
serviceTier:
toStringOrNull(responseBody.service_tier) || toStringOrNull(responseBody.serviceTier),
};
const wsOptions = {
// #5591: chrome_149 is not a wreq-js 2.3.1 profile (max chrome_147); the
// prepare route now sends chrome_142, this fallback matches it.
browser: prepared.json.browser || "chrome_142",
os: prepared.json.os || "windows",
headers: prepared.json.headers || {},
};
// #5611: forward the configured proxy so the upstream WS connect honors the
// Proxy Registry in no-direct-egress deployments.
if (prepared.json.proxy) wsOptions.proxy = prepared.json.proxy;
const upstream = await this.wsFactory(prepared.json.upstreamUrl, wsOptions);
upstream.onmessage = (event) => {
if (this.closed) return;
const data =
typeof event.data === "string" ? event.data : Buffer.from(event.data).toString("utf8");
const terminalEvent = getTerminalResponseEvent(data);
if (terminalEvent) {
void this.persistHistory(terminalEvent);
}
this.sendFrame(0x1, Buffer.from(data, "utf8"));
};
upstream.onerror = (event) => {
if (this.closed) return;
const errorMessage = event.message || "Codex upstream WebSocket error";
const failurePayload = this.sendFailure("upstream_websocket_error", errorMessage);
void this.persistHistory({
status: 502,
success: false,
errorCode: "upstream_websocket_error",
errorMessage,
terminalMessage: failurePayload,
});
};
upstream.onclose = (event) => {
if (this.closed) return;
void this.persistHistory({
status: event.code === 1000 ? 499 : 502,
success: false,
errorCode: "upstream_websocket_closed",
errorMessage: event.reason || "Codex upstream WebSocket closed before completion",
terminalMessage: buildFailurePayload(
"upstream_websocket_closed",
event.reason || "Codex upstream WebSocket closed before completion"
),
});
this.close(event.code || 1000, event.reason || "upstream_closed");
};
this.upstream = upstream;
return {
upstream,
firstMessage: withPreparedResponseCreate(firstMessage, prepared.json.response),
};
})();
return this.upstreamReady;
}
async forwardClientMessage(message) {
try {
if (!this.upstream) {
const { upstream, firstMessage } = await this.ensureUpstream(message);
upstream.send(jsonStringifySafe(firstMessage));
return;
}
this.upstream.send(jsonStringifySafe(message));
} catch (error) {
const code = error?.code || "upstream_websocket_connect_failed";
const messageText = error instanceof Error ? error.message : String(error);
const failurePayload = this.sendFailure(code, messageText);
void this.persistHistory({
status: Number.isInteger(error?.status) ? error.status : 502,
success: false,
errorCode: code,
errorMessage: messageText,
terminalMessage: failurePayload,
});
this.close(1011, "upstream_connect_failed");
}
}
async persistHistory({
status = 200,
success = true,
errorCode = null,
errorMessage = null,
terminalMessage = null,
responseBody = null,
} = {}) {
if (this.historyLogged || !this.firstResponseBody) return;
this.historyLogged = true;
const finishedAt = Date.now();
try {
await callInternal(this.fetchImpl, this.baseUrl, this.bridgeSecret, "log", {
sessionId: this.sessionId,
transport: "responses_websocket",
requestUrl: this.requestUrl,
headers: getAuthHeaders(this.requestUrl, this.requestHeaders),
path: new URL(this.requestUrl || "/v1/responses", "http://omniroute.local").pathname,
startedAt: new Date(this.startedAt).toISOString(),
completedAt: new Date(finishedAt).toISOString(),
durationMs: Math.max(0, finishedAt - this.startedAt),
status: toFiniteNumber(status),
success,
errorCode,
errorMessage,
clientRequest: this.firstResponseBody,
terminalMessage,
responseBody,
sourceFormat: "openai-responses",
targetFormat: "openai-responses",
...this.preparedContext,
});
} catch {
// History logging must never break an already-established WebSocket session.
}
}
close(code = 1000, reason = "normal_closure") {
if (this.closed) return;
this.closed = true;
clearInterval(this.pingTimer);
this.cleanupBuffers();
try {
this.upstream?.close?.(code, reason);
} catch {
// ignore close races
}
const reasonBuffer = Buffer.from(reason, "utf8");
const payload = Buffer.allocUnsafe(2 + reasonBuffer.length);
payload.writeUInt16BE(code, 0);
reasonBuffer.copy(payload, 2);
if (!this.socket.destroyed && this.socket.writable) {
this.socket.write(encodeWsFrame(0x8, payload));
}
this.socket.end();
setTimeout(() => {
if (!this.socket.destroyed) {
this.socket.destroy();
}
}, 50).unref?.();
}
dispose() {
if (this.closed) return;
this.closed = true;
clearInterval(this.pingTimer);
this.cleanupBuffers();
try {
this.upstream?.close?.(1000, "downstream_closed");
} catch {
// ignore close races
}
}
}
export function createResponsesWsProxy({
baseUrl,
bridgeSecret,
fetchImpl = fetch,
wsFactory = getWebSocketTransport(),
pingIntervalMs = 25000,
idleTimeoutMs = 90000,
maxBufferBytes = DEFAULT_MAX_WS_BUFFER_BYTES,
maxMessageBytes = DEFAULT_MAX_WS_MESSAGE_BYTES,
} = {}) {
if (!isText(baseUrl)) {
throw new Error("createResponsesWsProxy requires a baseUrl");
}
if (!isText(bridgeSecret)) {
throw new Error("createResponsesWsProxy requires a bridgeSecret");
}
return {
isResponsesWsPath,
async handleUpgrade(req, socket, head) {
const pathname = new URL(req.url || "/", baseUrl).pathname;
if (!isResponsesWsPath(pathname)) {
return false;
}
if (!wsFactory) {
writeHttpError(
socket,
503,
JSON.stringify({
error: {
message:
"Responses WebSocket proxy unavailable: wreq-js is not installed on this platform",
code: "wreq_js_unavailable",
},
})
);
return true;
}
const upgradeHeader = String(req.headers.upgrade || "").toLowerCase();
if (upgradeHeader !== "websocket") {
writeHttpError(
socket,
426,
JSON.stringify({
error: {
message: "Upgrade Required",
code: "upgrade_required",
},
}),
{ Upgrade: "websocket" }
);
return true;
}
try {
const auth = await callInternal(fetchImpl, baseUrl, bridgeSecret, "authenticate", {
requestUrl: req.url || pathname,
headers: getAuthHeaders(req.url || pathname, req.headers),
});
if (!auth.ok) {
// Do NOT forward the internal fetch's response headers onto the raw
// upgrade socket — they carry chunked transfer-encoding + Next security
// headers that collide with writeHttpError's Content-Length framing.
// The sanitized JSON body alone is enough for the client.
writeHttpError(socket, auth.status, auth.text || "{}");
return true;
}
const wsKey = req.headers["sec-websocket-key"];
if (!isText(wsKey)) {
writeHttpError(
socket,
400,
JSON.stringify({
error: {
message: "Missing sec-websocket-key header",
code: "bad_websocket_handshake",
},
})
);
return true;
}
const acceptKey = createHash("sha1").update(`${wsKey}${WS_GUID}`).digest("base64");
const headers = [
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${acceptKey}`,
"",
"",
].join("\r\n");
socket.write(headers);
if (head && head.length > 0) {
socket.unshift(head);
}
new ResponsesWsSession({
baseUrl,
bridgeSecret,
fetchImpl,
socket,
requestUrl: req.url || pathname,
requestHeaders: req.headers,
wsFactory,
pingIntervalMs,
idleTimeoutMs,
maxBufferBytes,
maxMessageBytes,
});
return true;
} catch (error) {
writeHttpError(
socket,
500,
JSON.stringify({
error: {
message: error instanceof Error ? error.message : String(error),
code: "responses_websocket_proxy_failed",
},
})
);
return true;
}
},
};
}
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { sanitizeColorEnv } from "../build/runtime-env.mjs";
function parsePort(value, fallback) {
const parsed = Number.parseInt(String(value), 10);
return Number.isFinite(parsed) && parsed > 0 && parsed <= 65535 ? parsed : fallback;
}
const explicitBaseUrl = process.env.OMNIROUTE_BASE_URL || "";
const isolatedPort = parsePort(
process.env.DASHBOARD_PORT || process.env.PORT,
22000 + (process.pid % 1000)
);
const isolatedDataDir =
process.env.DATA_DIR || join(process.cwd(), ".tmp", "ecosystem-data", String(process.pid));
const port = explicitBaseUrl ? null : isolatedPort;
const baseUrl = explicitBaseUrl || `http://127.0.0.1:${isolatedPort}`;
const healthUrl = `${baseUrl}/api/monitoring/health`;
const maxWaitMs = Number(process.env.ECOSYSTEM_SERVER_WAIT_MS || 180000);
const pollMs = 2000;
async function isServerReady() {
const timeout = AbortSignal.timeout(2000);
try {
const res = await fetch(healthUrl, { signal: timeout });
return res.ok;
} catch {
return false;
}
}
async function waitForServerReady() {
const maxAttempts = Math.ceil(maxWaitMs / pollMs);
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
if (await isServerReady()) {
return;
}
await delay(pollMs);
}
throw new Error(`Timed out waiting for ${healthUrl} after ${maxWaitMs}ms`);
}
async function main() {
let serverProcess = null;
let startedHere = false;
const testEnv = {
...sanitizeColorEnv(process.env),
DATA_DIR: isolatedDataDir,
...(explicitBaseUrl
? {}
: {
PORT: String(port),
DASHBOARD_PORT: String(port),
API_PORT: String(port),
OMNIROUTE_BASE_URL: baseUrl,
}),
OMNIROUTE_E2E_BOOTSTRAP_MODE: process.env.OMNIROUTE_E2E_BOOTSTRAP_MODE || "open",
REQUIRE_API_KEY: explicitBaseUrl ? process.env.REQUIRE_API_KEY : "false",
ENABLE_CLI_TOOLS: "true",
};
if (!(await isServerReady())) {
serverProcess = spawn(process.execPath, ["scripts/dev/run-next-playwright.mjs", "dev"], {
stdio: "inherit",
env: testEnv,
});
startedHere = true;
await waitForServerReady();
}
const vitestProcess = spawn(
process.execPath,
["./node_modules/vitest/vitest.mjs", "run", "tests/e2e/ecosystem.test.ts"],
{
stdio: "inherit",
env: testEnv,
}
);
const exitCode = await new Promise((resolve) => {
vitestProcess.on("exit", (code, signal) => {
if (signal) {
resolve(1);
return;
}
resolve(code ?? 1);
});
});
if (startedHere && serverProcess) {
serverProcess.kill("SIGTERM");
await delay(1000);
if (!serverProcess.killed) {
serverProcess.kill("SIGKILL");
}
}
process.exit(exitCode);
}
main().catch((error) => {
console.error("[test:ecosystem] Failed:", error?.message || error);
process.exit(1);
});
+298
View File
@@ -0,0 +1,298 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { cpSync, existsSync, mkdirSync, readdirSync, renameSync } from "node:fs";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import {
resolveRuntimePorts,
sanitizeColorEnv,
spawnWithForwardedSignals,
withRuntimePortEnv,
} from "../build/runtime-env.mjs";
import { bootstrapEnv } from "../build/bootstrap-env.mjs";
const mode = process.argv[2] === "start" ? "start" : "dev";
const cwd = process.cwd();
const appDir = join(cwd, "app");
const srcAppDir = join(cwd, "src", "app");
const appPage = join(appDir, "page.tsx");
const defaultBackupDir = join(cwd, "app.__qa_backup");
const backupDir = resolvePlaywrightAppBackupDir({
cwd,
baseBackupExists: existsSync(defaultBackupDir),
appDirExists: existsSync(appDir),
});
const usingAlternativeBackupDir = backupDir !== defaultBackupDir;
const buildScript = join(cwd, "scripts", "build", "build-next-isolated.mjs");
const standaloneServer = join(cwd, testDistDir(), "standalone", "server.js");
const rootStaticDir = join(cwd, testDistDir(), "static");
const rootPublicDir = join(cwd, "public");
const standaloneStaticDir = join(cwd, testDistDir(), "standalone", ".next", "static");
const standalonePublicDir = join(cwd, testDistDir(), "standalone", "public");
let appDirMoved = false;
function testDistDir() {
// Layer 1 moved the Next distDir default to .build/next; the Playwright
// `start` runner must resolve the standalone server under the same dir.
return process.env.NEXT_DIST_DIR || ".build/next";
}
function resolvePlaywrightDataDir({ cwd, env, pid = process.pid }) {
if (typeof env.DATA_DIR === "string" && env.DATA_DIR.trim().length > 0) {
return env.DATA_DIR;
}
return join(cwd, ".tmp", "playwright-data", String(pid));
}
export function resolvePlaywrightAppBackupDir({
cwd,
baseBackupExists,
appDirExists,
pid = process.pid,
now = Date.now(),
}) {
const baseBackupDir = join(cwd, "app.__qa_backup");
if (!baseBackupExists || !appDirExists) {
return baseBackupDir;
}
return join(cwd, `app.__qa_backup.${pid}.${now}`);
}
function shouldMoveAppDir() {
return existsSync(appDir) && !existsSync(appPage) && existsSync(srcAppDir);
}
export function directoryHasEntries(dirPath) {
try {
return readdirSync(dirPath).length > 0;
} catch {
return false;
}
}
export function standaloneAssetsNeedSync({
standaloneServerPath,
rootStaticDirPath,
standaloneStaticDirPath,
}) {
return (
existsSync(standaloneServerPath) &&
existsSync(rootStaticDirPath) &&
!directoryHasEntries(standaloneStaticDirPath)
);
}
export function syncStandaloneRuntimeAssets({
standaloneServerPath,
rootStaticDirPath,
standaloneStaticDirPath,
rootPublicDirPath,
standalonePublicDirPath,
log = console,
}) {
if (!existsSync(standaloneServerPath)) return false;
let changed = false;
if (existsSync(rootPublicDirPath) && !directoryHasEntries(standalonePublicDirPath)) {
cpSync(rootPublicDirPath, standalonePublicDirPath, {
recursive: true,
force: true,
});
changed = true;
}
if (existsSync(rootStaticDirPath) && !directoryHasEntries(standaloneStaticDirPath)) {
mkdirSync(dirname(standaloneStaticDirPath), {
recursive: true,
});
cpSync(rootStaticDirPath, standaloneStaticDirPath, {
recursive: true,
force: true,
});
changed = true;
}
if (changed) {
log.log("[Playwright WebServer] Rehydrated standalone static/public assets");
}
return changed;
}
function prepareAppDir() {
if (!shouldMoveAppDir()) return;
if (usingAlternativeBackupDir) {
console.warn(
"[Playwright WebServer] Existing app.__qa_backup detected; using a per-run backup dir instead."
);
}
renameSync(appDir, backupDir);
appDirMoved = true;
console.log("[Playwright WebServer] Temporarily moved app/ to app.__qa_backup");
}
function restoreAppDir() {
if (!appDirMoved) return;
if (!existsSync(backupDir) || existsSync(appDir)) return;
renameSync(backupDir, appDir);
console.log("[Playwright WebServer] Restored app/ directory");
}
const playwrightDataDir = resolvePlaywrightDataDir({
cwd,
env: process.env,
});
const bootstrapEnvVars = bootstrapEnv({
quiet: true,
dataDirOverride: playwrightDataDir,
});
const runtimePorts = resolveRuntimePorts(bootstrapEnvVars);
const bootstrapMode = process.env.OMNIROUTE_E2E_BOOTSTRAP_MODE || "auth";
const playwrightPassword =
process.env.OMNIROUTE_E2E_PASSWORD || process.env.INITIAL_PASSWORD || "omniroute-e2e-password";
const testServerEnv = {
...sanitizeColorEnv(bootstrapEnvVars),
...sanitizeColorEnv(process.env),
NODE_ENV: mode === "start" ? "production" : "development",
DATA_DIR: playwrightDataDir,
NEXT_PUBLIC_OMNIROUTE_E2E_MODE: process.env.NEXT_PUBLIC_OMNIROUTE_E2E_MODE || "1",
OMNIROUTE_DISABLE_BACKGROUND_SERVICES:
process.env.OMNIROUTE_DISABLE_BACKGROUND_SERVICES || "true",
OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK: process.env.OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK || "true",
OMNIROUTE_DISABLE_LOCAL_HEALTHCHECK: process.env.OMNIROUTE_DISABLE_LOCAL_HEALTHCHECK || "true",
OMNIROUTE_HIDE_HEALTHCHECK_LOGS: process.env.OMNIROUTE_HIDE_HEALTHCHECK_LOGS || "true",
...(bootstrapMode === "open"
? {
INITIAL_PASSWORD: "",
OMNIROUTE_E2E_PASSWORD: "",
OMNIROUTE_API_KEY: "",
}
: {
INITIAL_PASSWORD: playwrightPassword,
OMNIROUTE_E2E_PASSWORD: playwrightPassword,
}),
...(process.env.OMNIROUTE_USE_TURBOPACK
? {
OMNIROUTE_USE_TURBOPACK: process.env.OMNIROUTE_USE_TURBOPACK,
}
: {}),
};
export function shouldUseWebpackForPlaywrightDev({ mode, env }) {
// Webpack only on the explicit escape hatch (=0) — turbopack is the default.
return mode === "dev" && env.OMNIROUTE_USE_TURBOPACK === "0";
}
function runChild(command, args, env) {
return new Promise((resolve) => {
const child = spawn(command, args, {
stdio: "inherit",
env,
});
const forward = (signal) => {
if (!child.killed) child.kill(signal);
};
process.on("SIGINT", forward);
process.on("SIGTERM", forward);
child.on("exit", (code, signal) => {
process.off("SIGINT", forward);
process.off("SIGTERM", forward);
resolve({ code: code ?? 1, signal: signal ?? null });
});
});
}
async function runBuildForStart() {
if (mode !== "start") return;
if (process.env.OMNIROUTE_PLAYWRIGHT_SKIP_BUILD === "1") return;
console.log("[Playwright WebServer] Building fresh standalone app for this run...");
const buildEnv = withRuntimePortEnv(testServerEnv, runtimePorts);
const result = await runChild(process.execPath, [buildScript], buildEnv);
if (result.signal) {
process.kill(process.pid, result.signal);
return;
}
if (result.code !== 0) {
process.exit(result.code);
}
}
export async function main() {
process.on("exit", restoreAppDir);
process.on("uncaughtException", (error) => {
restoreAppDir();
throw error;
});
prepareAppDir();
await runBuildForStart();
if (mode === "start") {
if (existsSync(standaloneServer)) {
syncStandaloneRuntimeAssets({
standaloneServerPath: standaloneServer,
rootStaticDirPath: rootStaticDir,
standaloneStaticDirPath: standaloneStaticDir,
rootPublicDirPath: rootPublicDir,
standalonePublicDirPath: standalonePublicDir,
});
spawnWithForwardedSignals(process.execPath, [standaloneServer], {
stdio: "inherit",
env: {
...withRuntimePortEnv(testServerEnv, runtimePorts),
PORT: String(runtimePorts.dashboardPort),
HOSTNAME: process.env.HOSTNAME || "127.0.0.1",
},
});
return;
}
const args = [
"./node_modules/next/dist/bin/next",
"start",
"--port",
String(runtimePorts.dashboardPort),
];
spawnWithForwardedSignals(process.execPath, args, {
stdio: "inherit",
env: withRuntimePortEnv(testServerEnv, runtimePorts),
});
return;
}
const args = [
"./node_modules/next/dist/bin/next",
mode,
"--port",
String(runtimePorts.dashboardPort),
];
if (shouldUseWebpackForPlaywrightDev({ mode, env: testServerEnv })) {
args.splice(2, 0, "--webpack");
}
spawnWithForwardedSignals(process.execPath, args, {
stdio: "inherit",
env: withRuntimePortEnv(testServerEnv, runtimePorts),
});
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
await main();
}
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env node
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import next from "next";
import { bootstrapEnv } from "../build/bootstrap-env.mjs";
import { resolveRuntimePorts, withRuntimePortEnv } from "../build/runtime-env.mjs";
import { createOmnirouteWsBridge } from "./v1-ws-bridge.mjs";
import { createResponsesWsProxy } from "./responses-ws-proxy.mjs";
import { ensurePeerStampToken, stampPeerIp } from "./peer-stamp.mjs";
import methodGuard from "./http-method-guard.cjs";
import { ensureNativeSqlite } from "./ensure-native-sqlite.mjs";
import {
isTurbopackCacheCorruption,
purgeAllTurbopackCaches,
} from "./turbopackCacheHeal.mjs";
import { randomUUID } from "node:crypto";
const { maybeHandleDisallowedMethod } = methodGuard;
// Pre-read DATA_DIR from local .env before bootstrap resolves paths
if (!process.env.DATA_DIR) {
try {
const raw = fs.readFileSync(path.join(process.cwd(), ".env"), "utf8");
const match = raw.match(/^DATA_DIR=(.+)$/m);
if (match?.[1]?.trim()) process.env.DATA_DIR = match[1].trim();
} catch {
/* .env ausente ou ilegível — ok, bootstrap usa o padrão */
}
}
// Add check for conflicting app/ directory (Issue #1206)
const rootAppDir = path.join(process.cwd(), "app");
if (fs.existsSync(rootAppDir) && fs.statSync(rootAppDir).isDirectory()) {
console.error("\x1b[31m[FATAL ERROR]\x1b[0m Next.js App Router conflict detected!");
console.error(`A root-level 'app/' directory was found at: ${rootAppDir}`);
console.error("This conflicts with the 'src/app/' directory on Windows environments.");
console.error("Next.js will serve 404s for all pages because it prefers the root 'app/' folder.");
console.error("Please rename or delete the root 'app/' directory before starting OmniRoute.\n");
process.exit(1);
}
const mode = process.argv[2] === "start" ? "start" : "dev";
const dev = mode === "dev";
// Self-heal a stale better-sqlite3 native binary after a Node version switch
// (nvm 22 <-> 24) before bootstrap touches the DB. No-op when the ABI matches.
if (dev) {
ensureNativeSqlite();
}
const bootstrappedEnv = bootstrapEnv();
const runtimePorts = resolveRuntimePorts(bootstrappedEnv);
const mergedEnv = withRuntimePortEnv(bootstrappedEnv, runtimePorts);
for (const [key, value] of Object.entries(mergedEnv)) {
if (value !== undefined) {
process.env[key] = value;
}
}
// The mergedEnv copy above pulls NODE_ENV straight from `.env` — and the shipped
// `.env.example` default is `NODE_ENV=production`. Next's programmatic `next()`
// entry (unlike the `next` CLI) trusts that value verbatim, so `npm run dev`
// would boot the dev bundler with NODE_ENV=production. That desyncs Next's
// webpack CSS pipeline and `src/app/globals.css` reaches webpack's JS parser
// instead of PostCSS — failing as `Module parse failed: Unexpected character
// '@'` on the `@import "tailwindcss"` line. Force NODE_ENV to track the run
// mode, exactly like the `next` CLI does.
process.env.NODE_ENV = dev ? "development" : "production";
const { dashboardPort } = runtimePorts;
const hostname = process.env.HOST || "0.0.0.0";
// Turbopack by default in dev (matches the Next 16 CLI default and the production
// build default in build-next-isolated.mjs); OMNIROUTE_USE_TURBOPACK=0 is the
// webpack escape hatch.
const useTurbopack = dev && mergedEnv.OMNIROUTE_USE_TURBOPACK !== "0";
process.env.OMNIROUTE_WS_BRIDGE_SECRET ||= randomUUID();
// Per-process secret used to prove the trusted peer-IP stamp came from this
// server (read by the authz middleware in the same process). See peer-stamp.mjs.
ensurePeerStampToken();
// Next 16 picks Turbopack by default in dev. Passing `turbopack: false` to the
// programmatic next() entry is *not* enough on its own:
// - parseBundlerArgs (node_modules/next/dist/lib/bundler.js) sees no positive
// bundler flag and falls back to `process.env.TURBOPACK = 'auto'`.
// - next-dev-server.js then reads `process.env.TURBOPACK` directly and
// starts Turbopack regardless of the option we passed.
// Force webpack by both passing `webpack: true` and clearing the env var.
// Mirrors the workaround PR #4052 applied for the production Docker build.
if (!useTurbopack) {
delete process.env.TURBOPACK;
}
function createNextApp() {
return next({
dev,
dir: process.cwd(),
hostname,
port: dashboardPort,
turbopack: useTurbopack,
webpack: !useTurbopack,
});
}
let nextApp = createNextApp();
// Best-effort self-heal for a corrupted Turbopack persistent dev cache (#6289):
// on Windows an mmap of an SST cache file can fail ("os error 1455" / paging
// file too small), which Turbopack surfaces as a misleading module-resolve
// error. This is an UPSTREAM Turbopack cache-corruption bug — not our code.
// When `prepare()` rejects with that signature we purge the cache and retry
// ONCE. Caveat: the failure often surfaces as a runtime overlay rather than a
// `prepare()` rejection, so this cannot always intercept it — the reliable
// remedy remains manually deleting `.build/next/**/cache/turbopack`.
async function prepareWithHeal() {
try {
await nextApp.prepare();
} catch (error) {
const detail = error instanceof Error ? `${error.message}\n${error.stack ?? ""}` : String(error);
if (!useTurbopack || !isTurbopackCacheCorruption(detail)) throw error;
console.warn(
"[Next] Turbopack dev cache looks corrupted (Windows mmap / os error 1455 — known upstream bug). Purging and retrying once…"
);
const removed = purgeAllTurbopackCaches();
for (const dir of removed) console.warn(`[Next] purged Turbopack cache: ${dir}`);
nextApp = createNextApp();
await nextApp.prepare();
console.warn("[Next] Turbopack dev cache purged; startup retry succeeded.");
}
}
async function start() {
await prepareWithHeal();
const requestHandler = nextApp.getRequestHandler();
const upgradeHandler = nextApp.getUpgradeHandler();
const responsesWsProxy = createResponsesWsProxy({
baseUrl: `http://127.0.0.1:${dashboardPort}`,
bridgeSecret: process.env.OMNIROUTE_WS_BRIDGE_SECRET,
});
const wsBridge = createOmnirouteWsBridge({
baseUrl: `http://127.0.0.1:${dashboardPort}`,
});
const server = http.createServer((req, res) => {
if (maybeHandleDisallowedMethod(req, res)) return;
// Stamp the real TCP peer IP before Next sees the request, so the authz
// middleware can decide LOCAL_ONLY locality without trusting the Host header.
stampPeerIp(req);
return requestHandler(req, res);
});
server.on("upgrade", async (req, socket, head) => {
try {
const responsesWsHandled = await responsesWsProxy.handleUpgrade(req, socket, head);
if (responsesWsHandled) return;
const handled = await wsBridge.handleUpgrade(req, socket, head);
if (handled) return;
await upgradeHandler(req, socket, head);
} catch (error) {
if (!socket.destroyed) {
socket.destroy(error instanceof Error ? error : undefined);
}
console.error("[WS] Upgrade handling failed:", error);
}
});
server.on("error", (error) => {
console.error("[FATAL] Next custom server failed:", error);
process.exit(1);
});
const shutdown = async (signal) => {
try {
await new Promise((resolve) => server.close(resolve));
await nextApp.close();
} catch (error) {
console.error("[SHUTDOWN] Failed during signal:", signal, error);
} finally {
process.exit(0);
}
};
process.on("SIGINT", () => void shutdown("SIGINT"));
process.on("SIGTERM", () => void shutdown("SIGTERM"));
server.listen(dashboardPort, hostname, () => {
const bundler = dev ? (useTurbopack ? "turbopack" : "webpack") : "production";
console.log(
`[Next] ${mode} server listening on http://${hostname}:${dashboardPort} (${bundler})`
);
});
}
start().catch((error) => {
console.error("[FATAL] Failed to start Next custom server:", error);
process.exit(1);
});
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { sanitizeColorEnv } from "../build/runtime-env.mjs";
const defaultArgs = ["test", "tests/e2e/*.spec.ts"];
const forwardedArgs = process.argv.slice(2);
const args = forwardedArgs.length > 0 ? forwardedArgs : defaultArgs;
const playwrightEnv = sanitizeColorEnv(process.env);
delete playwrightEnv.NO_COLOR;
delete playwrightEnv.FORCE_COLOR;
const child = spawn(process.execPath, ["./node_modules/playwright/cli.js", ...args], {
stdio: "inherit",
env: playwrightEnv,
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { sanitizeColorEnv } from "../build/runtime-env.mjs";
function parsePort(value, fallback) {
const parsed = Number.parseInt(String(value), 10);
return Number.isFinite(parsed) && parsed > 0 && parsed <= 65535 ? parsed : fallback;
}
const explicitBaseUrl = process.env.OMNIROUTE_BASE_URL || "";
const isolatedPort = parsePort(
process.env.DASHBOARD_PORT || process.env.PORT,
23000 + (process.pid % 1000)
);
const isolatedDataDir =
process.env.DATA_DIR || join(process.cwd(), ".tmp", "protocol-clients-data", String(process.pid));
const port = explicitBaseUrl ? null : isolatedPort;
const baseUrl = explicitBaseUrl || `http://127.0.0.1:${isolatedPort}`;
const healthUrl = `${baseUrl}/api/monitoring/health`;
const maxWaitMs = Number(process.env.ECOSYSTEM_SERVER_WAIT_MS || 180000);
const pollMs = 2000;
async function isServerReady() {
const timeout = AbortSignal.timeout(2000);
try {
const res = await fetch(healthUrl, { signal: timeout });
return res.ok;
} catch {
return false;
}
}
async function waitForServerReady() {
const maxAttempts = Math.ceil(maxWaitMs / pollMs);
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
if (await isServerReady()) return;
await delay(pollMs);
}
throw new Error(`Timed out waiting for ${healthUrl} after ${maxWaitMs}ms`);
}
async function main() {
let serverProcess = null;
let startedHere = false;
const testEnv = {
...sanitizeColorEnv(process.env),
DATA_DIR: isolatedDataDir,
...(explicitBaseUrl
? {}
: {
PORT: String(port),
DASHBOARD_PORT: String(port),
API_PORT: String(port),
OMNIROUTE_BASE_URL: baseUrl,
}),
OMNIROUTE_E2E_BOOTSTRAP_MODE: process.env.OMNIROUTE_E2E_BOOTSTRAP_MODE || "open",
};
if (!(await isServerReady())) {
serverProcess = spawn(process.execPath, ["scripts/dev/run-next-playwright.mjs", "dev"], {
stdio: "inherit",
env: testEnv,
});
startedHere = true;
await waitForServerReady();
}
const vitestProcess = spawn(
process.execPath,
[
"./node_modules/vitest/vitest.mjs",
"run",
"--environment",
"node",
"tests/e2e/protocol-clients.test.ts",
],
{
stdio: "inherit",
env: testEnv,
}
);
const exitCode = await new Promise((resolve) => {
vitestProcess.on("exit", (code, signal) => {
if (signal) {
resolve(1);
return;
}
resolve(code ?? 1);
});
});
if (startedHere && serverProcess) {
serverProcess.kill("SIGTERM");
await delay(1000);
if (!serverProcess.killed) {
serverProcess.kill("SIGKILL");
}
}
process.exit(exitCode);
}
main().catch((error) => {
console.error("[test:protocols:e2e] Failed:", error?.message || error);
process.exit(1);
});
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env node
import { existsSync } from "node:fs";
import {
resolveRuntimePorts,
withRuntimePortEnv,
resolveMaxOldSpaceMb,
spawnWithForwardedSignals,
} from "../build/runtime-env.mjs";
import { bootstrapEnv } from "../build/bootstrap-env.mjs";
const env = bootstrapEnv();
const runtimePorts = resolveRuntimePorts(env);
const childEnv = withRuntimePortEnv(env, runtimePorts);
// #2939: honor OMNIROUTE_MEMORY_MB (default 512), the same knob
// `omniroute serve` uses, so Docker users can control the server heap under
// load / large SQLite DBs. A trailing --max-old-space-size wins, so this
// overrides the image fallback without clobbering any other NODE_OPTIONS flags.
const maxOldSpaceMb = resolveMaxOldSpaceMb(childEnv.OMNIROUTE_MEMORY_MB);
childEnv.NODE_OPTIONS =
`${childEnv.NODE_OPTIONS || ""} --max-old-space-size=${maxOldSpaceMb}`.trim();
// Prefer the WS-aware wrapper (server-ws.mjs) over the bare Next standalone
// server.js: it installs the trusted peer-IP stamp (scripts/dev/peer-stamp.mjs)
// that the authz middleware needs to allow loopback/LAN access to LOCAL_ONLY
// routes. Falling back to server.js fails CLOSED (every LOCAL_ONLY request 403s)
// rather than trusting the spoofable Host header.
const entry = existsSync("server-ws.mjs") ? "server-ws.mjs" : "server.js";
spawnWithForwardedSignals("node", [entry], {
stdio: "inherit",
env: childEnv,
});
+522
View File
@@ -0,0 +1,522 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { existsSync, readdirSync, statSync } from "node:fs";
import { mkdir, mkdtemp, rm } from "node:fs/promises";
import { arch, platform, tmpdir } from "node:os";
import { dirname, join, resolve, sep } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const ROOT = join(__dirname, "..", "..");
const DEFAULT_TIMEOUT_MS = 45_000;
const DEFAULT_SETTLE_MS = 2_000;
const DEFAULT_URL = "http://127.0.0.1:20128/login";
export const LINUX_EXECUTABLE_NAMES = ["omniroute-desktop", "omniroute", "OmniRoute"];
export const FATAL_LOG_PATTERNS = [
/Cannot find module/i,
/MODULE_NOT_FOUND/,
/ERR_DLOPEN_FAILED/,
/Server exited with code:\s*[1-9]/,
/Failed to start server/i,
/Unhandled Rejection/i,
/Uncaught Exception/i,
];
function parsePositiveInteger(value, fallback) {
const parsed = Number.parseInt(value || "", 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}
function sleep(ms) {
return new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
}
function discoverMacExecutable() {
const distDir = join(ROOT, "electron", "dist-electron");
if (process.env.ELECTRON_SMOKE_APP_EXECUTABLE) {
return process.env.ELECTRON_SMOKE_APP_EXECUTABLE;
}
const candidates = [
join(
distDir,
arch() === "arm64" ? "mac-arm64" : "mac",
"OmniRoute.app",
"Contents",
"MacOS",
"OmniRoute"
),
join(distDir, "mac", "OmniRoute.app", "Contents", "MacOS", "OmniRoute"),
join(distDir, "mac-arm64", "OmniRoute.app", "Contents", "MacOS", "OmniRoute"),
];
return candidates.find((candidate) => existsSync(candidate)) || candidates[0];
}
function findExecutableByName(rootDir, names) {
const pending = [rootDir];
const wanted = new Set(names.map((name) => name.toLowerCase()));
while (pending.length > 0) {
const dir = pending.shift();
if (!existsSync(dir)) continue;
for (const entry of readdirSync(dir)) {
const fullPath = join(dir, entry);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
pending.push(fullPath);
continue;
}
if (!wanted.has(entry.toLowerCase())) continue;
if (platform() === "linux" && (stat.mode & 0o111) === 0) continue;
return fullPath;
}
}
return null;
}
function discoverWindowsExecutable() {
const distDir = join(ROOT, "electron", "dist-electron");
const candidates = [
join(distDir, "win-unpacked", "OmniRoute.exe"),
join(distDir, "win-x64-unpacked", "OmniRoute.exe"),
join(distDir, "win-arm64-unpacked", "OmniRoute.exe"),
];
return (
candidates.find((candidate) => existsSync(candidate)) ||
findExecutableByName(distDir, ["OmniRoute.exe"]) ||
candidates[0]
);
}
function discoverLinuxExecutable() {
const distDir = join(ROOT, "electron", "dist-electron");
const unpackedDirs = ["linux-unpacked", "linux-arm64-unpacked"];
const candidates = unpackedDirs.flatMap((dir) =>
LINUX_EXECUTABLE_NAMES.map((name) => join(distDir, dir, name))
);
return (
candidates.find((candidate) => existsSync(candidate)) ||
findExecutableByName(distDir, LINUX_EXECUTABLE_NAMES) ||
candidates[0]
);
}
function discoverPackagedExecutable() {
if (process.env.ELECTRON_SMOKE_APP_EXECUTABLE) {
return process.env.ELECTRON_SMOKE_APP_EXECUTABLE;
}
if (platform() === "darwin") return discoverMacExecutable();
if (platform() === "win32") return discoverWindowsExecutable();
if (platform() === "linux") return discoverLinuxExecutable();
throw new Error(`Packaged Electron smoke check does not support ${platform()}.`);
}
async function fetchWithTimeout(url, timeoutMs) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(url, {
cache: "no-store",
redirect: "manual",
signal: controller.signal,
});
} finally {
clearTimeout(timeout);
}
}
async function assertPortIsFree(url) {
try {
const response = await fetchWithTimeout(url, 1_000);
throw new Error(
`Smoke URL already responded with HTTP ${response.status}: ${url}. Stop the existing OmniRoute process before running this check.`
);
} catch (error) {
if (error instanceof Error && error.message.startsWith("Smoke URL already responded")) {
throw error;
}
}
}
async function waitForPortClosed(url, timeoutMs = 5_000) {
const deadline = Date.now() + timeoutMs;
let lastStatus = null;
while (Date.now() < deadline) {
try {
const response = await fetchWithTimeout(url, 1_000);
lastStatus = response.status;
} catch {
return;
}
await sleep(250);
}
throw new Error(
`Smoke URL still responded after app shutdown${
lastStatus === null ? "" : ` with HTTP ${lastStatus}`
}: ${url}`
);
}
function appendLog(buffer, chunk, prefix, streamLogs) {
const text = chunk.toString();
if (streamLogs) {
process.stdout.write(`${prefix}${text}`);
}
const next = buffer.value + text;
buffer.value = next.length > 40_000 ? next.slice(-40_000) : next;
}
function printLogTail(logs) {
if (!logs.trim()) return;
console.error("[electron-smoke] captured app log tail:");
console.error(logs.trimEnd());
}
function assertNoFatalLogs(logs) {
const fatalPattern = FATAL_LOG_PATTERNS.find((pattern) => pattern.test(logs));
if (fatalPattern) {
throw new Error(`Packaged Electron app emitted fatal startup logs matching ${fatalPattern}.`);
}
}
async function waitForExit(child, timeoutMs) {
if (child.exitCode !== null || child.signalCode !== null) return;
await Promise.race([new Promise((resolve) => child.once("exit", resolve)), sleep(timeoutMs)]);
}
function isProcessGroupAlive(pid) {
if (!pid || platform() === "win32") return false;
try {
process.kill(-pid, 0);
return true;
} catch (error) {
if (error?.code === "ESRCH") return false;
if (error?.code === "EPERM") return true;
throw error;
}
}
async function waitForProcessTreeExit(child, timeoutMs) {
if (!child.pid || platform() === "win32") {
await waitForExit(child, timeoutMs);
return;
}
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (!isProcessGroupAlive(child.pid)) return;
await sleep(100);
}
}
async function runQuietly(command, args) {
await new Promise((resolveRun) => {
const proc = spawn(command, args, { stdio: "ignore" });
proc.once("error", resolveRun);
proc.once("exit", resolveRun);
});
}
async function signalProcessTree(child, signal) {
if (!child.pid) return;
if (platform() === "win32") {
if (signal === "SIGKILL") {
await runQuietly("taskkill", ["/pid", String(child.pid), "/t", "/f"]);
} else {
child.kill(signal);
}
return;
}
try {
process.kill(-child.pid, signal);
} catch (error) {
if (error?.code !== "ESRCH") throw error;
}
}
async function stopApp(child) {
if (!child.pid) return;
await signalProcessTree(child, "SIGTERM");
await waitForProcessTreeExit(child, 5_000);
const isStillRunning =
platform() === "win32"
? child.exitCode === null && child.signalCode === null
: isProcessGroupAlive(child.pid);
if (isStillRunning) {
await signalProcessTree(child, "SIGKILL");
await waitForProcessTreeExit(child, 2_000);
}
}
export function buildSmokeEnv({
dataDir,
parentEnv = process.env,
currentPlatform = platform(),
} = {}) {
if (!dataDir) {
throw new Error("buildSmokeEnv requires dataDir.");
}
const inheritedNames = [
"PATH",
"Path",
"SystemRoot",
"WINDIR",
"COMSPEC",
"PATHEXT",
"TMPDIR",
"TMP",
"TEMP",
"LANG",
"LC_ALL",
"LC_CTYPE",
"DISPLAY",
"WAYLAND_DISPLAY",
"XAUTHORITY",
"XDG_RUNTIME_DIR",
"DBUS_SESSION_BUS_ADDRESS",
"ELECTRON_OZONE_PLATFORM_HINT",
];
const smokeEnv = {};
for (const name of inheritedNames) {
if (parentEnv[name]) {
smokeEnv[name] = parentEnv[name];
}
}
if (currentPlatform === "win32") {
smokeEnv.USERPROFILE = join(dataDir, "userprofile");
smokeEnv.APPDATA = join(dataDir, "AppData", "Roaming");
smokeEnv.LOCALAPPDATA = join(dataDir, "AppData", "Local");
smokeEnv.TEMP ||= join(dataDir, "tmp");
smokeEnv.TMP ||= smokeEnv.TEMP;
} else {
smokeEnv.HOME = join(dataDir, "home");
smokeEnv.XDG_CONFIG_HOME = join(dataDir, "config");
smokeEnv.XDG_CACHE_HOME = join(dataDir, "cache");
smokeEnv.XDG_DATA_HOME = join(dataDir, "data");
smokeEnv.TMPDIR ||= join(dataDir, "tmp");
}
const baseEnv = {
...smokeEnv,
DATA_DIR: dataDir,
ELECTRON_ENABLE_LOGGING: "1",
ELECTRON_ENABLE_STACK_DUMPING: "1",
};
// CI environments need sandbox disabled (GitHub Actions runners
// cannot configure SUID chrome-sandbox on Linux, and Windows
// runners may exit silently without it).
if (parentEnv.CI) {
baseEnv.CI = parentEnv.CI;
baseEnv.ELECTRON_DISABLE_SANDBOX = "1";
}
return baseEnv;
}
function isInsideDir(parentDir, candidateDir) {
const parent = resolve(parentDir);
const candidate = resolve(candidateDir);
return candidate === parent || candidate.startsWith(parent + sep);
}
async function ensureSmokeEnvDirs(smokeEnv, dataDir) {
const dirNames = [
"DATA_DIR",
"HOME",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"XDG_CONFIG_HOME",
"XDG_CACHE_HOME",
"XDG_DATA_HOME",
"TMPDIR",
"TMP",
"TEMP",
];
const dirs = [
...new Set(
dirNames.map((name) => smokeEnv[name]).filter((dir) => dir && isInsideDir(dataDir, dir))
),
];
// On Windows, Electron derives its userData from APPDATA/<productName>.
// requestSingleInstanceLock() runs synchronously at module load and
// fails silently if the directory doesn't exist yet — causing exit(0).
if (platform() === "win32" && smokeEnv.APPDATA) {
for (const subdir of ["omniroute-desktop", "OmniRoute", "omniroute"]) {
dirs.push(join(smokeEnv.APPDATA, subdir));
}
}
await Promise.all(dirs.map((dir) => mkdir(dir, { recursive: true })));
}
async function settleAfterReady({ getExitState, logs, settleMs }) {
const deadline = Date.now() + settleMs;
while (Date.now() < deadline) {
assertNoFatalLogs(logs.value);
const { exitCode, signalCode } = getExitState();
if (exitCode !== null || signalCode !== null) {
throw new Error(
`Packaged Electron app exited during readiness settle: code=${exitCode} signal=${signalCode}`
);
}
await sleep(Math.min(250, Math.max(0, deadline - Date.now())));
}
}
async function main() {
const appExecutable = discoverPackagedExecutable();
if (!existsSync(appExecutable)) {
throw new Error(
`Packaged OmniRoute executable not found at ${appExecutable}. Build it first with \`npm run build:<target> --prefix electron\` or set ELECTRON_SMOKE_APP_EXECUTABLE.`
);
}
const smokeUrl = process.env.ELECTRON_SMOKE_URL || DEFAULT_URL;
const timeoutMs = parsePositiveInteger(process.env.ELECTRON_SMOKE_TIMEOUT_MS, DEFAULT_TIMEOUT_MS);
const settleMs = parsePositiveInteger(process.env.ELECTRON_SMOKE_SETTLE_MS, DEFAULT_SETTLE_MS);
const dataDir =
process.env.ELECTRON_SMOKE_DATA_DIR ||
(await mkdtemp(join(tmpdir(), "omniroute-electron-smoke-")));
const removeDataDir =
!process.env.ELECTRON_SMOKE_DATA_DIR && process.env.ELECTRON_SMOKE_KEEP_DATA !== "1";
const smokeEnv = buildSmokeEnv({ dataDir });
await assertPortIsFree(smokeUrl);
await ensureSmokeEnvDirs(smokeEnv, dataDir);
// ── CI sandbox workaround ──────────────────────────────────
// GitHub Actions runners cannot set SUID on chrome-sandbox (Linux)
// and Windows runners may fail silently without --no-sandbox.
const spawnArgs = [];
if (process.env.CI) {
spawnArgs.push("--no-sandbox", "--disable-gpu");
if (platform() === "linux") {
spawnArgs.push("--disable-dev-shm-usage");
}
}
console.log(`[electron-smoke] launching ${appExecutable}`);
if (spawnArgs.length) console.log(`[electron-smoke] CI args: ${spawnArgs.join(" ")}`);
console.log(`[electron-smoke] DATA_DIR=${dataDir}`);
console.log(`[electron-smoke] waiting for ${smokeUrl}`);
const logs = { value: "" };
const streamLogs = process.env.ELECTRON_SMOKE_STREAM_LOGS === "1";
const child = spawn(appExecutable, spawnArgs, {
detached: platform() !== "win32",
env: smokeEnv,
stdio: ["ignore", "pipe", "pipe"],
});
child.stdout?.on("data", (chunk) => appendLog(logs, chunk, "[electron] ", streamLogs));
child.stderr?.on("data", (chunk) => appendLog(logs, chunk, "[electron:err] ", streamLogs));
let exitCode = null;
let signalCode = null;
let spawnError = null;
child.once("exit", (code, signal) => {
exitCode = code;
signalCode = signal;
});
child.once("error", (error) => {
spawnError = error;
});
try {
const startedAt = Date.now();
let lastError = null;
while (Date.now() - startedAt < timeoutMs) {
assertNoFatalLogs(logs.value);
if (spawnError !== null) {
throw new Error(`Packaged Electron app failed to launch: ${spawnError.message}`);
}
if (exitCode !== null || signalCode !== null) {
throw new Error(
`Packaged Electron app exited before readiness: code=${exitCode} signal=${signalCode}`
);
}
try {
const response = await fetchWithTimeout(smokeUrl, 1_000);
if (response.status === 200) {
assertNoFatalLogs(logs.value);
console.log(`[electron-smoke] ready: ${smokeUrl} returned HTTP 200`);
await settleAfterReady({
getExitState: () => ({ exitCode, signalCode }),
logs,
settleMs,
});
console.log(`[electron-smoke] stable for ${settleMs}ms after readiness`);
return;
}
lastError = new Error(`HTTP ${response.status}`);
} catch (error) {
lastError = error;
}
await new Promise((resolve) => setTimeout(resolve, 500));
}
throw new Error(
`Packaged Electron app did not serve ${smokeUrl} within ${timeoutMs}ms. Last error: ${
lastError instanceof Error ? lastError.message : String(lastError)
}`
);
} catch (error) {
if (!streamLogs) {
printLogTail(logs.value);
}
throw error;
} finally {
await stopApp(child);
await waitForPortClosed(smokeUrl);
if (removeDataDir) {
await rm(dataDir, { recursive: true, force: true });
}
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch((error) => {
console.error(
`[electron-smoke] failed: ${error instanceof Error ? error.message : String(error)}`
);
process.exit(1);
});
}
+163
View File
@@ -0,0 +1,163 @@
import http from "node:http";
import net from "node:net";
import { randomUUID } from "node:crypto";
import { createResponsesWsProxy } from "./responses-ws-proxy.mjs";
import { ensurePeerStampToken, wrapRequestListenerWithPeerStamp } from "./peer-stamp.mjs";
import { maybeHandleWebdav } from "./webdav-handler.mjs";
import methodGuard from "./http-method-guard.cjs";
import { resolveTlsOptions, createServerListener } from "./tls-options.mjs";
const originalCreateServer = http.createServer.bind(http);
const proxiesByPort = new Map();
const { wrapRequestListenerWithMethodGuard } = methodGuard;
// Opt-in native HTTPS (#5242). Resolved once at boot: when both OMNIROUTE_TLS_CERT
// and OMNIROUTE_TLS_KEY point at readable files we terminate TLS on the same
// listener Next binds to (so WS `upgrade` / request wrappers keep working over
// TLS). Absent or misconfigured → null → identical plain-HTTP behavior as before.
const tlsOptions = resolveTlsOptions(process.env);
if (tlsOptions) {
console.log(
`[omniroute][tls] HTTPS enabled — terminating TLS with cert=${tlsOptions.certPath}`
);
}
process.env.OMNIROUTE_WS_BRIDGE_SECRET ||= randomUUID();
// Per-process secret proving the trusted peer-IP stamp came from this server.
ensurePeerStampToken();
function getPort(server) {
const address = server.address?.();
if (address && typeof address === "object" && typeof address.port === "number") {
return address.port;
}
const rawPort = process.env.PORT || process.env.DASHBOARD_PORT || "3000";
const parsed = Number.parseInt(rawPort, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 3000;
}
function getProxy(server) {
const port = getPort(server);
const existing = proxiesByPort.get(port);
if (existing) return existing;
const proxy = createResponsesWsProxy({
baseUrl: `http://127.0.0.1:${port}`,
bridgeSecret: process.env.OMNIROUTE_WS_BRIDGE_SECRET,
});
proxiesByPort.set(port, proxy);
return proxy;
}
function proxyLiveWs(req, socket, head) {
const targetPort = parseInt(process.env.LIVE_WS_PORT || "20129", 10);
const targetSocket = net.connect(targetPort, "127.0.0.1", () => {
let rawRequest = `${req.method} ${req.url} HTTP/${req.httpVersion}\r\n`;
for (const [key, val] of Object.entries(req.headers)) {
if (Array.isArray(val)) {
for (const v of val) rawRequest += `${key}: ${v}\r\n`;
} else {
rawRequest += `${key}: ${val}\r\n`;
}
}
rawRequest += "\r\n";
targetSocket.write(rawRequest);
if (head && head.length > 0) targetSocket.write(head);
targetSocket.pipe(socket);
socket.pipe(targetSocket);
});
targetSocket.on("error", () => !socket.destroyed && socket.destroy());
socket.on("error", () => !targetSocket.destroyed && targetSocket.destroy());
}
function wrapUpgradeListener(server, listener) {
return async function responsesWsAwareUpgrade(req, socket, head) {
try {
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
if (url.pathname === "/live-ws" || url.pathname.startsWith("/live-ws")) {
proxyLiveWs(req, socket, head);
return;
}
const handled = await getProxy(server).handleUpgrade(req, socket, head);
if (handled) return;
return listener.call(this, req, socket, head);
} catch (error) {
if (!socket.destroyed) {
socket.destroy(error instanceof Error ? error : undefined);
}
console.error("[Responses WS] Upgrade handling failed:", error);
}
};
}
/**
* Wrap a request listener so WebDAV requests at /api/v1/webdav are handled
* before the peer-stamp/Next.js layer sees them.
* Returns true if the request was handled; the wrapped listener is never called.
*/
function wrapRequestListenerWithWebdav(listener) {
return async function webdavAwareRequestHandler(req, res) {
try {
const handled = await maybeHandleWebdav(req, res);
if (handled) return;
} catch {
// Never block a request on WebDAV errors — fall through to Next
}
return listener.call(this, req, res);
};
}
http.createServer = function createServerWithResponsesWs(...args) {
// Next's standalone server.js may pass its request listener directly to
// createServer; wrap it so the real TCP peer IP is stamped before Next runs.
const lastFnIdx = args.map((a) => typeof a === "function").lastIndexOf(true);
if (lastFnIdx >= 0) {
// Method guard runs before Next because Next 16 rejects TRACE while constructing requests.
args[lastFnIdx] = wrapRequestListenerWithMethodGuard(
wrapRequestListenerWithWebdav(wrapRequestListenerWithPeerStamp(args[lastFnIdx]))
);
}
// When TLS is configured, return an https.Server (terminating TLS on the same
// listener); otherwise the original http.Server. The downstream .on/.addListener
// patches below apply identically to both (https.Server extends http.Server).
const server = createServerListener(args, tlsOptions, { createHttp: originalCreateServer });
const originalOn = server.on.bind(server);
const originalAddListener = server.addListener.bind(server);
server.on = function patchedOn(eventName, listener) {
if (eventName === "upgrade" && typeof listener === "function") {
return originalOn(eventName, wrapUpgradeListener(server, listener));
}
// …or it may attach the handler via server.on("request"): wrap that too.
if (eventName === "request" && typeof listener === "function") {
return originalOn(
eventName,
wrapRequestListenerWithMethodGuard(
wrapRequestListenerWithWebdav(wrapRequestListenerWithPeerStamp(listener))
)
);
}
return originalOn(eventName, listener);
};
server.addListener = function patchedAddListener(eventName, listener) {
if (eventName === "upgrade" && typeof listener === "function") {
return originalAddListener(eventName, wrapUpgradeListener(server, listener));
}
if (eventName === "request" && typeof listener === "function") {
return originalAddListener(
eventName,
wrapRequestListenerWithMethodGuard(
wrapRequestListenerWithWebdav(wrapRequestListenerWithPeerStamp(listener))
)
);
}
return originalAddListener(eventName, listener);
};
return server;
};
await import("./server.js");
+362
View File
@@ -0,0 +1,362 @@
#!/usr/bin/env node
/**
* OmniRoute — Environment Sync
*
* Ensures .env exists and contains the selected keys from .env.example.
* Runs on installs and can be executed manually via `npm run env:sync`.
*
* Rules:
* - Never overwrites existing values in .env
* - Auto-generates cryptographic secrets if blank in .env.example
* - Copies default values from .env.example for new keys
* - Skips commented lines from .env.example
*/
import { copyFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import { createRequire } from "node:module";
import { dirname, join, resolve } from "node:path";
import { homedir } from "node:os";
import { fileURLToPath } from "node:url";
/**
* Resolve the repository/package root that holds `.env` / `.env.example`.
*
* When this module is statically bundled into a Next.js standalone route,
* `import.meta.url` is frozen to the build-machine path
* (`file:///home/runner/.../sync-env.mjs`) and `fileURLToPath` can throw at
* runtime. Callers (e.g. the env-repair route) pass an explicit `rootDir`;
* when they don't, fall back to `process.cwd()` instead of crashing. (#5006)
*/
function resolveRootDir(rootDir) {
if (rootDir) return rootDir;
try {
return dirname(dirname(fileURLToPath(import.meta.url)));
} catch {
return process.cwd();
}
}
const CRYPTO_SECRETS = {
JWT_SECRET: () => randomBytes(64).toString("hex"),
API_KEY_SECRET: () => randomBytes(32).toString("hex"),
// STORAGE_ENCRYPTION_KEY: Generated at server startup instead of postinstall.
// Generated in bin/omniroute.mjs:ensureStorageEncryptionKey() and persisted to
// ~/.omniroute/.env to survive across upgrades. This prevents credential loss
// when upgrading OmniRoute (issue #1622).
MACHINE_ID_SALT: () => `omniroute-${randomBytes(8).toString("hex")}`,
};
/**
* Keys that MUST NOT be regenerated when existing encrypted data exists in the DB.
* Generating a new key would make all previously-encrypted credentials unrecoverable.
*
* Note: STORAGE_ENCRYPTION_KEY is no longer auto-generated in postinstall.
* It's generated at server startup in bin/omniroute.mjs and persisted to
* ~/.omniroute/.env to survive across upgrades.
* @see https://github.com/diegosouzapw/OmniRoute/issues/1622
*/
const ENCRYPTION_BOUND_KEYS = new Set([]);
// ── Resolve DATA_DIR (mirrors bootstrap-env.mjs / dataPaths.ts) ─────────────
function resolveDataDir(env = process.env) {
const configured = env.DATA_DIR?.trim();
if (configured) return resolve(configured);
if (process.platform === "win32") {
const appData = env.APPDATA || join(homedir(), "AppData", "Roaming");
return join(appData, "omniroute");
}
const xdg = env.XDG_CONFIG_HOME?.trim();
if (xdg) return join(resolve(xdg), "omniroute");
return join(homedir(), ".omniroute");
}
/**
* Check whether the SQLite database already contains credentials encrypted
* under a previous STORAGE_ENCRYPTION_KEY. If so, generating a new key would
* make them permanently unrecoverable (AES-GCM auth-tag mismatch).
*/
function hasEncryptedCredentials(dataDir) {
const dbPath = join(dataDir, "storage.sqlite");
if (!existsSync(dbPath)) return false;
try {
// Resolve `require` lazily here (not at module top-level): when this file is
// bundled into a standalone route, a top-level `createRequire(import.meta.url)`
// throws during module evaluation and 500s the whole route (#5006). Inside this
// guarded block, any failure simply returns false (the safe default below).
const require = createRequire(import.meta.url);
const Database = require("better-sqlite3");
const db = new Database(dbPath, { readonly: true, fileMustExist: true });
try {
const row = db
.prepare(
`SELECT 1
FROM provider_connections
WHERE access_token LIKE 'enc:v1:%'
OR refresh_token LIKE 'enc:v1:%'
OR api_key LIKE 'enc:v1:%'
OR id_token LIKE 'enc:v1:%'
LIMIT 1`
)
.get();
return !!row;
} finally {
db.close();
}
} catch {
// If we can't open the DB (e.g. missing better-sqlite3 during install),
// err on the side of caution: don't block secret generation.
return false;
}
}
export function parseEnvFile(filePath) {
if (!existsSync(filePath)) return new Map();
const content = readFileSync(filePath, "utf8");
const entries = new Map();
for (const line of content.split(/\r?\n/)) {
const parsed = parseEnvEntry(line);
if (!parsed) continue;
const [key, value] = parsed;
entries.set(key, value);
}
return entries;
}
function parseEnvEntry(line) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) return null;
const eqIndex = trimmed.indexOf("=");
if (eqIndex < 1) return null;
const key = trimmed.slice(0, eqIndex).trim();
const value = unquoteEnvValue(trimmed.slice(eqIndex + 1).trim());
return [key, value];
}
function unquoteEnvValue(value) {
if (value.length < 2) return value;
const quote = value[0];
if ((quote !== '"' && quote !== "'") || value[value.length - 1] !== quote) return value;
return value.slice(1, -1);
}
function parseExampleEntries(content, scope = "full") {
const entries = new Map();
const lines = content.split(/\r?\n/);
if (scope === "oauth") {
let inOauthSection = false;
for (const line of lines) {
const trimmed = line.trim();
if (/OAUTH PROVIDER CREDENTIALS/i.test(trimmed)) {
inOauthSection = true;
continue;
}
if (!inOauthSection) continue;
if (/Provider User-Agent Overrides/i.test(trimmed)) break;
const parsed = parseEnvEntry(line);
if (!parsed) continue;
const [key, value] = parsed;
entries.set(key, value);
}
return entries;
}
for (const line of lines) {
const parsed = parseEnvEntry(line);
if (!parsed) continue;
const [key, value] = parsed;
entries.set(key, value);
}
return entries;
}
export function getEnvSyncPlan({ rootDir, scope = "full" } = {}) {
const root = resolveRootDir(rootDir);
const envExamplePath = join(root, ".env.example");
const envPath = join(root, ".env");
if (!existsSync(envExamplePath)) {
return {
available: false,
created: false,
added: 0,
missingEntries: [],
};
}
const exampleEntries = parseExampleEntries(readFileSync(envExamplePath, "utf8"), scope);
const currentEntries = parseEnvFile(envPath);
const missingEntries = [];
// Check once whether encrypted data exists — avoids repeated DB opens
let _encryptedDataExists;
function encryptedDataExists() {
if (_encryptedDataExists === undefined) {
try {
_encryptedDataExists = hasEncryptedCredentials(resolveDataDir());
} catch {
_encryptedDataExists = false;
}
}
return _encryptedDataExists;
}
for (const [key, defaultValue] of exampleEntries) {
if (currentEntries.has(key)) continue;
if (CRYPTO_SECRETS[key] && !defaultValue) {
// Guard: never generate a new encryption key if the DB already has
// credentials encrypted under the previous key (#1622)
if (ENCRYPTION_BOUND_KEYS.has(key) && encryptedDataExists()) {
missingEntries.push({
key,
value: "",
generated: false,
blocked: true,
});
continue;
}
missingEntries.push({ key, value: CRYPTO_SECRETS[key](), generated: true });
continue;
}
missingEntries.push({ key, value: defaultValue, generated: false });
}
return {
available: true,
created: !existsSync(envPath),
added: missingEntries.length,
missingEntries,
};
}
function replaceBlankSecret(content, key, value) {
const pattern = new RegExp(`^${key}=\\s*$`, "m");
return pattern.test(content) ? content.replace(pattern, `${key}=${value}`) : content;
}
export function syncEnv({ rootDir, quiet = false, scope = "full" } = {}) {
const log = quiet ? () => {} : (message) => process.stderr.write(`[sync-env] ${message}\n`);
const root = resolveRootDir(rootDir);
const envExamplePath = join(root, ".env.example");
const envPath = join(root, ".env");
if (!existsSync(envExamplePath)) {
log("⚠️ .env.example not found — skipping sync");
return { created: false, added: 0 };
}
const exampleEntries = parseExampleEntries(readFileSync(envExamplePath, "utf8"), scope);
if (!existsSync(envPath)) {
if (scope === "full") {
copyFileSync(envExamplePath, envPath);
let content = readFileSync(envPath, "utf8");
let generated = 0;
// Check once whether encrypted data exists — avoids repeated DB opens
let dbHasEncrypted;
try {
dbHasEncrypted = hasEncryptedCredentials(resolveDataDir());
} catch {
dbHasEncrypted = false;
}
for (const [key, generator] of Object.entries(CRYPTO_SECRETS)) {
// Guard: never generate a new encryption key if the DB already has
// credentials encrypted under the previous key (#1622)
if (ENCRYPTION_BOUND_KEYS.has(key) && dbHasEncrypted) {
log(
`⚠️ ${key} NOT generated — encrypted credentials exist in DB. ` +
`Restore your previous key via ~/.omniroute/server.env, ~/.omniroute/.env, ` +
`or the STORAGE_ENCRYPTION_KEY environment variable.`
);
continue;
}
const nextContent = replaceBlankSecret(content, key, generator());
if (nextContent !== content) {
content = nextContent;
generated++;
log(`${key} auto-generated`);
}
}
writeFileSync(envPath, content, "utf8");
log(
`✨ Created .env from .env.example (${exampleEntries.size} keys, ${generated} secrets generated)`
);
return { created: true, added: exampleEntries.size };
}
const { missingEntries } = getEnvSyncPlan({ rootDir: root, scope });
const content = [
"# ── Auto-added by sync-env (oauth defaults) ──",
...missingEntries.map((entry) => `${entry.key}=${entry.value}`),
"",
].join("\n");
writeFileSync(envPath, content, "utf8");
log(`✨ Created .env with oauth defaults (${missingEntries.length} keys)`);
return { created: true, added: missingEntries.length };
}
const { missingEntries } = getEnvSyncPlan({ rootDir: root, scope });
if (missingEntries.length === 0) {
log("✅ .env is up to date (0 keys added)");
return { created: false, added: 0 };
}
const appendLines = [
"",
`# ── Auto-added by sync-env (${new Date().toISOString().slice(0, 10)}) ──`,
];
for (const entry of missingEntries) {
if (entry.blocked) {
log(
`⚠️ ${entry.key} NOT generated — encrypted credentials exist in DB. ` +
`Restore your previous key via ~/.omniroute/server.env, ~/.omniroute/.env, ` +
`or the STORAGE_ENCRYPTION_KEY environment variable.`
);
continue;
}
appendLines.push(`${entry.key}=${entry.value}`);
log(
`${entry.generated ? "✨" : "📦"} ${entry.key}${entry.generated ? " (auto-generated)" : ""}`
);
}
appendLines.push("");
const currentContent = readFileSync(envPath, "utf8");
writeFileSync(envPath, `${currentContent.trimEnd()}\n${appendLines.join("\n")}`, "utf8");
log(`📦 Synced .env — added ${missingEntries.length} missing keys`);
return { created: false, added: missingEntries.length };
}
if (process.argv[1]?.endsWith("sync-env.mjs")) {
syncEnv({ scope: process.argv.includes("--oauth-only") ? "oauth" : "full" });
}
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env node
/**
* system-info.mjs — OmniRoute System Information Reporter (#280)
*
* Collects system/environment info for bug reports.
* Usage: node scripts/dev/system-info.mjs [--output system-info.txt]
*
* Output includes:
* - Node.js version
* - OmniRoute version
* - OS info
* - Relevant system packages (if apt available)
* - Agent CLI tools (qoder, gemini, claude, codex, antigravity, droid, etc.)
* - Docker / PM2 status
*/
import { execSync } from "child_process";
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import os from "os";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, "..", "..");
// ── Helpers ────────────────────────────────────────────────────────────────
function run(cmd, fallback = "N/A") {
try {
return execSync(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
} catch {
return fallback;
}
}
function toolVersion(cmd, args = "--version") {
const version = run(`${cmd} ${args}`, null);
if (version === null) return "not installed";
// Trim to first line, remove prefixes like "v", "Version: "
return version
.split("\n")[0]
.replace(/^(version\s*:?\s*|v)/i, "")
.trim();
}
function section(title) {
const line = "─".repeat(60);
return `\n${line}\n ${title}\n${line}\n`;
}
// ── Collect Info ──────────────────────────────────────────────────────────
const lines = [];
lines.push("OmniRoute System Information Report");
lines.push(`Generated: ${new Date().toISOString()}`);
// ── Node.js & Runtime ────────────────────────────────────────────────────
lines.push(section("Node.js & Runtime"));
lines.push(`Node.js: ${process.version}`);
lines.push(`npm: v${run("npm --version")}`);
lines.push(`Platform: ${process.platform} (${process.arch})`);
lines.push(`OS: ${os.type()} ${os.release()} (${os.arch()})`);
lines.push(`Hostname: ${os.hostname()}`);
lines.push(`CPUs: ${os.cpus().length}x ${os.cpus()[0]?.model || "unknown"}`);
lines.push(`Total RAM: ${Math.round(os.totalmem() / 1024 / 1024)} MB`);
lines.push(`Free RAM: ${Math.round(os.freemem() / 1024 / 1024)} MB`);
// ── OmniRoute Version ────────────────────────────────────────────────────
lines.push(section("OmniRoute"));
try {
const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf-8"));
lines.push(`Version: ${pkg.version}`);
lines.push(`Name: ${pkg.name}`);
} catch {
lines.push("Version: unable to read package.json");
}
const installedGlobal = run("npm list -g omniroute --depth=0 2>/dev/null | grep omniroute");
lines.push(`Global npm: ${installedGlobal || "not installed globally"}`);
const pm2Status = run("pm2 list 2>/dev/null | grep omniroute | awk '{print $4, $10, $12}'");
lines.push(`PM2 status: ${pm2Status || "not running via PM2"}`);
// ── Agent CLI Tools ──────────────────────────────────────────────────────
lines.push(section("Agent CLI Tools"));
const cliTools = [
{ name: "qoder-cli", cmd: "qoder", args: "--version" },
{ name: "claude-code", cmd: "claude", args: "--version" },
{ name: "openai-codex", cmd: "codex", args: "--version" },
{ name: "antigravity", cmd: "antigravity", args: "--version" },
{ name: "droid", cmd: "droid", args: "--version" },
{ name: "openclaw", cmd: "openclaw", args: "--version" },
{ name: "kilo", cmd: "kilo", args: "--version" },
{ name: "cursor", cmd: "cursor", args: "--version" },
{ name: "aider", cmd: "aider", args: "--version" },
];
for (const { name, cmd, args } of cliTools) {
const v = toolVersion(cmd, args);
lines.push(`${name.padEnd(20)} ${v}`);
}
// ── Docker ───────────────────────────────────────────────────────────────
lines.push(section("Docker"));
lines.push(`Docker: ${run("docker --version", "not installed")}`);
const dockerContainers = run(
"docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}' 2>/dev/null",
"N/A"
);
lines.push(`Containers:\n${dockerContainers}`);
// ── System Packages ──────────────────────────────────────────────────────
lines.push(section("System Packages (relevant)"));
const relevantPkgs = ["build-essential", "libssl-dev", "openssl", "libsqlite3-dev", "python3"];
for (const pkg of relevantPkgs) {
const ver = run(`dpkg -l ${pkg} 2>/dev/null | grep '^ii' | awk '{print $3}'`, "not found");
lines.push(`${pkg.padEnd(24)} ${ver}`);
}
// ── Environment Variables (safe subset) ─────────────────────────────────
lines.push(section("Environment Variables (non-sensitive)"));
const safeEnvKeys = [
"NODE_ENV",
"PORT",
"DATA_DIR",
"DB_BACKUPS_DIR",
"LOG_LEVEL",
"NEXT_PUBLIC_APP_URL",
"ROUTER_API_KEY_HINT",
];
for (const key of safeEnvKeys) {
const val = process.env[key];
if (val !== undefined) {
// Mask if looks like a secret
const masked = val.length > 8 ? val.substring(0, 4) + "****" : "****";
lines.push(`${key.padEnd(28)} ${masked}`);
}
}
// ── Output ───────────────────────────────────────────────────────────────
const report = lines.join("\n") + "\n";
// Write to file
const outArg = process.argv.find((a) => a.startsWith("--output="));
const outFile = outArg
? outArg.replace("--output=", "")
: process.argv[process.argv.indexOf("--output") + 1] || "system-info.txt";
const outPath = join(ROOT, outFile);
mkdirSync(dirname(outPath), { recursive: true });
writeFileSync(outPath, report);
console.log(report);
console.log(`\n✅ Report saved to: ${outPath}`);
console.log(
`📎 Attach this file when reporting issues at: https://github.com/diegosouzapw/OmniRoute/issues`
);
+92
View File
@@ -0,0 +1,92 @@
// scripts/dev/tls-options.mjs
//
// Pure, dependency-light helpers for OmniRoute's opt-in native HTTPS/TLS serving
// (#5242, Bug 1C). Kept side-effect-free and free of heavy imports so it can be
// imported both by the CLI (bin/cli/commands/serve.mjs) and by the standalone
// server wrapper (standalone-server-ws.mjs), and unit-tested in isolation.
//
// TLS is strictly opt-in: when neither cert nor key is provided the server
// behaves EXACTLY as before (plain HTTP). A misconfiguration (only one of the
// pair, or an unreadable path) NEVER crashes the server — it logs a warning and
// falls back to HTTP, preserving today's behavior and loopback/security posture.
import fs from "node:fs";
import http from "node:http";
import https from "node:https";
/**
* Resolve TLS options from environment variables.
*
* Reads `OMNIROUTE_TLS_CERT` and `OMNIROUTE_TLS_KEY` (filesystem paths). Returns
* `{ cert, key }` (file contents) only when BOTH are provided and readable.
* Otherwise returns `null` so the caller serves plain HTTP — never throwing.
*
* @param {NodeJS.ProcessEnv} [env=process.env]
* @param {{ readFileSync?: typeof fs.readFileSync, warn?: (msg: string) => void }} [deps]
* @returns {{ cert: Buffer|string, key: Buffer|string, certPath: string, keyPath: string } | null}
*/
export function resolveTlsOptions(
env = process.env,
{ readFileSync = fs.readFileSync, warn = (m) => console.warn(m) } = {}
) {
const certPath = typeof env?.OMNIROUTE_TLS_CERT === "string" ? env.OMNIROUTE_TLS_CERT.trim() : "";
const keyPath = typeof env?.OMNIROUTE_TLS_KEY === "string" ? env.OMNIROUTE_TLS_KEY.trim() : "";
// Neither provided → plain HTTP, no warning (the common, default case).
if (!certPath && !keyPath) return null;
// Only one of the pair → never half-enable TLS. Warn + fall back to HTTP.
if (!certPath || !keyPath) {
warn(
`[omniroute][tls] HTTPS not enabled: both OMNIROUTE_TLS_CERT and OMNIROUTE_TLS_KEY ` +
`are required (only ${certPath ? "cert" : "key"} provided). Serving HTTP.`
);
return null;
}
// Both provided → read them. A bad/unreadable path falls back to HTTP rather
// than crashing the server over a TLS misconfiguration.
try {
const cert = readFileSync(certPath);
const key = readFileSync(keyPath);
return { cert, key, certPath, keyPath };
} catch (err) {
warn(
`[omniroute][tls] HTTPS not enabled: could not read TLS cert/key ` +
`(${err?.code || err?.message || String(err)}). Serving HTTP.`
);
return null;
}
}
/**
* Create either an `https.Server` (when `tlsOptions` is provided) or an
* `http.Server` (when it is `null`), forwarding the same request-listener /
* options arguments the caller would otherwise pass to `http.createServer`.
*
* When TLS is enabled, any leading options object is merged with `cert`/`key`
* and the trailing request listener is preserved, so existing wiring (WebSocket
* `upgrade` handling, request wrappers) keeps working over TLS unchanged.
*
* @param {any[]} args - the args originally passed to http.createServer (options?, listener?)
* @param {{ cert: Buffer|string, key: Buffer|string } | null} tlsOptions
* @param {{ createHttp?: Function, createHttps?: Function }} [deps]
* @returns {import("node:http").Server | import("node:https").Server}
*/
export function createServerListener(
args,
tlsOptions,
{ createHttp = http.createServer.bind(http), createHttps = https.createServer.bind(https) } = {}
) {
const argList = Array.isArray(args) ? args : args === undefined ? [] : [args];
if (!tlsOptions) return createHttp(...argList);
const { cert, key } = tlsOptions;
const lastFnIdx = argList.map((a) => typeof a === "function").lastIndexOf(true);
const listener = lastFnIdx >= 0 ? argList[lastFnIdx] : undefined;
const baseOpts =
argList[0] && typeof argList[0] === "object" && !Buffer.isBuffer(argList[0]) ? argList[0] : {};
const merged = { ...baseOpts, cert, key };
return listener ? createHttps(merged, listener) : createHttps(merged);
}
+74
View File
@@ -0,0 +1,74 @@
// Best-effort self-heal for a corrupted Turbopack persistent dev cache.
//
// Context (#6289): on Windows, `pnpm dev` can fail at startup when Turbopack
// mmaps a persistent-cache SST file and the OS refuses the mapping
// ("os error 1455" — "paging file too small"). Turbopack then surfaces a
// misleading `Module not found: Can't resolve '@/shared/utils/machine'`.
// This is a known UPSTREAM Turbopack cache-corruption bug — NOT our code.
// The reliable remedy is deleting the Turbopack cache dir; this module lets
// the dev launcher attempt that automatically once before giving up.
//
// Pure + side-effect-isolated so it can be unit-tested without booting Next.
import fs from "node:fs";
import path from "node:path";
// Signature of the corrupted-cache failure. Kept intentionally broad because
// the same corruption surfaces through several messages (the raw mmap/SST
// error, the Windows paging-file error code, and the misleading module-resolve
// error emitted by Turbopack's "restore task data" step).
const CORRUPTION_SIGNATURE = /restore task data|mmap .*SST|os error 1455|paging file/i;
/**
* True when an error message looks like a corrupted Turbopack persistent cache.
* @param {unknown} message
* @returns {boolean}
*/
export function isTurbopackCacheCorruption(message) {
if (message == null) return false;
return CORRUPTION_SIGNATURE.test(String(message));
}
/**
* Candidate Turbopack cache directories for a given Next dist dir. Next has
* placed the persistent cache under both `<distDir>/cache/turbopack` and
* `<distDir>/dev/cache/turbopack` across versions, so purge both.
* @param {string} [distDir]
* @param {string} [cwd]
* @returns {string[]}
*/
export function turbopackCacheDirs(
distDir = process.env.NEXT_DIST_DIR || ".build/next",
cwd = process.cwd()
) {
const base = path.isAbsolute(distDir) ? distDir : path.join(cwd, distDir);
return [
path.join(base, "cache", "turbopack"),
path.join(base, "dev", "cache", "turbopack"),
];
}
/**
* Recursively remove a single Turbopack cache directory.
* @param {string} dir
* @returns {boolean} true if the directory existed and was removed
*/
export function purgeTurbopackCache(dir) {
if (!dir || !fs.existsSync(dir)) return false;
fs.rmSync(dir, { recursive: true, force: true });
return true;
}
/**
* Purge every candidate Turbopack cache directory for the given dist dir.
* @param {string} [distDir]
* @param {string} [cwd]
* @returns {string[]} the directories that existed and were removed
*/
export function purgeAllTurbopackCaches(distDir, cwd) {
const removed = [];
for (const dir of turbopackCacheDirs(distDir, cwd)) {
if (purgeTurbopackCache(dir)) removed.push(dir);
}
return removed;
}
+671
View File
@@ -0,0 +1,671 @@
import { createHash, randomUUID } from "node:crypto";
import { STATUS_CODES } from "node:http";
export const WS_PUBLIC_PATHS = new Set(["/v1/ws", "/api/v1/ws"]);
export const WS_ALLOWED_ENDPOINTS = new Set([
"/v1/chat/completions",
"/api/v1/chat/completions",
"/v1/messages",
"/api/v1/messages",
"/v1/responses",
"/api/v1/responses",
"/v1/completions",
"/api/v1/completions",
]);
const HANDSHAKE_PATH = "/api/v1/ws";
const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
const WS_QUERY_TOKEN_KEYS = ["api_key", "token", "access_token"];
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
function isText(value) {
return typeof value === "string" && value.length > 0;
}
function jsonStringifySafe(value) {
try {
return JSON.stringify(value);
} catch {
return JSON.stringify({
type: "protocol.error",
code: "serialization_failed",
message: "Failed to serialize WebSocket payload",
});
}
}
function encodeWsFrame(opcode, payload = Buffer.alloc(0)) {
const payloadBuffer = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
const length = payloadBuffer.length;
let header;
if (length < 126) {
header = Buffer.allocUnsafe(2);
header[1] = length;
} else if (length <= 0xffff) {
header = Buffer.allocUnsafe(4);
header[1] = 126;
header.writeUInt16BE(length, 2);
} else {
header = Buffer.allocUnsafe(10);
header[1] = 127;
header.writeBigUInt64BE(BigInt(length), 2);
}
header[0] = 0x80 | (opcode & 0x0f);
return Buffer.concat([header, payloadBuffer]);
}
function decodeClientFrames(buffer) {
const frames = [];
let offset = 0;
while (buffer.length - offset >= 2) {
const byte1 = buffer[offset];
const byte2 = buffer[offset + 1];
const fin = (byte1 & 0x80) !== 0;
const opcode = byte1 & 0x0f;
const masked = (byte2 & 0x80) !== 0;
let payloadLength = byte2 & 0x7f;
let headerLength = 2;
if (!masked) {
throw new Error("Client WebSocket frames must be masked");
}
if (payloadLength === 126) {
if (buffer.length - offset < 4) break;
payloadLength = buffer.readUInt16BE(offset + 2);
headerLength = 4;
} else if (payloadLength === 127) {
if (buffer.length - offset < 10) break;
const bigLength = buffer.readBigUInt64BE(offset + 2);
if (bigLength > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new Error("WebSocket payload too large");
}
payloadLength = Number(bigLength);
headerLength = 10;
}
const totalLength = headerLength + 4 + payloadLength;
if (buffer.length - offset < totalLength) break;
const mask = buffer.subarray(offset + headerLength, offset + headerLength + 4);
const payload = Buffer.from(buffer.subarray(offset + headerLength + 4, offset + totalLength));
for (let index = 0; index < payload.length; index += 1) {
payload[index] ^= mask[index % 4];
}
frames.push({ fin, opcode, payload });
offset += totalLength;
}
return {
frames,
remaining: buffer.subarray(offset),
};
}
function writeHttpError(socket, status, body, headers = {}) {
if (!socket.writable || socket.destroyed) return;
const bodyBuffer = Buffer.from(body || "", "utf8");
const statusText = STATUS_CODES[status] || "Error";
const responseHeaders = {
Connection: "close",
"Content-Length": String(bodyBuffer.length),
"Content-Type": "application/json; charset=utf-8",
...headers,
};
const head = [
`HTTP/1.1 ${status} ${statusText}`,
...Object.entries(responseHeaders).map(([name, value]) => `${name}: ${value}`),
"",
"",
].join("\r\n");
socket.write(head);
socket.end(bodyBuffer);
}
function isWsPath(pathname) {
return WS_PUBLIC_PATHS.has(pathname);
}
function normalizeEndpoint(rawEndpoint) {
const endpoint = isText(rawEndpoint) ? rawEndpoint : "/v1/chat/completions";
let parsed;
try {
parsed = new URL(endpoint, "http://omniroute.local");
} catch {
return null;
}
if (parsed.origin !== "http://omniroute.local") {
return null;
}
if (!WS_ALLOWED_ENDPOINTS.has(parsed.pathname)) {
return null;
}
return `${parsed.pathname}${parsed.search}`;
}
function getForwardHeaders(requestUrl, requestHeaders) {
const headers = {
accept: "text/event-stream",
"content-type": "application/json",
};
const authorization = requestHeaders.authorization;
if (isText(authorization)) {
headers.authorization = authorization;
} else {
const url = new URL(requestUrl, "http://omniroute.local");
for (const key of WS_QUERY_TOKEN_KEYS) {
const value = url.searchParams.get(key);
if (isText(value)) {
headers.authorization = `Bearer ${value.trim()}`;
break;
}
}
}
const cookie = requestHeaders.cookie;
if (isText(cookie)) {
headers.cookie = cookie;
}
const origin = requestHeaders.origin;
if (isText(origin)) {
headers.origin = origin;
}
return headers;
}
async function performHandshake(fetchImpl, baseUrl, requestUrl, requestHeaders) {
const incomingUrl = new URL(requestUrl, baseUrl);
const handshakeUrl = new URL(HANDSHAKE_PATH, baseUrl);
for (const [key, value] of incomingUrl.searchParams.entries()) {
handshakeUrl.searchParams.set(key, value);
}
handshakeUrl.searchParams.set("handshake", "1");
const response = await fetchImpl(handshakeUrl, {
method: "GET",
headers: {
authorization: requestHeaders.authorization || "",
cookie: requestHeaders.cookie || "",
origin: requestHeaders.origin || "",
"x-forwarded-for": requestHeaders["x-forwarded-for"] || "",
},
});
const bodyText = await response.text();
let bodyJson = null;
try {
bodyJson = bodyText ? JSON.parse(bodyText) : null;
} catch {
bodyJson = null;
}
return {
status: response.status,
headers: Object.fromEntries(response.headers.entries()),
bodyText,
bodyJson,
ok: response.ok,
};
}
class WebSocketSession {
constructor(options) {
this.baseUrl = options.baseUrl;
this.fetchImpl = options.fetchImpl;
this.idleTimeoutMs = options.idleTimeoutMs;
this.pingIntervalMs = options.pingIntervalMs;
this.socket = options.socket;
this.requestHeaders = options.requestHeaders;
this.requestUrl = options.requestUrl;
this.sessionId = randomUUID();
this.closed = false;
this.buffer = Buffer.alloc(0);
this.fragmentOpcode = null;
this.fragmentParts = [];
this.activeRequests = new Map();
this.lastSeenAt = Date.now();
this.pingTimer = setInterval(() => {
if (this.closed) return;
const idleForMs = Date.now() - this.lastSeenAt;
if (idleForMs >= this.idleTimeoutMs) {
this.close(1001, "idle_timeout");
return;
}
this.sendFrame(0x9);
}, this.pingIntervalMs);
this.socket.setNoDelay(true);
this.socket.on("data", (chunk) => {
this.onData(chunk).catch((error) => {
this.sendProtocolError(
"frame_decode_failed",
error instanceof Error ? error.message : String(error)
);
});
});
this.socket.on("close", () => this.dispose());
this.socket.on("end", () => this.dispose());
this.socket.on("error", () => this.dispose());
}
sendFrame(opcode, payload) {
if (this.closed || this.socket.destroyed) return;
this.socket.write(encodeWsFrame(opcode, payload));
}
sendJson(payload) {
this.sendFrame(0x1, Buffer.from(jsonStringifySafe(payload), "utf8"));
}
sendProtocolError(code, message, id = null) {
this.sendJson({
type: "protocol.error",
code,
id,
message,
});
}
async onData(chunk) {
this.lastSeenAt = Date.now();
this.buffer = Buffer.concat([this.buffer, chunk]);
const parsed = decodeClientFrames(this.buffer);
this.buffer = parsed.remaining;
for (const frame of parsed.frames) {
await this.handleFrame(frame);
}
}
async handleFrame(frame) {
switch (frame.opcode) {
case 0x0:
if (this.fragmentOpcode === null) {
this.sendProtocolError("unexpected_continuation", "Unexpected continuation frame");
return;
}
this.fragmentParts.push(frame.payload);
if (frame.fin) {
const payload = Buffer.concat(this.fragmentParts);
const opcode = this.fragmentOpcode;
this.fragmentOpcode = null;
this.fragmentParts = [];
await this.handleDataFrame(opcode, payload);
}
return;
case 0x1:
case 0x2:
if (!frame.fin) {
this.fragmentOpcode = frame.opcode;
this.fragmentParts = [frame.payload];
return;
}
await this.handleDataFrame(frame.opcode, frame.payload);
return;
case 0x8:
this.close();
return;
case 0x9:
this.sendFrame(0xa, frame.payload);
return;
case 0xa:
this.lastSeenAt = Date.now();
return;
default:
this.sendProtocolError("unsupported_opcode", `Unsupported opcode ${frame.opcode}`);
}
}
async handleDataFrame(opcode, payload) {
if (opcode !== 0x1) {
this.sendProtocolError("unsupported_payload", "Only UTF-8 text messages are supported");
return;
}
const raw = textDecoder.decode(payload);
let message;
try {
message = JSON.parse(raw);
} catch {
this.sendProtocolError("invalid_json", "WebSocket message must be valid JSON");
return;
}
await this.handleMessage(message);
}
async handleMessage(message) {
if (!message || typeof message !== "object" || Array.isArray(message)) {
this.sendProtocolError("invalid_envelope", "WebSocket message must be an object");
return;
}
if (message.type === "ping") {
this.sendJson({ type: "pong", sessionId: this.sessionId });
return;
}
if (message.type === "cancel") {
const requestId = isText(message.id) ? message.id : null;
if (!requestId) {
this.sendProtocolError("invalid_cancel", "cancel envelopes require a string id");
return;
}
const active = this.activeRequests.get(requestId);
if (!active) {
this.sendProtocolError(
"unknown_request",
"No active request matches the provided id",
requestId
);
return;
}
active.abortController.abort();
return;
}
if (message.type !== "request") {
this.sendProtocolError(
"unsupported_type",
"Supported message types are request, cancel, and ping"
);
return;
}
const requestId = isText(message.id) ? message.id : null;
if (!requestId) {
this.sendProtocolError("invalid_request_id", "request envelopes require a non-empty id");
return;
}
if (this.activeRequests.has(requestId)) {
this.sendProtocolError(
"duplicate_request",
"A request with this id is already in flight",
requestId
);
return;
}
if (!message.payload || typeof message.payload !== "object" || Array.isArray(message.payload)) {
this.sendProtocolError(
"invalid_payload",
"request envelopes require an object payload",
requestId
);
return;
}
const endpoint = normalizeEndpoint(message.endpoint);
if (!endpoint) {
this.sendProtocolError(
"invalid_endpoint",
"Endpoint must target a supported /v1 chat surface",
requestId
);
return;
}
const requestPayload = {
...message.payload,
stream: message.payload.stream === undefined ? true : message.payload.stream,
};
const abortController = new AbortController();
this.activeRequests.set(requestId, { abortController });
this.executeRequest(requestId, endpoint, requestPayload, abortController).catch((error) => {
this.sendJson({
type: abortController.signal.aborted ? "response.cancelled" : "response.error",
id: requestId,
code: abortController.signal.aborted ? "client_cancelled" : "request_failed",
message: error instanceof Error ? error.message : String(error),
});
this.activeRequests.delete(requestId);
});
}
async executeRequest(requestId, endpoint, payload, abortController) {
const headers = {
...this.requestHeaders,
accept: payload.stream === false ? "application/json" : "text/event-stream",
"content-type": "application/json",
"x-omniroute-ws-session-id": this.sessionId,
"x-omniroute-ws-request-id": requestId,
};
const response = await this.fetchImpl(new URL(endpoint, this.baseUrl), {
method: "POST",
headers,
body: JSON.stringify(payload),
signal: abortController.signal,
});
const contentType = response.headers.get("content-type") || "";
this.sendJson({
type: "response.start",
id: requestId,
status: response.status,
ok: response.ok,
contentType,
endpoint,
});
if (contentType.includes("text/event-stream") && response.body) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
if (chunk) {
this.sendJson({
type: "response.chunk",
id: requestId,
chunk,
});
}
}
const tail = decoder.decode();
if (tail) {
this.sendJson({
type: "response.chunk",
id: requestId,
chunk: tail,
});
}
} finally {
this.activeRequests.delete(requestId);
}
this.sendJson({
type: response.ok ? "response.completed" : "response.error",
id: requestId,
status: response.status,
ok: response.ok,
});
return;
}
const bodyText = await response.text();
let body = bodyText;
try {
body = bodyText ? JSON.parse(bodyText) : null;
} catch {
body = bodyText;
}
this.activeRequests.delete(requestId);
this.sendJson({
type: response.ok ? "response.output" : "response.error",
id: requestId,
status: response.status,
ok: response.ok,
body,
});
this.sendJson({
type: "response.completed",
id: requestId,
status: response.status,
ok: response.ok,
});
}
close(code = 1000, reason = "normal_closure") {
if (this.closed) return;
this.closed = true;
clearInterval(this.pingTimer);
for (const active of this.activeRequests.values()) {
active.abortController.abort();
}
this.activeRequests.clear();
const reasonBuffer = Buffer.from(reason, "utf8");
const payload = Buffer.allocUnsafe(2 + reasonBuffer.length);
payload.writeUInt16BE(code, 0);
reasonBuffer.copy(payload, 2);
this.sendFrame(0x8, payload);
this.socket.end();
setTimeout(() => {
if (!this.socket.destroyed) {
this.socket.destroy();
}
}, 50).unref?.();
}
dispose() {
if (this.closed) return;
this.closed = true;
clearInterval(this.pingTimer);
for (const active of this.activeRequests.values()) {
active.abortController.abort();
}
this.activeRequests.clear();
}
}
export function createOmnirouteWsBridge({
baseUrl,
fetchImpl = fetch,
pingIntervalMs = 25000,
idleTimeoutMs = 90000,
} = {}) {
if (!isText(baseUrl)) {
throw new Error("createOmnirouteWsBridge requires a baseUrl");
}
return {
isWsPath,
async handleUpgrade(req, socket, head) {
const pathname = new URL(req.url || "/", baseUrl).pathname;
if (!isWsPath(pathname)) {
return false;
}
const upgradeHeader = String(req.headers.upgrade || "").toLowerCase();
if (upgradeHeader !== "websocket") {
writeHttpError(
socket,
426,
JSON.stringify({
error: {
message: "Upgrade Required",
code: "upgrade_required",
},
}),
{ Upgrade: "websocket" }
);
return true;
}
try {
const handshake = await performHandshake(fetchImpl, baseUrl, req.url || "/", req.headers);
if (!handshake.ok) {
writeHttpError(socket, handshake.status, handshake.bodyText || "{}", handshake.headers);
return true;
}
const wsKey = req.headers["sec-websocket-key"];
if (!isText(wsKey)) {
writeHttpError(
socket,
400,
JSON.stringify({
error: {
message: "Missing sec-websocket-key header",
code: "bad_websocket_handshake",
},
})
);
return true;
}
const acceptKey = createHash("sha1").update(`${wsKey}${WS_GUID}`).digest("base64");
const headers = [
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${acceptKey}`,
"",
"",
].join("\r\n");
socket.write(headers);
if (head && head.length > 0) {
socket.unshift(head);
}
const session = new WebSocketSession({
baseUrl,
fetchImpl,
idleTimeoutMs,
pingIntervalMs,
socket,
requestUrl: req.url || pathname,
requestHeaders: getForwardHeaders(req.url || pathname, req.headers),
});
session.sendJson({
type: "session.ready",
sessionId: session.sessionId,
path: handshake.bodyJson?.path || pathname,
wsAuth: handshake.bodyJson?.wsAuth === true,
authenticated: handshake.bodyJson?.authenticated === true,
authType: handshake.bodyJson?.authType || "none",
});
return true;
} catch (error) {
writeHttpError(
socket,
500,
JSON.stringify({
error: {
message: error instanceof Error ? error.message : String(error),
code: "websocket_bridge_failed",
},
})
);
return true;
}
},
};
}
File diff suppressed because it is too large Load Diff