cdp-toolkit 3.0.3 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/CONTRACT.md +2 -2
- package/README.md +122 -1
- package/dist/bidi/mux-daemon.js +675 -130
- package/dist/cli.js +1432 -635
- package/dist/index.js +1110 -116
- package/dist/mcp.js +1474 -658
- package/package.json +3 -1
- package/src/bidi/snapshot.ts +123 -113
- package/src/cdp/driver.ts +55 -41
- package/src/cdp/endpoint.ts +200 -0
- package/src/cdp/session.ts +246 -0
- package/src/cli.ts +17 -4
- package/src/client.ts +140 -16
- package/src/endpoints.ts +428 -0
- package/src/leases-tools.ts +6 -3
- package/src/leases.ts +28 -4
- package/src/manifest.ts +54 -42
- package/src/mcp.ts +52 -8
- package/src/origins.ts +5 -2
- package/src/policy.ts +163 -0
- package/src/reap.ts +14 -0
- package/src/shared-tools.ts +164 -25
- package/src/toolDocs.ts +41 -38
- package/src/tools/browser-session.ts +26 -12
- package/src/tools/dispatch-mouse.ts +2 -1
- package/src/tools/evaluate.ts +3 -3
- package/src/tools/focus-emulation.ts +5 -3
- package/src/tools/lighthouse.ts +4 -2
- package/src/tools/navigation.ts +3 -3
- package/src/tools/network_mock.ts +2 -2
- package/src/tools/performance.ts +5 -5
- package/src/tools/recorder.ts +3 -3
- package/src/tools/screencast.ts +46 -6
- package/src/tools/snapshot.ts +2 -2
- package/src/version.ts +1 -1
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the DevTools endpoint is, and which of its two transports this Chrome
|
|
3
|
+
* actually serves.
|
|
4
|
+
*
|
|
5
|
+
* THE FACT THIS MODULE EXISTS FOR. Chrome has always had two ways in, and
|
|
6
|
+
* until recently every build served both:
|
|
7
|
+
*
|
|
8
|
+
* A. the HTTP discovery endpoints — `/json/version`, `/json/list` — plus a
|
|
9
|
+
* per-target socket at `/devtools/page/<targetId>`;
|
|
10
|
+
* B. one browser-level socket at `/devtools/browser/<uuid>`, over which
|
|
11
|
+
* `Target.getTargets` lists and `Target.attachToTarget` reaches a page.
|
|
12
|
+
*
|
|
13
|
+
* A Chrome started with `--remote-debugging-port` serves both. A Chrome that
|
|
14
|
+
* had debugging turned on at RUNTIME, through the toggle on
|
|
15
|
+
* `chrome://inspect/#remote-debugging`, serves only (B) — measured on Chrome
|
|
16
|
+
* 153 (the same handshake on a `--remote-debugging-port` instance returns 101
|
|
17
|
+
* for all three):
|
|
18
|
+
*
|
|
19
|
+
* ws://127.0.0.1:<port>/devtools/browser/<uuid> -> HTTP 101
|
|
20
|
+
* ws://127.0.0.1:<port>/devtools/page/<targetId> -> HTTP 403
|
|
21
|
+
* http://127.0.0.1:<port>/json/version, /json/list -> HTTP 404
|
|
22
|
+
*
|
|
23
|
+
* That is not a degraded mode to work around, it is the transport a user gets
|
|
24
|
+
* when they attach to the browser they were already using rather than
|
|
25
|
+
* relaunching it. Everything the toolkit needs is reachable over (B).
|
|
26
|
+
*
|
|
27
|
+
* WHY DETECTED AND NOT CONFIGURED. Making the user declare the transport would
|
|
28
|
+
* make them diagnose a 404 first. The detection is cached per process.
|
|
29
|
+
*
|
|
30
|
+
* WHY THE FALLBACK IS DRIVEN BY A FAILED OPERATION, not by a probe that runs
|
|
31
|
+
* first. `listTargets` still issues its original `/json/list` request before
|
|
32
|
+
* anything here is consulted, and only a request that did NOT answer reaches
|
|
33
|
+
* the fallback. So on a Chrome that serves (A) the code path is the one that
|
|
34
|
+
* shipped, byte for byte, and the new transport cannot regress it — there is
|
|
35
|
+
* no added round-trip, no added failure mode, and no ordering question. The
|
|
36
|
+
* cost of (B) is one 404 on the first listing, then the decision is cached.
|
|
37
|
+
*
|
|
38
|
+
* WHY THE PORT FILE. The browser socket's URL contains a uuid that is minted
|
|
39
|
+
* fresh on every Chrome start, so it cannot be written into a config once. The
|
|
40
|
+
* uuid and the port are the two lines of `DevToolsActivePort` in the profile
|
|
41
|
+
* directory, which is where `/json/version` would otherwise have supplied it.
|
|
42
|
+
* Resolved at connect time for that reason, never memoized across a restart.
|
|
43
|
+
*/
|
|
44
|
+
import { readFile } from "node:fs/promises";
|
|
45
|
+
import { homedir } from "node:os";
|
|
46
|
+
import { join } from "node:path";
|
|
47
|
+
import { currentEndpoint, isDefaultEndpoint } from "../endpoints.ts";
|
|
48
|
+
// A cycle (client.ts imports this module), safe because CdpConnection is only
|
|
49
|
+
// used at call time, never while either module is still evaluating.
|
|
50
|
+
import { CdpConnection } from "../client.ts";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Which transport this endpoint serves.
|
|
54
|
+
* "http" — `/json/*` answers; per-target sockets exist. The original path.
|
|
55
|
+
* "browser-ws" — only the browser socket answers; pages are reached by session.
|
|
56
|
+
*/
|
|
57
|
+
export type CdpTransport = "http" | "browser-ws";
|
|
58
|
+
|
|
59
|
+
export interface EndpointInfo {
|
|
60
|
+
transport: CdpTransport;
|
|
61
|
+
/** The browser-level WebSocket URL. Always present: both transports have one. */
|
|
62
|
+
browserWsUrl: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The browser socket URL from a profile's `DevToolsActivePort`.
|
|
67
|
+
*
|
|
68
|
+
* The file is exactly two lines — port, then the path component including the
|
|
69
|
+
* uuid — and Chrome rewrites it on every start. A profile that is not running
|
|
70
|
+
* leaves a STALE file behind rather than deleting it, so a URL from here is a
|
|
71
|
+
* candidate to be handshaked, never a fact; `detectEndpoint` treats a failed
|
|
72
|
+
* connect as "not this profile" and moves on.
|
|
73
|
+
*/
|
|
74
|
+
async function browserWsFromPortFile(dir: string, base: string): Promise<string | undefined> {
|
|
75
|
+
const raw = await readFile(join(dir, "DevToolsActivePort"), "utf8").catch(() => undefined);
|
|
76
|
+
if (!raw) return undefined;
|
|
77
|
+
const [port, path] = raw.split("\n");
|
|
78
|
+
if (!port?.trim() || !path?.trim()) return undefined;
|
|
79
|
+
const host = new URL(base).hostname;
|
|
80
|
+
return `ws://${host}:${port.trim()}${path.trim()}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The browser socket for an explicitly named profile, and ONLY an explicitly
|
|
85
|
+
* named one.
|
|
86
|
+
*
|
|
87
|
+
* NEVER SCANS THE DEFAULT PROFILE, and that restraint is the point rather than
|
|
88
|
+
* an omission. Connecting to a DevTools endpoint is not a neutral act: a Chrome
|
|
89
|
+
* with runtime debugging enabled raises a modal "Allow remote debugging?"
|
|
90
|
+
* consent prompt on the user's screen for each new client, and that prompt
|
|
91
|
+
* grants full access to a logged-in browsing session. A library that guesses
|
|
92
|
+
* its way to a browser nobody named would raise that prompt from a unit-test
|
|
93
|
+
* run — which is exactly how this restriction was found, by doing it.
|
|
94
|
+
*
|
|
95
|
+
* So the profile is opt-in: `CDP_USER_DATA_DIR` names it, or nothing is tried.
|
|
96
|
+
* Pointing this toolkit at a browser stays a decision the user makes.
|
|
97
|
+
*/
|
|
98
|
+
async function discoverBrowserWs(base: string): Promise<string | undefined> {
|
|
99
|
+
const dir = process.env.CDP_USER_DATA_DIR;
|
|
100
|
+
return dir ? browserWsFromPortFile(dir, base) : undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A bounded WebSocket handshake. The port file can name a Chrome that exited,
|
|
105
|
+
* and a dead port would otherwise stall the whole detection on a connect that
|
|
106
|
+
* never resolves. Goes through `CdpConnection` (CONTRIBUTING.md, code rule 2),
|
|
107
|
+
* whose connect is bounded by `timeoutMs`; the socket is closed either way.
|
|
108
|
+
*/
|
|
109
|
+
async function handshake(url: string, timeoutMs: number): Promise<boolean> {
|
|
110
|
+
const conn = new CdpConnection(url, { timeoutMs });
|
|
111
|
+
try {
|
|
112
|
+
await conn.connect();
|
|
113
|
+
return true;
|
|
114
|
+
} catch {
|
|
115
|
+
return false;
|
|
116
|
+
} finally {
|
|
117
|
+
conn.close();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Keyed by endpoint base: named endpoints are separate browsers, each with its own transport. */
|
|
122
|
+
const cached = new Map<string, Promise<EndpointInfo>>();
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Locate the browser socket for an endpoint that serves no `/json`.
|
|
126
|
+
*
|
|
127
|
+
* Called only after an HTTP request has already failed, so it never runs at all
|
|
128
|
+
* against a Chrome started with `--remote-debugging-port`. `CDP_BROWSER_WS`
|
|
129
|
+
* short-circuits the profile lookup, for an endpoint the port file cannot name
|
|
130
|
+
* (a container, a forwarded port, a profile outside the defaults).
|
|
131
|
+
*
|
|
132
|
+
* Per endpoint: the base comes from currentEndpoint() on each call. CDP_BROWSER_WS and
|
|
133
|
+
* CDP_USER_DATA_DIR each name ONE browser, so they apply to the default endpoint only;
|
|
134
|
+
* a named endpoint is detected from its own `/json/version`.
|
|
135
|
+
*/
|
|
136
|
+
export function detectEndpoint(): Promise<EndpointInfo> {
|
|
137
|
+
// Only a resolved detection is worth keeping. A failure here is usually
|
|
138
|
+
// transient — Chrome still starting, a port file mid-rewrite — and caching
|
|
139
|
+
// the rejection would make the first unlucky call poison every later one.
|
|
140
|
+
const endpoint = currentEndpoint();
|
|
141
|
+
const base = endpoint.base;
|
|
142
|
+
const isDefault = isDefaultEndpoint(endpoint);
|
|
143
|
+
const hit = cached.get(base);
|
|
144
|
+
if (hit) return hit;
|
|
145
|
+
const detection = (async (): Promise<EndpointInfo> => {
|
|
146
|
+
const forced = isDefault ? process.env.CDP_BROWSER_WS : undefined;
|
|
147
|
+
if (forced) return { transport: "browser-ws", browserWsUrl: forced };
|
|
148
|
+
|
|
149
|
+
const discovered = isDefault ? await discoverBrowserWs(base) : undefined;
|
|
150
|
+
if (discovered && (await handshake(discovered, 5_000))) {
|
|
151
|
+
return { transport: "browser-ws", browserWsUrl: discovered };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Bounded for the same reason the handshake above is: a host that accepts
|
|
155
|
+
// the connection and never answers would otherwise stall detection forever.
|
|
156
|
+
const version = await fetch(`${base}/json/version`, { signal: AbortSignal.timeout(5_000) })
|
|
157
|
+
.then((r) => (r.ok ? (r.json() as Promise<{ webSocketDebuggerUrl?: string }>) : undefined))
|
|
158
|
+
.catch(() => undefined);
|
|
159
|
+
if (version?.webSocketDebuggerUrl) {
|
|
160
|
+
return { transport: "http", browserWsUrl: version.webSocketDebuggerUrl };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const dir = isDefault ? process.env.CDP_USER_DATA_DIR : undefined;
|
|
164
|
+
throw new Error(
|
|
165
|
+
`no DevTools endpoint at ${base}: GET /json/version did not answer and ` +
|
|
166
|
+
(dir
|
|
167
|
+
? `no live browser socket was named by ${dir}/DevToolsActivePort. `
|
|
168
|
+
: `no profile was searched — CDP_USER_DATA_DIR is unset, and no profile is ever scanned unless you name one. `) +
|
|
169
|
+
`Set CDP_BROWSER_WS to the ws://.../devtools/browser/<uuid> URL, or CDP_USER_DATA_DIR to the profile in use.`,
|
|
170
|
+
);
|
|
171
|
+
})().then(
|
|
172
|
+
(info) => {
|
|
173
|
+
// Keep only a browser-ws answer. An "http" one carries a `/json/version`
|
|
174
|
+
// uuid that a Chrome restart invalidates, and that endpoint can simply be
|
|
175
|
+
// asked again, as the HTTP path always has.
|
|
176
|
+
if (info.transport === "http") cached.delete(base);
|
|
177
|
+
return info;
|
|
178
|
+
},
|
|
179
|
+
(error: unknown) => {
|
|
180
|
+
cached.delete(base);
|
|
181
|
+
throw error;
|
|
182
|
+
},
|
|
183
|
+
);
|
|
184
|
+
cached.set(base, detection);
|
|
185
|
+
return detection;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Forget the current endpoint's detection, so the next `detectEndpoint` looks
|
|
190
|
+
* again. For a browser socket that stopped answering: its URL carries a uuid
|
|
191
|
+
* Chrome mints on every start, so after a restart the cached one is stale.
|
|
192
|
+
*/
|
|
193
|
+
export function forgetEndpoint(): void {
|
|
194
|
+
cached.delete(currentEndpoint().base);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Test seam: drop the per-process detection cache. */
|
|
198
|
+
export function resetEndpointCache(): void {
|
|
199
|
+
cached.clear();
|
|
200
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A page connection carried by a flat `Target.attachToTarget` session on the
|
|
3
|
+
* browser socket, for the endpoints that serve no per-target socket (see
|
|
4
|
+
* ./endpoint.ts for why those exist).
|
|
5
|
+
*
|
|
6
|
+
* WHAT THIS IS. `SessionConnection` presents the same surface as
|
|
7
|
+
* `CdpConnection` — `send`, `on`, `waitFor`, `close`, with the same
|
|
8
|
+
* per-command timeout — but instead of owning a socket it owns a sessionId and
|
|
9
|
+
* borrows the shared browser socket. Every tool module in the toolkit is typed
|
|
10
|
+
* against that surface, so none of them has to know which one it holds. The
|
|
11
|
+
* one-target-per-call guarantee is unchanged: a call attaches to the ONE
|
|
12
|
+
* target it named and detaches when it is done.
|
|
13
|
+
*
|
|
14
|
+
* WHY FLAT SESSIONS. With `flatten: true` every message for an attached target
|
|
15
|
+
* carries its `sessionId` on the same socket, so routing is a map lookup and
|
|
16
|
+
* two sessions never see each other's events. The nested alternative wraps
|
|
17
|
+
* each message in `Target.receivedMessageFromTarget`, which would mean
|
|
18
|
+
* re-implementing correlation a second time.
|
|
19
|
+
*
|
|
20
|
+
* WHY THE SOCKET IS SHARED AND REFERENCE-COUNTED. Chrome mints a NEW session
|
|
21
|
+
* per attach, and sessions on one socket are independent — measured: attaching
|
|
22
|
+
* twice to one target yields two distinct ids, and detaching one leaves the
|
|
23
|
+
* other working. So concurrent calls can and should share a single browser
|
|
24
|
+
* socket. What they must not do is close it while another call is still using
|
|
25
|
+
* it, hence the refcount: the socket opens on the first borrower and closes
|
|
26
|
+
* after the last one releases.
|
|
27
|
+
*
|
|
28
|
+
* THE WEDGED-TAB PROPERTY IS PRESERVED, and it is the reason the toolkit is
|
|
29
|
+
* worth pointing at a browser with a wedged tab in it. A command to a hung
|
|
30
|
+
* renderer times out in `CdpConnection.send` exactly as before — the timer is
|
|
31
|
+
* per command id, not per socket — and because this transport never attaches
|
|
32
|
+
* to a target it was not asked for, a wedged tab is only ever reached by a
|
|
33
|
+
* call that named it.
|
|
34
|
+
*/
|
|
35
|
+
import { CdpConnection, CdpError, DEFAULT_TIMEOUT_MS } from "../client.ts";
|
|
36
|
+
import { detectEndpoint, forgetEndpoint } from "./endpoint.ts";
|
|
37
|
+
|
|
38
|
+
type EventHandler = (params: Record<string, unknown>, sessionId?: string) => void;
|
|
39
|
+
|
|
40
|
+
/* ----------------------------- shared browser socket ----------------------------- */
|
|
41
|
+
|
|
42
|
+
let shared: { conn: CdpConnection; refs: number; url: string } | undefined;
|
|
43
|
+
let opening: Promise<CdpConnection> | undefined;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Borrow the shared browser socket, opening it if nobody holds one.
|
|
47
|
+
*
|
|
48
|
+
* `opening` deduplicates a concurrent first borrow: two calls that arrive
|
|
49
|
+
* together must end up on ONE socket, not race to open two and leak the loser.
|
|
50
|
+
*/
|
|
51
|
+
async function acquireBrowserConn(): Promise<CdpConnection> {
|
|
52
|
+
if (shared) {
|
|
53
|
+
shared.refs++;
|
|
54
|
+
return shared.conn;
|
|
55
|
+
}
|
|
56
|
+
if (!opening) {
|
|
57
|
+
opening = (async () => {
|
|
58
|
+
let { browserWsUrl } = await detectEndpoint();
|
|
59
|
+
let conn: CdpConnection;
|
|
60
|
+
try {
|
|
61
|
+
conn = await new CdpConnection(browserWsUrl).connect();
|
|
62
|
+
} catch (error) {
|
|
63
|
+
// The detection is cached, and a Chrome restart mints a new browser
|
|
64
|
+
// uuid, so a URL that stopped answering may just be stale: forget it and
|
|
65
|
+
// detect once more. Same URL again (CDP_BROWSER_WS, or Chrome really is
|
|
66
|
+
// down) means there is nothing newer to try.
|
|
67
|
+
forgetEndpoint();
|
|
68
|
+
const fresh = (await detectEndpoint().catch(() => undefined))?.browserWsUrl;
|
|
69
|
+
if (!fresh || fresh === browserWsUrl) throw error;
|
|
70
|
+
browserWsUrl = fresh;
|
|
71
|
+
conn = await new CdpConnection(browserWsUrl).connect();
|
|
72
|
+
}
|
|
73
|
+
shared = { conn, refs: 0, url: browserWsUrl };
|
|
74
|
+
return conn;
|
|
75
|
+
})().finally(() => {
|
|
76
|
+
opening = undefined;
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const conn = await opening;
|
|
80
|
+
// `shared` is set by the block above before it resolves; a concurrent
|
|
81
|
+
// release cannot have run in between, because releasing requires a ref and
|
|
82
|
+
// this borrower has not taken one yet.
|
|
83
|
+
shared!.refs++;
|
|
84
|
+
return conn;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Return a borrow. The socket closes when the last holder lets go. */
|
|
88
|
+
function releaseBrowserConn(): void {
|
|
89
|
+
if (!shared) return;
|
|
90
|
+
shared.refs--;
|
|
91
|
+
if (shared.refs <= 0) {
|
|
92
|
+
const { conn } = shared;
|
|
93
|
+
shared = undefined;
|
|
94
|
+
conn.close();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Run `fn` on the shared browser socket. The browser-domain counterpart of
|
|
100
|
+
* client.ts's `withPage`, and the only way this module opens a socket.
|
|
101
|
+
*/
|
|
102
|
+
export async function withBrowserSocket<T>(fn: (conn: CdpConnection) => Promise<T>): Promise<T> {
|
|
103
|
+
const conn = await acquireBrowserConn();
|
|
104
|
+
try {
|
|
105
|
+
return await fn(conn);
|
|
106
|
+
} finally {
|
|
107
|
+
releaseBrowserConn();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/* -------------------------------- page sessions -------------------------------- */
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* One attached target, shaped like a `CdpConnection`.
|
|
115
|
+
*
|
|
116
|
+
* Structural, not a subclass: `CdpConnection` owns a socket in its constructor
|
|
117
|
+
* and this owns a sessionId, so there is no state to inherit. Callers hold
|
|
118
|
+
* them through the shared `PageConnection` type below.
|
|
119
|
+
*/
|
|
120
|
+
export class SessionConnection {
|
|
121
|
+
private detached = false;
|
|
122
|
+
private readonly offs: Array<() => void> = [];
|
|
123
|
+
|
|
124
|
+
constructor(
|
|
125
|
+
private readonly browser: CdpConnection,
|
|
126
|
+
readonly sessionId: string,
|
|
127
|
+
private readonly opts: { timeoutMs?: number } = {},
|
|
128
|
+
) {}
|
|
129
|
+
|
|
130
|
+
/** Send over this session. Same timeout semantics as CdpConnection.send. */
|
|
131
|
+
send<T = Record<string, unknown>>(
|
|
132
|
+
method: string,
|
|
133
|
+
params: Record<string, unknown> = {},
|
|
134
|
+
opts: { timeoutMs?: number; sessionId?: string } = {},
|
|
135
|
+
): Promise<T> {
|
|
136
|
+
if (this.detached) return Promise.reject(new CdpError("connection not open"));
|
|
137
|
+
// An explicit sessionId wins, so a caller that attached a NESTED session of
|
|
138
|
+
// its own (cdp/workers.ts does this for ServiceWorker) still addresses it.
|
|
139
|
+
return this.browser.send<T>(method, params, {
|
|
140
|
+
timeoutMs: opts.timeoutMs ?? this.opts.timeoutMs,
|
|
141
|
+
sessionId: opts.sessionId ?? this.sessionId,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Subscribe, filtered to THIS session.
|
|
147
|
+
*
|
|
148
|
+
* The filter is what makes one socket behave like many: the browser socket
|
|
149
|
+
* carries every attached target's events, and a handler registered here must
|
|
150
|
+
* see only its own. An event with no sessionId is browser-level (a
|
|
151
|
+
* `Target.*` notification) and is delivered too, matching what a per-target
|
|
152
|
+
* socket shows.
|
|
153
|
+
*/
|
|
154
|
+
on(method: string, handler: EventHandler): () => void {
|
|
155
|
+
const off = this.browser.on(method, (params, sessionId) => {
|
|
156
|
+
if (sessionId && sessionId !== this.sessionId) return;
|
|
157
|
+
handler(params, sessionId);
|
|
158
|
+
});
|
|
159
|
+
this.offs.push(off);
|
|
160
|
+
return off;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
waitFor<P = Record<string, unknown>>(
|
|
164
|
+
method: string,
|
|
165
|
+
predicate?: (params: P) => boolean,
|
|
166
|
+
timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
167
|
+
): Promise<P> {
|
|
168
|
+
return new Promise<P>((resolve, reject) => {
|
|
169
|
+
const timer = setTimeout(() => {
|
|
170
|
+
off();
|
|
171
|
+
reject(new CdpError(`waitFor('${method}') timed out after ${timeoutMs}ms`));
|
|
172
|
+
}, timeoutMs);
|
|
173
|
+
const off = this.on(method, (params) => {
|
|
174
|
+
if (!predicate || predicate(params as P)) {
|
|
175
|
+
clearTimeout(timer);
|
|
176
|
+
off();
|
|
177
|
+
resolve(params as P);
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Detach and return the socket borrow.
|
|
185
|
+
*
|
|
186
|
+
* Named `close` because that is the method every tool module already calls in
|
|
187
|
+
* its `finally`. The detach is fire-and-forget: the borrow must be returned
|
|
188
|
+
* even when the target died first, and a failed detach on a target that is
|
|
189
|
+
* already gone is not a caller's problem.
|
|
190
|
+
*/
|
|
191
|
+
close(): void {
|
|
192
|
+
if (this.detached) return;
|
|
193
|
+
this.detached = true;
|
|
194
|
+
for (const off of this.offs) off();
|
|
195
|
+
this.offs.length = 0;
|
|
196
|
+
void this.browser.send("Target.detachFromTarget", { sessionId: this.sessionId }).catch(() => {
|
|
197
|
+
/* target already gone */
|
|
198
|
+
});
|
|
199
|
+
releaseBrowserConn();
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* What every tool module actually holds: a `CdpConnection` when the endpoint
|
|
205
|
+
* serves per-target sockets, a `SessionConnection` when it does not.
|
|
206
|
+
*
|
|
207
|
+
* AN INTERFACE, NOT A UNION, on purpose. A union of the two classes would make
|
|
208
|
+
* every tool module narrow before it could send, for a distinction none of them
|
|
209
|
+
* cares about. This is the surface they were already using — four methods —
|
|
210
|
+
* so both implementations satisfy it structurally and `withPage` hands over
|
|
211
|
+
* whichever one the transport produced.
|
|
212
|
+
*/
|
|
213
|
+
export interface PageConnection {
|
|
214
|
+
send<T = Record<string, unknown>>(
|
|
215
|
+
method: string,
|
|
216
|
+
params?: Record<string, unknown>,
|
|
217
|
+
opts?: { timeoutMs?: number; sessionId?: string },
|
|
218
|
+
): Promise<T>;
|
|
219
|
+
on(method: string, handler: EventHandler): () => void;
|
|
220
|
+
waitFor<P = Record<string, unknown>>(
|
|
221
|
+
method: string,
|
|
222
|
+
predicate?: (params: P) => boolean,
|
|
223
|
+
timeoutMs?: number,
|
|
224
|
+
): Promise<P>;
|
|
225
|
+
close(): void;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Attach to one target and wrap the session. The caller closes it. */
|
|
229
|
+
export async function openSession(
|
|
230
|
+
targetId: string,
|
|
231
|
+
opts: { timeoutMs?: number } = {},
|
|
232
|
+
): Promise<SessionConnection> {
|
|
233
|
+
const browser = await acquireBrowserConn();
|
|
234
|
+
try {
|
|
235
|
+
const { sessionId } = await browser.send<{ sessionId?: string }>(
|
|
236
|
+
"Target.attachToTarget",
|
|
237
|
+
{ targetId, flatten: true },
|
|
238
|
+
{ timeoutMs: opts.timeoutMs },
|
|
239
|
+
);
|
|
240
|
+
if (!sessionId) throw new CdpError(`Target.attachToTarget returned no sessionId for ${targetId}`);
|
|
241
|
+
return new SessionConnection(browser, sessionId, opts);
|
|
242
|
+
} catch (e) {
|
|
243
|
+
releaseBrowserConn();
|
|
244
|
+
throw e;
|
|
245
|
+
}
|
|
246
|
+
}
|
package/src/cli.ts
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* wins; --json is applied first, then the individual flags).
|
|
20
20
|
*
|
|
21
21
|
* Output:
|
|
22
|
-
* - success -> JSON.stringify(result, null, 2) to stdout, exit 0.
|
|
22
|
+
* - success -> JSON.stringify(result ?? null, null, 2) to stdout, exit 0.
|
|
23
23
|
* - throw -> JSON.stringify({ error: message }) to stderr, exit 1.
|
|
24
24
|
* - no tool -> usage message to stderr, exit 1.
|
|
25
25
|
* - --list -> all tool names (one per line) to stdout, exit 0.
|
|
@@ -29,7 +29,9 @@ import { resolveBackend, stripBrowserFlag, stripConnectFlag, startFirefoxSession
|
|
|
29
29
|
import { toolAvailability } from "./capabilities.ts";
|
|
30
30
|
import { FIREFOX_TOOLS } from "./firefox-tools.ts";
|
|
31
31
|
import { leaseFromArgs, withLeaseScope } from "./leases.ts";
|
|
32
|
+
import { ENDPOINTS_FIREFOX_MESSAGE, stripEndpointArgs, usesEndpointArgs, withEndpointScope } from "./endpoints.ts";
|
|
32
33
|
import { MANIFEST } from "./manifest.ts";
|
|
34
|
+
import { assertAllowed } from "./policy.ts";
|
|
33
35
|
import { runInstaller } from "./install/wizard.ts";
|
|
34
36
|
import { realpathSync } from "node:fs";
|
|
35
37
|
import { fileURLToPath } from "node:url";
|
|
@@ -344,16 +346,27 @@ async function main(): Promise<number> {
|
|
|
344
346
|
return withLeaseScope(leaseFromArgs(parsed.args), async () => {
|
|
345
347
|
if (browser === "chrome") {
|
|
346
348
|
const fn = TOOLS[tool];
|
|
349
|
+
// Same endpoint scope as mcp.ts's runTool: the endpoint:<name>/ prefix (or
|
|
350
|
+
// --endpoint) is resolved and stripped once, here. A bad name or a malformed
|
|
351
|
+
// CDP_ENDPOINTS throws to main's catch, which prints {"error": ...} and exits 1.
|
|
352
|
+
const { endpoint, args: toolArgs } = stripEndpointArgs(parsed.args);
|
|
353
|
+
// Read-only endpoint policy, before the tool runs (same check as mcp.ts's runTool).
|
|
354
|
+
// A PolicyError throws to main's catch: {"error": "'click' is not allowed on endpoint ..."}, exit 1.
|
|
355
|
+
assertAllowed(tool, endpoint, toolArgs);
|
|
347
356
|
// The registry's value type is the union of all tool signatures; each tool
|
|
348
357
|
// validates its own args at runtime, so we hand the parsed object through.
|
|
349
|
-
const result = await (fn as (args: unknown) => Promise<unknown>)(
|
|
350
|
-
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
358
|
+
const result = await withEndpointScope(endpoint, () => (fn as (args: unknown) => Promise<unknown>)(toolArgs));
|
|
359
|
+
process.stdout.write(`${JSON.stringify(result ?? null, null, 2)}\n`);
|
|
351
360
|
return 0;
|
|
352
361
|
}
|
|
353
362
|
|
|
354
363
|
// Firefox: one process per invocation. Launch (or, with --connect/CDP_FIREFOX_ENDPOINT,
|
|
355
364
|
// attach), run exactly one tool call, always dispose, even if the tool call itself throws —
|
|
356
365
|
// in launch mode that reaps the spawned process; in attach mode it only ends the BiDi session.
|
|
366
|
+
if (usesEndpointArgs(parsed.args)) {
|
|
367
|
+
process.stderr.write(`${JSON.stringify({ error: ENDPOINTS_FIREFOX_MESSAGE })}\n`);
|
|
368
|
+
return 1;
|
|
369
|
+
}
|
|
357
370
|
const neutralFn = FIREFOX_TOOLS[tool];
|
|
358
371
|
if (!neutralFn) {
|
|
359
372
|
process.stderr.write(`${JSON.stringify({ error: `tool '${tool}' has no Firefox implementation wired` })}\n`);
|
|
@@ -362,7 +375,7 @@ async function main(): Promise<number> {
|
|
|
362
375
|
const session = await startFirefoxSession({ endpoint });
|
|
363
376
|
try {
|
|
364
377
|
const result = await neutralFn(session.driver, parsed.args as never);
|
|
365
|
-
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
378
|
+
process.stdout.write(`${JSON.stringify(result ?? null, null, 2)}\n`);
|
|
366
379
|
return 0;
|
|
367
380
|
} finally {
|
|
368
381
|
await session.dispose();
|