refactor!: simplify runtime tools and remove replay engines (#572)
* fix(hopper): report unavailable procedure body coverage * refactor!: simplify runtime tools and remove replay engines Keep direct inspection, capture, and comparison tools. Bind handlers to named contracts and let agents compose experiments with commands and local fixture servers. BREAKING CHANGE: Remove controlled replay, Node characterization, finite replay-machine, managed runtime planning, and redundant string-tracing tools. Retire process replay, shims, reactive scenarios, custom checkpoints, and active browser replay and origin-scope inputs.
This commit is contained in:
@@ -18,7 +18,6 @@ const baseScenario = () => ({
|
||||
url: "https://app.example.test/",
|
||||
query: [{ name: "token", value: secret("session") }],
|
||||
},
|
||||
allowed_origins: ["https://api.example.test", "https://app.example.test"],
|
||||
actions: [
|
||||
{
|
||||
step_id: "login",
|
||||
@@ -60,28 +59,6 @@ const baseScenario = () => ({
|
||||
},
|
||||
],
|
||||
},
|
||||
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",
|
||||
@@ -106,10 +83,6 @@ const baseScenario = () => ({
|
||||
describe("browserScenarioSchema", () => {
|
||||
it("accepts and normalizes a declared scenario", () => {
|
||||
const parsed = browserScenarioSchema.parse(baseScenario());
|
||||
expect(parsed.allowed_origins).toEqual([
|
||||
"https://api.example.test",
|
||||
"https://app.example.test",
|
||||
]);
|
||||
expect(parsed.browser).toMatchObject({ mode: "launch", headless: true });
|
||||
expect(parsed.environment).toMatchObject({
|
||||
viewport: { width: 1_280, height: 720, device_scale_factor: 1 },
|
||||
@@ -119,11 +92,6 @@ describe("browserScenarioSchema", () => {
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
});
|
||||
expect(parsed.request_replay).toEqual({
|
||||
mode: "exact",
|
||||
unmatched: "abort",
|
||||
routes: expect.any(Array),
|
||||
});
|
||||
expect(parsed.capture).toEqual({
|
||||
after_each_step: ["screenshot", "url", "accessibility"],
|
||||
at_end: ["dom", "storage"],
|
||||
@@ -197,44 +165,18 @@ describe("browserScenarioSchema", () => {
|
||||
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("accepts explicitly selected navigation and storage origins without an allowlist", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.actions[2] = {
|
||||
...scenario.actions[2],
|
||||
destination: { url: "https://other.example.test/" },
|
||||
} as never;
|
||||
scenario.storage.local_storage[0]!.origin = "https://storage.example.test";
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("browserScenarioSchema credential handling", () => {
|
||||
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);
|
||||
});
|
||||
|
||||
describe("browserScenarioSchema secret declarations", () => {
|
||||
it("rejects missing and duplicate secret declarations but accepts redaction-only declarations", () => {
|
||||
const missing = baseScenario();
|
||||
missing.secrets = missing.secrets.filter(
|
||||
@@ -260,42 +202,17 @@ describe("browserScenarioSchema credential handling", () => {
|
||||
expect(browserScenarioSchema.safeParse(unused).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts literal credential headers and rejects provider-owned headers", () => {
|
||||
const credentialHeaders = baseScenario();
|
||||
credentialHeaders.request_replay.routes[0]!.response = {
|
||||
kind: "response",
|
||||
status: 200,
|
||||
headers: [
|
||||
{ name: "authorization", value: literal("Bearer caller-value") },
|
||||
{ name: "cookie", value: literal("session=caller-value") },
|
||||
{ name: "set-cookie", value: literal("session=caller-value") },
|
||||
],
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(credentialHeaders).success).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
for (const name of ["content-length", "location", "transfer-encoding"]) {
|
||||
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 duplicate replay response headers case-insensitively", () => {
|
||||
const scenario = baseScenario();
|
||||
const response = scenario.request_replay.routes[0]!.response;
|
||||
if (response.kind !== "response")
|
||||
throw new Error("Expected replay response fixture");
|
||||
response.headers.push({
|
||||
name: "Content-Type",
|
||||
value: literal("text/plain"),
|
||||
});
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
it("rejects removed replay and origin policy options", () => {
|
||||
for (const legacyField of [
|
||||
{ request_replay: { mode: "disabled" } },
|
||||
{ allowed_origins: ["https://app.example.test"] },
|
||||
])
|
||||
expect(
|
||||
browserScenarioSchema.safeParse({
|
||||
...baseScenario(),
|
||||
...legacyField,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects raw secret-shaped action values", () => {
|
||||
|
||||
@@ -51,14 +51,12 @@ const scenario = (
|
||||
executable_path: "/opt/chromium",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
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: [],
|
||||
capture: {
|
||||
after_each_step: options.captures ?? ["url"],
|
||||
|
||||
@@ -288,7 +288,6 @@ const runScenario = async (
|
||||
},
|
||||
scenario: {
|
||||
start_origin: new URL(scenario.start_url.url).origin,
|
||||
allowed_origins: scenario.allowed_origins,
|
||||
action_count: scenario.actions.length,
|
||||
secret_references: scenario.secrets.map(({ secret_id: id }) => id).sort(),
|
||||
},
|
||||
|
||||
@@ -11,7 +11,6 @@ const scenario = browserScenarioSchema.parse({
|
||||
executable_path: "/opt/chromium",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
|
||||
});
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
|
||||
@@ -27,7 +26,6 @@ it("returns a complete requested text artifact beyond the former inline ceiling"
|
||||
const result = await capturePlaywrightStepArtifacts({
|
||||
context: {} as BrowserContext,
|
||||
page,
|
||||
scenario,
|
||||
secrets,
|
||||
requested: new Set(["dom"]),
|
||||
});
|
||||
@@ -80,7 +78,6 @@ it("redacts declared secrets from current and historical URL artifacts", async (
|
||||
const result = await capturePlaywrightStepArtifacts({
|
||||
context: {} as BrowserContext,
|
||||
page,
|
||||
scenario: scenarioWithSecretUrl,
|
||||
secrets: scenarioSecrets,
|
||||
requested: new Set(["url", "history"]),
|
||||
});
|
||||
|
||||
@@ -134,12 +134,15 @@ const captureHistory = async (page: Page, secrets: BrowserScenarioSecrets) => {
|
||||
const captureStorage = async (input: {
|
||||
readonly context: BrowserContext;
|
||||
readonly page: Page;
|
||||
readonly scenario: BrowserScenario;
|
||||
readonly secrets: BrowserScenarioSecrets;
|
||||
}) => {
|
||||
const { context, page, scenario, secrets } = input;
|
||||
const { context, page, secrets } = input;
|
||||
try {
|
||||
const cookies = await context.cookies(scenario.allowed_origins);
|
||||
const pageUrl = new URL(page.url());
|
||||
const cookies =
|
||||
pageUrl.protocol === "http:" || pageUrl.protocol === "https:"
|
||||
? await context.cookies(pageUrl.href)
|
||||
: [];
|
||||
const pageStorage = storageValueSchema.parse(
|
||||
await page.evaluate(`(() => ({
|
||||
local_storage: Object.entries(window.localStorage),
|
||||
@@ -171,39 +174,20 @@ const captureStorage = async (input: {
|
||||
}
|
||||
};
|
||||
|
||||
const isAllowedPage = (
|
||||
page: Page,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): boolean => {
|
||||
try {
|
||||
return allowedOrigins.has(new URL(page.url()).origin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** Capture selected step artifacts without retaining data after scope loss. */
|
||||
export const capturePlaywrightStepArtifacts = async (input: {
|
||||
readonly context: BrowserContext;
|
||||
readonly page: Page;
|
||||
readonly scenario: BrowserScenario;
|
||||
readonly secrets: BrowserScenarioSecrets;
|
||||
readonly requested: ReadonlySet<SnapshotKind>;
|
||||
}): Promise<BrowserStepArtifacts> => {
|
||||
const { context, page, scenario, secrets, requested } = input;
|
||||
const allowed = isAllowedPage(page, new Set(scenario.allowed_origins));
|
||||
const denied = () => missing("current page is outside approved origins");
|
||||
const { context, page, secrets, requested } = input;
|
||||
const state = <Value>(
|
||||
kind: SnapshotKind,
|
||||
capture: () => Promise<Value>,
|
||||
): Promise<
|
||||
Value | ReturnType<typeof notRequested> | ReturnType<typeof missing>
|
||||
> =>
|
||||
!requested.has(kind)
|
||||
? Promise.resolve(notRequested())
|
||||
: allowed || kind === "url"
|
||||
? capture()
|
||||
: Promise.resolve(denied());
|
||||
> => (!requested.has(kind) ? Promise.resolve(notRequested()) : capture());
|
||||
return browserStepArtifactsSchema.parse({
|
||||
screenshot: await state("screenshot", () => captureScreenshot(page)),
|
||||
dom: await state("dom", () => captureDom({ page, secrets })),
|
||||
@@ -216,7 +200,7 @@ export const capturePlaywrightStepArtifacts = async (input: {
|
||||
})),
|
||||
history: await state("history", () => captureHistory(page, secrets)),
|
||||
storage: await state("storage", () =>
|
||||
captureStorage({ context, page, scenario, secrets }),
|
||||
captureStorage({ context, page, secrets }),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -48,21 +48,9 @@ const allowedBrowserEnvironment = (
|
||||
);
|
||||
};
|
||||
|
||||
const originAllowed = (
|
||||
value: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): boolean => {
|
||||
try {
|
||||
return allowedOrigins.has(new URL(value).origin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const findConnectedPage = async (
|
||||
browser: Browser,
|
||||
targetId: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): Promise<{ readonly context: BrowserContext; readonly page: Page }> => {
|
||||
for (const context of browser.contexts())
|
||||
for (const page of context.pages()) {
|
||||
@@ -70,11 +58,6 @@ const findConnectedPage = async (
|
||||
try {
|
||||
const { targetInfo } = await session.send("Target.getTargetInfo");
|
||||
if (targetInfo.targetId !== targetId) continue;
|
||||
if (
|
||||
page.url() !== "about:blank" &&
|
||||
!originAllowed(page.url(), allowedOrigins)
|
||||
)
|
||||
throw new BrowserObservationError(OPERATION, "target_not_allowed");
|
||||
return { context, page };
|
||||
} finally {
|
||||
await session.detach();
|
||||
@@ -128,7 +111,6 @@ export const openPlaywrightScenarioBrowser = async (
|
||||
const target = await findConnectedPage(
|
||||
browser,
|
||||
scenario.browser.target_id,
|
||||
new Set(scenario.allowed_origins),
|
||||
);
|
||||
await configureAttachedEnvironment(target.context, target.page, scenario);
|
||||
return { ...target, browser, profilePath: undefined };
|
||||
|
||||
@@ -20,7 +20,6 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
executable_path: "/opt/chromium",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
@@ -36,7 +35,6 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
},
|
||||
],
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
capture: {
|
||||
after_each_step: [],
|
||||
@@ -50,7 +48,6 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
page,
|
||||
enabled: new Set(["page-errors"]),
|
||||
secrets,
|
||||
allowedOrigins: scenario.allowed_origins,
|
||||
});
|
||||
const error = new Error("m".repeat(70_000));
|
||||
error.stack = "s".repeat(300_000);
|
||||
@@ -79,7 +76,6 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
executable_path: "/opt/chromium",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
actions: [
|
||||
{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 },
|
||||
],
|
||||
@@ -91,7 +87,6 @@ describe("PlaywrightScenarioEvents", () => {
|
||||
page,
|
||||
enabled: new Set(["page-errors"]),
|
||||
secrets,
|
||||
allowedOrigins: scenario.allowed_origins,
|
||||
});
|
||||
for (let index = 0; index < 2_001; index += 1)
|
||||
listeners
|
||||
|
||||
@@ -36,7 +36,6 @@ interface EventCaptureOptions {
|
||||
readonly page: Page;
|
||||
readonly enabled: ReadonlySet<EventName>;
|
||||
readonly secrets: BrowserScenarioSecrets;
|
||||
readonly allowedOrigins: readonly string[];
|
||||
}
|
||||
|
||||
/** Arrival-ordered Playwright event capture with current-step attribution. */
|
||||
@@ -46,12 +45,10 @@ export class PlaywrightScenarioEvents {
|
||||
private sequence = 0;
|
||||
private readonly enabled: ReadonlySet<EventName>;
|
||||
private readonly secrets: BrowserScenarioSecrets;
|
||||
private readonly allowedOrigins: ReadonlySet<string>;
|
||||
|
||||
constructor(options: EventCaptureOptions) {
|
||||
this.enabled = options.enabled;
|
||||
this.secrets = options.secrets;
|
||||
this.allowedOrigins = new Set(options.allowedOrigins);
|
||||
this.observePage(options.page);
|
||||
}
|
||||
|
||||
@@ -91,67 +88,38 @@ export class PlaywrightScenarioEvents {
|
||||
|
||||
private observePage(page: Page): void {
|
||||
if (this.enabled.has("console"))
|
||||
page.on("console", (message) => {
|
||||
if (this.pageInScope(page)) this.console(message);
|
||||
});
|
||||
page.on("console", (message) => this.console(message));
|
||||
if (this.enabled.has("page-errors"))
|
||||
page.on("pageerror", (error) => {
|
||||
if (this.pageInScope(page))
|
||||
this.push({
|
||||
kind: "page-error",
|
||||
message: this.secrets.redact(error.message),
|
||||
stack:
|
||||
error.stack === undefined
|
||||
? null
|
||||
: this.secrets.redact(error.stack),
|
||||
});
|
||||
this.push({
|
||||
kind: "page-error",
|
||||
message: this.secrets.redact(error.message),
|
||||
stack:
|
||||
error.stack === undefined ? null : this.secrets.redact(error.stack),
|
||||
});
|
||||
});
|
||||
if (this.enabled.has("network")) {
|
||||
page.on("request", (request) => {
|
||||
if (this.pageInScope(page)) this.request("request", request);
|
||||
});
|
||||
page.on("response", (response) => {
|
||||
if (this.pageInScope(page)) this.response(response);
|
||||
});
|
||||
page.on("requestfailed", (request) => {
|
||||
if (this.pageInScope(page)) this.request("request-failed", request);
|
||||
});
|
||||
page.on("request", (request) => this.request("request", request));
|
||||
page.on("response", (response) => this.response(response));
|
||||
page.on("requestfailed", (request) =>
|
||||
this.request("request-failed", request),
|
||||
);
|
||||
}
|
||||
if (this.enabled.has("websockets"))
|
||||
page.on("websocket", (socket) => {
|
||||
if (this.pageInScope(page)) this.webSocket(page, socket);
|
||||
});
|
||||
page.on("websocket", (socket) => this.webSocket(socket));
|
||||
if (this.enabled.has("frames")) {
|
||||
page.on("frameattached", (frame) => {
|
||||
if (this.pageInScope(page)) this.frame("frame-attached", frame);
|
||||
});
|
||||
page.on("framedetached", (frame) => {
|
||||
if (this.pageInScope(page)) this.frame("frame-detached", frame);
|
||||
});
|
||||
page.on("framenavigated", (frame) => {
|
||||
if (this.pageInScope(page)) this.frame("frame-navigated", frame);
|
||||
});
|
||||
page.on("frameattached", (frame) => this.frame("frame-attached", frame));
|
||||
page.on("framedetached", (frame) => this.frame("frame-detached", frame));
|
||||
page.on("framenavigated", (frame) =>
|
||||
this.frame("frame-navigated", frame),
|
||||
);
|
||||
}
|
||||
if (this.enabled.has("workers"))
|
||||
page.on("worker", (worker) => {
|
||||
if (this.pageInScope(page)) this.worker(page, worker);
|
||||
});
|
||||
page.on("worker", (worker) => this.worker(worker));
|
||||
if (this.enabled.has("popups"))
|
||||
page.on("popup", (popup) => {
|
||||
if (this.pageInScope(page)) this.popup(popup);
|
||||
});
|
||||
page.on("popup", (popup) => this.popup(popup));
|
||||
if (this.enabled.has("downloads"))
|
||||
page.on("download", (download) => {
|
||||
if (this.pageInScope(page)) this.download(download);
|
||||
});
|
||||
}
|
||||
|
||||
private pageInScope(page: Page): boolean {
|
||||
try {
|
||||
return this.allowedOrigins.has(new URL(page.url()).origin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
page.on("download", (download) => this.download(download));
|
||||
}
|
||||
|
||||
private safeUrl(value: string) {
|
||||
@@ -209,20 +177,16 @@ export class PlaywrightScenarioEvents {
|
||||
});
|
||||
}
|
||||
|
||||
private webSocket(page: Page, socket: WebSocket): void {
|
||||
private webSocket(socket: WebSocket): void {
|
||||
const url = this.safeUrl(socket.url());
|
||||
this.push({ kind: "websocket-opened", url });
|
||||
socket.on("framesent", ({ payload }) => {
|
||||
if (this.pageInScope(page))
|
||||
this.webSocketFrame("websocket-frame-sent", url, payload);
|
||||
});
|
||||
socket.on("framereceived", ({ payload }) => {
|
||||
if (this.pageInScope(page))
|
||||
this.webSocketFrame("websocket-frame-received", url, payload);
|
||||
});
|
||||
socket.on("close", () => {
|
||||
if (this.pageInScope(page)) this.push({ kind: "websocket-closed", url });
|
||||
});
|
||||
socket.on("framesent", ({ payload }) =>
|
||||
this.webSocketFrame("websocket-frame-sent", url, payload),
|
||||
);
|
||||
socket.on("framereceived", ({ payload }) =>
|
||||
this.webSocketFrame("websocket-frame-received", url, payload),
|
||||
);
|
||||
socket.on("close", () => this.push({ kind: "websocket-closed", url }));
|
||||
}
|
||||
|
||||
private webSocketFrame(
|
||||
@@ -265,36 +229,27 @@ export class PlaywrightScenarioEvents {
|
||||
});
|
||||
}
|
||||
|
||||
private worker(page: Page, worker: Worker): void {
|
||||
private worker(worker: Worker): void {
|
||||
const details = {
|
||||
url: this.safeUrl(worker.url()),
|
||||
name: null,
|
||||
};
|
||||
this.push({ kind: "worker-created", ...details });
|
||||
worker.on("close", () => {
|
||||
if (this.pageInScope(page))
|
||||
this.push({ kind: "worker-closed", ...details });
|
||||
});
|
||||
worker.on("close", () => this.push({ kind: "worker-closed", ...details }));
|
||||
}
|
||||
|
||||
private popup(page: Page): void {
|
||||
if (!this.pageInScope(page)) {
|
||||
void page.close().catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
const opened = {
|
||||
url: page.url() === "" ? null : this.safeUrl(page.url()),
|
||||
name: null,
|
||||
};
|
||||
this.push({ kind: "popup-opened", ...opened });
|
||||
page.on("close", () =>
|
||||
this.pageInScope(page)
|
||||
? this.push({
|
||||
kind: "popup-closed",
|
||||
url: page.url() === "" ? null : this.safeUrl(page.url()),
|
||||
name: null,
|
||||
})
|
||||
: undefined,
|
||||
this.push({
|
||||
kind: "popup-closed",
|
||||
url: page.url() === "" ? null : this.safeUrl(page.url()),
|
||||
name: null,
|
||||
}),
|
||||
);
|
||||
this.observePage(page);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
type BrowserContext,
|
||||
type Page,
|
||||
type Route,
|
||||
type WebSocketRoute,
|
||||
} from "playwright-core";
|
||||
import { type BrowserContext, type Page } from "playwright-core";
|
||||
|
||||
import type {
|
||||
BrowserScenario,
|
||||
@@ -27,17 +22,6 @@ import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.j
|
||||
|
||||
const OPERATION = "capture_browser_scenario" as const;
|
||||
|
||||
const originAllowed = (
|
||||
value: string,
|
||||
allowedOrigins: ReadonlySet<string>,
|
||||
): boolean => {
|
||||
try {
|
||||
return allowedOrigins.has(new URL(value).origin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const storageSeeds = (
|
||||
blocks: BrowserScenario["storage"]["local_storage"],
|
||||
secrets: BrowserScenarioSecrets,
|
||||
@@ -81,111 +65,6 @@ const installStorageSeeds = async (
|
||||
})()`);
|
||||
};
|
||||
|
||||
const installHttpPolicy = async (input: {
|
||||
readonly context: BrowserContext;
|
||||
readonly scenario: BrowserScenario;
|
||||
readonly secrets: BrowserScenarioSecrets;
|
||||
readonly ownedPages: Set<Page>;
|
||||
readonly claimOwnedPage: (page: Page) => Promise<boolean>;
|
||||
}): Promise<void> => {
|
||||
const { context, scenario, secrets, ownedPages, claimOwnedPage } = input;
|
||||
const routes =
|
||||
scenario.request_replay.mode === "exact"
|
||||
? new Map(
|
||||
scenario.request_replay.routes.map((route) => [
|
||||
`${route.method} ${secrets.url(route.request)}`,
|
||||
route,
|
||||
]),
|
||||
)
|
||||
: new Map();
|
||||
await context.route("**/*", async (route, request) => {
|
||||
let requestPage: Page | undefined;
|
||||
try {
|
||||
requestPage = request.frame().page();
|
||||
} catch {
|
||||
requestPage = undefined;
|
||||
}
|
||||
if (
|
||||
scenario.browser.mode === "connect" &&
|
||||
requestPage !== undefined &&
|
||||
!ownedPages.has(requestPage)
|
||||
)
|
||||
await claimOwnedPage(requestPage);
|
||||
if (
|
||||
scenario.browser.mode === "connect" &&
|
||||
(requestPage === undefined || !ownedPages.has(requestPage))
|
||||
) {
|
||||
await route.continue();
|
||||
return;
|
||||
}
|
||||
if (!originAllowed(request.url(), new Set(scenario.allowed_origins))) {
|
||||
await route.abort("blockedbyclient");
|
||||
return;
|
||||
}
|
||||
const replay = routes.get(`${request.method()} ${request.url()}`);
|
||||
if (replay !== undefined) {
|
||||
await fulfillReplayRoute(route, replay.response, secrets);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
scenario.request_replay.mode === "exact" &&
|
||||
scenario.request_replay.unmatched === "abort"
|
||||
) {
|
||||
await route.abort("blockedbyclient");
|
||||
return;
|
||||
}
|
||||
await route.continue();
|
||||
});
|
||||
};
|
||||
|
||||
type ReplayResponse = Extract<
|
||||
BrowserScenario["request_replay"],
|
||||
{ readonly mode: "exact" }
|
||||
>["routes"][number]["response"];
|
||||
|
||||
const fulfillReplayRoute = async (
|
||||
route: Route,
|
||||
response: ReplayResponse,
|
||||
secrets: BrowserScenarioSecrets,
|
||||
): Promise<void> => {
|
||||
if (response.kind === "redirect") {
|
||||
await route.fulfill({
|
||||
status: response.status,
|
||||
headers: { location: secrets.url(response.destination) },
|
||||
});
|
||||
return;
|
||||
}
|
||||
await route.fulfill({
|
||||
status: response.status,
|
||||
headers: Object.fromEntries(
|
||||
response.headers.map(({ name, value }) => [name, secrets.value(value)]),
|
||||
),
|
||||
...(response.body === undefined
|
||||
? {}
|
||||
: { body: secrets.value(response.body) }),
|
||||
});
|
||||
};
|
||||
|
||||
const installWebSocketPolicy = async (
|
||||
owner: BrowserContext | Page,
|
||||
scenario: BrowserScenario,
|
||||
): Promise<void> => {
|
||||
const allowed = new Set(scenario.allowed_origins);
|
||||
await owner.routeWebSocket("**/*", async (route: WebSocketRoute) => {
|
||||
const url = new URL(route.url());
|
||||
const httpOrigin = `${url.protocol === "wss:" ? "https:" : "http:"}//${url.host}`;
|
||||
if (
|
||||
!allowed.has(httpOrigin) ||
|
||||
(scenario.request_replay.mode === "exact" &&
|
||||
scenario.request_replay.unmatched === "abort")
|
||||
) {
|
||||
await route.close({ code: 1008, reason: "outside scenario policy" });
|
||||
return;
|
||||
}
|
||||
route.connectToServer();
|
||||
});
|
||||
};
|
||||
|
||||
const blockAttachedServiceWorkers = async (page: Page): Promise<void> => {
|
||||
const controller = await page.evaluate(
|
||||
"Boolean(navigator.serviceWorker?.controller)",
|
||||
@@ -210,40 +89,12 @@ const initializePage = async (
|
||||
page: Page,
|
||||
scenario: BrowserScenario,
|
||||
secrets: BrowserScenarioSecrets,
|
||||
): Promise<Set<Page>> => {
|
||||
): Promise<void> => {
|
||||
context.setDefaultTimeout(0);
|
||||
context.setDefaultNavigationTimeout(0);
|
||||
const ownedPages = new Set([page]);
|
||||
if (scenario.browser.mode === "connect")
|
||||
await blockAttachedServiceWorkers(page);
|
||||
await installWebSocketPolicy(
|
||||
scenario.browser.mode === "launch" ? context : page,
|
||||
scenario,
|
||||
);
|
||||
const claimOwnedPage = async (candidate: Page): Promise<boolean> => {
|
||||
if (ownedPages.has(candidate)) return true;
|
||||
const opener = await candidate.opener();
|
||||
if (opener === null || !ownedPages.has(opener)) return false;
|
||||
await installWebSocketPolicy(candidate, scenario);
|
||||
ownedPages.add(candidate);
|
||||
return true;
|
||||
};
|
||||
await installHttpPolicy({
|
||||
context,
|
||||
scenario,
|
||||
secrets,
|
||||
ownedPages,
|
||||
claimOwnedPage,
|
||||
});
|
||||
page.on("popup", (popup) => {
|
||||
if (scenario.browser.mode === "connect")
|
||||
void claimOwnedPage(popup).catch(async () => {
|
||||
await popup.close().catch(() => undefined);
|
||||
});
|
||||
else ownedPages.add(popup);
|
||||
});
|
||||
await installStorageSeeds(context, page, scenario, secrets);
|
||||
return ownedPages;
|
||||
};
|
||||
|
||||
export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
@@ -256,13 +107,12 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
|
||||
private constructor(
|
||||
private readonly opened: OpenedScenarioBrowser,
|
||||
private readonly scenario: BrowserScenario,
|
||||
mode: BrowserScenario["browser"]["mode"],
|
||||
private readonly secrets: BrowserScenarioSecrets,
|
||||
private readonly eventCapture: PlaywrightScenarioEvents,
|
||||
) {
|
||||
this.mode = scenario.browser.mode;
|
||||
this.processOwnership =
|
||||
scenario.browser.mode === "launch" ? "provider-owned" : "external";
|
||||
this.mode = mode;
|
||||
this.processOwnership = mode === "launch" ? "provider-owned" : "external";
|
||||
this.version = opened.browser.version();
|
||||
this.initialUrl = opened.page.url();
|
||||
}
|
||||
@@ -303,11 +153,10 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
page: opened.page,
|
||||
enabled: new Set(scenario.capture.events),
|
||||
secrets,
|
||||
allowedOrigins: scenario.allowed_origins,
|
||||
});
|
||||
const session = new PlaywrightScenarioSession(
|
||||
opened,
|
||||
scenario,
|
||||
scenario.browser.mode,
|
||||
secrets,
|
||||
events,
|
||||
);
|
||||
@@ -378,7 +227,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
capturePlaywrightStepArtifacts({
|
||||
context: this.opened.context,
|
||||
page: this.opened.page,
|
||||
scenario: this.scenario,
|
||||
secrets: this.secrets,
|
||||
requested,
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user