test(browser): consolidate CDP and source map coverage

Use shared captures to verify discovery, document identity, screenshot recovery, and source map evidence and cleanup across varied responses. Remove redundant tests and unused fixture controls.
This commit is contained in:
morluto committed 2026-11-18 03:51:31 -05:00
1 parent 1592b7f2c0
commit caedefa00d
19 files changed
+1729 -2195

No files matched your search

+34 -41
View File
@@ -627,48 +627,41 @@ describe("CDP DOM snapshot empty strings", () => {
});
});
it.each([7, null, "without-hash"])(
"retains base URL evidence with malformed fragment %s",
(urlFragment) => {
it("preserves the base URL when fragment syntax is unreadable", () => {
for (const urlFragment of [7, null, "without-hash"]) {
expect(
observeCdpFrameUrl({ url: `${origin}/page?x=1#old`, urlFragment }),
).toEqual({ kind: "invalid_fragment", scopeUrl: `${origin}/page?x=1#old` });
},
);
}
});
it.each([7, "missing-hash"])(
"retains foreign frame scope independently of malformed fragment %s",
(urlFragment) => {
const completeness = new CdpCaptureCompleteness();
const captured = captureFrames(
frameTreeReply({
frameTree: {
frame: { id: "root", url: origin },
childFrames: [
{
frame: {
id: "foreign",
parentId: "root",
url: "https://foreign.test/page",
urlFragment,
},
},
],
},
}),
new Set([origin]),
undefined,
completeness,
);
expect(captured.items.map((frame) => frame.frame_id)).toEqual(["root"]);
expect(completeness.snapshot().excluded).toEqual(
expect.arrayContaining([
{ section: "frames", reason: "invalid_protocol_value", count: 1 },
{ section: "frames", reason: "disallowed_origin", count: 1 },
]),
);
expect(completeness.snapshot().policy_filtered_sections).toContain(
"frames",
);
},
);
it("counts both malformed foreign fragments and their origin exclusions", () => {
const completeness = new CdpCaptureCompleteness();
const captured = captureFrames(
frameTreeReply({
frameTree: {
frame: { id: "root", url: origin },
childFrames: [7, "missing-hash"].map((urlFragment, index) => ({
frame: {
id: `foreign-${index}`,
parentId: "root",
url: `https://foreign.test/page-${index}`,
urlFragment,
},
})),
},
}),
new Set([origin]),
undefined,
completeness,
);
const snapshot = completeness.snapshot();
expect(captured.items.map((frame) => frame.frame_id)).toEqual(["root"]);
expect(snapshot.excluded).toEqual(
expect.arrayContaining([
{ section: "frames", reason: "invalid_protocol_value", count: 2 },
{ section: "frames", reason: "disallowed_origin", count: 2 },
]),
);
expect(snapshot.policy_filtered_sections).toContain("frames");
});
+24 -188
View File
@@ -7,11 +7,8 @@ import { WEB_RUNTIME_LIMITS } from "../domain/webRuntime.js";
import { afterEach, describe, expect, it } from "vitest";
import { fakeCdpSend } from "../../tests/fixtures/fakeCdpSend.js";
import type { CdpConnection } from "./CdpConnection.js";
import {
discoverCdpEndpoint,
discoverCdpBrowserSocket,
readCdpJson,
withCdpDiscoveryDeadline,
} from "./CdpEndpoint.js";
@@ -168,55 +165,22 @@ describe("CDP discovery cancellation ownership", () => {
expect((failure as AnalysisCancelledError).cause).toBe(reason);
});
it("does not replace a primary discovery failure when cancellation arrives later", async () => {
const primary = new BrowserObservationError(
"inspect_web_page",
"protocol_error",
);
const controller = new AbortController();
const failure = await withCdpDiscoveryDeadline(
"inspect_web_page",
controller.signal,
async () => {
throw primary;
},
100,
).catch((error: unknown) => error);
controller.abort(new Error("late caller cancellation"));
expect(failure).toBe(primary);
});
it("does not replace a plain physical failure rejected before a late abort", async () => {
const primary = new Error("socket failed before cancellation");
const controller = new AbortController();
const pending = withCdpDiscoveryDeadline(
"inspect_web_page",
controller.signal,
() => Promise.reject(primary),
100,
).catch((error: unknown) => error);
controller.abort(new Error("later caller cancellation"));
const failure = await pending;
expect(failure).toBe(primary);
});
it("classifies its own discovery deadline as timeout", async () => {
const failure = await withCdpDiscoveryDeadline(
"inspect_web_page",
undefined,
(signal) =>
new Promise((_resolve, reject) => {
signal.addEventListener("abort", () => reject(signal.reason), {
once: true,
});
}),
1,
).catch((error: unknown) => error);
expect(failure).toBeInstanceOf(BrowserObservationError);
expect(failure).toMatchObject({ reason: "timeout" });
it("keeps typed and plain discovery failures produced before a caller abort", async () => {
const failures = [
new BrowserObservationError("inspect_web_page", "protocol_error"),
new Error("socket failed before cancellation"),
];
for (const primary of failures) {
const controller = new AbortController();
const pending = withCdpDiscoveryDeadline(
"inspect_web_page",
controller.signal,
() => Promise.reject(primary),
100,
).catch((error: unknown) => error);
controller.abort(new Error("later caller cancellation"));
expect(await pending).toBe(primary);
}
});
it("normalizes a typed cancellation caused by its own deadline to timeout", async () => {
@@ -270,13 +234,17 @@ describe("CDP discovery cancellation ownership", () => {
controller.signal,
(signal) =>
new Promise((_resolve, reject) => {
signal.addEventListener("abort", () => reject(signal.reason), {
once: true,
});
signal.addEventListener(
"abort",
() => {
controller.abort(new Error("caller stopped after timeout"));
reject(signal.reason);
},
{ once: true },
);
}),
0,
).catch((error: unknown) => error);
controller.abort(new Error("caller stopped after timeout"));
expect(failure).toBeInstanceOf(BrowserObservationError);
expect(failure).toMatchObject({ reason: "timeout" });
@@ -326,73 +294,6 @@ it("names the HTTP discovery document budget when that response deadline expires
);
});
const socketDiscoveryConnection = (
targetReply: unknown,
): Pick<CdpConnection, "send"> => ({
send: fakeCdpSend((method) => {
if (method === "Browser.getVersion")
return {
protocolVersion: "1.3",
product: "fixture",
revision: "fixture",
userAgent: "fixture",
jsVersion: "fixture",
};
if (method === "Target.getTargets") return targetReply;
throw new Error(method);
}),
});
it.each([
{ label: "absent document", reply: undefined },
{ label: "null document", reply: null },
{ label: "array document", reply: [] },
{ label: "missing target list", reply: {} },
{ label: "null target list", reply: { targetInfos: null } },
{ label: "string target list", reply: { targetInfos: "invalid" } },
{ label: "object target list", reply: { targetInfos: {} } },
])("rejects an $label during browser-socket discovery", async ({ reply }) => {
await expect(
discoverCdpBrowserSocket(
socketDiscoveryConnection(reply),
"ws://127.0.0.1:9222/devtools/browser/fixture",
"list_browser_targets",
),
).rejects.toMatchObject({
reason: "invalid_endpoint_response",
detail: expect.stringContaining("CDP Target.getTargets"),
});
});
it("reports a malformed browser-socket version as an invalid endpoint response", async () => {
await expect(
discoverCdpBrowserSocket(
{
send: fakeCdpSend((method) =>
method === "Browser.getVersion"
? { protocolVersion: "", product: "fixture" }
: { targetInfos: [] },
),
},
"ws://127.0.0.1:9222/devtools/browser/fixture",
"list_browser_targets",
),
).rejects.toMatchObject({
reason: "invalid_endpoint_response",
detail: expect.stringContaining("CDP Browser.getVersion"),
});
});
it("retains an explicitly empty browser-socket target inventory", async () => {
await expect(
discoverCdpBrowserSocket(
socketDiscoveryConnection({ targetInfos: [] }),
"ws://127.0.0.1:9222/devtools/browser/fixture",
"list_browser_targets",
),
).resolves.toMatchObject({ targets: [], limitations: [] });
});
it("preserves an independent typed cancellation when the discovery deadline also expires", async () => {
const primary = new AnalysisCancelledError("inspect_web_page", {
cause: "independent cancellation",
@@ -408,68 +309,3 @@ it("preserves an independent typed cancellation when the discovery deadline also
).catch((cause: unknown) => cause);
expect(failure).toBe(primary);
});
it("preserves browser-socket sibling identities and reports malformed optional metadata", async () => {
const discovery = await discoverCdpBrowserSocket(
{
send: fakeCdpSend((method) =>
method === "Browser.getVersion"
? {
protocolVersion: "1.3",
product: "Chrome/fixture",
revision: "r",
userAgent: "fixture",
jsVersion: "v8",
}
: {
targetInfos: [
{
targetId: "valid",
type: "page",
url: "https://example.test/",
title: "Example",
attached: false,
},
{
targetId: "partial",
type: "page",
url: "https://example.test/other",
title: 42,
attached: "yes",
},
{ targetId: "broken", type: "page" },
{
id: "wrong-identity-field",
type: "page",
url: "https://example.test/",
},
],
},
),
},
"ws://127.0.0.1:9222/devtools/browser/fixture",
"list_browser_targets",
);
expect(discovery.targets).toEqual([
{
id: "valid",
type: "page",
url: "https://example.test/",
title: "Example",
attached: false,
},
{
id: "partial",
type: "page",
url: "https://example.test/other",
title: "",
attached: null,
},
]);
expect(discovery.limitations).toHaveLength(4);
expect(
discovery.limitations?.every((limitation) =>
limitation.startsWith("CDP Target.getTargets row"),
),
).toBe(true);
});
+15 -19
View File
@@ -12,25 +12,21 @@ const cdpFrameEventFacts = (event: CdpEvent) => {
};
describe("CDP frame identity ownership", () => {
it.each([
["missing", {}],
["null", { frame: null }],
["non-object", { frame: "frame" }],
])("does not infer a root from a %s frame object", (_label, params) => {
expect(
selectCdpFrameIdentity(
cdpFrameEventFacts({ method: "Page.frameNavigated", params }),
"selected-main",
),
).toMatchObject({
applicability: "applicable",
selection: "unknown",
isRootReplacement: false,
identityIssue: "missing_frame",
parentRelation: "unknown",
parentId: null,
parentIssue: null,
});
it("keeps missing or malformed frame objects from becoming root evidence", () => {
for (const params of [{}, { frame: null }, { frame: "frame" }]) {
expect(
selectCdpFrameIdentity(
cdpFrameEventFacts({ method: "Page.frameNavigated", params }),
"selected-main",
),
).toMatchObject({
selection: "unknown",
frameId: null,
identityIssue: "missing_frame",
parentRelation: "unknown",
isRootReplacement: false,
});
}
});
it("recognizes a valid frame with no parent property as a root", () => {
+3 -23
View File
@@ -24,17 +24,13 @@ const script = (scriptId: string): CapturedScript => ({
frameId: null,
});
const capture = async (
sources: Readonly<Record<string, string>>,
includeScriptSources = true,
signal?: AbortSignal,
) => {
const capture = async (sources: Readonly<Record<string, string>>) => {
const input = inspectWebPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "page-1",
allowed_origins: ["https://example.test"],
observation_ms: 0,
include_script_sources: includeScriptSources,
include_script_sources: true,
});
const events = new CdpCaptureEvents(input, new Set(input.allowed_origins));
for (const id of Object.keys(sources)) events.scripts.set(id, script(id));
@@ -51,7 +47,6 @@ const capture = async (
discovery: undefined,
target: undefined,
input,
...(signal === undefined ? {} : { signal }),
} as unknown as CaptureContext;
const result = await captureScripts({
context,
@@ -60,7 +55,7 @@ const capture = async (
resources: [],
frameIds: new Set(),
});
return { result, events, send };
return { result, events };
};
it("admits a prefix and fitting suffix around an oversized script source", async () => {
@@ -217,18 +212,3 @@ it.each([
}
},
);
it("leaves source-off capture unchanged and does not issue source reads", async () => {
const { result, events, send } = await capture({ first: "unused" }, false);
expect(send).not.toHaveBeenCalled();
expect(result.inventory.items[0]?.source).toEqual({
included: false,
reason: "source capture was not selected",
});
expect(events.completeness.snapshot().excluded).toContainEqual({
section: "script_sources",
reason: "not_approved",
count: 1,
});
});
+40 -37
View File
@@ -17,38 +17,51 @@ it("reads encoded dimensions without changing screenshot bytes", () => {
expect(bytes.equals(original)).toBe(true);
});
it.each([12, 13, 14, 15])("rejects ASCII-folded IHDR byte at %s", (offset) => {
const bytes = Buffer.from(png);
bytes[offset] = (bytes[offset] ?? 0) | 0x80;
bytes.writeUInt32BE(crc32(bytes.subarray(12, 29)), 29);
expect(bytes.subarray(12, 16).toString("ascii")).toBe("IHDR");
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
});
it("rejects incomplete headers, invalid signatures and zero dimensions", () => {
expect(readPngHeaderDimensions(png.subarray(0, 23))).toBeUndefined();
const badSignature = Buffer.from(png);
badSignature[0] = 0;
expect(readPngHeaderDimensions(badSignature)).toBeUndefined();
for (const offset of [16, 20]) {
const zero = Buffer.from(png);
zero.writeUInt32BE(0, offset);
zero.writeUInt32BE(crc32(zero.subarray(12, 29)), 29);
expect(readPngHeaderDimensions(zero)).toBeUndefined();
it("rejects a high-bit lookalike at any position in the IHDR chunk name", () => {
for (const offset of [12, 13, 14, 15]) {
const bytes = Buffer.from(png);
bytes[offset] = (bytes[offset] ?? 0) | 0x80;
bytes.writeUInt32BE(crc32(bytes.subarray(12, 29)), 29);
expect(
readPngHeaderDimensions(bytes),
`chunk-name offset ${offset}`,
).toBeUndefined();
}
});
it.each([0, 12, 14, 0xffff_ffff])("rejects IHDR data length %s", (length) => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(length, 8);
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
it("rejects incomplete or corrupted IHDR data", () => {
const badSignature = Buffer.from(png);
badSignature[0] = 0;
const badChecksum = Buffer.from(png);
badChecksum[29] = (badChecksum[29] ?? 0) ^ 1;
expect(readPngHeaderDimensions(png.subarray(0, 32))).toBeUndefined();
expect(readPngHeaderDimensions(badSignature)).toBeUndefined();
expect(readPngHeaderDimensions(badChecksum)).toBeUndefined();
});
it.each([16, 20])("rejects out-of-range PNG dimension at %s", (offset) => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(0x8000_0000, offset);
bytes.writeUInt32BE(crc32(bytes.subarray(12, 29)), 29);
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
it("requires the fixed IHDR data length", () => {
for (const length of [0, 12, 14, 0xffff_ffff]) {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(length, 8);
expect(
readPngHeaderDimensions(bytes),
`declared length ${length}`,
).toBeUndefined();
}
});
it("requires both dimensions to be positive PNG integers", () => {
for (const offset of [16, 20]) {
for (const dimension of [0, 0x8000_0000]) {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(dimension, offset);
bytes.writeUInt32BE(crc32(bytes.subarray(12, 29)), 29);
expect(
readPngHeaderDimensions(bytes),
`dimension ${dimension} at ${offset}`,
).toBeUndefined();
}
}
});
it("accepts the largest dimension representable by the PNG specification", () => {
@@ -60,13 +73,3 @@ it("accepts the largest dimension representable by the PNG specification", () =>
height: 1,
});
});
it.each([24, 32, "crc"])("rejects incomplete or corrupt IHDR %s", (kind) => {
const bytes = Buffer.from(png);
if (kind === "crc") bytes[29] = (bytes[29] ?? 0) ^ 1;
expect(
readPngHeaderDimensions(
typeof kind === "number" ? bytes.subarray(0, kind) : bytes,
),
).toBeUndefined();
});