From 4e4b15b8250b29e176d4191c9610a3931b693474 Mon Sep 17 00:00:00 2001 From: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sun, 11 Oct 2026 10:59:25 +0800 Subject: [PATCH] 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> --- src/browser/CdpBrowserProvider.ts | 7 + src/browser/PngVisualDiff.test.ts | 225 ++++++++++++++++++ src/browser/PngVisualDiff.ts | 156 ++++++++++-- .../cli/browserCompareJsonFiles.test.ts | 75 ++++++ tests/boundary/mcp/browserMcp.test.ts | 66 +++++ tests/fixtures/fakeCdpBrowserResults.ts | 2 +- 6 files changed, 505 insertions(+), 26 deletions(-) diff --git a/src/browser/CdpBrowserProvider.ts b/src/browser/CdpBrowserProvider.ts index a97ef7358..72838626d 100644 --- a/src/browser/CdpBrowserProvider.ts +++ b/src/browser/CdpBrowserProvider.ts @@ -43,6 +43,7 @@ import { type WebScreenshotDiff, } from "../domain/webScreenshot.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; +import { AnalysisInputError } from "../domain/analysisErrorCore.js"; import { BrowserObservationError } from "../domain/browserObservationError.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { type BrowserObservationOperation } from "../domain/browserObservationErrors.js"; @@ -314,6 +315,12 @@ export class CdpBrowserProvider implements BrowserObservationPort { try { return ok(webScreenshotDiffSchema.parse(comparePngScreenshots(input))); } catch (cause: unknown) { + if (cause instanceof TypeError) + return err( + new AnalysisInputError("compare_web_screenshots", { cause }, [ + { path: [], reason: "invalid_format", message: cause.message }, + ]), + ); return err(providerError(cause, "compare_web_screenshots")); } } diff --git a/src/browser/PngVisualDiff.test.ts b/src/browser/PngVisualDiff.test.ts index e3aa38737..8a4fc6f87 100644 --- a/src/browser/PngVisualDiff.test.ts +++ b/src/browser/PngVisualDiff.test.ts @@ -3,6 +3,7 @@ import { crc32, deflateSync } from "node:zlib"; import { describe, expect, it } from "vitest"; import { comparePngScreenshots } from "./PngVisualDiff.js"; +import { AnalysisUnsupportedTargetError } from "../domain/analysisErrorCore.js"; import { compareWebScreenshotsInputSchema, createWebScreenshotArtifact, @@ -149,6 +150,230 @@ describe("PNG visual diff", () => { }); }); +describe("PNG chunk integrity", () => { + it.each(["IHDR", "IDAT", "IEND"])( + "rejects a corrupt %s chunk checksum", + (type) => { + const bytes = png(1, 1, [0, 0, 0, 255]); + let offset = 8; + while (offset < bytes.length) { + const length = bytes.readUInt32BE(offset); + if (bytes.subarray(offset + 4, offset + 8).toString("ascii") === type) { + bytes[offset + 8 + length] = (bytes[offset + 8 + length] ?? 0) ^ 1; + break; + } + offset += length + 12; + } + const image = createWebScreenshotArtifact(bytes); + expect(() => + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ + before: image, + after: image, + }), + ), + ).toThrow("Invalid PNG chunk checksum"); + }, + ); + + it("reports a CRC-valid but corrupt compressed stream as invalid PNG data", () => { + const header = Buffer.from(png(1, 1, [0, 0, 0, 255]).subarray(16, 29)); + const image = createWebScreenshotArtifact( + Buffer.concat([ + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), + chunk("IHDR", header), + chunk("IDAT", Buffer.from("bad")), + chunk("IEND", Buffer.alloc(0)), + ]), + ); + expect(() => + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ before: image, after: image }), + ), + ).toThrow("Invalid PNG image data"); + }); + + it("rejects high-bit bytes in a CRC-valid PNG chunk name", () => { + const bytes = png(1, 1, [0, 0, 0, 255]); + const headerChunk = Buffer.from(bytes.subarray(8, 33)); + headerChunk[4] = 0xc9; + headerChunk.writeUInt32BE(crc32(headerChunk.subarray(4, 21)), 21); + const malformed = createWebScreenshotArtifact( + Buffer.concat([bytes.subarray(0, 8), headerChunk, bytes.subarray(33)]), + ); + expect(() => + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ + before: malformed, + after: malformed, + }), + ), + ).toThrow("Invalid PNG chunk type"); + }); + + it("rejects duplicate image headers and unknown critical chunks while preserving ancillary chunks", () => { + const bytes = png(1, 1, [0, 0, 0, 255]); + const duplicate = Buffer.concat([ + bytes.subarray(0, 33), + bytes.subarray(8, 33), + bytes.subarray(33), + ]); + const unknown = Buffer.concat([ + bytes.subarray(0, 33), + chunk("ABCD", Buffer.alloc(0)), + bytes.subarray(33), + ]); + for (const malformed of [duplicate, unknown]) { + const image = createWebScreenshotArtifact(malformed); + expect(() => + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ + before: image, + after: image, + }), + ), + ).toThrow(/Invalid PNG header order|Unsupported critical PNG chunk/u); + } + const ancillary = createWebScreenshotArtifact( + Buffer.concat([ + bytes.subarray(0, 33), + chunk("tEXt", Buffer.from("Comment\0original capture")), + bytes.subarray(33), + ]), + ); + expect( + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ + before: ancillary, + after: createWebScreenshotArtifact(bytes), + }), + ).status, + ).toBe("identical"); + }); + + it("rejects bytes after IEND and reports valid unsupported PNG encodings separately", () => { + const bytes = png(1, 1, [0, 0, 0, 255]); + const trailing = createWebScreenshotArtifact( + Buffer.concat([bytes, Buffer.from([0])]), + ); + expect(() => + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ + before: trailing, + after: trailing, + }), + ), + ).toThrow("Invalid PNG end chunk"); + + const grayscaleHeader = Buffer.from(bytes.subarray(16, 29)); + grayscaleHeader[9] = 0; + const grayscale = createWebScreenshotArtifact( + Buffer.concat([ + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), + chunk("IHDR", grayscaleHeader), + chunk("IDAT", deflateSync(Buffer.from([0, 30]))), + chunk("IEND", Buffer.alloc(0)), + ]), + ); + expect(() => + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ + before: grayscale, + after: grayscale, + }), + ), + ).toThrow(AnalysisUnsupportedTargetError); + }); +}); + +describe("PNG chunk ordering", () => { + it("rejects malformed palettes, interrupted data and misplaced transparency while retaining valid chunks", () => { + const header = Buffer.from(png(1, 1, [10, 20, 30, 255]).subarray(16, 29)); + header[9] = 2; + const ihdr = chunk("IHDR", header); + const compressed = deflateSync(Buffer.from([0, 10, 20, 30])); + const idat = chunk("IDAT", compressed); + const iend = chunk("IEND", Buffer.alloc(0)); + const palette = chunk("PLTE", Buffer.from([10, 20, 30])); + const transparency = chunk("tRNS", Buffer.from([0, 10, 0, 20, 0, 30])); + const ancillary = chunk("tEXt", Buffer.from("Comment\0retained")); + const image = (...chunks: readonly Buffer[]) => + createWebScreenshotArtifact( + Buffer.concat([ + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), + ...chunks, + ]), + ); + const original = image(ihdr, idat, iend); + const cases = [ + [ihdr, chunk("PLTE", Buffer.alloc(1)), idat, iend], + [ihdr, palette, palette, idat, iend], + [ihdr, idat, palette, iend], + [ihdr, transparency, palette, idat, iend], + [ihdr, transparency, transparency, idat, iend], + [ihdr, idat, transparency, iend], + [ + ihdr, + chunk("IDAT", compressed.subarray(0, 6)), + ancillary, + chunk("IDAT", compressed.subarray(6)), + iend, + ], + [ihdr, idat, chunk("IEND", Buffer.from([1]))], + ]; + for (const chunks of cases) { + const malformed = image(...chunks); + expect(() => + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ + before: malformed, + after: original, + }), + ), + ).toThrow( + /Invalid PNG palette|Invalid PNG transparency order|Nonconsecutive PNG image data|Invalid PNG end chunk/u, + ); + } + const indexedHeader = Buffer.from(header); + indexedHeader[8] = 1; + indexedHeader[9] = 3; + const emptyTransparency = image( + chunk("IHDR", indexedHeader), + chunk("PLTE", Buffer.from([10, 20, 30])), + chunk("tRNS", Buffer.alloc(0)), + chunk("IDAT", deflateSync(Buffer.from([0, 0]))), + iend, + ); + expect(() => + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ + before: emptyTransparency, + after: original, + }), + ), + ).toThrow("Unsupported PNG transparency"); + for (const valid of [ + image(ihdr, palette, idat, iend), + image(ihdr, ancillary, idat, iend), + image( + ihdr, + chunk("IDAT", compressed.subarray(0, 6)), + chunk("IDAT", compressed.subarray(6)), + iend, + ), + ]) { + expect( + comparePngScreenshots( + compareWebScreenshotsInputSchema.parse({ + before: valid, + after: original, + }), + ).status, + ).toBe("identical"); + } + }); +}); + const artifact = (width: number, height: number, pixels: readonly number[]) => createWebScreenshotArtifact(png(width, height, pixels)); diff --git a/src/browser/PngVisualDiff.ts b/src/browser/PngVisualDiff.ts index 77393c89d..dc570bada 100644 --- a/src/browser/PngVisualDiff.ts +++ b/src/browser/PngVisualDiff.ts @@ -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 | 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 = ( diff --git a/tests/boundary/cli/browserCompareJsonFiles.test.ts b/tests/boundary/cli/browserCompareJsonFiles.test.ts index 0f067175f..fbaed83cf 100644 --- a/tests/boundary/cli/browserCompareJsonFiles.test.ts +++ b/tests/boundary/cli/browserCompareJsonFiles.test.ts @@ -97,6 +97,14 @@ describe("browser comparison JSON file inputs", () => { INTEGRATION_TEST_TIMEOUT_MS, ); + it( + "reports malformed PNG chunks as invalid input and valid unsupported PNGs as unsupported targets", + async () => { + await assertPngInputErrorProjections(); + }, + INTEGRATION_TEST_TIMEOUT_MS, + ); + it( "identifies a missing capture file instead of reporting malformed JSON", async () => { @@ -123,3 +131,70 @@ describe("browser comparison JSON file inputs", () => { INTEGRATION_TEST_TIMEOUT_MS, ); }); + +const assertPngInputErrorProjections = async (): Promise => { + const damagedBytes = noisePng(1, 1); + damagedBytes[29] = (damagedBytes[29] ?? 0) ^ 1; + const damaged = JSON.stringify(createWebScreenshotArtifact(damagedBytes)); + expect( + await runCli(["compare-web-screenshots", damaged, damaged, "--json"]), + ).toMatchObject({ + code: "invalid_request", + details: { + operation: "compare_web_screenshots", + issues: [ + { path: [], reason: "invalid_format", message: expect.any(String) }, + ], + }, + }); + + const header = Buffer.alloc(13); + header.writeUInt32BE(1, 0); + header.writeUInt32BE(1, 4); + header.set([8, 2, 0, 0, 0], 8); + const malformedDeflate = JSON.stringify( + createWebScreenshotArtifact( + Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + pngChunk("IHDR", header), + pngChunk("IDAT", Buffer.from("bad")), + pngChunk("IEND", Buffer.alloc(0)), + ]), + ), + ); + expect( + await runCli([ + "compare-web-screenshots", + malformedDeflate, + malformedDeflate, + "--json", + ]), + ).toMatchObject({ + code: "invalid_request", + details: { + operation: "compare_web_screenshots", + issues: [{ path: [], reason: "invalid_format" }], + }, + }); + + const grayscaleHeader = Buffer.alloc(13); + grayscaleHeader.writeUInt32BE(1, 0); + grayscaleHeader.writeUInt32BE(1, 4); + grayscaleHeader.set([8, 0, 0, 0, 0], 8); + const grayscale = JSON.stringify( + createWebScreenshotArtifact( + Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + pngChunk("IHDR", grayscaleHeader), + pngChunk("IDAT", deflateSync(Buffer.from([0, 30]))), + pngChunk("IEND", Buffer.alloc(0)), + ]), + ), + ); + expect( + await runCli(["compare-web-screenshots", grayscale, grayscale, "--json"]), + ).toMatchObject({ + code: "unsupported_target", + details: { operation: "compare_web_screenshots" }, + }); +}; diff --git a/tests/boundary/mcp/browserMcp.test.ts b/tests/boundary/mcp/browserMcp.test.ts index 17a8f404a..9c0bd9dfc 100644 --- a/tests/boundary/mcp/browserMcp.test.ts +++ b/tests/boundary/mcp/browserMcp.test.ts @@ -1,4 +1,5 @@ import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { crc32, deflateSync } from "node:zlib"; import { parseEvidence } from "../../../src/domain/evidence.js"; import { ok as resultOk } from "../../../src/domain/result.js"; import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; @@ -7,6 +8,7 @@ import { afterEach, expect, it } from "vitest"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js"; import { webPageInspectionSchema } from "../../../src/domain/browserObservationSchemas.js"; +import { createWebScreenshotArtifact } from "../../../src/domain/webScreenshot.js"; import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascript/javascriptRuntimeReconciliationExample.js"; import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js"; import { createServer } from "../../../src/server/createServer.js"; @@ -262,6 +264,8 @@ const verifySessionAndComparisonTools = async ( expect(visual.structuredContent).toMatchObject({ normalized_result: { status: "identical", changed_pixels: 0 }, }); + + await assertScreenshotPngFailures(connected.client); expect(inspected.structuredContent).toMatchObject({ normalized_result: expect.any(Object), operation: "inspect_web_page", @@ -270,6 +274,68 @@ const verifySessionAndComparisonTools = async ( }); }; +const pngChunk = (type: string, data: Buffer): Buffer => { + const chunk = Buffer.alloc(12 + data.length); + chunk.writeUInt32BE(data.length, 0); + chunk.write(type, 4, 4, "ascii"); + data.copy(chunk, 8); + chunk.writeUInt32BE( + crc32(chunk.subarray(4, 8 + data.length)), + 8 + data.length, + ); + return chunk; +}; + +const assertScreenshotPngFailures = async (client: Client): Promise => { + const header = Buffer.alloc(13); + header.writeUInt32BE(1, 0); + header.writeUInt32BE(1, 4); + header.set([8, 2, 0, 0, 0], 8); + const malformedPng = Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + pngChunk("IHDR", header), + pngChunk("IDAT", Buffer.from("bad")), + pngChunk("IEND", Buffer.alloc(0)), + ]); + const malformedArtifact = createWebScreenshotArtifact(malformedPng); + const malformed = await client.callTool({ + name: "compare_web_screenshots", + arguments: { + before: malformedArtifact, + after: malformedArtifact, + }, + }); + expect(parseMcpToolError(malformed)).toMatchObject({ + error: { + code: "invalid_request", + category: "invalid_input", + details: { + operation: "compare_web_screenshots", + issues: [{ path: [], reason: "invalid_format" }], + }, + }, + }); + + const grayscaleHeader = Buffer.alloc(13); + grayscaleHeader.writeUInt32BE(1, 0); + grayscaleHeader.writeUInt32BE(1, 4); + grayscaleHeader.set([8, 0, 0, 0, 0], 8); + const unsupportedPng = Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + pngChunk("IHDR", grayscaleHeader), + pngChunk("IDAT", deflateSync(Buffer.from([0, 30]))), + pngChunk("IEND", Buffer.alloc(0)), + ]); + const unsupported = createWebScreenshotArtifact(unsupportedPng); + const rejectedFormat = await client.callTool({ + name: "compare_web_screenshots", + arguments: { before: unsupported, after: unsupported }, + }); + expect(parseMcpToolError(rejectedFormat)).toMatchObject({ + error: { code: "unsupported_target", category: "unsupported_target" }, + }); +}; + it("does not attach to a target outside the request's allowed origin scope", async () => { const browser = await startFakeCdpBrowser(); browsers.push(browser); diff --git a/tests/fixtures/fakeCdpBrowserResults.ts b/tests/fixtures/fakeCdpBrowserResults.ts index 5b5f38bbb..908db238e 100644 --- a/tests/fixtures/fakeCdpBrowserResults.ts +++ b/tests/fixtures/fakeCdpBrowserResults.ts @@ -118,7 +118,7 @@ const responseBodyResult = (options: FakeOptions) => }; const screenshotResult = () => ({ - data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PzWvWQAAAABJRU5ErkJggg==", + data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==", }); const storageUsageResult = () => ({