Skip to content

Commit 3e49e93

Browse files
committed
fix(gateway): prevent RangeError on large clipboard screenshot attachments (#99163)
canonicalizeBase64 in packages/media-core/src/base64.ts built its output string using character-by-character concatenation () in a loop. For large base64 payloads (~2.7M chars from a ~2MB clipboard PNG screenshot), this created a deeply nested V8 cons-string tree. When any downstream operation triggered V8 string flattening — e.g. or in sniffMimeFromBase64 — V8 recursed into the cons-string tree and overflowed the call stack, producing: RangeError: Maximum call stack size exceeded in the gateway's chat.send attachment parse/stage pipeline. Smaller images (~200KB) worked fine because their cons-string trees were shallow enough to flatten without stack overflow. Fix: accumulate characters in an array and join once at the end, producing a flat string in O(n) without deep V8 recursion. The function is called from sniffMimeFromBase64 → parseMessageWithAttachments → chat.send handler, so this fix resolves the crash for all attachment types that go through the base64 canonicalization path. Tests: - Added regression test in base64.test.ts verifying canonicalizeBase64 handles ~2MB PNG payloads without RangeError on .slice() or Buffer.from() - Added regression test in base64.test.ts for large payloads with whitespace - Added end-to-end regression test in chat-attachments.test.ts verifying parseMessageWithAttachments processes ~2MB PNG without RangeError
1 parent 0011a18 commit 3e49e93

3 files changed

Lines changed: 81 additions & 4 deletions

File tree

‎packages/media-core/src/base64.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,20 @@
22
import { describe, expect, it } from "vitest";
33
import { canonicalizeBase64, estimateBase64DecodedBytes } from "./base64.js";
44

5+
/**
6+
* Generates a large valid base64 string (~2.7M chars) simulating a ~2MB PNG
7+
* clipboard screenshot. The raw bytes are a valid PNG header followed by
8+
* filler so sniffers still recognise it as image/png.
9+
*/
10+
function largePngBase64(sizeBytes = 2_000_000): string {
11+
const buffer = Buffer.alloc(sizeBytes);
12+
// PNG magic bytes
13+
buffer.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0);
14+
// IHDR chunk marker (minimal)
15+
buffer.write("IHDR", 12, "ascii");
16+
return buffer.toString("base64");
17+
}
18+
519
describe("base64 helpers", () => {
620
function expectBase64HelperCase<T>(actual: T, expected: T) {
721
expect(actual).toBe(expected);
@@ -41,4 +55,31 @@ describe("base64 helpers", () => {
4155
] as const)("$name", ({ actual, expected }) => {
4256
expectBase64HelperCase(actual, expected);
4357
});
58+
59+
it("canonicalizeBase64 does not overflow the call stack on ~2MB PNG payloads", () => {
60+
// Regression: character-by-character string concatenation (`cleaned += ch`)
61+
// produced a deeply nested V8 cons-string that overflowed the stack when
62+
// flattened. A ~2MB screenshot encodes to ~2.7M base64 chars.
63+
const large = largePngBase64(2_000_000);
64+
expect(large.length).toBeGreaterThan(2_600_000);
65+
66+
const result = canonicalizeBase64(large);
67+
expect(result).toBeDefined();
68+
// The result must be a flat string — .slice() and Buffer.from() must not
69+
// throw RangeError.
70+
expect(() => result!.slice(0, 256)).not.toThrow();
71+
expect(() => Buffer.from(result!.slice(0, 256), "base64")).not.toThrow();
72+
// Correctness: canonical output should equal the input (no whitespace to strip).
73+
expect(result).toBe(large);
74+
});
75+
76+
it("canonicalizeBase64 handles large payloads with whitespace without stack overflow", () => {
77+
const large = largePngBase64(2_000_000);
78+
// Insert whitespace every 4096 chars to exercise the whitespace-stripping path.
79+
const withWhitespace = large.replace(/(.{4096})/g, "$1\n");
80+
const result = canonicalizeBase64(withWhitespace);
81+
expect(result).toBeDefined();
82+
expect(() => result!.slice(0, 256)).not.toThrow();
83+
expect(result).toBe(large);
84+
});
4485
});

‎packages/media-core/src/base64.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,17 @@ function isBase64DataChar(code: number): boolean {
5050
/**
5151
* Normalizes and validates a base64 string, returning canonical no-whitespace
5252
* base64 only when the input has valid alphabet, padding, and length.
53+
*
54+
* Implementation note: we accumulate characters into an array and join once
55+
* at the end instead of using `cleaned += base64[i]` in a loop. Repeated
56+
* string concatenation creates a deeply nested V8 cons-string tree; for
57+
* large payloads (~2.7M chars from a 2MB clipboard PNG) V8 overflows the
58+
* call stack when it later tries to flatten the tree (e.g. during `.slice()`
59+
* or `Buffer.from(..., "base64")`). Array join produces a flat string in O(n)
60+
* without deep recursion.
5361
*/
5462
export function canonicalizeBase64(base64: string): string | undefined {
55-
let cleaned = "";
63+
const parts: string[] = [];
5664
let padding = 0;
5765
let sawPadding = false;
5866
for (let i = 0; i < base64.length; i += 1) {
@@ -66,17 +74,18 @@ export function canonicalizeBase64(base64: string): string | undefined {
6674
return undefined;
6775
}
6876
sawPadding = true;
69-
cleaned += "=";
77+
parts.push("=");
7078
continue;
7179
}
7280
if (sawPadding || !isBase64DataChar(code)) {
7381
return undefined;
7482
}
75-
cleaned += base64[i];
83+
parts.push(base64[i]);
7684
}
77-
if (!cleaned) {
85+
if (parts.length === 0) {
7886
return undefined;
7987
}
88+
let cleaned = parts.join("");
8089
const remainder = cleaned.length % 4;
8190
if (remainder !== 0) {
8291
if (sawPadding || remainder === 1) {

‎src/gateway/chat-attachments.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,3 +523,30 @@ describe("attachment validation", () => {
523523
}
524524
});
525525
});
526+
527+
describe("parseMessageWithAttachments large payload regression (issue #99163)", () => {
528+
it("processes ~2MB PNG screenshot without RangeError", async () => {
529+
// Regression: a ~2MB clipboard PNG encodes to ~2.7M base64 chars.
530+
// canonicalizeBase64 used char-by-char concatenation creating a deep V8
531+
// cons-string that overflowed the stack on flatten. The full
532+
// parseMessageWithAttachments pipeline (sniff → size check → offload)
533+
// must complete without RangeError.
534+
const pngBytes = Buffer.alloc(2_000_000);
535+
pngBytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0);
536+
pngBytes.write("IHDR", 12, "ascii");
537+
const base64 = pngBytes.toString("base64");
538+
expect(base64.length).toBeGreaterThan(2_600_000);
539+
540+
const parsed = await parseMessageWithAttachments(
541+
"see this screenshot",
542+
[{ type: "image", mimeType: "image/png", fileName: "screenshot.png", content: base64 }],
543+
{ log: { warn: () => {} } },
544+
);
545+
546+
// 2MB exceeds OFFLOAD_THRESHOLD_BYTES (2_000_000) so it should offload.
547+
expect(parsed.offloadedRefs).toHaveLength(1);
548+
expect(parsed.offloadedRefs[0]?.mimeType).toBe("image/png");
549+
expect(parsed.images).toHaveLength(0);
550+
expect(saveMediaBufferMock).toHaveBeenCalledOnce();
551+
});
552+
});

0 commit comments

Comments
 (0)