diff --git a/src/bounds.ts b/src/bounds.ts index 75408bb..428920d 100644 --- a/src/bounds.ts +++ b/src/bounds.ts @@ -17,6 +17,9 @@ export async function deadline(run: (signal: AbortSignal) => Promise, 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 { if (!response.body) return ""; const reader = response.body.getReader(); diff --git a/src/proxy.ts b/src/proxy.ts index 5b845f1..568ab02 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -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"; @@ -47,7 +47,7 @@ async function* events(body: ReadableStream): 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) { @@ -67,7 +67,7 @@ async function* events(body: ReadableStream): 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); @@ -144,7 +144,7 @@ export function runProxy(options: ProxyOptions): Promise { 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(); @@ -214,7 +214,7 @@ export function runProxy(options: ProxyOptions): Promise { 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); } } diff --git a/test/hardening.test.ts b/test/hardening.test.ts index 7b30647..3a7d809 100644 --- a/test/hardening.test.ts +++ b/test/hardening.test.ts @@ -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), { @@ -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'); @@ -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() {} });