refactor(browser): return complete observation evidence

This commit is contained in:
morluto
2026-09-29 13:56:49 +08:00
parent 9d1f88cbe8
commit 0e2738ffb6
69 changed files with 747 additions and 1206 deletions
+5 -31
View File
@@ -76,30 +76,6 @@ describe("browser observation contracts", () => {
include_websocket_shapes: false,
include_script_sources: false,
include_storage_keys: false,
limits: {
max_frames: 200,
max_dom_nodes: 2_000,
max_ax_nodes: 2_000,
max_ax_text_field_bytes: 1_024,
max_total_ax_text_bytes: 65_536,
max_scripts: 200,
max_resources: 2_000,
max_workers: 500,
max_storage_keys: 1_000,
max_script_source_bytes: 1_048_576,
max_total_script_source_bytes: 4_194_304,
max_network_events: 1_000,
max_console_events: 200,
max_console_text_field_bytes: 1_024,
max_total_console_text_bytes: 65_536,
max_json_body_bytes: 1_048_576,
max_total_json_body_bytes: 4_194_304,
max_json_shape_nodes: 5_000,
max_json_shape_depth: 20,
max_websocket_events: 500,
max_websocket_shape_bytes: 65_536,
max_total_websocket_shape_bytes: 1_048_576,
},
});
expect(
inspectWebPageInputSchema.safeParse({
@@ -157,7 +133,7 @@ describe("browser observation sensitive surfaces and retention", () => {
});
});
it("bounds retained URL and query-name metadata", () => {
it("retains complete URL and query-name metadata while redacting values", () => {
const longName = `a${"x".repeat(400)}`;
const parameters = [
`${longName}=secret`,
@@ -169,17 +145,15 @@ describe("browser observation sensitive surfaces and retention", () => {
const sanitized = sanitizeBrowserUrl(
`https://app.example.test/path?${parameters}`,
);
expect(sanitized.query_parameter_names).toHaveLength(256);
expect(
sanitized.query_parameter_names.every((name) => name.length <= 256),
).toBe(true);
expect(sanitized.query_parameter_names).toHaveLength(301);
expect(sanitized.query_parameter_names).toContain(longName);
expect(sanitized.url).not.toContain("secret");
const oversized = sanitizeBrowserUrl(
`https://app.example.test/${"p".repeat(70_000)}`,
);
expect(oversized.origin).toBe("https://app.example.test");
expect(oversized.url.length).toBeLessThanOrEqual(131_072);
expect(oversized.redacted).toBe(true);
expect(oversized.url.length).toBeGreaterThan(70_000);
expect(oversized.redacted).toBe(false);
});
});
+13 -48
View File
@@ -27,16 +27,10 @@ const parseExactOrigin = (value: string): string | undefined => {
return url.origin;
};
const MAX_BROWSER_URL_CHARS = 65_536;
const MAX_SANITIZED_BROWSER_URL_CHARS = 131_072;
const MAX_QUERY_PARAMETER_NAMES = 256;
const MAX_QUERY_PARAMETER_NAME_CHARS = 256;
/** Exact normalized HTTP(S) authority used for browser observation scope. */
export const browserOriginSchema = z
.string()
.min(1)
.max(2_048)
.transform((value, context) => {
const origin = parseExactOrigin(value);
if (origin === undefined) {
@@ -57,7 +51,6 @@ export const isLiteralLoopbackHostname = (hostname: string): boolean =>
export const browserEndpointSchema = z
.string()
.min(1)
.max(2_048)
.transform((value, context) => {
let url: URL;
try {
@@ -89,8 +82,7 @@ export const browserEndpointSchema = z
export const browserAllowedOriginsSchema = z
.array(browserOriginSchema)
.min(1)
.max(32)
.transform((origins) => [...new Set(origins)].sort());
.transform((origins) => Array.from(new Set(origins)).sort());
const browserInput = {
cdp_endpoint: browserEndpointSchema,
@@ -102,21 +94,10 @@ export const listBrowserTargetsInputSchema = z.object({
...browserInput,
});
/** Per-value limits for optional text and JSON-shape capture. */
export const DEFAULT_BROWSER_INSPECTION_LIMITS = {
max_ax_text_field_bytes: 1_024,
max_script_source_bytes: 1_024 * 1_024,
max_console_text_field_bytes: 1_024,
max_json_body_bytes: 1_024 * 1_024,
max_json_shape_nodes: 5_000,
max_json_shape_depth: 20,
max_websocket_shape_bytes: 64 * 1_024,
};
const inspectWebPageInputFacts = {
...browserInput,
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(500),
target_id: z.string().trim().min(1),
observation_ms: z.number().int().min(0).default(500),
include_accessibility_text: z.boolean().default(false),
include_console_text: z.boolean().default(false),
include_json_body_shapes: z.boolean().default(false),
@@ -161,12 +142,8 @@ export const inspectWebPageToolInputSchema = z.union([
inspectWebPageWithSourceInputSchema,
]);
/** Internal parsed input with per-value capture limits applied. */
export const inspectWebPageInputSchema =
inspectWebPageToolInputSchema.transform((input) => ({
...input,
limits: DEFAULT_BROWSER_INSPECTION_LIMITS,
}));
/** Parsed passive browser inspection input. */
export const inspectWebPageInputSchema = inspectWebPageToolInputSchema;
export type ListBrowserTargetsInput = z.infer<
typeof listBrowserTargetsInputSchema
@@ -174,11 +151,9 @@ export type ListBrowserTargetsInput = z.infer<
export type InspectWebPageInput = z.infer<typeof inspectWebPageInputSchema>;
export const sanitizedBrowserUrlSchema = z.object({
url: z.string().max(MAX_SANITIZED_BROWSER_URL_CHARS),
origin: z.string().max(2_048).nullable(),
query_parameter_names: z
.array(z.string().max(MAX_QUERY_PARAMETER_NAME_CHARS))
.max(MAX_QUERY_PARAMETER_NAMES),
url: z.string(),
origin: z.string().nullable(),
query_parameter_names: z.array(z.string()),
redacted: z.boolean(),
});
export type SanitizedBrowserUrl = z.infer<typeof sanitizedBrowserUrlSchema>;
@@ -186,9 +161,8 @@ export type SanitizedBrowserUrl = z.infer<typeof sanitizedBrowserUrlSchema>;
/** Remove credentials and query values before a browser URL becomes durable. */
export const sanitizeBrowserUrl = (value: string): SanitizedBrowserUrl => {
let parsed: URL;
const wasTruncated = value.length > MAX_BROWSER_URL_CHARS;
try {
parsed = new URL(value.slice(0, MAX_BROWSER_URL_CHARS));
parsed = new URL(value);
} catch {
return {
url: "[unsupported-url]",
@@ -199,15 +173,7 @@ export const sanitizeBrowserUrl = (value: string): SanitizedBrowserUrl => {
}
const hadCredentials = parsed.username !== "" || parsed.password !== "";
const hadFragment = parsed.hash !== "";
const names = [
...new Set(
[...parsed.searchParams.keys()].map((name) =>
name.slice(0, MAX_QUERY_PARAMETER_NAME_CHARS),
),
),
]
.sort()
.slice(0, MAX_QUERY_PARAMETER_NAMES);
const names = [...new Set(parsed.searchParams.keys())].sort();
parsed.username = "";
parsed.password = "";
parsed.hash = "";
@@ -217,20 +183,19 @@ export const sanitizeBrowserUrl = (value: string): SanitizedBrowserUrl => {
url: parsed.href,
origin: parsed.origin === "null" ? null : parsed.origin,
query_parameter_names: names,
redacted: wasTruncated || hadCredentials || hadFragment || names.length > 0,
redacted: hadCredentials || hadFragment || names.length > 0,
};
};
/** Remove credentials, fragments, and query values from endpoint candidates. */
export const sanitizeEndpointCandidate = (value: string): string => {
const bounded = value.slice(0, 4_096);
try {
const parsed = new URL(bounded, "https://rea.invalid");
const parsed = new URL(value, "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] ?? "";
return value.split("#", 1)[0]?.split("?", 1)[0] ?? "";
}
};
+3 -12
View File
@@ -119,13 +119,7 @@ const browserNetworkRequestSchema = z.object({
column: z.number().int().min(0).nullable(),
}),
body_shapes: z.object({
status: z.enum([
"not_approved",
"included",
"partial",
"unavailable",
"truncated",
]),
status: z.enum(["not_approved", "included", "partial", "unavailable"]),
request: jsonShapeSchema.nullable(),
response: jsonShapeSchema.nullable(),
}),
@@ -138,7 +132,7 @@ const browserConsoleEventSchema = z.object({
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"]),
status: z.enum(["not_approved", "included"]),
values: z.array(
z.object({
argument_index: z.number().int().min(0),
@@ -147,7 +141,6 @@ const browserConsoleEventSchema = z.object({
}),
),
retained_bytes: z.number().int().min(0),
truncated_values: z.number().int().min(0),
}),
});
const browserWebSocketEventSchema = z.object({
@@ -159,7 +152,6 @@ const browserWebSocketEventSchema = z.object({
.object({
format: z.enum(["json", "text", "binary"]),
json_shape: jsonShapeSchema.nullable(),
truncated: z.boolean(),
})
.nullable(),
});
@@ -261,10 +253,9 @@ 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"]),
status: z.enum(["not_approved", "included", "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),
}),
+54
View File
@@ -125,6 +125,29 @@ describe("browser scenario comparison validation", () => {
).toBe(false);
});
it("returns every aligned step beyond the former capture ceiling", () => {
const before = multiStepScenarioCapture(130, "before");
const after = multiStepScenarioCapture(130, "after");
const result = compareBrowserScenarios(
compareBrowserScenariosInputSchema.parse({
before_scenario: before,
after_scenario: after,
}),
);
expect(result.alignment).toMatchObject({
status: "aligned",
aligned_steps: 131,
});
expect(result.steps).toHaveLength(131);
expect(result.steps.at(-1)).toMatchObject({
before_step_index: 130,
after_step_index: 130,
status: "changed",
});
expect(result.artifact_diffs.total).toBe(130);
});
it("reports missing aligned steps without claiming equality", () => {
const before = scenarioCapture({});
const after = scenarioCapture({ stepId: "open-profile" });
@@ -182,6 +205,37 @@ describe("browser scenario comparison validation", () => {
});
});
const multiStepScenarioCapture = (
actionCount: number,
content: string,
): BrowserScenarioCapture => {
const capture = scenarioCapture({});
const template = capture.steps[1];
if (template === undefined) throw new Error("Expected scenario action step");
const steps = [
capture.steps[0],
...Array.from({ length: actionCount }, (_, index) => ({
...template,
step_index: index + 1,
step_id: `step-${String(index + 1)}`,
event_sequence_start: index + 1,
event_sequence_end: index + 1,
artifacts: {
...template.artifacts,
dom: {
state: "captured" as const,
value: textArtifact(`${content}-${String(index + 1)}`),
},
},
})),
];
return browserScenarioCaptureSchema.parse({
...capture,
scenario: { ...capture.scenario, action_count: actionCount },
steps,
});
};
interface ScenarioCaptureOptions {
readonly stepId?: string;
readonly action?: string;
+21 -25
View File
@@ -55,7 +55,7 @@ const normalizationRuleSchema = z.strictObject({
const normalizationInputSchema = z
.strictObject({
rules: z.array(normalizationRuleSchema).max(128).default([]),
rules: z.array(normalizationRuleSchema).default([]),
})
.superRefine((normalization, context) => {
const ruleIds = new Set<string>();
@@ -86,9 +86,7 @@ export const compareBrowserScenariosInputSchema = z.strictObject({
),
normalization: normalizationInputSchema
.default({ rules: [] })
.describe(
"Bounded exact-literal rules committed in the comparison result.",
),
.describe("Exact-literal rules committed in the comparison result."),
});
/** Parsed browser scenario comparison input. */
export type CompareBrowserScenariosInput = z.infer<
@@ -137,39 +135,37 @@ const builtInNormalizationSchema = z.enum([
"compare_normalized_text_content",
]);
/** Step alignment, recorded normalization, and bounded artifact differences. */
/** Step alignment, recorded normalization, and inline artifact differences. */
export const browserScenarioDiffSchema = z.strictObject({
comparison_kind: z.literal("browser_scenario"),
overall_status: z.enum(["changed", "unchanged", "unknown"]),
normalization: z.strictObject({
built_in_rules: z.array(builtInNormalizationSchema).length(5),
rules: z.array(normalizationRuleSchema).max(128),
rules: z.array(normalizationRuleSchema),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
}),
alignment: z.strictObject({
status: z.enum(["aligned", "partial", "failed"]),
aligned_steps: z.number().int().min(0).max(129),
before_only: z.array(z.string().min(1).max(64)).max(129),
after_only: z.array(z.string().min(1).max(64)).max(129),
failures: z.array(alignmentFailureSchema).max(520),
aligned_steps: z.number().int().min(0),
before_only: z.array(z.string().min(1).max(64)),
after_only: z.array(z.string().min(1).max(64)),
failures: z.array(alignmentFailureSchema),
}),
steps: z
.array(
z.strictObject({
step_id: z.string().min(1).max(64),
before_step_index: z.number().int().min(0).max(128),
after_step_index: z.number().int().min(0).max(128),
before_action: z.string().min(1).max(64),
after_action: z.string().min(1).max(64),
status: z.enum(["changed", "unchanged", "unknown"]),
artifact_diffs: z.array(artifactDiffSchema).max(8),
}),
)
.max(129),
steps: z.array(
z.strictObject({
step_id: z.string().min(1).max(64),
before_step_index: z.number().int().min(0),
after_step_index: z.number().int().min(0),
before_action: z.string().min(1).max(64),
after_action: z.string().min(1).max(64),
status: z.enum(["changed", "unchanged", "unknown"]),
artifact_diffs: z.array(artifactDiffSchema),
}),
),
artifact_diffs: z.strictObject({
total: z.number().int().min(0).max(1_032),
total: z.number().int().min(0),
}),
limitations: z.array(z.string().min(1).max(2_048)).max(64),
limitations: z.array(z.string().min(1).max(2_048)),
});
/** Browser scenario comparison result. */
export type BrowserScenarioDiff = z.infer<typeof browserScenarioDiffSchema>;
+4 -5
View File
@@ -6,13 +6,12 @@ import {
} from "./browserObservation.js";
import { browserCompletenessSchema } from "./browserCompleteness.js";
/** Input for a bounded, navigation-aware browser observation window. */
export const observeWebSessionInputSchema = z.object({
/** Input for a navigation-aware browser observation window. */
export const observeWebSessionInputSchema = z.strictObject({
cdp_endpoint: browserEndpointSchema,
allowed_origins: browserAllowedOriginsSchema,
target_id: z.string().trim().min(1).max(256),
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),
target_id: z.string().trim().min(1),
observation_ms: z.number().int().min(1).default(10_000),
});
export type ObserveWebSessionInput = z.infer<
typeof observeWebSessionInputSchema
+10 -15
View File
@@ -12,11 +12,9 @@ export const electronFileRootsSchema = z
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 = {
@@ -24,9 +22,6 @@ const approvedElectronInput = {
allowed_file_roots: electronFileRootsSchema,
};
/** Per-script source validation bound for passive Electron capture. */
export const MAX_ELECTRON_SCRIPT_SOURCE_BYTES = 1_024 * 1_024;
/** Input for listing root-confined file:// page targets from Electron CDP. */
export const listElectronTargetsInputSchema = z.strictObject({
...approvedElectronInput,
@@ -38,8 +33,8 @@ export type ListElectronTargetsInput = z.infer<
/** Input for passive structural inspection of one Electron file page. */
const inspectElectronPageFacts = {
...approvedElectronInput,
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(100),
target_id: z.string().trim().min(1),
observation_ms: z.number().int().min(0).default(100),
} as const;
export const inspectElectronPageInputSchema = z.union([
z.strictObject({
@@ -54,14 +49,14 @@ export const inspectElectronPageInputSchema = z.union([
export const inspectElectronPageToolInputSchema = z.union([
z.strictObject({
discovery_evidence_id: z.string().min(1),
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(100),
target_id: z.string().trim().min(1),
observation_ms: z.number().int().min(0).default(100),
include_script_sources: z.literal(false).default(false),
}),
z.strictObject({
discovery_evidence_id: z.string().min(1),
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(100),
target_id: z.string().trim().min(1),
observation_ms: z.number().int().min(0).default(100),
include_script_sources: z.literal(true),
}),
]);
@@ -159,12 +154,12 @@ export const electronPageInspectionSchema = z.object({
workers: z
.array(
z.object({
target_id: z.string().min(1).max(256),
type: z.string().min(1).max(100),
target_id: z.string().min(1),
type: z.string().min(1),
file_path: z.string(),
attached: z.boolean(),
opener_target_id: z.string().min(1).max(256).nullable(),
parent_frame_id: z.string().min(1).max(256).nullable(),
opener_target_id: z.string().min(1).nullable(),
parent_frame_id: z.string().min(1).nullable(),
}),
)
.default([]),
+3 -24
View File
@@ -27,8 +27,6 @@ import {
} from "./javascriptStaticAnalysisHelpers.js";
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js";
const MAX_WEB_PREFERENCES = 64;
/** Inspect BrowserWindow, contextBridge, and utility-process syntax. */
export const inspectElectronBrowserNode = (
node: t.Node,
@@ -48,7 +46,7 @@ const inspectBrowserWindow = (
if (name !== "BrowserWindow" && !name.endsWith(".BrowserWindow")) return;
const options = argumentNode(node.arguments[0]);
const collected = collectWindowOptions(context.source, options);
accountForStructure(context, collected.unknown, collected.omitted);
context.accumulator.unknownFindings += collected.unknown;
const finding: ElectronBrowserWindowFinding = {
options_status:
options === undefined
@@ -58,7 +56,6 @@ const inspectBrowserWindow = (
: "dynamic",
web_preferences_status: collected.status,
web_preferences: collected.preferences,
omitted_web_preferences: collected.omitted,
...collected.preload,
module_key: null,
location: range(node),
@@ -79,7 +76,6 @@ const collectWindowOptions = (
readonly preferences: readonly ElectronWebPreference[];
readonly preload: ElectronBrowserWindowPreload;
readonly unknown: number;
readonly omitted: number;
} => {
if (!t.isObjectExpression(options))
return {
@@ -87,7 +83,6 @@ const collectWindowOptions = (
preferences: [],
preload: { preload_path: null, preload_resolution_context: null },
unknown: options === undefined ? 0 : 1,
omitted: 0,
};
const property = objectProperty(options, "webPreferences");
if (property === undefined)
@@ -96,7 +91,6 @@ const collectWindowOptions = (
preferences: [],
preload: { preload_path: null, preload_resolution_context: null },
unknown: 0,
omitted: 0,
};
if (!t.isObjectExpression(property.value))
return {
@@ -104,7 +98,6 @@ const collectWindowOptions = (
preferences: [],
preload: { preload_path: null, preload_resolution_context: null },
unknown: 1,
omitted: 0,
};
return collectWebPreferences(source, property.value);
};
@@ -117,7 +110,6 @@ const collectWebPreferences = (
readonly preferences: readonly ElectronWebPreference[];
readonly preload: ElectronBrowserWindowPreload;
readonly unknown: number;
readonly omitted: number;
} => {
const preferences: ElectronWebPreference[] = [];
let unknown = 0;
@@ -167,10 +159,9 @@ const collectWebPreferences = (
preferences.sort((left, right) => compareCodePoints(left.name, right.name));
return {
status: "object-literal",
preferences: preferences.slice(0, MAX_WEB_PREFERENCES),
preferences,
preload,
unknown,
omitted: Math.max(0, preferences.length - MAX_WEB_PREFERENCES),
};
};
@@ -197,7 +188,7 @@ const inspectContextBridge = (
(key.status === "dynamic" ? 1 : 0) +
(worldId?.status === "dynamic" ? 1 : 0) +
api.unknown;
accountForStructure(context, unknown, api.omitted);
context.accumulator.unknownFindings += unknown;
const apiKey: ElectronContextBridgeApiKey =
key.status === "dynamic"
? { api_key: null, api_key_expression: key.expression }
@@ -211,7 +202,6 @@ const inspectContextBridge = (
api_status: api.status,
members: api.members,
unknown_members: api.unknown,
omitted_members: api.omitted,
module_key: null,
location: range(node),
};
@@ -265,14 +255,3 @@ const inspectUtilityProcess = (
value: finding,
});
};
const accountForStructure = (
context: JavaScriptFindingContext,
unknown: number,
omitted: number,
): void => {
context.accumulator.unknownFindings += unknown;
if (omitted === 0) return;
context.accumulator.structuralTruncation = true;
context.accumulator.droppedFindings += omitted;
};
+1 -12
View File
@@ -12,8 +12,6 @@ import {
} from "./javascriptStaticAnalysisHelpers.js";
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js";
const MAX_NATIVE_MEMBERS = 64;
interface NativeBindingInput {
readonly context: JavaScriptFindingContext;
readonly node: t.Node;
@@ -127,15 +125,7 @@ const addBinding = (input: NativeBindingInput): void => {
const unique = [
...new Set(input.members.filter((member) => member !== "")),
].sort(compareCodePoints);
const members = (unique.length === 0 ? ["*"] : unique).slice(
0,
MAX_NATIVE_MEMBERS,
);
const omitted = Math.max(0, unique.length - MAX_NATIVE_MEMBERS);
if (omitted > 0) {
context.accumulator.structuralTruncation = true;
context.accumulator.droppedFindings += omitted;
}
const members = unique.length === 0 ? ["*"] : unique;
addLocatedFinding(context, {
collection: context.accumulator.nativeAddonBindings,
key: `native-addon-binding\0${kind}\0${specifier}\0${members.join("\0")}`,
@@ -144,7 +134,6 @@ const addBinding = (input: NativeBindingInput): void => {
specifier,
binding_kind: kind,
members,
members_truncated: omitted > 0,
module_key: null,
location: range(node),
},
@@ -38,7 +38,6 @@ export type ElectronBrowserWindowFinding = ElectronBrowserWindowPreload & {
readonly options_status: "object-literal" | "dynamic" | "missing";
readonly web_preferences_status: "object-literal" | "dynamic" | "missing";
readonly web_preferences: readonly ElectronWebPreference[];
readonly omitted_web_preferences: number;
readonly module_key: string | null;
readonly location: JavaScriptSourceRange;
};
@@ -56,7 +55,6 @@ export type ElectronContextBridgeFinding = ElectronContextBridgeApiKey & {
readonly api_status: "object-literal" | "dynamic" | "missing";
readonly members: readonly string[];
readonly unknown_members: number;
readonly omitted_members: number;
readonly module_key: string | null;
readonly location: JavaScriptSourceRange;
};
@@ -165,7 +163,6 @@ export interface ElectronNativeAddonBindingFinding {
readonly specifier: string;
readonly binding_kind: "import" | "require" | "re-export";
readonly members: readonly string[];
readonly members_truncated: boolean;
readonly module_key: string | null;
readonly location: JavaScriptSourceRange;
}
+7 -24
View File
@@ -7,9 +7,7 @@ import {
sourceSlice,
} from "./javascriptStaticAnalysisHelpers.js";
const MAX_EXPRESSION_CHARACTERS = 4_096;
/** Preserve one literal value or the exact bounded inert expression. */
/** Preserve one literal value or the exact inert expression. */
export const electronStaticValue = (
source: string,
node: t.Node | null | undefined,
@@ -24,17 +22,14 @@ export const electronStaticValue = (
};
};
/** Return an actionable bounded expression without evaluating it. */
/** Return an actionable expression without evaluating it. */
export const boundedExpression = (
source: string,
node: t.Node | null | undefined,
): string => {
if (node === null || node === undefined) return "[missing-expression]";
const expression = sourceSlice(source, node).trim();
return (expression === "" ? `[${node.type}]` : expression).slice(
0,
MAX_EXPRESSION_CHARACTERS,
);
return expression === "" ? `[${node.type}]` : expression;
};
/** Read one named object property without following spreads or bindings. */
@@ -72,29 +67,25 @@ export function handlerKind(
return "dynamic-expression";
}
/** Collect bounded dotted keys from one literal contextBridge API object. */
/** Collect statically visible dotted keys from one literal contextBridge API object. */
export const collectContextBridgeMembers = (
node: t.Node | null | undefined,
maximum = 128,
): {
readonly status: "object-literal" | "dynamic" | "missing";
readonly members: readonly string[];
readonly unknown: number;
readonly omitted: number;
} => {
if (node === null || node === undefined)
return {
status: "missing",
members: [],
unknown: 0,
omitted: 0,
};
if (!t.isObjectExpression(node))
return {
status: "dynamic",
members: [],
unknown: 1,
omitted: 0,
};
const state: { members: string[]; unknown: number } = {
members: [],
@@ -104,9 +95,8 @@ export const collectContextBridgeMembers = (
const members = [...new Set(state.members)].sort(compareCodePoints);
return {
status: "object-literal",
members: members.slice(0, maximum),
members,
unknown: state.unknown,
omitted: Math.max(0, members.length - maximum),
};
};
@@ -130,10 +120,7 @@ const collectMembersAt = (
state.unknown += 1;
continue;
}
const path = (prefix === "" ? name : `${prefix}.${name}`).slice(
0,
MAX_EXPRESSION_CHARACTERS,
);
const path = prefix === "" ? name : `${prefix}.${name}`;
state.members.push(path);
if (t.isObjectProperty(property) && t.isObjectExpression(property.value))
collectMembersAt(property.value, path, depth + 1, state);
@@ -152,11 +139,7 @@ const literalValue = (
if (t.isTemplateLiteral(node) && node.expressions.length === 0)
return {
found: true,
value: (
node.quasis[0]?.value.cooked ??
node.quasis[0]?.value.raw ??
""
).slice(0, MAX_EXPRESSION_CHARACTERS),
value: node.quasis[0]?.value.cooked ?? node.quasis[0]?.value.raw ?? "",
};
if (
t.isUnaryExpression(node, { operator: "-" }) &&
+15 -25
View File
@@ -13,12 +13,10 @@ describe("inferJsonShape", () => {
],
optional: null,
}),
{ maximumBytes: 4_096, maximumNodes: 100, maximumDepth: 10 },
);
expect(shape).toMatchObject({
root_type: "object",
truncated: false,
properties: expect.arrayContaining([
{ path: "/token", types: ["string"], observations: 1 },
{
@@ -37,30 +35,22 @@ describe("inferJsonShape", () => {
expect(JSON.stringify(shape)).not.toContain("second-secret");
});
it("rejects malformed and oversized JSON without returning a prefix", () => {
const limits = {
maximumBytes: 8,
maximumNodes: 100,
maximumDepth: 10,
};
expect(inferJsonShape("not-json", limits)).toBeNull();
expect(inferJsonShape('{"secret":"value"}', limits)).toBeNull();
it("rejects malformed JSON", () => {
expect(inferJsonShape("not-json")).toBeNull();
});
it("reports node and depth truncation deterministically", () => {
expect(
inferJsonShape('{"a":{"b":{"c":1}}}', {
maximumBytes: 1_024,
maximumNodes: 100,
maximumDepth: 1,
}),
).toMatchObject({ truncated: true, max_depth_observed: 1 });
expect(
inferJsonShape("[1,2,3,4]", {
maximumBytes: 1_024,
maximumNodes: 2,
maximumDepth: 10,
}),
).toMatchObject({ truncated: true, node_count: 2 });
it("retains every parsed property beyond the former shape-node limit", () => {
const content = Object.fromEntries(
Array.from({ length: 5_001 }, (_, index) => [`field_${index}`, index]),
);
const shape = inferJsonShape(JSON.stringify(content));
expect(shape?.properties).toHaveLength(5_001);
expect(shape?.node_count).toBe(5_002);
expect(shape?.properties).toContainEqual({
path: "/field_5000",
types: ["number"],
observations: 1,
});
});
});
+7 -46
View File
@@ -22,22 +22,11 @@ export const jsonShapeSchema = z.object({
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;
export const inferJsonShape = (text: string): JsonShape | null => {
let root: unknown;
try {
root = JSON.parse(text);
@@ -55,28 +44,13 @@ export const inferJsonShape = (
}> = [{ 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)
for (let index = current.value.length - 1; index >= 0; index -= 1)
pending.push({
value: current.value[index],
path: `${current.path}/*`,
@@ -86,17 +60,11 @@ export const inferJsonShape = (
}
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];
for (let index = allEntries.length - 1; index >= 0; index -= 1) {
const entry = allEntries[index];
if (entry === undefined) continue;
const [name, value] = entry;
const path = `${current.path}/${pointerName(name)}`.slice(0, 2_048);
const path = `${current.path}/${pointerName(name)}`;
const type = jsonValueType(value);
const existing = properties.get(path);
if (existing === undefined)
@@ -118,9 +86,7 @@ export const inferJsonShape = (
types: [...value.types].sort(),
observations: value.observations,
}))
.sort((left, right) => left.path.localeCompare(right.path))
.slice(0, limits.maximumNodes),
truncated,
.sort((left, right) => left.path.localeCompare(right.path)),
});
};
@@ -139,13 +105,8 @@ const jsonValueType = (value: unknown): JsonValueType => {
}
};
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");
value.replaceAll("~", "~0").replaceAll("/", "~1");
+1 -2
View File
@@ -346,8 +346,7 @@ const accessibilityComparable = (
} => {
const text =
inspection.accessibility.text_capture.status === "included" &&
inspection.accessibility.text_capture.excluded_fields === 0 &&
inspection.accessibility.text_capture.truncated_fields === 0;
inspection.accessibility.text_capture.excluded_fields === 0;
const nodes =
inspection.accessibility.total_nodes ===
inspection.accessibility.nodes.length;
+2 -2
View File
@@ -11,8 +11,8 @@ import { jsonShapeSchema } from "./jsonShape.js";
export const discoverWebMcpToolsInputSchema = z.strictObject({
cdp_endpoint: browserEndpointSchema,
allowed_origins: browserAllowedOriginsSchema,
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(100),
target_id: z.string().trim().min(1),
observation_ms: z.number().int().min(0).default(100),
});
export type DiscoverWebMcpToolsInput = z.infer<
typeof discoverWebMcpToolsInputSchema
+8 -20
View File
@@ -8,15 +8,13 @@ import {
browserEndpointSchema,
} from "./browserObservation.js";
const MAX_SCREENSHOT_BYTES = 8 * 1_024 * 1_024;
/** Self-verifying inline PNG artifact for CLI/MCP parity. */
export const webScreenshotArtifactSchema = z
.object({
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
bytes: z.number().int().min(1).max(MAX_SCREENSHOT_BYTES),
bytes: z.number().int().min(1),
media_type: z.literal("image/png"),
data_base64: z.string().max(Math.ceil((MAX_SCREENSHOT_BYTES * 4) / 3) + 4),
data_base64: z.string(),
})
.superRefine((artifact, context) => {
const bytes = decodeCanonicalBase64(artifact.data_base64);
@@ -34,16 +32,10 @@ export const webScreenshotArtifactSchema = z
export type WebScreenshotArtifact = z.infer<typeof webScreenshotArtifactSchema>;
/** Input for one read-only visible-viewport screenshot. */
export const captureWebScreenshotInputSchema = z.object({
export const captureWebScreenshotInputSchema = z.strictObject({
cdp_endpoint: browserEndpointSchema,
allowed_origins: browserAllowedOriginsSchema,
target_id: z.string().trim().min(1).max(256),
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
@@ -57,7 +49,7 @@ const browserVersionSchema = z.object({
js_version: z.string(),
});
/** Bounded screenshot observation with embedded immutable artifact bytes. */
/** Screenshot observation with embedded immutable artifact bytes. */
export const webScreenshotSchema = z.object({
browser: browserVersionSchema,
target: z.object({
@@ -76,12 +68,11 @@ export const webScreenshotSchema = z.object({
});
export type WebScreenshot = z.infer<typeof webScreenshotSchema>;
/** Input for bounded local pixel comparison of two screenshot artifacts. */
export const compareWebScreenshotsInputSchema = z.object({
/** Input for local pixel comparison of two screenshot artifacts. */
export const compareWebScreenshotsInputSchema = z.strictObject({
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
@@ -153,7 +144,7 @@ export const webScreenshotDiffSchema = z
});
export type WebScreenshotDiff = z.infer<typeof webScreenshotDiffSchema>;
/** Create a content-addressed PNG artifact from already bounded bytes. */
/** Create a content-addressed PNG artifact from captured bytes. */
export const createWebScreenshotArtifact = (
bytes: Buffer,
): WebScreenshotArtifact => {
@@ -168,10 +159,7 @@ export const createWebScreenshotArtifact = (
/** 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;
if (value.length === 0 || value.length % 4 !== 0) 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;