refactor(browser): return complete observation evidence

This commit is contained in:
morluto
2026-09-29 13:56:49 +08:00
parent 9d1f88cbe8
commit 0e2738ffb6
69 changed files with 747 additions and 1206 deletions
@@ -20,7 +20,7 @@ describeBrowser("CdpBrowserProvider: document script 1", () => {
).toBe(false);
});
it("captures bounded accessibility text only after independent approval", async () => {
it("captures approved accessibility text inline", async () => {
const browser = await startFakeCdpBrowser();
trackBrowser(browser);
const request = inspectWebPageInputSchema.parse({
@@ -30,26 +30,16 @@ describeBrowser("CdpBrowserProvider: document script 1", () => {
observation_ms: 0,
include_accessibility_text: true,
});
const result = await new CdpBrowserProvider().inspectPage({
...request,
limits: {
...request.limits,
max_ax_text_field_bytes: 6,
},
});
const result = await new CdpBrowserProvider().inspectPage(request);
if (!result.ok) throw result.error;
expect(result.value.accessibility).toMatchObject({
text_capture: {
status: "truncated",
retained_bytes: 12,
truncated_fields: 2,
status: "included",
retained_bytes: 27,
},
nodes: [expect.objectContaining({ name: "Submit" })],
nodes: [expect.objectContaining({ name: "Submit report" })],
});
expect(result.value.completeness.truncated_sections).toContain(
"accessibility",
);
});
it("includes allowed script source only after explicit approval", async () => {
@@ -288,6 +278,38 @@ describeBrowser("CdpBrowserProvider: document script 2", () => {
});
});
describeBrowser("CdpBrowserProvider WebMCP inventory completeness", () => {
it("retains every field in a large declared WebMCP input schema", async () => {
const propertyCount = 5_001;
const browser = await startFakeCdpBrowser({
webMcpTools: true,
webMcpSchemaPropertyCount: propertyCount,
});
trackBrowser(browser);
const result = await new CdpBrowserProvider().discoverWebMcpTools(
discoverWebMcpToolsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
const shape = result.value.tools.items[0]?.input_schema_shape;
expect(
shape?.properties.filter(({ path }) =>
path.startsWith("/properties/field_"),
),
).toHaveLength(propertyCount * 2);
expect(shape?.properties).toContainEqual({
path: "/properties/field_5000/type",
types: ["string"],
observations: 1,
});
});
});
describeBrowser("CdpBrowserProvider: document script 3", () => {
it("removes WebMCP declarations after their child frame leaves scope", async () => {
const browser = await startFakeCdpBrowser({
@@ -369,7 +391,7 @@ describeBrowser("CdpBrowserProvider: document script 3", () => {
});
});
it("returns every DOM node and applies the per-script source limit", async () => {
it("returns every DOM node and complete approved script source", async () => {
const browser = await startFakeCdpBrowser();
trackBrowser(browser);
const request = inspectWebPageInputSchema.parse({
@@ -379,24 +401,17 @@ describeBrowser("CdpBrowserProvider: document script 3", () => {
observation_ms: 0,
include_script_sources: true,
});
const result = await new CdpBrowserProvider().inspectPage({
...request,
limits: {
...request.limits,
max_script_source_bytes: 10,
},
});
const result = await new CdpBrowserProvider().inspectPage(request);
if (!result.ok) throw result.error;
expect(result.value.completeness).toMatchObject({
truncated_sections: ["script_sources"],
});
expect(result.value.completeness.truncated_sections).not.toContain(
"script_sources",
);
expect(result.value.dom).toMatchObject({ total_nodes: 2 });
expect(result.value.dom.nodes).toHaveLength(2);
expect(result.value.scripts.items[0]?.source).toMatchObject({
included: false,
reason: "declared script length exceeds per-script limit",
included: true,
});
expect(browser.commands.map(({ method }) => method)).not.toContain(
expect(browser.commands.map(({ method }) => method)).toContain(
"Debugger.getScriptSource",
);
});
@@ -270,7 +270,7 @@ describeBrowser("CdpBrowserProvider: lifecycle failures 3", () => {
);
for (const [options, reason] of [
[{ oversizedDiscovery: true }, "payload_limit"],
[{ oversizedDiscovery: true }, "invalid_endpoint_response"],
[{ invalidBrowserWebSocket: true }, "invalid_endpoint_response"],
] as const) {
const failed = await startFakeCdpBrowser(options);
@@ -158,6 +158,33 @@ describeBrowser("CdpBrowserProvider: sensitive data 1", () => {
});
});
describeBrowser("CdpBrowserProvider: complete storage fingerprints", () => {
it("fingerprints cache bodies above the former byte ceiling", async () => {
const body = "x".repeat(64 * 1_024 + 1);
const browser = await startFakeCdpBrowser({ cachedResponseBody: body });
trackBrowser(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
include_storage_keys: true,
include_storage_fingerprints: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value.storage.fingerprints_complete).toBe(true);
expect(
result.value.storage.content_fingerprints.find(
({ scope }) => scope === "cache_entry",
),
).toMatchObject({ complete: true, value_sha256: expect.any(String) });
expect(JSON.stringify(result.value)).not.toContain(body);
});
});
describeBrowser("CdpBrowserProvider: sensitive data 2", () => {
it("captures only approved redacted console text and value-free payload shapes", async () => {
const browser = await startFakeCdpBrowser({
@@ -185,7 +212,6 @@ describeBrowser("CdpBrowserProvider: sensitive data 2", () => {
{ argument_index: 1, type: "number", text: "42" },
],
retained_bytes: 26,
truncated_values: 0,
});
expect(result.value.network.requests[0]?.body_shapes).toMatchObject({
status: "included",
@@ -227,7 +253,6 @@ describeBrowser("CdpBrowserProvider: sensitive data 2", () => {
payload_shape: {
format: "binary",
json_shape: null,
truncated: false,
},
}),
]);
@@ -247,8 +272,8 @@ describeBrowser("CdpBrowserProvider: sensitive data 2", () => {
});
});
describeBrowser("CdpBrowserProvider: sensitive data 3", () => {
it("keeps per-value text, body, and WebSocket shape validation", async () => {
describeBrowser("CdpBrowserProvider: complete sensitive data", () => {
it("returns complete approved text and shapes while redacting secrets", async () => {
const browser = await startFakeCdpBrowser({ sensitiveShapes: true });
trackBrowser(browser);
const request = inspectWebPageInputSchema.parse({
@@ -260,41 +285,24 @@ describeBrowser("CdpBrowserProvider: sensitive data 3", () => {
include_json_body_shapes: true,
include_websocket_shapes: true,
});
const result = await new CdpBrowserProvider().inspectPage({
...request,
limits: {
...request.limits,
max_console_text_field_bytes: 5,
max_json_body_bytes: 10,
max_websocket_shape_bytes: 5,
},
});
const result = await new CdpBrowserProvider().inspectPage(request);
if (!result.ok) throw result.error;
expect(result.value.console.events[0]?.text_capture).toEqual({
status: "truncated",
status: "included",
values: [
{ argument_index: 0, type: "string", text: "autho" },
{ argument_index: 0, type: "string", text: "authorization=[REDACTED]" },
{ argument_index: 1, type: "number", text: "42" },
],
retained_bytes: 7,
truncated_values: 1,
retained_bytes: 26,
});
expect(result.value.network.requests[0]?.body_shapes.status).toBe(
"truncated",
"included",
);
expect(result.value.network.websocket_events[0]?.payload_shape).toEqual({
format: "text",
json_shape: null,
truncated: true,
format: "json",
json_shape: expect.objectContaining({ root_type: "object" }),
});
expect(result.value.completeness.truncated_sections).toEqual(
expect.arrayContaining([
"console_text",
"json_body_shapes",
"websocket_shapes",
]),
);
});
it("fails closed on malformed approved response and binary payload encodings", async () => {
@@ -0,0 +1,53 @@
import { expect, it } from "vitest";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { observeWebSessionInputSchema } from "../../../src/domain/browserSession.js";
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
describeBrowser("CdpBrowserProvider navigation timeline", () => {
it("accepts caller-selected windows and rejects the removed event-count option", () => {
const accepted = observeWebSessionInputSchema.safeParse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: ["https://app.example.test"],
target_id: "page-1",
observation_ms: 120_000,
});
expect(accepted.success).toBe(true);
expect(
observeWebSessionInputSchema.safeParse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: ["https://app.example.test"],
target_id: "page-1",
max_timeline_events: 1,
}).success,
).toBe(false);
});
it("returns every event beyond the former default collection cap", async () => {
const additionalEvents = 2_001;
const browser = await startFakeCdpBrowser({
pageScopedVersionWebSocket: true,
omitTargetWebSocket: true,
sessionTimeline: "same_origin",
sessionTimelineEventCount: additionalEvents,
});
trackBrowser(browser);
const result = await new CdpBrowserProvider().observeSession(
observeWebSessionInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 1,
}),
);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.timeline).toHaveLength(additionalEvents + 6);
expect(result.value.completeness.truncated_sections).not.toContain(
"timeline",
);
});
});
@@ -96,4 +96,49 @@ describe("safe CDP response metadata", () => {
},
]);
});
it("retains every parsed header, CSP directive, link, relation, and policy feature", () => {
const csp = Array.from(
{ length: 105 },
(_, index) => `x-${String(index)} 'self'`,
).join("; ");
const links = Array.from(
{ length: 105 },
(_, index) => `</${String(index)}>; rel="mcp service-desc"`,
).join(", ");
const permissions = Array.from(
{ length: 205 },
(_, index) => `feature-${String(index)}=()`,
).join(", ");
const headers = Object.fromEntries(
Array.from({ length: 501 }, (_, index) => [
`x-extra-${String(index)}`,
"ok",
]),
);
const captured = safeResponseMetadata(
"request-1",
`${origin}/api`,
{
mimeType: "application/json",
headers: {
...headers,
"Content-Security-Policy": csp,
Link: links,
"Permissions-Policy": permissions,
"X-Model-Context": "present-after-many-headers",
},
},
new Set([origin]),
);
expect(captured.response.csp.directives).toHaveLength(105);
expect(captured.response.links).toHaveLength(105);
expect(captured.response.policies.permissions_policy_features).toHaveLength(
205,
);
expect(captured.agentHints).toContainEqual(
expect.objectContaining({ declaration: "x-model-context" }),
);
});
});
@@ -63,8 +63,6 @@ describe("web source-map fetching and validation", () => {
status: "included",
requested: 1,
processed: 1,
dropped: 0,
dropped_script_keys: [],
items: [
{
status: "included",
@@ -96,44 +94,6 @@ describe("web source-map fetching and validation", () => {
expectInvalidIncludedSourceMaps(result);
});
it("validates sectioned maps and reports bounded mapping truncation", async () => {
const regular = {
version: 3,
names: [],
sources: ["a.js"],
sourcesContent: ["export const a = 1"],
mappings: "AAAA;AACA",
};
const result = await fetchWebSourceMaps(
[request],
input({ analysis_limits: { max_source_map_mappings: 1 } }),
undefined,
{
fetch: () =>
Promise.resolve(
new Response(
JSON.stringify({
version: 3,
sections: [{ offset: { line: 0, column: 0 }, map: regular }],
}),
{ status: 200 },
),
),
},
);
expect(result).toMatchObject({
status: "truncated",
items: [
{
status: "truncated",
mappings: [expect.any(Object)],
limitation: expect.stringContaining("truncated from 2 to 1"),
},
],
});
});
it("reauthorizes every redirect and never contacts a disallowed origin", async () => {
const calls: string[] = [];
const result = await fetchWebSourceMaps([request], input(), undefined, {
@@ -159,101 +119,108 @@ describe("web source-map fetching and validation", () => {
});
});
it("distinguishes invalid JSON from declared or streamed byte truncation", async () => {
for (const response of [
new Response("not-json", { status: 200 }),
new Response("{}", {
status: 200,
headers: { "content-length": "999999" },
}),
]) {
const result = await fetchWebSourceMaps(
[request],
input({ analysis_limits: { max_source_map_bytes: 100 } }),
undefined,
{ fetch: () => Promise.resolve(response) },
);
expect(result.items[0]?.status).toBe(
response.headers.has("content-length") ? "truncated" : "invalid",
);
}
it("follows an approved redirect chain without an arbitrary hop ceiling", async () => {
const calls: string[] = [];
const result = await fetchWebSourceMaps([request], input(), undefined, {
fetch: (url) => {
const current = String(url);
calls.push(current);
const hop = Number(new URL(current).searchParams.get("hop") ?? "0");
return Promise.resolve(
hop < 7
? new Response(null, {
status: 302,
headers: {
location: `${origin}/assets/app.js.map?hop=${String(hop + 1)}`,
},
})
: validMapResponse(),
);
},
});
expect(calls).toHaveLength(8);
expect(result.items[0]?.status).toBe("included");
});
it("reports malformed source-map JSON as invalid", async () => {
const result = await fetchWebSourceMaps([request], input(), undefined, {
fetch: () => Promise.resolve(new Response("not-json", { status: 200 })),
});
expect(result.items[0]?.status).toBe("invalid");
});
});
describe("web source-map aggregate limits", () => {
it("bounds aggregate map count and reports omitted requests", async () => {
const calls: string[] = [];
const requests = [0, 1, 2].map((index) => ({
...request,
scriptKey: `scr_${String(index + 1).repeat(64)}`,
fetchUrl: `${origin}/assets/${String(index)}.js.map`,
}));
const result = await fetchWebSourceMaps(
requests,
input({ analysis_limits: { max_source_maps: 1 } }),
undefined,
{
fetch: (url) => {
calls.push(String(url));
return Promise.resolve(validMapResponse());
},
},
);
expect(calls).toEqual([requests[0]?.fetchUrl]);
expect(result).toMatchObject({
status: "truncated",
requested: 3,
processed: 1,
dropped: 2,
dropped_script_keys: [requests[1]?.scriptKey, requests[2]?.scriptKey],
describe("web source-map collection", () => {
it("retains every mapping from a sectioned source map", async () => {
const segmentCount = 10_001;
const regular = {
version: 3,
names: [],
sources: ["a.js"],
sourcesContent: ["export const a = 1"],
mappings: Array.from({ length: segmentCount }, () => "AAAA").join(","),
};
const result = await fetchWebSourceMaps([request], input(), undefined, {
fetch: () =>
Promise.resolve(
new Response(
JSON.stringify({
version: 3,
sections: [{ offset: { line: 0, column: 0 }, map: regular }],
}),
{ status: 200 },
),
),
});
expect(result.status).toBe("included");
expect(result.items[0]?.status).toBe("included");
expect(result.items[0]?.mappings).toHaveLength(segmentCount);
});
it("stops after exhausting the aggregate response-byte budget", async () => {
const requests = [0, 1, 2].map((index) => ({
it("fetches and returns every requested map inline", async () => {
const calls: string[] = [];
const requests = Array.from({ length: 101 }, (_, index) => ({
...request,
scriptKey: `scr_${String(index + 1).repeat(64)}`,
scriptKey: `scr_${String(index + 1).padStart(64, "0")}`,
fetchUrl: `${origin}/assets/${String(index)}.js.map`,
}));
const calls: string[] = [];
const result = await fetchWebSourceMaps(
requests,
input({
analysis_limits: {
max_source_map_bytes: 128,
max_total_source_map_bytes: 128,
},
}),
undefined,
{
fetch: (url) => {
calls.push(String(url));
return Promise.resolve(validMapResponse());
},
const result = await fetchWebSourceMaps(requests, input(), undefined, {
fetch: (url) => {
calls.push(String(url));
return Promise.resolve(validMapResponse());
},
);
expect(calls).toHaveLength(2);
expect(result).toMatchObject({
status: "truncated",
requested: 3,
processed: 2,
dropped: 1,
dropped_script_keys: [requests[2]?.scriptKey],
items: [{ status: "included" }, { status: "truncated" }],
});
expect(calls).toHaveLength(requests.length);
expect(result).toMatchObject({
status: "included",
requested: requests.length,
processed: requests.length,
});
expect(result.items).toHaveLength(requests.length);
});
it("does not accept caller overrides for provider source-map limits", () => {
const parsed = analyzeWebBundleInputSchema.safeParse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
target_id: "page-1",
analysis_limits: { max_source_maps: 0 },
it("includes source-map text above the former per-map byte budget", async () => {
const content = "x".repeat(8 * 1_024 * 1_024 + 1);
const map = JSON.stringify({
version: 3,
names: [],
sources: ["large.ts"],
sourcesContent: [content],
mappings: "AAAA",
});
const result = await fetchWebSourceMaps([request], input(), undefined, {
fetch: () => Promise.resolve(new Response(map, { status: 200 })),
});
expect(parsed.success).toBe(false);
expect(result.status).toBe("included");
expect(result.items[0]?.status).toBe("included");
if (result.items[0]?.status !== "included") throw new Error("not included");
expect(result.items[0].original_sources[0]?.artifact?.bytes).toBe(
Buffer.byteLength(content),
);
});
});
@@ -270,21 +237,11 @@ const validMapResponse = () =>
);
const input = (overrides: Record<string, unknown> = {}) => {
const { analysis_limits: internalLimitOverrides, ...callerOverrides } =
overrides;
const parsed = analyzeWebBundleInputSchema.parse({
return analyzeWebBundleInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
target_id: "page-1",
fetch_source_maps: true,
...callerOverrides,
...overrides,
});
const limits = {
...parsed.analysis_limits,
...(internalLimitOverrides as Record<string, number> | undefined),
};
return {
...parsed,
analysis_limits: limits,
};
};
@@ -232,7 +232,7 @@ describe("browser scenario MCP tool", () => {
"evidence_id",
);
expect(session.evidenceById(String(evidenceId))).toMatchObject({
predicate_type: "rea.browser-scenario-capture/v1",
predicate_type: "rea.browser-scenario-capture",
});
const captureResult = Reflect.get(
captured.structuredContent ?? {},
+1 -1
View File
@@ -273,7 +273,7 @@ it("exposes active Electron scenarios through the separately granted MCP boundar
"evidence_id",
);
expect(session.evidenceById(String(evidenceId))).toMatchObject({
predicate_type: "rea.electron-active-scenario/v1",
predicate_type: "rea.electron-active-scenario",
parameters: {
args: ["--token", "<redacted>"],
actions: [{ step_id: "submit", kind: "click" }],
+24 -4
View File
@@ -23,6 +23,18 @@ const emitWebMcpEvents = (
options: FakeOptions,
): void => {
if (command.method === "WebMCP.enable" && options.webMcpTools === true) {
const inputSchemaProperties =
options.webMcpSchemaPropertyCount === undefined
? {
orderId: { type: "string", example: "schema-secret" },
includeItems: { type: "boolean", default: true },
}
: Object.fromEntries(
Array.from(
{ length: options.webMcpSchemaPropertyCount },
(_value, index) => [`field_${String(index)}`, { type: "string" }],
),
);
event(socket, "WebMCP.toolsAdded", command.sessionId, {
tools: [
{
@@ -32,10 +44,7 @@ const emitWebMcpEvents = (
backendNodeId: 42,
inputSchema: {
type: "object",
properties: {
orderId: { type: "string", example: "schema-secret" },
includeItems: { type: "boolean", default: true },
},
properties: inputSchemaProperties,
required: ["orderId"],
},
annotations: {
@@ -170,6 +179,17 @@ const emitSessionTimeline = (
name: "networkIdle",
timestamp: 15,
});
for (
let index = 0;
index < (options.sessionTimelineEventCount ?? 0);
index += 1
)
event(socket, "Page.lifecycleEvent", command.sessionId, {
frameId: "frame-main",
loaderId: "loader-reload",
name: `lifecycle-${String(index)}`,
timestamp: 16 + index,
});
if (options.sessionTimeline === "target_detached")
event(socket, "Target.detachedFromTarget", undefined, {
sessionId: command.sessionId,
+7 -3
View File
@@ -43,7 +43,7 @@ export const resultFor = (
case "CacheStorage.requestEntries":
return cacheEntriesResult(port);
case "CacheStorage.requestCachedResponse":
return cachedResponseResult();
return cachedResponseResult(options);
default:
return {};
}
@@ -190,8 +190,12 @@ const cacheEntriesResult = (port: number) => ({
returnCount: 1,
});
const cachedResponseResult = () => ({
response: { body: Buffer.from("cache-body-secret").toString("base64") },
const cachedResponseResult = (options: FakeOptions) => ({
response: {
body: Buffer.from(
options.cachedResponseBody ?? "cache-body-secret",
).toString("base64"),
},
});
export const versionTargetId = (options: FakeOptions): string =>
+3
View File
@@ -53,11 +53,14 @@ export interface FakeOptions {
| "same_origin"
| "outside_policy"
| "target_detached";
readonly sessionTimelineEventCount?: number;
readonly closeAfterMethod?: string;
readonly sensitiveShapes?: boolean;
readonly cachedResponseBody?: string;
readonly invalidResponseBodyBase64?: boolean;
readonly webMcpTools?: boolean;
readonly webMcpFrameCount?: number;
readonly webMcpSchemaPropertyCount?: number;
readonly webMcpChildLeavesScope?: boolean;
readonly electronFileUrl?: string;
readonly duplicateElectronInventory?: boolean;