feat(browser): capture controlled Playwright scenarios
This commit is contained in:
@@ -0,0 +1,283 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { browserScenarioSchema } from "../src/domain/browserScenario.js";
|
||||
|
||||
const secret = (secret_id: string) => ({ source: "secret", secret_id });
|
||||
const literal = (value: string) => ({
|
||||
source: "literal",
|
||||
value,
|
||||
classification: "public",
|
||||
});
|
||||
|
||||
const baseScenario = () => ({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium/chrome",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: {
|
||||
url: "https://app.example.test/",
|
||||
query: [{ name: "token", value: secret("session") }],
|
||||
},
|
||||
allowed_origins: ["https://api.example.test", "https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "dark",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "login",
|
||||
action: "fill",
|
||||
locator: { kind: "test_id", value: "password" },
|
||||
value: secret("password"),
|
||||
},
|
||||
{
|
||||
step_id: "submit",
|
||||
action: "click",
|
||||
locator: {
|
||||
kind: "role",
|
||||
role: "button",
|
||||
name: "Sign in",
|
||||
exact: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
step_id: "dashboard",
|
||||
action: "goto",
|
||||
destination: { url: "https://app.example.test/dashboard" },
|
||||
wait_until: "load",
|
||||
},
|
||||
],
|
||||
storage: {
|
||||
cookies: [
|
||||
{
|
||||
name: "sid",
|
||||
value: secret("cookie"),
|
||||
destination: { url: "https://app.example.test/" },
|
||||
http_only: true,
|
||||
secure: true,
|
||||
same_site: "Lax",
|
||||
},
|
||||
],
|
||||
local_storage: [
|
||||
{
|
||||
origin: "https://app.example.test",
|
||||
entries: [{ name: "theme", value: literal("dark") }],
|
||||
},
|
||||
],
|
||||
},
|
||||
request_replay: {
|
||||
mode: "exact",
|
||||
unmatched: "abort",
|
||||
routes: [
|
||||
{
|
||||
route_id: "profile",
|
||||
method: "GET",
|
||||
request: { url: "https://api.example.test/profile" },
|
||||
response: {
|
||||
kind: "response",
|
||||
status: 200,
|
||||
headers: [
|
||||
{
|
||||
name: "content-type",
|
||||
value: literal("application/json"),
|
||||
},
|
||||
],
|
||||
body: literal('{"name":"Ada"}'),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
secrets: [
|
||||
{
|
||||
secret_id: "session",
|
||||
environment_variable: "REA_TEST_SESSION",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
{
|
||||
secret_id: "password",
|
||||
environment_variable: "REA_TEST_PASSWORD",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
{
|
||||
secret_id: "cookie",
|
||||
environment_variable: "REA_TEST_COOKIE",
|
||||
purpose: "storage",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: ["token"],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: ["screenshot", "url", "accessibility"],
|
||||
at_end: ["dom", "storage"],
|
||||
events: ["console", "page-errors", "network", "websockets"],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 60_000,
|
||||
action_timeout_ms: 5_000,
|
||||
navigation_timeout_ms: 10_000,
|
||||
max_events: 2_000,
|
||||
max_frames: 100,
|
||||
max_workers: 20,
|
||||
max_popups: 10,
|
||||
max_websockets: 100,
|
||||
max_dom_nodes: 10_000,
|
||||
max_accessibility_nodes: 10_000,
|
||||
max_screenshots: 16,
|
||||
max_screenshot_bytes: 4 * 1_024 * 1_024,
|
||||
max_storage_entries: 256,
|
||||
max_total_metadata_bytes: 4 * 1_024 * 1_024,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
|
||||
describe("browserScenarioSchema", () => {
|
||||
it("accepts and normalizes a bounded declared scenario", () => {
|
||||
const parsed = browserScenarioSchema.parse(baseScenario());
|
||||
expect(parsed.allowed_origins).toEqual([
|
||||
"https://api.example.test",
|
||||
"https://app.example.test",
|
||||
]);
|
||||
expect(parsed.environment.viewport.device_scale_factor).toBe(1);
|
||||
expect(parsed.redaction.header_names).toEqual([
|
||||
"authorization",
|
||||
"cookie",
|
||||
"proxy-authorization",
|
||||
"set-cookie",
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects unsupported actions", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.actions = [
|
||||
{
|
||||
step_id: "script",
|
||||
action: "evaluate",
|
||||
expression: "document.cookie",
|
||||
} as never,
|
||||
];
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects every undeclared navigation, storage, and replay origin", () => {
|
||||
for (const mutate of [
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.start_url.url = "https://other.example.test/";
|
||||
},
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.actions[2] = {
|
||||
...scenario.actions[2],
|
||||
destination: { url: "https://other.example.test/" },
|
||||
} as never;
|
||||
},
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.storage.local_storage[0]!.origin =
|
||||
"https://other.example.test";
|
||||
},
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.request_replay.routes[0]!.request.url =
|
||||
"https://other.example.test/data";
|
||||
},
|
||||
]) {
|
||||
const scenario = baseScenario();
|
||||
mutate(scenario);
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects redirects outside declared origins", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.request_replay.routes[0]!.response = {
|
||||
kind: "redirect",
|
||||
status: 302,
|
||||
destination: { url: "https://other.example.test/" },
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects missing, duplicate, and unused secret declarations", () => {
|
||||
const missing = baseScenario();
|
||||
missing.secrets = missing.secrets.filter(
|
||||
({ secret_id }) => secret_id !== "password",
|
||||
);
|
||||
expect(browserScenarioSchema.safeParse(missing).success).toBe(false);
|
||||
|
||||
const duplicate = baseScenario();
|
||||
duplicate.secrets.push({ ...duplicate.secrets[0]! });
|
||||
expect(browserScenarioSchema.safeParse(duplicate).success).toBe(false);
|
||||
|
||||
const unused = baseScenario();
|
||||
unused.secrets.push({
|
||||
secret_id: "unused",
|
||||
environment_variable: "REA_TEST_UNUSED",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
});
|
||||
expect(browserScenarioSchema.safeParse(unused).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects secret query values without named redaction", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.redaction.query_parameter_names = [];
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects literal credential headers and provider-owned headers", () => {
|
||||
for (const name of ["authorization", "content-length"]) {
|
||||
const scenario = baseScenario();
|
||||
scenario.request_replay.routes[0]!.response = {
|
||||
kind: "response",
|
||||
status: 200,
|
||||
headers: [{ name, value: literal("raw") }],
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects raw secret-shaped action values", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.actions[0] = {
|
||||
...scenario.actions[0],
|
||||
value: "raw-password",
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects embedded URL credentials and query values", () => {
|
||||
for (const url of [
|
||||
"https://user:password@app.example.test/",
|
||||
"https://app.example.test/?token=raw",
|
||||
]) {
|
||||
const scenario = baseScenario();
|
||||
scenario.start_url.url = url;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("requires explicit external ownership for CDP connections", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.browser = {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
ownership: "external",
|
||||
cleanup: "disconnect-only",
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(true);
|
||||
|
||||
scenario.browser.cleanup = "close-browser" as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,278 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { dirname } from "node:path";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
|
||||
import type { BrowserScenarioCapturePort } from "../src/application/BrowserScenarioCapturePort.js";
|
||||
import { BinarySession } from "../src/application/BinarySession.js";
|
||||
import { loadConfiguredPermissionAuthority } from "../src/application/PermissionConfiguration.js";
|
||||
import type {
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../src/application/AnalysisProvider.js";
|
||||
import { CdpBrowserProvider } from "../src/browser/CdpBrowserProvider.js";
|
||||
import { parseConfig } from "../src/config.js";
|
||||
import { sanitizeBrowserUrl } from "../src/domain/browserObservation.js";
|
||||
import type { BrowserScenario } from "../src/domain/browserScenario.js";
|
||||
import {
|
||||
browserScenarioCaptureSchema,
|
||||
type BrowserScenarioCapture,
|
||||
} from "../src/domain/browserScenarioCapture.js";
|
||||
import type { AnalysisError } from "../src/domain/errors.js";
|
||||
import { ok, type Result } from "../src/domain/result.js";
|
||||
import { createServer } from "../src/server/createServer.js";
|
||||
import { observed } from "./fixtures/analysisExecution.js";
|
||||
|
||||
const providerIdentity: ProviderIdentity = {
|
||||
id: "test-browser-scenario",
|
||||
name: "Test browser scenario provider",
|
||||
version: "1",
|
||||
};
|
||||
|
||||
class FakeBrowserScenarioProvider implements BrowserScenarioCapturePort {
|
||||
readonly scenarios: BrowserScenario[] = [];
|
||||
|
||||
identity(): ProviderIdentity {
|
||||
return providerIdentity;
|
||||
}
|
||||
|
||||
captureScenario(
|
||||
scenario: BrowserScenario,
|
||||
_options?: ExecutionOptions,
|
||||
): Promise<Result<BrowserScenarioCapture, AnalysisError>> {
|
||||
this.scenarios.push(scenario);
|
||||
return Promise.resolve(ok(captureFor(scenario)));
|
||||
}
|
||||
}
|
||||
|
||||
const artifacts = {
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "not_requested" },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "not_requested" },
|
||||
history: { state: "not_requested" },
|
||||
storage: { state: "not_requested" },
|
||||
} as const;
|
||||
|
||||
const captureFor = (scenario: BrowserScenario): BrowserScenarioCapture => {
|
||||
const start = scenario.start_url.url;
|
||||
const step = (stepIndex: number, stepId: string, action: string) => ({
|
||||
step_index: stepIndex,
|
||||
step_id: stepId,
|
||||
action,
|
||||
status: "completed",
|
||||
elapsed_ms: 1,
|
||||
before_url: sanitizeBrowserUrl(start),
|
||||
after_url: sanitizeBrowserUrl(start),
|
||||
error: null,
|
||||
event_sequence_start: 1,
|
||||
event_sequence_end: 0,
|
||||
artifacts,
|
||||
completeness: {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
},
|
||||
});
|
||||
return browserScenarioCaptureSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: scenario.browser.mode,
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
product: "Test Browser",
|
||||
version: "1",
|
||||
},
|
||||
scenario: {
|
||||
start_origin: new URL(start).origin,
|
||||
allowed_origins: scenario.allowed_origins,
|
||||
action_count: scenario.actions.length,
|
||||
secret_references: scenario.secrets.map(({ secret_id: id }) => id),
|
||||
},
|
||||
duration_ms: 2,
|
||||
steps: [
|
||||
step(0, "scenario_start", "goto_start"),
|
||||
...scenario.actions.map((action, index) =>
|
||||
step(index + 1, action.step_id, action.action),
|
||||
),
|
||||
],
|
||||
events: { retained: 0, dropped: 0, items: [] },
|
||||
completeness: {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
};
|
||||
|
||||
const scenario = (origin = "https://app.example.test") => ({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
executable_path: process.execPath,
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: { url: `${origin}/`, query: [] },
|
||||
allowed_origins: [origin],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "password",
|
||||
action: "fill",
|
||||
locator: { kind: "test_id", value: "password" },
|
||||
value: { source: "secret", secret_id: "password" },
|
||||
},
|
||||
],
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [
|
||||
{
|
||||
secret_id: "password",
|
||||
environment_variable: "REA_TEST_PASSWORD",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: { after_each_step: [], at_end: [], events: [] },
|
||||
limits: {
|
||||
max_duration_ms: 10_000,
|
||||
action_timeout_ms: 1_000,
|
||||
navigation_timeout_ms: 1_000,
|
||||
max_events: 100,
|
||||
max_frames: 10,
|
||||
max_workers: 5,
|
||||
max_popups: 2,
|
||||
max_websockets: 10,
|
||||
max_dom_nodes: 1_000,
|
||||
max_accessibility_nodes: 1_000,
|
||||
max_screenshots: 2,
|
||||
max_screenshot_bytes: 1_048_576,
|
||||
max_storage_entries: 100,
|
||||
max_total_metadata_bytes: 1_048_576,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
|
||||
describe("browser scenario MCP tool", () => {
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(resources.splice(0).map((item) => item.close()));
|
||||
});
|
||||
|
||||
test("authorizes exact scope, records Evidence, and retains no secret value", async () => {
|
||||
const configured = parseConfig({
|
||||
REA_BROWSER_SCENARIO_ENABLED: "true",
|
||||
REA_BROWSER_SCENARIO_AUTO_GRANT: "true",
|
||||
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: JSON.stringify([
|
||||
dirname(process.execPath),
|
||||
]),
|
||||
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
|
||||
REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON: '["REA_TEST_PASSWORD"]',
|
||||
});
|
||||
if (!configured.ok) throw configured.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(configured.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const provider = new FakeBrowserScenarioProvider();
|
||||
const session = new BinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
browserObservation: new CdpBrowserProvider(),
|
||||
browserScenarioCapture: provider,
|
||||
permissionAuthority: authority.value,
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
investigationInputRoots: 0,
|
||||
browserObservationEnabled: true,
|
||||
browserScenarioEnabled: true,
|
||||
}),
|
||||
});
|
||||
const client = new Client({ name: "browser-scenario-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server, session);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const captured = await client.callTool({
|
||||
name: "capture_browser_scenario",
|
||||
arguments: scenario(),
|
||||
});
|
||||
expect(captured.isError, JSON.stringify(captured)).not.toBe(true);
|
||||
expect(captured.structuredContent).toMatchObject({
|
||||
result: {
|
||||
scenario: {
|
||||
secret_references: ["password"],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(provider.scenarios).toHaveLength(1);
|
||||
expect(JSON.stringify(captured.structuredContent)).not.toContain(
|
||||
"correct horse battery staple",
|
||||
);
|
||||
const evidenceId = Reflect.get(
|
||||
captured.structuredContent ?? {},
|
||||
"evidence_id",
|
||||
);
|
||||
expect(session.evidenceById(String(evidenceId))).toMatchObject({
|
||||
predicate_type: "rea.browser-scenario-capture/v1",
|
||||
});
|
||||
const captureResult = Reflect.get(
|
||||
captured.structuredContent ?? {},
|
||||
"result",
|
||||
);
|
||||
const compared = await client.callTool({
|
||||
name: "compare_web_captures",
|
||||
arguments: {
|
||||
before_scenario: captureResult,
|
||||
after_scenario: captureResult,
|
||||
normalization: { rules: [] },
|
||||
},
|
||||
});
|
||||
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
|
||||
expect(compared.structuredContent).toMatchObject({
|
||||
result: {
|
||||
comparison_kind: "browser_scenario",
|
||||
overall_status: "unchanged",
|
||||
alignment: { status: "aligned", aligned_steps: 2 },
|
||||
},
|
||||
});
|
||||
|
||||
const denied = await client.callTool({
|
||||
name: "capture_browser_scenario",
|
||||
arguments: scenario("https://other.example.test"),
|
||||
});
|
||||
expect(denied.isError).toBe(true);
|
||||
expect(provider.scenarios).toHaveLength(1);
|
||||
|
||||
const unapprovedEnvironment = scenario();
|
||||
const secretDeclaration = unapprovedEnvironment.secrets.at(0);
|
||||
if (secretDeclaration === undefined)
|
||||
throw new Error("Scenario secret fixture disappeared");
|
||||
secretDeclaration.environment_variable = "REA_UNAPPROVED_SECRET";
|
||||
const deniedSecret = await client.callTool({
|
||||
name: "capture_browser_scenario",
|
||||
arguments: unapprovedEnvironment,
|
||||
});
|
||||
expect(deniedSecret.isError).toBe(true);
|
||||
expect(provider.scenarios).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,388 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BrowserScenarioSessionPort } from "../src/browser/BrowserScenarioSessionPort.js";
|
||||
import { PlaywrightBrowserScenarioProvider } from "../src/browser/PlaywrightBrowserScenarioProvider.js";
|
||||
import { BrowserScenarioCaptureBudget } from "../src/browser/PlaywrightScenarioArtifacts.js";
|
||||
import { sanitizeBrowserUrl } from "../src/domain/browserObservation.js";
|
||||
import {
|
||||
browserScenarioSchema,
|
||||
type BrowserScenario,
|
||||
type BrowserScenarioAction,
|
||||
} from "../src/domain/browserScenario.js";
|
||||
import {
|
||||
browserStepArtifactsSchema,
|
||||
type BrowserScenarioEvent,
|
||||
type BrowserStepArtifacts,
|
||||
} from "../src/domain/browserScenarioCapture.js";
|
||||
|
||||
const scenario = (
|
||||
options: {
|
||||
readonly mode?: "launch" | "connect";
|
||||
readonly captures?: readonly (
|
||||
| "screenshot"
|
||||
| "dom"
|
||||
| "accessibility"
|
||||
| "url"
|
||||
| "history"
|
||||
| "storage"
|
||||
)[];
|
||||
readonly events?: readonly (
|
||||
| "console"
|
||||
| "page-errors"
|
||||
| "network"
|
||||
| "websockets"
|
||||
| "frames"
|
||||
| "workers"
|
||||
| "popups"
|
||||
| "downloads"
|
||||
)[];
|
||||
readonly actions?: number;
|
||||
} = {},
|
||||
): BrowserScenario =>
|
||||
browserScenarioSchema.parse({
|
||||
schema_version: 1,
|
||||
browser:
|
||||
options.mode === "connect"
|
||||
? {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
ownership: "external",
|
||||
cleanup: "disconnect-only",
|
||||
}
|
||||
: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: Array.from({ length: options.actions ?? 1 }, (_, index) => ({
|
||||
step_id: `wait_${index}`,
|
||||
action: "wait_for_timeout",
|
||||
duration_ms: 1,
|
||||
})),
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: options.captures ?? ["url"],
|
||||
at_end: [],
|
||||
events: options.events ?? [],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 10_000,
|
||||
action_timeout_ms: 1_000,
|
||||
navigation_timeout_ms: 1_000,
|
||||
max_events: 100,
|
||||
max_frames: 10,
|
||||
max_workers: 10,
|
||||
max_popups: 10,
|
||||
max_websockets: 10,
|
||||
max_dom_nodes: 100,
|
||||
max_accessibility_nodes: 100,
|
||||
max_screenshots: 2,
|
||||
max_screenshot_bytes: 1_024,
|
||||
max_storage_entries: 10,
|
||||
max_total_metadata_bytes: 16_384,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
|
||||
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
|
||||
|
||||
const artifactState = (
|
||||
kind: SnapshotKind,
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
incomplete: boolean,
|
||||
) => {
|
||||
if (!requested.has(kind)) return { state: "not_requested" as const };
|
||||
if (kind === "url")
|
||||
return {
|
||||
state: "captured" as const,
|
||||
value: sanitizeBrowserUrl("https://app.example.test/current"),
|
||||
};
|
||||
if (incomplete && kind === "screenshot")
|
||||
return {
|
||||
state: "truncated" as const,
|
||||
observed: 2_048,
|
||||
retained: 0,
|
||||
reason: "fixture limit",
|
||||
};
|
||||
return { state: "missing" as const, reason: "fixture unavailable" };
|
||||
};
|
||||
|
||||
class FakeSession implements BrowserScenarioSessionPort {
|
||||
readonly product = "Fake Chromium";
|
||||
readonly version = "1";
|
||||
readonly initialUrl = "about:blank";
|
||||
readonly processOwnership: "provider-owned" | "external";
|
||||
closeCalls = 0;
|
||||
performCalls = 0;
|
||||
captureCalls = 0;
|
||||
eventTruncations: (
|
||||
| "events"
|
||||
| "frames"
|
||||
| "workers"
|
||||
| "popups"
|
||||
| "websockets"
|
||||
)[] = [];
|
||||
onPerform: (() => void) | undefined;
|
||||
private step = 0;
|
||||
|
||||
constructor(
|
||||
readonly mode: "launch" | "connect",
|
||||
private readonly incomplete = false,
|
||||
private readonly failAction = false,
|
||||
private readonly failCapture = false,
|
||||
) {
|
||||
this.processOwnership = mode === "launch" ? "provider-owned" : "external";
|
||||
}
|
||||
|
||||
currentUrl() {
|
||||
return "https://app.example.test/current";
|
||||
}
|
||||
|
||||
setStep(index: number) {
|
||||
this.step = index;
|
||||
}
|
||||
|
||||
nextEventSequence() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
lastEventSequence() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
events(): {
|
||||
readonly retained: number;
|
||||
readonly dropped: number;
|
||||
readonly items: readonly BrowserScenarioEvent[];
|
||||
} {
|
||||
return { retained: 0, dropped: 0, items: [] };
|
||||
}
|
||||
|
||||
eventTruncationSections() {
|
||||
return this.eventTruncations;
|
||||
}
|
||||
|
||||
async perform(
|
||||
_action: BrowserScenarioAction,
|
||||
_timeout: number,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
this.performCalls += 1;
|
||||
this.onPerform?.();
|
||||
if (signal?.aborted === true) throw new Error("request cancelled");
|
||||
if (this.failAction) throw new Error("fixture secret action failure");
|
||||
}
|
||||
|
||||
capture(
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
_budget: BrowserScenarioCaptureBudget,
|
||||
): Promise<BrowserStepArtifacts> {
|
||||
this.captureCalls += 1;
|
||||
if (this.failCapture) return Promise.reject(new Error("capture failed"));
|
||||
return Promise.resolve(
|
||||
browserStepArtifactsSchema.parse({
|
||||
screenshot: artifactState("screenshot", requested, this.incomplete),
|
||||
dom: artifactState("dom", requested, this.incomplete),
|
||||
accessibility: artifactState(
|
||||
"accessibility",
|
||||
requested,
|
||||
this.incomplete,
|
||||
),
|
||||
url: artifactState("url", requested, this.incomplete),
|
||||
history: artifactState("history", requested, this.incomplete),
|
||||
storage: artifactState("storage", requested, this.incomplete),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closeCalls += 1;
|
||||
return Promise.resolve(
|
||||
this.mode === "launch"
|
||||
? ("terminated-owned-process" as const)
|
||||
: ("disconnected-external" as const),
|
||||
);
|
||||
}
|
||||
|
||||
redactError(error: unknown) {
|
||||
return error instanceof Error
|
||||
? error.message.replaceAll("secret", "[REDACTED]")
|
||||
: "fixture failure";
|
||||
}
|
||||
}
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider", () => {
|
||||
it("captures initial and action steps and closes its launched session", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario());
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps.map(({ step_index }) => step_index)).toEqual([
|
||||
0, 1,
|
||||
]);
|
||||
expect(result.value.browser).toMatchObject({
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
});
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("makes missing and truncated captures ineligible for equality", async () => {
|
||||
const session = new FakeSession("launch", true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ captures: ["screenshot", "dom"] }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["dom"],
|
||||
truncated_sections: ["screenshot"],
|
||||
});
|
||||
});
|
||||
|
||||
it("makes event limit truncation ineligible for equality", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
session.eventTruncations = ["events", "websockets"];
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ events: ["websockets"] }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
truncated_sections: ["events", "websockets"],
|
||||
});
|
||||
});
|
||||
|
||||
it("records one failed step, cancels later actions, and still cleans up", async () => {
|
||||
const session = new FakeSession("launch", false, true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario({ actions: 2 }));
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps.map(({ status }) => status)).toEqual([
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
]);
|
||||
expect(result.value.steps[1]?.error).toBe(
|
||||
"fixture [REDACTED] action failure",
|
||||
);
|
||||
expect(session.performCalls).toBe(1);
|
||||
expect(session.closeCalls).toBe(1);
|
||||
expect(result.value.completeness.equality_eligible).toBe(false);
|
||||
});
|
||||
|
||||
it("disconnects external CDP sessions and marks pre-attach events missing", async () => {
|
||||
const session = new FakeSession("connect");
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ mode: "connect" }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.browser).toMatchObject({
|
||||
process_ownership: "external",
|
||||
cleanup: "disconnected-external",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "incomplete",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["events"],
|
||||
});
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("closes the session when initial capture fails", async () => {
|
||||
const session = new FakeSession("launch", false, false, true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario());
|
||||
expect(result.ok).toBe(false);
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("does not open a session for an already-cancelled request", async () => {
|
||||
let opens = 0;
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => {
|
||||
opens += 1;
|
||||
return Promise.resolve(new FakeSession("launch"));
|
||||
},
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const result = await provider.captureScenario(scenario(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
expect(opens).toBe(0);
|
||||
});
|
||||
|
||||
it("cancels an active action and still closes the session", async () => {
|
||||
const controller = new AbortController();
|
||||
const session = new FakeSession("launch");
|
||||
session.onPerform = () => controller.abort();
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps[1]?.status).toBe("cancelled");
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BrowserScenarioCaptureBudget", () => {
|
||||
it("enforces cumulative screenshot and metadata limits", () => {
|
||||
const budget = new BrowserScenarioCaptureBudget(1, 10);
|
||||
expect(budget.claimScreenshot()).toBe(true);
|
||||
expect(budget.claimScreenshot()).toBe(false);
|
||||
expect(budget.claimMetadata(6)).toBe(true);
|
||||
expect(budget.claimMetadata(5)).toBe(false);
|
||||
expect(budget.claimMetadata(4)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { withPlaywrightExecutionBoundary } from "../src/browser/PlaywrightExecutionBoundary.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../src/domain/errors.js";
|
||||
|
||||
describe("withPlaywrightExecutionBoundary", () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("rejects work that exceeds its absolute remaining duration", async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = withPlaywrightExecutionBoundary(
|
||||
() => new Promise<never>(() => undefined),
|
||||
25,
|
||||
);
|
||||
const rejection =
|
||||
expect(result).rejects.toBeInstanceOf(AnalysisTimeoutError);
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
await rejection;
|
||||
});
|
||||
|
||||
it("rejects when the caller cancels active work", async () => {
|
||||
const controller = new AbortController();
|
||||
const result = withPlaywrightExecutionBoundary(
|
||||
() => new Promise<never>(() => undefined),
|
||||
1_000,
|
||||
controller.signal,
|
||||
);
|
||||
controller.abort();
|
||||
await expect(result).rejects.toBeInstanceOf(AnalysisCancelledError);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user