Files
reverse-engineering-anything/tests/boundary/browser/cdpConnection.test.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

845 lines
28 KiB
TypeScript

import { createHash } from "node:crypto";
import { createServer } from "node:http";
import { createServer as createNetServer, type Socket } from "node:net";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
CdpConnection,
type CdpTransportEvent,
} from "../../../src/browser/CdpConnection.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../../../src/domain/analysisErrorCore.js";
import { WEB_RUNTIME_LIMITS } from "../../../src/domain/webRuntime.js";
import { CdpMalformedReply } from "../../../src/browser/protocol/CdpCommands.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "../../fixtures/fakeCdpBrowser.js";
import { waitFor } from "../../support/testWait.js";
const INVALID_REPLIES = [
["missing result and error", (id: number) => ({ id })],
[
"both result and error",
(id: number) => ({
id,
result: {},
error: { code: -32_602, message: "Invalid params" },
}),
],
[
"detached-session error and result",
(id: number) => ({
id,
result: {},
error: { code: -32_001, message: "Session with given id not found." },
}),
],
[
"malformed error",
(id: number) => ({
id,
error: { code: "bad", message: "Invalid params" },
}),
],
["invalid result", (id: number) => ({ id, result: [] })],
["missing session id", (id: number) => ({ id, result: {} })],
["invalid session id", (id: number) => ({ id, result: {}, sessionId: 7 })],
[
"foreign session id",
(id: number) => ({ id, result: {}, sessionId: "foreign-session" }),
],
[
"detached-session error with a foreign session id",
(id: number) => ({
id,
error: { code: -32_001, message: "Session with given id not found." },
sessionId: "foreign-session",
}),
],
[
"unrouted detached-session message with another code",
(id: number) => ({
id,
error: { code: -32_000, message: "Session with given id not found." },
}),
],
[
"unrouted detached-session code with another message",
(id: number) => ({
id,
error: { code: -32_001, message: "No session with given id" },
}),
],
] as const;
const browsers: FakeCdpBrowser[] = [];
afterEach(async () => {
vi.useRealTimers();
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
});
describe("CDP connection admission cancellation", () => {
it("preserves an AnalysisError reason when admission is already cancelled", async () => {
const controller = new AbortController();
const reason = new AnalysisOutputError(
"inspect_web_page",
"caller supplied cancellation reason",
);
controller.abort(reason);
const failure = await CdpConnection.connect(
"ws://127.0.0.1:1/unused",
"inspect_web_page",
controller.signal,
).then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(AnalysisCancelledError);
if (!(failure instanceof AnalysisCancelledError))
throw new Error("Expected admission cancellation");
expect(failure.cause).toBe(reason);
});
});
describe("CDP connection response correlation", () => {
it("preserves the remote value of a debugger evaluation", async () => {
const browser = await startFakeCdpBrowser({
commandResult: (command) =>
command.method === "Debugger.evaluateOnCallFrame"
? { result: { type: "boolean", value: false } }
: undefined,
});
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"inspect_web_page",
);
try {
await expect(
connection.send("Debugger.evaluateOnCallFrame", {
callFrameId: "frame-1",
expression: "false",
returnByValue: true,
}),
).resolves.toEqual({ result: { type: "boolean", value: false } });
} finally {
await connection.close();
}
});
it("rejects one malformed registered reply without poisoning the connection", async () => {
const browser = await startFakeCdpBrowser({
commandResult: (command) =>
command.method === "Page.getFrameTree"
? { frameTree: "not a tree" }
: undefined,
});
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"inspect_web_page",
);
const protocolFailures: unknown[] = [];
connection.onProtocolFailure((error) => protocolFailures.push(error));
try {
const rejection = await connection
.send("Page.getFrameTree")
.catch((cause: unknown) => cause);
expect(rejection).toBeInstanceOf(CdpMalformedReply);
expect(rejection).toMatchObject({
reason: "protocol_error",
command: "Page.getFrameTree",
pointer: "/frameTree",
});
expect(String((rejection as CdpMalformedReply).detail)).not.toContain(
"not a tree",
);
await expect(connection.send("Runtime.enable")).resolves.toEqual({});
expect(connection.isReusable()).toBe(true);
expect(protocolFailures).toEqual([]);
} finally {
await connection.close();
}
});
it("correlates concurrent command responses over a real WebSocket", async () => {
const browser = await startFakeCdpBrowser({
hangOnMethod: "Storage.getStorageKey",
});
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"inspect_web_page",
);
try {
const [attached, frames] = await Promise.all([
connection.send("Target.attachToTarget"),
connection.send("Page.getFrameTree"),
]);
expect(attached).toMatchObject({ sessionId: "session-1" });
expect(frames.root.facts.frameId).toBe("frame-main");
browser.emitRawMessage(JSON.stringify({ id: 999 }));
await expect(connection.send("Runtime.enable")).resolves.toEqual({});
const first = connection.send("Storage.getStorageKey", {
frameId: "first",
});
const second = connection.send("Storage.getStorageKey", {
frameId: "second",
});
const replies = Promise.all([first, second]);
await waitFor(() => expect(browser.commands).toHaveLength(5));
const firstCommand = browser.commands[3];
const secondCommand = browser.commands[4];
if (firstCommand === undefined || secondCommand === undefined)
throw new Error("Fake browser did not receive both pending commands");
expect(firstCommand.params).toEqual({ frameId: "first" });
expect(secondCommand.params).toEqual({ frameId: "second" });
browser.emitRawMessage(
JSON.stringify({
id: secondCommand.id,
result: { storageKey: "second" },
}),
);
browser.emitRawMessage(
JSON.stringify({
id: firstCommand.id,
result: { storageKey: "first" },
}),
);
await expect(replies).resolves.toEqual([
{ storageKey: "first" },
{ storageKey: "second" },
]);
await expect(connection.send("Runtime.enable")).resolves.toEqual({});
} finally {
await connection.close();
}
});
it("carries the original event payload byte count before parsing", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"inspect_web_page",
);
try {
const eventMessage = String.raw` { "method" : "Fixture.event", "params" : {"text":"escaped quote: \" slash: \\ unicode: \u96ea"}, "sessionId" : "session-1", "extra" : "counted from source bytes" } `;
let deliveredEvents = 0;
const eventPromise = new Promise<CdpTransportEvent>((resolve) => {
connection.onEvent((event) => {
deliveredEvents += 1;
if (event.domain === "Fixture") resolve(event);
});
});
browser.emitRawMessage(eventMessage);
const event = await eventPromise;
expect(event.wireBytes).toBe(Buffer.byteLength(eventMessage, "utf8"));
expect(event).toMatchObject({
domain: "Fixture",
sessionId: "session-1",
registered: undefined,
});
expect(event).not.toHaveProperty("params");
expect(event).not.toHaveProperty("method");
expect(deliveredEvents).toBe(1);
const protocolFailure = new Promise((resolve) =>
connection.onProtocolFailure(resolve),
);
browser.emitRawMessage("{not-json");
await protocolFailure;
expect(deliveredEvents).toBe(1);
} finally {
await connection.close();
}
});
});
describe("CDP connection event admission", () => {
it("parses a registered event once and shares it with every subscriber", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"inspect_web_page",
);
try {
const params = {
frame: {
id: "main",
loaderId: "loader-1",
url: "https://app.example.test/page",
},
type: "Navigation",
};
const subscriber = () =>
new Promise<CdpTransportEvent>((resolve) => {
connection.onEvent((event) => {
if (event.registered?.method === "Page.frameNavigated")
resolve(event);
});
});
const first = subscriber();
const second = subscriber();
browser.emitRawMessage(
JSON.stringify({ method: "Page.frameNavigated", params }),
);
const [left, right] = await Promise.all([first, second]);
expect(left.registered).toMatchObject({
method: "Page.frameNavigated",
payload: {
url: { kind: "observed", url: "https://app.example.test/page" },
},
});
expect(right.registered).toBe(left.registered);
expect(left).not.toHaveProperty("params");
expect(right).not.toHaveProperty("params");
} finally {
await connection.close();
}
});
});
describe("CDP command cancellation causes", () => {
it("preserves a supplied reason when a command starts with an aborted signal", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"observe_web_session",
);
const controller = new AbortController();
const reason = new Error("command was cancelled before send");
controller.abort(reason);
try {
const failure = await connection
.send("Page.enable", {}, undefined, controller.signal)
.then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(AnalysisCancelledError);
if (!(failure instanceof AnalysisCancelledError))
throw new Error("Expected pre-send command cancellation");
expect(failure.cause).toBe(reason);
expect(browser.commands).toHaveLength(0);
} finally {
await connection.close();
}
});
it("waits for an unresponsive command until caller cancellation", async () => {
const browser = await startFakeCdpBrowser({ hangOnMethod: "Page.enable" });
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"observe_web_session",
);
try {
const controller = new AbortController();
const pending = connection.send(
"Page.enable",
{},
undefined,
controller.signal,
);
await waitFor(() => expect(browser.commands).toHaveLength(1));
const reason = new Error("cancel the pending CDP command");
controller.abort(reason);
const failure = await pending.then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(AnalysisCancelledError);
if (!(failure instanceof AnalysisCancelledError))
throw new Error("Expected command cancellation");
expect(failure.operation).toBe("observe_web_session");
expect(failure.cause).toBe(reason);
} finally {
await connection.close();
}
});
it("preserves AbortController's default reason for an in-flight command", async () => {
const browser = await startFakeCdpBrowser({ hangOnMethod: "Page.enable" });
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"observe_web_session",
);
const controller = new AbortController();
try {
const pending = connection.send(
"Page.enable",
{},
undefined,
controller.signal,
);
await waitFor(() => expect(browser.commands).toHaveLength(1));
controller.abort();
const failure = await pending.then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(AnalysisCancelledError);
if (!(failure instanceof AnalysisCancelledError))
throw new Error("Expected command cancellation");
expect(failure.cause).toBe(controller.signal.reason);
expect(failure.cause).toMatchObject({ name: "AbortError" });
} finally {
await connection.close();
}
});
});
describe("CDP handshake cancellation", () => {
it("preserves handshake cancellation and closes the pending socket", async () => {
const sockets = new Set<Socket>();
const server = createNetServer((socket) => {
sockets.add(socket);
socket.once("close", () => sockets.delete(socket));
socket.resume();
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("Expected a TCP listener address");
const controller = new AbortController();
const reason = new Error("cancel pending CDP handshake");
const connecting = CdpConnection.connect(
`ws://127.0.0.1:${String(address.port)}/target`,
"inspect_web_page",
controller.signal,
);
try {
await waitFor(() => expect(sockets.size).toBe(1));
controller.abort(reason);
const failure = await connecting.then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(AnalysisCancelledError);
if (!(failure instanceof AnalysisCancelledError))
throw new Error("Expected handshake cancellation");
expect(failure.cause).toBe(reason);
await waitFor(() => expect(sockets.size).toBe(0));
} finally {
if (sockets.size > 0) for (const socket of sockets) socket.destroy();
await new Promise<void>((resolve, reject) =>
server.close((error) =>
error === undefined ? resolve() : reject(error),
),
);
}
});
});
describe("CDP transport failure precedence", () => {
it("keeps a completed transport failure primary over a later abort", async () => {
const browser = await startFakeCdpBrowser({ closeOnMethod: "Page.enable" });
browsers.push(browser);
const controller = new AbortController();
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"observe_web_session",
);
try {
const pending = connection
.send("Page.enable", {}, undefined, controller.signal)
.then(
() => undefined,
(cause: unknown) => cause,
);
await waitFor(() => expect(browser.commands).toHaveLength(1));
const failure = await pending;
expect(failure).toMatchObject({
_tag: "BrowserObservationError",
reason: "disconnected",
});
controller.abort(new Error("abort after transport failure"));
expect(failure).toMatchObject({
_tag: "BrowserObservationError",
reason: "disconnected",
});
} finally {
await connection.close();
}
});
});
describe("CDP connection command responses", () => {
it("rejects invalid UTF-8 replies without aliasing a literal replacement character", async () => {
const browser = await startFakeCdpBrowser({
hangOnMethod: "Storage.getStorageKey",
});
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"inspect_web_page",
);
try {
const control = connection.send("Storage.getStorageKey");
await waitFor(() => expect(browser.commands).toHaveLength(1));
browser.emitRawMessage(
Buffer.from(
JSON.stringify({
id: browser.commands[0]?.id,
result: { storageKey: "�" },
}),
),
);
await expect(control).resolves.toEqual({ storageKey: "�" });
const pending = connection.send("Storage.getStorageKey");
const rejected = expect(pending).rejects.toMatchObject({
reason: "protocol_error",
});
await waitFor(() => expect(browser.commands).toHaveLength(2));
browser.emitRawMessage(
Buffer.concat([
Buffer.from(
`{"id":${String(browser.commands[1]?.id)},"result":{"storageKey":"`,
),
Buffer.from([0xff]),
Buffer.from('"}}'),
]),
);
await rejected;
expect(connection.isReusable()).toBe(false);
} finally {
await connection.close();
}
});
it("surfaces an unmodeled fake command as a CDP method rejection", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"observe_web_session",
);
try {
await expect(
connection.send("Storage.getStorageKey"),
).rejects.toMatchObject({
_tag: "BrowserObservationError",
command: "Storage.getStorageKey",
code: -32_601,
reportedMessage: "Method not found: Storage.getStorageKey",
});
} finally {
await connection.close();
}
});
it.each(INVALID_REPLIES)(
"fails the connection for a correlated reply with %s",
async (_case, reply) => {
const browser = await startFakeCdpBrowser({
hangOnMethod: "Page.enable",
});
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"observe_web_session",
);
try {
const pending = connection.send("Page.enable", {}, "selected-session");
const rejection = expect(pending).rejects.toMatchObject({
_tag: "BrowserObservationError",
reason: "protocol_error",
});
await waitFor(() => expect(browser.commands).toHaveLength(1));
const command = browser.commands[0];
if (command === undefined)
throw new Error("Fake browser received no command");
browser.emitRawMessage(JSON.stringify(reply(command.id)));
await rejection;
await expect(connection.send("Runtime.enable")).rejects.toMatchObject({
reason: "protocol_error",
});
} finally {
await connection.close();
}
},
);
it("preserves Chromium's unrouted rejection for a detached flat session", async () => {
const browser = await startFakeCdpBrowser({ hangOnMethod: "Page.enable" });
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"capture_browser_scenario",
);
try {
const pending = connection.send("Page.enable", {}, "detached-session");
const rejection = expect(pending).rejects.toMatchObject({
command: "Page.enable",
code: -32_001,
reportedMessage: "Session with given id not found.",
});
await waitFor(() => expect(browser.commands).toHaveLength(1));
const command = browser.commands[0];
if (command === undefined)
throw new Error("Fake browser received no command");
browser.emitRawMessage(
JSON.stringify({
id: command.id,
error: {
code: -32_001,
message: "Session with given id not found.",
},
}),
);
await rejection;
await expect(connection.send("Runtime.enable")).resolves.toEqual({});
} finally {
await connection.close();
}
});
});
describe("CDP connection payload budgets", () => {
it("accepts an exact UTF-8 payload and rejects one byte more at the selected limit", async () => {
const maxPayloadBytes = 512;
const exactResult = cdpResultAtSize(maxPayloadBytes);
const oversizedResult = cdpResultAtSize(maxPayloadBytes + 1);
const results = [exactResult, oversizedResult];
let resultIndex = 0;
const browser = await startFakeCdpBrowser({
commandResult: () => results[resultIndex++],
});
browsers.push(browser);
let connection: CdpConnection | undefined;
try {
connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"observe_web_execution",
undefined,
{ maxPayloadBytes },
);
await expect(connection.send("Storage.getStorageKey")).resolves.toEqual(
exactResult,
);
await connection.close();
connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"observe_web_execution",
undefined,
{ maxPayloadBytes },
);
const disconnected = vi.fn();
connection.onDisconnect(disconnected);
const openedConnection = connection;
const disconnectNotification = new Promise((resolve) =>
openedConnection.onDisconnect(resolve),
);
await expect(connection.send("Runtime.enable")).rejects.toMatchObject({
reason: "payload_limit",
userMessage: expect.stringContaining("512 byte protocol budget"),
});
expect(await disconnectNotification).toMatchObject({
reason: "payload_limit",
});
expect(disconnected).toHaveBeenCalledTimes(1);
const lateListener = vi.fn();
connection.onDisconnect(lateListener);
expect(lateListener).toHaveBeenCalledWith(
expect.objectContaining({ reason: "payload_limit" }),
);
await expect(connection.send("Debugger.enable")).rejects.toMatchObject({
reason: "payload_limit",
});
expect(browser.commands).toHaveLength(2);
} finally {
await connection?.close();
}
});
it("uses the shared protocol budget by default and rejects an oversized frame header", async () => {
const server = await startOversizedFrameServer(
WEB_RUNTIME_LIMITS.protocolBytes + 1,
);
let connection: CdpConnection | undefined;
try {
connection = await CdpConnection.connect(server.url, "inspect_web_page");
const disconnectNotification = new Promise((resolve) =>
connection?.onDisconnect(resolve),
);
await expect(connection.send("Runtime.enable")).rejects.toMatchObject({
reason: "payload_limit",
userMessage: expect.stringContaining(
`${WEB_RUNTIME_LIMITS.protocolBytes} byte protocol budget`,
),
});
expect(await disconnectNotification).toMatchObject({
reason: "payload_limit",
});
await expect(connection.send("Debugger.enable")).rejects.toMatchObject({
reason: "payload_limit",
});
} finally {
await connection?.close();
await server.close();
}
});
it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY, 0x8000_0000])(
"rejects invalid explicit CDP payload budget %s",
async (maxPayloadBytes) => {
await expect(
CdpConnection.connect(
"ws://127.0.0.1:1/unused",
"inspect_web_page",
undefined,
{ maxPayloadBytes },
),
).rejects.toThrow(RangeError);
},
);
});
const cdpResultAtSize = (bytes: number): Readonly<Record<string, unknown>> => {
const emptyReply = JSON.stringify({ id: 1, result: { storageKey: "" } });
const valueBytes = bytes - Buffer.byteLength(emptyReply);
if (valueBytes < 0)
throw new RangeError("Requested fixture reply is too small");
const value =
"é".repeat(Math.floor(valueBytes / 2)) + (valueBytes % 2 === 0 ? "" : "x");
const result = { storageKey: value };
const reply = JSON.stringify({ id: 1, result });
if (Buffer.byteLength(reply) !== bytes)
throw new Error("Fixture reply did not match its requested byte length");
return result;
};
const startOversizedFrameServer = async (payloadBytes: number) => {
const server = createServer();
const sockets = new Set<{ destroy(): void }>();
server.on("upgrade", (request, socket) => {
const key = request.headers["sec-websocket-key"];
if (typeof key !== "string") {
socket.destroy();
return;
}
const accept = createHash("sha1")
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
.digest("base64");
socket.write(
[
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${accept}`,
"",
"",
].join("\r\n"),
);
sockets.add(socket);
socket.once("close", () => sockets.delete(socket));
let sentOversizedHeader = false;
socket.on("data", () => {
if (sentOversizedHeader) {
socket.end(Buffer.from([0x88, 0]));
return;
}
sentOversizedHeader = true;
const header = Buffer.alloc(10);
header[0] = 0x81;
header[1] = 127;
header.writeBigUInt64BE(BigInt(payloadBytes), 2);
socket.write(header);
});
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (address === null || typeof address === "string")
throw new TypeError("Expected a TCP listener address");
return {
url: `ws://127.0.0.1:${String(address.port)}`,
async close(): Promise<void> {
for (const socket of sockets) socket.destroy();
await new Promise<void>((resolve, reject) =>
server.close((error) =>
error === undefined ? resolve() : reject(error),
),
);
},
};
};
describe("CDP event subscriber failures", () => {
it("routes a throwing event listener to the connection's sessions as a protocol failure", async () => {
const browser = await startFakeCdpBrowser({
hangOnMethod: "Storage.getStorageKey",
});
browsers.push(browser);
const connection = await CdpConnection.connect(
browser.browserWebSocketUrl,
"observe_web_session",
);
const uncaught: unknown[] = [];
const onUncaught = (cause: unknown): void => {
uncaught.push(cause);
};
process.on("uncaughtException", onUncaught);
try {
const listenerFailure = new Error("listener rejected a malformed event");
const later = vi.fn();
connection.onEvent(() => {
throw listenerFailure;
});
connection.onEvent(later);
const protocolFailures: unknown[] = [];
connection.onProtocolFailure((error) => protocolFailures.push(error));
const pending = connection.send("Storage.getStorageKey", {}).then(
() => undefined,
(cause: unknown) => cause,
);
await waitFor(() => expect(browser.commands).toHaveLength(1));
browser.emitEvent({ method: "Target.targetCreated", params: {} });
const failure = await pending;
expect(failure).toMatchObject({
_tag: "BrowserObservationError",
reason: "protocol_error",
cause: listenerFailure,
});
expect(protocolFailures).toEqual([
expect.objectContaining({
reason: "protocol_error",
cause: listenerFailure,
}),
]);
await expect(connection.send("Page.enable")).rejects.toMatchObject({
reason: "protocol_error",
cause: listenerFailure,
});
expect(later).not.toHaveBeenCalled();
expect(connection.isReusable()).toBe(false);
// The wire is sound: an owner can still restore what it changed.
connection.beginCleanupGrace(1_000);
await expect(connection.send("Page.enable")).resolves.toEqual({});
expect(uncaught).toEqual([]);
} finally {
process.off("uncaughtException", onUncaught);
await connection.close();
}
});
});