cdp-toolkit 3.0.3 → 3.1.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/src/origins.ts CHANGED
@@ -32,7 +32,7 @@
32
32
  import { mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
33
33
  import { join } from "node:path";
34
34
  import type { BrowserDriver, PageInfo } from "./driver.ts";
35
- import { defaultLabel, leaseDir, listLeases, type LeaseBackend } from "./leases.ts";
35
+ import { BACKEND_KEY_SOURCE, defaultLabel, leaseDir, listLeases, type LeaseBackend } from "./leases.ts";
36
36
 
37
37
  /** What list_pages can say about where a tab came from. There is deliberately
38
38
  * no "human": see the file header. */
@@ -60,7 +60,10 @@ export function originFile(backend: LeaseBackend, targetId: string): string {
60
60
  return join(leaseDir(), `origin-${backend}-${safeId(targetId)}.json`);
61
61
  }
62
62
 
63
- const ORIGIN_FILE_RE = /^origin-(chrome|firefox)-(.+)\.json$/;
63
+ // Same backend-key grammar as leases.ts: `origin-chrome@teams-<id>.json` for a named
64
+ // endpoint. listOrigins' liveBackend scoping then keeps one endpoint's target list from
65
+ // reaping another endpoint's records.
66
+ const ORIGIN_FILE_RE = new RegExp(`^origin-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
64
67
 
65
68
  /**
66
69
  * Record that this toolkit just created `targetId`.
package/src/policy.ts ADDED
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Read-only endpoint policy (#15): which tools may run against an endpoint marked read-only.
3
+ *
4
+ * The rule: a READ tool sends no CDP command that changes page or browser state. Every tool in
5
+ * the registry (`TOOLS`, src/index.ts) is in exactly one of READ_TOOLS / MUTATING_TOOLS, and the
6
+ * dispatch-only meta tools of src/mcp.ts (search_tools, call_tool, describe_tool) are META: the
7
+ * inner tool of a call_tool is checked when it re-enters dispatch. test/policy.test.ts fails when
8
+ * a tool is added to the registry without being classified here.
9
+ *
10
+ * Default-deny: a name in none of the sets is treated as MUTATING.
11
+ *
12
+ * DECISION (user): evaluate_script is READ. The agent is responsible for what it runs.
13
+ *
14
+ * Classification is by tool name. A few READ tools have arguments that escalate them to a state
15
+ * change (see `escalatesToMutation`); the optional `args` parameter of `assertAllowed` covers those.
16
+ */
17
+
18
+ /** Tools that change no page or browser state (see the borderline notes inline). */
19
+ export const READ_TOOLS: ReadonlySet<string> = new Set([
20
+ // borderline: GET /json/list, plus a local lease/ledger read. `probe` only does a Runtime.evaluate
21
+ // (renderer ping + beacon read). CAVEAT for the dispatcher: under strict-lease mode listPages first
22
+ // reaps stale agent tabs (Target.closeTarget, src/shared-tools.ts listPages); skip the reap on a
23
+ // read-only endpoint.
24
+ "list_pages",
25
+ // borderline: polls Runtime.evaluate for text; changes nothing.
26
+ "wait_for",
27
+ // borderline: arbitrary JS. READ by the user's decision, not by the nature of the tool.
28
+ "evaluate_script",
29
+ // Network.getCookies only. (set_cookie / delete_cookies are MUTATING.)
30
+ "list_cookies",
31
+ // borderline: Accessibility.enable + getFullAXTree; enabling a domain is not a page change.
32
+ "take_snapshot",
33
+ // borderline: Page.getLayoutMetrics + Page.captureScreenshot. With `uid`/`selector` it calls
34
+ // DOM.scrollIntoViewIfNeeded (a scroll); with renderWidth/renderHeight it applies and restores an
35
+ // Emulation.setDeviceMetricsOverride. The latter is escalated in `escalatesToMutation`.
36
+ "take_screenshot",
37
+ // borderline: default reads a buffer a prior recorder wrote. `reload:true` runs Page.reload
38
+ // (escalated in `escalatesToMutation`).
39
+ "list_console_messages",
40
+ "get_console_message",
41
+ "list_network_requests",
42
+ // borderline: metadata read, but `includeBody` with `url` drives a reload capture (escalated).
43
+ "get_network_request",
44
+ // borderline: reads a local trace JSON file; sends no CDP command at all.
45
+ "performance_analyze_insight",
46
+ // borderline: HeapProfiler.enable + takeHeapSnapshot. Forces a GC and can stall the page for a
47
+ // moment, but changes no state.
48
+ "take_heapsnapshot",
49
+ // borderline: lists local fake-backend sessions; its only CDP command is a Runtime.evaluate("1") liveness ping.
50
+ "list_mocks",
51
+ // borderline: a Runtime.evaluate that cleans the page HTML, then POSTs it to an LLM endpoint.
52
+ // Nothing is written to the page. Data leaves the machine; that is not a page-state change.
53
+ "extract_page",
54
+ // borderline: reads the local lease store and /json/list. Same strict-mode reap caveat as list_pages.
55
+ "list_leases",
56
+ ]);
57
+
58
+ /** Tools that send a CDP command that changes page or browser state, or change lease state. */
59
+ export const MUTATING_TOOLS: ReadonlySet<string> = new Set([
60
+ // pages
61
+ "new_page", // Target.createTarget
62
+ "close_page", // Target.closeTarget
63
+ // borderline: Target.activateTarget raises the tab and steals window focus. A state change.
64
+ "select_page",
65
+ "navigate_page", // Page.navigate / reload / history
66
+ "set_cookie",
67
+ "delete_cookies",
68
+ // interaction
69
+ "click",
70
+ "hover", // borderline: Input.dispatchMouseEvent mouseMoved fires hover handlers and can open menus
71
+ "drag",
72
+ "scroll", // borderline: wheel event moves the scroll offset and can trigger lazy loading
73
+ "fill",
74
+ "fill_form",
75
+ "type_text",
76
+ "press_key",
77
+ "upload_file",
78
+ // emulation
79
+ "emulate",
80
+ "resize_page",
81
+ "handle_dialog",
82
+ // performance
83
+ // borderline: Tracing.start begins a browser-wide trace session, and the one-shot variant also reloads.
84
+ "performance_start_trace",
85
+ "performance_stop_trace",
86
+ "performance_trace",
87
+ // recorder: Page.startScreencast / bringToFront, plus ffmpeg and files
88
+ "start_screen_recording",
89
+ "stop_screen_recording",
90
+ // borderline: attaches Lighthouse, which navigates, reloads and throttles the page
91
+ "lighthouse_audit",
92
+ // Fetch.enable: intercepts and rewrites the page's traffic
93
+ "mock_request",
94
+ "clear_mocks",
95
+ "dispatch_mouse",
96
+ "focus_emulation", // Emulation.setFocusEmulationEnabled
97
+ "click_focus_gated",
98
+ "wait_for_download", // borderline: Browser.setDownloadBehavior changes browser state
99
+ "grant_permissions", // Browser.grantPermissions
100
+ // leases: claim installs an activity beacon in the page and writes a lease; release can close a tab
101
+ "claim_page",
102
+ "release_page",
103
+ ]);
104
+
105
+ /** Dispatch-only tools of src/mcp.ts (not in TOOLS). The inner tool is checked on re-entry. */
106
+ export const META_TOOLS: ReadonlySet<string> = new Set(["search_tools", "call_tool", "describe_tool"]);
107
+
108
+ export class PolicyError extends Error {
109
+ readonly code = "read_only_endpoint";
110
+ readonly tool: string;
111
+ readonly endpoint: string;
112
+ constructor(tool: string, endpoint: string) {
113
+ super(`'${tool}' is not allowed on endpoint '${endpoint}': the endpoint is read-only (tools that change state are refused before any CDP message is sent)`);
114
+ this.name = "PolicyError";
115
+ this.tool = tool;
116
+ this.endpoint = endpoint;
117
+ }
118
+ }
119
+
120
+ /** True when the tool is a known READ tool. Unknown names are false (default-deny). */
121
+ export function isReadTool(name: string): boolean {
122
+ return READ_TOOLS.has(name);
123
+ }
124
+
125
+ /**
126
+ * Argument combinations that turn a READ tool into a state change. Returns true when the call
127
+ * must be refused on a read-only endpoint even though the tool name is READ.
128
+ */
129
+ export function escalatesToMutation(tool: string, args: unknown): boolean {
130
+ if (typeof args !== "object" || args === null) return false;
131
+ const a = args as Record<string, unknown>;
132
+ switch (tool) {
133
+ case "list_console_messages":
134
+ case "list_network_requests":
135
+ return a.reload === true;
136
+ case "get_network_request":
137
+ return a.includeBody === true && typeof a.url === "string" && a.url !== "";
138
+ case "take_screenshot":
139
+ return a.renderWidth !== undefined || a.renderHeight !== undefined;
140
+ default:
141
+ return false;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Throw PolicyError when the endpoint is read-only and `tool` may change state. Unknown names are
147
+ * treated as MUTATING. Pass the call's `args` to also refuse the escalating combinations above.
148
+ */
149
+ export function assertAllowed(
150
+ tool: string,
151
+ endpoint: { name: string; readOnly: boolean },
152
+ args?: unknown,
153
+ ): void {
154
+ if (!endpoint.readOnly) return;
155
+ if (META_TOOLS.has(tool)) return;
156
+ if (!READ_TOOLS.has(tool)) throw new PolicyError(tool, endpoint.name);
157
+ if (escalatesToMutation(tool, args)) throw new PolicyError(tool, endpoint.name);
158
+ }
159
+
160
+ /** MCP tools/list annotation: `readOnlyHint` is true for READ tools only. */
161
+ export function toolAnnotations(name: string): { readOnlyHint: boolean } {
162
+ return { readOnlyHint: READ_TOOLS.has(name) };
163
+ }
package/src/reap.ts CHANGED
@@ -30,6 +30,7 @@
30
30
  * `expired` as grounds to close anything. See staleAgentTabs' condition 4.
31
31
  */
32
32
  import type { BrowserDriver } from "./driver.ts";
33
+ import { currentEndpoint } from "./endpoints.ts";
33
34
  import { listLeases, releaseLeaseFor, type LeaseBackend, type LeaseSummary } from "./leases.ts";
34
35
  import { originIndex, type OriginSummary } from "./origins.ts";
35
36
 
@@ -125,6 +126,19 @@ export function reapGraceMs(): number {
125
126
  return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_REAP_GRACE_MS;
126
127
  }
127
128
 
129
+ /**
130
+ * Whether the strict-mode reap may run in the current dispatch scope (#15).
131
+ * NEVER on a read-only endpoint: the reap closes tabs (Target.closeTarget), and
132
+ * a read-only endpoint promises that list_pages / list_leases change nothing
133
+ * there. Read off currentEndpoint(), not the dispatch endpoint, because
134
+ * list_pages{allEndpoints} re-scopes per endpoint. The bidi (Firefox) driver
135
+ * has no named endpoints and never loads their config, so it is always allowed.
136
+ */
137
+ export function reapAllowed(driver: BrowserDriver): boolean {
138
+ if (driver.scheme === "bidi") return true;
139
+ return !currentEndpoint().readOnly;
140
+ }
141
+
128
142
  /**
129
143
  * Select, close, and drop the leases. Returns ONLY the tabs actually closed.
130
144
  *
@@ -42,14 +42,15 @@ import { isTiledCapture } from "./driver.ts";
42
42
  import { stitchPngBandsToFile } from "./png.ts";
43
43
  import type { TargetSelector } from "./types.ts";
44
44
  import {
45
- assertLeaseOk, claimLease, defaultLabel, leaseTtlMs, listLeases, releaseLeaseFor, requireLease,
45
+ assertLeaseOk, chromeLeaseBackend, claimLease, defaultLabel, leaseTtlMs, listLeases, releaseLeaseFor, requireLease,
46
46
  type LeaseBackend, type LeaseStaleReason, type LeaseToken,
47
47
  } from "./leases.ts";
48
48
  import { installBeacon, probeRendererActivity, rendererProbeSupported } from "./activity.ts";
49
49
  import { newTrackedPage, originIndex, resolveLiveLabel, type PageOrigin } from "./origins.ts";
50
50
  import { isWorkerSelector, WORKER_SELECTOR_PAGE_ONLY_MESSAGE, WORKER_SELECTOR_UNSUPPORTED_MESSAGE } from "./workers.ts";
51
51
  import { FRAME_SELECTOR_PAGE_ONLY_MESSAGE, FRAME_SELECTOR_UNSUPPORTED_MESSAGE, isFrameSelector } from "./frames.ts";
52
- import { reapStaleAgentTabs, type ReapedTab } from "./reap.ts";
52
+ import { reapAllowed, reapStaleAgentTabs, type ReapedTab } from "./reap.ts";
53
+ import { allEndpoints, currentEndpoint, isDefaultEndpoint, withEndpointScope } from "./endpoints.ts";
53
54
 
54
55
  const ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
55
56
  const STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
@@ -64,7 +65,8 @@ function target3(p: PageInfo): { id: string; url: string; title: string } {
64
65
  /** Same discriminator leases-tools.ts uses: the driver's own uid scheme tag
65
66
  * ("cdp" for Chrome, "bidi" for Firefox). */
66
67
  function backendOf(driver: BrowserDriver): LeaseBackend {
67
- return driver.scheme === "bidi" ? "firefox" : "chrome";
68
+ // Chrome's key carries the dispatch scope's named endpoint (chrome@<name>); see LeaseBackend.
69
+ return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
68
70
  }
69
71
 
70
72
  /* -------------------------------- page acquisition -------------------------------- */
@@ -217,6 +219,12 @@ function locatorOf(args: { uid?: DriverUid; selector?: string }): ElementLocator
217
219
  * them today.
218
220
  */
219
221
  export interface ListedPage extends PageInfo {
222
+ /** The named CDP endpoint this page lives on (src/endpoints.ts). Present on
223
+ * every row from a NON-default endpoint, and on every row of an
224
+ * allEndpoints listing, so a caller can build an `endpoint:<name>/<id>`
225
+ * selector. Absent on a default-endpoint listing, which keeps that output
226
+ * byte-identical to before named endpoints existed. */
227
+ endpoint?: string;
220
228
  /** "agent" when the creation ledger has a record for this target. Otherwise
221
229
  * "unknown", NEVER "human": the absence of a record is not proof that a
222
230
  * person opened the tab. See src/origins.ts. */
@@ -277,7 +285,66 @@ async function reapSet(driver: BrowserDriver, pages: PageInfo[], all?: boolean):
277
285
  }
278
286
  }
279
287
 
288
+ /** One endpoint's status in a list_pages{allEndpoints:true} result. */
289
+ export type EndpointListing =
290
+ | { endpoint: string; base: string; readOnly: boolean; count: number }
291
+ | { endpoint: string; base: string; readOnly: boolean; down: true; error: string };
292
+
293
+ /**
294
+ * list_pages. With allEndpoints (Chrome only) every configured endpoint is
295
+ * listed in its own endpoint scope, concurrently: page rows are tagged with
296
+ * `endpoint`, `endpoints` reports each endpoint's count, and an endpoint that
297
+ * cannot be reached is reported `{endpoint, down: true, error}` there instead
298
+ * of failing the call. Each endpoint's reap runs in its own scope, so it
299
+ * compares that endpoint's leases only against that endpoint's live targets,
300
+ * and a down endpoint reaps nothing at all.
301
+ */
280
302
  export async function listPages(
303
+ driver: BrowserDriver,
304
+ args: { all?: boolean; probe?: boolean; allEndpoints?: boolean } = {},
305
+ ): Promise<{ pages: ListedPage[]; count: number; reaped?: Array<ReapedTab & { endpoint?: string }>; endpoints?: EndpointListing[] }> {
306
+ const one = { all: args.all, probe: args.probe };
307
+ if (args.allEndpoints === true) {
308
+ if (driver.scheme === "bidi") throw new SharedToolError("list_pages: allEndpoints needs the Chrome backend; named endpoints are CDP-only");
309
+ const results = await Promise.all(
310
+ allEndpoints().map((ep) =>
311
+ withEndpointScope(ep, () => listPagesOne(driver, one)).then(
312
+ (r) => ({ ep, r }),
313
+ (e: unknown) => ({ ep, error: e instanceof Error ? e.message : String(e) }),
314
+ ),
315
+ ),
316
+ );
317
+ const pages: ListedPage[] = [];
318
+ const reaped: Array<ReapedTab & { endpoint: string }> = [];
319
+ const endpoints: EndpointListing[] = [];
320
+ for (const res of results) {
321
+ const { ep } = res;
322
+ if ("error" in res) {
323
+ endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, down: true, error: res.error });
324
+ continue;
325
+ }
326
+ for (const p of res.r.pages) pages.push({ ...p, endpoint: ep.name });
327
+ for (const t of res.r.reaped ?? []) reaped.push({ ...t, endpoint: ep.name });
328
+ endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, count: res.r.count });
329
+ }
330
+ return { pages, count: pages.length, ...(reaped.length ? { reaped } : {}), endpoints };
331
+ }
332
+ const res = await listPagesOne(driver, one);
333
+ if (driver.scheme !== "bidi") {
334
+ const ep = currentEndpoint();
335
+ if (!isDefaultEndpoint(ep)) {
336
+ return {
337
+ ...res,
338
+ pages: res.pages.map((p) => ({ ...p, endpoint: ep.name })),
339
+ ...(res.reaped ? { reaped: res.reaped.map((t) => ({ ...t, endpoint: ep.name })) } : {}),
340
+ };
341
+ }
342
+ }
343
+ return res;
344
+ }
345
+
346
+ /** One endpoint's listing: the pre-#15 list_pages body, unchanged. */
347
+ async function listPagesOne(
281
348
  driver: BrowserDriver,
282
349
  args: { all?: boolean; probe?: boolean } = {},
283
350
  ): Promise<{ pages: ListedPage[]; count: number; reaped?: ReapedTab[] }> {
@@ -286,7 +353,8 @@ export async function listPages(
286
353
  // this same call is in the middle of deleting. Under strict mode only: see
287
354
  // requireLease.
288
355
  const backend = backendOf(driver);
289
- const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
356
+ // Never on a read-only endpoint (#15): reapAllowed.
357
+ const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
290
358
  const reapedIds = new Set(reaped.map((r) => r.targetId));
291
359
  const pages = (await driver.listPages({ all: args.all })).filter((p) => !reapedIds.has(p.id));
292
360
  // Never let provenance break the listing: originIndex does not throw, and a