Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(companion): large bot lists reach paired devices (stream the JSON scrub) (#4831)

Milind Soni80365572b981
diff --git a/companion/src/json-scrub.ts b/companion/src/json-scrub.ts
new file mode 100644
index 0000000000..0a97cc7a8c
--- /dev/null
+++ b/companion/src/json-scrub.ts
@@ -0,0 +1,191 @@
+// `scrub` for a JSON body that arrives in pieces: the same withheld members are dropped, and memory is one chunk
+// rather than the whole body. Strict JSON only. Anything else throws, because a structure this reader got wrong
+// could hide a withheld key from it while the device's JSON.parse still found that key.
+import { isWithheldKey } from "./wire.ts";
+
+/** Real payloads nest a few dozen deep; the stack here is an array, so this only bounds a hostile body's memory. */
+const MAX_DEPTH = 1_000;
+/** Field names, never content: a key this long is not one of ours. */
+const MAX_KEY_CHARS = 64 * 1024;
+const MAX_ATOM_CHARS = 512;
+const ATOM = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)$/;
+const ATOM_START = /^[-0-9tfn]$/;
+const ATOM_CHAR = /^[-+.0-9a-zA-Z]$/;
+/** `"` `\` `/` b f n r t */
+const ESCAPABLE = new Set([0x22, 0x5c, 0x2f, 0x62, 0x66, 0x6e, 0x72, 0x74]);
+
+// Where the reader is: what the next significant character may be.
+const VALUE = 0;
+const FIRST_VALUE = 1; // just after `[`
+const FIRST_KEY = 2; // just after `{`
+const KEY = 3; // after `,` in an object
+const KEY_STRING = 4;
+const COLON = 5;
+const STRING = 6;
+const ATOM_TEXT = 7;
+const AFTER = 8; // a value just ended
+
+const isHex = (c: number): boolean => (c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66);
+const isSpace = (char: string): boolean => char === " " || char === "\t" || char === "\n" || char === "\r";
+
+export interface JsonScrubber {
+ /** The scrubbed text this piece completes; it may be empty. Throws when the body is not JSON. */
+ write(chunk: string): string;
+ /** The rest; throws when the body stopped part-way through a value. */
+ end(): string;
+}
+
+/** Re-emits the body compactly (no insignificant whitespace), commas placed by this reader so that dropping a
+ * member never leaves a stray one. */
+export function createJsonScrubber(): JsonScrubber {
+ const stack: { object: boolean; members: number }[] = [];
+ let state = VALUE;
+ /** The depth whose current member is withheld; -1 while nothing is. */
+ let dropDepth = -1;
+ let key = "";
+ let atom = "";
+ let escape = false;
+ let hex = 0;
+ let out: string[] = [];
+
+ const fail = (why: string): never => {
+ throw new Error(`not JSON: ${why}`);
+ };
+ const emit = (text: string): void => {
+ if (dropDepth < 0) out.push(text);
+ };
+ const valueDone = (): void => {
+ state = AFTER;
+ if (dropDepth === stack.length) dropDepth = -1;
+ };
+ const close = (char: string): void => {
+ const top = stack.at(-1);
+ if (!top || top.object !== (char === "}")) fail(`unbalanced ${char}`);
+ emit(char);
+ stack.pop();
+ valueDone();
+ };
+ const startValue = (char: string): void => {
+ const top = stack.at(-1);
+ if (top && !top.object && top.members++ > 0) emit(",");
+ if (char === "{" || char === "[") {
+ if (stack.length >= MAX_DEPTH) fail("nested too deep");
+ emit(char);
+ stack.push({ object: char === "{", members: 0 });
+ state = char === "{" ? FIRST_KEY : FIRST_VALUE;
+ } else if (char === '"') {
+ emit(char);
+ state = STRING;
+ } else if (ATOM_START.test(char)) {
+ atom = char;
+ state = ATOM_TEXT;
+ } else {
+ fail(`unexpected ${JSON.stringify(char)}`);
+ }
+ };
+ const finishAtom = (): void => {
+ if (!ATOM.test(atom)) fail(`bad value ${JSON.stringify(atom.slice(0, 32))}`);
+ emit(atom);
+ atom = "";
+ valueDone();
+ };
+ /** The key is whole and checked by its decoded name, so an escaped spelling is withheld too. */
+ const member = (): void => {
+ const top = stack.at(-1)!;
+ const name = JSON.parse(key) as string;
+ if (dropDepth < 0 && isWithheldKey(name)) {
+ dropDepth = stack.length;
+ } else {
+ emit(`${top.members > 0 ? "," : ""}${key}:`);
+ top.members++;
+ }
+ key = "";
+ state = VALUE;
+ };
+
+ /** Consumes a string's characters up to and including its closing quote, or to the chunk's end. */
+ const scanString = (chunk: string, from: number): { next: number; closed: boolean } => {
+ let i = from;
+ while (i < chunk.length) {
+ const c = chunk.charCodeAt(i++);
+ if (hex > 0) {
+ if (!isHex(c)) fail("bad \\u escape");
+ hex--;
+ } else if (escape) {
+ escape = false;
+ if (c === 0x75) hex = 4;
+ else if (!ESCAPABLE.has(c)) fail("bad escape");
+ } else if (c === 0x5c) {
+ escape = true;
+ } else if (c === 0x22) {
+ return { next: i, closed: true };
+ } else if (c < 0x20) {
+ fail("control character in a string");
+ }
+ }
+ return { next: i, closed: false };
+ };
+
+ const write = (chunk: string): string => {
+ out = [];
+ let i = 0;
+ while (i < chunk.length) {
+ if (state === STRING || state === KEY_STRING) {
+ const { next, closed } = scanString(chunk, i);
+ const run = chunk.slice(i, next);
+ i = next;
+ if (state === STRING) {
+ emit(run);
+ if (closed) valueDone();
+ } else {
+ key += run;
+ if (key.length > MAX_KEY_CHARS) fail("key too long");
+ if (closed) state = COLON;
+ }
+ continue;
+ }
+ const char = chunk[i];
+ if (state === ATOM_TEXT) {
+ if (ATOM_CHAR.test(char)) {
+ atom += char;
+ if (atom.length > MAX_ATOM_CHARS) fail("value too long");
+ i++;
+ } else {
+ finishAtom(); // the character is read again as what follows the value
+ }
+ continue;
+ }
+ i++;
+ if (isSpace(char)) continue;
+ if (state === VALUE) startValue(char);
+ else if (state === FIRST_VALUE && char === "]") close(char);
+ else if (state === FIRST_VALUE) startValue(char);
+ else if (state === FIRST_KEY && char === "}") close(char);
+ else if (state === FIRST_KEY || state === KEY) {
+ if (char !== '"') fail("expected a key");
+ key = char;
+ state = KEY_STRING;
+ } else if (state === COLON) {
+ if (char !== ":") fail("expected :");
+ member();
+ } else if (char === "}" || char === "]") {
+ close(char);
+ } else if (char === "," && stack.length) {
+ state = stack.at(-1)!.object ? KEY : VALUE;
+ } else {
+ fail(stack.length ? `unexpected ${JSON.stringify(char)}` : "data after the value");
+ }
+ }
+ return out.join("");
+ };
+
+ return {
+ write,
+ end(): string {
+ out = [];
+ if (state === ATOM_TEXT && stack.length === 0) finishAtom();
+ if (state !== AFTER || stack.length) fail("the body ended part-way through a value");
+ return out.join("");
+ },
+ };
+}
diff --git a/companion/src/proxy.ts b/companion/src/proxy.ts
index ccb5031eae..41a91af107 100644
--- a/companion/src/proxy.ts
+++ b/companion/src/proxy.ts
@@ -2,7 +2,9 @@
// (a DNS-rebinding defence), so a device's request is replayed to 127.0.0.1
// as this process, never with the device's Host or Origin.
import { request as httpRequest, type IncomingMessage, type ServerResponse } from "node:http";
-import type { Duplex } from "node:stream";
+import type { Duplex, Readable } from "node:stream";
+import { StringDecoder } from "node:string_decoder";
+import { createGzip, type Gzip } from "node:zlib";
import { bearerToken } from "./devices.ts";
import type { E2EDescriptor } from "./e2e/descriptor.ts";
@@ -19,7 +21,8 @@ import {
isCloudDesktopAccess,
isMessageFileDownload,
} from "./routes.ts";
-import { sendTunnelJson } from "./tunnel-gzip.ts";
+import { createJsonScrubber } from "./json-scrub.ts";
+import { acceptsGzip, gzipCandidate, sendTunnelJson, varyOnEncoding } from "./tunnel-gzip.ts";
import { CompanionViewerRelay, requestTarget } from "./viewer-relay.ts";
import { createSseScrubber, isJson, scrub } from "./wire.ts";
@@ -46,6 +49,8 @@ export interface ProxyOptions {
* it synchronously on revoke; the returned disposer is called exactly once. */
connected?: (deviceId: string, disconnect: () => void) => () => void;
headersTimeoutMs?: number;
+ /** Tests only: a lower whole-body ceiling, so a reply past it need not be tens of MiB. */
+ wholeJsonBodyBytes?: number;
/** The `e2e` descriptor for one device (null: the phone pairing now); null when end-to-end is off. */
e2eDescriptor?: (deviceId: string | null) => E2EDescriptor | null;
/** A phone paired through an encrypted session keyed by the pairing token: the session is now that device's. */
@@ -85,7 +90,10 @@ export function proxyHeadersTimeoutMs(url: string, override?: number): number {
?? (PHONE_SECRET_PROVIDE_PATH.test(url) ? PHONE_SECRET_HEADERS_TIMEOUT_MS : HEADERS_TIMEOUT_MS);
}
-const MAX_JSON_BODY_BYTES = 32 * 1024 * 1024;
+/** A JSON reply up to this size is scrubbed whole; past it, it is scrubbed as it streams, so a long history reaches a
+ * paired device as it reaches the desktop. Whole, the companion briefly holds several times the body (bytes, text,
+ * parsed objects, the re-serialised copy). */
+const WHOLE_JSON_BODY_BYTES = 32 * 1024 * 1024;
/** Bounded: an unbounded read on an unauthenticated route is a
* memory-exhaustion vector. */
@@ -145,6 +153,92 @@ const sendJson = (res: ServerResponse, status: number, body: unknown): void => {
res.end(text);
};
+/** Writes to a device and holds `source` back until that write has reached the socket. Paced by the write's own
+ * callback, not the response's 'drain': on Node 24 on Linux a chunked response that wrote a large piece can finish
+ * flushing with `writableNeedDrain` still set and never emit 'drain', which left the reply stalled for good. */
+function toDevice(res: ServerResponse, data: string | Buffer, source: Readable): void {
+ let held = false;
+ held = !res.write(data, () => {
+ if (held) source.resume();
+ });
+ if (held) source.pause();
+}
+
+/** A JSON reply past the whole-body ceiling, scrubbed as it streams. Bytes that were never JSON go on verbatim, as a
+ * small body's do; a body that stops being JSON after its start is out can only be cut off. */
+function streamScrubbedJson(harness: IncomingMessage, res: ServerResponse, held: Buffer[]): void {
+ const status = harness.statusCode ?? 200;
+ const scrubber = createJsonScrubber();
+ const decoder = new StringDecoder("utf8");
+ const head = Buffer.concat(held);
+ let first: string;
+ try {
+ first = scrubber.write(decoder.write(head));
+ } catch {
+ res.writeHead(status, privateHeaders(harness.headers));
+ toDevice(res, head, harness);
+ harness.on("data", (chunk: Buffer) => toDevice(res, chunk, harness));
+ harness.on("end", () => res.end());
+ return;
+ }
+ const headers = { ...harness.headers };
+ delete headers["content-length"];
+ delete headers["content-encoding"];
+ delete headers["transfer-encoding"];
+ const reply = privateHeaders(headers);
+ let zip: Gzip | null = null;
+ // A phone tunnel gzips a whole JSON reply; this one is gzipped as it goes.
+ if (gzipCandidate(res, status, reply, first)) {
+ const vary = varyOnEncoding(reply.vary ?? res.getHeader("vary"));
+ if (acceptsGzip(res.req.headers["accept-encoding"])) {
+ res.writeHead(status, { ...reply, vary, "content-encoding": "gzip" });
+ zip = createGzip();
+ const gzipped = zip;
+ gzipped.on("data", (chunk: Buffer) => toDevice(res, chunk, gzipped));
+ gzipped.on("end", () => res.end());
+ gzipped.on("error", () => res.destroy());
+ // zlib's own 'drain' is an ordinary stream's, and it holds the harness back while it compresses.
+ gzipped.on("drain", () => harness.resume());
+ } else {
+ res.writeHead(status, { ...reply, vary });
+ }
+ } else {
+ res.writeHead(status, reply);
+ }
+ const send = (text: string): void => {
+ if (!zip) toDevice(res, text, harness);
+ else if (!zip.write(text)) harness.pause();
+ };
+ const finish = (text: string): void => {
+ if (zip) zip.end(text);
+ else res.end(text);
+ };
+ const cut = (): void => {
+ harness.destroy();
+ zip?.destroy();
+ res.destroy();
+ };
+ send(first);
+ harness.on("data", (chunk: Buffer) => {
+ let text: string;
+ try {
+ text = scrubber.write(decoder.write(chunk));
+ } catch {
+ return cut();
+ }
+ if (text) send(text);
+ });
+ harness.on("end", () => {
+ let rest: string;
+ try {
+ rest = scrubber.write(decoder.end()) + scrubber.end();
+ } catch {
+ return cut();
+ }
+ finish(rest);
+ });
+}
+
/** Validated and capped at the network boundary so no producer can publish an
* extra field, a path-bearing URL or an unbounded list. */
const endpointSnapshot = (options: ProxyOptions): CompanionEndpointSnapshot => {
@@ -590,18 +684,23 @@ export function createProxyHandler(options: ProxyOptions) {
const chunks: Buffer[] = [];
let size = 0;
- harness.on("data", (chunk: Buffer) => {
+ const hold = (chunk: Buffer) => {
size += chunk.length;
- if (size > MAX_JSON_BODY_BYTES) {
+ chunks.push(chunk);
+ if (size <= (options.wholeJsonBodyBytes ?? WHOLE_JSON_BODY_BYTES)) return;
+ harness.off("data", hold);
+ harness.off("end", finish);
+ // These two are rewritten or withdrawn whole, so neither can start before its end.
+ if (browserRequest || viewers.rewritesJoin(path)) {
harness.destroy();
- if (res.headersSent) res.destroy();
- else sendJson(res, 502, { error: "the response from OpenMausBot was too large" });
+ sendJson(res, 502, { error: "the response from OpenMausBot was too large" });
return;
}
- chunks.push(chunk);
- });
+ streamScrubbedJson(harness, res, chunks);
+ };
+ harness.on("data", hold);
harness.on("error", () => res.destroy());
- harness.on("end", () => {
+ const finish = (): void => {
const refusal = browserRefusal();
if (refusal) return sendJson(res, refusal.status, { error: refusal.error });
const body = Buffer.concat(chunks).toString("utf8");
@@ -633,7 +732,8 @@ export function createProxyHandler(options: ProxyOptions) {
return;
}
forward(text, harness.headers, harness.statusCode ?? 200);
- });
+ };
+ harness.on("end", finish);
/** The body was re-serialised, so the harness's framing headers are
* dropped: Node's parser rejects transfer-encoding alongside
diff --git a/companion/src/viewer-relay.ts b/companion/src/viewer-relay.ts
index 83e8e2ea04..5ddfae654e 100644
--- a/companion/src/viewer-relay.ts
+++ b/companion/src/viewer-relay.ts
@@ -173,6 +173,11 @@ export class CompanionViewerRelay {
this.#upgrades.clear();
}
+ /** Whether rewriteJoinResponse may change this path's answer, which it does to the whole parsed body. */
+ rewritesJoin(path: string): boolean {
+ return BOT_JOIN_PATH.test(path);
+ }
+
rewriteJoinResponse(path: string, value: unknown, deviceId?: string, controlLeaseId?: string | null): unknown {
const join = BOT_JOIN_PATH.exec(path);
const botId = join?.[1];
diff --git a/companion/src/wire.ts b/companion/src/wire.ts
index 09711d2a9e..2e06d579b2 100644
--- a/companion/src/wire.ts
+++ b/companion/src/wire.ts
@@ -7,12 +7,14 @@
// alias such as "vps" out of `cloudBackend: "vps"` and the user's messages.
const WITHHELD_KEYS = new Set(["resumeCursors", "sshAlias", "vpsAlias", "vpsAliases"]);
+export const isWithheldKey = (key: string): boolean => WITHHELD_KEYS.has(key);
+
export function scrub<T>(value: T): T {
if (Array.isArray(value)) return value.map(scrub) as unknown as T;
if (value && typeof value === "object") {
const out: Record<string, unknown> = {};
for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {
- if (WITHHELD_KEYS.has(key)) continue;
+ if (isWithheldKey(key)) continue;
out[key] = scrub(inner);
}
return out as T;
diff --git a/companion/test/json-scrub.test.ts b/companion/test/json-scrub.test.ts
new file mode 100644
index 0000000000..a96c249583
--- /dev/null
+++ b/companion/test/json-scrub.test.ts
@@ -0,0 +1,95 @@
+// The streaming scrub must agree with `scrub` on every body, however the bytes are split.
+import { describe, expect, it } from "vitest";
+
+import { createJsonScrubber } from "../src/json-scrub.ts";
+import { scrub } from "../src/wire.ts";
+
+/** Feeds `body` in pieces of `size` characters (0: one piece). */
+const run = (body: string, size = 0): string => {
+ const scrubber = createJsonScrubber();
+ let out = "";
+ if (!size) out += scrubber.write(body);
+ else for (let i = 0; i < body.length; i += size) out += scrubber.write(body.slice(i, i + size));
+ return out + scrubber.end();
+};
+const expected = (value: unknown): string => JSON.stringify(scrub(value));
+
+/** Deterministic, so a failure reproduces. */
+const random = (seed: number) => () => {
+ seed = (seed * 1_103_515_245 + 12_345) & 0x7fffffff;
+ return seed / 0x7fffffff;
+};
+const KEYS = ["id", "resumeCursors", "name", "sshAlias", "messages", "vpsAlias", "text", "vpsAliases", "tool", ""];
+const STRINGS = ["", "plain", 'quote " and \\ backslash', "line\nbreak\ttab", "é and 😀", "\u0001\u001f", '"resumeCursors":{}', "}]{[,:"];
+function value(next: () => number, depth: number): unknown {
+ const pick = next();
+ if (depth > 5 || pick < 0.35) {
+ const atoms = [null, true, false, 0, -1.5, 1e21, 42, STRINGS[Math.floor(next() * STRINGS.length)]];
+ return atoms[Math.floor(next() * atoms.length)];
+ }
+ const count = Math.floor(next() * 5);
+ if (pick < 0.6) return Array.from({ length: count }, () => value(next, depth + 1));
+ return Object.fromEntries(Array.from({ length: count }, () => [KEYS[Math.floor(next() * KEYS.length)], value(next, depth + 1)]));
+}
+
+describe("streaming JSON scrub", () => {
+ it("drops a withheld member wherever it sits, with the commas still right", () => {
+ const body = {
+ resumeCursors: { agent: "first" },
+ bots: [
+ { id: "b1", sshAlias: "box", tasks: [{ id: "t1", resumeCursors: { a: [1, { b: 2 }] } }] },
+ { vpsAlias: "only" },
+ { id: "b3", vpsAliases: ["x", "y"] },
+ ],
+ last: 1,
+ vpsAlias: null,
+ };
+ const out = run(JSON.stringify(body));
+ expect(out).toBe(expected(body));
+ expect(JSON.parse(out)).toEqual({ bots: [{ id: "b1", tasks: [{ id: "t1" }] }, {}, { id: "b3" }], last: 1 });
+ });
+
+ it("withholds a key spelled with escapes, as JSON.parse on the device would read it", () => {
+ const out = run('{"keep":1,"resume\\u0043ursors":{"agent":"cursor-value"},"ssh\\u0041lias":"box"}');
+ expect(out).toBe('{"keep":1}');
+ });
+
+ it("keeps a message that merely mentions a withheld key", () => {
+ const body = { text: '{"resumeCursors":{"agent":"x"}}', resumeCursors: 1 };
+ expect(run(JSON.stringify(body))).toBe(JSON.stringify({ text: body.text }));
+ });
+
+ it("agrees with scrub on random bodies, pretty or compact, split anywhere", () => {
+ const next = random(7);
+ for (let n = 0; n < 400; n++) {
+ const body = value(next, 0);
+ const text = JSON.stringify(body, null, n % 3 === 0 ? 2 : undefined);
+ for (const size of [0, 1, 2, 7]) expect(run(text, size)).toBe(expected(body));
+ }
+ });
+
+ it("takes top-level atoms and surrounding whitespace", () => {
+ expect(run(" 12 ")).toBe("12");
+ expect(run("1", 1)).toBe("1");
+ expect(run('"text"')).toBe('"text"');
+ expect(run("null\n")).toBe("null");
+ });
+
+ it("refuses everything that is not strict JSON", () => {
+ const refused = [
+ "", " ", "{", "[1,]", '{"a":1,}', "{,}", "[1 2]", '{"a" 1}', '{"a":1]', "[1}", "]", "01", "1.", "-", "tru", "nul",
+ "undefined", "NaN", "'x'", '"\\x"', '"\\u12G4"', '"tab\there"', '"open', "{} {}", "1 2", '{"a":1}x', "{}",
+ '{a:1}', "[1,,2]",
+ ];
+ for (const body of refused) {
+ expect(() => JSON.parse(body), body).toThrow();
+ expect(() => run(body), body).toThrow(/not JSON/);
+ expect(() => run(body, 1), body).toThrow(/not JSON/);
+ }
+ });
+
+ it("bounds nesting with its own stack rather than the runtime's", () => {
+ expect(run(`${"[".repeat(1_000)}${"]".repeat(1_000)}`)).toBe(`${"[".repeat(1_000)}${"]".repeat(1_000)}`);
+ expect(() => run(`${"[".repeat(1_001)}${"]".repeat(1_001)}`)).toThrow(/too deep/);
+ });
+});
diff --git a/companion/test/large-json.test.ts b/companion/test/large-json.test.ts
new file mode 100644
index 0000000000..7f7aeab092
--- /dev/null
+++ b/companion/test/large-json.test.ts
@@ -0,0 +1,195 @@
+// A bot list past the whole-body ceiling (a long history: about 52 MiB in the field) reaches a paired device
+// scrubbed, instead of a 502. One test crosses the real 32 MiB ceiling; the rest lower it, so each body stays small.
+import { createServer, request, type IncomingHttpHeaders, type RequestListener, type Server, type ServerResponse } from "node:http";
+import { gunzipSync } from "node:zlib";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { createProxyHandler, type ProxyOptions } from "../src/proxy.ts";
+import { gzipTunnelReplies } from "../src/tunnel-gzip.ts";
+import { scrub } from "../src/wire.ts";
+
+const TOKEN = "omb_test_token";
+const MiB = 1024 * 1024;
+const LOW_CEILING = 256 * 1024;
+
+/** Multi-byte characters, quotes and escapes, so chunk edges land inside all of them. */
+const LINE = 'A long reply with "quotes", a back\\slash, é, 😀 and a\nnew line. ';
+function snapshot(bots: number, messages: number, lines: number) {
+ const text = LINE.repeat(lines);
+ return {
+ bots: Array.from({ length: bots }, (_, b) => ({
+ id: `b${b}`,
+ name: `Bot ${b}`,
+ sshAlias: "my-server",
+ tasks: [{ id: `t${b}`, title: "Main", resumeCursors: { claude: `cursor-value-${b}` } }],
+ messages: Array.from({ length: messages }, (_, m) => ({ id: `m${b}-${m}`, role: m % 2 ? "bot" : "user", text })),
+ hasMore: true,
+ })),
+ groups: [],
+ sections: [],
+ resumeCursors: { agent: "cursor-value" },
+ };
+}
+/** About 1.3 MiB: five times the lowered ceiling. */
+const SMALL = snapshot(25, 20, 40);
+const BODY = Buffer.from(JSON.stringify(SMALL));
+const SCRUBBED = JSON.stringify(scrub(SMALL));
+
+let harness: Server;
+const servers: Server[] = [];
+const ports = { real: 0, lan: 0, origin: 0 };
+let respond: (res: ServerResponse) => void = (res) => res.end();
+
+/** Written in odd-sized slices, as a socket would deliver them. */
+const send = (res: ServerResponse, body: Buffer): void => {
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
+ for (let i = 0; i < body.length; i += 65_521) res.write(body.subarray(i, i + 65_521));
+ res.end();
+};
+
+const listen = (server: Server): Promise<number> =>
+ new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve((server.address() as { port: number }).port)));
+
+/** Whatever bytes arrived, and whether the response ended cleanly or was cut. A connection the proxy neither
+ * finishes nor closes fails here by name, rather than as a test timeout. */
+function device(port: number, path = "/api/bots", method = "GET", slow = false): Promise<{ status: number; headers: IncomingHttpHeaders; raw: Buffer; complete: boolean }> {
+ return new Promise((resolve, reject) => {
+ const req = request({ host: "127.0.0.1", port, path, method, headers: { authorization: `Bearer ${TOKEN}`, "accept-encoding": "gzip" } }, (res) => {
+ const chunks: Buffer[] = [];
+ let complete = false;
+ res.on("data", (chunk: Buffer) => {
+ chunks.push(chunk);
+ // A reader slower than the proxy, so the device's socket backs up and the proxy has to wait for it.
+ if (slow) {
+ res.pause();
+ setTimeout(() => res.resume(), 1);
+ }
+ });
+ res.on("end", () => {
+ complete = true;
+ });
+ res.on("error", () => {});
+ res.on("close", () => {
+ clearTimeout(deadline);
+ resolve({ status: res.statusCode ?? 0, headers: res.headers, raw: Buffer.concat(chunks), complete });
+ });
+ });
+ const deadline = setTimeout(() => {
+ req.destroy();
+ reject(new Error("the proxy neither finished nor closed the connection"));
+ }, 15_000);
+ req.on("error", () => {
+ clearTimeout(deadline);
+ resolve({ status: 0, headers: {}, raw: Buffer.alloc(0), complete: false });
+ });
+ req.end();
+ });
+}
+
+beforeAll(async () => {
+ harness = createServer((_req, res) => respond(res));
+ const options = (extra: Partial<ProxyOptions> = {}): ProxyOptions => ({
+ harnessPort: 0,
+ authenticate: (t) => (t === TOKEN ? { id: "phone-1", cloudDesktopAccess: true, browserControlAccess: true } : null),
+ redeem: () => ({ error: "not used here" }),
+ serverName: () => "Test computer",
+ ...extra,
+ });
+ const harnessPort = await listen(harness);
+ const real = createProxyHandler(options({ harnessPort }));
+ const lowered = createProxyHandler(options({ harnessPort, wholeJsonBodyBytes: LOW_CEILING }));
+ const make = (handler: RequestListener) => {
+ const server = createServer(handler);
+ servers.push(server);
+ return listen(server);
+ };
+ ports.real = await make(real);
+ ports.lan = await make(lowered);
+ ports.origin = await make(gzipTunnelReplies(lowered));
+});
+
+afterAll(async () => {
+ for (const server of [...servers, harness]) {
+ server.closeAllConnections();
+ await new Promise((resolve) => server.close(resolve));
+ }
+});
+
+describe("a JSON reply past the whole-body ceiling", () => {
+ it("crosses the real 32 MiB ceiling and still arrives, scrubbed", async () => {
+ // One shared message text keeps the heap small; only the serialised body is this large.
+ const big = snapshot(25, 140, 150);
+ const body = Buffer.from(JSON.stringify(big));
+ expect(body.length).toBeGreaterThan(34 * MiB);
+ respond = (res) => send(res, body);
+ const { status, raw, complete } = await device(ports.real, "/api/bots", "GET", true);
+ expect(status).toBe(200);
+ expect(complete).toBe(true);
+ const text = raw.toString("utf8");
+ expect(text === JSON.stringify(scrub(big))).toBe(true);
+ expect(text).not.toContain("cursor-value");
+ });
+
+ it("reaches a paired device whole, with the withheld fields gone", async () => {
+ expect(BODY.length).toBeGreaterThan(4 * LOW_CEILING);
+ respond = (res) => send(res, BODY);
+ const { status, headers, raw, complete } = await device(ports.lan);
+ expect(status).toBe(200);
+ expect(complete).toBe(true);
+ expect(headers["cache-control"]).toBe("private, no-store");
+ expect(headers["content-length"]).toBeUndefined();
+ const text = raw.toString("utf8");
+ expect(text === SCRUBBED).toBe(true);
+ expect(text).not.toContain("cursor-value");
+ expect(text).not.toContain("my-server");
+ expect((JSON.parse(text) as { bots: unknown[] }).bots).toHaveLength(25);
+ });
+
+ it("keeps going to a reader slower than the proxy, long after the socket buffers fill", async () => {
+ // Several MiB past the ceiling: on Linux the device's socket backs up many times over. Waiting on the
+ // response's 'drain' there stalled for good; this reply must still finish.
+ const long = snapshot(25, 40, 150);
+ const body = Buffer.from(JSON.stringify(long));
+ expect(body.length).toBeGreaterThan(8 * MiB);
+ respond = (res) => send(res, body);
+ const { status, raw, complete } = await device(ports.lan, "/api/bots", "GET", true);
+ expect(status).toBe(200);
+ expect(complete).toBe(true);
+ expect(raw.toString("utf8") === JSON.stringify(scrub(long))).toBe(true);
+ });
+
+ it("is gzipped as it streams on the phone tunnel", async () => {
+ respond = (res) => send(res, BODY);
+ const { status, headers, raw, complete } = await device(ports.origin);
+ expect(status).toBe(200);
+ expect(complete).toBe(true);
+ expect(headers["content-encoding"]).toBe("gzip");
+ expect(headers.vary).toContain("Accept-Encoding");
+ expect(raw.length).toBeLessThan(BODY.length / 10);
+ expect(gunzipSync(raw).toString("utf8") === SCRUBBED).toBe(true);
+ });
+
+ it("passes through verbatim when it was never JSON, as a small body does", async () => {
+ const notJson = Buffer.from(`not JSON ${"x".repeat(2 * LOW_CEILING)}`);
+ respond = (res) => send(res, notJson);
+ const { status, raw, complete } = await device(ports.lan);
+ expect(status).toBe(200);
+ expect(complete).toBe(true);
+ expect(raw.equals(notJson)).toBe(true);
+ });
+
+ it("is cut off, never finished unscrubbed, when it stops being JSON after its start went out", async () => {
+ const tail = Buffer.from(' {"resumeCursors":{"agent":"late-cursor"}}');
+ respond = (res) => send(res, Buffer.concat([BODY, tail]));
+ const { raw, complete } = await device(ports.lan);
+ expect(complete).toBe(false);
+ expect(raw.toString("utf8")).not.toContain("late-cursor");
+ });
+
+ it("still refuses an oversized answer that must be checked whole", async () => {
+ respond = (res) => send(res, BODY);
+ const { status, raw } = await device(ports.lan, "/api/bots/b1/browser/action", "POST");
+ expect(status).toBe(502);
+ expect(raw.toString("utf8")).toContain("too large");
+ });
+});