Skip to content

Commit d886267

Browse files
t3dotggclaude
andcommitted
fix(server): validate base64 structure in parseBase64DataUrl
Address review: '=' was accepted anywhere in the payload and length was not required to be a multiple of 4, so malformed input like 'AB=CD' passed and Node's lenient decoder would silently truncate it. Allow '=' only as one or two trailing padding characters and require the assembled length to be a multiple of 4, keeping the iterative stack-safe style. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 196393a commit d886267

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,27 @@ describe("imageMime", () => {
3737
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
3838
});
3939

40+
it("rejects structurally malformed base64", () => {
41+
// '=' before the trailing padding position
42+
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
43+
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
44+
// more than two padding characters
45+
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull();
46+
// length not a multiple of 4
47+
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull();
48+
});
49+
50+
it("accepts base64 with one or two trailing padding characters", () => {
51+
expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({
52+
mimeType: "image/png",
53+
base64: "SGVsbA==",
54+
});
55+
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({
56+
mimeType: "image/png",
57+
base64: "SGVsbG8h",
58+
});
59+
});
60+
4061
it("rejects empty and whitespace-only payloads", () => {
4162
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
4263
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();

‎apps/server/src/imageMime.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,16 @@ export function parseBase64DataUrl(
9898
runs.push(payload.slice(runStart));
9999
}
100100
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
101-
if (base64.length === 0) return null;
101+
if (base64.length === 0 || base64.length % 4 !== 0) return null;
102+
const firstPad = base64.indexOf("=");
103+
if (firstPad !== -1) {
104+
// '=' is only valid as one or two trailing padding characters; Node's
105+
// decoder would otherwise silently truncate at the first '='.
106+
if (base64.length - firstPad > 2) return null;
107+
for (let index = firstPad; index < base64.length; index += 1) {
108+
if (base64.charCodeAt(index) !== 0x3d) return null;
109+
}
110+
}
102111

103112
return { mimeType, base64 };
104113
}

0 commit comments

Comments
 (0)