feat: add web and Electron reverse-engineering workflows

This commit is contained in:
N0zoM1z0
2026-07-14 20:24:12 +09:00
committed by N0zoM1z0
parent c2e64a42c8
commit be76f8090b
106 changed files with 11893 additions and 404 deletions
+145 -3
View File
@@ -10,7 +10,7 @@ import {
const execute = promisify(execFile);
const browsers: FakeCdpBrowser[] = [];
const INTEGRATION_TEST_TIMEOUT_MS = 20_000;
const INTEGRATION_TEST_TIMEOUT_MS = 40_000;
afterEach(async () => {
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
@@ -20,7 +20,11 @@ describe("browser CLI parity", () => {
it(
"returns the same Evidence v2 discovery and inspection contracts",
async () => {
const browser = await startFakeCdpBrowser();
const browser = await startFakeCdpBrowser({
sessionTimeline: "same_origin",
webMcpTools: true,
sensitiveShapes: true,
});
browsers.push(browser);
const environment = {
...process.env,
@@ -49,6 +53,12 @@ describe("browser CLI parity", () => {
"--approved",
"--observation-ms",
"0",
"--include-console-text",
"--console-text-approved",
"--include-json-body-shapes",
"--json-body-schema-approved",
"--include-websocket-shapes",
"--websocket-shape-approved",
"--json",
],
environment,
@@ -58,9 +68,122 @@ describe("browser CLI parity", () => {
provider: { id: "rea-cdp-browser" },
normalized_result: {
target: { target_id: "allowed-page" },
network: { prior_activity_available: false },
network: {
prior_activity_available: false,
requests: [
expect.objectContaining({
body_shapes: expect.objectContaining({ status: "included" }),
}),
],
},
},
});
const inspection = normalizedResult(inspected);
const compared = await runCli(
[
"compare-web-captures",
JSON.stringify({ inspection }),
JSON.stringify({ inspection }),
"--json",
],
environment,
);
expect(compared).toMatchObject({
operation: "compare_web_captures",
normalized_result: {
overall_status: "unknown",
dimensions: {
network: { status: "unknown", total_changes: 0 },
},
},
});
const analyzed = await runCli(
[
"analyze-web-bundle",
browser.endpoint,
"allowed-page",
"--approved",
"--source-capture-approved",
"--observation-ms",
"0",
"--json",
],
environment,
);
expect(analyzed).toMatchObject({
operation: "analyze_web_bundle",
normalized_result: {
capture: { scripts_analyzed: 1 },
observations: { source_maps: { status: "not_requested" } },
},
});
const observedSession = await runCli(
[
"observe-web-session",
browser.endpoint,
"allowed-page",
"--approved",
"--observation-ms",
"5",
"--json",
],
environment,
);
expect(observedSession).toMatchObject({
operation: "observe_web_session",
normalized_result: {
window: { end_reason: "window_elapsed" },
timeline: expect.arrayContaining([
expect.objectContaining({ type: "same_origin_reload" }),
]),
},
});
const webMcp = await runCli(
[
"discover-webmcp-tools",
browser.endpoint,
"allowed-page",
"--approved",
"--observation-ms",
"0",
"--json",
],
environment,
);
expect(webMcp).toMatchObject({
operation: "discover_webmcp_tools",
normalized_result: {
tools: {
items: [expect.objectContaining({ name: "search_orders" })],
},
},
});
const screenshot = await runCli(
[
"capture-web-screenshot",
browser.endpoint,
"allowed-page",
"--approved",
"--screenshot-approved",
"--json",
],
environment,
);
const artifact = screenshotArtifact(screenshot);
expect(artifact).toMatchObject({ media_type: "image/png", bytes: 70 });
const visual = await runCli(
[
"compare-web-screenshots",
JSON.stringify(artifact),
JSON.stringify(artifact),
"--json",
],
environment,
);
expect(visual).toMatchObject({
operation: "compare_web_screenshots",
normalized_result: { status: "identical", changed_pixels: 0 },
});
const policy = await runCli(
[
"policy",
@@ -137,3 +260,22 @@ const runCli = async (
throw cause;
}
};
const screenshotArtifact = (value: unknown): Record<string, unknown> => {
if (
!isRecord(value) ||
!isRecord(value.normalized_result) ||
!isRecord(value.normalized_result.artifact)
)
throw new TypeError("Missing CLI screenshot artifact");
return value.normalized_result.artifact;
};
const normalizedResult = (value: unknown): Record<string, unknown> => {
if (!isRecord(value) || !isRecord(value.normalized_result))
throw new TypeError("Missing CLI normalized result");
return value.normalized_result;
};
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
+149 -5
View File
@@ -27,14 +27,29 @@ describe("browser MCP tools", () => {
it(
"exposes CLI-equivalent Evidence v2 and session resources",
async () => {
const browser = await startFakeCdpBrowser();
const browser = await startFakeCdpBrowser({
sessionTimeline: "same_origin",
webMcpTools: true,
sensitiveShapes: true,
});
browsers.push(browser);
const connected = await connectBrowser(browser);
const tools = await connected.client.listTools();
expect(tools.tools).toHaveLength(70);
expect(tools.tools).toHaveLength(78);
expect(tools.tools.map(({ name }) => name)).toEqual(
expect.arrayContaining(["list_browser_targets", "inspect_web_page"]),
expect.arrayContaining([
"list_browser_targets",
"inspect_web_page",
"analyze_web_bundle",
"observe_web_session",
"discover_webmcp_tools",
"compare_web_captures",
"capture_web_screenshot",
"compare_web_screenshots",
"list_electron_targets",
"inspect_electron_page",
]),
);
const status = await connected.client.callTool({
name: "binary_session",
@@ -65,7 +80,7 @@ describe("browser MCP tools", () => {
authority: "external-service",
confidence: "observed",
subject: null,
provider: { id: "rea-cdp-browser", version: "1" },
provider: { id: "rea-cdp-browser", version: "2" },
normalized_result: {
targets: { items: [{ target_id: "allowed-page" }] },
},
@@ -78,6 +93,12 @@ describe("browser MCP tools", () => {
target_id: "allowed-page",
approved: true,
observation_ms: 0,
include_console_text: true,
console_text_approved: true,
include_json_body_shapes: true,
json_body_schema_approved: true,
include_websocket_shapes: true,
websocket_shape_approved: true,
},
});
expect(inspected.isError).not.toBe(true);
@@ -85,10 +106,112 @@ describe("browser MCP tools", () => {
operation: "inspect_web_page",
normalized_result: {
target: { target_id: "allowed-page" },
network: { prior_activity_available: false },
console: { prior_activity_available: false },
network: {
prior_activity_available: false,
requests: [
expect.objectContaining({
body_shapes: expect.objectContaining({ status: "included" }),
}),
],
},
},
});
const analyzed = await connected.client.callTool({
name: "analyze_web_bundle",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
source_capture_approved: true,
observation_ms: 0,
},
});
expect(analyzed.isError).not.toBe(true);
expect(analyzed.structuredContent).toMatchObject({
operation: "analyze_web_bundle",
normalized_result: {
capture: { scripts_analyzed: 1 },
observations: { source_maps: { status: "not_requested" } },
},
});
const observedSession = await connected.client.callTool({
name: "observe_web_session",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 5,
},
});
expect(observedSession.isError).not.toBe(true);
expect(observedSession.structuredContent).toMatchObject({
operation: "observe_web_session",
normalized_result: {
window: { end_reason: "window_elapsed" },
timeline: expect.arrayContaining([
expect.objectContaining({ type: "same_origin_reload" }),
]),
},
});
const webMcp = await connected.client.callTool({
name: "discover_webmcp_tools",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
},
});
expect(webMcp.isError).not.toBe(true);
expect(webMcp.structuredContent).toMatchObject({
operation: "discover_webmcp_tools",
normalized_result: {
tools: {
items: [expect.objectContaining({ name: "search_orders" })],
},
},
});
const capture = normalizedResultOf(inspected.structuredContent);
const compared = await connected.client.callTool({
name: "compare_web_captures",
arguments: {
before: { inspection: capture },
after: { inspection: capture },
},
});
expect(compared.isError).not.toBe(true);
expect(compared.structuredContent).toMatchObject({
operation: "compare_web_captures",
normalized_result: { overall_status: "unknown" },
});
const screenshot = await connected.client.callTool({
name: "capture_web_screenshot",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
screenshot_approved: true,
},
});
expect(screenshot.isError).not.toBe(true);
const screenshotArtifact = artifactOf(screenshot.structuredContent);
const visual = await connected.client.callTool({
name: "compare_web_screenshots",
arguments: {
before: screenshotArtifact,
after: screenshotArtifact,
},
});
expect(visual.isError).not.toBe(true);
expect(visual.structuredContent).toMatchObject({
operation: "compare_web_screenshots",
normalized_result: { status: "identical", changed_pixels: 0 },
});
const evidenceId = evidenceIdOf(inspected.structuredContent);
const evidence = await connected.client.readResource({
uri: `rea://evidence/${evidenceId}`,
@@ -168,3 +291,24 @@ const evidenceIdOf = (value: unknown): string => {
throw new TypeError("Missing browser evidence ID");
return value.evidence_id;
};
const normalizedResultOf = (value: unknown): unknown => {
if (
typeof value !== "object" ||
value === null ||
!("normalized_result" in value)
)
throw new TypeError("Missing normalized browser result");
return value.normalized_result;
};
const artifactOf = (value: unknown): unknown => {
const normalized = normalizedResultOf(value);
if (
typeof normalized !== "object" ||
normalized === null ||
!("artifact" in normalized)
)
throw new TypeError("Missing screenshot artifact");
return normalized.artifact;
};
+53
View File
@@ -7,6 +7,7 @@ import {
listBrowserTargetsInputSchema,
sanitizeBrowserUrl,
} from "../src/domain/browserObservation.js";
import { captureWebScreenshotInputSchema } from "../src/domain/webScreenshot.js";
describe("browser observation contracts", () => {
it("normalizes exact HTTP origins without accepting broader URL scopes", () => {
@@ -66,12 +67,21 @@ describe("browser observation contracts", () => {
}),
).toMatchObject({
observation_ms: 500,
include_accessibility_text: false,
include_console_text: false,
console_text_approved: false,
include_json_body_shapes: false,
json_body_schema_approved: false,
include_websocket_shapes: false,
websocket_shape_approved: false,
include_script_sources: false,
include_storage_keys: false,
limits: {
max_frames: 200,
max_dom_nodes: 2_000,
max_ax_nodes: 2_000,
max_ax_text_field_bytes: 1_024,
max_total_ax_text_bytes: 65_536,
max_scripts: 200,
max_resources: 2_000,
max_workers: 500,
@@ -80,11 +90,54 @@ describe("browser observation contracts", () => {
max_total_script_source_bytes: 4_194_304,
max_network_events: 1_000,
max_console_events: 200,
max_console_text_field_bytes: 1_024,
max_total_console_text_bytes: 65_536,
max_json_body_bytes: 1_048_576,
max_total_json_body_bytes: 4_194_304,
max_json_shape_nodes: 5_000,
max_json_shape_depth: 20,
max_websocket_events: 500,
max_websocket_shape_bytes: 65_536,
max_total_websocket_shape_bytes: 1_048_576,
},
});
});
it("requires independent approval for each sensitive capture surface", () => {
const base = {
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: ["https://app.example.test"],
target_id: "page-1",
approved: true,
};
for (const input of [
{ include_console_text: true },
{ include_json_body_shapes: true },
{ include_websocket_shapes: true },
])
expect(
inspectWebPageInputSchema.safeParse({ ...base, ...input }).success,
).toBe(false);
});
it("requires an independent literal approval for screenshot pixels", () => {
const input = {
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: ["https://app.example.test"],
target_id: "page-1",
approved: true,
};
expect(captureWebScreenshotInputSchema.safeParse(input).success).toBe(
false,
);
expect(
captureWebScreenshotInputSchema.safeParse({
...input,
screenshot_approved: true,
}).success,
).toBe(true);
});
it("removes credentials, query values, and fragments from observed URLs", () => {
expect(
sanitizeBrowserUrl(
+670 -5
View File
@@ -6,6 +6,10 @@ import {
listBrowserTargetsInputSchema,
webPageInspectionSchema,
} from "../src/domain/browserObservation.js";
import { analyzeWebBundleInputSchema } from "../src/domain/webBundleAnalysis.js";
import { observeWebSessionInputSchema } from "../src/domain/browserSession.js";
import { discoverWebMcpToolsInputSchema } from "../src/domain/webMcpDiscovery.js";
import { captureWebScreenshotInputSchema } from "../src/domain/webScreenshot.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
@@ -72,32 +76,92 @@ describe("CdpBrowserProvider", () => {
expect(() => webPageInspectionSchema.parse(result.value)).not.toThrow();
expect(result.value.frames).toHaveLength(1);
expect(result.value.dom.nodes).toHaveLength(2);
expect(result.value.dom.nodes[1]?.attribute_names).toEqual(["token"]);
expect(result.value.accessibility.nodes[0]?.name).toBe("Submit report");
expect(result.value.dom.nodes[1]?.attribute_names).toEqual([
"token",
"href",
"rel",
]);
expect(result.value.accessibility).toMatchObject({
text_capture: {
status: "not_approved",
retained_bytes: 0,
},
nodes: [expect.objectContaining({ name: null, description: null })],
});
expect(result.value.scripts.items).toHaveLength(1);
expect(result.value.scripts.items[0]?.script_id).toBe("script-allowed");
expect(result.value.scripts.items[0]?.script_key).toMatch(
/^scr_[a-f0-9]{64}$/u,
);
expect(result.value.scripts.items[0]?.resource_reconciliation).toEqual({
status: "exact",
resource_key: result.value.resources[0]?.resource_key,
});
expect(result.value.scripts.items[0]?.source).toEqual({
included: false,
reason: "source capture was not approved",
});
expect(result.value.resources).toHaveLength(1);
expect(result.value.network.requests).toHaveLength(1);
expect(result.value.network.requests[0]?.initiator).toEqual({
type: "script",
url: `${browser.allowedOrigin}/app.js?caller=%5BREDACTED%5D`,
line: 3,
column: 5,
});
expect(result.value.network.websocket_events).toEqual([
{
request_id: "websocket-1",
direction: "sent",
opcode: 1,
payload_bytes: Buffer.byteLength("websocket-secret"),
payload_shape: null,
},
{
request_id: "websocket-1",
direction: "received",
opcode: 2,
payload_bytes: 3,
payload_shape: null,
},
]);
expect(result.value.console.events[0]?.argument_types).toEqual(["string"]);
expect(result.value.workers).toHaveLength(1);
expect(result.value.metadata).toMatchObject({
headers_allowlisted: true,
responses: [
{
content_length: 321,
content_encoding: "br",
csp: { nonce_count: 1, hash_count: 1 },
policies: {
coop: "same-origin",
coep: "require-corp",
permissions_policy_features: ["camera", "geolocation"],
},
},
],
dom_urls: [
{
attribute: "href",
url: `${browser.allowedOrigin}/agent?token=%5BREDACTED%5D`,
destination_scope: "approved",
},
],
agent_hints: expect.arrayContaining([
expect.objectContaining({
mechanism: "link_rel",
declaration: "mcp service-desc",
}),
expect.objectContaining({
mechanism: "dom_link_rel",
declaration: "mcp",
}),
expect.objectContaining({
mechanism: "response_header",
declaration: "x-model-context",
}),
]),
});
expect(result.value.storage).toEqual(
expect.objectContaining({
local_storage_keys: ["public-key"],
@@ -121,6 +185,7 @@ describe("CdpBrowserProvider", () => {
"request-secret",
"request-body-secret",
"response-secret",
"response-body-secret",
"websocket-secret",
"websocket-url-secret",
"console-secret",
@@ -128,6 +193,11 @@ describe("CdpBrowserProvider", () => {
"unknown-console-value-secret",
"storage-secret",
"secret-id",
"dom-url-secret",
"link-secret",
"csp-secret",
"hash-secret",
"header-secret",
])
expect(serialized).not.toContain(secret);
const methods = browser.commands.map((command) => command.method);
@@ -135,6 +205,218 @@ describe("CdpBrowserProvider", () => {
expect(methods).not.toContain("Browser.close");
expect(methods).not.toContain("Target.closeTarget");
expect(methods).not.toContain("Runtime.evaluate");
expect(methods).not.toContain("Network.getResponseBody");
});
it("captures only approved redacted console text and value-free payload shapes", async () => {
const browser = await startFakeCdpBrowser({
sensitiveShapes: true,
binaryWebSocketEvent: true,
});
browsers.push(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
include_console_text: true,
console_text_approved: true,
include_json_body_shapes: true,
json_body_schema_approved: true,
include_websocket_shapes: true,
websocket_shape_approved: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value.console.events[0]?.text_capture).toEqual({
status: "included",
values: [
{ argument_index: 0, type: "string", text: "authorization=[REDACTED]" },
{ argument_index: 1, type: "number", text: "42" },
],
retained_bytes: 26,
truncated_values: 0,
});
expect(result.value.network.requests[0]?.body_shapes).toMatchObject({
status: "included",
request: {
root_type: "object",
properties: expect.arrayContaining([
expect.objectContaining({ path: "/token", types: ["string"] }),
expect.objectContaining({
path: "/filters/active",
types: ["boolean"],
}),
]),
},
response: {
root_type: "object",
properties: expect.arrayContaining([
expect.objectContaining({
path: "/result/token",
types: ["string"],
}),
expect.objectContaining({ path: "/items/*/id", types: ["number"] }),
]),
},
});
expect(result.value.network.websocket_events).toEqual([
expect.objectContaining({
opcode: 1,
payload_shape: expect.objectContaining({
format: "json",
json_shape: expect.objectContaining({
properties: expect.arrayContaining([
expect.objectContaining({ path: "/token", types: ["string"] }),
]),
}),
}),
}),
expect.objectContaining({
opcode: 2,
payload_shape: {
format: "binary",
json_shape: null,
truncated: false,
},
}),
]);
const serialized = JSON.stringify(result.value);
for (const secret of [
"request-body-secret",
"response-body-secret",
"websocket-secret",
"console-secret",
"object-secret",
])
expect(serialized).not.toContain(secret);
const methods = browser.commands.map(({ method }) => method);
expect(methods).toContain("Network.getResponseBody");
expect(methods).not.toContain("Runtime.getProperties");
expect(methods).not.toContain("Runtime.callFunctionOn");
});
it("reports independent sensitive-capture truncation at aggregate byte limits", async () => {
const browser = await startFakeCdpBrowser({ sensitiveShapes: true });
browsers.push(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
include_console_text: true,
console_text_approved: true,
include_json_body_shapes: true,
json_body_schema_approved: true,
include_websocket_shapes: true,
websocket_shape_approved: true,
limits: {
max_console_text_field_bytes: 5,
max_total_console_text_bytes: 5,
max_json_body_bytes: 10,
max_total_json_body_bytes: 10,
max_websocket_shape_bytes: 5,
max_total_websocket_shape_bytes: 5,
},
}),
);
if (!result.ok) throw result.error;
expect(result.value.console.events[0]?.text_capture).toEqual({
status: "truncated",
values: [{ argument_index: 0, type: "string", text: "autho" }],
retained_bytes: 5,
truncated_values: 2,
});
expect(result.value.network.requests[0]?.body_shapes.status).toBe(
"truncated",
);
expect(result.value.network.websocket_events[0]?.payload_shape).toEqual({
format: "text",
json_shape: null,
truncated: true,
});
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 () => {
const browser = await startFakeCdpBrowser({
invalidResponseBodyBase64: true,
binaryWebSocketEvent: true,
invalidBinaryWebSocketEvent: true,
});
browsers.push(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
include_json_body_shapes: true,
json_body_schema_approved: true,
include_websocket_shapes: true,
websocket_shape_approved: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value.network.requests[0]?.body_shapes).toMatchObject({
status: "partial",
request: expect.any(Object),
response: null,
});
expect(result.value.network.websocket_events[1]).toMatchObject({
opcode: 2,
payload_bytes: 0,
payload_shape: { format: "binary", json_shape: null },
});
expect(result.value.completeness.unavailable_sections).toEqual(
expect.arrayContaining(["json_body_shapes", "websocket_frames"]),
);
});
it("captures bounded accessibility text only after independent approval", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
include_accessibility_text: true,
limits: {
max_ax_text_field_bytes: 6,
max_total_ax_text_bytes: 6,
},
}),
);
if (!result.ok) throw result.error;
expect(result.value.accessibility).toMatchObject({
text_capture: {
status: "truncated",
retained_bytes: 6,
truncated_fields: 2,
},
nodes: [expect.objectContaining({ name: "Submit" })],
});
expect(result.value.completeness.truncated_sections).toContain(
"accessibility",
);
});
it("drops network evidence when a request redirects outside the approved origin", async () => {
@@ -175,8 +457,11 @@ describe("CdpBrowserProvider", () => {
expect(result.value.scripts.items[0]?.source).toEqual(
expect.objectContaining({
included: true,
content: "export const observed = 'source-secret';",
bytes: 40,
artifact: expect.objectContaining({
text: "export const observed = 'source-secret';",
bytes: 40,
uri: expect.stringMatching(/^rea:\/\/web-content\/sha256\//u),
}),
}),
);
expect(browser.commands.map((command) => command.method)).toContain(
@@ -184,6 +469,380 @@ describe("CdpBrowserProvider", () => {
);
});
it("fetches and validates source maps only after separate approval", async () => {
const browser = await startFakeCdpBrowser({
sourceMapBody: JSON.stringify({
version: 3,
names: [],
sources: ["src/main.ts"],
sourcesContent: ["export const original = true;"],
mappings: "AAAA",
}),
});
browsers.push(browser);
const result = await new CdpBrowserProvider().analyzeBundle(
analyzeWebBundleInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
source_capture_approved: true,
observation_ms: 0,
fetch_source_maps: true,
source_map_fetch_approved: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value.observations.source_maps).toMatchObject({
status: "included",
items: [
{
status: "included",
original_sources: [
expect.objectContaining({
source: `${browser.allowedOrigin}/src/main.ts`,
}),
],
mappings: [expect.any(Object)],
},
],
});
const sourceMapRequest = browser.httpRequests.find(({ url }) =>
url.startsWith("/app.js.map"),
);
expect(sourceMapRequest).toEqual({
url: "/app.js.map?token=map-secret",
authorization: undefined,
cookie: undefined,
referer: undefined,
});
});
it("observes user-driven reload, SPA, redirect, failure, and lifecycle events", async () => {
const browser = await startFakeCdpBrowser({
sessionTimeline: "same_origin",
});
browsers.push(browser);
const result = await new CdpBrowserProvider().observeSession(
observeWebSessionInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 20,
}),
);
if (!result.ok) throw result.error;
expect(result.value.window.end_reason).toBe("window_elapsed");
expect(result.value.timeline.map(({ type }) => type)).toEqual([
"navigation_requested",
"same_origin_reload",
"same_document_navigation",
"redirect",
"load_failed",
"lifecycle",
]);
expect(result.value.timeline).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "same_document_navigation",
url: `${browser.allowedOrigin}/reloaded?token=%5BREDACTED%5D`,
}),
expect.objectContaining({
type: "load_failed",
detail: "net::ERR_CONNECTION_REFUSED",
}),
]),
);
expect(result.value.completeness.status).toBe("attach_limited");
expect(JSON.stringify(result.value)).not.toContain("session-secret");
expect(JSON.stringify(result.value)).not.toContain("redirect-secret");
expect(browser.commands.map(({ method }) => method)).toContain(
"Target.detachFromTarget",
);
});
it("discovers untrusted WebMCP declarations without registering or invoking them", async () => {
const browser = await startFakeCdpBrowser({ webMcpTools: true });
browsers.push(browser);
const result = await new CdpBrowserProvider().discoverWebMcpTools(
discoverWebMcpToolsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
status: "available",
tools: {
total: 1,
items: [
{
name: "search_orders",
description: "Search orders; authorization=[REDACTED]",
declaration_kind: "declarative",
owner_origin: browser.allowedOrigin,
annotations: {
read_only: true,
untrusted_content: true,
autosubmit: false,
},
trust: "page-declared-untrusted",
registration_source: {
url: `${browser.allowedOrigin}/app.js?token=%5BREDACTED%5D`,
line: 12,
column: 4,
},
},
],
},
});
const serialized = JSON.stringify(result.value);
for (const secret of [
"tool-secret",
"schema-secret",
"tool-source-secret",
"private-tool-secret",
])
expect(serialized).not.toContain(secret);
const methods = browser.commands.map(({ method }) => method);
expect(methods).toContain("WebMCP.enable");
expect(methods).not.toContain("WebMCP.invokeTool");
expect(methods).not.toContain("Runtime.evaluate");
});
it("reports WebMCP unavailable when the experimental domain is absent", async () => {
const browser = await startFakeCdpBrowser({
unsupportedMethods: ["WebMCP.enable"],
});
browsers.push(browser);
const result = await new CdpBrowserProvider().discoverWebMcpTools(
discoverWebMcpToolsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
expect(result.value.status).toBe("unavailable");
expect(result.value.tools.items).toEqual([]);
expect(result.value.completeness.unavailable_sections).toContain(
"webmcp_tools",
);
});
it("rejects WebMCP evidence when the page leaves its approved origin", async () => {
const browser = await startFakeCdpBrowser({
webMcpTools: true,
frameUrlAfterFirstRead: "https://private.example.test/tools",
});
browsers.push(browser);
const result = await new CdpBrowserProvider().discoverWebMcpTools(
discoverWebMcpToolsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
}),
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "BrowserObservationError",
operation: "discover_webmcp_tools",
reason: "target_not_allowed",
},
});
expect(browser.commands.map(({ method }) => method)).not.toContain(
"WebMCP.invokeTool",
);
});
it("bounds WebMCP registration replay and reports dropped declarations", async () => {
const browser = await startFakeCdpBrowser({
webMcpTools: true,
extraCollections: true,
});
browsers.push(browser);
const result = await new CdpBrowserProvider().discoverWebMcpTools(
discoverWebMcpToolsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
max_tools: 1,
}),
);
if (!result.ok) throw result.error;
expect(result.value.tools).toMatchObject({
total: 2,
items: [expect.any(Object)],
});
expect(result.value.completeness).toMatchObject({
status: "truncated",
dropped_events: { webmcp_tools: 1 },
});
});
it("removes WebMCP declarations after their child frame leaves scope", async () => {
const browser = await startFakeCdpBrowser({
webMcpTools: true,
extraCollections: true,
webMcpChildLeavesScope: true,
});
browsers.push(browser);
const result = await new CdpBrowserProvider().discoverWebMcpTools(
discoverWebMcpToolsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
const names = result.value.tools.items.map(({ name }) => name);
expect(names).toEqual(
expect.arrayContaining(["search_orders", "update_order"]),
);
expect(names).not.toEqual(
expect.arrayContaining(["child_tool", "escaped_child_tool"]),
);
expect(result.value.completeness.policy_filtered_sections).toContain(
"webmcp_tools",
);
expect(JSON.stringify(result.value)).not.toContain(
"cross-origin-child-secret",
);
});
it("captures an explicitly approved content-addressed viewport screenshot", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const result = await new CdpBrowserProvider().captureScreenshot(
captureWebScreenshotInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
screenshot_approved: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
viewport: { width: 1, height: 1 },
artifact: {
uri: expect.stringMatching(/^rea:\/\/web-screenshot\/sha256\//u),
bytes: 70,
media_type: "image/png",
},
});
expect(browser.commands.map(({ method }) => method)).toContain(
"Page.captureScreenshot",
);
});
it("discards screenshot pixels when the main frame navigates during capture", async () => {
const browser = await startFakeCdpBrowser({
navigateDuringScreenshotUrl: "https://private.example.test/screenshot",
});
browsers.push(browser);
const result = await new CdpBrowserProvider().captureScreenshot(
captureWebScreenshotInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
screenshot_approved: true,
}),
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "BrowserObservationError",
operation: "capture_web_screenshot",
reason: "target_not_allowed",
},
});
});
it("ends immediately when a redirect leaves policy without exposing its URL", async () => {
const browser = await startFakeCdpBrowser({
sessionTimeline: "outside_policy",
});
browsers.push(browser);
const result = await new CdpBrowserProvider().observeSession(
observeWebSessionInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 1_000,
}),
);
if (!result.ok) throw result.error;
expect(result.value.window.end_reason).toBe("target_left_scope");
expect(result.value.timeline.at(-1)).toMatchObject({
type: "redirect",
url: null,
destination_scope: "outside_policy",
});
expect(result.value.completeness).toMatchObject({
status: "policy_filtered",
policy_filtered_sections: ["timeline"],
excluded: [
{
section: "timeline",
reason: "out_of_target_scope",
count: 1,
},
],
});
expect(JSON.stringify(result.value)).not.toContain("private.example.test");
});
it("fails closed when the final session frame leaves policy without an event", async () => {
const browser = await startFakeCdpBrowser({
frameUrlAfterFirstRead: "https://private.example.test/final",
});
browsers.push(browser);
const result = await new CdpBrowserProvider().observeSession(
observeWebSessionInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 1,
}),
);
if (!result.ok) throw result.error;
expect(result.value.window.end_reason).toBe("target_left_scope");
expect(result.value.target.final_url).toBeNull();
expect(result.value.completeness).toMatchObject({
status: "policy_filtered",
policy_filtered_sections: ["timeline"],
});
expect(JSON.stringify(result.value)).not.toContain("private.example.test");
});
it("rejects missing and disallowed page targets before attaching", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
@@ -354,6 +1013,12 @@ describe("CdpBrowserProvider", () => {
);
if (!degraded.ok) throw degraded.error;
expect(degraded.value.accessibility.nodes).toEqual([]);
expect(degraded.value.accessibility.text_capture.status).toBe(
"unavailable",
);
expect(degraded.value.completeness.unavailable_sections).toContain(
"accessibility",
);
expect(degraded.value.limitations).toContain(
"Accessibility.getFullAXTree was unavailable from this browser target.",
);
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { CdpCaptureCompleteness } from "../src/browser/CdpCaptureCompleteness.js";
describe("CdpCaptureCompleteness", () => {
it("reports attach-window limitations without claiming a complete history", () => {
const capture = new CdpCaptureCompleteness([
"network_requests",
"console_events",
]);
expect(capture.snapshot()).toMatchObject({
status: "attach_limited",
conditions: ["attach_limited"],
attach_limited_sections: ["console_events", "network_requests"],
excluded: [],
dropped_events: { total: 0 },
});
});
it("aggregates sparse exclusions and applies explicit status precedence", () => {
const capture = new CdpCaptureCompleteness(["network_requests"]);
capture.exclude("scripts", "disallowed_origin");
capture.exclude("scripts", "disallowed_origin", 2);
capture.exclude("storage_keys", "not_approved", null);
capture.drop("console_events", 4);
expect(capture.snapshot()).toMatchObject({
status: "truncated",
conditions: ["attach_limited", "policy_filtered", "truncated"],
policy_filtered_sections: ["scripts", "storage_keys"],
truncated_sections: ["console_events"],
excluded: [
{ section: "scripts", reason: "disallowed_origin", count: 3 },
{ section: "storage_keys", reason: "not_approved", count: null },
],
dropped_events: { console_events: 4, total: 4 },
});
});
it("restores initial attach limitations when reused for a new capture", () => {
const capture = new CdpCaptureCompleteness(["websocket_frames"]);
capture.drop("scripts");
capture.exclude("resources", "provider_unavailable", null);
capture.reset();
expect(capture.snapshot()).toMatchObject({
status: "attach_limited",
attach_limited_sections: ["websocket_frames"],
unavailable_sections: [],
excluded: [],
dropped_events: { total: 0 },
});
});
});
+62
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
captureAccessibility,
captureDom,
captureFrames,
captureResources,
@@ -71,4 +72,65 @@ describe("CDP document capture", () => {
-1, 0, -1, 2,
]);
});
it("bounds approved accessibility text by UTF-8 bytes without splitting characters", () => {
const capture = captureAccessibility(
[
{
nodes: [
{
nodeId: "node-1",
role: { value: "button" },
name: { value: "😀a" },
description: { value: "éé" },
},
],
},
],
10,
{
includeText: true,
maximumFieldBytes: 4,
maximumTotalBytes: 7,
},
);
expect(capture.nodes[0]).toMatchObject({ name: "😀", description: "é" });
expect(capture.textCapture).toEqual({
status: "truncated",
retained_bytes: 6,
excluded_fields: 0,
truncated_fields: 2,
});
});
it("counts accessibility fields omitted without text approval", () => {
const capture = captureAccessibility(
[
{
nodes: [
{
nodeId: "node-1",
name: { value: "private name" },
description: { value: "private description" },
},
],
},
],
10,
{
includeText: false,
maximumFieldBytes: 1_024,
maximumTotalBytes: 64 * 1_024,
},
);
expect(capture.nodes[0]).toMatchObject({ name: null, description: null });
expect(capture.textCapture).toEqual({
status: "not_approved",
retained_bytes: 0,
excluded_fields: 2,
truncated_fields: 0,
});
});
});
+211
View File
@@ -0,0 +1,211 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { CdpElectronProvider } from "../src/browser/CdpElectronProvider.js";
import {
inspectElectronPageInputSchema,
listElectronTargetsInputSchema,
} from "../src/domain/electronObservation.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "./fixtures/fakeCdpBrowser.js";
describe("CdpElectronProvider", () => {
const browsers: FakeCdpBrowser[] = [];
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
browsers.splice(0).map(async (browser) => browser.close()),
);
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
it("lists and inspects only canonical file targets beneath approved roots", async () => {
const root = await electronFixture();
const index = join(root, "index.html");
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(index).href,
duplicateElectronInventory: true,
});
browsers.push(browser);
const provider = new CdpElectronProvider();
const listed = await provider.listTargets(
listElectronTargetsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
approved: true,
}),
);
if (!listed.ok) throw listed.error;
expect(listed.value.targets.items).toEqual([
expect.objectContaining({
target_id: "electron-page",
file_path: index,
}),
]);
expect(listed.value.excluded).toEqual({
outside_root: 0,
unsupported_url: 3,
non_page: 1,
});
const inspected = await provider.inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
approved: true,
observation_ms: 0,
}),
);
if (!inspected.ok) throw inspected.error;
expect(inspected.value.target.file_path).toBe(index);
expect(inspected.value.frames).toEqual([
expect.objectContaining({ file_path: index }),
]);
expect(inspected.value.dom).toMatchObject({ total_nodes: 2 });
expect(inspected.value.scripts).toMatchObject({
total: 1,
items: [
expect.objectContaining({
file_path: join(root, "app.js"),
source: {
included: false,
reason: "source capture was not approved",
},
}),
],
});
expect(inspected.value.resources).toEqual([
expect.objectContaining({ file_path: join(root, "app.js") }),
]);
const methods = browser.commands.map(({ method }) => method);
expect(methods).not.toContain("Runtime.evaluate");
expect(methods).not.toContain("Network.enable");
expect(methods).not.toContain("Debugger.getScriptSource");
expect(methods).toContain("Target.detachFromTarget");
const missing = await provider.inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "missing",
approved: true,
observation_ms: 0,
}),
);
expect(missing).toMatchObject({
ok: false,
error: {
_tag: "BrowserObservationError",
operation: "inspect_electron_page",
reason: "target_not_found",
},
});
});
it("captures Electron script source only after separate approval", async () => {
const root = await electronFixture();
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
});
browsers.push(browser);
const result = await new CdpElectronProvider().inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
approved: true,
observation_ms: 0,
include_script_sources: true,
source_capture_approved: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value.scripts.items[0]?.source).toMatchObject({
included: true,
artifact: { text: "export const observed = 'source-secret';" },
});
expect(browser.commands.map(({ method }) => method)).toContain(
"Debugger.getScriptSource",
);
});
it("rebases DOM parent indexes across allowed file documents", async () => {
const root = await electronFixture();
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
extraCollections: true,
});
browsers.push(browser);
const result = await new CdpElectronProvider().inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
approved: true,
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
expect(result.value.dom).toMatchObject({
total_nodes: 4,
nodes: [
{ index: 0, parent_index: -1 },
{ index: 1, parent_index: 0 },
{ index: 2, parent_index: -1 },
{ index: 3, parent_index: 2 },
],
});
});
it("rejects mixed Electron evidence when the main frame navigates", async () => {
const root = await electronFixture();
const page = join(root, "index.html");
const next = join(root, "next.html");
await writeFile(next, "<html>next</html>");
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(page).href,
navigateDuringCaptureUrl: pathToFileURL(next).href,
});
browsers.push(browser);
const result = await new CdpElectronProvider().inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
approved: true,
observation_ms: 0,
}),
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "BrowserObservationError",
operation: "inspect_electron_page",
reason: "target_changed",
},
});
});
const electronFixture = async (): Promise<string> => {
const root = await mkdtemp(join(tmpdir(), "rea-electron-provider-"));
temporary.push(root);
await writeFile(join(root, "index.html"), "<script src='app.js'></script>");
await writeFile(join(root, "app.js"), "export const app = true;");
await writeFile(join(root, "child.html"), "<div>child</div>");
return root;
};
});
+99
View File
@@ -0,0 +1,99 @@
import { describe, expect, it } from "vitest";
import { safeResponseMetadata } from "../src/browser/CdpSafeMetadata.js";
const origin = "https://app.example.test";
describe("safe CDP response metadata", () => {
it("retains only allowlisted header structure and redacted approved links", () => {
const captured = safeResponseMetadata(
"request-1",
`${origin}/api`,
{
mimeType: "application/json",
headers: {
Authorization: "Bearer credential-secret",
Cookie: "session=cookie-secret",
"Set-Cookie": "session=response-secret",
Link: `</agent?token=link-secret>; rel="mcp service-desc"; title="a,b", <https://private.example.test/x>; rel="mcp"`,
"Content-Security-Policy":
"default-src 'self'; script-src 'nonce-nonce-secret' 'sha256-hash-secret' https://private.example.test",
"Permissions-Policy":
"camera=(), geolocation=(self), invalid secret=()",
"X-Model-Context": "agent-header-secret",
},
},
new Set([origin]),
);
expect(captured.response).toMatchObject({
url: `${origin}/api`,
csp: {
nonce_count: 1,
hash_count: 1,
directives: expect.arrayContaining([
expect.objectContaining({
name: "script-src",
sources: expect.arrayContaining([
{ kind: "external_origin", value: null },
]),
}),
]),
},
links: [
{
href: `${origin}/agent?token=%5BREDACTED%5D`,
destination_scope: "approved",
rel: ["mcp", "service-desc"],
as: null,
type: null,
crossorigin: null,
},
expect.objectContaining({
href: null,
destination_scope: "outside_policy",
}),
],
policies: { permissions_policy_features: ["camera", "geolocation"] },
});
expect(captured.agentHints).toEqual(
expect.arrayContaining([
expect.objectContaining({ mechanism: "link_rel" }),
expect.objectContaining({
mechanism: "response_header",
declaration: "x-model-context",
}),
]),
);
const serialized = JSON.stringify(captured);
for (const secret of [
"credential-secret",
"cookie-secret",
"response-secret",
"link-secret",
"nonce-secret",
"hash-secret",
"agent-header-secret",
"private.example.test",
])
expect(serialized).not.toContain(secret);
});
it("reports well-known agent resources as untrusted observations", () => {
const captured = safeResponseMetadata(
"request-2",
`${origin}/.well-known/mcp?token=secret`,
{ headers: {} },
new Set([origin]),
);
expect(captured.agentHints).toEqual([
{
mechanism: "well_known_resource",
declaration: "/.well-known/mcp",
url: `${origin}/.well-known/mcp?token=%5BREDACTED%5D`,
trust: "page-declared-untrusted",
},
]);
});
});
+28
View File
@@ -29,9 +29,37 @@ describe("runtime configuration", () => {
expect(result.value.browserObservationEnabled).toBe(false);
expect(result.value.browserCdpEndpoints).toEqual([]);
expect(result.value.browserAllowedOrigins).toEqual([]);
expect(result.value.electronObservationEnabled).toBe(false);
expect(result.value.electronCdpEndpoints).toEqual([]);
expect(result.value.electronFileRoots).toEqual([]);
}
});
it("builds a separate Electron endpoint and file-root ceiling", () => {
const result = parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9223"]',
REA_ELECTRON_FILE_ROOTS_JSON: '["/tmp/electron-app"]',
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.permissionCeilings).toContainEqual({
capability: "electron_observe",
roots: ["/tmp/electron-app"],
executables: [],
environment_names: [],
origins: ["http://127.0.0.1:9223"],
network: "loopback",
mount: false,
});
});
it("rejects relative Electron file roots", () => {
expect(
parseConfig({ REA_ELECTRON_FILE_ROOTS_JSON: '["relative/app"]' }).ok,
).toBe(false);
});
it("parses database kind and loader arguments", () => {
expect(
parseConfig({
+8 -9
View File
@@ -9,6 +9,7 @@ import {
import { NATIVE_TOOL_CONTRACTS } from "../src/contracts/nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../src/contracts/artifactToolContracts.js";
import { BROWSER_TOOL_CONTRACTS } from "../src/contracts/browserToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "../src/contracts/electronToolContracts.js";
import {
enhancedOutputSchemas,
officialOutputSchemas,
@@ -36,8 +37,9 @@ describe("tool contract surface", () => {
...NATIVE_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...BROWSER_TOOL_CONTRACTS,
...ELECTRON_TOOL_CONTRACTS,
];
expect(contracts).toHaveLength(52);
expect(contracts).toHaveLength(60);
for (const contract of contracts) {
const inputSchema = z.toJSONSchema(contract.inputSchema, {
target: "draft-07",
@@ -49,12 +51,8 @@ describe("tool contract surface", () => {
});
expect(inputSchema.type).toBe("object");
expect(outputSchema.type).toBe("object");
expect(contract.annotations).toMatchObject({
idempotentHint: true,
});
expect(contract.annotations.openWorldHint).toBe(
contract.kind === "browser-provider",
);
expect(typeof contract.annotations.idempotentHint).toBe("boolean");
expect(typeof contract.annotations.openWorldHint).toBe("boolean");
expect(typeof contract.annotations.readOnlyHint).toBe("boolean");
expect(typeof contract.annotations.destructiveHint).toBe("boolean");
expect(contract.examples).toHaveLength(1);
@@ -140,16 +138,17 @@ describe("tool contract surface", () => {
}
});
it("publishes no unconstrained output-schema holes across all 70 tools", () => {
it("publishes no unconstrained output-schema holes across all 78 tools", () => {
const contracts = [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
...NATIVE_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...BROWSER_TOOL_CONTRACTS,
...ELECTRON_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
];
expect(contracts).toHaveLength(70);
expect(contracts).toHaveLength(78);
for (const contract of contracts) {
const schema = z.toJSONSchema(contract.outputSchema, {
target: "draft-07",
+108
View File
@@ -0,0 +1,108 @@
import { execFile } from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "./fixtures/fakeCdpBrowser.js";
const execute = promisify(execFile);
const INTEGRATION_TEST_TIMEOUT_MS = 20_000;
describe("Electron CLI parity", () => {
const browsers: FakeCdpBrowser[] = [];
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
browsers.splice(0).map(async (browser) => browser.close()),
);
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
it(
"returns the same root-confined Electron Evidence contracts",
async () => {
const root = await mkdtemp(join(tmpdir(), "rea-electron-cli-"));
temporary.push(root);
await writeFile(
join(root, "index.html"),
"<script src='app.js'></script>",
);
await writeFile(join(root, "app.js"), "export const app = true;");
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
});
browsers.push(browser);
const environment = {
...process.env,
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
};
const listed = await runCli(
["list-electron-targets", browser.endpoint, "--approved", "--json"],
environment,
);
expect(listed).toMatchObject({
operation: "list_electron_targets",
normalized_result: {
targets: { items: [{ target_id: "electron-page" }] },
},
});
const inspected = await runCli(
[
"inspect-electron-page",
browser.endpoint,
"electron-page",
"--approved",
"--observation-ms",
"0",
"--json",
],
environment,
);
expect(inspected).toMatchObject({
operation: "inspect_electron_page",
provider: { id: "rea-cdp-electron" },
normalized_result: {
target: { file_path: join(root, "index.html") },
},
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
});
const runCli = async (
arguments_: readonly string[],
environment: NodeJS.ProcessEnv,
): Promise<unknown> => {
try {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{ cwd: process.cwd(), env: environment, maxBuffer: 16 * 1_024 * 1_024 },
);
return JSON.parse(stdout);
} catch (cause: unknown) {
if (
typeof cause === "object" &&
cause !== null &&
"stdout" in cause &&
typeof cause.stdout === "string"
)
return JSON.parse(cause.stdout);
throw cause;
}
};
+57
View File
@@ -0,0 +1,57 @@
import { mkdtemp, mkdir, rm, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import {
authorizedElectronFile,
canonicalElectronRoots,
} from "../src/browser/ElectronFileScope.js";
describe("Electron file scope", () => {
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
it("accepts canonical files within a root and rejects escape forms", async () => {
const base = await mkdtemp(join(tmpdir(), "rea-electron-scope-"));
temporary.push(base);
const root = join(base, "root");
const outside = join(base, "outside");
await mkdir(root);
await mkdir(outside);
const allowed = join(root, "index.html");
const denied = join(outside, "secret.html");
await writeFile(allowed, "allowed");
await writeFile(denied, "denied");
await symlink(denied, join(root, "escape.html"));
const roots = await canonicalElectronRoots([root]);
expect(
await authorizedElectronFile(pathToFileURL(allowed).href, roots),
).toBe(allowed);
expect(
await authorizedElectronFile(pathToFileURL(denied).href, roots),
).toBeUndefined();
expect(
await authorizedElectronFile(
pathToFileURL(join(root, "escape.html")).href,
roots,
),
).toBeUndefined();
expect(
await authorizedElectronFile("file://server/share/index.html", roots),
).toBeUndefined();
expect(
await authorizedElectronFile("file:///tmp/root%2Findex.html", roots),
).toBeUndefined();
});
});
+131
View File
@@ -0,0 +1,131 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { pathToFileURL } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
import { BinarySession } from "../src/application/BinarySession.js";
import { loadConfiguredPermissionAuthority } from "../src/application/PermissionConfiguration.js";
import { CdpElectronProvider } from "../src/browser/CdpElectronProvider.js";
import { parseConfig } from "../src/config.js";
import { createServer } from "../src/server/createServer.js";
import { observed } from "./fixtures/analysisExecution.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "./fixtures/fakeCdpBrowser.js";
describe("Electron MCP tools", () => {
const browsers: FakeCdpBrowser[] = [];
const resources: Array<{ close(): Promise<unknown> }> = [];
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(resources.splice(0).map(async (item) => item.close()));
await Promise.all(
browsers.splice(0).map(async (browser) => browser.close()),
);
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
it("exposes root-confined Electron discovery and inspection as Evidence v2", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-electron-mcp-"));
temporary.push(root);
await writeFile(join(root, "index.html"), "<script src='app.js'></script>");
await writeFile(join(root, "app.js"), "export const app = true;");
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
});
browsers.push(browser);
const config = parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const session = new BinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
electronObservation: new CdpElectronProvider(),
permissionAuthority: authority.value,
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
electronObservationEnabled: true,
}),
});
const client = new Client({ name: "electron-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const listed = await client.callTool({
name: "list_electron_targets",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
approved: true,
},
});
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
operation: "list_electron_targets",
provider: { id: "rea-cdp-electron" },
normalized_result: {
targets: { items: [{ target_id: "electron-page" }] },
},
});
const inspected = await client.callTool({
name: "inspect_electron_page",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
approved: true,
observation_ms: 0,
},
});
expect(inspected.isError).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
operation: "inspect_electron_page",
normalized_result: {
target: { file_path: join(root, "index.html") },
scripts: {
items: [expect.objectContaining({ file_path: join(root, "app.js") })],
},
},
});
const outside = join(root, "..", `outside-${Date.now().toString(16)}`);
await mkdir(outside);
temporary.push(outside);
const commandsBeforeDenial = browser.commands.length;
const denied = await client.callTool({
name: "list_electron_targets",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_file_roots: [outside],
approved: true,
},
});
expect(denied.isError).toBe(true);
expect(denied.structuredContent).toMatchObject({
error: {
code: "permission_required",
details: { missing: { roots: [outside] } },
},
});
expect(browser.commands).toHaveLength(commandsBeforeDenial);
});
});
+9 -3
View File
@@ -4,7 +4,11 @@ import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../src/application/EnhancedTools.js";
import { ENHANCED_TOOL_CONTRACTS } from "../src/contracts/toolContracts.js";
import {
ENHANCED_TOOL_CONTRACTS,
SESSION_TOOL_CONTRACTS,
TOOL_CONTRACTS,
} from "../src/contracts/toolContracts.js";
import { AnalysisOutputError } from "../src/domain/errors.js";
import { jsonValueSchema, type JsonValue } from "../src/domain/jsonValue.js";
import { err } from "../src/domain/result.js";
@@ -180,10 +184,12 @@ const jsonResult = (result: CallToolResult): JsonValue => {
};
describe("enhanced MCP tools", () => {
it("lists the complete 33 plus 10 surface", async () => {
it("lists the complete target-open analysis surface", async () => {
const client = await connect();
const listed = await client.listTools();
expect(listed.tools).toHaveLength(52);
expect(listed.tools).toHaveLength(
TOOL_CONTRACTS.length - SESSION_TOOL_CONTRACTS.length,
);
expect(
listed.tools
.map(({ name }) => name)
+355 -29
View File
@@ -14,6 +14,12 @@ export interface FakeCdpBrowser {
readonly browserWebSocketUrl: string;
readonly allowedOrigin: string;
readonly commands: readonly FakeCdpCommand[];
readonly httpRequests: readonly {
readonly url: string;
readonly authorization: string | undefined;
readonly cookie: string | undefined;
readonly referer: string | undefined;
}[];
close(): Promise<void>;
}
@@ -29,13 +35,24 @@ interface FakeOptions {
readonly unsupportedMethods?: readonly string[];
readonly transitionalFrameReads?: number;
readonly attachedFrameUrl?: string;
readonly frameUrlAfterFirstRead?: string;
readonly navigateDuringObservationUrl?: string;
readonly navigateDuringCaptureUrl?: string;
readonly navigateDuringScreenshotUrl?: string;
readonly extraCollections?: boolean;
readonly foreignSessionEvents?: boolean;
readonly redirectToDisallowedOrigin?: boolean;
readonly unrelatedWorker?: boolean;
readonly binaryWebSocketEvent?: boolean;
readonly invalidBinaryWebSocketEvent?: boolean;
readonly sourceMapBody?: string;
readonly sessionTimeline?: "same_origin" | "outside_policy";
readonly sensitiveShapes?: boolean;
readonly invalidResponseBodyBase64?: boolean;
readonly webMcpTools?: boolean;
readonly webMcpChildLeavesScope?: boolean;
readonly electronFileUrl?: string;
readonly duplicateElectronInventory?: boolean;
}
/** Start a real HTTP/WebSocket fake at the same seams as a user-owned browser. */
@@ -43,11 +60,30 @@ export const startFakeCdpBrowser = async (
options: FakeOptions = {},
): Promise<FakeCdpBrowser> => {
const commands: FakeCdpCommand[] = [];
const httpRequests: {
url: string;
authorization: string | undefined;
cookie: string | undefined;
referer: string | undefined;
}[] = [];
const sockets = new Set<WebSocket>();
let frameTreeReads = 0;
let port = 0;
const http = createServer((request, response) => {
httpRequests.push({
url: request.url ?? "",
authorization: request.headers.authorization,
cookie: request.headers.cookie,
referer: request.headers.referer,
});
response.setHeader("content-type", "application/json");
if (
request.url?.startsWith("/app.js.map") === true &&
options.sourceMapBody !== undefined
) {
response.end(options.sourceMapBody);
return;
}
if (request.url === "/json/version") {
response.end(
options.oversizedDiscovery === true
@@ -138,6 +174,7 @@ export const startFakeCdpBrowser = async (
browserWebSocketUrl: `ws://127.0.0.1:${String(port)}/devtools/browser/fake`,
allowedOrigin: endpoint,
commands,
httpRequests,
async close() {
for (const socket of sockets) socket.terminate();
await new Promise<void>((resolve) => webSockets.close(() => resolve()));
@@ -208,6 +245,17 @@ const targets = (
},
]
: []),
...(options.electronFileUrl === undefined
? []
: [
{
id: "electron-page",
type: "page",
title: "Electron application",
url: options.electronFileUrl,
attached: false,
},
]),
];
const parseCommand = (text: string): FakeCdpCommand => {
@@ -245,19 +293,44 @@ const resultFor = (
case "Page.getFrameTree":
return frameTree(
port,
frameTreeReads <= (options.transitionalFrameReads ?? 0)
? ":"
: options.attachedFrameUrl,
frameTreeReads > 1 && options.frameUrlAfterFirstRead !== undefined
? options.frameUrlAfterFirstRead
: frameTreeReads <= (options.transitionalFrameReads ?? 0)
? ":"
: (options.electronFileUrl ?? options.attachedFrameUrl),
options.extraCollections === true,
);
case "Page.getResourceTree":
return resourceTree(port, options.extraCollections === true);
return resourceTree(
port,
options.extraCollections === true,
options.electronFileUrl,
options.duplicateElectronInventory === true,
);
case "DOMSnapshot.captureSnapshot":
return domSnapshot(port);
return domSnapshot(
port,
options.electronFileUrl,
options.extraCollections === true,
);
case "Accessibility.getFullAXTree":
return accessibilityTree(options.extraCollections === true);
case "Debugger.getScriptSource":
return { scriptSource: "export const observed = 'source-secret';" };
case "Network.getResponseBody":
return options.invalidResponseBodyBase64 === true
? { body: "%%%not-base64%%%", base64Encoded: true }
: {
body: JSON.stringify({
result: { ok: true, token: "response-body-secret" },
items: [{ id: 1 }, { id: 2 }],
}),
base64Encoded: false,
};
case "Page.captureScreenshot":
return {
data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PzWvWQAAAABJRU5ErkJggg==",
};
case "Target.getTargets":
return { targetInfos: targets(port, options).map(endpointTargetToInfo) };
case "Storage.getUsageAndQuota":
@@ -348,20 +421,38 @@ const frameTree = (
const resourceTree = (
port: number,
extraCollections = false,
electronFileUrl?: string,
duplicateElectronInventory = false,
): Readonly<Record<string, unknown>> => ({
frameTree: {
frame: {
id: "frame-main",
loaderId: "loader-main",
url: `http://127.0.0.1:${String(port)}/app`,
url: electronFileUrl ?? `http://127.0.0.1:${String(port)}/app`,
},
resources: [
{
url: `http://127.0.0.1:${String(port)}/app.js?api_key=resource-secret`,
url:
electronFileUrl === undefined
? `http://127.0.0.1:${String(port)}/app.js?token=script-secret`
: new URL("app.js", electronFileUrl).href,
type: "Script",
mimeType: "text/javascript",
contentSize: 128,
},
...(duplicateElectronInventory
? [
{
url:
electronFileUrl === undefined
? `http://127.0.0.1:${String(port)}/app.js?token=script-secret`
: new URL("app.js", electronFileUrl).href,
type: "Script",
mimeType: "text/javascript",
contentSize: 128,
},
]
: []),
...(extraCollections
? [
{
@@ -381,16 +472,30 @@ const resourceTree = (
},
});
const domSnapshot = (port: number): Readonly<Record<string, unknown>> => {
const domSnapshot = (
port: number,
electronFileUrl?: string,
extraCollections = false,
): Readonly<Record<string, unknown>> => {
const secondDocumentUrl =
electronFileUrl !== undefined && extraCollections
? new URL("child.html", electronFileUrl).href
: "https://private.example.test/frame";
const strings = [
`http://127.0.0.1:${String(port)}/app`,
electronFileUrl ?? `http://127.0.0.1:${String(port)}/app`,
"#document",
"",
"HTML",
"LINK",
"token",
"dom-secret",
"https://private.example.test/frame",
secondDocumentUrl,
"PRIVATE-TEXT",
"href",
"/agent?token=dom-url-secret",
"rel",
"mcp",
"DIV",
"child text",
];
return {
strings,
@@ -402,18 +507,27 @@ const domSnapshot = (port: number): Readonly<Record<string, unknown>> => {
nodeName: [1, 3],
nodeValue: [2, 2],
parentIndex: [-1, 0],
attributes: [[], [4, 5]],
attributes: [[], [4, 5, 8, 9, 10, 11]],
},
},
{
documentURL: 6,
nodes: {
nodeType: [3],
nodeName: [1],
nodeValue: [7],
parentIndex: [-1],
attributes: [[]],
},
nodes:
electronFileUrl !== undefined && extraCollections
? {
nodeType: [9, 1],
nodeName: [1, 12],
nodeValue: [2, 13],
parentIndex: [-1, 0],
attributes: [[], []],
}
: {
nodeType: [3],
nodeName: [1],
nodeValue: [7],
parentIndex: [-1],
attributes: [[]],
},
},
],
};
@@ -461,13 +575,28 @@ const emitEvents = (
});
event(socket, "Debugger.scriptParsed", command.sessionId, {
scriptId: "script-allowed",
url: `http://127.0.0.1:${String(port)}/app.js?token=script-secret`,
url:
options.electronFileUrl === undefined
? `http://127.0.0.1:${String(port)}/app.js?token=script-secret`
: new URL("app.js", options.electronFileUrl).href,
hash: "cdp-hash",
length: 40,
isModule: true,
scriptLanguage: "JavaScript",
sourceMapURL: `http://127.0.0.1:${String(port)}/app.js.map?token=map-secret`,
});
if (
options.electronFileUrl !== undefined &&
options.duplicateElectronInventory === true
)
event(socket, "Debugger.scriptParsed", command.sessionId, {
scriptId: "script-allowed-duplicate",
url: new URL("app.js", options.electronFileUrl).href,
hash: "cdp-hash",
length: 40,
isModule: true,
scriptLanguage: "JavaScript",
});
event(socket, "Debugger.scriptParsed", command.sessionId, {
scriptId: "script-private",
url: "https://private.example.test/private.js?secret=forbidden",
@@ -498,14 +627,27 @@ const emitEvents = (
request: {
url,
method: "POST",
headers: { Authorization: "Bearer request-secret" },
postData: "request-body-secret",
headers: {
Authorization: "Bearer request-secret",
"Content-Type": "application/json; charset=utf-8",
},
postData: JSON.stringify({
operation: "lookup",
token: "request-body-secret",
filters: { active: true },
}),
},
initiator: {
type: "script",
callFrames: [
{ url: `${url}#caller-secret`, lineNumber: 3, columnNumber: 5 },
],
stack: {
callFrames: [
{
url: `http://127.0.0.1:${String(port)}/app.js?caller=caller-secret`,
lineNumber: 3,
columnNumber: 5,
},
],
},
},
});
if (options.redirectToDisallowedOrigin === true)
@@ -526,7 +668,18 @@ const emitEvents = (
: url,
status: 200,
mimeType: "application/json",
headers: { "Set-Cookie": "response-secret" },
headers: {
"Set-Cookie": "response-secret",
"Content-Length": "321",
"Content-Encoding": "br",
"Content-Security-Policy":
"default-src 'self' https:; script-src 'nonce-csp-secret' 'sha256-hash-secret' https://private.example.test https://127.0.0.1",
Link: `</agent?token=link-secret>; rel="mcp service-desc"; type="application/json", <https://private.example.test/agent>; rel="mcp"`,
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp",
"Permissions-Policy": "camera=(), geolocation=(self)",
"X-Model-Context": "header-secret",
},
},
});
event(socket, "Network.loadingFinished", command.sessionId, {
@@ -539,19 +692,51 @@ const emitEvents = (
});
event(socket, "Network.webSocketFrameSent", command.sessionId, {
requestId: "websocket-1",
response: { opcode: 1, payloadData: "websocket-secret" },
response: {
opcode: 1,
payloadData:
options.sensitiveShapes === true
? JSON.stringify({
event: "updated",
token: "websocket-secret",
payload: { count: 2 },
})
: "websocket-secret",
},
});
if (options.binaryWebSocketEvent === true)
event(socket, "Network.webSocketFrameReceived", command.sessionId, {
requestId: "websocket-1",
response: { opcode: 2, payloadData: "AQID" },
response: {
opcode: 2,
payloadData:
options.invalidBinaryWebSocketEvent === true ? "%%%" : "AQID",
},
});
}
if (command.method === "Runtime.enable") {
event(socket, "Runtime.consoleAPICalled", command.sessionId, {
type: "log",
timestamp: 123,
args: [{ type: "string", value: "console-secret" }],
args: [
{
type: "string",
value:
options.sensitiveShapes === true
? "authorization=Bearer console-secret"
: "console-secret",
},
...(options.sensitiveShapes === true
? [
{ type: "number", value: 42 },
{
type: "object",
objectId: "must-not-be-expanded",
description: "object-secret",
},
]
: []),
],
stackTrace: {
callFrames: [
{
@@ -568,6 +753,85 @@ const emitEvents = (
args: [{ type: "string", value: "unknown-console-value-secret" }],
});
}
if (command.method === "WebMCP.enable" && options.webMcpTools === true) {
event(socket, "WebMCP.toolsAdded", command.sessionId, {
tools: [
{
name: "search_orders",
description: "Search orders; authorization=Bearer tool-secret",
frameId: "frame-main",
backendNodeId: 42,
inputSchema: {
type: "object",
properties: {
orderId: { type: "string", example: "schema-secret" },
includeItems: { type: "boolean", default: true },
},
required: ["orderId"],
},
annotations: {
readOnly: true,
untrustedContent: true,
autosubmit: false,
},
stackTrace: {
callFrames: [
{
url: `http://127.0.0.1:${String(port)}/app.js?token=tool-source-secret`,
lineNumber: 12,
columnNumber: 4,
},
],
},
},
{
name: "private_tool",
description: "private-tool-secret",
frameId: "frame-private",
},
...(options.extraCollections === true
? [
{
name: "update_order",
description: "Update an order",
frameId: "frame-main",
inputSchema: {
type: "object",
properties: { orderId: { type: "string" } },
},
},
]
: []),
...(options.webMcpChildLeavesScope === true
? [
{
name: "child_tool",
description: "Must be removed after child navigation",
frameId: "frame-child",
},
]
: []),
],
});
if (options.webMcpChildLeavesScope === true) {
event(socket, "Page.frameNavigated", command.sessionId, {
frame: {
id: "frame-child",
parentId: "frame-main",
url: "https://private.example.test/escaped",
},
});
event(socket, "WebMCP.toolsAdded", command.sessionId, {
tools: [
{
name: "escaped_child_tool",
description: "cross-origin-child-secret",
frameId: "frame-child",
},
],
});
}
}
if (
command.method === "DOMSnapshot.captureSnapshot" &&
options.navigateDuringCaptureUrl !== undefined
@@ -578,6 +842,68 @@ const emitEvents = (
url: options.navigateDuringCaptureUrl,
},
});
if (
command.method === "Page.captureScreenshot" &&
options.navigateDuringScreenshotUrl !== undefined
)
event(socket, "Page.frameNavigated", command.sessionId, {
frame: {
id: "frame-main",
url: options.navigateDuringScreenshotUrl,
},
});
if (
command.method === "Page.setLifecycleEventsEnabled" &&
options.sessionTimeline !== undefined
) {
const allowed = `http://127.0.0.1:${String(port)}/reloaded?token=session-secret`;
event(socket, "Page.frameRequestedNavigation", command.sessionId, {
frameId: "frame-main",
url: allowed,
reason: "reload",
timestamp: 10,
});
event(socket, "Page.frameNavigated", command.sessionId, {
frame: {
id: "frame-main",
loaderId: "loader-reload",
url: allowed,
transitionType: "reload",
},
timestamp: 11,
});
event(socket, "Page.navigatedWithinDocument", command.sessionId, {
frameId: "frame-main",
url: `${allowed}#spa-secret`,
navigationType: "historyApi",
timestamp: 12,
});
const redirectUrl =
options.sessionTimeline === "outside_policy"
? "https://private.example.test/outside?token=redirect-secret"
: `http://127.0.0.1:${String(port)}/redirected?token=redirect-secret`;
event(socket, "Network.requestWillBeSent", command.sessionId, {
requestId: "document-request",
frameId: "frame-main",
loaderId: "loader-redirect",
request: { url: redirectUrl, method: "GET" },
redirectResponse: { status: 302 },
timestamp: 13,
});
event(socket, "Network.loadingFailed", command.sessionId, {
requestId: "failed-request",
frameId: "frame-main",
loaderId: "loader-reload",
errorText: "net::ERR_CONNECTION_REFUSED",
timestamp: 14,
});
event(socket, "Page.lifecycleEvent", command.sessionId, {
frameId: "frame-main",
loaderId: "loader-reload",
name: "networkIdle",
timestamp: 15,
});
}
};
const event = (
+10 -4
View File
@@ -19,6 +19,10 @@ import { processCaptureSchema } from "../../src/domain/processCapture.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../src/contracts/processCaptureExample.js";
import { jsonValueSchema } from "../../src/domain/jsonValue.js";
import { PROCESS_PROVIDER } from "../../src/server/sessionToolPolicies.js";
import {
SESSION_TOOL_CONTRACTS,
TOOL_CONTRACTS,
} from "../../src/contracts/toolContracts.js";
const resources: Array<{ close(): Promise<void> }> = [];
@@ -127,7 +131,7 @@ describe("full MCP integration with multi-tool sequences", () => {
});
});
it("preserves the complete 70-tool inventory with a session", async () => {
it("preserves the complete 78-tool inventory with a session", async () => {
const session = new BinarySession(
(_path) =>
({
@@ -150,7 +154,7 @@ describe("full MCP integration with multi-tool sequences", () => {
await client.connect(clientTransport);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(70);
expect(listed.tools).toHaveLength(78);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
@@ -374,12 +378,14 @@ describe("full MCP integration with multi-tool sequences", () => {
});
});
it("preserves the 52-tool inventory without a session", async () => {
it("preserves the target-open tool inventory without a session", async () => {
const client = await connect({
execute: () => Promise.resolve(ok(null)),
});
const listed = await client.listTools();
expect(listed.tools).toHaveLength(52);
expect(listed.tools).toHaveLength(
TOOL_CONTRACTS.length - SESSION_TOOL_CONTRACTS.length,
);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("binary_overview");
expect(names).toContain("batch_decompile");
+66
View File
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { inferJsonShape } from "../src/domain/jsonShape.js";
describe("inferJsonShape", () => {
it("retains paths and types without retaining JSON values", () => {
const shape = inferJsonShape(
JSON.stringify({
token: "super-secret",
users: [
{ id: 1, active: true },
{ id: "second-secret", active: false },
],
optional: null,
}),
{ maximumBytes: 4_096, maximumNodes: 100, maximumDepth: 10 },
);
expect(shape).toMatchObject({
root_type: "object",
truncated: false,
properties: expect.arrayContaining([
{ path: "/token", types: ["string"], observations: 1 },
{
path: "/users/*/id",
types: ["number", "string"],
observations: 2,
},
{
path: "/users/*/active",
types: ["boolean"],
observations: 2,
},
]),
});
expect(JSON.stringify(shape)).not.toContain("super-secret");
expect(JSON.stringify(shape)).not.toContain("second-secret");
});
it("rejects malformed and oversized JSON without returning a prefix", () => {
const limits = {
maximumBytes: 8,
maximumNodes: 100,
maximumDepth: 10,
};
expect(inferJsonShape("not-json", limits)).toBeNull();
expect(inferJsonShape('{"secret":"value"}', limits)).toBeNull();
});
it("reports node and depth truncation deterministically", () => {
expect(
inferJsonShape('{"a":{"b":{"c":1}}}', {
maximumBytes: 1_024,
maximumNodes: 100,
maximumDepth: 1,
}),
).toMatchObject({ truncated: true, max_depth_observed: 1 });
expect(
inferJsonShape("[1,2,3,4]", {
maximumBytes: 1_024,
maximumNodes: 2,
maximumDepth: 10,
}),
).toMatchObject({ truncated: true, node_count: 2 });
});
});
+95
View File
@@ -0,0 +1,95 @@
import { deflateSync } from "node:zlib";
import { describe, expect, it } from "vitest";
import { comparePngScreenshots } from "../src/browser/PngVisualDiff.js";
import {
compareWebScreenshotsInputSchema,
createWebScreenshotArtifact,
} from "../src/domain/webScreenshot.js";
describe("PNG visual diff", () => {
it("reports exact changed-pixel and channel metrics", () => {
const before = artifact(1, 1, [0, 0, 0, 255]);
const after = artifact(1, 1, [10, 0, 0, 255]);
const result = comparePngScreenshots(
compareWebScreenshotsInputSchema.parse({ before, after }),
);
expect(result).toMatchObject({
status: "different",
compared_pixels: 1,
changed_pixels: 1,
changed_ratio: 1,
maximum_channel_delta: 10,
mean_absolute_channel_delta: 2.5,
});
});
it("applies a channel threshold and reports dimension mismatch", () => {
const one = artifact(1, 1, [0, 0, 0, 255]);
const near = artifact(1, 1, [2, 0, 0, 255]);
expect(
comparePngScreenshots(
compareWebScreenshotsInputSchema.parse({
before: one,
after: near,
channel_threshold: 2,
}),
).status,
).toBe("identical");
expect(
comparePngScreenshots(
compareWebScreenshotsInputSchema.parse({
before: one,
after: artifact(2, 1, [0, 0, 0, 255, 0, 0, 0, 255]),
}),
),
).toMatchObject({ status: "dimension_mismatch", compared_pixels: 0 });
});
it("rejects images above the caller's decoded pixel limit", () => {
const image = artifact(2, 1, [0, 0, 0, 255, 0, 0, 0, 255]);
expect(() =>
comparePngScreenshots(
compareWebScreenshotsInputSchema.parse({
before: image,
after: image,
maximum_pixels: 1,
}),
),
).toThrow("oversized PNG");
});
});
const artifact = (width: number, height: number, pixels: readonly number[]) =>
createWebScreenshotArtifact(png(width, height, pixels));
const png = (
width: number,
height: number,
pixels: readonly number[],
): Buffer => {
const header = Buffer.alloc(13);
header.writeUInt32BE(width, 0);
header.writeUInt32BE(height, 4);
header[8] = 8;
header[9] = 6;
const rows: number[] = [];
for (let row = 0; row < height; row += 1)
rows.push(0, ...pixels.slice(row * width * 4, (row + 1) * width * 4));
return Buffer.concat([
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
chunk("IHDR", header),
chunk("IDAT", deflateSync(Buffer.from(rows))),
chunk("IEND", Buffer.alloc(0)),
]);
};
const chunk = (type: string, data: Buffer): Buffer => {
const result = Buffer.alloc(12 + data.byteLength);
result.writeUInt32BE(data.byteLength, 0);
result.write(type, 4, 4, "ascii");
data.copy(result, 8);
return result;
};
+1 -1
View File
@@ -54,7 +54,7 @@ describe("guided prompts over MCP", () => {
),
);
}
expect((await client.listTools()).tools).toHaveLength(70);
expect((await client.listTools()).tools).toHaveLength(78);
const result = await client.getPrompt({
name: "investigate_feature",
arguments: {
+4 -2
View File
@@ -11,6 +11,7 @@ import {
import { NATIVE_TOOL_CONTRACTS } from "../src/contracts/nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../src/contracts/artifactToolContracts.js";
import { BROWSER_TOOL_CONTRACTS } from "../src/contracts/browserToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "../src/contracts/electronToolContracts.js";
const readmes = [
"README.md",
@@ -26,14 +27,15 @@ const expectedToolCounts = [
NATIVE_TOOL_CONTRACTS.length,
ARTIFACT_TOOL_CONTRACTS.length,
BROWSER_TOOL_CONTRACTS.length,
ELECTRON_TOOL_CONTRACTS.length,
SESSION_TOOL_CONTRACTS.length,
] as const;
const toolCountsFromReadme = (content: string, path: string): number[] => {
const lines = content.split(/\r?\n/u);
const headingIndex = lines.findIndex((line) => /^## .*70/u.test(line));
const headingIndex = lines.findIndex((line) => /^## .*78/u.test(line));
if (headingIndex === -1)
throw new Error(`Missing 70-tool heading in ${path}`);
throw new Error(`Missing 78-tool heading in ${path}`);
const counts: number[] = [];
for (const line of lines.slice(headingIndex + 1)) {
+3 -3
View File
@@ -10,7 +10,7 @@ const fixturePath = fileURLToPath(
);
describe("production stdio runtime", () => {
it("starts the built entrypoint, lists 70 tools, calls one, and shuts down", async () => {
it("starts the built entrypoint, lists 78 tools, calls one, and shuts down", async () => {
const transport = new StdioClientTransport({
command: process.execPath,
args: [mainPath],
@@ -32,7 +32,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
const tools = await client.listTools();
expect(tools.tools).toHaveLength(70);
expect(tools.tools).toHaveLength(78);
const result = await client.callTool({
name: "current_document",
arguments: {},
@@ -78,7 +78,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
expect((await client.listTools()).tools).toHaveLength(70);
expect((await client.listTools()).tools).toHaveLength(78);
} finally {
await client.close();
await transport.close();
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import {
boundedSensitiveText,
redactSensitiveText,
} from "../src/browser/SensitiveTextCapture.js";
describe("sensitive console text", () => {
it("redacts assignments, bearer credentials, and JWT-shaped values", () => {
const jwt = "eyJabcdefghijk.abcdefghijkl.abcdefghijk";
expect(
redactSensitiveText(
`authorization=Bearer abc.def password='hunter2' api_key=key ${jwt}`,
),
).toBe(
"authorization=[REDACTED] password=[REDACTED] api_key=[REDACTED] [REDACTED_JWT]",
);
});
it("bounds UTF-8 after redaction without splitting a code point", () => {
expect(boundedSensitiveText("password=secret 你好", 22)).toEqual({
text: "password=[REDACTED] ",
bytes: 20,
truncated: true,
});
});
});
+5 -5
View File
@@ -24,11 +24,11 @@ describe("server and catalog identity", () => {
});
expect(PRODUCT_IDENTITY.packageVersion).toBe(packageJson.version);
expect(SDK_IDENTITY.server).toBe("2.0.0-beta.4");
expect(CLI_COMMAND_NAMES).toHaveLength(30);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(30);
expect(CLI_COMMAND_NAMES).toHaveLength(38);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(38);
expect(CATALOG_IDENTITY.counts).toEqual({
cli_commands: 30,
mcp_tools: 70,
cli_commands: 38,
mcp_tools: 78,
mcp_prompts: 6,
mcp_resources: 2,
mcp_resource_templates: 7,
@@ -162,7 +162,7 @@ describe("server and catalog identity", () => {
expect(status.structuredContent).toMatchObject({
result: {
server_identity: {
catalog: { counts: { mcp_tools: 70, cli_commands: 30 } },
catalog: { counts: { mcp_tools: 78, cli_commands: 38 } },
alignment: { state: "mcp_server_restart_required" },
},
tool_availability: expect.arrayContaining([
+1 -1
View File
@@ -76,7 +76,7 @@ describe("target-free MCP lifecycle", () => {
expect(text(before)).toBe(
"No app is open. Ask the user which app to investigate, then call open_binary with its local path.",
);
expect((await mcp.listTools()).tools).toHaveLength(70);
expect((await mcp.listTools()).tools).toHaveLength(78);
const deniedCapture = await mcp.callTool({
name: "capture_process_scenario",
arguments: {
+1 -1
View File
@@ -27,7 +27,7 @@ describe("canonical skill transaction", () => {
expect(await readFile(`${destination}.rea.backup`, "utf8")).toBe(
"stale managed skill\n",
);
expect(await readFile(destination, "utf8")).toContain('version: "13"');
expect(await readFile(destination, "utf8")).toContain('version: "14"');
expect(await readFile(destination, "utf8")).toContain(
`tool_count: ${String(TOOL_CONTRACTS.length)}`,
);
+14 -3
View File
@@ -9,9 +9,10 @@ import {
import { ARTIFACT_TOOL_CONTRACTS } from "../src/contracts/artifactToolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "../src/contracts/nativeToolContracts.js";
import { BROWSER_TOOL_CONTRACTS } from "../src/contracts/browserToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "../src/contracts/electronToolContracts.js";
describe("tool contract inventory", () => {
it("publishes 52 analysis contracts and eighteen session tools", () => {
it("publishes 60 analysis contracts and eighteen session tools", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(33);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(10);
expect(NATIVE_TOOL_CONTRACTS).toHaveLength(5);
@@ -19,6 +20,16 @@ describe("tool contract inventory", () => {
expect(BROWSER_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"list_browser_targets",
"inspect_web_page",
"analyze_web_bundle",
"observe_web_session",
"discover_webmcp_tools",
"compare_web_captures",
"capture_web_screenshot",
"compare_web_screenshots",
]);
expect(ELECTRON_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"list_electron_targets",
"inspect_electron_page",
]);
expect(SESSION_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"open_binary",
@@ -40,8 +51,8 @@ describe("tool contract inventory", () => {
"update_unknown",
"verify_unknown_resolution",
]);
expect(TOOL_CONTRACTS).toHaveLength(70);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(70);
expect(TOOL_CONTRACTS).toHaveLength(78);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(78);
});
it("retains documented enhanced-tool limits at the input boundary", () => {
+267
View File
@@ -0,0 +1,267 @@
import { describe, expect, it } from "vitest";
import {
inspectWebPageInputSchema,
webPageInspectionSchema,
} from "../src/domain/browserObservation.js";
import { analyzeCapturedWebBundle } from "../src/domain/webBundleAnalyzer.js";
import {
analyzeWebBundleInputSchema,
webBundleAnalysisSchema,
} from "../src/domain/webBundleAnalysis.js";
import { createWebTextArtifact } from "../src/domain/webContentArtifact.js";
const origin = "https://app.example.test";
describe("web bundle analyzer", () => {
it("extracts bounded graph, route, endpoint, vendor, and WebMCP evidence", () => {
const source = `
import { createApp } from "./chunk.js?token=secret";
const lazy = import("./lazy.js");
const routes = [{ path: "/users/:id?token=secret" }];
fetch("/api/users?authorization=secret");
document.modelContext.registerTool({
name: "lookup-user",
description: "Untrusted page declaration",
inputSchema: {
type: "object",
properties: {
userId: { type: "string" },
verbose: { type: "boolean" }
}
}
});
const __webpack_require__ = () => createApp(routes, lazy);
`;
const result = analyzeCapturedWebBundle(inspection(source), input());
expect(result.observations.chunks.edges).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "static_import",
specifier: "./chunk.js?token=secret",
resolved_url: `${origin}/assets/chunk.js?token=%5BREDACTED%5D`,
}),
expect.objectContaining({
kind: "dynamic_import",
specifier: "./lazy.js",
}),
]),
);
expect(result.observations.routes).toEqual([
expect.objectContaining({ value: "/users/:id?token=%5BREDACTED%5D" }),
]);
expect(result.observations.endpoints).toEqual([
expect.objectContaining({
value: "/api/users?authorization=%5BREDACTED%5D",
}),
]);
expect(result.observations.webmcp_declarations).toEqual([
expect.objectContaining({
name: "lookup-user",
trust: "page-declared-untrusted",
schema_property_names: ["userId", "verbose"],
}),
]);
expect(result.inferences).toEqual(
expect.arrayContaining([
expect.objectContaining({ value: "webpack", confidence: "high" }),
expect.objectContaining({ value: "Vue" }),
]),
);
expect(JSON.stringify(result)).not.toContain("authorization=secret");
expect(result.completeness.status).toBe("complete_within_limits");
});
it("reports parser gaps and finding truncation instead of claiming completeness", () => {
const malformed = inspection("function broken( {");
const failed = analyzeCapturedWebBundle(malformed, input());
expect(failed.completeness).toMatchObject({
status: "partial",
parse_failures: 1,
});
expect(failed.unknowns[0]?.dimension).toBe("javascript_ast");
const bounded = analyzeCapturedWebBundle(
inspection("fetch('/one'); fetch('/two'); fetch('/three');"),
input({ analysis_limits: { max_findings: 1 } }),
);
expect(bounded.observations.endpoints).toHaveLength(1);
expect(bounded.completeness).toMatchObject({
status: "truncated",
dropped_findings: 2,
});
});
it("propagates source-map truncation into completeness and unknowns", () => {
const analysis = analyzeCapturedWebBundle(
inspection("export {};"),
input(),
{
status: "truncated",
requested: 2,
processed: 1,
dropped: 1,
dropped_script_keys: [`scr_${"2".repeat(64)}`],
items: [
{
script_key: `scr_${"1".repeat(64)}`,
declared_url: "https://app.example.test/app.js.map",
status: "truncated",
artifact: null,
original_sources: [],
original_module_edges: [],
mappings: [],
limitation: "Source-map response exceeded the byte budget.",
},
],
},
);
expect(analysis.completeness.status).toBe("truncated");
expect(analysis.unknowns).toContainEqual({
dimension: "source_maps",
reason: "Source-map evidence was truncated by approved limits",
affected_script_keys: [`scr_${"1".repeat(64)}`, `scr_${"2".repeat(64)}`],
});
});
it("rejects inconsistent source-map coverage counts", () => {
const result = analyzeCapturedWebBundle(inspection("export {};"), input());
expect(
webBundleAnalysisSchema.safeParse({
...result,
observations: {
...result.observations,
source_maps: {
...result.observations.source_maps,
requested: 1,
},
},
}).success,
).toBe(false);
});
});
const input = (overrides: Record<string, unknown> = {}) =>
analyzeWebBundleInputSchema.parse({
...inspectWebPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
target_id: "page-1",
approved: true,
include_script_sources: true,
}),
source_capture_approved: true,
...overrides,
});
const inspection = (source: string) =>
webPageInspectionSchema.parse({
schema_version: 2,
browser: {
product: "Fake Chrome",
protocol_version: "1.3",
revision: "1",
user_agent: "fake",
js_version: "1",
},
target: {
target_id: "page-1",
type: "page",
title: "App",
url: `${origin}/app`,
origin,
attached: false,
},
capture_window: {
started_at: "2026-07-14T00:00:00.000Z",
ended_at: "2026-07-14T00:00:01.000Z",
observation_ms: 1_000,
},
completeness: {
status: "attach_limited",
conditions: ["attach_limited"],
policy_filtered_sections: [],
attach_limited_sections: ["network_requests"],
truncated_sections: [],
unavailable_sections: [],
excluded: [],
dropped_events: {
scripts: 0,
network_requests: 0,
console_events: 0,
websocket_connections: 0,
websocket_frames: 0,
webmcp_tools: 0,
timeline_events: 0,
total: 0,
},
},
frames: [],
dom: { total_nodes: 0, nodes: [] },
accessibility: {
total_nodes: 0,
text_capture: {
status: "not_approved",
retained_bytes: 0,
excluded_fields: 0,
truncated_fields: 0,
},
nodes: [],
},
scripts: {
total: 1,
items: [
{
script_key: `scr_${"1".repeat(64)}`,
url: `${origin}/assets/app.js`,
origin,
cdp_hash: "hash",
length: Buffer.byteLength(source),
is_module: true,
language: "JavaScript",
source_map_url: null,
resource_reconciliation: {
status: "unmatched",
reason: "no_exact_sanitized_url",
},
source: {
included: true,
artifact: createWebTextArtifact(source, "text/javascript"),
},
},
],
},
resources: [],
network: {
requests: [],
websocket_events: [],
coverage_started_at: "2026-07-14T00:00:00.000Z",
prior_activity_available: false,
},
console: {
events: [],
coverage_started_at: "2026-07-14T00:00:00.000Z",
prior_activity_available: false,
},
workers: [],
metadata: {
responses: [],
dom_urls: [],
agent_hints: [],
excluded_dom_urls: 0,
headers_allowlisted: true,
},
storage: {
origin,
usage_bytes: null,
quota_bytes: null,
local_storage_keys: [],
session_storage_keys: [],
indexed_db_names: [],
cache_names: [],
values_redacted: true,
},
limitations: [],
});
+151
View File
@@ -0,0 +1,151 @@
import { afterEach, describe, expect, it } from "vitest";
import { CdpBrowserProvider } from "../src/browser/CdpBrowserProvider.js";
import { inspectWebPageInputSchema } from "../src/domain/browserObservation.js";
import {
compareWebCaptures,
compareWebCapturesInputSchema,
} from "../src/domain/webCaptureDiff.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "./fixtures/fakeCdpBrowser.js";
describe("web capture diff", () => {
const browsers: FakeCdpBrowser[] = [];
afterEach(async () => {
await Promise.all(
browsers.splice(0).map(async (browser) => browser.close()),
);
});
it("reports stable observed changes while preserving unknown dimensions", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
}),
);
if (!captured.ok) throw captured.error;
const after = structuredClone(captured.value);
after.scripts.items = [];
const request = after.network.requests[0];
if (request !== undefined) request.status = 204;
const result = compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: captured.value },
after: { inspection: after },
}),
);
expect(result.overall_status).toBe("changed");
expect(result.dimensions.scripts).toMatchObject({
status: "changed",
total_changes: 1,
changes: [expect.objectContaining({ change: "removed" })],
});
expect(result.dimensions.network).toMatchObject({
status: "changed",
changes: [expect.objectContaining({ change: "modified" })],
});
expect(result.dimensions.webmcp).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
it("does not claim unchanged when a relevant section is incomplete", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
}),
);
if (!captured.ok) throw captured.error;
const incomplete = structuredClone(captured.value);
incomplete.completeness.truncated_sections.push("dom");
const result = compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: incomplete },
after: { inspection: captured.value },
}),
);
expect(result.dimensions.dom_structure.status).toBe("unknown");
expect(result.dimensions.dom_structure.reason).toContain("incomplete");
});
it("ignores transient request IDs and capture-approval state", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
}),
);
if (!captured.ok) throw captured.error;
const after = structuredClone(captured.value);
const request = after.network.requests[0];
if (request !== undefined) request.request_id = "different-cdp-request-id";
const response = after.metadata.responses[0];
if (response !== undefined)
response.request_id = "different-cdp-request-id";
const script = after.scripts.items[0];
if (script !== undefined && !script.source.included)
script.source.reason = "different approval explanation";
markSectionsComplete(captured.value, ["scripts", "metadata"]);
markSectionsComplete(after, ["scripts", "metadata"]);
const result = compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: captured.value },
after: { inspection: after },
}),
);
expect(result.dimensions.scripts.status).toBe("unchanged");
expect(result.dimensions.metadata.status).toBe("unchanged");
expect(result.dimensions.network.status).toBe("unknown");
expect(result.dimensions.network.total_changes).toBe(0);
});
});
const markSectionsComplete = (
inspection: {
completeness: {
policy_filtered_sections: string[];
attach_limited_sections: string[];
truncated_sections: string[];
unavailable_sections: string[];
};
},
sections: readonly string[],
): void => {
const completed = new Set(sections);
for (const key of [
"policy_filtered_sections",
"attach_limited_sections",
"truncated_sections",
"unavailable_sections",
] as const)
inspection.completeness[key] = inspection.completeness[key].filter(
(section) => !completed.has(section),
);
};
+154
View File
@@ -0,0 +1,154 @@
import { describe, expect, it } from "vitest";
import {
reconcileCapturedWebScript,
reconcileWebScript,
stableWebResources,
stableWebScriptKey,
} from "../src/domain/webInventory.js";
import {
createWebTextArtifact,
webTextArtifactSchema,
} from "../src/domain/webContentArtifact.js";
describe("web content artifacts", () => {
it("binds UTF-8 content, size, digest, and URI", () => {
const artifact = createWebTextArtifact(
"const marker = '😀';",
"text/javascript",
);
expect(webTextArtifactSchema.parse(artifact)).toEqual(artifact);
expect(artifact.bytes).toBe(Buffer.byteLength(artifact.text));
expect(artifact.uri).toBe(`rea://web-content/sha256/${artifact.sha256}`);
});
it("rejects altered content that reuses an artifact digest", () => {
const artifact = createWebTextArtifact("original", "text/javascript");
expect(
webTextArtifactSchema.safeParse({ ...artifact, text: "altered!" })
.success,
).toBe(false);
});
});
describe("stable web inventory", () => {
const script = {
url: "https://app.example.test/assets/app.js",
cdp_hash: "stable-cdp-hash",
length: 1_024,
is_module: true,
language: "JavaScript",
source_map_url: "https://app.example.test/assets/app.js.map",
};
it("excludes transient CDP and target identity from script keys", () => {
expect(stableWebScriptKey(script)).toBe(stableWebScriptKey({ ...script }));
expect(stableWebScriptKey({ ...script, length: 1_025 })).not.toBe(
stableWebScriptKey(script),
);
});
it("sorts resources deterministically and reconciles only exact URLs", () => {
const inputs = [
{
url: "https://app.example.test/assets/vendor.js",
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 200,
},
{
url: script.url,
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 1_024,
},
];
const forward = stableWebResources(inputs);
const reverse = stableWebResources([...inputs].reverse());
expect(reverse).toEqual(forward);
expect(reconcileWebScript(script, forward)).toEqual({
status: "exact",
resource_key: forward.find(({ url }) => url === script.url)?.resource_key,
});
expect(
reconcileWebScript({ ...script, url: `${script.url}?v=2` }, forward),
).toEqual({ status: "unmatched", reason: "no_exact_sanitized_url" });
});
it("reports duplicate resource observations as ambiguous", () => {
const duplicate = {
url: script.url,
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 1_024,
};
const resources = stableWebResources([
duplicate,
{ ...duplicate, content_size: 2_048 },
]);
expect(reconcileWebScript(script, resources)).toEqual({
status: "ambiguous",
candidate_resource_keys: resources
.map(({ resource_key }) => resource_key)
.sort(),
});
});
it("deduplicates identical resource observations by stable identity", () => {
const duplicate = {
url: script.url,
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 1_024,
};
expect(stableWebResources([duplicate, duplicate])).toEqual(
stableWebResources([duplicate]),
);
});
it("reconciles raw URLs independently of stable inventory sort order", () => {
const app = {
url: script.url,
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 1_024,
rawUrl: `${script.url}?token=secret`,
};
const vendor = {
url: "https://app.example.test/assets/vendor.js",
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 2_048,
rawUrl: "https://app.example.test/assets/vendor.js?v=1",
};
for (const rawResources of [
[app, vendor],
[vendor, app],
]) {
const resources = stableWebResources(
rawResources.map(({ rawUrl: _rawUrl, ...resource }) => resource),
);
expect(
reconcileCapturedWebScript(
{ ...script, rawUrl: app.rawUrl },
rawResources,
resources,
),
).toEqual({
status: "exact",
resource_key: resources.find(({ url }) => url === script.url)
?.resource_key,
});
}
});
});
+264
View File
@@ -0,0 +1,264 @@
import { describe, expect, it } from "vitest";
import { fetchWebSourceMaps } from "../src/browser/WebSourceMapFetcher.js";
import { analyzeWebBundleInputSchema } from "../src/domain/webBundleAnalysis.js";
const origin = "https://app.example.test";
const request = {
scriptKey: `scr_${"1".repeat(64)}`,
declaredUrl: `${origin}/assets/app.js.map?token=%5BREDACTED%5D`,
fetchUrl: `${origin}/assets/app.js.map?token=secret`,
};
describe("web source-map fetcher", () => {
it("fetches without credentials and derives mappings and original modules", async () => {
const calls: Array<{ url: string; init: RequestInit | undefined }> = [];
const map = JSON.stringify({
version: 3,
file: "app.js",
names: ["entry"],
sources: ["../src/main.ts"],
sourcesContent: ["import './dependency.ts';\nexport const entry = 1;"],
mappings: "AAAAA",
});
const result = await fetchWebSourceMaps([request], input(), undefined, {
fetch: (url, init) => {
calls.push({ url: String(url), init });
return Promise.resolve(
new Response(map, {
status: 200,
headers: { "content-type": "application/json" },
}),
);
},
});
expect(calls).toHaveLength(1);
expect(calls[0]).toMatchObject({
url: request.fetchUrl,
init: {
credentials: "omit",
redirect: "manual",
referrerPolicy: "no-referrer",
},
});
expect(JSON.stringify(calls[0]?.init)).not.toContain("secret");
expect(result).toMatchObject({
status: "included",
requested: 1,
processed: 1,
dropped: 0,
dropped_script_keys: [],
items: [
{
status: "included",
artifact: { media_type: "application/source-map+json" },
original_sources: [
{
source: `${origin}/src/main.ts`,
artifact: { media_type: "text/typescript" },
},
],
original_module_edges: [
{
kind: "static_import",
specifier: "./dependency.ts",
resolved_source: `${origin}/src/dependency.ts`,
},
],
mappings: [
{
generated_line: 1,
generated_column: 0,
original_line: 1,
original_column: 0,
},
],
},
],
});
});
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, {
fetch: (url) => {
calls.push(String(url));
return Promise.resolve(
new Response(null, {
status: 302,
headers: { location: "https://private.example.test/map" },
}),
);
},
});
expect(calls).toEqual([request.fetchUrl]);
expect(result).toMatchObject({
status: "unavailable",
items: [{ status: "policy_filtered" }],
});
});
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("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],
});
});
it("stops after exhausting the aggregate response-byte budget", async () => {
const requests = [0, 1, 2].map((index) => ({
...request,
scriptKey: `scr_${String(index + 1).repeat(64)}`,
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());
},
},
);
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" }],
});
});
it("rejects a per-map byte limit larger than the aggregate limit", () => {
const parsed = analyzeWebBundleInputSchema.safeParse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
target_id: "page-1",
approved: true,
source_capture_approved: true,
analysis_limits: {
max_source_map_bytes: 2,
max_total_source_map_bytes: 1,
},
});
expect(parsed.success).toBe(false);
});
});
const validMapResponse = () =>
new Response(
JSON.stringify({
version: 3,
names: [],
sources: ["a.js"],
sourcesContent: ["export const a = 1"],
mappings: "AAAA",
}),
{ status: 200 },
);
const input = (overrides: Record<string, unknown> = {}) =>
analyzeWebBundleInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
target_id: "page-1",
approved: true,
source_capture_approved: true,
fetch_source_maps: true,
source_map_fetch_approved: true,
...overrides,
});