Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Stream relayed core responses through the web UI server (#2469)

Regan Belle923e34b9f3f
diff --git a/plugins/chassis/src/core-client.ts b/plugins/chassis/src/core-client.ts
index 3bf411f68..afb1c6e54 100644
--- a/plugins/chassis/src/core-client.ts
+++ b/plugins/chassis/src/core-client.ts
@@ -1,3 +1,8 @@
+import { request as httpRequest, type IncomingMessage, type ServerResponse } from "node:http";
+import { request as httpsRequest } from "node:https";
+import { pipeline } from "node:stream/promises";
+import { reportBackendError } from "./error-reporting.ts";
+import { gzipAccepted, withVary } from "./http.ts";
import { signedRequestHeaders } from "./source-auth-sign.ts";
export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
@@ -79,3 +84,73 @@ export async function fetchCoreText(input: {
}
}
}
+
+export async function relayCoreStream(
+ res: ServerResponse,
+ input: {
+ origin: string;
+ secret?: string;
+ method: HttpMethod;
+ path: string;
+ body?: string;
+ headers?: Record<string, string>;
+ },
+): Promise<void> {
+ const path = withSourceAuthNonce(input.path, input.secret);
+ const body = input.body ?? "";
+ const url = new URL(`${input.origin}${path}`);
+ const send = url.protocol === "https:" ? httpsRequest : httpRequest;
+ const browserGone = new AbortController();
+ const onClose = () => browserGone.abort();
+ res.once("close", onClose);
+ let upstream: IncomingMessage;
+ try {
+ upstream = await new Promise<IncomingMessage>((resolve, reject) => {
+ const req = send(
+ url,
+ {
+ method: input.method,
+ signal: AbortSignal.any([browserGone.signal, AbortSignal.timeout(300_000)]),
+ headers: {
+ ...input.headers,
+ ...signedHeaders(input.secret, input.method, path, body),
+ "accept-encoding": gzipAccepted(res.req) ? "gzip" : "identity",
+ ...(body ? { "content-length": String(Buffer.byteLength(body)) } : {}),
+ },
+ },
+ resolve,
+ );
+ req.on("error", reject);
+ req.end(body || undefined);
+ });
+ } catch (error) {
+ if (browserGone.signal.aborted) return;
+ throw error;
+ } finally {
+ res.off("close", onClose);
+ }
+ upstream.once("error", (error: Error & { code?: string }) => {
+ if (res.destroyed) return;
+ const detail = {
+ method: input.method,
+ path: url.pathname,
+ status: upstream.statusCode,
+ requestId: upstream.headers["x-request-id"],
+ code: error.code ?? error.name,
+ cause: String(error.cause ?? error.message),
+ };
+ console.warn("core_relay_interrupted", detail);
+ reportBackendError(error, "core_relay_interrupted", detail);
+ });
+ const headers: Record<string, string> = {
+ "content-type": "application/json",
+ "x-content-type-options": "nosniff",
+ vary: withVary(res, "accept-encoding"),
+ };
+ for (const name of ["content-encoding", "content-length"] as const) {
+ const value = upstream.headers[name];
+ if (value) headers[name] = value;
+ }
+ res.writeHead(upstream.statusCode ?? 502, headers);
+ await pipeline(upstream, res).catch(() => undefined);
+}
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 9db6c9e2f..7f580d199 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -16,6 +16,7 @@ import { randomBytes } from "node:crypto";
import { LRUCache } from "lru-cache";
import {
fetchCoreText,
+ relayCoreStream,
signedHeaders,
withSourceAuthNonce,
CAPABILITY_HEADER,
@@ -688,11 +689,7 @@ async function coreFetch(
});
}
-async function coreFetchCap(
- method: HttpMethod,
- pathWithQuery: string,
- rawBody = "",
-): Promise<{ status: number; text: string }> {
+async function mintSessionCap(): Promise<{ token: string } | { status: number; text: string }> {
const cap = await coreFetch("POST", "/v1/session-cap", "");
if (cap.status !== 200) return { status: cap.status === 401 ? 401 : 503, text: cap.text };
let token: string | undefined;
@@ -703,9 +700,19 @@ async function coreFetchCap(
}
if (!token)
return { status: 503, text: JSON.stringify({ error: "not_configured", message: "no session capability" }) };
+ return { token };
+}
+
+async function coreFetchCap(
+ method: HttpMethod,
+ pathWithQuery: string,
+ rawBody = "",
+): Promise<{ status: number; text: string }> {
+ const cap = await mintSessionCap();
+ if (!("token" in cap)) return cap;
const r = await fetch(`${CORE}${pathWithQuery}`, {
method,
- headers: { "content-type": "application/json", [CAPABILITY_HEADER]: token },
+ headers: { "content-type": "application/json", [CAPABILITY_HEADER]: cap.token },
...(rawBody ? { body: rawBody } : {}),
redirect: "manual",
});
@@ -713,11 +720,27 @@ async function coreFetchCap(
}
async function relayCore(res: ServerResponse, method: HttpMethod, pathWithQuery: string, rawBody = ""): Promise<void> {
- relay(res, await coreFetch(method, pathWithQuery, rawBody));
+ const portalTok = portalTokenStore.getStore();
+ return relayCoreStream(res, {
+ origin: CORE,
+ secret: CORE_SIGNING_SECRET,
+ method,
+ path: pathWithQuery,
+ body: rawBody,
+ headers: portalTok ? { [PORTAL_IDENTITY_HEADER]: portalTok } : undefined,
+ });
}
async function relayCap(res: ServerResponse, method: HttpMethod, pathWithQuery: string, rawBody = ""): Promise<void> {
- relay(res, await coreFetchCap(method, pathWithQuery, rawBody));
+ const cap = await mintSessionCap();
+ if (!("token" in cap)) return relay(res, cap);
+ return relayCoreStream(res, {
+ origin: CORE,
+ method,
+ path: pathWithQuery,
+ body: rawBody,
+ headers: { [CAPABILITY_HEADER]: cap.token },
+ });
}
/**
@@ -2848,7 +2871,7 @@ const apiRoutes: readonly WebRoute[] = [
path: "/api/webhooks",
handle: async (c) => {
const { res, user } = c;
- return relay(res, await coreFetch("GET", `/v1/webhooks?viewer=${encodeURIComponent(user)}`));
+ return relayCore(res, "GET", `/v1/webhooks?viewer=${encodeURIComponent(user)}`);
},
},
{
@@ -3081,7 +3104,7 @@ const apiRoutes: readonly WebRoute[] = [
verification,
...(filters ? { filters } : {}),
});
- return relay(res, await coreFetch("POST", "/v1/webhooks", reqBody));
+ return relayCore(res, "POST", "/v1/webhooks", reqBody);
},
},
{
diff --git a/plugins/web-ui/test/core-relay-stream.test.ts b/plugins/web-ui/test/core-relay-stream.test.ts
new file mode 100644
index 000000000..9d1d698fd
--- /dev/null
+++ b/plugins/web-ui/test/core-relay-stream.test.ts
@@ -0,0 +1,86 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createServer, request, type IncomingMessage } from "node:http";
+import { once } from "node:events";
+import type { AddressInfo } from "node:net";
+import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";
+
+const secret = "relay-stream-test";
+let releaseTail: (() => void) | undefined;
+let heldClosed: (() => void) | undefined;
+const seen: { method?: string; acceptEncoding?: string; body: string }[] = [];
+const core = createServer((req, res) => {
+ let body = "";
+ req.on("data", (c: Buffer) => (body += c));
+ req.on("end", () => {
+ seen.push({ method: req.method, acceptEncoding: req.headers["accept-encoding"], body });
+ if (req.method === "DELETE") return void res.end(JSON.stringify({ echoed: JSON.parse(body) }));
+ res.writeHead(200, { "content-type": "application/json" });
+ res.write('{"sessions":[');
+ res.once("close", () => heldClosed?.());
+ releaseTail = () => res.end("]}");
+ });
+}).listen(0, "127.0.0.1");
+await once(core, "listening");
+process.env.CORE_API_URL = `http://127.0.0.1:${(core.address() as AddressInfo).port}`;
+process.env.CORE_SIGNING_SECRET = secret;
+process.env.WEB_UI_PRINCIPALS = "alice";
+const { handler } = await import("../server/index.ts");
+const web = createServer((req, res) => void handler(req, res)).listen(0, "127.0.0.1");
+await once(web, "listening");
+test.after(() => {
+ releaseTail?.();
+ web.closeAllConnections();
+ web.close();
+ core.closeAllConnections();
+ core.close();
+});
+
+function get(path: string, headers: Record<string, string>, method = "GET", body?: string): Promise<IncomingMessage> {
+ const token = mintPortalIdentity({ p: "alice", exp: Date.now() + 60_000 }, secret);
+ return new Promise((resolve, reject) => {
+ const req = request({ host: "127.0.0.1", port: (web.address() as AddressInfo).port, path, method }, resolve);
+ req.setHeader(PORTAL_IDENTITY_HEADER, token);
+ for (const [k, v] of Object.entries(headers)) req.setHeader(k, v);
+ if (body) req.setHeader("content-length", Buffer.byteLength(body));
+ req.on("error", reject);
+ req.end(body);
+ });
+}
+
+async function collect(res: IncomingMessage): Promise<Buffer> {
+ const chunks: Buffer[] = [];
+ for await (const c of res) chunks.push(c as Buffer);
+ return Buffer.concat(chunks);
+}
+
+test("session list streams the first core bytes before core finishes the body", { timeout: 5_000 }, async () => {
+ const res = await get("/api/sessions", {});
+ assert.equal(res.statusCode, 200);
+ assert.equal(res.headers["content-type"], "application/json");
+ assert.equal(seen.at(-1)?.acceptEncoding, "identity");
+ const [first] = (await once(res, "data")) as [Buffer];
+ assert.equal(first.toString(), '{"sessions":[');
+ releaseTail!();
+ const rest = await collect(res);
+ assert.equal(first.toString() + rest.toString(), '{"sessions":[]}');
+});
+
+test("a relayed DELETE carries its JSON body to core", async () => {
+ const res = await get("/api/memory", { "content-type": "application/json" }, "DELETE", '{"ids":["f1"]}');
+ assert.equal(res.statusCode, 200);
+ assert.deepEqual(JSON.parse((await collect(res)).toString()), {
+ echoed: { principalId: "alice", ids: ["f1"] },
+ });
+});
+
+test("a browser that leaves mid-body closes the core response too", { timeout: 5_000 }, async () => {
+ const closed = new Promise<void>((resolve) => (heldClosed = resolve));
+ const res = await get("/api/sessions", {});
+ await once(res, "data");
+ res.destroy();
+ await Promise.race([
+ closed,
+ new Promise((_, reject) => setTimeout(() => reject(new Error("core response still open")), 500)),
+ ]);
+});
diff --git a/plugins/web-ui/test/response-compression.test.ts b/plugins/web-ui/test/response-compression.test.ts
index 1d993cda8..a2cfc95e3 100644
--- a/plugins/web-ui/test/response-compression.test.ts
+++ b/plugins/web-ui/test/response-compression.test.ts
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { gunzipSync, gzipSync } from "node:zlib";
import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";
+import { sendBuffered } from "../../chassis/src/http.ts";
const SECRET = "web-ui-compression-test";
@@ -21,8 +22,12 @@ const sessionsPayload = JSON.stringify({
const core = createServer((req: IncomingMessage, res) => {
req.resume();
- res.writeHead(200, { "content-type": "application/json" });
- res.end((req.url ?? "").startsWith("/v1/sessions") ? sessionsPayload : "{}");
+ sendBuffered(
+ res,
+ 200,
+ { "content-type": "application/json" },
+ (req.url ?? "").startsWith("/v1/sessions") ? sessionsPayload : "{}",
+ );
});
await new Promise<void>((r) => core.listen(0, r));