Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/bounds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ export async function deadline<T>(run: (signal: AbortSignal) => Promise<T>, ms:
}
}

/** Largest gateway reply the proxy accepts: one JSON body, SSE line or SSE event. */
export const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;

export async function boundedText(response: Response, limit = 1024 * 1024): Promise<string> {
if (!response.body) return "";
const reader = response.body.getReader();
Expand Down
10 changes: 5 additions & 5 deletions src/proxy.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { boundedText, deadline } from "./bounds.js";
import { MAX_RESPONSE_BYTES, boundedText, deadline } from "./bounds.js";
import { StringDecoder } from "node:string_decoder";
import type { Readable, Writable } from "node:stream";

Expand Down Expand Up @@ -47,7 +47,7 @@ async function* events(body: ReadableStream<Uint8Array>): AsyncGenerator<{ data:
let lineBytes = 0;
const append = (part: string) => {
lineBytes += Buffer.byteLength(part, "utf8");
if (lineBytes > 1024 * 1024) throw new Error("SSE line exceeded the size limit");
if (lineBytes > MAX_RESPONSE_BYTES) throw new Error("SSE line exceeded the size limit");
buffer += part;
};
for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {
Expand All @@ -67,7 +67,7 @@ async function* events(body: ReadableStream<Uint8Array>): AsyncGenerator<{ data:
continue;
}
eventBytes += Buffer.byteLength(line, "utf8");
if (eventBytes > 1024 * 1024) throw new Error("SSE event exceeded the size limit");
if (eventBytes > MAX_RESPONSE_BYTES) throw new Error("SSE event exceeded the size limit");
if (line.startsWith(":")) continue;
const colon = line.indexOf(":");
const field = colon === -1 ? line : line.slice(0, colon);
Expand Down Expand Up @@ -144,7 +144,7 @@ export function runProxy(options: ProxyOptions): Promise<void> {
if (closed) return Promise.resolve();
const text = `${JSON.stringify(message)}\n`;
const bytes = Buffer.byteLength(text);
if (queuedWrites >= 128 || queuedBytes + bytes > 8 * 1024 * 1024) {
if (queuedWrites >= 128 || queuedBytes + bytes > 2 * MAX_RESPONSE_BYTES) {
options.log("Proxy output limit exceeded; closing the connection.");
stop();
return Promise.resolve();
Expand Down Expand Up @@ -214,7 +214,7 @@ export function runProxy(options: ProxyOptions): Promise<void> {
return;
}
if (type.includes("application/json")) {
const body: unknown = JSON.parse(await boundedText(response));
const body: unknown = JSON.parse(await boundedText(response, MAX_RESPONSE_BYTES));
for (const message of Array.isArray(body) ? body : [body]) await take(message);
}
}
Expand Down
17 changes: 15 additions & 2 deletions test/hardening.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { createApi } from "../src/api.js";
import { loadState, saveState } from "../src/state.js";
import { withFileLock } from "../src/file-lock.js";
import { writeEntry, writeText } from "../src/agents.js";
import { boundedText } from "../src/bounds.js";
import { MAX_RESPONSE_BYTES, boundedText } from "../src/bounds.js";

afterEach(() => vi.useRealTimers());
const json = (body: unknown, session?: string) => new Response(JSON.stringify(body), {
Expand Down Expand Up @@ -145,7 +145,7 @@ it("rejects oversized SSE events and error bodies without buffering to EOF", asy
for (const sse of [false, true]) {
let cancelled = false;
const p = proxy((async () => new Response(new ReadableStream({
start(c) { c.enqueue(new TextEncoder().encode(sse ? `data: ${"x".repeat(1024 * 1024 + 1)}` : "x".repeat(5000))); },
start(c) { c.enqueue(new TextEncoder().encode(sse ? `data: ${"x".repeat(MAX_RESPONSE_BYTES + 1)}` : "x".repeat(5000))); },
cancel() { cancelled = true; },
}), { status: sse ? 200 : 403, headers: { "content-type": sse ? "text/event-stream" : "text/plain" } })) as typeof fetch);
p.input.end('{"jsonrpc":"2.0","id":1,"method":"ping"}\n');
Expand All @@ -155,6 +155,19 @@ it("rejects oversized SSE events and error bodies without buffering to EOF", asy
}
});

it("relays gateway replies up to the response limit", async () => {
const big = "x".repeat(MAX_RESPONSE_BYTES - 1024);
for (const sse of [false, true]) {
const reply = JSON.stringify({ jsonrpc: "2.0", id: 1, result: { big } });
const p = proxy((async () => new Response(sse ? `data: ${reply}\n\n` : reply, {
headers: { "content-type": sse ? "text/event-stream" : "application/json" },
})) as typeof fetch);
p.input.end('{"jsonrpc":"2.0","id":1,"method":"ping"}\n');
await p.done;
expect(p.messages().find((m) => m.id === 1)?.result).toEqual({ big });
}
});

it("bounds shutdown when stdout never completes its write", async () => {
vi.useFakeTimers();
const output = new Writable({ write() {} });
Expand Down