fix(browser): validate PNG chunks and preserve unsupported encodings

Validate chunk checksums, type bytes, ordering and end boundaries before pixel comparison. Distinguish malformed PNGs and corrupt DEFLATE streams from recognized unsupported encodings through CLI and MCP error projection.

Adapted from #1375 with additional decoder and public boundary regressions. Eighteen decoder tests and six compiled CLI/MCP cases passed.

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Rudy Celekli
2026-10-11 11:07:15 +08:00
committed by morluto
co-authored by morluto
parent 21dbcf7a14
commit 4e4b15b825
6 changed files with 505 additions and 26 deletions
+131 -25
View File
@@ -1,10 +1,11 @@
import { inflateSync } from "node:zlib";
import { crc32, inflateSync } from "node:zlib";
import type {
CompareWebScreenshotsInput,
WebScreenshotArtifact,
WebScreenshotDiff,
} from "../domain/webScreenshot.js";
import { AnalysisUnsupportedTargetError } from "../domain/analysisErrorCore.js";
import { decodeCanonicalBase64 } from "../domain/webScreenshot.js";
interface DecodedPng {
@@ -17,8 +18,8 @@ interface DecodedPng {
export const comparePngScreenshots = (
input: CompareWebScreenshotsInput,
): WebScreenshotDiff => {
const before = decodePng(input.before);
const after = decodePng(input.after);
const before = decodePng(input.before, "before");
const after = decodePng(input.after, "after");
if (before.width !== after.width || before.height !== after.height)
return {
status: "dimension_mismatch",
@@ -73,7 +74,10 @@ export const comparePngScreenshots = (
};
};
const decodePng = (artifact: WebScreenshotArtifact): DecodedPng => {
const decodePng = (
artifact: WebScreenshotArtifact,
field: "before" | "after",
): DecodedPng => {
const bytes = decodeCanonicalBase64(artifact.data_base64);
if (bytes === undefined || !bytes.subarray(0, 8).equals(PNG_SIGNATURE))
throw new TypeError("Invalid PNG signature");
@@ -81,38 +85,104 @@ const decodePng = (artifact: WebScreenshotArtifact): DecodedPng => {
let header: ReturnType<typeof parseHeader> | undefined;
const compressed: Buffer[] = [];
let sawEnd = false;
let sawPalette = false;
let imageDataEnded = false;
let paletteEntries = 0;
let transparentColor: readonly number[] | undefined;
let sawTransparency = false;
let unsupportedReason: string | undefined;
while (offset < bytes.length) {
if (offset + 12 > bytes.length) throw new TypeError("Truncated PNG chunk");
const length = bytes.readUInt32BE(offset);
const type = bytes.subarray(offset + 4, offset + 8).toString("ascii");
if (length > 0x7fffffff) throw new TypeError("Invalid PNG chunk length");
const type = bytes.subarray(offset + 4, offset + 8).toString("latin1");
const dataStart = offset + 8;
const dataEnd = dataStart + length;
if (dataEnd + 4 > bytes.length) throw new TypeError("Truncated PNG data");
const data = bytes.subarray(dataStart, dataEnd);
if (type === "IHDR") header = parseHeader(data);
if (
crc32(bytes.subarray(offset + 4, dataEnd)) !== bytes.readUInt32BE(dataEnd)
)
throw new TypeError("Invalid PNG chunk checksum");
if (!/^[A-Za-z]{4}$/u.test(type) || type[2] !== type[2]?.toUpperCase())
throw new TypeError("Invalid PNG chunk type");
if (type !== "IDAT" && compressed.length > 0) imageDataEnded = true;
if (type === "IHDR") {
if (offset !== 8 || header !== undefined)
throw new TypeError("Invalid PNG header order");
header = parseHeader(data);
} else if (header === undefined)
throw new TypeError("Invalid PNG header order");
else if (type === "tRNS") {
if (header?.channels !== 3 || data.length !== 6)
if (sawTransparency || compressed.length > 0)
throw new TypeError("Invalid PNG transparency order");
sawTransparency = true;
if (header.colorType === 2 && data.length === 6) {
transparentColor = [
data.readUInt16BE(0),
data.readUInt16BE(2),
data.readUInt16BE(4),
];
} else if (
(header.colorType === 0 && data.length === 2) ||
(header.colorType === 3 &&
sawPalette &&
data.length > 0 &&
data.length <= paletteEntries)
) {
unsupportedReason ??=
"PNG transparency for this color type is not supported.";
} else {
throw new TypeError("Unsupported PNG transparency");
transparentColor = [
data.readUInt16BE(0),
data.readUInt16BE(2),
data.readUInt16BE(4),
];
} else if (type === "IDAT") compressed.push(data);
else if (type === "IEND") {
}
} else if (type === "PLTE") {
if (
sawPalette ||
sawTransparency ||
compressed.length > 0 ||
length === 0 ||
length > 768 ||
length % 3 !== 0 ||
(header.colorType === 3 && length / 3 > 2 ** header.bitDepth) ||
(header.colorType !== 2 &&
header.colorType !== 3 &&
header.colorType !== 6)
)
throw new TypeError("Invalid PNG palette");
sawPalette = true;
paletteEntries = length / 3;
} else if (type === "IDAT") {
if (imageDataEnded) throw new TypeError("Nonconsecutive PNG image data");
compressed.push(data);
} else if (type === "IEND") {
if (length !== 0 || dataEnd + 4 !== bytes.length)
throw new TypeError("Invalid PNG end chunk");
sawEnd = true;
break;
} else if (/^[A-Z]/u.test(type)) {
unsupportedReason ??= `Unsupported critical PNG chunk ${type}.`;
}
offset = dataEnd + 4;
}
if (header === undefined || !sawEnd || compressed.length === 0)
throw new TypeError("Incomplete PNG");
if (header.colorType === 3 && !sawPalette)
throw new TypeError("Missing PNG palette");
if (unsupportedReason !== undefined)
throw new AnalysisUnsupportedTargetError(
"compare_web_screenshots",
field,
unsupportedReason,
);
if (!header.supported)
throw new AnalysisUnsupportedTargetError(
"compare_web_screenshots",
field,
"PNG encoding is not supported for pixel comparison.",
);
const rowBytes = header.width * header.channels;
const expected = (rowBytes + 1) * header.height;
const raw = inflateSync(Buffer.concat(compressed), {
maxOutputLength: expected + 1,
});
const raw = inflatePng(Buffer.concat(compressed), expected + 1);
if (raw.byteLength !== expected) throw new TypeError("Unexpected PNG size");
return {
width: header.width,
@@ -125,24 +195,60 @@ const decodePng = (artifact: WebScreenshotArtifact): DecodedPng => {
};
};
const inflatePng = (compressed: Buffer, maxOutputLength: number): Buffer => {
try {
return inflateSync(compressed, { maxOutputLength });
} catch (cause: unknown) {
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "Z_DATA_ERROR" ||
cause.code === "Z_BUF_ERROR" ||
cause.code === "ERR_BUFFER_TOO_LARGE")
)
throw new TypeError("Invalid PNG image data", { cause });
throw cause;
}
};
const parseHeader = (data: Buffer) => {
if (data.byteLength !== 13) throw new TypeError("Invalid PNG header");
const width = data.readUInt32BE(0);
const height = data.readUInt32BE(4);
const bitDepth = data[8];
const colorType = data[9];
const bitDepth = data[8] ?? 0;
const colorType = data[9] ?? -1;
const safePixelCount =
BigInt(width) * BigInt(height) <= BigInt(Number.MAX_SAFE_INTEGER);
const validDepth =
(colorType === 0 && [1, 2, 4, 8, 16].includes(bitDepth)) ||
(colorType === 2 && [8, 16].includes(bitDepth)) ||
(colorType === 3 && [1, 2, 4, 8].includes(bitDepth)) ||
(colorType === 4 && [8, 16].includes(bitDepth)) ||
(colorType === 6 && [8, 16].includes(bitDepth));
if (
width === 0 ||
height === 0 ||
!Number.isSafeInteger(width * height) ||
bitDepth !== 8 ||
(colorType !== 2 && colorType !== 6) ||
width > 0x7fffffff ||
height > 0x7fffffff ||
!validDepth ||
data[10] !== 0 ||
data[11] !== 0 ||
data[12] !== 0
(data[12] !== 0 && data[12] !== 1)
)
throw new TypeError("Unsupported PNG");
return { width, height, channels: colorType === 6 ? 4 : 3 };
throw new TypeError("Invalid PNG header");
return {
width,
height,
colorType,
bitDepth,
interlace: data[12],
channels: colorType === 6 ? 4 : 3,
supported:
safePixelCount &&
bitDepth === 8 &&
(colorType === 2 || colorType === 6) &&
data[12] === 0,
};
};
const unfilter = (