test(browser): consolidate source-map and deadline contracts (#13220)

This commit is contained in:
morluto authored and GitHub committed 2026-11-21 16:57:36 -05:00
1 parent d41af199f0
commit 7b3fb897c0
5 files changed
+151 -299

No files matched your search

+69 -10
View File
@@ -2,6 +2,8 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
import { describe, expect, it } from "vitest";
import { createBrowserEvidence } from "./BrowserEvidence.js";
import { listBrowserTargetsInputSchema } from "../domain/browserObservation.js";
import { browserTargetListSchema } from "../domain/browserObservationSchemas.js";
import {
analyzeWebBundleInputSchema,
webBundleAnalysisSchema,
@@ -40,16 +42,25 @@ const result = webBundleAnalysisSchema.parse({
limitations: [],
});
const bundleInput = {
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "page-1",
observation_ms: 0,
};
const input = (allowedOrigins: string[]) =>
analyzeWebBundleInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "page-1",
observation_ms: 0,
...bundleInput,
allowed_origins: allowedOrigins,
});
describe("web bundle Evidence origin scope", () => {
it("records the captured target origin when the request uses the default scope", () => {
const deadlines = {
command_timeout_ms: 1_500,
discovery_timeout_ms: 15_000,
source_map_fetch_timeout_ms: 1_750,
};
describe("web bundle Evidence scope", () => {
it("records the captured target origin and leaves implicit deadlines omitted", () => {
const evidence = createBrowserEvidence(
"analyze_web_bundle",
input([]),
@@ -60,19 +71,27 @@ describe("web bundle Evidence origin scope", () => {
expect(evidence.parameters.allowed_origins).toEqual([
"https://app.example.test",
]);
for (const deadline of Object.keys(deadlines))
expect(evidence.parameters).not.toHaveProperty(deadline);
});
it("preserves an explicit caller origin scope", () => {
it("preserves the caller's explicit origin scope and independent deadlines", () => {
const evidence = createBrowserEvidence(
"analyze_web_bundle",
input(["https://explicit.example.test"]),
analyzeWebBundleInputSchema.parse({
...bundleInput,
allowed_origins: ["https://explicit.example.test"],
fetch_source_maps: true,
...deadlines,
}),
{ source: jsonValueSchema.parse(result), facts: result },
provider,
);
expect(evidence.parameters.allowed_origins).toEqual([
"https://explicit.example.test",
]);
expect(evidence.parameters).toMatchObject({
allowed_origins: ["https://explicit.example.test"],
...deadlines,
});
});
it("does not infer an origin from a URL without one", () => {
@@ -134,3 +153,43 @@ it.each([undefined, {}, { decoded_records: 1024 }])(
else expect(evidence.parameters.source_map_limits).toEqual(selection);
},
);
const targetList = browserTargetListSchema.parse({
browser: {
product: "fixture",
protocol_version: "1.3",
revision: "fake-revision",
user_agent: "FakeChrome",
js_version: "13.0",
},
targets: [],
excluded: { disallowed_origin: 0, unsupported_url: 0, non_page: 0 },
limitations: [],
});
it("records only the caller-selected discovery deadline on target listing", () => {
const cdp_endpoint = "ws://127.0.0.1:9222/devtools/browser/fake";
const observation = {
source: jsonValueSchema.parse(targetList),
facts: targetList,
};
const explicit = createBrowserEvidence(
"list_browser_targets",
listBrowserTargetsInputSchema.parse({
cdp_endpoint,
discovery_timeout_ms: 25_000,
}),
observation,
provider,
);
expect(explicit.parameters.discovery_timeout_ms).toBe(25_000);
expect(explicit.parameters).not.toHaveProperty("command_timeout_ms");
const omitted = createBrowserEvidence(
"list_browser_targets",
listBrowserTargetsInputSchema.parse({ cdp_endpoint }),
observation,
provider,
);
expect(omitted.parameters).not.toHaveProperty("discovery_timeout_ms");
expect(omitted.parameters).not.toHaveProperty("command_timeout_ms");
});
@@ -1,168 +0,0 @@
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { expect, it } from "vitest";
import { createBrowserEvidence } from "../../../src/application/BrowserEvidence.js";
import { CDP_BROWSER_PROVIDER_IDENTITY } from "../../../src/browser/providerIdentities.js";
import { listBrowserTargetsInputSchema } from "../../../src/domain/browserObservation.js";
import { browserTargetListSchema } from "../../../src/domain/browserObservationSchemas.js";
import {
analyzeWebBundleInputSchema,
webBundleAnalysisSchema,
} from "../../../src/domain/webBundleAnalysis.js";
const targetList = browserTargetListSchema.parse({
browser: {
product: "FakeChrome/1.0",
protocol_version: "1.3",
revision: "fake-revision",
user_agent: "FakeChrome",
js_version: "13.0",
},
targets: [],
excluded: { disallowed_origin: 0, unsupported_url: 0, non_page: 0 },
limitations: [],
});
const bundle = webBundleAnalysisSchema.parse({
capture: {
target_url: "https://example.test/",
target_origin: "https://example.test",
scripts_observed: 0,
scripts_analyzed: 0,
source_artifacts: [],
},
observations: {
chunks: { nodes: [], edges: [] },
routes: [],
endpoints: [],
webmcp_declarations: [],
source_maps: {
status: "not_requested",
requested: 0,
processed: 0,
items: [],
},
},
inferences: [],
unknowns: [],
completeness: {
status: "complete",
parsed_scripts: 0,
parse_failures: 0,
visited_ast_nodes: 0,
},
limitations: [],
});
it("records an explicit command deadline and omits the default", () => {
const base = {
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "page",
fetch_source_maps: false,
};
const explicit = createBrowserEvidence(
"analyze_web_bundle",
analyzeWebBundleInputSchema.parse({
...base,
command_timeout_ms: 1_500,
}),
{ source: jsonValueSchema.parse(bundle), facts: bundle },
CDP_BROWSER_PROVIDER_IDENTITY,
);
expect(explicit.parameters.command_timeout_ms).toBe(1_500);
const omitted = createBrowserEvidence(
"analyze_web_bundle",
analyzeWebBundleInputSchema.parse(base),
{ source: jsonValueSchema.parse(bundle), facts: bundle },
CDP_BROWSER_PROVIDER_IDENTITY,
);
expect(omitted.parameters).not.toHaveProperty("command_timeout_ms");
});
it("rejects a command deadline on target listing and leaves it out of Evidence", () => {
expect(
listBrowserTargetsInputSchema.safeParse({
cdp_endpoint: "http://127.0.0.1:9222",
command_timeout_ms: 1_500,
}).success,
).toBe(false);
const evidence = createBrowserEvidence(
"list_browser_targets",
listBrowserTargetsInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
}),
{ source: jsonValueSchema.parse(targetList), facts: targetList },
CDP_BROWSER_PROVIDER_IDENTITY,
);
expect(evidence.parameters).not.toHaveProperty("command_timeout_ms");
});
it("records an explicit discovery deadline and omits the default", () => {
const explicitListing = createBrowserEvidence(
"list_browser_targets",
listBrowserTargetsInputSchema.parse({
cdp_endpoint: "ws://127.0.0.1:9222/devtools/browser/fake",
discovery_timeout_ms: 25_000,
}),
{ source: jsonValueSchema.parse(targetList), facts: targetList },
CDP_BROWSER_PROVIDER_IDENTITY,
);
expect(explicitListing.parameters.discovery_timeout_ms).toBe(25_000);
const omittedListing = createBrowserEvidence(
"list_browser_targets",
listBrowserTargetsInputSchema.parse({
cdp_endpoint: "ws://127.0.0.1:9222/devtools/browser/fake",
}),
{ source: jsonValueSchema.parse(targetList), facts: targetList },
CDP_BROWSER_PROVIDER_IDENTITY,
);
expect(omittedListing.parameters).not.toHaveProperty("discovery_timeout_ms");
const baseBundle = {
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "page",
fetch_source_maps: false,
};
const explicitBundle = createBrowserEvidence(
"analyze_web_bundle",
analyzeWebBundleInputSchema.parse({
...baseBundle,
discovery_timeout_ms: 15_000,
}),
{ source: jsonValueSchema.parse(bundle), facts: bundle },
CDP_BROWSER_PROVIDER_IDENTITY,
);
expect(explicitBundle.parameters.discovery_timeout_ms).toBe(15_000);
const omittedBundle = createBrowserEvidence(
"analyze_web_bundle",
analyzeWebBundleInputSchema.parse(baseBundle),
{ source: jsonValueSchema.parse(bundle), facts: bundle },
CDP_BROWSER_PROVIDER_IDENTITY,
);
expect(omittedBundle.parameters).not.toHaveProperty("discovery_timeout_ms");
});
it("records an explicit source-map fetch deadline and omits the default", () => {
const base = {
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "page",
fetch_source_maps: true,
};
const explicit = createBrowserEvidence(
"analyze_web_bundle",
analyzeWebBundleInputSchema.parse({
...base,
source_map_fetch_timeout_ms: 1_500,
}),
{ source: jsonValueSchema.parse(bundle), facts: bundle },
CDP_BROWSER_PROVIDER_IDENTITY,
);
expect(explicit.parameters.source_map_fetch_timeout_ms).toBe(1_500);
const omitted = createBrowserEvidence(
"analyze_web_bundle",
analyzeWebBundleInputSchema.parse(base),
{ source: jsonValueSchema.parse(bundle), facts: bundle },
CDP_BROWSER_PROVIDER_IDENTITY,
);
expect(omitted.parameters).not.toHaveProperty("source_map_fetch_timeout_ms");
});
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
import { createServer } from "node:http";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { phaseArrival } from "../../support/lifecycleHarness.js";
import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs";
@@ -555,16 +555,19 @@ describe("source-map declared URL policy", () => {
});
describe("web source-map fetching and validation: enforcing fetch limits and validating responses", () => {
it("settles an endless unique-URL redirect chain at the selected fetch deadline", async () => {
let calls = 0;
it("aborts a paused HTTP redirect chain at the selected fetch deadline", async () => {
const stalled = phaseArrival<number>();
const requests: number[] = [];
const server = createServer((incoming, response) => {
calls += 1;
const next =
Number(
new URL(incoming.url ?? "/", "http://local").searchParams.get("n") ??
"0",
) + 1;
response.writeHead(302, { location: `/map?n=${String(next)}` }).end();
const hop = Number(
new URL(incoming.url ?? "/", "http://local").searchParams.get("n"),
);
requests.push(hop);
if (hop === 8) stalled.arrive(hop);
else
response
.writeHead(302, { location: `/map?n=${String(hop + 1)}` })
.end();
});
try {
await new Promise<void>((resolve, reject) => {
@@ -576,37 +579,45 @@ describe("web source-map fetching and validation: enforcing fetch limits and val
throw new TypeError("Expected a TCP listener address");
const localOrigin = `http://127.0.0.1:${String(address.port)}`;
const url = `${localOrigin}/map?n=0`;
const result = await fetchWebSourceMapsOk(
const deadline = 13_700;
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
const capture = fetchWebSourceMapsOk(
[{ ...request, fetchUrl: url, declaredUrl: url }],
input({
allowed_origins: [localOrigin],
source_map_fetch_timeout_ms: 250,
source_map_fetch_timeout_ms: deadline,
}),
AbortSignal.timeout(2_000),
{ fetch },
AbortSignal.timeout(4_000),
);
expect(calls).toBeGreaterThan(1);
expect(result).toMatchObject({
await stalled.reached(
capture,
"ninth HTTP request in an approved redirect chain",
);
expect(requests).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);
await vi.advanceTimersByTimeAsync(deadline);
expect(await capture).toMatchObject({
status: "unavailable",
processed: 1,
items: [
{
status: "fetch_failed",
effective_url: `${localOrigin}/map?n=7`,
artifact: null,
limitation: expect.stringContaining(
"250 ms source_map_fetch_timeout_ms deadline",
`${String(deadline)} ms source_map_fetch_timeout_ms deadline`,
),
},
],
});
} finally {
vi.useRealTimers();
server.closeAllConnections();
if (server.listening)
await new Promise<void>((resolve, reject) => {
await new Promise<void>((resolve, reject) =>
server.close((error) =>
error === undefined ? resolve() : reject(error),
);
});
),
);
}
});
@@ -1,87 +0,0 @@
import { createHash } from "node:crypto";
import { createServer } from "node:http";
import { expect, it } from "vitest";
import { fetchWebSourceMapsOk } from "../../fixtures/fetchWebSourceMapsOk.js";
import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
it("retains literal dependencies from HTTP source-map originals", async () => {
const source = [
'// import "./comment.js";',
String.raw`const quoted = "require(\"./string.js\")";`,
"const template = `import './template-comment.js'`;",
`export { value } from "./it's-real.js";`,
'import "package-name";',
'import("./dynamic.js");',
"import(`./dep.js`);",
"import(`./dep.${name}.js`);",
'require("./normal.cjs");',
"require(`./templated.cjs`);",
"require(`./${name}.cjs`);",
'require?.("./optional.cjs");',
'function local(require) { require?.("./shadowed.cjs"); }',
"require?.(selectedModule);",
].join("\n");
const text = JSON.stringify({
version: 3,
names: [],
mappings: "AAAA",
sources: ["main.cjs"],
sourcesContent: [source],
});
const server = createServer((_request, response) => response.end(text));
try {
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (address === null || typeof address === "string")
throw new TypeError("Expected a TCP listener address");
const origin = `http://127.0.0.1:${String(address.port)}`;
const url = `${origin}/app.js.map`;
const result = await fetchWebSourceMapsOk(
[{ scriptKey: `scr_${"1".repeat(64)}`, declaredUrl: url, fetchUrl: url }],
analyzeWebBundleInputSchema.parse({
cdp_endpoint: origin,
target_id: "fixture",
allowed_origins: [origin],
fetch_source_maps: true,
}),
);
expect(result.items[0]).toMatchObject({
status: "included",
artifact: {
text,
bytes: Buffer.byteLength(text),
sha256: createHash("sha256").update(text).digest("hex"),
},
original_sources: [{ artifact: { text: source } }],
mappings: [{ generated_line: 1, source: `${origin}/main.cjs` }],
original_module_edges: [
{ specifier: "./it's-real.js", kind: "static_import" },
{ specifier: "package-name", kind: "static_import" },
{ specifier: "./dynamic.js", kind: "dynamic_import" },
{ specifier: "./dep.js", kind: "dynamic_import" },
{ specifier: "./normal.cjs", kind: "require" },
{ specifier: "./templated.cjs", kind: "require" },
{ specifier: "./optional.cjs", kind: "require" },
].map(({ kind, specifier }) => ({
from_source: `${origin}/main.cjs`,
kind,
specifier,
resolved_source:
specifier === "package-name" ? null : new URL(specifier, origin).href,
})),
});
} finally {
server.closeAllConnections();
if (server.listening)
await new Promise<void>((resolve, reject) => {
server.close((error) =>
error === undefined ? resolve() : reject(error),
);
});
}
});
@@ -10,7 +10,40 @@ import { fetchWebSourceMapsOk } from "../../fixtures/fetchWebSourceMapsOk.js";
const typescriptContent = 'import "./dep.ts"; const value = <number>1;';
const annotatedContent = 'import "./dep.ts"; const value: number = 1;';
const javascriptContent = 'import "./dep.ts"; const value = 1;';
const commonJsContent = [
'// import "./comment.js";',
String.raw`const quoted = "require(\"./string.js\")";`,
"const template = `import './template-comment.js'`;",
`export { value } from "./it's-real.js";`,
'import "package-name";',
'import("./dynamic.js");',
"import(`./dep.js`);",
"import(`./dep.${name}.js`);",
'require("./normal.cjs");',
"require(`./templated.cjs`);",
"require(`./${name}.cjs`);",
'require?.("./optional.cjs");',
'function local(require) { require?.("./shadowed.cjs"); }',
"require?.(selectedModule);",
].join("\n");
const commonJsEdges = [
["static_import", "./it's-real.js"],
["static_import", "package-name"],
["dynamic_import", "./dynamic.js"],
["dynamic_import", "./dep.js"],
["require", "./normal.cjs"],
["require", "./templated.cjs"],
["require", "./optional.cjs"],
] as const;
const declarations = [
{
path: "main.cjs",
mediaType: "text/javascript",
content: commonJsContent,
edges: commonJsEdges,
},
{
path: "plain.ts?revision=2#view.tsx",
mediaType: "text/typescript",
@@ -117,7 +150,11 @@ it("selects the language of HTTP map originals and retains exact URLs and depend
expect(result.items[0]).toMatchObject({
status: "included",
limitation: null,
artifact: { text },
artifact: {
text,
bytes: Buffer.byteLength(text),
sha256: createHash("sha256").update(text).digest("hex"),
},
original_sources: sources.map(({ source, content, mediaType }) => ({
source,
artifact: {
@@ -132,22 +169,22 @@ it("selects the language of HTTP map originals and retains exact URLs and depend
source,
})),
original_module_edges: sources.flatMap(
({ source, requires = [] }, declaration_index) => [
{
({ source, edges, requires = [] }, declaration_index) => {
const imports = edges ?? [
["static_import", "./dep.ts"] as const,
...requires.map((specifier) => ["require", specifier] as const),
];
return imports.map(([kind, specifier]) => ({
declaration_index,
from_source: source,
kind: "static_import",
specifier: "./dep.ts",
resolved_source: `${origin}/maps/dep.ts`,
},
...requires.map((specifier) => ({
declaration_index,
from_source: source,
kind: "require",
kind,
specifier,
resolved_source: new URL(specifier, source).href,
})),
],
resolved_source:
specifier === "package-name"
? null
: new URL(specifier, source).href,
}));
},
),
});
} finally {