Skip to content

Commit 196393a

Browse files
t3dotggclaude
andcommitted
fix(server): parse image data URLs without payload-sized regexes
parseBase64DataUrl ran two regexes across the entire multi-megabyte attachment payload. V8's regex engine borrows the JS call stack, so when the parser was invoked from a deep call stack (Effect fiber execution in dispatchCommand), matching a ~10 MB image threw 'RangeError: Maximum call stack size exceeded' and the send failed before validation could return a proper error. Replace the regex with indexOf/slice header parsing and a single iterative charCodeAt loop that validates the base64 alphabet and strips whitespace in one pass, keeping stack usage constant regardless of payload size or call depth. Accepted/rejected inputs are unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent c1ec191 commit 196393a

2 files changed

Lines changed: 90 additions & 8 deletions

File tree

‎apps/server/src/imageMime.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,42 @@ describe("imageMime", () => {
3232
});
3333
});
3434

35+
it("rejects payload with characters outside the base64 alphabet", () => {
36+
expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull();
37+
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
38+
});
39+
40+
it("rejects empty and whitespace-only payloads", () => {
41+
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
42+
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();
43+
});
44+
45+
it("parses a case-insensitive scheme and mime type", () => {
46+
expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({
47+
mimeType: "image/png",
48+
base64: "SGVsbG8=",
49+
});
50+
});
51+
52+
it("parses a multi-megabyte payload from a deep call stack", () => {
53+
// Regression: matching the payload with a regex borrowed the JS call
54+
// stack, so a ~10 MB image parsed inside fiber execution threw
55+
// "RangeError: Maximum call stack size exceeded".
56+
const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`;
57+
const atDepth = (depth: number): ReturnType<typeof parseBase64DataUrl> =>
58+
depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1);
59+
const findMaxDepth = (depth: number): number => {
60+
try {
61+
return findMaxDepth(depth + 1);
62+
} catch {
63+
return depth;
64+
}
65+
};
66+
const result = atDepth(Math.floor(findMaxDepth(0) * 0.85));
67+
expect(result?.mimeType).toBe("image/png");
68+
expect(result?.base64.length).toBe(14_000_000);
69+
});
70+
3571
it("does not read inherited keys from mime extension map", () => {
3672
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
3773
});

‎apps/server/src/imageMime.ts‎

Lines changed: 54 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,43 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
2929
".webp",
3030
]);
3131

32+
// Whether `code` is a character the base64 payload may contain, aside from
33+
// the whitespace handled separately below.
34+
function isBase64Char(code: number): boolean {
35+
return (
36+
(code >= 0x61 && code <= 0x7a) || // a-z
37+
(code >= 0x41 && code <= 0x5a) || // A-Z
38+
(code >= 0x30 && code <= 0x39) || // 0-9
39+
code === 0x2b || // +
40+
code === 0x2f || // /
41+
code === 0x3d // =
42+
);
43+
}
44+
45+
function isBase64Whitespace(code: number): boolean {
46+
return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space
47+
}
48+
49+
// Data URLs carry the full image payload, so this parser must never run a
50+
// regex across the payload: V8's regex engine borrows the JS call stack, and
51+
// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
52+
// execution) throws "Maximum call stack size exceeded".
3253
export function parseBase64DataUrl(
3354
dataUrl: string,
3455
): { readonly mimeType: string; readonly base64: string } | null {
35-
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
36-
if (!match) return null;
56+
const trimmed = dataUrl.trim();
57+
if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
58+
59+
const commaIndex = trimmed.indexOf(",");
60+
if (commaIndex === -1) return null;
61+
const header = trimmed.slice(5, commaIndex);
62+
if (header.length === 0) return null;
3763

3864
const headerParts: Array<string> = [];
39-
for (const part of (match[1] ?? "").split(";")) {
40-
const trimmed = part.trim();
41-
if (trimmed.length > 0) {
42-
headerParts.push(trimmed);
65+
for (const part of header.split(";")) {
66+
const partTrimmed = part.trim();
67+
if (partTrimmed.length > 0) {
68+
headerParts.push(partTrimmed);
4369
}
4470
}
4571
if (headerParts.length < 2) {
@@ -51,8 +77,28 @@ export function parseBase64DataUrl(
5177
}
5278

5379
const mimeType = headerParts[0]?.toLowerCase();
54-
const base64 = match[2]?.replace(/\s+/g, "");
55-
if (!mimeType || !base64) return null;
80+
if (!mimeType) return null;
81+
82+
const payload = trimmed.slice(commaIndex + 1);
83+
const runs: Array<string> = [];
84+
let runStart = -1;
85+
for (let index = 0; index < payload.length; index += 1) {
86+
const code = payload.charCodeAt(index);
87+
if (isBase64Char(code)) {
88+
if (runStart === -1) runStart = index;
89+
continue;
90+
}
91+
if (!isBase64Whitespace(code)) return null;
92+
if (runStart !== -1) {
93+
runs.push(payload.slice(runStart, index));
94+
runStart = -1;
95+
}
96+
}
97+
if (runStart !== -1) {
98+
runs.push(payload.slice(runStart));
99+
}
100+
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
101+
if (base64.length === 0) return null;
56102

57103
return { mimeType, base64 };
58104
}

0 commit comments

Comments
 (0)