feat: add web and Electron reverse-engineering workflows
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Stable browser sections used by coverage and omission accounting. */
|
||||
const browserSectionSchema = z.enum([
|
||||
"frames",
|
||||
"dom",
|
||||
"accessibility",
|
||||
"scripts",
|
||||
"script_sources",
|
||||
"resources",
|
||||
"network_requests",
|
||||
"network_initiators",
|
||||
"console_events",
|
||||
"console_text",
|
||||
"websocket_connections",
|
||||
"websocket_frames",
|
||||
"websocket_shapes",
|
||||
"json_body_shapes",
|
||||
"workers",
|
||||
"storage",
|
||||
"storage_keys",
|
||||
"metadata",
|
||||
"webmcp_tools",
|
||||
"screenshot",
|
||||
"source_maps",
|
||||
"timeline",
|
||||
]);
|
||||
export type BrowserSection = z.infer<typeof browserSectionSchema>;
|
||||
|
||||
/** Why an eligible browser observation was not retained. */
|
||||
const browserExclusionReasonSchema = z.enum([
|
||||
"disallowed_origin",
|
||||
"unsupported_url",
|
||||
"unattributed_origin",
|
||||
"not_approved",
|
||||
"out_of_target_scope",
|
||||
"provider_unavailable",
|
||||
"invalid_protocol_value",
|
||||
]);
|
||||
export type BrowserExclusionReason = z.infer<
|
||||
typeof browserExclusionReasonSchema
|
||||
>;
|
||||
|
||||
const browserExclusionSchema = z.object({
|
||||
section: browserSectionSchema,
|
||||
reason: browserExclusionReasonSchema,
|
||||
count: z.number().int().min(0).nullable(),
|
||||
});
|
||||
export type BrowserExclusion = z.infer<typeof browserExclusionSchema>;
|
||||
|
||||
const browserDroppedEventsSchema = z.object({
|
||||
scripts: z.number().int().min(0),
|
||||
network_requests: z.number().int().min(0),
|
||||
console_events: z.number().int().min(0),
|
||||
websocket_connections: z.number().int().min(0),
|
||||
websocket_frames: z.number().int().min(0),
|
||||
webmcp_tools: z.number().int().min(0),
|
||||
timeline_events: z.number().int().min(0),
|
||||
total: z.number().int().min(0),
|
||||
});
|
||||
export type BrowserDroppedEvents = z.infer<typeof browserDroppedEventsSchema>;
|
||||
export type BrowserDroppedEventKind = Exclude<
|
||||
keyof BrowserDroppedEvents,
|
||||
"total"
|
||||
>;
|
||||
|
||||
const browserCompletenessConditionSchema = z.enum([
|
||||
"complete_within_window",
|
||||
"policy_filtered",
|
||||
"attach_limited",
|
||||
"truncated",
|
||||
]);
|
||||
|
||||
/** Explicit, non-lossy coverage semantics for a bounded browser observation. */
|
||||
export const browserCompletenessSchema = z.object({
|
||||
status: browserCompletenessConditionSchema,
|
||||
conditions: z.array(browserCompletenessConditionSchema).min(1).max(3),
|
||||
policy_filtered_sections: z.array(browserSectionSchema),
|
||||
attach_limited_sections: z.array(browserSectionSchema),
|
||||
truncated_sections: z.array(browserSectionSchema),
|
||||
unavailable_sections: z.array(browserSectionSchema),
|
||||
excluded: z.array(browserExclusionSchema),
|
||||
dropped_events: browserDroppedEventsSchema,
|
||||
});
|
||||
export type BrowserCompleteness = z.infer<typeof browserCompletenessSchema>;
|
||||
|
||||
/** Build canonical completeness output from one adapter-owned capture ledger. */
|
||||
export const classifyBrowserCompleteness = (input: {
|
||||
readonly policyFilteredSections: ReadonlySet<BrowserSection>;
|
||||
readonly attachLimitedSections: ReadonlySet<BrowserSection>;
|
||||
readonly truncatedSections: ReadonlySet<BrowserSection>;
|
||||
readonly unavailableSections: ReadonlySet<BrowserSection>;
|
||||
readonly excluded: readonly BrowserExclusion[];
|
||||
readonly droppedEvents: Omit<BrowserDroppedEvents, "total">;
|
||||
}): BrowserCompleteness => {
|
||||
const policyFiltered = input.policyFilteredSections.size > 0;
|
||||
const truncated =
|
||||
input.truncatedSections.size > 0 ||
|
||||
Object.values(input.droppedEvents).some((count) => count > 0);
|
||||
const attachLimited =
|
||||
input.attachLimitedSections.size > 0 || input.unavailableSections.size > 0;
|
||||
const status = truncated
|
||||
? "truncated"
|
||||
: policyFiltered
|
||||
? "policy_filtered"
|
||||
: attachLimited
|
||||
? "attach_limited"
|
||||
: "complete_within_window";
|
||||
const conditions = [
|
||||
...(attachLimited ? (["attach_limited"] as const) : []),
|
||||
...(policyFiltered ? (["policy_filtered"] as const) : []),
|
||||
...(truncated ? (["truncated"] as const) : []),
|
||||
];
|
||||
const droppedTotal = Object.values(input.droppedEvents).reduce(
|
||||
(sum, count) => sum + count,
|
||||
0,
|
||||
);
|
||||
return browserCompletenessSchema.parse({
|
||||
status,
|
||||
conditions:
|
||||
conditions.length === 0 ? ["complete_within_window"] : conditions,
|
||||
policy_filtered_sections: sortedSections(input.policyFilteredSections),
|
||||
attach_limited_sections: sortedSections(input.attachLimitedSections),
|
||||
truncated_sections: sortedSections(input.truncatedSections),
|
||||
unavailable_sections: sortedSections(input.unavailableSections),
|
||||
excluded: canonicalExclusions(input.excluded),
|
||||
dropped_events: { ...input.droppedEvents, total: droppedTotal },
|
||||
});
|
||||
};
|
||||
|
||||
const sortedSections = (
|
||||
sections: ReadonlySet<BrowserSection>,
|
||||
): BrowserSection[] => [...sections].sort();
|
||||
|
||||
const canonicalExclusions = (
|
||||
exclusions: readonly BrowserExclusion[],
|
||||
): BrowserExclusion[] =>
|
||||
[...exclusions].sort(
|
||||
(left, right) =>
|
||||
left.section.localeCompare(right.section) ||
|
||||
left.reason.localeCompare(right.reason),
|
||||
);
|
||||
@@ -1,5 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { browserCompletenessSchema } from "./browserCompleteness.js";
|
||||
import { webTextArtifactSchema } from "./webContentArtifact.js";
|
||||
import { jsonShapeSchema } from "./jsonShape.js";
|
||||
|
||||
const parseExactOrigin = (value: string): string | undefined => {
|
||||
let url: URL;
|
||||
try {
|
||||
@@ -78,7 +82,7 @@ export const browserEndpointSchema = z
|
||||
return url.origin;
|
||||
});
|
||||
|
||||
const allowedOriginsSchema = z
|
||||
export const browserAllowedOriginsSchema = z
|
||||
.array(browserOriginSchema)
|
||||
.min(1)
|
||||
.max(32)
|
||||
@@ -86,7 +90,7 @@ const allowedOriginsSchema = z
|
||||
|
||||
const approvedBrowserInput = {
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
allowed_origins: allowedOriginsSchema,
|
||||
allowed_origins: browserAllowedOriginsSchema,
|
||||
approved: z
|
||||
.literal(true)
|
||||
.describe("Explicit approval for browser observation"),
|
||||
@@ -103,6 +107,18 @@ const browserInspectionLimitsSchema = z.object({
|
||||
max_frames: z.number().int().min(1).max(1_000).default(200),
|
||||
max_dom_nodes: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_ax_nodes: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_ax_text_field_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16 * 1_024)
|
||||
.default(1_024),
|
||||
max_total_ax_text_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(1_024 * 1_024)
|
||||
.default(64 * 1_024),
|
||||
max_scripts: z.number().int().min(1).max(1_000).default(200),
|
||||
max_resources: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_workers: z.number().int().min(1).max(5_000).default(500),
|
||||
@@ -121,13 +137,53 @@ const browserInspectionLimitsSchema = z.object({
|
||||
.default(4 * 1_024 * 1_024),
|
||||
max_network_events: z.number().int().min(1).max(10_000).default(1_000),
|
||||
max_console_events: z.number().int().min(1).max(2_000).default(200),
|
||||
max_console_text_field_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16 * 1_024)
|
||||
.default(1_024),
|
||||
max_total_console_text_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(1_024 * 1_024)
|
||||
.default(64 * 1_024),
|
||||
max_json_body_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(4 * 1_024 * 1_024)
|
||||
.default(1_024 * 1_024),
|
||||
max_total_json_body_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16 * 1_024 * 1_024)
|
||||
.default(4 * 1_024 * 1_024),
|
||||
max_json_shape_nodes: z.number().int().min(1).max(100_000).default(5_000),
|
||||
max_json_shape_depth: z.number().int().min(1).max(100).default(20),
|
||||
max_websocket_events: z.number().int().min(1).max(5_000).default(500),
|
||||
max_websocket_shape_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(1_024 * 1_024)
|
||||
.default(64 * 1_024),
|
||||
max_total_websocket_shape_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16 * 1_024 * 1_024)
|
||||
.default(1_024 * 1_024),
|
||||
});
|
||||
|
||||
const DEFAULT_BROWSER_INSPECTION_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: 64 * 1_024,
|
||||
max_scripts: 200,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
@@ -136,7 +192,15 @@ const DEFAULT_BROWSER_INSPECTION_LIMITS = {
|
||||
max_total_script_source_bytes: 4 * 1_024 * 1_024,
|
||||
max_network_events: 1_000,
|
||||
max_console_events: 200,
|
||||
max_console_text_field_bytes: 1_024,
|
||||
max_total_console_text_bytes: 64 * 1_024,
|
||||
max_json_body_bytes: 1_024 * 1_024,
|
||||
max_total_json_body_bytes: 4 * 1_024 * 1_024,
|
||||
max_json_shape_nodes: 5_000,
|
||||
max_json_shape_depth: 20,
|
||||
max_websocket_events: 500,
|
||||
max_websocket_shape_bytes: 64 * 1_024,
|
||||
max_total_websocket_shape_bytes: 1_024 * 1_024,
|
||||
} as const;
|
||||
|
||||
/** Public input for one passive, bounded inspection of an existing page. */
|
||||
@@ -145,6 +209,13 @@ export const inspectWebPageInputSchema = z
|
||||
...approvedBrowserInput,
|
||||
target_id: z.string().trim().min(1).max(256),
|
||||
observation_ms: z.number().int().min(0).max(10_000).default(500),
|
||||
include_accessibility_text: z.boolean().default(false),
|
||||
include_console_text: z.boolean().default(false),
|
||||
console_text_approved: z.boolean().default(false),
|
||||
include_json_body_shapes: z.boolean().default(false),
|
||||
json_body_schema_approved: z.boolean().default(false),
|
||||
include_websocket_shapes: z.boolean().default(false),
|
||||
websocket_shape_approved: z.boolean().default(false),
|
||||
include_script_sources: z.boolean().default(false),
|
||||
include_storage_keys: z.boolean().default(false),
|
||||
limits: browserInspectionLimitsSchema.default(
|
||||
@@ -161,6 +232,66 @@ export const inspectWebPageInputSchema = z
|
||||
path: ["limits", "max_script_source_bytes"],
|
||||
message: "Per-script source limit cannot exceed the total source limit",
|
||||
});
|
||||
for (const [include, approved, path, message] of [
|
||||
[
|
||||
input.include_console_text,
|
||||
input.console_text_approved,
|
||||
"console_text_approved",
|
||||
"Console text capture requires separate approval",
|
||||
],
|
||||
[
|
||||
input.include_json_body_shapes,
|
||||
input.json_body_schema_approved,
|
||||
"json_body_schema_approved",
|
||||
"JSON body schema capture requires separate approval",
|
||||
],
|
||||
[
|
||||
input.include_websocket_shapes,
|
||||
input.websocket_shape_approved,
|
||||
"websocket_shape_approved",
|
||||
"WebSocket shape capture requires separate approval",
|
||||
],
|
||||
] as const)
|
||||
if (include && !approved)
|
||||
context.addIssue({ code: "custom", path: [path], message });
|
||||
if (
|
||||
input.limits.max_console_text_field_bytes >
|
||||
input.limits.max_total_console_text_bytes
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["limits", "max_console_text_field_bytes"],
|
||||
message:
|
||||
"Per-field console text limit cannot exceed the total text limit",
|
||||
});
|
||||
if (
|
||||
input.limits.max_json_body_bytes > input.limits.max_total_json_body_bytes
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["limits", "max_json_body_bytes"],
|
||||
message: "Per-body JSON limit cannot exceed the total body limit",
|
||||
});
|
||||
if (
|
||||
input.limits.max_websocket_shape_bytes >
|
||||
input.limits.max_total_websocket_shape_bytes
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["limits", "max_websocket_shape_bytes"],
|
||||
message:
|
||||
"Per-frame WebSocket limit cannot exceed the total frame limit",
|
||||
});
|
||||
if (
|
||||
input.limits.max_ax_text_field_bytes >
|
||||
input.limits.max_total_ax_text_bytes
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["limits", "max_ax_text_field_bytes"],
|
||||
message:
|
||||
"Per-field accessibility text limit cannot exceed the total text limit",
|
||||
});
|
||||
});
|
||||
|
||||
export type ListBrowserTargetsInput = z.infer<
|
||||
@@ -280,13 +411,22 @@ const browserScriptSourceSchema = z.discriminatedUnion("included", [
|
||||
z.object({ included: z.literal(false), reason: z.string() }),
|
||||
z.object({
|
||||
included: z.literal(true),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
bytes: z.number().int().min(0),
|
||||
content: z.string(),
|
||||
artifact: webTextArtifactSchema,
|
||||
}),
|
||||
]);
|
||||
const browserResourceReconciliationSchema = z.discriminatedUnion("status", [
|
||||
z.object({ status: z.literal("exact"), resource_key: z.string() }),
|
||||
z.object({
|
||||
status: z.literal("ambiguous"),
|
||||
candidate_resource_keys: z.array(z.string()),
|
||||
}),
|
||||
z.object({
|
||||
status: z.literal("unmatched"),
|
||||
reason: z.literal("no_exact_sanitized_url"),
|
||||
}),
|
||||
]);
|
||||
const browserScriptSchema = z.object({
|
||||
script_id: z.string(),
|
||||
script_key: z.string().regex(/^scr_[a-f0-9]{64}(?:_[0-9]+)?$/u),
|
||||
url: z.string(),
|
||||
origin: z.string().nullable(),
|
||||
cdp_hash: z.string(),
|
||||
@@ -294,9 +434,11 @@ const browserScriptSchema = z.object({
|
||||
is_module: z.boolean(),
|
||||
language: z.string().nullable(),
|
||||
source_map_url: z.string().nullable(),
|
||||
resource_reconciliation: browserResourceReconciliationSchema,
|
||||
source: browserScriptSourceSchema,
|
||||
});
|
||||
const browserResourceSchema = z.object({
|
||||
resource_key: z.string().regex(/^res_[a-f0-9]{64}$/u),
|
||||
url: z.string(),
|
||||
origin: z.string().nullable(),
|
||||
type: z.string(),
|
||||
@@ -318,6 +460,17 @@ const browserNetworkRequestSchema = z.object({
|
||||
line: z.number().int().min(0).nullable(),
|
||||
column: z.number().int().min(0).nullable(),
|
||||
}),
|
||||
body_shapes: z.object({
|
||||
status: z.enum([
|
||||
"not_approved",
|
||||
"included",
|
||||
"partial",
|
||||
"unavailable",
|
||||
"truncated",
|
||||
]),
|
||||
request: jsonShapeSchema.nullable(),
|
||||
response: jsonShapeSchema.nullable(),
|
||||
}),
|
||||
});
|
||||
const browserConsoleEventSchema = z.object({
|
||||
type: z.string(),
|
||||
@@ -326,12 +479,31 @@ const browserConsoleEventSchema = z.object({
|
||||
url: z.string().nullable(),
|
||||
line: z.number().int().min(0).nullable(),
|
||||
column: z.number().int().min(0).nullable(),
|
||||
text_capture: z.object({
|
||||
status: z.enum(["not_approved", "included", "truncated"]),
|
||||
values: z.array(
|
||||
z.object({
|
||||
argument_index: z.number().int().min(0),
|
||||
type: z.string(),
|
||||
text: z.string(),
|
||||
}),
|
||||
),
|
||||
retained_bytes: z.number().int().min(0),
|
||||
truncated_values: z.number().int().min(0),
|
||||
}),
|
||||
});
|
||||
const browserWebSocketEventSchema = z.object({
|
||||
request_id: z.string(),
|
||||
direction: z.enum(["sent", "received"]),
|
||||
opcode: z.number().int().min(0),
|
||||
payload_bytes: z.number().int().min(0),
|
||||
payload_shape: z
|
||||
.object({
|
||||
format: z.enum(["json", "text", "binary"]),
|
||||
json_shape: jsonShapeSchema.nullable(),
|
||||
truncated: z.boolean(),
|
||||
})
|
||||
.nullable(),
|
||||
});
|
||||
const browserWorkerSchema = z.object({
|
||||
target_id: z.string(),
|
||||
@@ -340,10 +512,80 @@ const browserWorkerSchema = z.object({
|
||||
origin: z.string().nullable(),
|
||||
attached: z.boolean(),
|
||||
});
|
||||
const browserCspSourceSchema = z.object({
|
||||
kind: z.enum([
|
||||
"keyword",
|
||||
"scheme",
|
||||
"approved_origin",
|
||||
"external_origin",
|
||||
"other",
|
||||
]),
|
||||
value: z.string().nullable(),
|
||||
});
|
||||
const browserLinkMetadataSchema = z.object({
|
||||
href: z.string().nullable(),
|
||||
destination_scope: z.enum(["approved", "outside_policy", "unsupported"]),
|
||||
rel: z.array(z.string()),
|
||||
as: z.string().nullable(),
|
||||
type: z.string().nullable(),
|
||||
crossorigin: z.string().nullable(),
|
||||
});
|
||||
const browserAgentHintSchema = z.object({
|
||||
mechanism: z.enum([
|
||||
"link_rel",
|
||||
"dom_link_rel",
|
||||
"well_known_resource",
|
||||
"response_header",
|
||||
]),
|
||||
declaration: z.string(),
|
||||
url: z.string().nullable(),
|
||||
trust: z.literal("page-declared-untrusted"),
|
||||
});
|
||||
const browserSafeMetadataSchema = z.object({
|
||||
responses: z.array(
|
||||
z.object({
|
||||
request_id: z.string(),
|
||||
url: z.string(),
|
||||
mime_type: z.string().nullable(),
|
||||
content_length: z.number().int().min(0).nullable(),
|
||||
content_encoding: z.string().nullable(),
|
||||
csp: z.object({
|
||||
directives: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
sources: z.array(browserCspSourceSchema),
|
||||
}),
|
||||
),
|
||||
nonce_count: z.number().int().min(0),
|
||||
hash_count: z.number().int().min(0),
|
||||
}),
|
||||
links: z.array(browserLinkMetadataSchema),
|
||||
policies: z.object({
|
||||
coop: z.string().nullable(),
|
||||
coep: z.string().nullable(),
|
||||
corp: z.string().nullable(),
|
||||
referrer_policy: z.string().nullable(),
|
||||
x_content_type_options: z.string().nullable(),
|
||||
permissions_policy_features: z.array(z.string()),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
dom_urls: z.array(
|
||||
z.object({
|
||||
node_index: z.number().int().min(0),
|
||||
attribute: z.enum(["href", "src", "action", "formaction", "poster"]),
|
||||
url: z.string().nullable(),
|
||||
destination_scope: z.enum(["approved", "outside_policy", "unsupported"]),
|
||||
}),
|
||||
),
|
||||
agent_hints: z.array(browserAgentHintSchema),
|
||||
excluded_dom_urls: z.number().int().min(0),
|
||||
headers_allowlisted: z.literal(true),
|
||||
});
|
||||
|
||||
/** Provider-neutral normalized result for one passive web-page observation. */
|
||||
export const webPageInspectionSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
schema_version: z.literal(2),
|
||||
browser: browserVersionSchema,
|
||||
target: browserTargetSchema,
|
||||
capture_window: z.object({
|
||||
@@ -351,11 +593,7 @@ export const webPageInspectionSchema = z.object({
|
||||
ended_at: z.iso.datetime(),
|
||||
observation_ms: z.number().int().min(0),
|
||||
}),
|
||||
completeness: z.object({
|
||||
status: z.enum(["complete", "truncated"]),
|
||||
truncated_sections: z.array(z.string()),
|
||||
dropped_events: z.number().int().min(0),
|
||||
}),
|
||||
completeness: browserCompletenessSchema,
|
||||
frames: z.array(browserFrameSchema),
|
||||
dom: z.object({
|
||||
total_nodes: z.number().int().min(0),
|
||||
@@ -363,6 +601,12 @@ export const webPageInspectionSchema = z.object({
|
||||
}),
|
||||
accessibility: z.object({
|
||||
total_nodes: z.number().int().min(0),
|
||||
text_capture: z.object({
|
||||
status: z.enum(["not_approved", "included", "truncated", "unavailable"]),
|
||||
retained_bytes: z.number().int().min(0),
|
||||
excluded_fields: z.number().int().min(0),
|
||||
truncated_fields: z.number().int().min(0),
|
||||
}),
|
||||
nodes: z.array(browserAxNodeSchema),
|
||||
}),
|
||||
scripts: z.object({
|
||||
@@ -382,6 +626,7 @@ export const webPageInspectionSchema = z.object({
|
||||
prior_activity_available: z.literal(false),
|
||||
}),
|
||||
workers: z.array(browserWorkerSchema),
|
||||
metadata: browserSafeMetadataSchema,
|
||||
storage: z.object({
|
||||
origin: z.string(),
|
||||
usage_bytes: z.number().min(0).nullable(),
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
browserAllowedOriginsSchema,
|
||||
browserEndpointSchema,
|
||||
} from "./browserObservation.js";
|
||||
import { browserCompletenessSchema } from "./browserCompleteness.js";
|
||||
|
||||
/** Input for a bounded, navigation-aware browser observation window. */
|
||||
export const observeWebSessionInputSchema = z.object({
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
allowed_origins: browserAllowedOriginsSchema,
|
||||
target_id: z.string().trim().min(1).max(256),
|
||||
approved: z.literal(true),
|
||||
observation_ms: z.number().int().min(1).max(60_000).default(10_000),
|
||||
max_timeline_events: z.number().int().min(1).max(20_000).default(2_000),
|
||||
});
|
||||
export type ObserveWebSessionInput = z.infer<
|
||||
typeof observeWebSessionInputSchema
|
||||
>;
|
||||
|
||||
const timelineEventSchema = z.object({
|
||||
sequence: z.number().int().min(1),
|
||||
type: z.enum([
|
||||
"navigation_requested",
|
||||
"navigation_committed",
|
||||
"same_origin_reload",
|
||||
"same_document_navigation",
|
||||
"redirect",
|
||||
"load_failed",
|
||||
"lifecycle",
|
||||
"target_terminated",
|
||||
]),
|
||||
timestamp: z.number().min(0),
|
||||
frame_id: z.string().nullable(),
|
||||
loader_id: z.string().nullable(),
|
||||
request_id: z.string().nullable(),
|
||||
url: z.string().nullable(),
|
||||
destination_scope: z
|
||||
.enum(["approved", "outside_policy", "unsupported"])
|
||||
.nullable(),
|
||||
detail: z.string().nullable(),
|
||||
});
|
||||
|
||||
/** Navigation-aware session result for external user actions. */
|
||||
export const webObservationSessionSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
browser: z.object({
|
||||
product: z.string(),
|
||||
protocol_version: z.string(),
|
||||
revision: z.string(),
|
||||
user_agent: z.string(),
|
||||
js_version: z.string(),
|
||||
}),
|
||||
target: z.object({
|
||||
target_id: z.string(),
|
||||
initial_url: z.string(),
|
||||
final_url: z.string().nullable(),
|
||||
}),
|
||||
window: z.object({
|
||||
armed_at: z.iso.datetime(),
|
||||
ended_at: z.iso.datetime(),
|
||||
requested_ms: z.number().int().min(1),
|
||||
end_reason: z.enum([
|
||||
"window_elapsed",
|
||||
"target_left_scope",
|
||||
"target_terminated",
|
||||
]),
|
||||
}),
|
||||
timeline: z.array(timelineEventSchema),
|
||||
completeness: browserCompletenessSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type WebObservationSession = z.infer<typeof webObservationSessionSchema>;
|
||||
@@ -0,0 +1,194 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { browserCompletenessSchema } from "./browserCompleteness.js";
|
||||
import { browserEndpointSchema } from "./browserObservation.js";
|
||||
import { webTextArtifactSchema } from "./webContentArtifact.js";
|
||||
|
||||
/** Absolute operator-approved filesystem roots for Electron file pages. */
|
||||
export const electronFileRootsSchema = z
|
||||
.array(
|
||||
z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(16_384)
|
||||
.refine(isAbsolute, "Electron file roots must be absolute paths"),
|
||||
)
|
||||
.min(1)
|
||||
.max(32)
|
||||
.transform((roots) => [...new Set(roots)].sort());
|
||||
|
||||
const approvedElectronInput = {
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
allowed_file_roots: electronFileRootsSchema,
|
||||
approved: z.literal(true),
|
||||
};
|
||||
|
||||
/** Input for listing root-confined file:// page targets from Electron CDP. */
|
||||
export const listElectronTargetsInputSchema = z.object({
|
||||
...approvedElectronInput,
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(200).default(100),
|
||||
});
|
||||
export type ListElectronTargetsInput = z.infer<
|
||||
typeof listElectronTargetsInputSchema
|
||||
>;
|
||||
|
||||
/** Input for passive structural inspection of one Electron file page. */
|
||||
export const inspectElectronPageInputSchema = z
|
||||
.object({
|
||||
...approvedElectronInput,
|
||||
target_id: z.string().trim().min(1).max(256),
|
||||
observation_ms: z.number().int().min(0).max(10_000).default(100),
|
||||
include_script_sources: z.boolean().default(false),
|
||||
source_capture_approved: z.boolean().default(false),
|
||||
limits: z
|
||||
.object({
|
||||
max_frames: z.number().int().min(1).max(1_000).default(200),
|
||||
max_dom_nodes: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_scripts: z.number().int().min(1).max(2_000).default(500),
|
||||
max_resources: z.number().int().min(1).max(10_000).default(2_000),
|
||||
max_script_source_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(4 * 1_024 * 1_024)
|
||||
.default(1_024 * 1_024),
|
||||
max_total_script_source_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16 * 1_024 * 1_024)
|
||||
.default(4 * 1_024 * 1_024),
|
||||
})
|
||||
.default({
|
||||
max_frames: 200,
|
||||
max_dom_nodes: 2_000,
|
||||
max_scripts: 500,
|
||||
max_resources: 2_000,
|
||||
max_script_source_bytes: 1_024 * 1_024,
|
||||
max_total_script_source_bytes: 4 * 1_024 * 1_024,
|
||||
}),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
if (input.include_script_sources && !input.source_capture_approved)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["source_capture_approved"],
|
||||
message: "Electron script source capture requires separate approval",
|
||||
});
|
||||
if (
|
||||
input.limits.max_script_source_bytes >
|
||||
input.limits.max_total_script_source_bytes
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["limits", "max_script_source_bytes"],
|
||||
message: "Per-script source limit cannot exceed the total source limit",
|
||||
});
|
||||
});
|
||||
export type InspectElectronPageInput = z.infer<
|
||||
typeof inspectElectronPageInputSchema
|
||||
>;
|
||||
|
||||
const browserVersionSchema = z.object({
|
||||
product: z.string(),
|
||||
protocol_version: z.string(),
|
||||
revision: z.string(),
|
||||
user_agent: z.string(),
|
||||
js_version: z.string(),
|
||||
});
|
||||
const electronTargetSchema = z.object({
|
||||
target_id: z.string(),
|
||||
type: z.string(),
|
||||
title: z.string(),
|
||||
file_path: z.string(),
|
||||
attached: z.boolean(),
|
||||
});
|
||||
|
||||
/** Root-filtered Electron file target inventory. */
|
||||
export const electronTargetListSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
browser: browserVersionSchema,
|
||||
targets: z.object({
|
||||
items: z.array(electronTargetSchema),
|
||||
offset: z.number().int().min(0),
|
||||
limit: z.number().int().min(1),
|
||||
total: z.number().int().min(0),
|
||||
next_offset: z.number().int().min(0).nullable(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
excluded: z.object({
|
||||
outside_root: z.number().int().min(0),
|
||||
unsupported_url: z.number().int().min(0),
|
||||
non_page: z.number().int().min(0),
|
||||
}),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type ElectronTargetList = z.infer<typeof electronTargetListSchema>;
|
||||
|
||||
const electronSourceSchema = z.discriminatedUnion("included", [
|
||||
z.object({ included: z.literal(false), reason: z.string() }),
|
||||
z.object({ included: z.literal(true), artifact: webTextArtifactSchema }),
|
||||
]);
|
||||
|
||||
/** Provider-neutral passive Electron file-page structure and script inventory. */
|
||||
export const electronPageInspectionSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
browser: browserVersionSchema,
|
||||
target: electronTargetSchema,
|
||||
capture_window: z.object({
|
||||
started_at: z.iso.datetime(),
|
||||
ended_at: z.iso.datetime(),
|
||||
observation_ms: z.number().int().min(0),
|
||||
}),
|
||||
completeness: browserCompletenessSchema,
|
||||
frames: z.array(
|
||||
z.object({
|
||||
frame_id: z.string(),
|
||||
parent_frame_id: z.string().nullable(),
|
||||
file_path: z.string(),
|
||||
}),
|
||||
),
|
||||
dom: z.object({
|
||||
total_nodes: z.number().int().min(0),
|
||||
nodes: z.array(
|
||||
z.object({
|
||||
index: z.number().int().min(0),
|
||||
parent_index: z.number().int().min(-1),
|
||||
node_type: z.number().int().min(0),
|
||||
node_name: z.string(),
|
||||
node_value_length: z.number().int().min(0),
|
||||
attribute_names: z.array(z.string()),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
scripts: z.object({
|
||||
total: z.number().int().min(0),
|
||||
items: z.array(
|
||||
z.object({
|
||||
script_key: z.string().regex(/^electron_script_[a-f0-9]{64}$/u),
|
||||
file_path: z.string(),
|
||||
cdp_hash: z.string(),
|
||||
length: z.number().int().min(0),
|
||||
is_module: z.boolean(),
|
||||
language: z.string().nullable(),
|
||||
source: electronSourceSchema,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
resources: z.array(
|
||||
z.object({
|
||||
resource_key: z.string().regex(/^electron_resource_[a-f0-9]{64}$/u),
|
||||
file_path: z.string(),
|
||||
type: z.string(),
|
||||
mime_type: z.string(),
|
||||
content_size: z.number().min(0).nullable(),
|
||||
}),
|
||||
),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type ElectronPageInspection = z.infer<
|
||||
typeof electronPageInspectionSchema
|
||||
>;
|
||||
+14
-1
@@ -144,12 +144,25 @@ export class ProviderAdapterError extends AnalysisError {
|
||||
}
|
||||
}
|
||||
|
||||
/** Public browser and Electron operations that can fail at a CDP boundary. */
|
||||
export type BrowserObservationOperation =
|
||||
| "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";
|
||||
|
||||
/** A bounded passive browser observation failed at its CDP boundary. */
|
||||
export class BrowserObservationError extends AnalysisError {
|
||||
readonly _tag = "BrowserObservationError";
|
||||
|
||||
constructor(
|
||||
readonly operation: "list_browser_targets" | "inspect_web_page",
|
||||
readonly operation: BrowserObservationOperation,
|
||||
readonly reason:
|
||||
| "endpoint_unreachable"
|
||||
| "invalid_endpoint_response"
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const jsonValueTypeSchema = z.enum([
|
||||
"object",
|
||||
"array",
|
||||
"string",
|
||||
"number",
|
||||
"boolean",
|
||||
"null",
|
||||
]);
|
||||
type JsonValueType = z.infer<typeof jsonValueTypeSchema>;
|
||||
|
||||
/** Value-free structural summary of one approved JSON payload. */
|
||||
export const jsonShapeSchema = z.object({
|
||||
root_type: jsonValueTypeSchema,
|
||||
node_count: z.number().int().min(1),
|
||||
max_depth_observed: z.number().int().min(0),
|
||||
properties: z.array(
|
||||
z.object({
|
||||
path: z.string(),
|
||||
types: z.array(jsonValueTypeSchema).min(1),
|
||||
observations: z.number().int().min(1),
|
||||
}),
|
||||
),
|
||||
truncated: z.boolean(),
|
||||
});
|
||||
export type JsonShape = z.infer<typeof jsonShapeSchema>;
|
||||
|
||||
export interface JsonShapeLimits {
|
||||
readonly maximumBytes: number;
|
||||
readonly maximumNodes: number;
|
||||
readonly maximumDepth: number;
|
||||
}
|
||||
|
||||
/** Parse approved JSON and immediately discard values after iterative shape inference. */
|
||||
export const inferJsonShape = (
|
||||
text: string,
|
||||
limits: JsonShapeLimits,
|
||||
): JsonShape | null => {
|
||||
if (Buffer.byteLength(text) > limits.maximumBytes) return null;
|
||||
let root: unknown;
|
||||
try {
|
||||
root = JSON.parse(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const properties = new Map<
|
||||
string,
|
||||
{ readonly types: Set<JsonValueType>; observations: number }
|
||||
>();
|
||||
const pending: Array<{
|
||||
readonly value: unknown;
|
||||
readonly path: string;
|
||||
readonly depth: number;
|
||||
}> = [{ value: root, path: "", depth: 0 }];
|
||||
let nodeCount = 0;
|
||||
let maxDepthObserved = 0;
|
||||
let truncated = false;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
if (nodeCount >= limits.maximumNodes) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
nodeCount += 1;
|
||||
maxDepthObserved = Math.max(maxDepthObserved, current.depth);
|
||||
if (current.depth >= limits.maximumDepth) {
|
||||
if (hasChildren(current.value)) truncated = true;
|
||||
continue;
|
||||
}
|
||||
if (Array.isArray(current.value)) {
|
||||
const capacity = Math.max(
|
||||
0,
|
||||
limits.maximumNodes - nodeCount - pending.length,
|
||||
);
|
||||
const retained = Math.min(current.value.length, capacity);
|
||||
if (retained < current.value.length) truncated = true;
|
||||
for (let index = retained - 1; index >= 0; index -= 1)
|
||||
pending.push({
|
||||
value: current.value[index],
|
||||
path: `${current.path}/*`,
|
||||
depth: current.depth + 1,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (!isRecord(current.value)) continue;
|
||||
const allEntries = Object.entries(current.value);
|
||||
const capacity = Math.max(
|
||||
0,
|
||||
limits.maximumNodes - nodeCount - pending.length,
|
||||
);
|
||||
const entries = allEntries.slice(0, capacity);
|
||||
if (entries.length < allEntries.length) truncated = true;
|
||||
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
||||
const entry = entries[index];
|
||||
if (entry === undefined) continue;
|
||||
const [name, value] = entry;
|
||||
const path = `${current.path}/${pointerName(name)}`.slice(0, 2_048);
|
||||
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;
|
||||
}
|
||||
pending.push({ value, path, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return jsonShapeSchema.parse({
|
||||
root_type: jsonValueType(root),
|
||||
node_count: nodeCount,
|
||||
max_depth_observed: maxDepthObserved,
|
||||
properties: [...properties.entries()]
|
||||
.map(([path, value]) => ({
|
||||
path,
|
||||
types: [...value.types].sort(),
|
||||
observations: value.observations,
|
||||
}))
|
||||
.sort((left, right) => left.path.localeCompare(right.path))
|
||||
.slice(0, limits.maximumNodes),
|
||||
truncated,
|
||||
});
|
||||
};
|
||||
|
||||
const jsonValueType = (value: unknown): JsonValueType => {
|
||||
if (value === null) return "null";
|
||||
if (Array.isArray(value)) return "array";
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
return "string";
|
||||
case "number":
|
||||
return "number";
|
||||
case "boolean":
|
||||
return "boolean";
|
||||
default:
|
||||
return "object";
|
||||
}
|
||||
};
|
||||
|
||||
const hasChildren = (value: unknown): boolean =>
|
||||
Array.isArray(value)
|
||||
? value.length > 0
|
||||
: isRecord(value) && Object.keys(value).length > 0;
|
||||
|
||||
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const pointerName = (value: string): string =>
|
||||
value.slice(0, 256).replaceAll("~", "~0").replaceAll("/", "~1");
|
||||
@@ -6,6 +6,7 @@ import { err, ok, type Result } from "./result.js";
|
||||
export type PermissionCapability =
|
||||
| "process_capture"
|
||||
| "browser_observe"
|
||||
| "electron_observe"
|
||||
| "evidence_read"
|
||||
| "evidence_write"
|
||||
| "investigation_input"
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { inspectWebPageInputSchema } from "./browserObservation.js";
|
||||
import { webTextArtifactSchema } from "./webContentArtifact.js";
|
||||
|
||||
const webBundleLimitsSchema = z.object({
|
||||
max_findings: z.number().int().min(1).max(10_000).default(1_000),
|
||||
max_ast_nodes: z.number().int().min(1).max(2_000_000).default(250_000),
|
||||
max_source_maps: z.number().int().min(1).max(1_000).default(100),
|
||||
max_source_map_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16 * 1_024 * 1_024)
|
||||
.default(4 * 1_024 * 1_024),
|
||||
max_total_source_map_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(64 * 1_024 * 1_024)
|
||||
.default(16 * 1_024 * 1_024),
|
||||
max_source_map_mappings: z.number().int().min(1).max(100_000).default(10_000),
|
||||
max_original_sources: z.number().int().min(1).max(20_000).default(2_000),
|
||||
});
|
||||
|
||||
/** Capture-and-analyze input with separate source and source-map approvals. */
|
||||
export const analyzeWebBundleInputSchema = inspectWebPageInputSchema
|
||||
.safeExtend({
|
||||
include_script_sources: z.literal(true).default(true),
|
||||
source_capture_approved: z.literal(true),
|
||||
fetch_source_maps: z.boolean().default(false),
|
||||
source_map_fetch_approved: z.boolean().default(false),
|
||||
analysis_limits: webBundleLimitsSchema.default({
|
||||
max_findings: 1_000,
|
||||
max_ast_nodes: 250_000,
|
||||
max_source_maps: 100,
|
||||
max_source_map_bytes: 4 * 1_024 * 1_024,
|
||||
max_total_source_map_bytes: 16 * 1_024 * 1_024,
|
||||
max_source_map_mappings: 10_000,
|
||||
max_original_sources: 2_000,
|
||||
}),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
if (input.fetch_source_maps && !input.source_map_fetch_approved)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["source_map_fetch_approved"],
|
||||
message: "Source-map network fetch requires separate approval",
|
||||
});
|
||||
if (
|
||||
input.analysis_limits.max_source_map_bytes >
|
||||
input.analysis_limits.max_total_source_map_bytes
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["analysis_limits", "max_source_map_bytes"],
|
||||
message:
|
||||
"Per-map source-map byte limit cannot exceed the aggregate limit",
|
||||
});
|
||||
});
|
||||
export type AnalyzeWebBundleInput = z.infer<typeof analyzeWebBundleInputSchema>;
|
||||
|
||||
const sourceLocationSchema = z.object({
|
||||
script_key: z.string(),
|
||||
line: z.number().int().min(1).nullable(),
|
||||
column: z.number().int().min(0).nullable(),
|
||||
});
|
||||
|
||||
const basisSchema = z.object({
|
||||
script_key: z.string(),
|
||||
artifact_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
line: z.number().int().min(1).nullable(),
|
||||
column: z.number().int().min(0).nullable(),
|
||||
detector: z.string(),
|
||||
});
|
||||
|
||||
const findingSchema = z.object({
|
||||
value: z.string(),
|
||||
mechanism: z.string(),
|
||||
location: sourceLocationSchema,
|
||||
});
|
||||
|
||||
const sourceMapSchema = z.object({
|
||||
script_key: z.string(),
|
||||
declared_url: z.string(),
|
||||
status: z.enum([
|
||||
"included",
|
||||
"fetch_failed",
|
||||
"invalid",
|
||||
"policy_filtered",
|
||||
"truncated",
|
||||
]),
|
||||
artifact: webTextArtifactSchema.nullable(),
|
||||
original_sources: z.array(
|
||||
z.object({
|
||||
source: z.string(),
|
||||
artifact: webTextArtifactSchema.nullable(),
|
||||
}),
|
||||
),
|
||||
original_module_edges: z.array(
|
||||
z.object({
|
||||
from_source: z.string(),
|
||||
kind: z.enum(["static_import", "dynamic_import", "require"]),
|
||||
specifier: z.string(),
|
||||
resolved_source: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
mappings: z.array(
|
||||
z.object({
|
||||
generated_line: z.number().int().min(1),
|
||||
generated_column: z.number().int().min(0),
|
||||
source: z.string(),
|
||||
original_line: z.number().int().min(1),
|
||||
original_column: z.number().int().min(0),
|
||||
name: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
limitation: z.string().nullable(),
|
||||
});
|
||||
|
||||
const webTextArtifactSummarySchema = z.object({
|
||||
uri: z.string().regex(/^rea:\/\/web-content\/sha256\/[a-f0-9]{64}$/u),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
bytes: z.number().int().min(0),
|
||||
media_type: z.string().min(1).max(256),
|
||||
charset: z.literal("utf-8"),
|
||||
text_available: z.literal(true),
|
||||
});
|
||||
|
||||
const sourceMapsSchema = z
|
||||
.object({
|
||||
status: z.enum([
|
||||
"not_requested",
|
||||
"included",
|
||||
"partial",
|
||||
"unavailable",
|
||||
"truncated",
|
||||
]),
|
||||
requested: z.number().int().min(0),
|
||||
processed: z.number().int().min(0),
|
||||
dropped: z.number().int().min(0),
|
||||
dropped_script_keys: z.array(z.string()),
|
||||
items: z.array(sourceMapSchema),
|
||||
})
|
||||
.superRefine((sourceMaps, context) => {
|
||||
if (
|
||||
sourceMaps.requested !== sourceMaps.processed + sourceMaps.dropped ||
|
||||
sourceMaps.processed !== sourceMaps.items.length ||
|
||||
sourceMaps.dropped !== sourceMaps.dropped_script_keys.length
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Source-map coverage counts are inconsistent",
|
||||
});
|
||||
});
|
||||
|
||||
/** Provider-neutral result of bounded JavaScript bundle reverse engineering. */
|
||||
export const webBundleAnalysisSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
capture: z.object({
|
||||
target_url: z.string(),
|
||||
scripts_observed: z.number().int().min(0),
|
||||
scripts_analyzed: z.number().int().min(0),
|
||||
source_artifacts: z.array(webTextArtifactSummarySchema),
|
||||
}),
|
||||
observations: z.object({
|
||||
chunks: z.object({
|
||||
nodes: z.array(
|
||||
z.object({
|
||||
script_key: z.string(),
|
||||
url: z.string(),
|
||||
artifact_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
bytes: z.number().int().min(0),
|
||||
}),
|
||||
),
|
||||
edges: z.array(
|
||||
z.object({
|
||||
from_script_key: z.string(),
|
||||
kind: z.enum([
|
||||
"static_import",
|
||||
"dynamic_import",
|
||||
"require",
|
||||
"worker_import",
|
||||
]),
|
||||
specifier: z.string(),
|
||||
resolved_url: z.string().nullable(),
|
||||
location: sourceLocationSchema,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
routes: z.array(findingSchema),
|
||||
endpoints: z.array(findingSchema),
|
||||
webmcp_declarations: z.array(
|
||||
z.object({
|
||||
name: z.string().nullable(),
|
||||
description: z.string().nullable(),
|
||||
schema_property_names: z.array(z.string()),
|
||||
trust: z.literal("page-declared-untrusted"),
|
||||
location: sourceLocationSchema,
|
||||
}),
|
||||
),
|
||||
source_maps: sourceMapsSchema,
|
||||
}),
|
||||
inferences: z.array(
|
||||
z.object({
|
||||
kind: z.enum(["vendor_fingerprint", "route_framework", "bundle_runtime"]),
|
||||
value: z.string(),
|
||||
confidence: z.enum(["low", "medium", "high"]),
|
||||
basis: z.array(basisSchema).min(1),
|
||||
}),
|
||||
),
|
||||
unknowns: z.array(
|
||||
z.object({
|
||||
dimension: z.string(),
|
||||
reason: z.string(),
|
||||
affected_script_keys: z.array(z.string()),
|
||||
}),
|
||||
),
|
||||
completeness: z.object({
|
||||
status: z.enum(["complete_within_limits", "truncated", "partial"]),
|
||||
parsed_scripts: z.number().int().min(0),
|
||||
parse_failures: z.number().int().min(0),
|
||||
visited_ast_nodes: z.number().int().min(0),
|
||||
dropped_findings: z.number().int().min(0),
|
||||
}),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type WebBundleAnalysis = z.infer<typeof webBundleAnalysisSchema>;
|
||||
@@ -0,0 +1,640 @@
|
||||
import { parse } from "@babel/parser";
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type { WebPageInspection } from "./browserObservation.js";
|
||||
import { sanitizeBrowserUrl } from "./browserObservation.js";
|
||||
import {
|
||||
webBundleAnalysisSchema,
|
||||
type AnalyzeWebBundleInput,
|
||||
type WebBundleAnalysis,
|
||||
} from "./webBundleAnalysis.js";
|
||||
|
||||
type BundleObservations = WebBundleAnalysis["observations"];
|
||||
type ChunkEdge = BundleObservations["chunks"]["edges"][number];
|
||||
type Finding = BundleObservations["routes"][number];
|
||||
type WebMcpDeclaration = BundleObservations["webmcp_declarations"][number];
|
||||
type Inference = WebBundleAnalysis["inferences"][number];
|
||||
type BrowserScript = WebPageInspection["scripts"]["items"][number];
|
||||
type IncludedSource = Extract<BrowserScript["source"], { included: true }>;
|
||||
type IncludedScript = Omit<BrowserScript, "source"> & {
|
||||
readonly source: IncludedSource;
|
||||
};
|
||||
|
||||
interface AnalysisAccumulator {
|
||||
readonly edges: ChunkEdge[];
|
||||
readonly routes: Finding[];
|
||||
readonly endpoints: Finding[];
|
||||
readonly webMcp: WebMcpDeclaration[];
|
||||
readonly inferences: Inference[];
|
||||
readonly seen: Set<string>;
|
||||
visitedNodes: number;
|
||||
parsedScripts: number;
|
||||
parseFailures: number;
|
||||
droppedFindings: number;
|
||||
astLimitReached: boolean;
|
||||
}
|
||||
|
||||
/** Analyze captured, explicitly approved JavaScript source without execution. */
|
||||
export const analyzeCapturedWebBundle = (
|
||||
inspection: WebPageInspection,
|
||||
input: AnalyzeWebBundleInput,
|
||||
sourceMaps: BundleObservations["source_maps"] = {
|
||||
status: "not_requested",
|
||||
requested: 0,
|
||||
processed: 0,
|
||||
dropped: 0,
|
||||
dropped_script_keys: [],
|
||||
items: [],
|
||||
},
|
||||
): WebBundleAnalysis => {
|
||||
const accumulator = emptyAccumulator();
|
||||
const sourceScripts = inspection.scripts.items.filter(isIncludedScript);
|
||||
for (const script of sourceScripts) analyzeScript(script, input, accumulator);
|
||||
const unavailable = inspection.scripts.items
|
||||
.filter((script) => !script.source.included)
|
||||
.map(({ script_key }) => script_key);
|
||||
const sourceMapIncomplete =
|
||||
sourceMaps.status === "partial" || sourceMaps.status === "unavailable";
|
||||
const partial =
|
||||
accumulator.parseFailures > 0 ||
|
||||
unavailable.length > 0 ||
|
||||
sourceMapIncomplete;
|
||||
const truncated =
|
||||
accumulator.astLimitReached ||
|
||||
accumulator.droppedFindings > 0 ||
|
||||
sourceMaps.status === "truncated";
|
||||
return webBundleAnalysisSchema.parse({
|
||||
schema_version: 1,
|
||||
capture: {
|
||||
target_url: inspection.target.url,
|
||||
scripts_observed: inspection.scripts.total,
|
||||
scripts_analyzed: sourceScripts.length,
|
||||
source_artifacts: sourceScripts.map((script) => {
|
||||
if (!script.source.included)
|
||||
throw new TypeError("Filtered source changed");
|
||||
const { text: _text, ...artifact } = script.source.artifact;
|
||||
return { ...artifact, text_available: true };
|
||||
}),
|
||||
},
|
||||
observations: {
|
||||
chunks: {
|
||||
nodes: sourceScripts.map((script) => {
|
||||
if (!script.source.included)
|
||||
throw new TypeError("Filtered source changed");
|
||||
return {
|
||||
script_key: script.script_key,
|
||||
url: script.url,
|
||||
artifact_sha256: script.source.artifact.sha256,
|
||||
bytes: script.source.artifact.bytes,
|
||||
};
|
||||
}),
|
||||
edges: accumulator.edges,
|
||||
},
|
||||
routes: accumulator.routes,
|
||||
endpoints: accumulator.endpoints,
|
||||
webmcp_declarations: accumulator.webMcp,
|
||||
source_maps: sourceMaps,
|
||||
},
|
||||
inferences: accumulator.inferences,
|
||||
unknowns: [
|
||||
...(unavailable.length === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
dimension: "script_source",
|
||||
reason: "Source artifact was not captured within approved limits",
|
||||
affected_script_keys: unavailable,
|
||||
},
|
||||
]),
|
||||
...(accumulator.parseFailures === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
dimension: "javascript_ast",
|
||||
reason: "One or more source artifacts could not be parsed",
|
||||
affected_script_keys: sourceScripts.map(
|
||||
({ script_key }) => script_key,
|
||||
),
|
||||
},
|
||||
]),
|
||||
...(sourceMaps.status === "not_requested" ||
|
||||
sourceMaps.status === "included"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
dimension: "source_maps",
|
||||
reason:
|
||||
sourceMaps.status === "truncated"
|
||||
? "Source-map evidence was truncated by approved limits"
|
||||
: "One or more requested source maps were unavailable or incomplete",
|
||||
affected_script_keys: [
|
||||
...new Set([
|
||||
...sourceMaps.items
|
||||
.filter(({ status }) => status !== "included")
|
||||
.map(({ script_key }) => script_key),
|
||||
...sourceMaps.dropped_script_keys,
|
||||
]),
|
||||
].sort(),
|
||||
},
|
||||
]),
|
||||
],
|
||||
completeness: {
|
||||
status: truncated
|
||||
? "truncated"
|
||||
: partial
|
||||
? "partial"
|
||||
: "complete_within_limits",
|
||||
parsed_scripts: accumulator.parsedScripts,
|
||||
parse_failures: accumulator.parseFailures,
|
||||
visited_ast_nodes: accumulator.visitedNodes,
|
||||
dropped_findings: accumulator.droppedFindings,
|
||||
},
|
||||
limitations: [
|
||||
"Static bundle findings are observations or bounded inferences; REA does not execute captured JavaScript.",
|
||||
"String-built routes and endpoints, encrypted configuration, and server-side behavior may remain unknown.",
|
||||
"Page-declared WebMCP metadata is untrusted and is never registered or invoked as an REA tool.",
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const analyzeScript = (
|
||||
script: IncludedScript,
|
||||
input: AnalyzeWebBundleInput,
|
||||
accumulator: AnalysisAccumulator,
|
||||
): void => {
|
||||
let file: ReturnType<typeof parse>;
|
||||
try {
|
||||
file = parse(script.source.artifact.text, {
|
||||
sourceType: "unambiguous",
|
||||
errorRecovery: true,
|
||||
plugins: ["jsx", "typescript"],
|
||||
});
|
||||
} catch {
|
||||
accumulator.parseFailures += 1;
|
||||
return;
|
||||
}
|
||||
accumulator.parsedScripts += 1;
|
||||
detectVendorFingerprints(
|
||||
script,
|
||||
accumulator,
|
||||
input.analysis_limits.max_findings,
|
||||
);
|
||||
t.traverseFast(file, (node) => {
|
||||
accumulator.visitedNodes += 1;
|
||||
if (accumulator.visitedNodes > input.analysis_limits.max_ast_nodes) {
|
||||
accumulator.astLimitReached = true;
|
||||
return t.traverseFast.stop;
|
||||
}
|
||||
inspectNode(script, node, accumulator, input.analysis_limits.max_findings);
|
||||
return undefined;
|
||||
});
|
||||
};
|
||||
|
||||
const inspectNode = (
|
||||
script: IncludedScript,
|
||||
node: t.Node,
|
||||
accumulator: AnalysisAccumulator,
|
||||
maximumFindings: number,
|
||||
): void => {
|
||||
if (
|
||||
(t.isImportDeclaration(node) || t.isExportAllDeclaration(node)) &&
|
||||
node.source !== undefined
|
||||
)
|
||||
addEdge(
|
||||
script,
|
||||
node.source.value,
|
||||
"static_import",
|
||||
node,
|
||||
accumulator,
|
||||
maximumFindings,
|
||||
);
|
||||
else if (t.isExportNamedDeclaration(node) && node.source != null)
|
||||
addEdge(
|
||||
script,
|
||||
node.source.value,
|
||||
"static_import",
|
||||
node,
|
||||
accumulator,
|
||||
maximumFindings,
|
||||
);
|
||||
else if (t.isImportExpression(node) && t.isStringLiteral(node.source))
|
||||
addEdge(
|
||||
script,
|
||||
node.source.value,
|
||||
"dynamic_import",
|
||||
node,
|
||||
accumulator,
|
||||
maximumFindings,
|
||||
);
|
||||
if (t.isObjectProperty(node))
|
||||
inspectRouteProperty(script, node, accumulator, maximumFindings);
|
||||
if (t.isCallExpression(node) || t.isNewExpression(node))
|
||||
inspectCall(script, node, accumulator, maximumFindings);
|
||||
};
|
||||
|
||||
const inspectCall = (
|
||||
script: IncludedScript,
|
||||
node: t.CallExpression | t.NewExpression,
|
||||
accumulator: AnalysisAccumulator,
|
||||
maximumFindings: number,
|
||||
): void => {
|
||||
const name = calleeName(node.callee);
|
||||
const first = stringArgument(node.arguments[0]);
|
||||
if ((name === "require" || name.endsWith(".require")) && first !== undefined)
|
||||
addEdge(script, first, "require", node, accumulator, maximumFindings);
|
||||
if (
|
||||
(name === "importScripts" || name.endsWith(".importScripts")) &&
|
||||
first !== undefined
|
||||
)
|
||||
addEdge(script, first, "worker_import", node, accumulator, maximumFindings);
|
||||
if (
|
||||
routeCallNames.some(
|
||||
(candidate) => name === candidate || name.endsWith(`.${candidate}`),
|
||||
)
|
||||
) {
|
||||
if (first !== undefined)
|
||||
addFinding(
|
||||
accumulator.routes,
|
||||
script,
|
||||
first,
|
||||
`call:${name}`,
|
||||
node,
|
||||
accumulator,
|
||||
maximumFindings,
|
||||
);
|
||||
addRouteFrameworkInference(
|
||||
script,
|
||||
name,
|
||||
node,
|
||||
accumulator,
|
||||
maximumFindings,
|
||||
);
|
||||
}
|
||||
const endpoint = endpointArgument(name, node.arguments);
|
||||
if (endpoint !== undefined)
|
||||
addFinding(
|
||||
accumulator.endpoints,
|
||||
script,
|
||||
endpoint,
|
||||
`call:${name}`,
|
||||
node,
|
||||
accumulator,
|
||||
maximumFindings,
|
||||
);
|
||||
if (
|
||||
name.endsWith("modelContext.registerTool") ||
|
||||
name === "modelContext.registerTool"
|
||||
)
|
||||
addWebMcpDeclaration(script, node, accumulator, maximumFindings);
|
||||
};
|
||||
|
||||
const inspectRouteProperty = (
|
||||
script: IncludedScript,
|
||||
node: t.ObjectProperty,
|
||||
accumulator: AnalysisAccumulator,
|
||||
maximumFindings: number,
|
||||
): void => {
|
||||
const key = propertyName(node.key);
|
||||
if ((key === "path" || key === "route") && t.isStringLiteral(node.value))
|
||||
addFinding(
|
||||
accumulator.routes,
|
||||
script,
|
||||
node.value.value,
|
||||
`property:${key}`,
|
||||
node,
|
||||
accumulator,
|
||||
maximumFindings,
|
||||
);
|
||||
};
|
||||
|
||||
const addEdge = (
|
||||
script: IncludedScript,
|
||||
specifier: string,
|
||||
kind: ChunkEdge["kind"],
|
||||
node: t.Node,
|
||||
accumulator: AnalysisAccumulator,
|
||||
maximumFindings: number,
|
||||
): void => {
|
||||
const bounded = specifier.slice(0, 4_096);
|
||||
const key = `edge\0${script.script_key}\0${kind}\0${bounded}`;
|
||||
addBounded(accumulator, key, maximumFindings, () =>
|
||||
accumulator.edges.push({
|
||||
from_script_key: script.script_key,
|
||||
kind,
|
||||
specifier: bounded,
|
||||
resolved_url: resolveSpecifier(bounded, script.url),
|
||||
location: location(script.script_key, node),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const addFinding = (
|
||||
collection: Finding[],
|
||||
script: IncludedScript,
|
||||
rawValue: string,
|
||||
mechanism: string,
|
||||
node: t.Node,
|
||||
accumulator: AnalysisAccumulator,
|
||||
maximumFindings: number,
|
||||
): void => {
|
||||
const value = sanitizeCandidate(rawValue);
|
||||
const key = `finding\0${mechanism}\0${script.script_key}\0${value}`;
|
||||
addBounded(accumulator, key, maximumFindings, () =>
|
||||
collection.push({
|
||||
value,
|
||||
mechanism,
|
||||
location: location(script.script_key, node),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const addWebMcpDeclaration = (
|
||||
script: IncludedScript,
|
||||
node: t.CallExpression | t.NewExpression,
|
||||
accumulator: AnalysisAccumulator,
|
||||
maximumFindings: number,
|
||||
): void => {
|
||||
const declaration = node.arguments[0];
|
||||
if (!t.isObjectExpression(declaration)) return;
|
||||
const name = objectString(declaration, "name");
|
||||
const description = objectString(declaration, "description");
|
||||
const schema =
|
||||
objectValue(declaration, "inputSchema") ??
|
||||
objectValue(declaration, "input_schema");
|
||||
const declaredProperties = t.isObjectExpression(schema)
|
||||
? objectValue(schema, "properties")
|
||||
: undefined;
|
||||
const propertyObject = t.isObjectExpression(declaredProperties)
|
||||
? declaredProperties
|
||||
: schema;
|
||||
const schemaPropertyNames = t.isObjectExpression(propertyObject)
|
||||
? propertyObject.properties.flatMap((property) =>
|
||||
t.isObjectProperty(property)
|
||||
? [propertyName(property.key)].filter(Boolean)
|
||||
: [],
|
||||
)
|
||||
: [];
|
||||
const key = `webmcp\0${script.script_key}\0${name ?? ""}\0${schemaPropertyNames.join("\0")}`;
|
||||
addBounded(accumulator, key, maximumFindings, () =>
|
||||
accumulator.webMcp.push({
|
||||
name: name?.slice(0, 256) ?? null,
|
||||
description: description?.slice(0, 2_048) ?? null,
|
||||
schema_property_names: [...new Set(schemaPropertyNames)]
|
||||
.sort()
|
||||
.slice(0, 256),
|
||||
trust: "page-declared-untrusted",
|
||||
location: location(script.script_key, node),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const detectVendorFingerprints = (
|
||||
script: IncludedScript,
|
||||
accumulator: AnalysisAccumulator,
|
||||
maximumFindings: number,
|
||||
): void => {
|
||||
const text = script.source.artifact.text;
|
||||
for (const detector of vendorDetectors) {
|
||||
if (!detector.patterns.some((pattern) => text.includes(pattern))) continue;
|
||||
const key = `vendor\0${script.script_key}\0${detector.value}`;
|
||||
addBounded(accumulator, key, maximumFindings, () =>
|
||||
accumulator.inferences.push({
|
||||
kind: detector.kind,
|
||||
value: detector.value,
|
||||
confidence: detector.confidence,
|
||||
basis: [basis(script, detector.detector)],
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const addRouteFrameworkInference = (
|
||||
script: IncludedScript,
|
||||
name: string,
|
||||
node: t.Node,
|
||||
accumulator: AnalysisAccumulator,
|
||||
maximumFindings: number,
|
||||
): void => {
|
||||
const value =
|
||||
name.endsWith("useRoutes") || name.endsWith("createBrowserRouter")
|
||||
? "React Router-compatible route API"
|
||||
: "Generic route registration API";
|
||||
const key = `route-framework\0${script.script_key}\0${value}`;
|
||||
addBounded(accumulator, key, maximumFindings, () =>
|
||||
accumulator.inferences.push({
|
||||
kind: "route_framework",
|
||||
value,
|
||||
confidence: "medium",
|
||||
basis: [{ ...basis(script, `call:${name}`), ...locationFields(node) }],
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const addBounded = (
|
||||
accumulator: AnalysisAccumulator,
|
||||
key: string,
|
||||
maximum: number,
|
||||
add: () => void,
|
||||
): void => {
|
||||
if (accumulator.seen.has(key)) return;
|
||||
const findings =
|
||||
accumulator.edges.length +
|
||||
accumulator.routes.length +
|
||||
accumulator.endpoints.length +
|
||||
accumulator.webMcp.length +
|
||||
accumulator.inferences.length;
|
||||
if (findings >= maximum) {
|
||||
accumulator.droppedFindings += 1;
|
||||
return;
|
||||
}
|
||||
accumulator.seen.add(key);
|
||||
add();
|
||||
};
|
||||
|
||||
const endpointArgument = (
|
||||
name: string,
|
||||
args: readonly (
|
||||
| t.Expression
|
||||
| t.SpreadElement
|
||||
| t.JSXNamespacedName
|
||||
| t.ArgumentPlaceholder
|
||||
)[],
|
||||
): string | undefined => {
|
||||
if (name === "fetch" || name.endsWith(".fetch") || name === "WebSocket")
|
||||
return stringArgument(args[0]);
|
||||
if (name.endsWith(".open") && stringArgument(args[1]) !== undefined)
|
||||
return stringArgument(args[1]);
|
||||
if (
|
||||
["get", "post", "put", "patch", "delete", "request"].some(
|
||||
(method) => name === method || name.endsWith(`.${method}`),
|
||||
)
|
||||
)
|
||||
return stringArgument(args[0]);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const calleeName = (callee: t.Node): string => {
|
||||
if (t.isIdentifier(callee)) return callee.name;
|
||||
if (t.isImport(callee)) return "import";
|
||||
if (t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee)) {
|
||||
const object = t.isExpression(callee.object)
|
||||
? calleeName(callee.object)
|
||||
: "";
|
||||
const property = propertyName(callee.property);
|
||||
return object === "" ? property : `${object}.${property}`;
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
const stringArgument = (
|
||||
value: t.Node | null | undefined,
|
||||
): string | undefined => (t.isStringLiteral(value) ? value.value : undefined);
|
||||
|
||||
const propertyName = (value: t.Node): string => {
|
||||
if (t.isIdentifier(value)) return value.name;
|
||||
if (t.isStringLiteral(value)) return value.value;
|
||||
return "";
|
||||
};
|
||||
|
||||
const objectValue = (
|
||||
object: t.ObjectExpression,
|
||||
name: string,
|
||||
): t.ObjectProperty["value"] | undefined => {
|
||||
for (const property of object.properties)
|
||||
if (t.isObjectProperty(property) && propertyName(property.key) === name)
|
||||
return property.value;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const objectString = (
|
||||
object: t.ObjectExpression,
|
||||
name: string,
|
||||
): string | undefined => {
|
||||
const value = objectValue(object, name);
|
||||
return t.isStringLiteral(value) ? value.value : undefined;
|
||||
};
|
||||
|
||||
const resolveSpecifier = (specifier: string, base: string): string | null => {
|
||||
try {
|
||||
const resolved = new URL(specifier, base);
|
||||
if (resolved.protocol !== "http:" && resolved.protocol !== "https:")
|
||||
return null;
|
||||
return sanitizeBrowserUrl(resolved.href).url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const sanitizeCandidate = (value: string): string => {
|
||||
const bounded = value.slice(0, 4_096);
|
||||
try {
|
||||
const parsed = new URL(bounded, "https://rea.invalid");
|
||||
const sanitized = sanitizeBrowserUrl(parsed.href).url;
|
||||
return parsed.origin === "https://rea.invalid"
|
||||
? sanitized.replace("https://rea.invalid", "")
|
||||
: sanitized;
|
||||
} catch {
|
||||
return bounded.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
}
|
||||
};
|
||||
|
||||
const location = (scriptKey: string, node: t.Node) => ({
|
||||
script_key: scriptKey,
|
||||
...locationFields(node),
|
||||
});
|
||||
|
||||
const locationFields = (node: t.Node) => ({
|
||||
line: node.loc?.start.line ?? null,
|
||||
column: node.loc?.start.column ?? null,
|
||||
});
|
||||
|
||||
const basis = (script: IncludedScript, detector: string) => ({
|
||||
script_key: script.script_key,
|
||||
artifact_sha256: script.source.artifact.sha256,
|
||||
line: null,
|
||||
column: null,
|
||||
detector,
|
||||
});
|
||||
|
||||
const emptyAccumulator = (): AnalysisAccumulator => ({
|
||||
edges: [],
|
||||
routes: [],
|
||||
endpoints: [],
|
||||
webMcp: [],
|
||||
inferences: [],
|
||||
seen: new Set(),
|
||||
visitedNodes: 0,
|
||||
parsedScripts: 0,
|
||||
parseFailures: 0,
|
||||
droppedFindings: 0,
|
||||
astLimitReached: false,
|
||||
});
|
||||
|
||||
const isIncludedScript = (script: BrowserScript): script is IncludedScript =>
|
||||
script.source.included;
|
||||
|
||||
const routeCallNames = [
|
||||
"route",
|
||||
"addRoute",
|
||||
"useRoutes",
|
||||
"createBrowserRouter",
|
||||
"createHashRouter",
|
||||
] as const;
|
||||
|
||||
const vendorDetectors: readonly {
|
||||
readonly value: string;
|
||||
readonly detector: string;
|
||||
readonly patterns: readonly string[];
|
||||
readonly confidence: Inference["confidence"];
|
||||
readonly kind: Inference["kind"];
|
||||
}[] = [
|
||||
{
|
||||
value: "webpack",
|
||||
detector: "webpack-runtime",
|
||||
patterns: ["__webpack_require__"],
|
||||
confidence: "high",
|
||||
kind: "bundle_runtime",
|
||||
},
|
||||
{
|
||||
value: "Vite",
|
||||
detector: "vite-runtime",
|
||||
patterns: ["__vite__", "import.meta.hot"],
|
||||
confidence: "medium",
|
||||
kind: "bundle_runtime",
|
||||
},
|
||||
{
|
||||
value: "React",
|
||||
detector: "react-runtime",
|
||||
patterns: ["__REACT_DEVTOOLS_GLOBAL_HOOK__", "React.createElement"],
|
||||
confidence: "medium",
|
||||
kind: "vendor_fingerprint",
|
||||
},
|
||||
{
|
||||
value: "Vue",
|
||||
detector: "vue-runtime",
|
||||
patterns: ["__VUE__", "createApp("],
|
||||
confidence: "medium",
|
||||
kind: "vendor_fingerprint",
|
||||
},
|
||||
{
|
||||
value: "Next.js",
|
||||
detector: "next-runtime",
|
||||
patterns: ["__NEXT_DATA__", "/_next/"],
|
||||
confidence: "high",
|
||||
kind: "vendor_fingerprint",
|
||||
},
|
||||
{
|
||||
value: "Angular",
|
||||
detector: "angular-runtime",
|
||||
patterns: ["ɵɵdefineComponent"],
|
||||
confidence: "high",
|
||||
kind: "vendor_fingerprint",
|
||||
},
|
||||
{
|
||||
value: "Svelte",
|
||||
detector: "svelte-runtime",
|
||||
patterns: ["svelte/internal"],
|
||||
confidence: "medium",
|
||||
kind: "vendor_fingerprint",
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,286 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
webPageInspectionSchema,
|
||||
type WebPageInspection,
|
||||
} from "./browserObservation.js";
|
||||
import {
|
||||
webMcpDiscoverySchema,
|
||||
type WebMcpDiscovery,
|
||||
} from "./webMcpDiscovery.js";
|
||||
|
||||
const captureSnapshotSchema = z.object({
|
||||
inspection: webPageInspectionSchema,
|
||||
webmcp: webMcpDiscoverySchema.nullable().default(null),
|
||||
});
|
||||
|
||||
/** Input for deterministic comparison of two normalized web captures. */
|
||||
export const compareWebCapturesInputSchema = z.object({
|
||||
before: captureSnapshotSchema,
|
||||
after: captureSnapshotSchema,
|
||||
max_changes: z.number().int().min(1).max(20_000).default(2_000),
|
||||
});
|
||||
export type CompareWebCapturesInput = z.infer<
|
||||
typeof compareWebCapturesInputSchema
|
||||
>;
|
||||
|
||||
const changeSchema = z.object({
|
||||
identity: z.string(),
|
||||
change: z.enum(["added", "removed", "modified"]),
|
||||
});
|
||||
const dimensionSchema = z.object({
|
||||
status: z.enum(["changed", "unchanged", "unknown"]),
|
||||
total_changes: z.number().int().min(0),
|
||||
changes: z.array(changeSchema),
|
||||
omitted_changes: z.number().int().min(0),
|
||||
reason: z.string().nullable(),
|
||||
});
|
||||
|
||||
/** Completeness-aware changes across stable browser evidence dimensions. */
|
||||
export const webCaptureDiffSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
overall_status: z.enum(["changed", "unchanged", "unknown"]),
|
||||
before_target: z.object({ target_id: z.string(), url: z.string() }),
|
||||
after_target: z.object({ target_id: z.string(), url: z.string() }),
|
||||
dimensions: z.object({
|
||||
dom_structure: dimensionSchema,
|
||||
scripts: dimensionSchema,
|
||||
resources: dimensionSchema,
|
||||
network: dimensionSchema,
|
||||
metadata: dimensionSchema,
|
||||
webmcp: dimensionSchema,
|
||||
}),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type WebCaptureDiff = z.infer<typeof webCaptureDiffSchema>;
|
||||
type Dimension =
|
||||
WebCaptureDiff["dimensions"][keyof WebCaptureDiff["dimensions"]];
|
||||
type Change = Dimension["changes"][number];
|
||||
|
||||
/** Compare normalized observations without treating incomplete absence as proof. */
|
||||
export const compareWebCaptures = (
|
||||
input: CompareWebCapturesInput,
|
||||
): WebCaptureDiff => {
|
||||
let remaining = input.max_changes;
|
||||
const dimension = (
|
||||
before: ReadonlyMap<string, string>,
|
||||
after: ReadonlyMap<string, string>,
|
||||
complete: boolean,
|
||||
reason: string,
|
||||
): Dimension => {
|
||||
const all = compareIdentities(before, after);
|
||||
const retained = all.slice(0, remaining);
|
||||
remaining -= retained.length;
|
||||
return {
|
||||
status: all.length > 0 ? "changed" : complete ? "unchanged" : "unknown",
|
||||
total_changes: all.length,
|
||||
changes: retained,
|
||||
omitted_changes: all.length - retained.length,
|
||||
reason: all.length === 0 && !complete ? reason : null,
|
||||
};
|
||||
};
|
||||
const before = input.before.inspection;
|
||||
const after = input.after.inspection;
|
||||
const dimensions = {
|
||||
dom_structure: dimension(
|
||||
singleton("document", digest(domProjection(before))),
|
||||
singleton("document", digest(domProjection(after))),
|
||||
sectionsComplete(before, ["frames", "dom"]) &&
|
||||
sectionsComplete(after, ["frames", "dom"]),
|
||||
"DOM or frame capture was incomplete in at least one observation.",
|
||||
),
|
||||
scripts: dimension(
|
||||
keyed(
|
||||
before.scripts.items.map(scriptProjection),
|
||||
(item) => item.script_key,
|
||||
),
|
||||
keyed(
|
||||
after.scripts.items.map(scriptProjection),
|
||||
(item) => item.script_key,
|
||||
),
|
||||
sectionsComplete(before, ["scripts"]) &&
|
||||
sectionsComplete(after, ["scripts"]),
|
||||
"Script inventory was incomplete in at least one observation.",
|
||||
),
|
||||
resources: dimension(
|
||||
keyed(before.resources, (item) => item.resource_key),
|
||||
keyed(after.resources, (item) => item.resource_key),
|
||||
sectionsComplete(before, ["resources"]) &&
|
||||
sectionsComplete(after, ["resources"]),
|
||||
"Resource inventory was incomplete in at least one observation.",
|
||||
),
|
||||
network: dimension(
|
||||
networkMap(before),
|
||||
networkMap(after),
|
||||
sectionsComplete(before, ["network_requests"]) &&
|
||||
sectionsComplete(after, ["network_requests"]),
|
||||
"Network capture is attach-window limited or incomplete.",
|
||||
),
|
||||
metadata: dimension(
|
||||
singleton("metadata", digest(metadataProjection(before))),
|
||||
singleton("metadata", digest(metadataProjection(after))),
|
||||
sectionsComplete(before, ["metadata"]) &&
|
||||
sectionsComplete(after, ["metadata"]),
|
||||
"Safe metadata capture was incomplete in at least one observation.",
|
||||
),
|
||||
webmcp: dimension(
|
||||
webMcpMap(input.before.webmcp),
|
||||
webMcpMap(input.after.webmcp),
|
||||
webMcpComplete(input.before.webmcp) && webMcpComplete(input.after.webmcp),
|
||||
"WebMCP discovery was unavailable or incomplete in at least one capture.",
|
||||
),
|
||||
};
|
||||
const statuses = Object.values(dimensions).map(({ status }) => status);
|
||||
return webCaptureDiffSchema.parse({
|
||||
schema_version: 1,
|
||||
overall_status: statuses.includes("changed")
|
||||
? "changed"
|
||||
: statuses.includes("unknown")
|
||||
? "unknown"
|
||||
: "unchanged",
|
||||
before_target: {
|
||||
target_id: before.target.target_id,
|
||||
url: before.target.url,
|
||||
},
|
||||
after_target: {
|
||||
target_id: after.target.target_id,
|
||||
url: after.target.url,
|
||||
},
|
||||
dimensions,
|
||||
limitations: [
|
||||
"A changed status proves an observed difference; an unknown status means absence could not be established from capture completeness.",
|
||||
"Network comparison covers only activity observed after each CDP attachment.",
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const compareIdentities = (
|
||||
before: ReadonlyMap<string, string>,
|
||||
after: ReadonlyMap<string, string>,
|
||||
): Change[] => {
|
||||
const changes: Change[] = [];
|
||||
for (const [identity, fingerprint] of before) {
|
||||
const next = after.get(identity);
|
||||
if (next === undefined) changes.push({ identity, change: "removed" });
|
||||
else if (next !== fingerprint)
|
||||
changes.push({ identity, change: "modified" });
|
||||
}
|
||||
for (const identity of after.keys())
|
||||
if (!before.has(identity)) changes.push({ identity, change: "added" });
|
||||
return changes.sort(
|
||||
(left, right) =>
|
||||
left.identity.localeCompare(right.identity) ||
|
||||
left.change.localeCompare(right.change),
|
||||
);
|
||||
};
|
||||
|
||||
const keyed = <T>(
|
||||
values: readonly T[],
|
||||
identity: (value: T) => string,
|
||||
): ReadonlyMap<string, string> =>
|
||||
new Map(values.map((value) => [identity(value), digest(value)]));
|
||||
|
||||
const networkMap = (
|
||||
inspection: WebPageInspection,
|
||||
): ReadonlyMap<string, string> => {
|
||||
const grouped = new Map<string, unknown[]>();
|
||||
for (const request of inspection.network.requests) {
|
||||
const identity = `net_${digest({
|
||||
method: request.method,
|
||||
url: request.url,
|
||||
resource_type: request.resource_type,
|
||||
})}`;
|
||||
const values = grouped.get(identity) ?? [];
|
||||
values.push({
|
||||
status: request.status,
|
||||
mime_type: request.mime_type,
|
||||
encoded_data_length: request.encoded_data_length,
|
||||
initiator: request.initiator,
|
||||
body_shapes: request.body_shapes,
|
||||
});
|
||||
grouped.set(identity, values);
|
||||
}
|
||||
return new Map(
|
||||
[...grouped].map(([identity, values]) => [
|
||||
identity,
|
||||
digest(values.map((value) => digest(value)).sort()),
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
const webMcpMap = (
|
||||
discovery: WebMcpDiscovery | null,
|
||||
): ReadonlyMap<string, string> =>
|
||||
discovery === null
|
||||
? new Map()
|
||||
: keyed(discovery.tools.items, (tool) => tool.tool_key);
|
||||
|
||||
const webMcpComplete = (discovery: WebMcpDiscovery | null): boolean =>
|
||||
discovery !== null &&
|
||||
discovery.status === "available" &&
|
||||
!incompleteSections(discovery.completeness).has("webmcp_tools");
|
||||
|
||||
const sectionsComplete = (
|
||||
inspection: WebPageInspection,
|
||||
sections: readonly string[],
|
||||
): boolean => {
|
||||
const incomplete = incompleteSections(inspection.completeness);
|
||||
return sections.every((section) => !incomplete.has(section));
|
||||
};
|
||||
|
||||
const incompleteSections = (completeness: {
|
||||
readonly policy_filtered_sections: readonly string[];
|
||||
readonly attach_limited_sections: readonly string[];
|
||||
readonly truncated_sections: readonly string[];
|
||||
readonly unavailable_sections: readonly string[];
|
||||
}): ReadonlySet<string> =>
|
||||
new Set([
|
||||
...completeness.policy_filtered_sections,
|
||||
...completeness.attach_limited_sections,
|
||||
...completeness.truncated_sections,
|
||||
...completeness.unavailable_sections,
|
||||
]);
|
||||
|
||||
const domProjection = (inspection: WebPageInspection) => ({
|
||||
frames: inspection.frames
|
||||
.map(({ url, origin }) => ({ url, origin }))
|
||||
.sort((left, right) => left.url.localeCompare(right.url)),
|
||||
nodes: inspection.dom.nodes.map(({ index: _index, ...node }) => node),
|
||||
});
|
||||
|
||||
const scriptProjection = (
|
||||
script: WebPageInspection["scripts"]["items"][number],
|
||||
) => ({
|
||||
script_key: script.script_key,
|
||||
url: script.url,
|
||||
cdp_hash: script.cdp_hash,
|
||||
length: script.length,
|
||||
is_module: script.is_module,
|
||||
language: script.language,
|
||||
source_map_url: script.source_map_url,
|
||||
});
|
||||
|
||||
const metadataProjection = (inspection: WebPageInspection) => ({
|
||||
responses: inspection.metadata.responses
|
||||
.map(({ request_id: _requestId, ...response }) => response)
|
||||
.map((value) => digest(value))
|
||||
.sort(),
|
||||
dom_urls: inspection.metadata.dom_urls.map((value) => digest(value)).sort(),
|
||||
agent_hints: inspection.metadata.agent_hints
|
||||
.map((value) => digest(value))
|
||||
.sort(),
|
||||
excluded_dom_urls: inspection.metadata.excluded_dom_urls,
|
||||
headers_allowlisted: inspection.metadata.headers_allowlisted,
|
||||
});
|
||||
|
||||
const singleton = (key: string, value: string): ReadonlyMap<string, string> =>
|
||||
new Map([[key, value]]);
|
||||
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
/** Self-verifying text artifact used by web-source analysis boundaries. */
|
||||
export const webTextArtifactSchema = z
|
||||
.object({
|
||||
uri: z.string().regex(/^rea:\/\/web-content\/sha256\/[a-f0-9]{64}$/u),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
bytes: z.number().int().min(0),
|
||||
media_type: z.string().min(1).max(256),
|
||||
charset: z.literal("utf-8"),
|
||||
text: z.string(),
|
||||
})
|
||||
.superRefine((artifact, context) => {
|
||||
const bytes = Buffer.byteLength(artifact.text);
|
||||
const digest = createHash("sha256").update(artifact.text).digest("hex");
|
||||
if (artifact.bytes !== bytes)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["bytes"],
|
||||
message: "Byte count mismatch",
|
||||
});
|
||||
if (artifact.sha256 !== digest)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["sha256"],
|
||||
message: "Digest mismatch",
|
||||
});
|
||||
if (artifact.uri !== webContentUri(digest))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["uri"],
|
||||
message: "Content URI mismatch",
|
||||
});
|
||||
});
|
||||
export type WebTextArtifact = z.infer<typeof webTextArtifactSchema>;
|
||||
|
||||
/** Build an immutable content-addressed UTF-8 text artifact. */
|
||||
export const createWebTextArtifact = (
|
||||
text: string,
|
||||
mediaType: string,
|
||||
): WebTextArtifact => {
|
||||
const sha256 = createHash("sha256").update(text).digest("hex");
|
||||
return {
|
||||
uri: webContentUri(sha256),
|
||||
sha256,
|
||||
bytes: Buffer.byteLength(text),
|
||||
media_type: mediaType,
|
||||
charset: "utf-8",
|
||||
text,
|
||||
};
|
||||
};
|
||||
|
||||
const webContentUri = (sha256: string): string =>
|
||||
`rea://web-content/sha256/${sha256}`;
|
||||
@@ -0,0 +1,120 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
export interface WebInventoryResourceInput {
|
||||
readonly url: string;
|
||||
readonly origin: string | null;
|
||||
readonly type: string;
|
||||
readonly mime_type: string;
|
||||
readonly content_size: number | null;
|
||||
}
|
||||
|
||||
export interface WebInventoryScriptInput {
|
||||
readonly url: string;
|
||||
readonly cdp_hash: string;
|
||||
readonly length: number;
|
||||
readonly is_module: boolean;
|
||||
readonly language: string | null;
|
||||
readonly source_map_url: string | null;
|
||||
}
|
||||
|
||||
export interface StableWebResource extends WebInventoryResourceInput {
|
||||
readonly resource_key: string;
|
||||
}
|
||||
|
||||
export type WebResourceReconciliation =
|
||||
| { readonly status: "exact"; readonly resource_key: string }
|
||||
| { readonly status: "ambiguous"; readonly candidate_resource_keys: string[] }
|
||||
| { readonly status: "unmatched"; readonly reason: "no_exact_sanitized_url" };
|
||||
|
||||
/** Assign deterministic identities to a bounded resource inventory. */
|
||||
export const stableWebResources = (
|
||||
resources: readonly WebInventoryResourceInput[],
|
||||
): StableWebResource[] => {
|
||||
const keyed = resources.map((resource) => ({
|
||||
...resource,
|
||||
resource_key: `res_${digest(resource)}`,
|
||||
}));
|
||||
return [
|
||||
...new Map(
|
||||
keyed.map((resource) => [resource.resource_key, resource]),
|
||||
).values(),
|
||||
].sort(
|
||||
(left, right) =>
|
||||
left.resource_key.localeCompare(right.resource_key) ||
|
||||
left.url.localeCompare(right.url),
|
||||
);
|
||||
};
|
||||
|
||||
/** Reconcile one script with resource-tree observations without fuzzy matching. */
|
||||
export const reconcileWebScript = (
|
||||
script: WebInventoryScriptInput,
|
||||
resources: readonly StableWebResource[],
|
||||
): WebResourceReconciliation => {
|
||||
const candidates = resources.filter(
|
||||
(resource) => resource.url === script.url,
|
||||
);
|
||||
if (candidates.length === 1)
|
||||
return { status: "exact", resource_key: candidates[0]?.resource_key ?? "" };
|
||||
if (candidates.length > 1)
|
||||
return {
|
||||
status: "ambiguous",
|
||||
candidate_resource_keys: uniqueResourceKeys(candidates),
|
||||
};
|
||||
return { status: "unmatched", reason: "no_exact_sanitized_url" };
|
||||
};
|
||||
|
||||
/** Prefer exact transient raw-URL matching, then report sanitized ambiguity. */
|
||||
export const reconcileCapturedWebScript = (
|
||||
script: WebInventoryScriptInput & { readonly rawUrl: string },
|
||||
rawResources: readonly (WebInventoryResourceInput & {
|
||||
readonly rawUrl: string;
|
||||
})[],
|
||||
resources: readonly StableWebResource[],
|
||||
): WebResourceReconciliation => {
|
||||
const exact = rawResources.filter(
|
||||
(resource) => resource.rawUrl === script.rawUrl,
|
||||
);
|
||||
if (exact.length === 1) {
|
||||
const resource = exact[0];
|
||||
if (resource !== undefined) {
|
||||
const { rawUrl: _rawUrl, ...publicResource } = resource;
|
||||
const stable = stableWebResources([publicResource])[0];
|
||||
if (stable !== undefined)
|
||||
return { status: "exact", resource_key: stable.resource_key };
|
||||
}
|
||||
}
|
||||
const candidates = resources.filter(
|
||||
(resource) => resource.url === script.url,
|
||||
);
|
||||
if (candidates.length > 0)
|
||||
return {
|
||||
status: "ambiguous",
|
||||
candidate_resource_keys: uniqueResourceKeys(candidates),
|
||||
};
|
||||
return { status: "unmatched", reason: "no_exact_sanitized_url" };
|
||||
};
|
||||
|
||||
/** Stable script identity excludes target IDs, CDP script IDs, and timestamps. */
|
||||
export const stableWebScriptKey = (script: WebInventoryScriptInput): string =>
|
||||
`scr_${digest({
|
||||
url: script.url,
|
||||
cdp_hash: script.cdp_hash,
|
||||
length: script.length,
|
||||
is_module: script.is_module,
|
||||
language: script.language,
|
||||
source_map_url: script.source_map_url,
|
||||
})}`;
|
||||
|
||||
const uniqueResourceKeys = (
|
||||
resources: readonly StableWebResource[],
|
||||
): string[] =>
|
||||
[...new Set(resources.map(({ resource_key }) => resource_key))].sort();
|
||||
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Web inventory value is not canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { browserCompletenessSchema } from "./browserCompleteness.js";
|
||||
import {
|
||||
browserAllowedOriginsSchema,
|
||||
browserEndpointSchema,
|
||||
} from "./browserObservation.js";
|
||||
import { jsonShapeSchema } from "./jsonShape.js";
|
||||
|
||||
/** Input for passive discovery of page-registered WebMCP tools. */
|
||||
export const discoverWebMcpToolsInputSchema = z.object({
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
allowed_origins: browserAllowedOriginsSchema,
|
||||
target_id: z.string().trim().min(1).max(256),
|
||||
approved: z.literal(true),
|
||||
observation_ms: z.number().int().min(0).max(10_000).default(100),
|
||||
max_tools: z.number().int().min(1).max(5_000).default(500),
|
||||
max_schema_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(1_024 * 1_024)
|
||||
.default(256 * 1_024),
|
||||
max_schema_nodes: z.number().int().min(1).max(100_000).default(5_000),
|
||||
max_schema_depth: z.number().int().min(1).max(100).default(20),
|
||||
});
|
||||
export type DiscoverWebMcpToolsInput = z.infer<
|
||||
typeof discoverWebMcpToolsInputSchema
|
||||
>;
|
||||
|
||||
const browserVersionSchema = z.object({
|
||||
product: z.string(),
|
||||
protocol_version: z.string(),
|
||||
revision: z.string(),
|
||||
user_agent: z.string(),
|
||||
js_version: z.string(),
|
||||
});
|
||||
|
||||
const webMcpToolSchema = z.object({
|
||||
tool_key: z.string().regex(/^webmcp_[a-f0-9]{64}$/u),
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
frame_id: z.string(),
|
||||
frame_url: z.string(),
|
||||
owner_origin: z.string(),
|
||||
declaration_kind: z.enum(["declarative", "imperative"]),
|
||||
input_schema_shape: jsonShapeSchema.nullable(),
|
||||
annotations: z.object({
|
||||
read_only: z.boolean().nullable(),
|
||||
untrusted_content: z.boolean().nullable(),
|
||||
autosubmit: z.boolean().nullable(),
|
||||
}),
|
||||
registration_source: z
|
||||
.object({
|
||||
url: z.string(),
|
||||
line: z.number().int().min(0).nullable(),
|
||||
column: z.number().int().min(0).nullable(),
|
||||
})
|
||||
.nullable(),
|
||||
trust: z.literal("page-declared-untrusted"),
|
||||
});
|
||||
|
||||
/** Passive WebMCP inventory; it intentionally has no invocation surface. */
|
||||
export const webMcpDiscoverySchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
browser: browserVersionSchema,
|
||||
target: z.object({
|
||||
target_id: z.string(),
|
||||
url: z.string(),
|
||||
origin: z.string(),
|
||||
}),
|
||||
status: z.enum(["available", "unavailable"]),
|
||||
tools: z.object({
|
||||
total: z.number().int().min(0),
|
||||
items: z.array(webMcpToolSchema),
|
||||
}),
|
||||
completeness: browserCompletenessSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type WebMcpDiscovery = z.infer<typeof webMcpDiscoverySchema>;
|
||||
@@ -0,0 +1,142 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { browserCompletenessSchema } from "./browserCompleteness.js";
|
||||
import {
|
||||
browserAllowedOriginsSchema,
|
||||
browserEndpointSchema,
|
||||
} from "./browserObservation.js";
|
||||
|
||||
const MAX_SCREENSHOT_BYTES = 8 * 1_024 * 1_024;
|
||||
|
||||
/** Self-verifying inline PNG artifact for CLI/MCP parity. */
|
||||
const webScreenshotArtifactSchema = z
|
||||
.object({
|
||||
uri: z.string().regex(/^rea:\/\/web-screenshot\/sha256\/[a-f0-9]{64}$/u),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
bytes: z.number().int().min(1).max(MAX_SCREENSHOT_BYTES),
|
||||
media_type: z.literal("image/png"),
|
||||
data_base64: z.string().max(Math.ceil((MAX_SCREENSHOT_BYTES * 4) / 3) + 4),
|
||||
})
|
||||
.superRefine((artifact, context) => {
|
||||
const bytes = decodeCanonicalBase64(artifact.data_base64);
|
||||
if (bytes === undefined) {
|
||||
context.addIssue({ code: "custom", message: "Invalid canonical base64" });
|
||||
return;
|
||||
}
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
if (
|
||||
bytes.byteLength !== artifact.bytes ||
|
||||
sha256 !== artifact.sha256 ||
|
||||
artifact.uri !== `rea://web-screenshot/sha256/${sha256}`
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Screenshot artifact digest or size mismatch",
|
||||
});
|
||||
});
|
||||
export type WebScreenshotArtifact = z.infer<typeof webScreenshotArtifactSchema>;
|
||||
|
||||
/** Input for one read-only visible-viewport screenshot. */
|
||||
export const captureWebScreenshotInputSchema = z.object({
|
||||
cdp_endpoint: browserEndpointSchema,
|
||||
allowed_origins: browserAllowedOriginsSchema,
|
||||
target_id: z.string().trim().min(1).max(256),
|
||||
approved: z.literal(true),
|
||||
screenshot_approved: z.literal(true),
|
||||
maximum_image_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(MAX_SCREENSHOT_BYTES)
|
||||
.default(4 * 1_024 * 1_024),
|
||||
});
|
||||
export type CaptureWebScreenshotInput = z.infer<
|
||||
typeof captureWebScreenshotInputSchema
|
||||
>;
|
||||
|
||||
const browserVersionSchema = z.object({
|
||||
product: z.string(),
|
||||
protocol_version: z.string(),
|
||||
revision: z.string(),
|
||||
user_agent: z.string(),
|
||||
js_version: z.string(),
|
||||
});
|
||||
|
||||
/** Bounded screenshot observation with embedded immutable artifact bytes. */
|
||||
export const webScreenshotSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
browser: browserVersionSchema,
|
||||
target: z.object({
|
||||
target_id: z.string(),
|
||||
url: z.string(),
|
||||
origin: z.string(),
|
||||
}),
|
||||
captured_at: z.iso.datetime(),
|
||||
viewport: z.object({
|
||||
width: z.number().int().min(1),
|
||||
height: z.number().int().min(1),
|
||||
}),
|
||||
artifact: webScreenshotArtifactSchema,
|
||||
completeness: browserCompletenessSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type WebScreenshot = z.infer<typeof webScreenshotSchema>;
|
||||
|
||||
/** Input for bounded local pixel comparison of two screenshot artifacts. */
|
||||
export const compareWebScreenshotsInputSchema = z.object({
|
||||
before: webScreenshotArtifactSchema,
|
||||
after: webScreenshotArtifactSchema,
|
||||
channel_threshold: z.number().int().min(0).max(255).default(0),
|
||||
maximum_pixels: z.number().int().min(1).max(32_000_000).default(16_000_000),
|
||||
});
|
||||
export type CompareWebScreenshotsInput = z.infer<
|
||||
typeof compareWebScreenshotsInputSchema
|
||||
>;
|
||||
|
||||
/** Value-only visual difference metrics; no OCR or image mutation. */
|
||||
export const webScreenshotDiffSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
status: z.enum(["identical", "different", "dimension_mismatch"]),
|
||||
before: z.object({
|
||||
width: z.number().int().min(1),
|
||||
height: z.number().int().min(1),
|
||||
}),
|
||||
after: z.object({
|
||||
width: z.number().int().min(1),
|
||||
height: z.number().int().min(1),
|
||||
}),
|
||||
channel_threshold: z.number().int().min(0).max(255),
|
||||
compared_pixels: z.number().int().min(0),
|
||||
changed_pixels: z.number().int().min(0).nullable(),
|
||||
changed_ratio: z.number().min(0).max(1).nullable(),
|
||||
maximum_channel_delta: z.number().int().min(0).max(255).nullable(),
|
||||
mean_absolute_channel_delta: z.number().min(0).max(255).nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export type WebScreenshotDiff = z.infer<typeof webScreenshotDiffSchema>;
|
||||
|
||||
/** Create a content-addressed PNG artifact from already bounded bytes. */
|
||||
export const createWebScreenshotArtifact = (
|
||||
bytes: Buffer,
|
||||
): WebScreenshotArtifact => {
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
return webScreenshotArtifactSchema.parse({
|
||||
uri: `rea://web-screenshot/sha256/${sha256}`,
|
||||
sha256,
|
||||
bytes: bytes.byteLength,
|
||||
media_type: "image/png",
|
||||
data_base64: bytes.toString("base64"),
|
||||
});
|
||||
};
|
||||
|
||||
/** Strict canonical base64 decoder used before digest validation. */
|
||||
export const decodeCanonicalBase64 = (value: string): Buffer | undefined => {
|
||||
if (value.length === 0 || value.length % 4 !== 0 || !BASE64.test(value))
|
||||
return undefined;
|
||||
const decoded = Buffer.from(value, "base64");
|
||||
return decoded.toString("base64") === value ? decoded : undefined;
|
||||
};
|
||||
|
||||
const BASE64 = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/u;
|
||||
Reference in New Issue
Block a user