Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(browser)!: preserve payload shapes and WebMCP declarations
morluto4951a897c53b
diff --git a/docs/browser-observation.md b/docs/browser-observation.mdindex dae77e066..0cebe1649 100644--- a/docs/browser-observation.md+++ b/docs/browser-observation.md@@ -14,7 +14,7 @@ REA can attach to a user-owned Chrome-family browser through the Chrome DevTools- `inspect_web_page` / `rea inspect-web-page` captures DOM structure, accessibility nodes, scripts, resources, safe response/DOM metadata, attach-window network and console metadata, WebSocket frame sizes, workers, quota, and optionally selected storage key names, redacted storage-content fingerprints, or script sources.- `analyze_web_bundle` / `rea analyze-web-bundle` parses selected script artifacts without execution and derives chunk edges, route and endpoint candidates, vendor fingerprints, static WebMCP declarations, and optionally source-map/original-source evidence.- `observe_web_session` / `rea observe-web-session` arms an observation window of the requested duration for an external user action and records ordered reload, SPA navigation, redirect, failure, lifecycle, and target-termination metadata.-- `discover_webmcp_tools` / `rea discover-webmcp-tools` uses the experimental CDP WebMCP domain to return every in-scope registration and its complete structural input-schema summary inline. Registrations with the same name and URL in distinct observed frames retain separate identities. `tool_key` includes the observed frame ID; it is not a stable identity across navigation or browser sessions. Same-frame registration updates replace that owner only, and removal leaves other owners intact. REA never exposes `WebMCP.invokeTool`; malformed protocol payloads fail explicitly instead of returning incomplete tool metadata.+- `discover_webmcp_tools` / `rea discover-webmcp-tools` uses the experimental CDP WebMCP domain to return every in-scope registration and its complete observed `input_schema` declaration and canonical `input_schema_sha256` digest inline. Declarations are untrusted JSON data, including declared types, required fields, enums, examples and reference URLs. REA does not resolve schema references. These fields replace `input_schema_shape`. Registrations with the same name and URL in distinct observed frames retain separate identities. `tool_key` includes the observed frame ID; it is not a stable identity across navigation or browser sessions. Same-frame registration updates replace that owner only, and removal leaves other owners intact. REA never exposes `WebMCP.invokeTool`; malformed protocol payloads fail explicitly instead of returning incomplete tool metadata.- `compare_web_captures` / `rea compare-web-captures` compares passive captures or exact-step-aligned browser scenarios. Scenario results commit reproducible literal normalization and expose alignment failures plus artifact-level action, screenshot, DOM, accessibility, URL, history, storage, and event differences. Missing or truncated evidence is never treated as equivalence.- `capture_web_screenshot` / `rea capture-web-screenshot` returns a content-addressed visible-viewport PNG.- `compare_web_screenshots` / `rea compare-web-screenshots` performs bounded local PNG pixel comparison without OCR or external services.@@ -134,7 +134,7 @@ REA retains local observation data and removes only URL userinfo credentials, ex- DOM snapshots retain node types, node names, value lengths, and attribute names, but not text or attribute values.- Accessibility structure and roles are retained by default, while names and descriptions require `include_accessibility_text: true`.- Network observations retain method, status, MIME type, size, type, initiator stack location, and complete URLs with userinfo credentials removed. Redirects reported by CDP are attached as ordered `redirects` on the one request ID, with the prior request URL, CDP response URL, method/type, response status/MIME/encoded length, request timestamp, and the next `requestWillBeSent` event timestamp. CDP delivers `redirectResponse` with that next request event, so the latter is an event boundary rather than an exact response timestamp. Redirect response headers and bodies are discarded; hops outside the selected origins are discarded with the request chain. Headers are discarded after an allowlisted projection of length/encoding, structured CSP/Link/policy fields, and untrusted agent hints. Cookies and authorization headers are never retained.-- Request/response bodies are not requested or parsed by default. When selected, only allowed-origin JSON media types are read, converted immediately to complete value-free property paths/types, and discarded. `Network.getResponseBody` is never sent unless JSON body shape capture is selected.+- Request/response bodies are not requested or parsed by default. When selected, only allowed-origin JSON media types are read, converted immediately to complete value-free typed paths, types and observation counts, and discarded. Each path segment is either `{ "kind": "property", "name": "raw property name" }` or `{ "kind": "array-element" }`; array-element types include primitives and nested arrays. Literal `*` properties remain distinct from array elements. `Network.getResponseBody` is never sent unless JSON body shape capture is selected. Comparison uses body shapes only when both captures selected them, and compares request/response shapes only where both observations provide those facts. Unavailable or truncated selected coverage makes equivalence unknown; observed differences still report changed.- Console observations with a stack source retain call type, argument types, timestamp, and source location. When console text capture is selected, already-delivered primitive values are retained verbatim; objects, getters, and remote properties are never expanded.- WebSocket observations retain direction, opcode, and payload byte length. When shape capture is selected, text frames are classified as text or complete value-free JSON shape; binary bytes, hashes, prefixes, and raw frames are never retained.- Storage observations always redact values. Key names, IndexedDB names, and cache names require `include_storage_keys`; stable content fingerprints require the additional `include_storage_fingerprints` selection. Cookie fingerprints cover cookies applicable to the current main-frame URL, including its path, rather than every cookie path on that origin. Other storage remains scoped to the origin. Cache bodies above 64 KiB and partial IndexedDB remote objects make fingerprint coverage incomplete, so identical observations remain `unknown`.diff --git a/scripts/lib/browser-verifier-assertions.mjs b/scripts/lib/browser-verifier-assertions.mjsindex b0c9b88d5..8e484afa1 100644--- a/scripts/lib/browser-verifier-assertions.mjs+++ b/scripts/lib/browser-verifier-assertions.mjs@@ -209,10 +209,16 @@ export function assertSensitiveShapes(result) {(item) =>item.url.includes("/api") &&item.body_shapes.request?.properties.some(- ({ path }) => path === "/token",+ ({ path }) =>+ path.length === 1 &&+ path[0].kind === "property" &&+ path[0].name === "token",) &&item.body_shapes.response?.properties.some(- ({ path }) => path === "/secret",+ ({ path }) =>+ path.length === 1 &&+ path[0].kind === "property" &&+ path[0].name === "secret",),);if (request === undefined)@@ -244,7 +250,10 @@ export function assertSensitiveShapes(result) {(event) =>event.payload_shape?.format === "json" &&event.payload_shape.json_shape?.properties.some(- ({ path }) => path === "/token",+ ({ path }) =>+ path.length === 1 &&+ path[0].kind === "property" &&+ path[0].name === "token",),))diff --git a/src/browser/CdpWebMcpDiscovery.ts b/src/browser/CdpWebMcpDiscovery.tsindex 240043f08..1cdbd3334 100644--- a/src/browser/CdpWebMcpDiscovery.ts+++ b/src/browser/CdpWebMcpDiscovery.ts@@ -5,7 +5,8 @@ import type {DiscoverWebMcpToolsInput,WebMcpDiscovery,} from "../domain/webMcpDiscovery.js";-import { inferJsonShape } from "../domain/jsonShape.js";+import { jsonValueSchema } from "../domain/jsonValue.js";+import { digestCanonicalValue } from "../domain/canonicalDigest.js";import { compositeKey } from "../domain/unicodeCodePointOrder.js";import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";import type { CdpConnection, CdpEvent } from "./CdpConnection.js";@@ -413,6 +414,10 @@ const normalizeTool = (}const description = cdpStringValue(value.description) ?? "";const annotations = recordValue(value.annotations);+ const declaration = jsonValueSchema.safeParse(value.inputSchema);+ if (!declaration.success)+ completeness.exclude("webmcp_tools", "invalid_protocol_value");+ const schema = declaration.success ? declaration.data : null;return {tool_key: toolKey(frame.url, frameId, name),name,@@ -424,7 +429,10 @@ const normalizeTool = (numberValue(value.backendNodeId) === undefined? "imperative": "declarative",- input_schema_shape: schemaShape(value.inputSchema),+ input_schema: schema,+ input_schema_sha256: declaration.success+ ? digestCanonicalValue(schema)+ : null,annotations: {read_only: booleanOrNull(annotations?.readOnly),untrusted_content: booleanOrNull(annotations?.untrustedContent),@@ -438,15 +446,6 @@ const normalizeTool = (};};-const schemaShape = (value: unknown) => {- if (recordValue(value) === undefined) return null;- const encoded = JSON.stringify(value);- const shape = inferJsonShape(encoded);- if (shape === null)- throw new BrowserObservationError("inspect_web_page", "protocol_error");- return shape;-};-const registrationSource = (stack: UnknownRecord | undefined,allowedOrigins: ReadonlySet<string>,diff --git a/src/domain/jsonShape.test.ts b/src/domain/jsonShape.test.tsindex e1a5dad2b..136c58381 100644--- a/src/domain/jsonShape.test.ts+++ b/src/domain/jsonShape.test.ts@@ -2,6 +2,9 @@ import { describe, expect, it } from "vitest";import { inferJsonShape } from "./jsonShape.js";+const property = (name: string) => ({ kind: "property" as const, name });+const element = { kind: "array-element" as const };+describe("inferJsonShape", () => {it("retains paths and types without retaining JSON values", () => {const shape = inferJsonShape(@@ -18,14 +21,18 @@ describe("inferJsonShape", () => {expect(shape).toMatchObject({root_type: "object",properties: expect.arrayContaining([- { path: "/token", types: ["string"], observations: 1 },{- path: "/users/*/id",+ path: [property("token")],+ types: ["string"],+ observations: 1,+ },+ {+ path: [property("users"), element, property("id")],types: ["number", "string"],observations: 2,},{- path: "/users/*/active",+ path: [property("users"), element, property("active")],types: ["boolean"],observations: 2,},@@ -35,11 +42,36 @@ describe("inferJsonShape", () => {expect(JSON.stringify(shape)).not.toContain("second-secret");});+ it("distinguishes array elements from literal star properties and counts primitive types", () => {+ const shape = inferJsonShape('{"items":[{"*":1},[true,"x",null],2]}');+ expect(shape?.properties).toEqual(+ expect.arrayContaining([+ {+ path: [property("items"), element],+ types: ["array", "number", "object"],+ observations: 3,+ },+ {+ path: [property("items"), element, property("*")],+ types: ["number"],+ observations: 1,+ },+ {+ path: [property("items"), element, element],+ types: ["boolean", "null", "string"],+ observations: 3,+ },+ ]),+ );+ });+it("rejects malformed JSON", () => {expect(inferJsonShape("not-json")).toBeNull();});+});- it("preserves pointer escaping and code-point ordering independently of key insertion order", () => {+describe("JSON shape completeness and ordering", () => {+ it("preserves raw property names and code-point ordering independently of key insertion order", () => {for (const reverse of [false, true]) {const object = (number: number, value: unknown) => {const entries = [@@ -64,24 +96,66 @@ describe("inferJsonShape", () => {node_count: 23,max_depth_observed: 4,properties: [- { path: "/nested", types: ["array"], observations: 1 },- { path: "/nested/*/A", types: ["boolean"], observations: 2 },- { path: "/nested/*/_", types: ["boolean"], observations: 2 },- { path: "/nested/*/a", types: ["boolean"], observations: 2 },{- path: "/nested/*/e\u0301~1~0",+ path: [property("nested")],+ types: ["array"],+ observations: 1,+ },+ {+ path: [property("nested"), element],+ types: ["object"],+ observations: 2,+ },+ {+ path: [property("nested"), element, property("A")],+ types: ["boolean"],+ observations: 2,+ },+ {+ path: [property("nested"), element, property("_")],+ types: ["boolean"],+ observations: 2,+ },+ {+ path: [property("nested"), element, property("a")],+ types: ["boolean"],+ observations: 2,+ },+ {+ path: [property("nested"), element, property("e\u0301/~")],types: ["array", "null"],observations: 2,},{- path: "/nested/*/e\u0341~1~0",+ path: [property("nested"), element, property("e\u0301/~"), element],+ types: ["null"],+ observations: 1,+ },+ {+ path: [property("nested"), element, property("e\u0341/~")],+ types: ["boolean"],+ observations: 2,+ },+ {+ path: [property("nested"), element, property("z")],+ types: ["boolean"],+ observations: 2,+ },+ {+ path: [property("nested"), element, property("é/~")],+ types: ["number"],+ observations: 2,+ },+ {+ path: [property("nested"), element, property("\uE000")],+ types: ["boolean"],+ observations: 2,+ },+ {+ path: [property("nested"), element, property("\u{10000}")],types: ["boolean"],observations: 2,},- { path: "/nested/*/z", types: ["boolean"], observations: 2 },- { path: "/nested/*/é~1~0", types: ["number"], observations: 2 },- { path: "/nested/*/\uE000", types: ["boolean"], observations: 2 },- { path: "/nested/*/\u{10000}", types: ["boolean"], observations: 2 },],});}@@ -96,7 +170,7 @@ describe("inferJsonShape", () => {expect(shape?.properties).toHaveLength(5_001);expect(shape?.node_count).toBe(5_002);expect(shape?.properties).toContainEqual({- path: "/field_5000",+ path: [property("field_5000")],types: ["number"],observations: 1,});diff --git a/src/domain/jsonShape.ts b/src/domain/jsonShape.tsindex f8d844aaf..2976d3ceb 100644--- a/src/domain/jsonShape.ts+++ b/src/domain/jsonShape.ts@@ -12,6 +12,12 @@ const jsonValueTypeSchema = z.enum([]);type JsonValueType = z.infer<typeof jsonValueTypeSchema>;+const jsonShapePathSegmentSchema = z.discriminatedUnion("kind", [+ z.object({ kind: z.literal("property"), name: z.string() }),+ z.object({ kind: z.literal("array-element") }),+]);+type JsonShapePathSegment = z.infer<typeof jsonShapePathSegmentSchema>;+/** Value-free structural summary of one approved JSON payload. */export const jsonShapeSchema = z.object({root_type: jsonValueTypeSchema,@@ -19,7 +25,7 @@ export const jsonShapeSchema = z.object({max_depth_observed: z.number().int().min(0),properties: z.array(z.object({- path: z.string(),+ path: z.array(jsonShapePathSegmentSchema).min(1),types: z.array(jsonValueTypeSchema).min(1),observations: z.number().int().min(1),}),@@ -39,13 +45,17 @@ export const inferJsonShape = (text: string): JsonShape | null => {}const properties = new Map<string,- { readonly types: Set<JsonValueType>; observations: number }+ {+ readonly path: JsonShapePathSegment[];+ readonly types: Set<JsonValueType>;+ observations: number;+ }>();const pending: Array<{readonly value: unknown;- readonly path: string;+ readonly path: JsonShapePathSegment[];readonly depth: number;- }> = [{ value: root, path: "", depth: 0 }];+ }> = [{ value: root, path: [], depth: 0 }];let nodeCount = 0;let maxDepthObserved = 0;while (pending.length > 0) {@@ -53,11 +63,26 @@ export const inferJsonShape = (text: string): JsonShape | null => {if (current === undefined) break;nodeCount += 1;maxDepthObserved = Math.max(maxDepthObserved, current.depth);+ if (current.path.length > 0) {+ const key = JSON.stringify(current.path);+ const type = jsonValueType(current.value);+ const existing = properties.get(key);+ if (existing === undefined)+ properties.set(key, {+ path: current.path,+ types: new Set([type]),+ observations: 1,+ });+ else {+ existing.types.add(type);+ existing.observations += 1;+ }+ }if (Array.isArray(current.value)) {for (let index = current.value.length - 1; index >= 0; index -= 1)pending.push({value: current.value[index],- path: `${current.path}/*`,+ path: [...current.path, { kind: "array-element" }],depth: current.depth + 1,});continue;@@ -68,15 +93,10 @@ export const inferJsonShape = (text: string): JsonShape | null => {const entry = allEntries[index];if (entry === undefined) continue;const [name, value] = entry;- const path = `${current.path}/${pointerName(name)}`;- const type = jsonValueType(value);- const existing = properties.get(path);- if (existing === undefined)- properties.set(path, { types: new Set([type]), observations: 1 });- else {- existing.types.add(type);- existing.observations += 1;- }+ const path: JsonShapePathSegment[] = [+ ...current.path,+ { kind: "property", name },+ ];pending.push({ value, path, depth: current.depth + 1 });}}@@ -84,13 +104,13 @@ export const inferJsonShape = (text: string): JsonShape | null => {root_type: jsonValueType(root),node_count: nodeCount,max_depth_observed: maxDepthObserved,- properties: [...properties.entries()]- .map(([path, value]) => ({- path,+ properties: [...properties.values()]+ .map((value) => ({+ path: value.path,types: [...value.types].sort(),observations: value.observations,}))- .sort((left, right) => compareUnicodeCodePoints(left.path, right.path)),+ .sort((left, right) => compareShapePaths(left.path, right.path)),});};@@ -112,5 +132,20 @@ const jsonValueType = (value: unknown): JsonValueType => {const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>typeof value === "object" && value !== null && !Array.isArray(value);-const pointerName = (value: string): string =>- value.replaceAll("~", "~0").replaceAll("/", "~1");+const compareShapePaths = (+ left: readonly JsonShapePathSegment[],+ right: readonly JsonShapePathSegment[],+): number => {+ for (let index = 0; index < Math.min(left.length, right.length); index += 1) {+ const a = left[index];+ const b = right[index];+ if (a === undefined || b === undefined) break;+ const order =+ compareUnicodeCodePoints(a.kind, b.kind) ||+ (a.kind === "property" && b.kind === "property"+ ? compareUnicodeCodePoints(a.name, b.name)+ : 0);+ if (order !== 0) return order;+ }+ return left.length - right.length;+};diff --git a/src/domain/webCaptureDiff.ts b/src/domain/webCaptureDiff.tsindex cee5096d3..08c896818 100644--- a/src/domain/webCaptureDiff.ts+++ b/src/domain/webCaptureDiff.ts@@ -196,13 +196,7 @@ const compareWebCaptureDimensions = (sectionsComplete(after, ["resources"]),"Resource inventory was incomplete in at least one observation.",),- network: compareDimension(- networkMap(before),- networkMap(after),- sectionsComplete(before, ["network_requests"]) &&- sectionsComplete(after, ["network_requests"]),- "Network capture is attach-window limited or incomplete.",- ),+ network: networkDimension(before, after),metadata: compareDimension(singleton("metadata", digestCanonicalValue(metadataProjection(before))),singleton("metadata", digestCanonicalValue(metadataProjection(after))),@@ -229,16 +223,85 @@ const keyed = <T>(values.map((value) => [identity(value), digestCanonicalValue(value)]),);+type BodyShapeSources = {+ readonly request: boolean;+ readonly response: boolean;+};++const bodyShapesSelected = (inspection: WebPageInspection): boolean =>+ !inspection.completeness.excluded.some(+ ({ section, reason }) =>+ section === "json_body_shapes" && reason === "not_approved",+ ) &&+ (inspection.network.requests.length === 0 ||+ inspection.network.requests.some(+ ({ body_shapes }) => body_shapes.status !== "not_approved",+ ));++const networkIdentity = (+ request: WebPageInspection["network"]["requests"][number],+): string =>+ `net_${digestCanonicalValue({ method: request.method, url: request.url, resource_type: request.resource_type })}`;++const networkDimension = (+ before: WebPageInspection,+ after: WebPageInspection,+): Dimension => {+ const selected = bodyShapesSelected(before) && bodyShapesSelected(after);+ const sources = new Map<string, BodyShapeSources>();+ if (selected) {+ const observedSources = (inspection: WebPageInspection) => {+ const result = new Map<string, BodyShapeSources>();+ for (const request of inspection.network.requests) {+ const identity = networkIdentity(request);+ const previous = result.get(identity);+ result.set(identity, {+ request:+ previous?.request !== false && request.body_shapes.request !== null,+ response:+ previous?.response !== false &&+ request.body_shapes.response !== null,+ });+ }+ return result;+ };+ const left = observedSources(before);+ const right = observedSources(after);+ for (const [identity, coverage] of left) {+ const next = right.get(identity);+ sources.set(identity, {+ request: coverage.request && next?.request === true,+ response: coverage.response && next?.response === true,+ });+ }+ }+ const shapesComplete =+ !selected ||+ [before, after].every(+ (inspection) =>+ sectionsComplete(inspection, ["json_body_shapes"]) &&+ inspection.network.requests.every(+ ({ body_shapes }) => body_shapes.status === "included",+ ),+ );+ return compareDimension(+ networkMap(before, sources),+ networkMap(after, sources),+ sectionsComplete(before, ["network_requests"]) &&+ sectionsComplete(after, ["network_requests"]) &&+ shapesComplete,+ "Network capture or selected JSON body-shape coverage is attach-window limited, unavailable, or incomplete.",+ );+};+const networkMap = (inspection: WebPageInspection,+ sources: ReadonlyMap<string, BodyShapeSources>,): ReadonlyMap<string, string> => {const grouped = new Map<string, unknown[]>();for (const request of inspection.network.requests) {- const identity = `net_${digestCanonicalValue({- method: request.method,- url: request.url,- resource_type: request.resource_type,- })}`;+ const identity = networkIdentity(request);+ const shapes = sources.get(identity);const values = grouped.get(identity) ?? [];values.push({status: request.status,@@ -252,7 +315,12 @@ const networkMap = (}) => redirect,),initiator: request.initiator,- body_shapes: request.body_shapes,+ ...(shapes?.request === true+ ? { request_shape: request.body_shapes.request }+ : {}),+ ...(shapes?.response === true+ ? { response_shape: request.body_shapes.response }+ : {}),});grouped.set(identity, values);}diff --git a/src/domain/webMcpDiscovery.ts b/src/domain/webMcpDiscovery.tsindex fa429e453..f1a3f3b12 100644--- a/src/domain/webMcpDiscovery.ts+++ b/src/domain/webMcpDiscovery.ts@@ -6,8 +6,8 @@ import {browserEndpointSchema,} from "./browserObservation.js";import { browserVersionSchema } from "./browserObservationSchemas.js";-import { jsonShapeSchema } from "./jsonShape.js";-import { prefixedDigestSchema } from "./../domain/digests.js";+import { jsonValueSchema } from "./jsonValue.js";+import { digestSchema, prefixedDigestSchema } from "./../domain/digests.js";/** Input for passive discovery of page-registered WebMCP tools. */export const discoverWebMcpToolsInputSchema = z.strictObject({@@ -28,7 +28,8 @@ const webMcpToolSchema = z.object({frame_url: z.string(),owner_origin: z.string(),declaration_kind: z.enum(["declarative", "imperative"]),- input_schema_shape: jsonShapeSchema.nullable(),+ input_schema: jsonValueSchema.nullable(),+ input_schema_sha256: digestSchema.nullable(),annotations: z.object({read_only: z.boolean().nullable(),untrusted_content: z.boolean().nullable(),diff --git a/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts b/tests/boundary/browser/cdpBrowserProvider.document_script.test.tsindex 7131b30d8..b74c60081 100644--- a/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts+++ b/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts@@ -1,3 +1,8 @@+import { digestCanonicalValue } from "../../../src/domain/canonicalDigest.js";+import type { JsonValue } from "../../../src/domain/jsonValue.js";+import { compareWebCaptures } from "../../../src/domain/webCaptureDiff.js";+import { compareWebCapturesInputSchema } from "../../../src/domain/webCaptureDiffSchemas.js";+import { describe, expect, it } from "vitest";import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";@@ -292,8 +297,8 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {const serialized = JSON.stringify(result.value);expect(serialized).toContain("tool-secret");expect(serialized).toContain("tool-source-secret");- for (const secret of ["schema-secret", "private-tool-secret"])- expect(serialized).not.toContain(secret);+ expect(serialized).toContain("schema-secret");+ expect(serialized).not.toContain("private-tool-secret");const methods = browser.commands.map(({ method }) => method);expect(methods).toContain("WebMCP.enable");expect(methods).not.toContain("WebMCP.invokeTool");@@ -406,6 +411,85 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {});describe("CdpBrowserProvider WebMCP inventory completeness", () => {+ it("compares full untrusted declarations independently of object-key order", async () => {+ const declaration: JsonValue = {+ type: "object",+ properties: { value: { type: "string", enum: ["one", "two"] } },+ required: ["value"],+ $ref: "https://untrusted.invalid/schema.json",+ examples: [{ token: "caller-schema-value" }],+ };+ const options: { webMcpTools: boolean; webMcpInputSchema: JsonValue } = {+ webMcpTools: true,+ webMcpInputSchema: declaration,+ };+ const browser = await startFakeCdpBrowser(options);+ trackBrowser(browser);+ const provider = new CdpBrowserProvider();+ const input = {+ cdp_endpoint: browser.endpoint,+ allowed_origins: [browser.allowedOrigin],+ target_id: "allowed-page",+ observation_ms: 0,+ };+ const inspection = await provider.inspectPage(+ inspectWebPageInputSchema.parse(input),+ );+ if (!inspection.ok) throw inspection.error;+ const discover = async () => {+ const result = await provider.discoverWebMcpTools(+ discoverWebMcpToolsInputSchema.parse(input),+ );+ if (!result.ok) throw result.error;+ return result.value;+ };+ const before = await discover();+ expect(before.tools.items[0]).toMatchObject({+ input_schema: declaration,+ input_schema_sha256: digestCanonicalValue(declaration),+ trust: "page-declared-untrusted",+ });+ const compare = async (schema: JsonValue) => {+ options.webMcpInputSchema = schema;+ const after = await discover();+ const diff = compareWebCaptures(+ compareWebCapturesInputSchema.parse({+ before: { inspection: inspection.value, webmcp: before },+ after: { inspection: inspection.value, webmcp: after },+ }),+ );+ return { after, dimension: diff.dimensions.webmcp };+ };+ const reordered = Object.fromEntries(Object.entries(declaration).reverse());+ const equivalent = await compare(reordered);+ expect(equivalent.dimension).toMatchObject({+ status: "unknown",+ total_changes: 0,+ });+ expect(equivalent.after.tools.items[0]?.input_schema_sha256).toBe(+ before.tools.items[0]?.input_schema_sha256,+ );+ for (const changed of [+ {+ ...declaration,+ properties: { value: { type: "number", enum: ["one", "two"] } },+ },+ { ...declaration, required: [] },+ {+ ...declaration,+ properties: { value: { type: "string", enum: ["two", "three"] } },+ },+ false,+ ]) {+ const result = await compare(changed);+ expect(result.dimension).toMatchObject({+ status: "changed",+ total_changes: 1,+ changes: [expect.objectContaining({ change: "modified" })],+ });+ }+ });+it("retains every field in a large declared WebMCP input schema", async () => {const propertyCount = 5_001;const browser = await startFakeCdpBrowser({@@ -423,17 +507,21 @@ describe("CdpBrowserProvider WebMCP inventory completeness", () => {);if (!result.ok) throw result.error;- const shape = result.value.tools.items[0]?.input_schema_shape;- expect(- shape?.properties.filter(({ path }) =>- path.startsWith("/properties/field_"),- ),- ).toHaveLength(propertyCount * 2);- expect(shape?.properties).toContainEqual({- path: "/properties/field_5000/type",- types: ["string"],- observations: 1,+ const tool = result.value.tools.items[0];+ expect(tool?.input_schema).toMatchObject({+ type: "object",+ properties: { field_5000: { type: "string" } },});+ if (+ tool?.input_schema === null ||+ typeof tool?.input_schema !== "object" ||+ Array.isArray(tool.input_schema)+ )+ throw new Error("Expected an observed schema object");+ expect(Object.keys(tool.input_schema.properties ?? {})).toHaveLength(+ propertyCount,+ );+ expect(tool.input_schema_sha256).toMatch(/^[a-f0-9]{64}$/u);});});diff --git a/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts b/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.tsindex 0c51f200c..e079bead0 100644--- a/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts+++ b/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts@@ -254,9 +254,15 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", ()request: {root_type: "object",properties: expect.arrayContaining([- expect.objectContaining({ path: "/token", types: ["string"] }),expect.objectContaining({- path: "/filters/active",+ path: [{ kind: "property", name: "token" }],+ types: ["string"],+ }),+ expect.objectContaining({+ path: [+ { kind: "property", name: "filters" },+ { kind: "property", name: "active" },+ ],types: ["boolean"],}),]),@@ -265,10 +271,20 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", ()root_type: "object",properties: expect.arrayContaining([expect.objectContaining({- path: "/result/token",+ path: [+ { kind: "property", name: "result" },+ { kind: "property", name: "token" },+ ],types: ["string"],}),- expect.objectContaining({ path: "/items/*/id", types: ["number"] }),+ expect.objectContaining({+ path: [+ { kind: "property", name: "items" },+ { kind: "array-element" },+ { kind: "property", name: "id" },+ ],+ types: ["number"],+ }),]),},});@@ -279,7 +295,10 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", ()format: "json",json_shape: expect.objectContaining({properties: expect.arrayContaining([- expect.objectContaining({ path: "/token", types: ["string"] }),+ expect.objectContaining({+ path: [{ kind: "property", name: "token" }],+ types: ["string"],+ }),]),}),}),diff --git a/tests/boundary/browser/cdpJsonShapeComparison.test.ts b/tests/boundary/browser/cdpJsonShapeComparison.test.tsindex 23890f682..e6dfa8ef7 100644--- a/tests/boundary/browser/cdpJsonShapeComparison.test.ts+++ b/tests/boundary/browser/cdpJsonShapeComparison.test.ts@@ -63,6 +63,32 @@ describe.each<BodySource>(["request", "response", "base64 response"])(},);+ it.each([+ { name: "scalar array types", before: "[123]", after: '["a"]' },+ { name: "mixed array types", before: '[1,"a"]', after: "[1,true]" },+ { name: "nested arrays", before: "[[1],null]", after: '[["a"],null]' },+ {+ name: "literal star properties",+ before: '{"items":[{"*":1},[true]]}',+ after: '{"items":[{"*":true},[1]]}',+ },+ ])("compares $name without retaining values", async ({ before, after }) => {+ const length = Math.max(+ Buffer.byteLength(before),+ Buffer.byteLength(after),+ );+ const captures = comparableCaptures(+ source,+ before + " ".repeat(length - Buffer.byteLength(before)),+ after + " ".repeat(length - Buffer.byteLength(after)),+ );+ const result = await compareCaptures(...captures);+ expect(result.dimensions.network).toMatchObject({+ status: "changed",+ total_changes: 1,+ });+ });+it.each([{ name: "a type change", after: '{"é":null,"e\u0301":null}' },{ name: "a removed key", after: '{"e\u0301":null}' },@@ -94,6 +120,63 @@ describe.each<BodySource>(["request", "response", "base64 response"])(},);+describe("selected JSON body-shape coverage", () => {+ it.each(["unavailable", "partial", "truncated"] as const)(+ "keeps %s coverage unknown without reporting an availability change",+ async (coverage) => {+ const before = captureBody("request", "[123]");+ const after = structuredClone(before);+ for (const capture of [before, after])+ capture.completeness.attach_limited_sections = [];+ const request = after.network.requests[0];+ if (request === undefined) throw new Error("Expected request");+ if (coverage === "truncated")+ after.completeness.truncated_sections.push("json_body_shapes");+ else {+ request.body_shapes.status = coverage;+ request.body_shapes.response = null;+ if (coverage === "unavailable") request.body_shapes.request = null;+ after.completeness.unavailable_sections.push("json_body_shapes");+ }+ expect(+ (await compareCaptures(before, after)).dimensions.network,+ ).toMatchObject({ status: "unknown", total_changes: 0 });+ expect(+ (await compareCaptures(after, after)).dimensions.network.status,+ ).toBe("unknown");+ request.status = 503;+ expect(+ (await compareCaptures(before, after)).dimensions.network.status,+ ).toBe("changed");+ },+ );++ it("ignores shapes when either capture did not request them", async () => {+ const before = captureBody("request", "[123]");+ const after = structuredClone(before);+ for (const capture of [before, after])+ capture.completeness.attach_limited_sections = [];+ after.completeness.excluded.push({+ section: "json_body_shapes",+ reason: "not_approved",+ count: null,+ });+ after.completeness.policy_filtered_sections.push("json_body_shapes");+ for (const request of after.network.requests)+ request.body_shapes = {+ status: "not_approved",+ request: null,+ response: null,+ };+ expect(+ (await compareCaptures(before, after)).dimensions.network,+ ).toMatchObject({ status: "unchanged", total_changes: 0 });+ expect(+ (await compareCaptures(after, after)).dimensions.network.status,+ ).toBe("unchanged");+ });+});+const comparableCaptures = (source: BodySource,beforeBody: string,diff --git a/tests/fixtures/fakeCdpBrowserEvents.ts b/tests/fixtures/fakeCdpBrowserEvents.tsindex 5129f74b8..dda7ba3cd 100644--- a/tests/fixtures/fakeCdpBrowserEvents.ts+++ b/tests/fixtures/fakeCdpBrowserEvents.ts@@ -49,7 +49,7 @@ const emitWebMcpEvents = (description: "Search orders; authorization=Bearer tool-secret",frameId: "frame-main",backendNodeId: 42,- inputSchema: {+ inputSchema: options.webMcpInputSchema ?? {type: "object",properties: inputSchemaProperties,required: ["orderId"],diff --git a/tests/fixtures/fakeCdpBrowserTypes.ts b/tests/fixtures/fakeCdpBrowserTypes.tsindex 9abd64992..00d8807c5 100644--- a/tests/fixtures/fakeCdpBrowserTypes.ts+++ b/tests/fixtures/fakeCdpBrowserTypes.ts@@ -1,3 +1,4 @@+import type { JsonValue } from "../../src/domain/jsonValue.js";export interface FakeCdpCommand {readonly id: number;readonly method: string;@@ -100,6 +101,7 @@ export interface FakeOptions {readonly webMcpSameUrlRegistrations?: "retain" | "remove-second";readonly webMcpFrameCount?: number;readonly webMcpSchemaPropertyCount?: number;+ readonly webMcpInputSchema?: JsonValue;readonly webMcpChildLeavesScope?: boolean;readonly webMcpChildTransientBlank?: boolean;readonly webMcpChildRecoversAfterTransient?: boolean;