Files
reverse-engineering-anything/src/browser/PlaywrightScenarioServiceWorkers.ts
T
morluto abd36dd250 refactor(browser): parse Runtime and Debugger events once by registered schemas (#10742)
* refactor(browser): parse frame lifecycle events once by a registered event schema

CdpConnection admits each event through protocol/CdpEvents.ts, which parses
the five Page frame lifecycle events once into identity facts plus a frame
URL observation, like a frame-tree node. Screenshot, page capture, the
observation timeline, WebMCP, Electron inspection and the execution window
read those facts instead of re-parsing the raw payload; CdpFrameFacts no
longer carries the raw source record. Playwright CDP session subscriptions
name an event from Playwright's protocol table, and an architecture guard
counts the remaining raw event payload reads so they can only shrink.

* refactor(browser): parse Runtime and Debugger events once by registered schemas

Register Debugger.scriptParsed, Debugger.scriptFailedToParse,
Runtime.executionContextCreated, Runtime.executionContextDestroyed and
Runtime.consoleAPICalled. Script and context payloads carry both the
tolerant facts passive capture uses and the active runtime's strict
declaration, derived from one parse, plus the declaration's byte size for
the runtime retention budget. Page capture, Electron script capture, the
V8 Inspector provider and the runtime source inventory now read the
registered payload. The cdp-raw-event-params baseline drops from 20 to 7.

* refactor(browser): admit transport events through the registered-event owner

Remove the unused cdpFrameUrl wrapper; its fragment cases now exercise
observeCdpFrameUrl. Add a connection-level test that two subscribers share
one parsed payload and the raw params.

* fix(browser): report an unserializable event declaration's size instead of throwing

JSON.stringify can throw on a declaration JSON.parse accepted (nesting
deeper than the serializer's stack). The registry sized script and context
declarations inside the connection's WebSocket callback, so such an event
escaped as an uncaught exception. The size is now a Result; the runtime
source inventory raises the failure inside its own catch, as before.

* refactor(browser): parse Network events once by registered schemas (#10743)

* refactor(browser): parse Network events once by registered schemas

Register Network.requestWillBeSent, responseReceived, loadingFinished,
loadingFailed, webSocketCreated and webSocketFrameSent/Received. The
request payload carries the tolerant facts page capture and the timeline
read plus the active runtime's strict declaration. Page capture's network
and WebSocket handlers, the timeline's request tracking and the runtime
request inventory now read the registered payload. The
cdp-raw-event-params baseline drops from 7 to 5.

* refactor(browser): drop payload helpers the capture handlers no longer use

* refactor(browser): read every CDP event payload through the registry (#10745)

* refactor(browser): read every CDP event payload through the registry

Register Target.attachedToTarget, Target.detachedFromTarget,
Page.lifecycleEvent and WebMCP.toolsAdded/toolsRemoved, and carry a
requested navigation's reason and a commit's transition type in the
frame-event payload. The timeline no longer threads raw params into its
entries: each entry receives its timestamp, frame and loader identity
explicitly. WebMCP discovery, the service-worker policy blocker and the
target-event matcher read the registered payload. With no raw reads left,
the cdp-raw-event-params guard is enforced at zero instead of counted.

* refactor(browser): drop raw payload helpers the timeline and worker blocker no longer use

* refactor(browser): type Playwright CDP session events by the registry (#10751)

PlaywrightCdpSession.on subscribes only to registered events and hands
the listener the payload parsed by its registered schema, returning the
unsubscribe function. Private storage seeding reads registered payloads,
including the events of non-flat child sessions, and applies its strict
seeding policy to the parsed facts. Its local attach, detach, nested
message and pause schemas and the storage-only script/context schemas are
removed; Debugger.paused, Runtime.executionContextsCleared and
Target.receivedMessageFromTarget join the registry.

* test(browser): admit fake policy events through the event registry

The service-worker policy now reads event.registered, but the PlaywrightScenarioSession fake connection delivered raw events, so three detached-target tests never reached the policy. The fake now admits each event with receiveCdpEvent as CdpConnection does.

* fix(browser): fail the CDP session closed when an event listener throws (#10758)

* fix(browser): fail the CDP session closed when an event listener throws

An exception from a CDP event subscriber escaped CdpTransportCore's socket message callback uncaught (for example the service-worker blocker's protocol_error on a Target event without a sessionId). The transport now stops delivery, fails the connection as a protocol error whose cause is the listener's exception, rejects pending and later commands with it, and notifies protocol-failure subscribers. The Playwright CDP session relay applies the same rule to its event listeners.

* fix(browser): report a failed service-worker policy connection at the next policy check

The policy's event listener rejects a malformed Target event, which now fails its connection. With no policy command pending, nothing reported it and later iframe targets went unprotected. The policy records its connection's protocol failure and assertBlocked, run before each scenario step, rethrows it.

* fix(browser): keep cleanup commands available after a listener failure

A listener failure no longer marks the wire as broken. The transport still rejects pending commands, notifies protocol-failure subscribers, stops delivering events and refuses reuse, but it keeps reading replies and admits commands sent in cleanup grace. The service-worker policy can then remove its init scripts, restore the main realm, detach and release its socket. Wire-level protocol errors still refuse every later command. The PlaywrightScenarioSession policy fake gains onProtocolFailure, which the policy now subscribes to.

* refactor(browser): keep raw CDP event payloads out of the received event (#10764)

* refactor(browser): keep raw CDP event payloads out of the received event

CdpReceivedEvent and CdpTransportEvent no longer carry params: receiveCdpEvent hands the raw payload only to the registered schema, so a subscriber cannot read it by property access, destructuring or computed keys. This supersedes the event.params text guard in architecture-guards, which is removed.

* refactor(browser): read registered event payloads in the JavaScript verifiers

The runtime, storage and URL-userinfo verifiers subscribe to CdpConnection, which no longer hands subscribers raw params. They now read event.registered. A test scans every scripts/ onEvent callback for raw payload reads, since the TypeScript check does not cover them. The storage verifier's pause trace records a malformed pause instead of the unregistered reason member.

* refactor(browser): track the timeline's main frame with the document tracker (#10779)

TimelineCapture kept its own mutable main frame id and replaced it on a root replacement. It now holds the CdpDocumentTracker that CdpTargetSession owns and observes the replacement document through it; every main-frame check (lifecycle, navigation, document request, redirect) reads the tracker's current frame. A characterization test pins that the replaced root's lifecycle events are no longer recorded.

* refactor(browser): select CDP events only by their registered name (#10829)

CdpReceivedEvent carried the wire method as a plain string, so a subscriber
could compare it with a misspelt or unregistered name and the check compiled
but never matched. Three owners selected Inspector.targetCrashed, an
unregistered event, that way.

Register Inspector.targetCrashed and drop the wire method from the received
event. Subscribers select events by registered.method, whose type is the
registered event names. The capture coverage start keeps reading the
wire domain, now the event's domain field.

* fix(browser): retire a policy child session that CDP reports gone

After a listener failure the connection stops delivering events, so an
iframe's Target.detachedFromTarget never retires its policy target. Cleanup
then sent Page.removeScriptToEvaluateOnNewDocument to the dead session,
kept the stale child, and every retry failed before detaching the root.

The service-worker policy owner now treats CDP's session-not-found
rejection as proof that the child is gone and retires it. The classifier
moves from CdpTargetSession to CdpCommandRejection, its owner, and the
target-session detach path uses the same one.

* refactor(browser): route target events through one session owner (#10835)

* refactor(browser): route target events through one session owner

Page capture, WebMCP discovery, screenshot capture and the runtime sources
each compared the envelope session ID themselves, while the observation
window and execution collection used cdpTargetEventMatches, which also
routes the root Target.detachedFromTarget that names the target's session.

onCdpTargetEvent in CdpTargetEvents.ts now subscribes every target consumer
with that one rule; the matcher is private and the per-subscriber
comparisons are removed. Electron inspection keeps its own filter while
its capture isolation awaits a maintainer decision.

* fix(browser): report WebMCP subframe tools whose document is unverified (#10839)

* fix(browser): report WebMCP subframe tools whose document is unverified

A committed subframe navigation kept the frame's tools silently when CDP
reported no loader at the same URL, and removed them on any URL change even
when the loader proved the same document.

Each frame now carries a CdpDocumentTracker, the session's document
identity owner. Only a proven change removes the frame's tools. An unknown
comparison keeps them visible, marks webmcp_tools attach-limited and names
the frames whose document identity could not be established.

* test(browser): prove an unverified live subframe limits WebMCP coverage

* fix(browser): key a WebMCP registration by its frame and tool name

A subframe tool kept across a committed navigation that changed the URL
but not the loader was stored under a key built from the old URL, so a
later toolsAdded for the same frame and name added a second entry.
Registrations are now keyed by frame and name; tool_key still records the
registering frame URL.

* test(browser): deliver fake CDP events through the transport's admission (#10840)

Event fakes each rebuilt the received event: CdpAgentHints typed its
listeners as raw wire events behind an unknown cast, and the Electron,
scenario-session and routing tests each wrapped receiveCdpEvent by hand.

fakeCdpEvents (tests/fixtures) is a CdpConnection.onEvent fake whose emit
admits each raw event with receiveCdpEvent and the wire byte count, so a
change to the received event shape fails at the fake instead of silently
not exercising subscribers.

* refactor(browser): own the selected page generation in one target document tracker (#10860)

* refactor(browser): own the selected page generation in one target document tracker

Page capture, screenshot, the observation window, the runtime session and
the execution window each built a document tracker or rule of their own
from root-frame navigation events. CdpTargetDocument now follows the target
session's root-frame events and the frame-tree replies its consumers read,
classifies root identity once, and reports each navigation to consumers
that decide only what it means for their evidence.

* fix(browser): report a lost scenario policy connection before the next step (#10864)

* fix(browser): report a lost scenario policy connection before the next step

The service-worker policy recorded only protocol failures. When its CDP
socket closed or its page session detached, later documents lost the
blocking script, but the scenario learned of it only when a frame check
found an unprotected realm. The owner now records the disconnect or
detach when CDP reports it; the next policy check and the next step's
action report it first.

* fix(browser): refuse an unregistered CDP command before it reaches the browser (#10868)

JavaScript verifiers can name any command, and the send owners refused an
unregistered one only when its reply arrived, after the browser had acted
on it. CdpConnection and the Playwright session now refuse the name before
sending, and the Playwright session refuses an unregistered event name
instead of subscribing to events no listener receives. The verifier text
scan stays as an early warning and documents what it cannot see.

* fix(browser): keep a proven root change and the loaderless selection's uncertainty

Two review findings on the target document owner. A root event naming
another frame with a malformed loader set `changed` but was announced as
unidentified, so the execution window failed with protocol_error and
dropped what it had collected; the owner now announces it as the proven
change it is. The runtime session compared each frame-tree reply with the
tracker's current document, which can learn a loader from an event, so a
loaderless selection followed by an event and a reply with that loader
compared as same; it now compares the reply with the selected document
through the owner, and reports target_changed as before.

* test(browser): refuse the next scenario step after the policy session detaches

* refactor(browser): read WebMCP document identity from the target document owner (#10884)

* refactor(browser): read WebMCP document identity from the target document owner

WebMCP discovery compared the first and last frame-tree roots itself and
kept a document tracker per subframe. CdpTargetDocument now follows the
selected root and each committed subframe for it: the final frame tree
feeds the owner, a root change proven by a navigation event during
discovery is target_changed as in page capture, and a subframe whose
committed document changed loses its tools. A subframe navigation without
a loader still keeps the tools and reports them as unverified.

* fix(browser): start a subframe first seen within its document with an unknown loader

A subframe absent from the initial frame tree and first seen through Page.navigatedWithinDocument had no document tracker, so a later commit started a fresh one and the tools it registered meanwhile lost the unverified-document limitation. The owner now starts such a subframe with an unknown loader.

* fix(browser): refuse a verifier's unregistered CDP event name at subscription (#10885)

JavaScript verifiers subscribed to every event with CdpConnection.onEvent
and compared registered.method with a string literal. A misspelt or
unregistered name never matched and the verifier waited until its timeout.
CdpConnection.onRegisteredEvent now takes one event name, refuses an
unregistered one before subscribing (the same registry check the Playwright
session applies), and hands the listener only that event's registered
parse. The verifiers subscribe only through it, and the evaluation test
rejects a raw onEvent subscription in scripts.

* fix(browser): keep subframe documents by frame and loader without their URLs
2026-11-15 19:54:17 +08:00

554 lines
20 KiB
TypeScript

import { randomUUID } from "node:crypto";
import type { Frame, Page } from "playwright-core";
import {
CDP_CLEANUP_GRACE_MS,
CDP_DISCOVERY_RESPONSE_TIMEOUT_MS,
selectedCdpCommandTimeoutMs,
} from "../domain/browserDeadline.js";
import {
AnalysisTimeoutError,
OwnerCancellation,
} from "../domain/analysisErrorCore.js";
import { browserObservationEndpointSchema } from "../domain/browserObservation.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import { isCdpSessionGoneRejection } from "./CdpCommandRejection.js";
import { CdpTargetSessionOwner } from "./CdpTargetSessionOwner.js";
import {
withCdpDiscoveryDeadline,
type CdpEndpointTarget,
} from "./CdpEndpoint.js";
import { selectCdpDiscoveryTarget } from "./CdpDiscoveryTargets.js";
import {
attachCdpTargetSession,
failCdpOpenAfterCleanup,
openCdpEndpoint,
type CdpTargetSession,
} from "./CdpTargetSession.js";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
import type {
CdpCommand,
CdpCommandParams,
CdpCommandResult,
} from "./protocol/CdpCommands.js";
const OPERATION = "capture_browser_scenario" as const;
// Restoration performs several sequential CDP mutations before the transport's
// own bounded close. A single round-trip deadline is too short for the complete
// chain on a loaded Windows browser, while retries must still stay bounded.
const POLICY_CLEANUP_CONFIRMATION_TIMEOUT_MS = CDP_CLEANUP_GRACE_MS;
/**
* First blocked-service-worker registration check, before discovery starts.
* It keeps the previous fixed 10-second bound. command_timeout_ms does not
* apply yet, and this timer is not the discovery or attach deadline.
*/
export const SERVICE_WORKER_POLICY_CHECK_TIMEOUT_MS =
CDP_DISCOVERY_RESPONSE_TIMEOUT_MS;
const serviceWorkerPolicyCheckTimeout = (): AnalysisTimeoutError => {
const timeoutMs = SERVICE_WORKER_POLICY_CHECK_TIMEOUT_MS;
return new AnalysisTimeoutError(OPERATION, timeoutMs, {
userMessage: `Blocked service-worker policy check exceeded its ${String(timeoutMs)} ms deadline before CDP discovery. command_timeout_ms does not apply to this check.`,
remediationAction: `The ${String(timeoutMs)} ms blocked service-worker policy check stays fixed. This release has no runtime override. command_timeout_ms does not raise it.`,
});
};
type PolicyTarget = {
readonly id: string;
readonly detached: Promise<void>;
readonly markDetached: () => void;
ready: Promise<void>;
identifier?: string;
};
/** Owns only its frame scripts and registration wrappers, never caller-owned workers. */
export class PlaywrightScenarioServiceWorkers {
readonly #transportOwner = new CdpTargetSessionOwner();
private readonly marker = JSON.stringify(
`rea-service-workers-${randomUUID()}`,
);
private readonly restoreKey = JSON.stringify(`rea-restore-${randomUUID()}`);
private readonly secret = JSON.stringify(randomUUID());
#initialization: Promise<void> | undefined;
#restoration: Promise<void> | undefined;
#session: CdpTargetSession | undefined;
#targets = new Map<string, PolicyTarget>();
#closed = false;
#released = false;
#detached = false;
#loadingStopped = false;
#stopRequested = false;
#stopPromise: Promise<void> | undefined;
#removeListener: (() => void) | undefined;
#removeProtocolFailure: (() => void) | undefined;
#removeDisconnect: (() => void) | undefined;
/**
* The first loss of the policy connection: a protocol failure (including a
* malformed target event the listener rejected), the socket closing, or the
* policy session detaching before REA released it. Later documents would
* not be protected, so the next policy check and the next step report it.
*/
#failure: BrowserObservationError | undefined;
#setup = new AbortController();
constructor(
private readonly page: Pick<Page, "frames" | "isClosed" | "mainFrame">,
private readonly endpoint: string,
private readonly targetId: string,
private readonly commandTimeoutMs: number = selectedCdpCommandTimeoutMs(
undefined,
),
) {}
initialize(): Promise<void> {
return (this.#initialization ??= this.install());
}
private async install(): Promise<void> {
await withPlaywrightExecutionBoundary(
() => this.assertBlocked(),
SERVICE_WORKER_POLICY_CHECK_TIMEOUT_MS,
this.#setup.signal,
serviceWorkerPolicyCheckTimeout,
);
// Discovery stays on its fixed deadline. The following handshake and
// Target.attachToTarget each use command_timeout_ms.
const opened = await withCdpDiscoveryDeadline(
OPERATION,
this.#setup.signal,
(signal) =>
openCdpEndpoint(
browserObservationEndpointSchema.parse(this.endpoint),
OPERATION,
signal,
undefined,
this.#transportOwner,
this.commandTimeoutMs,
),
);
let target: CdpEndpointTarget;
try {
const selected = selectCdpDiscoveryTarget(
opened.discovery.targets,
this.targetId,
OPERATION,
opened.discovery.ambiguousTargetIds,
);
if (selected === undefined)
throw new BrowserObservationError(OPERATION, "target_not_found");
target = selected;
} catch (cause: unknown) {
if (opened.connection !== undefined)
return await failCdpOpenAfterCleanup(
opened.connection,
cause,
OPERATION,
this.#transportOwner,
);
throw cause;
}
const transport =
opened.connection ??
(await this.#transportOwner.connect(
opened.discovery.webSocket.url,
OPERATION,
{ signal: this.#setup.signal },
target.id,
{ commandTimeoutMs: this.commandTimeoutMs },
));
if (this.#closed)
transport.beginCleanupGrace(POLICY_CLEANUP_CONFIRMATION_TIMEOUT_MS);
try {
this.#session = await attachCdpTargetSession(
transport,
target,
OPERATION,
this.#setup.signal,
this.#transportOwner,
);
} catch (cause: unknown) {
return await failCdpOpenAfterCleanup(
transport,
cause,
OPERATION,
this.#transportOwner,
);
}
const connection = this.#session.connection;
this.#removeProtocolFailure = connection.onProtocolFailure((error) => {
this.#failure ??= error;
});
this.#removeDisconnect = connection.onDisconnect((error) => {
if (!this.#closed) this.#failure ??= error;
});
this.#removeListener = connection.onEvent((event) => {
const registered = event.registered;
if (
registered?.method === "Target.attachedToTarget" &&
this.#targets.has(event.sessionId ?? "")
) {
const { sessionId, targetType } = registered.payload;
if (sessionId === undefined || targetType === undefined)
throw new BrowserObservationError(OPERATION, "protocol_error");
if (targetType === "iframe") this.addTarget(sessionId);
} else if (registered?.method === "Target.detachedFromTarget") {
const id = registered.payload.sessionId;
if (id === undefined)
throw new BrowserObservationError(OPERATION, "protocol_error");
this.#targets.get(id)?.markDetached();
this.#targets.delete(id);
if (id === this.#session?.sessionId) {
this.#detached = true;
if (!this.#closed)
this.#failure ??= new BrowserObservationError(
OPERATION,
"target_session_detached",
);
}
}
});
const id = this.#session.sessionId;
if (id === undefined)
throw new BrowserObservationError(OPERATION, "protocol_error");
this.addTarget(id);
await this.settle();
// CDP returns an identifier even when an init script throws in a realm.
await withPlaywrightExecutionBoundary(
() => this.assertBlocked(),
undefined,
this.#setup.signal,
);
}
private addTarget(id: string): void {
this.#targets.get(id)?.markDetached();
let markDetached: () => void = () => undefined;
const detached = new Promise<void>((resolve) => {
markDetached = resolve;
});
const target: PolicyTarget = {
id,
detached,
markDetached,
ready: Promise.resolve(),
};
this.#targets.set(id, target);
const ready = this.initializeTarget(target);
target.ready = ready;
void ready.catch(() => undefined);
}
private async initializeTarget(target: PolicyTarget): Promise<void> {
try {
if (this.#closed) return;
await this.send(target.id, "Page.enable");
if (this.#closed) return;
const added = await this.send(
target.id,
"Page.addScriptToEvaluateOnNewDocument",
{
runImmediately: true,
source: `(() => {
if (!("serviceWorker" in navigator)) return;
const prototype = ServiceWorkerContainer.prototype;
const descriptor = Object.getOwnPropertyDescriptor(prototype, "register");
if (typeof descriptor?.value === "function" && Object.hasOwn(descriptor.value, Symbol.for(${this.marker}))) return;
const register = () => Promise.reject(new Error("service workers are blocked by scenario policy"));
Object.defineProperty(register, Symbol.for(${this.marker}), { value: true });
const secret = ${this.secret};
Object.defineProperty(globalThis, ${this.restoreKey}, { configurable: true, value: (provided) => {
if (provided !== secret) return false;
if (Object.getOwnPropertyDescriptor(prototype, "register")?.value === register) {
if (descriptor === undefined) delete prototype.register;
else Object.defineProperty(prototype, "register", descriptor);
}
delete globalThis[${this.restoreKey}];
return true;
}});
Object.defineProperty(prototype, "register", { ...descriptor, configurable: true, value: register });
})()`,
},
);
target.identifier = added.identifier;
if (!this.#closed)
await this.send(target.id, "Target.setAutoAttach", {
autoAttach: true,
waitForDebuggerOnStart: true,
flatten: true,
filter: [{ type: "iframe", exclude: false }, { exclude: true }],
});
} finally {
// Only this page's iframe targets are attached; unrelated workers/popups
// are not acquired. Resume a child even if installation or cleanup fails.
if (
this.#targets.has(target.id) &&
target.id !== this.#session?.sessionId
)
await this.send(target.id, "Runtime.runIfWaitingForDebugger");
}
}
private send<M extends CdpCommand>(
id: string,
method: M,
params: CdpCommandParams<M> = {} as CdpCommandParams<M>,
): Promise<CdpCommandResult<M>> {
if (this.#session === undefined)
throw new BrowserObservationError(OPERATION, "disconnected");
return this.#session.connection.send(method, params, id);
}
private async settle(): Promise<void> {
for (;;) {
const targets = [...this.#targets.values()];
await Promise.all(targets.map((target) => this.settleTarget(target)));
if (
targets.length === this.#targets.size &&
targets.every((target) => this.#targets.get(target.id) === target)
)
return;
}
}
private async settleTarget(target: PolicyTarget): Promise<void> {
try {
await Promise.race([target.ready, target.detached]);
} catch (cause: unknown) {
if (this.#targets.get(target.id) === target) throw cause;
}
}
private async settleTargetForRestore(target: PolicyTarget): Promise<void> {
try {
await Promise.race([target.ready, target.detached]);
} catch {
// Setup already reports its own failure. Cleanup must continue from the
// side effects that were acquired before it failed, such as an init
// script whose identifier was returned before auto-attach was rejected.
}
}
private restorationScript(): string {
return `(() => {
const restore = globalThis[${this.restoreKey}];
if (typeof restore === "function" && restore(${this.secret}) === true) return null;
const register = globalThis.ServiceWorkerContainer?.prototype.register;
return typeof register === "function" && Object.hasOwn(register, Symbol.for(${this.marker}))
? "policy_owned"
: null;
})()`;
}
private async restoreMainFrame(id: string): Promise<void> {
const { result } = await this.send(id, "Runtime.evaluate", {
expression: this.restorationScript(),
returnByValue: true,
});
if (result.value === "policy_owned")
throw new Error(
"service-worker policy restoration could not be confirmed",
);
// The script returns null once restored; anything else, including a
// thrown evaluation, is a protocol failure as in the Playwright frame path.
if (result.value !== null)
throw new BrowserObservationError(OPERATION, "protocol_error");
}
private async restorePlaywrightFrame(frame: Frame): Promise<void> {
try {
const failure = await frame.evaluate(this.restorationScript());
if (failure === "policy_owned")
throw new Error(
"service-worker policy restoration could not be confirmed",
);
if (failure !== null)
throw new BrowserObservationError(OPERATION, "protocol_error");
} catch (cause: unknown) {
if (!this.page.isClosed() && !frame.isDetached()) throw cause;
}
}
private async stopMainFrame(frame: Frame): Promise<void> {
try {
await frame.evaluate("globalThis.stop()");
} catch (cause: unknown) {
// A closed page no longer has an active navigation to stop. On a live
// page, including a detached frame, preserve failure so retry can use a
// fresh main-frame reference.
if (!this.page.isClosed()) throw cause;
}
}
/** Report a policy connection lost since installation, without page reads. */
assertConnected(): void {
if (this.#failure !== undefined) throw this.#failure;
}
async assertBlocked(): Promise<void> {
if (this.#failure !== undefined) throw this.#failure;
if (this.#session !== undefined) await this.settle();
if (this.#failure !== undefined) throw this.#failure;
for (const frame of this.page.frames()) {
let failure: unknown;
try {
failure = await frame.evaluate(`(async () => {
if (!("serviceWorker" in navigator)) return null;
const serviceWorker = navigator.serviceWorker;
if (${this.#session !== undefined} &&
(!Object.hasOwn(serviceWorker.register, Symbol.for(${this.marker})) ||
typeof globalThis[${this.restoreKey}] !== "function")) return "policy_unprotected";
if (serviceWorker.controller !== null) return "service_worker_blocked";
return (await serviceWorker.getRegistrations()).length > 0
? "service_worker_blocked"
: null;
})()`);
} catch (cause: unknown) {
if (frame.isDetached()) continue;
throw cause;
}
if (failure === "policy_unprotected")
throw new BrowserObservationError(OPERATION, "target_not_allowed");
if (failure === "service_worker_blocked")
throw new BrowserObservationError(OPERATION, "service_worker_blocked");
if (failure !== null)
throw new BrowserObservationError(OPERATION, "protocol_error");
}
}
close(stopLoading = false): Promise<void> {
this.#closed = true;
this.#stopRequested ||= stopLoading;
// Restoration commands keep the fixed grace even when command_timeout_ms was raised.
this.#session?.connection.beginCleanupGrace(
POLICY_CLEANUP_CONFIRMATION_TIMEOUT_MS,
);
// Abort discovery/handshakes and reads, never an already-sent page mutation.
this.#setup.abort(OwnerCancellation.ownerClosed);
const restoration = (this.#restoration ??= this.restore());
const clearRestoration = (): void => {
if (this.#restoration === restoration) this.#restoration = undefined;
};
void restoration.then(clearRestoration, clearRestoration);
// Restoration completion does not discharge a stop request that arrived
// after that restoration began. Both paths share the owner's stop latch.
const completion = restoration.then(() => this.fulfillStopRequest());
return withPlaywrightExecutionBoundary(
() => completion,
POLICY_CLEANUP_CONFIRMATION_TIMEOUT_MS,
);
}
private fulfillStopRequest(): Promise<void> {
if (!this.#stopRequested || this.#loadingStopped) return Promise.resolve();
if (this.#stopPromise !== undefined) return this.#stopPromise;
const stopping = (async () => {
if (this.page.isClosed()) {
this.#loadingStopped = true;
return;
}
const session = this.#session;
if (
!this.#released &&
!this.#detached &&
session?.sessionId !== undefined
) {
await this.send(session.sessionId, "Page.stopLoading");
} else {
await this.stopMainFrame(this.page.mainFrame());
}
this.#loadingStopped = true;
})();
this.#stopPromise = stopping;
const clearStop = (): void => {
if (this.#stopPromise === stopping) this.#stopPromise = undefined;
};
void stopping.then(clearStop, clearStop);
return stopping;
}
private async restore(): Promise<void> {
await this.#initialization?.catch(() => undefined);
await this.#transportOwner.retryPending();
this.#session?.connection.beginCleanupGrace(
POLICY_CLEANUP_CONFIRMATION_TIMEOUT_MS,
);
if (this.#released) return;
const session = this.#session;
if (session === undefined) {
await this.#transportOwner.close();
this.#released = true;
return;
}
if (!this.page.isClosed()) {
const mainFrame = this.page.mainFrame();
// This owner exists even with empty storage seeds. Stopped navigation is
// independent of storage and restoration never waits for a load event.
await this.fulfillStopRequest();
await Promise.all(
[...this.#targets.values()].map((target) =>
this.settleTargetForRestore(target),
),
);
for (const target of this.#targets.values()) {
if (!this.#detached && target.identifier !== undefined) {
try {
await this.send(
target.id,
"Page.removeScriptToEvaluateOnNewDocument",
{ identifier: target.identifier },
);
} catch (cause: unknown) {
// A child target can detach while event delivery is stopped by a
// listener failure, so its detach notice never retires it. CDP
// confirming the session is gone retires it here instead.
const gone =
target.id !== session.sessionId &&
isCdpSessionGoneRejection(cause);
if (!gone && this.#targets.get(target.id) === target) throw cause;
if (gone) {
target.markDetached();
this.#targets.delete(target.id);
}
}
delete target.identifier;
}
}
// Future documents cannot install our wrapper after the removals above.
// A realm lost to navigation is not assumed restored: retain and retry.
if (!this.#detached && session.sessionId !== undefined) {
await this.restoreMainFrame(session.sessionId);
} else {
await this.restorePlaywrightFrame(mainFrame);
}
for (const frame of this.page.frames()) {
// The owned CDP session evaluates the selected main realm directly,
// without Playwright waiting on an in-flight document transition.
if (frame === mainFrame) continue;
if (frame.isDetached()) continue;
// An empty URL has no committed document realm to restore. Future
// documents cannot install the wrapper after the script removals.
if (frame.url().length === 0) continue;
await this.restorePlaywrightFrame(frame);
}
}
// Detaching the exact owned session also releases its iframe auto-attach.
if (
!this.page.isClosed() &&
!this.#detached &&
session.sessionId !== undefined
) {
await session.connection.send("Target.detachFromTarget", {
sessionId: session.sessionId,
});
this.#detached = true;
}
this.#removeListener?.();
this.#removeProtocolFailure?.();
this.#removeDisconnect?.();
await this.#transportOwner.finish(session.connection);
await this.#transportOwner.close();
this.#released = true;
}
}