feat(browser): capture controlled Playwright scenarios

This commit is contained in:
morluto
2026-07-24 13:16:01 +00:00
parent d9977286f9
commit 1ac3118aa2
32 changed files with 4800 additions and 166 deletions
+28
View File
@@ -0,0 +1,28 @@
/** Public browser, Electron, Inspector, and scenario operations. */
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"
| "list_javascript_runtime_targets"
| "observe_javascript_runtime"
| "capture_browser_scenario";
/** Stable failure reasons shared by browser-family provider adapters. */
export type BrowserObservationFailureReason =
| "endpoint_unreachable"
| "invalid_endpoint_response"
| "target_not_found"
| "target_not_allowed"
| "target_changed"
| "protocol_error"
| "disconnected"
| "payload_limit"
| "cancelled"
| "secret_unavailable";
+338
View File
@@ -0,0 +1,338 @@
import { z } from "zod";
import {
BROWSER_SCENARIO_LIMITS,
browserScenarioActionSchema,
browserScenarioAllowedOriginsSchema,
browserScenarioBrowserSchema,
browserScenarioCaptureLimitsSchema,
browserScenarioCaptureSchema,
browserScenarioEnvironmentSchema,
browserScenarioRedactionSchema,
browserScenarioRequestReplaySchema,
browserScenarioSecretSchema,
browserScenarioStorageSchema,
browserScenarioUrlSchema,
type BrowserScenarioAction,
type BrowserScenarioUrl,
type BrowserScenarioValue,
} from "./browserScenarioValues.js";
export {
BROWSER_SCENARIO_LIMITS,
browserScenarioActionSchema,
browserScenarioUrlSchema,
browserScenarioValueSchema,
type BrowserScenarioAction,
type BrowserScenarioUrl,
type BrowserScenarioValue,
} from "./browserScenarioValues.js";
const scenarioShapeSchema = z.strictObject({
schema_version: z.literal(1),
browser: browserScenarioBrowserSchema,
start_url: browserScenarioUrlSchema,
allowed_origins: browserScenarioAllowedOriginsSchema,
environment: browserScenarioEnvironmentSchema,
actions: z
.array(browserScenarioActionSchema)
.min(1)
.max(BROWSER_SCENARIO_LIMITS.actions),
storage: browserScenarioStorageSchema,
request_replay: browserScenarioRequestReplaySchema,
secrets: z
.array(browserScenarioSecretSchema)
.max(BROWSER_SCENARIO_LIMITS.secrets)
.default([]),
redaction: browserScenarioRedactionSchema,
capture: browserScenarioCaptureSchema,
limits: browserScenarioCaptureLimitsSchema,
approved: z.literal(true),
});
type ScenarioShape = z.infer<typeof scenarioShapeSchema>;
const addIssue = (
context: z.RefinementCtx,
path: PropertyKey[],
message: string,
): void => context.addIssue({ code: "custom", path, message });
const assertUnique = (
values: readonly string[],
path: PropertyKey[],
label: string,
context: z.RefinementCtx,
): void => {
if (new Set(values).size !== values.length)
addIssue(context, path, `${label} must be unique`);
};
const originFor = (destination: BrowserScenarioUrl): string =>
new URL(destination.url).origin;
const assertAllowedDestination = (
destination: BrowserScenarioUrl,
allowedOrigins: ReadonlySet<string>,
path: PropertyKey[],
context: z.RefinementCtx,
): void => {
if (!allowedOrigins.has(originFor(destination)))
addIssue(
context,
path,
`URL origin ${originFor(destination)} is not declared in allowed_origins`,
);
};
const secretReferencesInValue = (
value: BrowserScenarioValue | undefined,
): readonly string[] => (value?.source === "secret" ? [value.secret_id] : []);
const destinationSecretReferences = (
destination: BrowserScenarioUrl,
): readonly string[] =>
destination.query.flatMap(({ value }) => secretReferencesInValue(value));
const actionSecretReferences = (
action: BrowserScenarioAction,
): readonly string[] => {
if (action.action === "fill" || action.action === "select_option")
return secretReferencesInValue(action.value);
if (action.action === "goto")
return destinationSecretReferences(action.destination);
return [];
};
const validateStorage = (
scenario: ScenarioShape,
allowedOrigins: ReadonlySet<string>,
context: z.RefinementCtx,
): readonly string[] => {
const references: string[] = [];
scenario.storage.cookies.forEach((cookie, index) => {
assertAllowedDestination(
cookie.destination,
allowedOrigins,
["storage", "cookies", index, "destination"],
context,
);
references.push(...secretReferencesInValue(cookie.value));
references.push(...destinationSecretReferences(cookie.destination));
});
for (const collection of ["local_storage", "session_storage"] as const)
scenario.storage[collection].forEach((storage, index) => {
if (!allowedOrigins.has(storage.origin))
addIssue(
context,
["storage", collection, index, "origin"],
`Storage origin ${storage.origin} is not declared in allowed_origins`,
);
for (const entry of storage.entries)
references.push(...secretReferencesInValue(entry.value));
});
return references;
};
const SENSITIVE_HEADERS = new Set([
"authorization",
"cookie",
"proxy-authorization",
"set-cookie",
]);
const FORBIDDEN_REPLAY_HEADERS = new Set([
"content-length",
"location",
"transfer-encoding",
]);
const validateRequestReplay = (
scenario: ScenarioShape,
allowedOrigins: ReadonlySet<string>,
context: z.RefinementCtx,
): readonly string[] => {
if (scenario.request_replay.mode === "disabled") return [];
assertUnique(
scenario.request_replay.routes.map(({ route_id: id }) => id),
["request_replay", "routes"],
"Replay route IDs",
context,
);
assertUnique(
scenario.request_replay.routes.map(
({ method, request }) =>
`${method} ${request.url}?${request.query
.map(({ name, value }) =>
value.source === "secret"
? `${name}=\${secret:${value.secret_id}}`
: `${name}=${value.value}`,
)
.join("&")}`,
),
["request_replay", "routes"],
"Replay request matchers",
context,
);
const references: string[] = [];
scenario.request_replay.routes.forEach((route, routeIndex) => {
assertAllowedDestination(
route.request,
allowedOrigins,
["request_replay", "routes", routeIndex, "request"],
context,
);
references.push(...destinationSecretReferences(route.request));
if (route.response.kind === "redirect") {
assertAllowedDestination(
route.response.destination,
allowedOrigins,
["request_replay", "routes", routeIndex, "response", "destination"],
context,
);
references.push(
...destinationSecretReferences(route.response.destination),
);
return;
}
route.response.headers.forEach((header, headerIndex) => {
if (FORBIDDEN_REPLAY_HEADERS.has(header.name))
addIssue(
context,
[
"request_replay",
"routes",
routeIndex,
"response",
"headers",
headerIndex,
],
`Replay header ${header.name} must be modeled by the provider`,
);
if (
SENSITIVE_HEADERS.has(header.name) &&
header.value.source === "literal"
)
addIssue(
context,
[
"request_replay",
"routes",
routeIndex,
"response",
"headers",
headerIndex,
"value",
],
`Credential header ${header.name} requires a declared secret`,
);
references.push(...secretReferencesInValue(header.value));
});
references.push(...secretReferencesInValue(route.response.body));
});
return references;
};
const validateSecretReferences = (
scenario: ScenarioShape,
references: readonly string[],
context: z.RefinementCtx,
): void => {
const declared = new Set(scenario.secrets.map(({ secret_id: id }) => id));
for (const reference of references)
if (!declared.has(reference))
addIssue(
context,
["secrets"],
`Secret reference ${reference} is not declared`,
);
const used = new Set(references);
scenario.secrets.forEach(({ secret_id: id }, index) => {
if (!used.has(id))
addIssue(
context,
["secrets", index, "secret_id"],
`Secret declaration ${id} is unused`,
);
});
};
const validateRedactionCoverage = (
scenario: ScenarioShape,
context: z.RefinementCtx,
): void => {
const redactedQueries = new Set(scenario.redaction.query_parameter_names);
const destinations: BrowserScenarioUrl[] = [scenario.start_url];
for (const action of scenario.actions)
if (action.action === "goto") destinations.push(action.destination);
for (const cookie of scenario.storage.cookies)
destinations.push(cookie.destination);
if (scenario.request_replay.mode === "exact")
for (const route of scenario.request_replay.routes) {
destinations.push(route.request);
if (route.response.kind === "redirect")
destinations.push(route.response.destination);
}
for (const destination of destinations)
for (const query of destination.query)
if (
query.value.source === "secret" &&
!redactedQueries.has(query.name.toLowerCase())
)
addIssue(
context,
["redaction", "query_parameter_names"],
`Secret query parameter ${query.name} must be declared for redaction`,
);
};
const validateBrowserScenario = (
scenario: ScenarioShape,
context: z.RefinementCtx,
): void => {
const allowedOrigins = new Set(scenario.allowed_origins);
assertAllowedDestination(
scenario.start_url,
allowedOrigins,
["start_url"],
context,
);
assertUnique(
scenario.actions.map(({ step_id: id }) => id),
["actions"],
"Action step IDs",
context,
);
assertUnique(
scenario.secrets.map(({ secret_id: id }) => id),
["secrets"],
"Secret IDs",
context,
);
assertUnique(
scenario.secrets.map(({ environment_variable: name }) => name),
["secrets"],
"Secret environment variables",
context,
);
const references = scenario.actions.flatMap(actionSecretReferences);
for (const [index, action] of scenario.actions.entries())
if (action.action === "goto")
assertAllowedDestination(
action.destination,
allowedOrigins,
["actions", index, "destination"],
context,
);
references.push(...destinationSecretReferences(scenario.start_url));
references.push(...validateStorage(scenario, allowedOrigins, context));
references.push(...validateRequestReplay(scenario, allowedOrigins, context));
validateSecretReferences(scenario, references, context);
validateRedactionCoverage(scenario, context);
};
/** Strict provider-neutral contract for one bounded browser capture scenario. */
export const browserScenarioSchema = scenarioShapeSchema.superRefine(
validateBrowserScenario,
);
export type BrowserScenario = z.infer<typeof browserScenarioSchema>;
+85
View File
@@ -0,0 +1,85 @@
import { z } from "zod";
import {
browserScenarioCompletenessSchema,
browserScenarioEventSchema,
browserScenarioStepSchema,
} from "./browserScenarioCaptureValues.js";
export {
browserScenarioCompletenessSchema,
browserScenarioEventSchema,
browserScenarioStepSchema,
browserStepArtifactsSchema,
captureStateSchema,
type BrowserScenarioCompleteness,
type BrowserScenarioEvent,
type BrowserScenarioStep,
type BrowserStepArtifacts,
} from "./browserScenarioCaptureValues.js";
/** Step-indexed, explicitly bounded browser scenario observation. */
export const browserScenarioCaptureSchema = z
.strictObject({
schema_version: z.literal(1),
browser: z.strictObject({
mode: z.enum(["launch", "connect"]),
process_ownership: z.enum(["provider-owned", "external"]),
cleanup: z.enum(["terminated-owned-process", "disconnected-external"]),
product: z.string().min(1).max(1_024),
version: z.string().min(1).max(256),
}),
scenario: z.strictObject({
start_origin: z.string().min(1).max(2_048),
allowed_origins: z.array(z.string().min(1).max(2_048)).min(1).max(32),
action_count: z.number().int().min(1).max(128),
secret_references: z.array(z.string().min(1).max(64)).max(64),
}),
duration_ms: z.number().int().min(0),
steps: z.array(browserScenarioStepSchema).min(1).max(129),
events: z.strictObject({
retained: z.number().int().min(0),
dropped: z.number().int().min(0),
items: z.array(browserScenarioEventSchema).max(100_000),
}),
completeness: browserScenarioCompletenessSchema,
limitations: z.array(z.string().min(1).max(2_048)).max(64),
})
.superRefine((capture, context) => {
if (capture.events.retained !== capture.events.items.length)
context.addIssue({
code: "custom",
path: ["events", "retained"],
message: "Retained event count must equal items length",
});
if (capture.steps.length !== capture.scenario.action_count + 1)
context.addIssue({
code: "custom",
path: ["steps"],
message: "Capture must include initial state and one entry per action",
});
const expectedIndices = capture.steps.map((_, index) => index);
if (
capture.steps.some(
({ step_index: index }, offset) => index !== expectedIndices[offset],
)
)
context.addIssue({
code: "custom",
path: ["steps"],
message: "Step indices must be contiguous from zero",
});
if (
capture.events.items.some(
({ step_index: index }) => index >= capture.steps.length,
)
)
context.addIssue({
code: "custom",
path: ["events", "items"],
message: "Event references an unknown step index",
});
});
export type BrowserScenarioCapture = z.infer<
typeof browserScenarioCaptureSchema
>;
+231
View File
@@ -0,0 +1,231 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import { sanitizedBrowserUrlSchema } from "./browserObservation.js";
import { webScreenshotArtifactSchema } from "./webScreenshot.js";
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const boundedTextSchema = z.string().max(1_048_576);
const textArtifactSchema = z
.strictObject({
sha256: digestSchema,
bytes: z
.number()
.int()
.min(0)
.max(16 * 1_024 * 1_024),
text: boundedTextSchema,
})
.superRefine((artifact, context) => {
const bytes = Buffer.from(artifact.text);
const sha256 = createHash("sha256").update(bytes).digest("hex");
if (bytes.byteLength !== artifact.bytes || sha256 !== artifact.sha256)
context.addIssue({
code: "custom",
message: "Text artifact digest or size mismatch",
});
});
export const captureStateSchema = <Schema extends z.ZodType>(value: Schema) =>
z.discriminatedUnion("state", [
z.strictObject({ state: z.literal("captured"), value }),
z.strictObject({
state: z.literal("not_requested"),
}),
z.strictObject({
state: z.literal("missing"),
reason: z.string().min(1).max(1_024),
}),
z.strictObject({
state: z.literal("truncated"),
observed: z.number().int().min(0),
retained: z.number().int().min(0),
reason: z.string().min(1).max(1_024),
}),
]);
const historySchema = z.strictObject({
length: z.number().int().min(0),
current_url: sanitizedBrowserUrlSchema,
navigation_entries: z
.array(
z.strictObject({
type: z.enum([
"navigate",
"reload",
"back_forward",
"prerender",
"unknown",
]),
name: sanitizedBrowserUrlSchema,
}),
)
.max(256),
});
const storageValueSchema = z.strictObject({
name: z.string().max(1_024),
value_state: z.enum(["hashed", "redacted-secret"]),
value_sha256: digestSchema.nullable(),
});
const storageSnapshotSchema = z.strictObject({
cookies: z
.array(
z.strictObject({
name: z.string().max(1_024),
domain: z.string().max(2_048),
path: z.string().max(4_096),
secure: z.boolean(),
http_only: z.boolean(),
same_site: z.enum(["Strict", "Lax", "None"]),
value_state: z.enum(["hashed", "redacted-secret"]),
value_sha256: digestSchema.nullable(),
}),
)
.max(512),
local_storage: z.array(storageValueSchema).max(512),
session_storage: z.array(storageValueSchema).max(512),
});
export const browserStepArtifactsSchema = z.strictObject({
screenshot: captureStateSchema(webScreenshotArtifactSchema),
dom: captureStateSchema(textArtifactSchema),
accessibility: captureStateSchema(textArtifactSchema),
url: captureStateSchema(sanitizedBrowserUrlSchema),
history: captureStateSchema(historySchema),
storage: captureStateSchema(storageSnapshotSchema),
});
export type BrowserStepArtifacts = z.infer<typeof browserStepArtifactsSchema>;
const eventBase = {
sequence: z.number().int().min(1),
step_index: z.number().int().min(0),
};
const eventUrl = sanitizedBrowserUrlSchema.nullable();
export const browserScenarioEventSchema = z.discriminatedUnion("kind", [
z.strictObject({
...eventBase,
kind: z.literal("console"),
level: z.string().min(1).max(64),
text: z.string().max(65_536),
url: eventUrl,
}),
z.strictObject({
...eventBase,
kind: z.literal("page-error"),
message: z.string().max(65_536),
stack: z.string().max(262_144).nullable(),
}),
z.strictObject({
...eventBase,
kind: z.enum(["request", "response", "request-failed"]),
method: z.string().min(1).max(32),
url: sanitizedBrowserUrlSchema,
resource_type: z.string().min(1).max(64),
status: z.number().int().min(100).max(599).nullable(),
header_names: z.array(z.string().max(256)).max(256),
failure: z.string().max(1_024).nullable(),
}),
z.strictObject({
...eventBase,
kind: z.enum(["websocket-opened", "websocket-closed"]),
url: sanitizedBrowserUrlSchema,
}),
z.strictObject({
...eventBase,
kind: z.enum(["websocket-frame-sent", "websocket-frame-received"]),
url: sanitizedBrowserUrlSchema,
payload_type: z.enum(["text", "binary"]),
payload_bytes: z.number().int().min(0),
payload_text: z.string().max(65_536).nullable(),
truncated: z.boolean(),
}),
z.strictObject({
...eventBase,
kind: z.enum([
"frame-attached",
"frame-detached",
"frame-navigated",
"worker-created",
"worker-closed",
"popup-opened",
"popup-closed",
]),
url: eventUrl,
name: z.string().max(1_024).nullable(),
}),
z.strictObject({
...eventBase,
kind: z.literal("download-cancelled"),
suggested_filename: z.string().max(1_024),
url: sanitizedBrowserUrlSchema,
}),
]);
export type BrowserScenarioEvent = z.infer<typeof browserScenarioEventSchema>;
const completenessSectionSchema = z.enum([
"action",
"screenshot",
"dom",
"accessibility",
"url",
"history",
"storage",
"events",
"frames",
"workers",
"popups",
"websockets",
]);
export const browserScenarioCompletenessSchema = z
.strictObject({
status: z.enum(["complete", "incomplete", "truncated"]),
equality_eligible: z.boolean(),
missing_sections: z.array(completenessSectionSchema),
truncated_sections: z.array(completenessSectionSchema),
})
.superRefine((value, context) => {
const expectedStatus =
value.truncated_sections.length > 0
? "truncated"
: value.missing_sections.length > 0
? "incomplete"
: "complete";
if (value.status !== expectedStatus)
context.addIssue({
code: "custom",
path: ["status"],
message: "Completeness status does not match section accounting",
});
if (value.equality_eligible !== (expectedStatus === "complete"))
context.addIssue({
code: "custom",
path: ["equality_eligible"],
message: "Missing or truncated evidence is never equality-eligible",
});
});
export type BrowserScenarioCompleteness = z.infer<
typeof browserScenarioCompletenessSchema
>;
export const browserScenarioStepSchema = z.strictObject({
step_index: z.number().int().min(0),
step_id: z.string().min(1).max(64),
action: z.string().min(1).max(64),
status: z.enum(["completed", "failed", "cancelled"]),
elapsed_ms: z.number().int().min(0),
before_url: sanitizedBrowserUrlSchema,
after_url: sanitizedBrowserUrlSchema,
error: z.string().max(4_096).nullable(),
event_sequence_start: z.number().int().min(1),
event_sequence_end: z.number().int().min(0),
artifacts: browserStepArtifactsSchema,
completeness: browserScenarioCompletenessSchema,
});
export type BrowserScenarioStep = z.infer<typeof browserScenarioStepSchema>;
+424
View File
@@ -0,0 +1,424 @@
import { z } from "zod";
import {
browserAllowedOriginsSchema,
browserEndpointSchema,
browserOriginSchema,
} from "./browserObservation.js";
export const BROWSER_SCENARIO_LIMITS = {
actions: 128,
secrets: 64,
storageEntries: 512,
replayRoutes: 256,
durationMs: 300_000,
actionTimeoutMs: 60_000,
} as const;
export const scenarioIdentifierSchema = z
.string()
.regex(/^[A-Za-z][A-Za-z0-9._-]{0,63}$/u);
const absoluteExecutablePathSchema = z
.string()
.min(1)
.max(4_096)
.refine(
(value) =>
value.startsWith("/") ||
/^[A-Za-z]:[\\/]/u.test(value) ||
value.startsWith("\\\\"),
"Expected an absolute browser executable path",
);
const browserScenarioBaseUrlSchema = z
.string()
.min(1)
.max(65_536)
.transform((value, context) => {
let url: URL;
try {
url = new URL(value);
} catch {
context.addIssue({ code: "custom", message: "Invalid browser URL" });
return z.NEVER;
}
if (
(url.protocol !== "http:" && url.protocol !== "https:") ||
url.username !== "" ||
url.password !== "" ||
url.search !== "" ||
url.hash !== ""
) {
context.addIssue({
code: "custom",
message:
"Browser URLs must be HTTP(S), omit credentials, and declare query values separately",
});
return z.NEVER;
}
return url.toString();
});
export const browserScenarioValueSchema = z.discriminatedUnion("source", [
z.strictObject({
source: z.literal("literal"),
value: z.string().max(65_536),
classification: z.literal("public"),
}),
z.strictObject({
source: z.literal("secret"),
secret_id: scenarioIdentifierSchema,
}),
]);
export type BrowserScenarioValue = z.infer<typeof browserScenarioValueSchema>;
const queryEntrySchema = z.strictObject({
name: z.string().min(1).max(256),
value: browserScenarioValueSchema,
});
/** URL whose values remain explicit public literals or declared secret references. */
export const browserScenarioUrlSchema = z.strictObject({
url: browserScenarioBaseUrlSchema,
query: z.array(queryEntrySchema).max(64).default([]),
});
export type BrowserScenarioUrl = z.infer<typeof browserScenarioUrlSchema>;
export const browserScenarioBrowserSchema = z.discriminatedUnion("mode", [
z.strictObject({
mode: z.literal("launch"),
executable_path: absoluteExecutablePathSchema,
headless: z.literal(true),
user_data: z.literal("temporary-owned"),
cleanup: z.literal("close-and-delete-profile"),
}),
z.strictObject({
mode: z.literal("connect"),
cdp_endpoint: browserEndpointSchema,
target_id: z.string().trim().min(1).max(256),
ownership: z.literal("external"),
cleanup: z.literal("disconnect-only"),
}),
]);
export const browserScenarioEnvironmentSchema = z.strictObject({
viewport: z.strictObject({
width: z.number().int().min(320).max(7_680),
height: z.number().int().min(240).max(4_320),
device_scale_factor: z.number().min(0.5).max(4).default(1),
}),
locale: z
.string()
.min(2)
.max(64)
.regex(/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/u),
timezone: z
.string()
.min(1)
.max(128)
.regex(/^[A-Za-z0-9_+-]+(?:\/[A-Za-z0-9_+-]+)*$/u),
color_scheme: z.enum(["light", "dark", "no-preference"]),
reduced_motion: z.enum(["reduce", "no-preference"]),
service_workers: z.literal("block"),
});
const locatorSchema = z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("test_id"),
value: z.string().min(1).max(512),
}),
z.strictObject({
kind: z.literal("role"),
role: z.enum([
"button",
"checkbox",
"combobox",
"dialog",
"link",
"listbox",
"menuitem",
"option",
"radio",
"slider",
"spinbutton",
"switch",
"tab",
"textbox",
]),
name: z.string().min(1).max(1_024),
exact: z.literal(true),
}),
z.strictObject({
kind: z.literal("css"),
selector: z.string().min(1).max(4_096),
approved: z.literal(true),
}),
]);
const stepBase = {
step_id: scenarioIdentifierSchema,
timeout_ms: z
.number()
.int()
.min(1)
.max(BROWSER_SCENARIO_LIMITS.actionTimeoutMs)
.optional(),
};
export const browserScenarioActionSchema = z.discriminatedUnion("action", [
z.strictObject({
...stepBase,
action: z.literal("goto"),
destination: browserScenarioUrlSchema,
wait_until: z.enum(["commit", "domcontentloaded", "load"]),
}),
z.strictObject({
...stepBase,
action: z.literal("click"),
locator: locatorSchema,
button: z.enum(["left", "middle", "right"]).default("left"),
click_count: z.number().int().min(1).max(3).default(1),
}),
z.strictObject({
...stepBase,
action: z.literal("fill"),
locator: locatorSchema,
value: browserScenarioValueSchema,
}),
z.strictObject({
...stepBase,
action: z.literal("press"),
locator: locatorSchema,
key: z.string().min(1).max(64),
}),
z.strictObject({
...stepBase,
action: z.literal("select_option"),
locator: locatorSchema,
value: browserScenarioValueSchema,
}),
z.strictObject({
...stepBase,
action: z.enum(["check", "uncheck"]),
locator: locatorSchema,
}),
z.strictObject({
...stepBase,
action: z.literal("wait_for"),
locator: locatorSchema,
state: z.enum(["attached", "detached", "visible", "hidden"]),
}),
z.strictObject({
step_id: scenarioIdentifierSchema,
action: z.literal("wait_for_timeout"),
duration_ms: z
.number()
.int()
.min(1)
.max(BROWSER_SCENARIO_LIMITS.actionTimeoutMs),
}),
]);
export type BrowserScenarioAction = z.infer<typeof browserScenarioActionSchema>;
const storageEntrySchema = z.strictObject({
name: z.string().min(1).max(1_024),
value: browserScenarioValueSchema,
});
export const browserScenarioStorageSchema = z.strictObject({
cookies: z
.array(
z.strictObject({
name: z.string().min(1).max(1_024),
value: browserScenarioValueSchema,
destination: browserScenarioUrlSchema,
http_only: z.boolean(),
secure: z.boolean(),
same_site: z.enum(["Strict", "Lax", "None"]),
}),
)
.max(128)
.default([]),
local_storage: z
.array(
z.strictObject({
origin: browserOriginSchema,
entries: z.array(storageEntrySchema).max(128),
}),
)
.max(32)
.default([]),
session_storage: z
.array(
z.strictObject({
origin: browserOriginSchema,
entries: z.array(storageEntrySchema).max(128),
}),
)
.max(32)
.default([]),
});
const headerNameSchema = z
.string()
.min(1)
.max(256)
.regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u)
.transform((value) => value.toLowerCase());
const replayHeaderSchema = z.strictObject({
name: headerNameSchema,
value: browserScenarioValueSchema,
});
const replayResponseSchema = z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("response"),
status: z.number().int().min(100).max(599),
headers: z.array(replayHeaderSchema).max(64).default([]),
body: browserScenarioValueSchema.optional(),
}),
z.strictObject({
kind: z.literal("redirect"),
status: z.union([
z.literal(301),
z.literal(302),
z.literal(303),
z.literal(307),
z.literal(308),
]),
destination: browserScenarioUrlSchema,
}),
]);
const replayRouteSchema = z.strictObject({
route_id: scenarioIdentifierSchema,
method: z.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]),
request: browserScenarioUrlSchema,
response: replayResponseSchema,
});
export const browserScenarioRequestReplaySchema = z.discriminatedUnion("mode", [
z.strictObject({ mode: z.literal("disabled") }),
z.strictObject({
mode: z.literal("exact"),
unmatched: z.enum(["abort", "passthrough-approved-origins"]),
routes: z
.array(replayRouteSchema)
.min(1)
.max(BROWSER_SCENARIO_LIMITS.replayRoutes),
}),
]);
export const browserScenarioSecretSchema = z.strictObject({
secret_id: scenarioIdentifierSchema,
environment_variable: z.string().regex(/^[A-Z_][A-Z0-9_]{0,127}$/u),
purpose: z.enum(["input", "storage", "request-replay"]),
redaction: z.literal("replace-with-secret-reference"),
});
const REQUIRED_REDACTED_HEADERS = [
"authorization",
"cookie",
"proxy-authorization",
"set-cookie",
] as const;
const normalizedNames = (maximum: number) =>
z
.array(
z
.string()
.trim()
.min(1)
.max(256)
.transform((value) => value.toLowerCase()),
)
.max(maximum)
.transform((values) => [...new Set(values)].sort());
export const browserScenarioRedactionSchema = z
.strictObject({
secret_values: z.literal("replace-with-secret-reference"),
query_parameter_names: normalizedNames(128).default([]),
header_names: normalizedNames(128).default([...REQUIRED_REDACTED_HEADERS]),
})
.superRefine(({ header_names: names }, context) => {
for (const required of REQUIRED_REDACTED_HEADERS)
if (!names.includes(required))
context.addIssue({
code: "custom",
path: ["header_names"],
message: `Required credential header ${required} must be redacted`,
});
});
const snapshotKindSchema = z.enum([
"screenshot",
"dom",
"accessibility",
"url",
"history",
"storage",
]);
export const browserScenarioCaptureSchema = z.strictObject({
after_each_step: z.array(snapshotKindSchema).max(6),
at_end: z.array(snapshotKindSchema).max(6),
events: z.array(
z.enum([
"console",
"page-errors",
"network",
"websockets",
"frames",
"workers",
"popups",
"downloads",
]),
),
});
export const browserScenarioCaptureLimitsSchema = z.strictObject({
max_duration_ms: z
.number()
.int()
.min(100)
.max(BROWSER_SCENARIO_LIMITS.durationMs),
action_timeout_ms: z
.number()
.int()
.min(1)
.max(BROWSER_SCENARIO_LIMITS.actionTimeoutMs),
navigation_timeout_ms: z
.number()
.int()
.min(1)
.max(BROWSER_SCENARIO_LIMITS.actionTimeoutMs),
max_events: z.number().int().min(1).max(100_000),
max_frames: z.number().int().min(1).max(1_000),
max_workers: z.number().int().min(0).max(1_000),
max_popups: z.number().int().min(0).max(100),
max_websockets: z.number().int().min(0).max(10_000),
max_dom_nodes: z.number().int().min(1).max(100_000),
max_accessibility_nodes: z.number().int().min(1).max(100_000),
max_screenshots: z.number().int().min(0).max(256),
max_screenshot_bytes: z
.number()
.int()
.min(1)
.max(8 * 1_024 * 1_024),
max_storage_entries: z
.number()
.int()
.min(0)
.max(BROWSER_SCENARIO_LIMITS.storageEntries),
max_total_metadata_bytes: z
.number()
.int()
.min(1_024)
.max(64 * 1_024 * 1_024),
});
export const browserScenarioAllowedOriginsSchema = browserAllowedOriginsSchema;
+1 -1
View File
@@ -11,7 +11,7 @@ import {
const MAX_SCREENSHOT_BYTES = 8 * 1_024 * 1_024;
/** Self-verifying inline PNG artifact for CLI/MCP parity. */
const webScreenshotArtifactSchema = z
export 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),