cdp-toolkit 1.2.0 → 1.4.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.
@@ -33,12 +33,13 @@
33
33
  * behavior outranks the abstraction, these 7 stay two implementations; see the migration report.
34
34
  */
35
35
  import { mkdir, writeFile } from "node:fs/promises";
36
- import { join } from "node:path";
36
+ import { dirname, join } from "node:path";
37
37
  import type {
38
- BrowserDriver, DriverUid, ElementLocator, NavigateResult, PageDriver, PageInfo, SnapshotNode,
38
+ BrowserCookie, BrowserDriver, DriverUid, ElementLocator, NavigateResult, PageDriver, PageInfo, SnapshotNode,
39
39
  } from "./driver.ts";
40
40
  import type { TargetSelector } from "./types.ts";
41
- import { assertLeaseOk, claimLease, leaseTtlMs, releaseLeaseFor, type LeaseBackend, type LeaseToken } from "./leases.ts";
41
+ import { assertLeaseOk, claimLease, defaultLabel, leaseTtlMs, releaseLeaseFor, type LeaseBackend, type LeaseToken } from "./leases.ts";
42
+ import { newTrackedPage, originIndex, type PageOrigin } from "./origins.ts";
42
43
 
43
44
  const ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
44
45
  const STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
@@ -133,21 +134,75 @@ function locatorOf(args: { uid?: DriverUid; selector?: string }): ElementLocator
133
134
 
134
135
  /* -------------------------------- pages (4) -------------------------------- */
135
136
 
136
- export async function listPages(driver: BrowserDriver, args: { all?: boolean } = {}): Promise<{ pages: PageInfo[]; count: number }> {
137
+ /**
138
+ * A page listing entry, PageInfo plus provenance. STRICTLY ADDITIVE: {id, url,
139
+ * title, type} are unchanged in name, type and value, because consumers read
140
+ * them today.
141
+ */
142
+ export interface ListedPage extends PageInfo {
143
+ /** "agent" when the creation ledger has a record for this target. Otherwise
144
+ * "unknown", NEVER "human": the absence of a record is not proof that a
145
+ * person opened the tab. See src/origins.ts. */
146
+ origin: PageOrigin;
147
+ /** The creating agent's label. Present only when origin is "agent". */
148
+ label?: string;
149
+ /** When this toolkit created the tab (epoch ms). Only when origin is "agent". */
150
+ createdAt?: number;
151
+ /** Present only when this target HAS a ledger record that could not be read:
152
+ * the errno, or "unparseable". origin stays "unknown" because provenance is
153
+ * genuinely unknown, but this field is what keeps an unreadable record from
154
+ * being reported as a clean "nothing was ever recorded". */
155
+ originUnreadable?: string;
156
+ }
157
+
158
+ /**
159
+ * The reap set for the origin ledger: every target the browser currently has,
160
+ * INCLUDING non-page targets, regardless of what this call is listing.
161
+ *
162
+ * Using the filtered page list would be a bug with a plausible disguise: a
163
+ * default list_pages call drops workers and iframes, so reaping against it
164
+ * would delete the ledger record of any target that is alive but filtered out.
165
+ * Returning undefined (which listOrigins reads as "reap nothing") when the
166
+ * unfiltered listing fails is the same principle one step further: a failed
167
+ * enumeration must never be able to empty the ledger.
168
+ */
169
+ async function reapSet(driver: BrowserDriver, pages: PageInfo[], all?: boolean): Promise<readonly string[] | undefined> {
170
+ if (all === true) return pages.map((p) => p.id);
171
+ try {
172
+ return (await driver.listPages({ all: true })).map((p) => p.id);
173
+ } catch {
174
+ return undefined;
175
+ }
176
+ }
177
+
178
+ export async function listPages(driver: BrowserDriver, args: { all?: boolean } = {}): Promise<{ pages: ListedPage[]; count: number }> {
137
179
  const pages = await driver.listPages({ all: args.all });
138
- return { pages, count: pages.length };
180
+ // Never let provenance break the listing: originIndex does not throw, and a
181
+ // missing or unreadable ledger yields an empty map, so every page falls back
182
+ // to origin "unknown" exactly as a pre-ledger consumer always saw.
183
+ const ledger = await originIndex(backendOf(driver), await reapSet(driver, pages, args.all));
184
+ const annotated: ListedPage[] = pages.map((p) => {
185
+ const rec = ledger.get(p.id);
186
+ if (!rec) return { ...p, origin: "unknown" };
187
+ if (rec.unreadable !== undefined) return { ...p, origin: "unknown", originUnreadable: rec.unreadable };
188
+ return { ...p, origin: "agent", label: rec.label, createdAt: rec.createdAt };
189
+ });
190
+ return { pages: annotated, count: annotated.length };
139
191
  }
140
192
 
141
193
  export async function newPage(
142
194
  driver: BrowserDriver,
143
195
  args: { url?: string; claim?: boolean; label?: string; ttlMs?: number } = {},
144
196
  ): Promise<{ targetId: string; url: string; lease?: LeaseToken; label?: string; expiresAt?: number }> {
145
- const p = await driver.newPage(args.url);
197
+ const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
198
+ // Creates the tab AND writes its creation record. The record outlives any
199
+ // lease taken below, which is the point: a released tab is still an agent's.
200
+ const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label });
146
201
  if (args.claim !== true) return { targetId: p.id, url: p.url };
147
202
  // Atomic in the sense that matters: the tab is claimed before this call
148
203
  // returns, so no other agent can see it unclaimed and take it first.
149
204
  const { record, token } = await claimLease(backendOf(driver), p.id, {
150
- label: typeof args.label === "string" && args.label.length ? args.label : `pid-${process.pid}`,
205
+ label,
151
206
  ttlMs: typeof args.ttlMs === "number" && args.ttlMs > 0 ? args.ttlMs : leaseTtlMs(),
152
207
  });
153
208
  return { targetId: p.id, url: p.url, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs };
@@ -232,14 +287,261 @@ export const waitFor = waitForText;
232
287
 
233
288
  /* ------------------------------- evaluate (1) ------------------------------- */
234
289
 
290
+ /**
291
+ * The `savePath` result shape. Deliberately carries NO form of the evaluated
292
+ * value: not the value, not a preview, not a truncation, not a byte prefix.
293
+ * The whole reason `savePath` exists is that the value may be a credential
294
+ * (a JWT or session token read out of localStorage), and anything this object
295
+ * carried would land in the caller's transcript, which is the exact leak the
296
+ * file sink is here to prevent. `type` is the JS typeof of the value ("null"
297
+ * for null), which describes the value without disclosing any of it.
298
+ */
299
+ export interface EvaluateScriptSaveResult {
300
+ path: string;
301
+ bytes: number;
302
+ type: string;
303
+ target: { id: string; url: string; title: string };
304
+ }
305
+
306
+ /**
307
+ * Serialize an evaluated value for the file sink. `undefined` (an expression
308
+ * with no result) is written as JSON null rather than left unwritten, so the
309
+ * file always exists and always parses.
310
+ */
311
+ function serializeForSink(value: unknown): string {
312
+ const json = JSON.stringify(value === undefined ? null : value, null, 2);
313
+ return json ?? "null";
314
+ }
315
+
316
+ /**
317
+ * THE file sink, shared by every tool that takes a `savePath`: serialize the
318
+ * value as JSON, write it, and report only where it went and how big it was.
319
+ * It returns no form of the value on purpose, so a caller of this helper
320
+ * cannot accidentally leak one back into a response.
321
+ *
322
+ * Path resolution matches take_heapsnapshot: an absolute path is used as-is, a
323
+ * relative one resolves under the artifact dir, and missing parent directories
324
+ * are created.
325
+ */
326
+ async function writeJsonSink(savePath: string, value: unknown): Promise<{ path: string; bytes: number }> {
327
+ const path = savePath.startsWith("/") ? savePath : join(ARTIFACT_DIR, savePath);
328
+ await mkdir(dirname(path), { recursive: true });
329
+ const json = serializeForSink(value);
330
+ await writeFile(path, json, "utf8");
331
+ return { path, bytes: Buffer.byteLength(json, "utf8") };
332
+ }
333
+
334
+ /** True when a savePath argument actually asks for the sink. An empty string is
335
+ * treated as absent, so the caller gets the value inline. */
336
+ function sinkRequested(savePath?: string): savePath is string {
337
+ return savePath !== undefined && savePath !== "";
338
+ }
339
+
235
340
  export async function evaluateScript(
236
341
  driver: BrowserDriver,
237
- args: { target?: TargetSelector; expression: string; awaitPromise?: boolean; args?: unknown[] },
342
+ args: { target?: TargetSelector; expression: string; awaitPromise?: boolean; args?: unknown[]; savePath?: string },
238
343
  ): Promise<unknown> {
239
344
  if (typeof args.expression !== "string" || args.expression.length === 0) {
240
345
  throw new SharedToolError("evaluateScript: 'expression' must be a non-empty string");
241
346
  }
242
- return withPage(driver, args.target, (page) => page.evaluate(args.expression, { args: args.args, awaitPromise: args.awaitPromise ?? true }));
347
+ return withPage(driver, args.target, async (page) => {
348
+ const value = await page.evaluate(args.expression, { args: args.args, awaitPromise: args.awaitPromise ?? true });
349
+ // No savePath: byte-identical to the pre-sink behavior, the value itself.
350
+ // A thrown page-side exception never reaches here, so it still surfaces as
351
+ // an error rather than being written into the file.
352
+ if (!sinkRequested(args.savePath)) return value;
353
+
354
+ const { path, bytes } = await writeJsonSink(args.savePath, value);
355
+ const result: EvaluateScriptSaveResult = {
356
+ path,
357
+ bytes,
358
+ type: value === null ? "null" : typeof value,
359
+ target: target3(page.info),
360
+ };
361
+ return result;
362
+ });
363
+ }
364
+
365
+ /* -------------------------------- cookies (1) -------------------------------- */
366
+
367
+ /**
368
+ * The `savePath` result shape for list_cookies. Same rule as
369
+ * EvaluateScriptSaveResult: NO cookie value in any form, not even a prefix. A
370
+ * session cookie IS the credential, so a preview of one is a leaked one.
371
+ * `count` is how many cookies were written, which tells a caller the read
372
+ * worked without disclosing anything about what it read.
373
+ */
374
+ export interface ListCookiesSaveResult {
375
+ path: string;
376
+ bytes: number;
377
+ count: number;
378
+ target: { id: string; url: string; title: string };
379
+ }
380
+
381
+ export interface ListCookiesResult {
382
+ cookies: BrowserCookie[];
383
+ count: number;
384
+ target: { id: string; url: string; title: string };
385
+ }
386
+
387
+ /**
388
+ * Cookie domain matching for the `domain` filter, deliberately small.
389
+ *
390
+ * A cookie's own domain carries a leading dot when it was set for subdomains
391
+ * (".example.test") and none when it was host-only ("example.test"), and a
392
+ * caller who types "example.test" means both. So the comparison strips a
393
+ * leading dot from each side and then accepts an exact match or a subdomain of
394
+ * the filter ("app.example.test" matches "example.test"). That is the whole
395
+ * rule: no wildcards, no patterns, no query language.
396
+ */
397
+ function cookieDomainMatches(cookieDomain: string, filter: string): boolean {
398
+ const bare = (d: string) => (d.startsWith(".") ? d.slice(1) : d).toLowerCase();
399
+ const c = bare(cookieDomain);
400
+ const f = bare(filter);
401
+ return c === f || c.endsWith(`.${f}`);
402
+ }
403
+
404
+ /** Apply the optional name/domain filters. Exported for the unit tests, which
405
+ * can then check the matching rule without standing up a browser. */
406
+ export function filterCookies(cookies: readonly BrowserCookie[], filter: { domain?: string; name?: string }): BrowserCookie[] {
407
+ return cookies.filter((c) => {
408
+ if (filter.name !== undefined && filter.name !== "" && c.name !== filter.name) return false;
409
+ if (filter.domain !== undefined && filter.domain !== "" && !cookieDomainMatches(c.domain, filter.domain)) return false;
410
+ return true;
411
+ });
412
+ }
413
+
414
+ /**
415
+ * Read the cookies of the target page, httpOnly ones included.
416
+ *
417
+ * This is the one read that a page script cannot do: document.cookie omits
418
+ * every httpOnly cookie by design, which is precisely the set a session
419
+ * credential lives in. Both drivers answer over the protocol's own cookie
420
+ * store, so the flags come from the browser rather than being inferred.
421
+ *
422
+ * With `savePath` set the cookie array is written to that file as JSON and the
423
+ * response carries only {path, bytes, count, target}: no value, no preview, no
424
+ * truncation. Without it, the cookies are returned inline.
425
+ */
426
+ export async function listCookies(
427
+ driver: BrowserDriver,
428
+ args: { target?: TargetSelector; domain?: string; name?: string; savePath?: string } = {},
429
+ ): Promise<ListCookiesResult | ListCookiesSaveResult> {
430
+ return withPage(driver, args.target, async (page) => {
431
+ const all = await page.getCookies();
432
+ const cookies = filterCookies(all, { domain: args.domain, name: args.name });
433
+ if (!sinkRequested(args.savePath)) {
434
+ return { cookies, count: cookies.length, target: target3(page.info) };
435
+ }
436
+ const { path, bytes } = await writeJsonSink(args.savePath, cookies);
437
+ return { path, bytes, count: cookies.length, target: target3(page.info) };
438
+ });
439
+ }
440
+
441
+ export interface SetCookieResult {
442
+ set: true;
443
+ target: { id: string; url: string; title: string };
444
+ }
445
+
446
+ export interface DeleteCookiesResult {
447
+ deleted: true;
448
+ target: { id: string; url: string; title: string };
449
+ }
450
+
451
+ /**
452
+ * THE site constraint both write tools share: a cookie has to be attributed to
453
+ * a site, and `url` or `domain` is how a caller says which.
454
+ *
455
+ * Checked here, above the drivers, so the refusal is ONE message on both
456
+ * backends rather than a CDP protocol error on one and a Firefox no-op on the
457
+ * other. It throws rather than defaulting to the current page's origin: a
458
+ * guessed domain writes a real cookie somewhere the caller did not name, and a
459
+ * cookie written to the wrong site is worse than a call that failed loudly.
460
+ *
461
+ * Exported for the unit tests, which pin the message without a browser.
462
+ */
463
+ export function assertCookieSite(
464
+ args: { url?: string; domain?: string },
465
+ toolName: string,
466
+ ): void {
467
+ const hasUrl = args.url !== undefined && args.url !== "";
468
+ const hasDomain = args.domain !== undefined && args.domain !== "";
469
+ if (!hasUrl && !hasDomain) {
470
+ throw new Error(`${toolName} requires either 'url' or 'domain': a cookie has to be attributed to a site, and neither was given.`);
471
+ }
472
+ }
473
+
474
+ /** The shared 'name' check. A write tool with no name has nothing to write and
475
+ * a delete tool with no name would match every cookie, so an empty one is
476
+ * refused rather than treated as absent. */
477
+ function assertCookieName(name: string | undefined, toolName: string): asserts name is string {
478
+ if (name === undefined || name === "") {
479
+ throw new Error(`${toolName} requires a non-empty 'name'.`);
480
+ }
481
+ }
482
+
483
+ /**
484
+ * Write one cookie into the target page's cookie store.
485
+ *
486
+ * The response is deliberately tiny: `{set: true, target}`. It does NOT echo
487
+ * the value back, because the value is frequently the credential and a caller
488
+ * who just supplied it does not need it repeated into their transcript. The
489
+ * `set: true` is earned rather than assumed: the CDP driver throws on Chrome's
490
+ * `{success:false}` refusal and the BiDi driver throws when it cannot derive
491
+ * the domain BiDi requires, so reaching this line means a backend confirmed
492
+ * the write.
493
+ */
494
+ export async function setCookie(
495
+ driver: BrowserDriver,
496
+ args: {
497
+ target?: TargetSelector; name: string; value: string; url?: string; domain?: string;
498
+ path?: string; expires?: number; httpOnly?: boolean; secure?: boolean;
499
+ sameSite?: "strict" | "lax" | "none" | "default";
500
+ },
501
+ ): Promise<SetCookieResult> {
502
+ assertCookieName(args.name, "set_cookie");
503
+ if (typeof args.value !== "string") throw new Error("set_cookie requires a string 'value'.");
504
+ assertCookieSite(args, "set_cookie");
505
+ return withPage(driver, args.target, async (page) => {
506
+ await page.setCookie({
507
+ name: args.name,
508
+ value: args.value,
509
+ ...(args.url !== undefined ? { url: args.url } : {}),
510
+ ...(args.domain !== undefined ? { domain: args.domain } : {}),
511
+ ...(args.path !== undefined ? { path: args.path } : {}),
512
+ ...(args.expires !== undefined ? { expires: args.expires } : {}),
513
+ ...(args.httpOnly !== undefined ? { httpOnly: args.httpOnly } : {}),
514
+ ...(args.secure !== undefined ? { secure: args.secure } : {}),
515
+ ...(args.sameSite !== undefined ? { sameSite: args.sameSite } : {}),
516
+ });
517
+ return { set: true as const, target: target3(page.info) };
518
+ });
519
+ }
520
+
521
+ /**
522
+ * Remove the named cookie from the target page's cookie store.
523
+ *
524
+ * `{deleted: true, target}` and NO count, on purpose. Neither protocol reports
525
+ * how many cookies it removed, so any number here would be invented; a caller
526
+ * who needs one reads list_cookies before and after. `deleted: true` means the
527
+ * backend accepted and performed the deletion, not that a matching cookie
528
+ * existed: deleting an absent cookie is a success on both backends.
529
+ */
530
+ export async function deleteCookies(
531
+ driver: BrowserDriver,
532
+ args: { target?: TargetSelector; name: string; url?: string; domain?: string; path?: string },
533
+ ): Promise<DeleteCookiesResult> {
534
+ assertCookieName(args.name, "delete_cookies");
535
+ assertCookieSite(args, "delete_cookies");
536
+ return withPage(driver, args.target, async (page) => {
537
+ await page.deleteCookies({
538
+ name: args.name,
539
+ ...(args.url !== undefined ? { url: args.url } : {}),
540
+ ...(args.domain !== undefined ? { domain: args.domain } : {}),
541
+ ...(args.path !== undefined ? { path: args.path } : {}),
542
+ });
543
+ return { deleted: true as const, target: target3(page.info) };
544
+ });
243
545
  }
244
546
 
245
547
  /* -------------------------------- snapshot (1) -------------------------------- */
@@ -440,7 +742,7 @@ export async function handleDialog(
440
742
 
441
743
  /* ------------------------------------- registry ------------------------------------- */
442
744
 
443
- /** The 20 tools this file unifies, importable by both src/index.ts (Chrome) and
745
+ /** The 23 tools this file unifies, importable by both src/index.ts (Chrome) and
444
746
  * src/firefox-tools.ts (Firefox). Each function is (driver, args) => Promise<result>. */
445
747
  export const SHARED_TOOLS = {
446
748
  list_pages: listPages,
@@ -450,6 +752,9 @@ export const SHARED_TOOLS = {
450
752
  navigate_page: navigatePage,
451
753
  wait_for: waitForText,
452
754
  evaluate_script: evaluateScript,
755
+ list_cookies: listCookies,
756
+ set_cookie: setCookie,
757
+ delete_cookies: deleteCookies,
453
758
  take_snapshot: takeSnapshot,
454
759
  click,
455
760
  hover,