Multiplayer agent harness for work.
Let listed first-party origins call the web chat API (#2004)
Tom Firth5be0bd1b111d
diff --git a/plugins/chassis/src/http.ts b/plugins/chassis/src/http.tsindex c5059d3ba..d3c792dfc 100644--- a/plugins/chassis/src/http.ts+++ b/plugins/chassis/src/http.ts@@ -28,8 +28,16 @@ export function gzipAccepted(req: IncomingMessage | undefined): boolean {return explicit ?? wildcard ?? false;}+export function withVary(res: ServerResponse, value: string): string {+ const existing = res.getHeader("vary");+ const tokens = [...(existing === undefined ? [] : String(existing).split(",")), ...value.split(",")]+ .map((token) => token.trim())+ .filter(Boolean);+ return [...new Map(tokens.map((token) => [token.toLowerCase(), token])).values()].join(", ");+}+export function sendBuffered(res: ServerResponse, status: number, headers: Record<string, string>, body: string): void {- const out = { ...headers, vary: "accept-encoding" };+ const out = { ...headers, vary: withVary(res, "accept-encoding") };if (Buffer.byteLength(body) < COMPRESS_MIN_BYTES || !gzipAccepted(res.req)) {res.writeHead(status, out);res.end(body);diff --git a/plugins/portal/README.md b/plugins/portal/README.mdindex f117fe120..3bc9def9e 100644--- a/plugins/portal/README.md+++ b/plugins/portal/README.md@@ -136,7 +136,18 @@ disposable test deployment: the test redeems real links for its configured admin- **Non-admin users need no per-id config.** `PORTAL_EXPECTED_TEAM_ID` pins the workspace, so anyverified member is a valid user (`WEB_UI_PRINCIPALS` empty = any verified principal).- **CSRF / open-redirect.** Every non-GET requires a same-origin `Origin`; `returnTo` is reduced- to a same-origin path (rejects `//evil`, `/\evil`, `https:/evil`, `%2f%2f`/`%5c`).+ to a same-origin path (rejects `//evil`, `/\evil`, `https:/evil`, `%2f%2f`/`%5c`). The one+ exception is an origin listed in `PORTAL_API_ALLOWED_ORIGINS`, and only on the chat API (below).+- **Embedding the chat from another app.** `PORTAL_API_ALLOWED_ORIGINS` lists the exact+ origins (comma-separated, bare `https://host[:port]`, no wildcards) that may call the web+ surface's chat API from their own pages with the user's portal session: `/me`, sending a turn,+ following, cancelling and withdrawing runs, listing and reading sessions and their approvals,+ deciding an approval, uploading attachment blobs, and downloading files. Those routes answer CORS preflights+ for listed origins and grant them credentialed reads and writes. Every other route keeps the+ same-origin rule, and unlisted origins get nothing. The session cookie is `SameSite=Lax`, so a+ browser only sends it on these calls when the embedding app is on the same site as the portal+ (for example `internal.example.com` beside `qm.example.com`). Listing an origin trusts every+ page on it to act as any signed-in user who visits it, so list only first-party apps.- **Secret hygiene.** In production the portal refuses to boot unless `PORTAL_SESSION_SECRET`,`PORTAL_IDENTITY_SECRET`, and `OIDC_CLIENT_SECRET` are set and distinct from core ingress auth.Public and OIDC endpoints must use HTTPS. Session and temporary cookies use domain-separated keys.@@ -226,6 +237,8 @@ Non-secret (`[env]`): `PORT` (8097 local / 8080 image), `PORTAL_PUBLIC_URL`, `CO`PORTAL_SESSION_TTL_S`, `PORTAL_SESSION_MAX_TTL_S`. `PORTAL_SESSION_MAX_TTL_S` caps a session's total life from authentication; it defaults to the larger of 30 days and `PORTAL_SESSION_TTL_S`, and boot fails if it is set below the TTL.There is no `PORTAL_ADMIN_PRINCIPALS` — adminaccess is derived from the core (see the security model above).+`PORTAL_API_ALLOWED_ORIGINS` (default empty) opens the chat API to other first-party origins;+see the security model. Boot fails on an entry that is not a bare https origin (plain http only for localhost).For local development only, `PORTAL_LOCAL_AUTH_BYPASS=1` mints a local session as`PORTAL_DEV_PRINCIPAL` without contacting OIDC. The portal refuses this in productionand only accepts it when `PORTAL_PUBLIC_URL` is loopback.diff --git a/plugins/portal/src/cors.ts b/plugins/portal/src/cors.tsnew file mode 100644index 000000000..6addece09--- /dev/null+++ b/plugins/portal/src/cors.ts@@ -0,0 +1,83 @@+import type { IncomingMessage, ServerResponse } from "node:http";++const ALLOWED_METHODS = "GET, POST";+const ALLOWED_HEADERS = "content-type";+const EXPOSED_HEADERS = "content-disposition";+const PREFLIGHT_MAX_AGE_S = 600;++const ID = "[^/]+";+const FILE_ID = "(?!by-name(?:/|$))[^/]+";+const CHAT_API_ROUTES: ReadonlyArray<{ method: string; re: RegExp }> = [+ { method: "GET", re: /^\/me$/ },+ { method: "POST", re: /^\/api\/turn$/ },+ { method: "GET", re: /^\/api\/runs\/active$/ },+ { method: "GET", re: new RegExp(`^/api/runs/${ID}$`) },+ { method: "GET", re: new RegExp(`^/api/runs/${ID}/events$`) },+ { method: "POST", re: new RegExp(`^/api/runs/${ID}/signal$`) },+ { method: "POST", re: new RegExp(`^/api/runs/${ID}/withdraw$`) },+ { method: "GET", re: /^\/api\/sessions$/ },+ { method: "GET", re: new RegExp(`^/api/sessions/${ID}$`) },+ { method: "GET", re: new RegExp(`^/api/sessions/${ID}/approvals$`) },+ { method: "POST", re: new RegExp(`^/api/approvals/${ID}$`) },+ { method: "POST", re: /^\/api\/blobs$/ },+ { method: "GET", re: new RegExp(`^/api/files/${FILE_ID}/content(?:/${ID})?$`) },+];++export function parseAllowedOrigins(raw: string | undefined): { origins: Set<string>; problems: string[] } {+ const origins = new Set<string>();+ const problems: string[] = [];+ for (const entry of (raw ?? "").split(",").map((part) => part.trim())) {+ if (!entry) continue;+ let url: URL;+ try {+ url = new URL(entry);+ } catch {+ problems.push(`PORTAL_API_ALLOWED_ORIGINS entry "${entry}" is not a URL`);+ continue;+ }+ if (url.origin !== entry) {+ problems.push(+ `PORTAL_API_ALLOWED_ORIGINS entry "${entry}" must be a bare origin (scheme, host and optional port, no path or trailing slash), e.g. "${url.origin}"`,+ );+ continue;+ }+ if (url.protocol !== "https:" && url.hostname !== "localhost" && url.hostname !== "127.0.0.1") {+ problems.push(`PORTAL_API_ALLOWED_ORIGINS entry "${entry}" must use https`);+ continue;+ }+ origins.add(url.origin);+ }+ return { origins, problems };+}++export function isChatApiRoute(method: string, pathname: string): boolean {+ return CHAT_API_ROUTES.some((route) => route.method === method && route.re.test(pathname));+}++export function prepareCors(+ req: IncomingMessage,+ res: ServerResponse,+ pathname: string,+ allowed: ReadonlySet<string>,+): string | undefined {+ if (allowed.size === 0) return undefined;+ const method = req.method === "OPTIONS" ? String(req.headers["access-control-request-method"] ?? "") : req.method;+ if (!isChatApiRoute(method ?? "", pathname)) return undefined;+ res.setHeader("vary", "Origin");+ const origin = req.headers.origin;+ if (typeof origin !== "string" || !allowed.has(origin)) return undefined;+ res.setHeader("access-control-allow-origin", origin);+ res.setHeader("access-control-allow-credentials", "true");+ res.setHeader("access-control-expose-headers", EXPOSED_HEADERS);+ return origin;+}++export function answerPreflight(res: ServerResponse): void {+ res.writeHead(204, {+ "access-control-allow-methods": ALLOWED_METHODS,+ "access-control-allow-headers": ALLOWED_HEADERS,+ "access-control-max-age": String(PREFLIGHT_MAX_AGE_S),+ "cache-control": "no-store",+ });+ res.end();+}diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex 47d11f3ac..0ac3c4a9b 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -15,6 +15,7 @@ import { pathToFileURL } from "node:url";import { ADMIN_LOGIN_SCRIPT, ADMIN_LOGIN_SCRIPT_HASH, openAdminLogin } from "./admin-login.ts";import { LRUCache } from "lru-cache";import { createTrustedEntry, trustedEntryConfig } from "./trusted-entry.ts";+import { answerPreflight, parseAllowedOrigins, prepareCors } from "./cors.ts";import {deriveKey,seal,@@ -95,6 +96,7 @@ const ORIGIN = (() => {return "";}})();+const API_ALLOWED_ORIGINS = parseAllowedOrigins(process.env.PORTAL_API_ALLOWED_ORIGINS);const LOCAL_AUTH_BYPASS_REQUESTED = process.env.PORTAL_LOCAL_AUTH_BYPASS === "1";const LOCAL_AUTH_BYPASS = LOCAL_AUTH_BYPASS_REQUESTED && !IS_PROD && isLocalPortalUrl(PUBLIC_URL);const LOCAL_AUTH_PRINCIPAL = process.env.PORTAL_DEV_PRINCIPAL || process.env.USER || "dev-admin";@@ -1000,6 +1002,9 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>return proxyToAppHost(req, res, CORE);}+ const crossOrigin = prepareCors(req, res, pathname, API_ALLOWED_ORIGINS.origins);+ if (crossOrigin && method === "OPTIONS") return answerPreflight(res);+const brokerPath = brokerRouteFor(method, pathname);const reauthentication =(method === "GET" &&@@ -1315,7 +1320,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>}}- if (method !== "GET" && method !== "HEAD" && !sameOriginRequest(req)) {+ if (method !== "GET" && method !== "HEAD" && !crossOrigin && !sameOriginRequest(req)) {return json(res, 403, { error: "forbidden", message: "cross-origin request refused" });}@@ -1366,7 +1371,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>let principal = session.sub;let impersonator: string | undefined;- if (key === "web-ui") {+ if (key === "web-ui" && !crossOrigin) {const imp = openImpersonation(readCookie(req.headers.cookie, "portal_impersonate"), impersonateKey, Date.now());if (imp && imp.actor === session.sub && imp.org === session.org && (await isAdmin(session.sub))) {principal = imp.target;@@ -1741,7 +1746,19 @@ async function authCallback(req: IncomingMessage, res: ServerResponse, url: URL)}export function bootChecks(): void {- const problems: string[] = [];+ const problems: string[] = [...API_ALLOWED_ORIGINS.problems];+ for (const origin of API_ALLOWED_ORIGINS.origins) {+ const host = hostOf(origin);+ if (IS_PROD && !origin.startsWith("https://")) {+ problems.push(`PORTAL_API_ALLOWED_ORIGINS entry "${origin}" must use https in production`);+ }+ if (APPS_DOMAIN && hostIsWithinDomain(host, APPS_DOMAIN)) {+ problems.push(+ `PORTAL_API_ALLOWED_ORIGINS entry "${origin}" is under the apps domain (${APPS_DOMAIN}), which serves user-deployed apps`,+ );+ }+ if (origin === ORIGIN) problems.push(`PORTAL_API_ALLOWED_ORIGINS must not list the portal's own origin`);+ }if (!AUTH_BROKER_UPSTREAM && originOf(OIDC.authEndpoint) && originOf(OIDC.authEndpoint) === originOf(PUBLIC_URL)) {problems.push("OIDC_AUTH_ENDPOINT is on the portal's own origin but AUTH_BROKER_UPSTREAM is unset — every sign-in would redirect from /auth/login back into the portal forever; wire AUTH_BROKER_UPSTREAM to the auth service or point OIDC_AUTH_ENDPOINT at a real identity provider",diff --git a/plugins/portal/src/proxy.ts b/plugins/portal/src/proxy.tsindex 823264b45..579f0647f 100644--- a/plugins/portal/src/proxy.ts+++ b/plugins/portal/src/proxy.ts@@ -1,5 +1,6 @@import { request as httpRequest, type IncomingMessage, type ServerResponse } from "node:http";import { signedHeaders } from "../../chassis/src/core-client.ts";+import { withVary } from "../../chassis/src/http.ts";import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";const IDENTITY_TTL_MS = 60_000;@@ -75,6 +76,7 @@ function relay(continue;out[k] = v;}+ if (out.vary !== undefined) out.vary = withVary(res, String(out.vary));if (target.honorFramePolicy && declaresFrameAncestors(out)) res.removeHeader("x-frame-options");res.writeHead(upRes.statusCode ?? 502, out);upRes.on("error", () => res.destroy());diff --git a/plugins/portal/test/api-cors.test.ts b/plugins/portal/test/api-cors.test.tsnew file mode 100644index 000000000..76d9eff13--- /dev/null+++ b/plugins/portal/test/api-cors.test.ts@@ -0,0 +1,211 @@+import test from "node:test";+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createServer, type IncomingMessage } from "node:http";+import type { AddressInfo } from "node:net";+import { isChatApiRoute, parseAllowedOrigins } from "../src/cors.ts";++const upstream = createServer((req: IncomingMessage, res) => {+ req.resume();+ req.on("end", () => {+ if (req.url === "/api/whoami") {+ res.writeHead(200, { "content-type": "application/json" });+ return void res.end(JSON.stringify({ isAdmin: (req.headers.cookie ?? "").includes("admin=U-admin") }));+ }+ res.writeHead(200, { "content-type": "application/json", vary: "accept-encoding" });+ res.end(JSON.stringify({ url: req.url, method: req.method, cookie: req.headers.cookie ?? null }));+ });+});+await new Promise<void>((r) => upstream.listen(0, r));+const upstreamUrl = `http://localhost:${(upstream.address() as AddressInfo).port}`;++const PUBLIC = "https://qm.test";+const EMBEDDER = "https://internal.example.test";+const STRANGER = "https://apps.qm.test";+process.env.PORTAL_PUBLIC_URL = PUBLIC;+process.env.PORTAL_SESSION_SECRET = "api-cors-test-portal-secret-0123456789";+process.env.CORE_SIGNING_SECRET = "api-cors-test-core-secret";+process.env.WEB_UI_UPSTREAM = upstreamUrl;+process.env.ADMIN_UPSTREAM = upstreamUrl;+process.env.CORE_API_URL = upstreamUrl;+process.env.PORTAL_API_ALLOWED_ORIGINS = `${EMBEDDER}, http://localhost:5173`;+const SESSION_TTL_S = 28800;+process.env.PORTAL_SESSION_TTL_S = String(SESSION_TTL_S);++const { server } = await import("../src/index.ts");+const { deriveKey, seal } = await import("../src/session.ts");+const impersonateKey = deriveKey("api-cors-test-portal-secret-0123456789", "portal.impersonate.v1");+await new Promise<void>((r) => server.listen(0, r));+const base = `http://localhost:${(server.address() as AddressInfo).port}`;++const sessionKey = deriveKey("api-cors-test-portal-secret-0123456789", "portal.session.v1");+function sessionCookie(sub: string): string {+ const iat = Math.floor(Date.now() / 1000);+ return `portal_session=${encodeURIComponent(seal({ k: "session", sub, org: "acme", iat, exp: iat + SESSION_TTL_S }, sessionKey))}`;+}++function impersonating(actor: string, target: string): string {+ const iat = Math.floor(Date.now() / 1000);+ return `portal_impersonate=${encodeURIComponent(seal({ k: "impersonate", actor, target, org: "acme", iat, exp: iat + 3600 }, impersonateKey))}`;+}++test.after(() => {+ server.close();+ upstream.close();+});++function preflight(path: string, origin: string, method = "POST"): Promise<Response> {+ return fetch(`${base}${path}`, {+ method: "OPTIONS",+ headers: { origin, "access-control-request-method": method, "access-control-request-headers": "content-type" },+ });+}++test("an allowlisted origin's preflight for a chat route is answered without a session", async () => {+ const r = await preflight("/api/turn", EMBEDDER);+ assert.equal(r.status, 204);+ assert.equal(r.headers.get("access-control-allow-origin"), EMBEDDER);+ assert.equal(r.headers.get("access-control-allow-credentials"), "true");+ assert.match(r.headers.get("access-control-allow-methods") ?? "", /POST/);+ assert.equal(r.headers.get("access-control-allow-headers"), "content-type");+ assert.equal(r.headers.get("vary"), "Origin");+});++test("a preflight from an unlisted origin, or for a route outside the chat API, gets no CORS grant", async () => {+ for (const r of [+ await preflight("/api/turn", STRANGER),+ await preflight("/api/memory", EMBEDDER, "PUT"),+ await preflight("/auth/logout", EMBEDDER),+ await preflight("/admin/api/whoami", EMBEDDER, "GET"),+ await preflight("/api/turn", EMBEDDER, "DELETE"),+ ]) {+ assert.equal(r.headers.get("access-control-allow-origin"), null);+ }+});++test("an allowlisted origin can POST a turn with the session cookie, and can read the answer", async () => {+ const r = await fetch(`${base}/api/turn`, {+ method: "POST",+ headers: { cookie: sessionCookie("U1"), origin: EMBEDDER, "content-type": "application/json" },+ body: JSON.stringify({ text: "hi" }),+ });+ assert.equal(r.status, 200);+ assert.equal(r.headers.get("access-control-allow-origin"), EMBEDDER);+ assert.equal(r.headers.get("access-control-allow-credentials"), "true");+ assert.equal(r.headers.get("access-control-expose-headers"), "content-disposition");+ assert.equal(((await r.json()) as { url: string }).url, "/api/turn");+});++test("Vary: Origin survives the surface's own Vary, and is sent on chat routes whatever the origin", async () => {+ for (const origin of [EMBEDDER, PUBLIC, STRANGER]) {+ const r = await fetch(`${base}/api/sessions/s1`, { headers: { cookie: sessionCookie("U1"), origin } });+ assert.equal(r.headers.get("vary"), "Origin, accept-encoding", origin);+ }+ const signedOut = await fetch(`${base}/me`, { headers: { origin: EMBEDDER } });+ assert.match(signedOut.headers.get("vary") ?? "", /Origin/);+});++test("an admin's impersonation applies to QM's own pages but never to calls from an embedding origin", async () => {+ const cookie = `${sessionCookie("U-admin")}; ${impersonating("U-admin", "alice@acme")}`;+ const same = await fetch(`${base}/api/sessions/s1`, { headers: { cookie, origin: PUBLIC } });+ assert.match(((await same.json()) as { cookie: string }).cookie, /webuiuser=alice%40acme/);+ const cross = await fetch(`${base}/api/sessions/s1`, { headers: { cookie, origin: EMBEDDER } });+ const forwarded = ((await cross.json()) as { cookie: string }).cookie;+ assert.match(forwarded, /webuiuser=U-admin/);+ assert.doesNotMatch(forwarded, /impersonator/);+});++test("reads of the chat API carry the CORS grant, including a signed-out 401 the embedder must read", async () => {+ const session = await fetch(`${base}/api/sessions/s1?tailTurns=5`, {+ headers: { cookie: sessionCookie("U1"), origin: EMBEDDER },+ });+ assert.equal(session.status, 200);+ assert.equal(session.headers.get("access-control-allow-origin"), EMBEDDER);+ const signedOut = await fetch(`${base}/me`, { headers: { origin: EMBEDDER } });+ assert.equal(signedOut.status, 401);+ assert.equal(signedOut.headers.get("access-control-allow-origin"), EMBEDDER);+});++test("CSRF still holds: an allowlisted origin cannot write outside the chat API, and an unlisted one cannot write at all", async () => {+ const outside = await fetch(`${base}/api/memory/restore`, {+ method: "POST",+ headers: { cookie: sessionCookie("U1"), origin: EMBEDDER },+ });+ assert.equal(outside.status, 403);+ assert.equal(outside.headers.get("access-control-allow-origin"), null);+ const stranger = await fetch(`${base}/api/turn`, {+ method: "POST",+ headers: { cookie: sessionCookie("U1"), origin: STRANGER },+ });+ assert.equal(stranger.status, 403);+ assert.equal(stranger.headers.get("access-control-allow-origin"), null);+});++test("same-origin requests are untouched by the allowlist", async () => {+ const r = await fetch(`${base}/api/turn`, {+ method: "POST",+ headers: { cookie: sessionCookie("U1"), origin: PUBLIC },+ });+ assert.equal(r.status, 200);+ assert.equal(r.headers.get("access-control-allow-origin"), null);+});++test("PORTAL_API_ALLOWED_ORIGINS accepts bare https origins and rejects everything else", () => {+ const ok = parseAllowedOrigins(" https://a.example.com ,https://b.example.com:8443,, http://localhost:5173");+ assert.deepEqual([...ok.origins], ["https://a.example.com", "https://b.example.com:8443", "http://localhost:5173"]);+ assert.deepEqual(ok.problems, []);+ assert.deepEqual([...parseAllowedOrigins(undefined).origins], []);+ for (const bad of ["*", "https://a.example.com/", "https://a.example.com/path", "http://a.example.com", "null"]) {+ const parsed = parseAllowedOrigins(bad);+ assert.equal(parsed.origins.size, 0, bad);+ assert.equal(parsed.problems.length, 1, bad);+ }+});++test("the chat API route set is exact on method and shape", () => {+ assert.ok(isChatApiRoute("GET", "/api/runs/r1/events"));+ assert.ok(isChatApiRoute("POST", "/api/runs/r1/signal"));+ assert.ok(isChatApiRoute("GET", "/api/files/f1/content/report.pdf"));+ assert.ok(isChatApiRoute("POST", "/api/blobs"));+ assert.ok(isChatApiRoute("GET", "/api/sessions"));+ assert.ok(!isChatApiRoute("POST", "/api/files/upload"));+ assert.ok(!isChatApiRoute("GET", "/api/files/by-name/content"));+ assert.ok(isChatApiRoute("GET", "/api/files/by-name-x/content"));+ assert.ok(!isChatApiRoute("PATCH", "/api/runs/r1/input"));+ assert.ok(!isChatApiRoute("POST", "/api/runs/r1/events"));+ assert.ok(!isChatApiRoute("GET", "/api/runs/r1/events/extra"));+ assert.ok(!isChatApiRoute("POST", "/api/sessions/s1"));+ assert.ok(!isChatApiRoute("POST", "/api/sessions/s1/share"));+});++test("boot refuses allowlist entries that would trust untrusted or downgraded origins", async () => {+ const command = "import('./src/index.ts').then(m => m.bootChecks())";+ const baseEnv: NodeJS.ProcessEnv = { ...process.env, NODE_ENV: "test", PORTAL_PUBLIC_URL: "https://qm.example.com" };+ delete baseEnv.PORTAL_COOKIE_DOMAIN;+ delete baseEnv.PORTAL_APPS_DOMAIN;+ delete baseEnv.DEPLOY_APPS_DOMAIN;+ delete baseEnv.PORTAL_PLAYGROUND;+ const boot = (env: NodeJS.ProcessEnv) =>+ new Promise<{ status: number | null; stderr: string }>((resolve, reject) => {+ const child = spawn(process.execPath, ["--input-type=module", "-e", command], { cwd: process.cwd(), env });+ let stderr = "";+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk));+ child.on("error", reject).on("close", (status) => resolve({ status, stderr }));+ });+ const ok = await boot({ ...baseEnv, PORTAL_API_ALLOWED_ORIGINS: "https://internal.example.com" });+ assert.equal(ok.status, 0, ok.stderr);+ const bad: Array<[NodeJS.ProcessEnv, RegExp]> = [+ [{ PORTAL_API_ALLOWED_ORIGINS: "https://internal.example.com/" }, /must be a bare origin/],+ [{ PORTAL_API_ALLOWED_ORIGINS: "http://internal.example.com" }, /must use https/],+ [{ PORTAL_API_ALLOWED_ORIGINS: "https://qm.example.com" }, /portal's own origin/],+ [+ { PORTAL_API_ALLOWED_ORIGINS: "https://tool.apps.qm.example.com", DEPLOY_APPS_DOMAIN: "apps.qm.example.com" },+ /under the apps domain/,+ ],+ ];+ const refused = await Promise.all(bad.map(([extra]) => boot({ ...baseEnv, ...extra })));+ bad.forEach(([extra, pattern], i) => {+ assert.notEqual(refused[i]!.status, 0, `expected boot failure for ${JSON.stringify(extra)}`);+ assert.match(refused[i]!.stderr, pattern);+ });+});diff --git a/src/api/http.ts b/src/api/http.tsindex c7ba4d688..9f458ed92 100644--- a/src/api/http.ts+++ b/src/api/http.ts@@ -22,8 +22,16 @@ export function gzipAccepted(req: IncomingMessage | undefined): boolean {return explicit ?? wildcard ?? false;}+export function withVary(res: ServerResponse, value: string): string {+ const existing = res.getHeader("vary");+ const tokens = [...(existing === undefined ? [] : String(existing).split(",")), ...value.split(",")]+ .map((token) => token.trim())+ .filter(Boolean);+ return [...new Map(tokens.map((token) => [token.toLowerCase(), token])).values()].join(", ");+}+export function sendBuffered(res: ServerResponse, status: number, headers: Record<string, string>, body: string): void {- const out = { ...headers, vary: "accept-encoding" };+ const out = { ...headers, vary: withVary(res, "accept-encoding") };if (Buffer.byteLength(body) < COMPRESS_MIN_BYTES || !gzipAccepted(res.req)) {res.writeHead(status, out);res.end(body);diff --git a/test/composio-route.test.ts b/test/composio-route.test.tsindex 6d257f2d9..2cf202ca3 100644--- a/test/composio-route.test.ts+++ b/test/composio-route.test.ts@@ -50,6 +50,7 @@ function fixture() {const url = new URL(path, "http://localhost");const res = {setHeader() {},+ getHeader() {},writeHead(code: number) {status = code;},diff --git a/test/connectors.test.ts b/test/connectors.test.tsindex 2034cc382..6bd9a5fc2 100644--- a/test/connectors.test.ts+++ b/test/connectors.test.ts@@ -424,6 +424,7 @@ test("oauthRevoke: a capability token disconnects its own connector, but not a nconst call = (capability: unknown, body: unknown) => {const out: { status?: number; body?: any } = {};const res = {+ getHeader() {},writeHead(s: number) {out.status = s;},diff --git a/test/context-policy-routes.test.ts b/test/context-policy-routes.test.tsindex 48d616fdf..d6dab3901 100644--- a/test/context-policy-routes.test.ts+++ b/test/context-policy-routes.test.ts@@ -8,6 +8,7 @@ function fakeRes() {const out = { status: 0, body: undefined as unknown };return {res: {+ getHeader() {},writeHead(status: number) {out.status = status;return this;diff --git a/test/git-http-broker.test.ts b/test/git-http-broker.test.tsindex a7974464b..87f93f197 100644--- a/test/git-http-broker.test.ts+++ b/test/git-http-broker.test.ts@@ -18,6 +18,7 @@ function res(): ServerResponse & PassThrough & { capturedHeaders?: Record<stringconst r = new PassThrough() as ServerResponse & PassThrough & { capturedHeaders?: Record<string, string> };let sent = false;Object.defineProperty(r, "headersSent", { get: () => sent });+ r.getHeader = () => undefined;r.writeHead = ((statusCode: number, headers?: Record<string, string>) => {r.statusCode = statusCode;r.capturedHeaders = headers ?? {};diff --git a/test/gmail-sent-route.test.ts b/test/gmail-sent-route.test.tsindex 5260383ed..d2972319d 100644--- a/test/gmail-sent-route.test.ts+++ b/test/gmail-sent-route.test.ts@@ -11,6 +11,7 @@ test("sent mail requires portal identity and ignores a forged principal query",url: new URL("http://localhost/v1/connectors/gmail/sent?principalId=someone-else"),res: {setHeader() {},+ getHeader() {},writeHead(code: number) {status = code;},@@ -56,6 +57,7 @@ test("sent mail resolves the connected Google account slot", async () => {params: {},res: {setHeader() {},+ getHeader() {},writeHead(code: number) {status = code;},diff --git a/test/inbox-selection.test.ts b/test/inbox-selection.test.tsindex 1d4029277..a9819c249 100644--- a/test/inbox-selection.test.ts+++ b/test/inbox-selection.test.ts@@ -48,6 +48,7 @@ function world(enabled = true, sourceRefresh?: ApiCtx["deps"]["inboxSourceRefresmanagesScope: async () => false,},res: {+ getHeader: () => undefined,writeHead: (value: number) => {status = value;},diff --git a/test/loop-ingress.test.ts b/test/loop-ingress.test.tsindex 9fabbcb1a..46fb90183 100644--- a/test/loop-ingress.test.ts+++ b/test/loop-ingress.test.ts@@ -329,6 +329,7 @@ test("ingestion configuration rejects nonowners and unattended callers", async (managesScope: async () => false,},res: {+ getHeader: () => undefined,writeHead: (value: number) => {status = value;},diff --git a/test/loop-item-routes.test.ts b/test/loop-item-routes.test.tsindex 88a15325a..ffeb275af 100644--- a/test/loop-item-routes.test.ts+++ b/test/loop-item-routes.test.ts@@ -21,6 +21,7 @@ function fakeRes() {const out = { status: 0, body: undefined as unknown };return {res: {+ getHeader() {},writeHead(status: number) {out.status = status;return this;diff --git a/test/loop-routes.test.ts b/test/loop-routes.test.tsindex 3949418fe..706d530cc 100644--- a/test/loop-routes.test.ts+++ b/test/loop-routes.test.ts@@ -16,6 +16,7 @@ function fakeRes() {const out = { status: 0, body: undefined as unknown };return {res: {+ getHeader() {},writeHead(status: number) {out.status = status;return this;diff --git a/test/member-edit-authz.test.ts b/test/member-edit-authz.test.tsindex 845f7c1c0..2cbfbec9c 100644--- a/test/member-edit-authz.test.ts+++ b/test/member-edit-authz.test.ts@@ -276,6 +276,7 @@ test("SOUL: the HTTP route reports durable storage failures as 500", async () =>const app = createApp(makeDeps({ config }) as unknown as AppDeps);const out: { status?: number; body?: { error?: string } } = {};const res = {+ getHeader() {},writeHead(status: number) {out.status = status;},@@ -308,6 +309,7 @@ test("SOUL: failed persistence restores the pre-write cache even when compensaticonst app = createApp(makeDeps({ config }) as unknown as AppDeps);const out: { status?: number } = {};const res = {+ getHeader() {},writeHead(status: number) {out.status = status;},diff --git a/test/response-compression-twins.test.ts b/test/response-compression-twins.test.tsindex 1d144695e..42d63c7e1 100644--- a/test/response-compression-twins.test.ts+++ b/test/response-compression-twins.test.ts@@ -15,7 +15,7 @@ const core = readFileSync(fileURLToPath(new URL("../src/api/http.ts", import.metconst chassis = readFileSync(fileURLToPath(new URL("../plugins/chassis/src/http.ts", import.meta.url)), "utf8");test("the plugin chassis carries a byte-identical copy of the response compressor", () => {- for (const name of ["gzipAccepted", "sendBuffered"]) {+ for (const name of ["gzipAccepted", "withVary", "sendBuffered"]) {assert.equal(extract(chassis, name),extract(core, name),diff --git a/test/sent-chat.test.ts b/test/sent-chat.test.tsindex 16beea73f..248306a3f 100644--- a/test/sent-chat.test.ts+++ b/test/sent-chat.test.ts@@ -19,6 +19,7 @@ test("sent chats are durable, idempotent, and isolated to the signed-in owner",deps: { loops: { store, items }, featureFlags: { enabled: async () => previewEnabled } },res: {setHeader() {},+ getHeader() {},writeHead(code: number) {status = code;},@@ -99,6 +100,7 @@ test("a sent email draft saves and sends into the original Gmail thread exactly},res: {setHeader() {},+ getHeader() {},writeHead(code: number) {status = code;},@@ -169,6 +171,7 @@ test("sent chat preserves long quoted recipient headers and rejects oversized indeps: { loops: { store, items }, featureFlags: { enabled: async () => true } },res: {setHeader() {},+ getHeader() {},writeHead(code: number) {status = code;},diff --git a/test/share-deployment.test.ts b/test/share-deployment.test.tsindex 6058e30a2..98621f6fc 100644--- a/test/share-deployment.test.ts+++ b/test/share-deployment.test.ts@@ -76,6 +76,7 @@ function callShare() {const out: { status?: number; body?: any } = {};const res = {+ getHeader() {},writeHead(s: number) {out.status = s;},@@ -102,6 +103,7 @@ function callManage() {const out: { status?: number; body?: any } = {};const res = {+ getHeader() {},writeHead(s: number) {out.status = s;},@@ -116,6 +118,7 @@ function callManage(function callDetail(app: ReturnType<typeof createApp>, capability: CapabilityClaims, id: string) {const out: { status?: number; body?: any } = {};const res = {+ getHeader() {},writeHead(s: number) {out.status = s;},@@ -735,6 +738,7 @@ test("exact email read grants admit app-only login and guest reach without membedeps: { identity, acl, featureFlags },url: new URL(`http://core/v1/auth/broker/email-allowed?email=${encodeURIComponent(email)}`),res: {+ getHeader() {},writeHead(s: number) {status = s;},diff --git a/test/share-verb.test.ts b/test/share-verb.test.tsindex b35b4253f..2a4bcbb7e 100644--- a/test/share-verb.test.ts+++ b/test/share-verb.test.ts@@ -547,6 +547,7 @@ test("a trigger (no liveActor) cannot MOVE a personal skill INTO a shared scopefunction callShareRoute(state: FakeState, capability: CapabilityClaims | null, body: unknown) {const out: { status?: number; body?: any } = {};const res = {+ getHeader() {},writeHead(s: number) {out.status = s;},diff --git a/test/suggested-activities-route.test.ts b/test/suggested-activities-route.test.tsindex a7a5699b1..5132a5e02 100644--- a/test/suggested-activities-route.test.ts+++ b/test/suggested-activities-route.test.ts@@ -23,6 +23,7 @@ async function request(body: unknown, enabled: boolean, actor = "alice") {}: {},res: {+ getHeader: () => undefined,writeHead: (code: number) => {status = code;},