mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-07 15:52:52 +03:00
refactor(scripts): organize into build/dev/check/docs/i18n/ad-hoc subfolders
Reorganizes the 29 active scripts under scripts/ into purpose-driven subfolders: - scripts/build/ (11) — Build, install, publish, runtime env - scripts/dev/ (13) — Dev servers, test runners, healthchecks - scripts/check/ (10) — Lint/validation/coverage checks - scripts/docs/ (2) — Docs index and provider reference generation - scripts/i18n/ (+3) — Adds Python translation utilities (check/validate/autotranslate) - scripts/ad-hoc/ (4) — One-shot maintenance utilities Updates all references in package.json, electron/package.json, .husky/pre-commit, .github/workflows/ci.yml, Dockerfile, src/, tests/, scripts/ internal cross-imports, playwright.config.ts, and English docs (CODEBASE_DOCUMENTATION, ENVIRONMENT, FEATURES, RELEASE_CHECKLIST, COVERAGE_PLAN, ELECTRON_GUIDE, I18N, GEMINI). Also patches scripts/build/pack-artifact-policy.ts so the npm pack allowlist mirrors the new layout. Validates with: - npm run lint (exit 0 — pre-existing minified-bundle errors only) - npm run typecheck:core (exit 0) - npm run check:docs-all (exit 0) - unit tests for moved scripts (57 tests pass) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
14
scripts/dev/healthcheck.mjs
Normal file
14
scripts/dev/healthcheck.mjs
Normal file
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Docker healthcheck script for OmniRoute.
|
||||
* Checks the /api/monitoring/health endpoint on the dashboard port.
|
||||
* Used by Dockerfile and docker-compose files.
|
||||
*/
|
||||
const port = process.env.DASHBOARD_PORT || process.env.PORT || "20128";
|
||||
|
||||
fetch(`http://127.0.0.1:${port}/api/monitoring/health`)
|
||||
.then((r) => {
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
})
|
||||
.catch(() => process.exit(1));
|
||||
676
scripts/dev/responses-ws-proxy.mjs
Normal file
676
scripts/dev/responses-ws-proxy.mjs
Normal file
@@ -0,0 +1,676 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { STATUS_CODES } from "node:http";
|
||||
import { websocket } from "wreq-js";
|
||||
|
||||
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 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",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
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 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.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.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) {
|
||||
this.sendJson({
|
||||
type: "response.failed",
|
||||
response: {
|
||||
id: null,
|
||||
status: "failed",
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
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;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const upstream = await this.wsFactory(prepared.json.upstreamUrl, {
|
||||
browser: prepared.json.browser || "chrome_142",
|
||||
os: prepared.json.os || "windows",
|
||||
headers: prepared.json.headers || {},
|
||||
});
|
||||
|
||||
upstream.onmessage = (event) => {
|
||||
if (this.closed) return;
|
||||
const data =
|
||||
typeof event.data === "string" ? event.data : Buffer.from(event.data).toString("utf8");
|
||||
this.sendFrame(0x1, Buffer.from(data, "utf8"));
|
||||
};
|
||||
upstream.onerror = (event) => {
|
||||
if (this.closed) return;
|
||||
this.sendFailure(
|
||||
"upstream_websocket_error",
|
||||
event.message || "Codex upstream WebSocket error"
|
||||
);
|
||||
};
|
||||
upstream.onclose = (event) => {
|
||||
if (this.closed) return;
|
||||
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);
|
||||
this.sendFailure(code, messageText);
|
||||
this.close(1011, "upstream_connect_failed");
|
||||
}
|
||||
}
|
||||
|
||||
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 = websocket,
|
||||
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;
|
||||
}
|
||||
|
||||
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) {
|
||||
writeHttpError(
|
||||
socket,
|
||||
auth.status,
|
||||
auth.text || "{}",
|
||||
Object.fromEntries(auth.headers.entries())
|
||||
);
|
||||
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
scripts/dev/run-ecosystem-tests.mjs
Normal file
108
scripts/dev/run-ecosystem-tests.mjs
Normal 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/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);
|
||||
});
|
||||
295
scripts/dev/run-next-playwright.mjs
Normal file
295
scripts/dev/run-next-playwright.mjs
Normal file
@@ -0,0 +1,295 @@
|
||||
#!/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-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() {
|
||||
return process.env.NEXT_DIST_DIR || ".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 }) {
|
||||
return mode === "dev" && env.OMNIROUTE_USE_TURBOPACK !== "1";
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
109
scripts/dev/run-next.mjs
Normal file
109
scripts/dev/run-next.mjs
Normal file
@@ -0,0 +1,109 @@
|
||||
#!/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 { randomUUID } from "node:crypto";
|
||||
|
||||
// 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";
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
const { dashboardPort } = runtimePorts;
|
||||
const hostname = process.env.HOST || "0.0.0.0";
|
||||
const useTurbopack = dev && mergedEnv.OMNIROUTE_USE_TURBOPACK === "1";
|
||||
process.env.OMNIROUTE_WS_BRIDGE_SECRET ||= randomUUID();
|
||||
|
||||
const nextApp = next({
|
||||
dev,
|
||||
dir: process.cwd(),
|
||||
hostname,
|
||||
port: dashboardPort,
|
||||
turbopack: useTurbopack,
|
||||
});
|
||||
|
||||
async function start() {
|
||||
await nextApp.prepare();
|
||||
|
||||
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) => 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}:`, 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
scripts/dev/run-playwright-tests.mjs
Normal file
25
scripts/dev/run-playwright-tests.mjs
Normal 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
scripts/dev/run-protocol-clients-tests.mjs
Normal file
110
scripts/dev/run-protocol-clients-tests.mjs
Normal 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/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);
|
||||
});
|
||||
16
scripts/dev/run-standalone.mjs
Normal file
16
scripts/dev/run-standalone.mjs
Normal file
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import {
|
||||
resolveRuntimePorts,
|
||||
withRuntimePortEnv,
|
||||
spawnWithForwardedSignals,
|
||||
} from "../build/runtime-env.mjs";
|
||||
import { bootstrapEnv } from "../build/bootstrap-env.mjs";
|
||||
|
||||
const env = bootstrapEnv();
|
||||
const runtimePorts = resolveRuntimePorts(env);
|
||||
|
||||
spawnWithForwardedSignals("node", ["server.js"], {
|
||||
stdio: "inherit",
|
||||
env: withRuntimePortEnv(env, runtimePorts),
|
||||
});
|
||||
522
scripts/dev/smoke-electron-packaged.mjs
Normal file
522
scripts/dev/smoke-electron-packaged.mjs
Normal 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);
|
||||
});
|
||||
}
|
||||
70
scripts/dev/standalone-server-ws.mjs
Normal file
70
scripts/dev/standalone-server-ws.mjs
Normal file
@@ -0,0 +1,70 @@
|
||||
import http from "node:http";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createResponsesWsProxy } from "./responses-ws-proxy.mjs";
|
||||
|
||||
const originalCreateServer = http.createServer.bind(http);
|
||||
const proxiesByPort = new Map();
|
||||
|
||||
process.env.OMNIROUTE_WS_BRIDGE_SECRET ||= randomUUID();
|
||||
|
||||
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 wrapUpgradeListener(server, listener) {
|
||||
return async function responsesWsAwareUpgrade(req, socket, head) {
|
||||
try {
|
||||
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);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
http.createServer = function createServerWithResponsesWs(...args) {
|
||||
const server = originalCreateServer(...args);
|
||||
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));
|
||||
}
|
||||
return originalOn(eventName, listener);
|
||||
};
|
||||
|
||||
server.addListener = function patchedAddListener(eventName, listener) {
|
||||
if (eventName === "upgrade" && typeof listener === "function") {
|
||||
return originalAddListener(eventName, wrapUpgradeListener(server, listener));
|
||||
}
|
||||
return originalAddListener(eventName, listener);
|
||||
};
|
||||
|
||||
return server;
|
||||
};
|
||||
|
||||
await import("./server.js");
|
||||
334
scripts/dev/sync-env.mjs
Normal file
334
scripts/dev/sync-env.mjs
Normal file
@@ -0,0 +1,334 @@
|
||||
#!/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";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
const CRYPTO_SECRETS = {
|
||||
JWT_SECRET: () => randomBytes(64).toString("hex"),
|
||||
API_KEY_SECRET: () => randomBytes(32).toString("hex"),
|
||||
STORAGE_ENCRYPTION_KEY: () => randomBytes(32).toString("hex"),
|
||||
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.
|
||||
* @see https://github.com/diegosouzapw/OmniRoute/issues/1622
|
||||
*/
|
||||
const ENCRYPTION_BOUND_KEYS = new Set(["STORAGE_ENCRYPTION_KEY"]);
|
||||
|
||||
// ── 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 {
|
||||
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 = rootDir || dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
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 = rootDir || dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
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" });
|
||||
}
|
||||
171
scripts/dev/system-info.mjs
Normal file
171
scripts/dev/system-info.mjs
Normal file
@@ -0,0 +1,171 @@
|
||||
#!/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: "gemini-cli", cmd: "gemini", 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`
|
||||
);
|
||||
671
scripts/dev/v1-ws-bridge.mjs
Normal file
671
scripts/dev/v1-ws-bridge.mjs
Normal 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;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user