cdp-toolkit 3.2.0 → 3.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.
@@ -590,7 +590,7 @@ export type LogEntry = LogGenericLogEntry | LogConsoleLogEntry | LogJavascriptLo
590
590
  // --- emulation module ----------------------------------------------------
591
591
 
592
592
  export type EmulationForcedColorsModeTheme = "light" | "dark";
593
- /** Firefox 153: not implemented. */
593
+ /** Firefox 160: not implemented. */
594
594
  export interface EmulationSetForcedColorsModeThemeOverrideParameters {
595
595
  theme: EmulationForcedColorsModeTheme | null; contexts?: BrowsingContextId[]; userContexts?: BrowserUserContext[];
596
596
  }
@@ -614,9 +614,8 @@ export interface EmulationSetLocaleOverrideParameters { locale: string | null; c
614
614
  export type EmulationSetLocaleOverrideResult = BidiEmptyResult;
615
615
 
616
616
  export interface EmulationMediaFeature { name: string; value: string }
617
- /** Firefox 153: not implemented. */
618
617
  export interface EmulationSetMediaFeaturesOverrideParameters {
619
- features: EmulationMediaFeature[] | null; contexts?: BrowsingContextId[]; userContexts?: BrowserUserContext[];
618
+ features: Record<string, string> | null; /* feature name -> value; null resets */ contexts?: BrowsingContextId[]; userContexts?: BrowserUserContext[];
620
619
  }
621
620
  export type EmulationSetMediaFeaturesOverrideResult = BidiEmptyResult;
622
621
 
@@ -649,7 +648,7 @@ export type EmulationSetUserAgentOverrideResult = BidiEmptyResult;
649
648
  export interface EmulationSetViewportMetaOverrideParameters { viewportMeta: true | null; contexts?: BrowsingContextId[]; userContexts?: BrowserUserContext[] }
650
649
  export type EmulationSetViewportMetaOverrideResult = BidiEmptyResult;
651
650
 
652
- /** Firefox 153: not implemented. */
651
+ /** Firefox 160: not implemented. */
653
652
  export interface EmulationSetScriptingEnabledParameters { enabled: false | null; contexts?: BrowsingContextId[]; userContexts?: BrowserUserContext[] }
654
653
  export type EmulationSetScriptingEnabledResult = BidiEmptyResult;
655
654
 
@@ -662,7 +661,7 @@ export type EmulationSetScrollbarTypeOverrideResult = BidiEmptyResult;
662
661
  export interface EmulationSetTimezoneOverrideParameters { timezone: string | null; contexts?: BrowsingContextId[]; userContexts?: BrowserUserContext[] }
663
662
  export type EmulationSetTimezoneOverrideResult = BidiEmptyResult;
664
663
 
665
- /** Firefox 153: not implemented. */
664
+ /** Firefox 160: not implemented. */
666
665
  export interface EmulationSetTouchOverrideParameters {
667
666
  maxTouchPoints: BidiJsUint | null /* .ge 1 */; contexts?: BrowsingContextId[]; userContexts?: BrowserUserContext[];
668
667
  }
@@ -725,25 +724,44 @@ export interface BidiCommands {
725
724
  "storage.getCookies": { params: StorageGetCookiesParameters; result: StorageGetCookiesResult };
726
725
  "storage.setCookie": { params: StorageSetCookieParameters; result: StorageSetCookieResult };
727
726
 
728
- /** Firefox 153: not implemented. */
727
+ /** Firefox 160: not implemented. */
729
728
  "emulation.setForcedColorsModeThemeOverride": { params: EmulationSetForcedColorsModeThemeOverrideParameters; result: EmulationSetForcedColorsModeThemeOverrideResult };
730
729
  "emulation.setGeolocationOverride": { params: EmulationSetGeolocationOverrideParameters; result: EmulationSetGeolocationOverrideResult };
731
730
  "emulation.setLocaleOverride": { params: EmulationSetLocaleOverrideParameters; result: EmulationSetLocaleOverrideResult };
732
- /** Firefox 153: not implemented. */
733
731
  "emulation.setMediaFeaturesOverride": { params: EmulationSetMediaFeaturesOverrideParameters; result: EmulationSetMediaFeaturesOverrideResult };
734
732
  "emulation.setNetworkConditions": { params: EmulationSetNetworkConditionsParameters; result: EmulationSetNetworkConditionsResult };
735
733
  "emulation.setScreenOrientationOverride": { params: EmulationSetScreenOrientationOverrideParameters; result: EmulationSetScreenOrientationOverrideResult };
736
734
  "emulation.setScreenSettingsOverride": { params: EmulationSetScreenSettingsOverrideParameters; result: EmulationSetScreenSettingsOverrideResult };
737
- /** Firefox 153: not implemented. */
735
+ /** Firefox 160: not implemented. */
738
736
  "emulation.setScriptingEnabled": { params: EmulationSetScriptingEnabledParameters; result: EmulationSetScriptingEnabledResult };
739
737
  /** Firefox 153: not implemented. */
740
738
  "emulation.setScrollbarTypeOverride": { params: EmulationSetScrollbarTypeOverrideParameters; result: EmulationSetScrollbarTypeOverrideResult };
741
739
  "emulation.setTimezoneOverride": { params: EmulationSetTimezoneOverrideParameters; result: EmulationSetTimezoneOverrideResult };
742
- /** Firefox 153: not implemented. */
740
+ /** Firefox 160: not implemented. */
743
741
  "emulation.setTouchOverride": { params: EmulationSetTouchOverrideParameters; result: EmulationSetTouchOverrideResult };
744
742
  "emulation.setUserAgentOverride": { params: EmulationSetUserAgentOverrideParameters; result: EmulationSetUserAgentOverrideResult };
745
743
  /** Firefox 153: not implemented. */
746
744
  "emulation.setViewportMetaOverride": { params: EmulationSetViewportMetaOverrideParameters; result: EmulationSetViewportMetaOverrideResult };
745
+
746
+ /** Measured on Firefox 160.0 (not present on 153): `allowed` + destinationFolder redirects every
747
+ * download; `null` restores the browser's own behavior. See ../bidi-browser-tools.ts. */
748
+ "browser.setDownloadBehavior": { params: BrowserSetDownloadBehaviorParameters; result: BidiEmptyResult };
749
+ /** WebDriver BiDi permissions extension module, measured on Firefox 160.0. */
750
+ "permissions.setPermission": { params: PermissionsSetPermissionParameters; result: BidiEmptyResult };
751
+ }
752
+
753
+ // --- browser.setDownloadBehavior / permissions extension -----------------
754
+ export type BrowserDownloadBehavior =
755
+ | { type: "allowed"; destinationFolder: string }
756
+ | { type: "denied" };
757
+ export interface BrowserSetDownloadBehaviorParameters {
758
+ downloadBehavior: BrowserDownloadBehavior | null; userContexts?: BrowserUserContext[];
759
+ }
760
+ export interface PermissionsPermissionDescriptor { name: string; [extra: string]: unknown }
761
+ export type PermissionsPermissionState = "granted" | "denied" | "prompt";
762
+ export interface PermissionsSetPermissionParameters {
763
+ descriptor: PermissionsPermissionDescriptor; state: PermissionsPermissionState; origin: string;
764
+ embeddedOrigin?: string; userContext?: string;
747
765
  }
748
766
  export type BidiMethod = keyof BidiCommands;
749
767
 
@@ -0,0 +1,366 @@
1
+ /**
2
+ * bidi-browser-tools.ts: Firefox (WebDriver BiDi) implementations of the two BROWSER-scoped tools,
3
+ * `wait_for_download` (capability "browser.downloads") and `grant_permissions` ("browser.permissions").
4
+ * Same argument schema, same validation (imported from the Chrome modules, never re-derived) and the
5
+ * same result shapes as src/tools/downloads.ts and src/tools/permissions.ts. Both need Firefox 160+
6
+ * (BIDI_CAPABILITY_MIN_FIREFOX in ./bidi/driver.ts); an older Firefox gets "unsupported" naming the
7
+ * version before any browser state is touched.
8
+ *
9
+ * HOW THEY REACH THE CONNECTION. Both tools first acquire `driver.page(target)` — that is the
10
+ * Firefox lease choke point (resolveContext) and the source of the `target` field — then do the
11
+ * browser-wide work through BidiBrowserDriver.withBrowserConnection, and register a dispose hook
12
+ * (BidiBrowserDriver.setDisposeHook) for state that must not outlive this process.
13
+ *
14
+ * MEASURED on headless Firefox 160.0 (probes /tmp/ffpar/dlperm/probe.ts, probe3.ts):
15
+ * - browser.setDownloadBehavior {type:"allowed", destinationFolder} redirects every download;
16
+ * `downloadBehavior: null` restores the profile's own behavior (a later download landed in the
17
+ * profile's browser.download.dir, not the capture folder). The override does NOT survive
18
+ * session.end — but in attach mode through the mux (./bidi/mux.ts) a joiner's session.end is
19
+ * answered locally, so the explicit null restore is the only restore there.
20
+ * - downloadWillBegin/downloadEnd fire for EVERY download, armed or not; the user's own downloads
21
+ * included. Only a download whose filepath is inside our staging folder is ever recorded.
22
+ * - Firefox de-duplicates a name collision itself ("one.txt" -> "one(1).txt") and reports the
23
+ * de-duplicated name as suggestedFilename.
24
+ * - permissions.setPermission: granted/denied/prompt are reflected by navigator.permissions.query.
25
+ * A grant SURVIVES session.end and a fresh session.new (it lives in the profile's permission
26
+ * manager), unlike Chrome's, which dies with the granting CDP client.
27
+ * - Firefox's PermissionName enum rejects clipboard-read/clipboard-write, background-sync,
28
+ * local-fonts, idle-detection, accelerometer ("not a valid value for enumeration"), and
29
+ * storage-access is "currently unsupported".
30
+ *
31
+ * ASYMMETRIES vs CHROME (for the README):
32
+ * 1. Downloads: Chrome stays armed for the life of the server once armed. Firefox is armed by
33
+ * every wait_for_download call and DISARMED (downloadBehavior:null) when a collecting call
34
+ * returns or times out, so the user's everyday Firefox goes back to normal downloads. A download
35
+ * started after one collecting call and before the next arm is therefore not captured: on
36
+ * Firefox, arm (arm:true or a pending wait) before EVERY download, not just the first.
37
+ * 2. Downloads: while armed, ANY download in that Firefox (including one the human starts) is
38
+ * redirected into the capture folder and can be the one a wait returns.
39
+ * 3. Downloads: two same-named downloads both uncollected at once get Firefox's own "(1)" suffix
40
+ * in suggestedFilename (Firefox de-dupes inside the staging folder before we see the name);
41
+ * the common case still gets Chrome's "name-1.ext" via nextFreeName.
42
+ * 4. Permissions take W3C descriptors, so Chrome PermissionType names are mapped through
43
+ * FIREFOX_PERMISSION_DESCRIPTORS — a local allowlist, which Chrome's implementation
44
+ * deliberately does not keep. A name with no measured Firefox equivalent is refused
45
+ * ("unsupported", naming it) before anything is granted, never silently skipped.
46
+ * 5. Permissions persist in the Firefox profile. To keep Chrome's "the grant lives as long as the
47
+ * server process" contract (and leave the user's Firefox as it was), every grant is undone
48
+ * when the session is disposed (server shutdown; end of a CLI command) and by reset:true. The
49
+ * undo restores the state the page reported BEFORE the first grant when the grant origin is the
50
+ * target tab's own origin; for any other origin the prior state cannot be read, and it is
51
+ * restored to "prompt". A process killed with SIGKILL leaves its grants in the profile.
52
+ * 6. Per CDP's docs (not measured here) Browser.grantPermissions also rejects the permissions it
53
+ * was NOT given for that origin; Firefox's setPermission touches only the named ones, and this
54
+ * implementation deliberately does not deny everything else in the user's real profile.
55
+ * 7. All of the above was measured headless. Download-panel / dialog behavior of a headed
56
+ * everyday Firefox under "allowed" was not observed.
57
+ */
58
+ import { mkdir, readdir, realpath, rename, stat } from "node:fs/promises";
59
+ import { basename, dirname, join, resolve } from "node:path";
60
+ import type { BidiConnection } from "./bidi/client.ts";
61
+ import { requireFirefox } from "./bidi/driver.ts";
62
+ import type { PermissionsPermissionDescriptor, PermissionsPermissionState } from "./bidi/protocol.ts";
63
+ import type { BrowserDriver, DriverError, PageDriver } from "./driver.ts";
64
+ import { DOWNLOADS_DIR, DOWNLOAD_BUFFER_LIMIT } from "./tools/browser-session.ts";
65
+ import {
66
+ nextFreeName, safeFilename, validateWaitForDownloadArgs,
67
+ type ArmDownloadResult, type WaitForDownloadArgs, type WaitForDownloadResult,
68
+ } from "./tools/downloads.ts";
69
+ import { originOf, validateGrantPermissionsArgs, type GrantPermissionsArgs, type GrantPermissionsResult } from "./tools/permissions.ts";
70
+
71
+ function unsupported(message: string): DriverError {
72
+ return Object.assign(new Error(message), { code: "unsupported" as const }) as DriverError;
73
+ }
74
+
75
+ /** The slice of BidiConnection these tools use; a structural type so tests can pass a stub. */
76
+ export type BrowserConn = Pick<BidiConnection, "send" | "on" | "capabilities">;
77
+
78
+ /** What BidiBrowserDriver adds for browser-scoped work (see its withBrowserConnection). */
79
+ interface BrowserScope {
80
+ withBrowserConnection<T>(fn: (conn: BrowserConn) => Promise<T>): Promise<T>;
81
+ setDisposeHook(key: string, hook: ((conn: BrowserConn) => Promise<void>) | undefined): void;
82
+ }
83
+
84
+ function scopeOf(driver: BrowserDriver, tool: string): BrowserScope {
85
+ const d = driver as Partial<BrowserScope>;
86
+ if (typeof d.withBrowserConnection !== "function" || typeof d.setDisposeHook !== "function") {
87
+ throw unsupported(`${tool}: this driver has no browser-scoped connection (the Firefox BiDi driver does; Chrome uses src/tools/).`);
88
+ }
89
+ return d as BrowserScope;
90
+ }
91
+
92
+ async function targetOf(driver: BrowserDriver, target: WaitForDownloadArgs["target"]): Promise<{ id: string; url: string; title: string }> {
93
+ const page = await driver.page(target);
94
+ try {
95
+ return { id: page.info.id, url: page.info.url, title: page.info.title };
96
+ } finally {
97
+ await page.release();
98
+ }
99
+ }
100
+
101
+ /* ===================================== downloads ===================================== */
102
+
103
+ /** Firefox writes here; wait_for_download then renames each file into DOWNLOADS_DIR under the
104
+ * page's own name, exactly as Chrome's guid files are renamed. A SIBLING of DOWNLOADS_DIR, never
105
+ * inside it, so it cannot count as a filename collision. */
106
+ export const FIREFOX_DOWNLOAD_STAGING_DIR = join(dirname(DOWNLOADS_DIR), "downloads-firefox-staging");
107
+
108
+ interface FfDownload {
109
+ id: string;
110
+ url?: string;
111
+ suggestedFilename?: string;
112
+ /** Where the finished file sits now (moved off Firefox's own name into an id-named file). */
113
+ filePath?: string;
114
+ state: "inProgress" | "completed";
115
+ consumed: boolean;
116
+ }
117
+
118
+ interface DownloadState {
119
+ downloads: FfDownload[];
120
+ /** In-progress downloads by id, until downloadEnd decides whether they are ours. */
121
+ begun: Map<string, FfDownload>;
122
+ waiters: Array<(r: FfDownload) => void>;
123
+ /** Accepted spellings of the staging folder (macOS /tmp -> /private/tmp). */
124
+ stagingDirs: Set<string>;
125
+ }
126
+
127
+ const downloadStates = new WeakMap<object, DownloadState>();
128
+
129
+ /** willBegin/downloadEnd correlate on `download` per the spec; Firefox 160 also populates
130
+ * `navigation` with the same id, so either is accepted. */
131
+ function downloadId(p: { download?: unknown; navigation?: unknown }): string | undefined {
132
+ const v = p.download ?? p.navigation;
133
+ return typeof v === "string" && v.length > 0 ? v : undefined;
134
+ }
135
+
136
+ function deliver(s: DownloadState, r: FfDownload): void {
137
+ r.state = "completed";
138
+ s.downloads.push(r);
139
+ while (s.downloads.length > DOWNLOAD_BUFFER_LIMIT) {
140
+ const i = s.downloads.findIndex((d) => d.consumed);
141
+ s.downloads.splice(i >= 0 ? i : 0, 1);
142
+ }
143
+ const waiter = s.waiters.shift();
144
+ if (waiter) {
145
+ r.consumed = true;
146
+ waiter(r);
147
+ }
148
+ }
149
+
150
+ function downloadStateFor(conn: BrowserConn): DownloadState {
151
+ let s = downloadStates.get(conn);
152
+ if (s) return s;
153
+ const state: DownloadState = { downloads: [], begun: new Map(), waiters: [], stagingDirs: new Set([resolve(FIREFOX_DOWNLOAD_STAGING_DIR)]) };
154
+ downloadStates.set(conn, state);
155
+ conn.on("browsingContext.downloadWillBegin", (p) => {
156
+ const id = downloadId(p);
157
+ if (!id) return;
158
+ state.begun.set(id, { id, url: p.url, suggestedFilename: p.suggestedFilename, state: "inProgress", consumed: false });
159
+ // Bound the map: a download that never reports an end must not grow it forever.
160
+ if (state.begun.size > DOWNLOAD_BUFFER_LIMIT) state.begun.delete(state.begun.keys().next().value as string);
161
+ });
162
+ conn.on("browsingContext.downloadEnd", (p) => {
163
+ const id = downloadId(p);
164
+ if (!id) return;
165
+ const rec = state.begun.get(id) ?? { id, state: "inProgress" as const, consumed: false };
166
+ state.begun.delete(id);
167
+ if (p.status !== "complete" || !p.filepath) return; // canceled, or nothing on disk: never returned
168
+ // Only OUR captures: an unarmed download (the human's own, into their normal folder) is left alone.
169
+ if (!state.stagingDirs.has(resolve(dirname(p.filepath)))) return;
170
+ rec.url ??= p.url;
171
+ const held = join(dirname(p.filepath), `${id.replace(/[^A-Za-z0-9-]/g, "_")}.download`);
172
+ // Move off Firefox's own name at once, so the next same-named download is not de-duplicated
173
+ // by Firefox into "name(1).ext" while this one waits to be collected.
174
+ rename(p.filepath, held).then(
175
+ () => { rec.filePath = held; },
176
+ () => { rec.filePath = p.filepath ?? undefined; },
177
+ ).finally(() => deliver(state, rec));
178
+ });
179
+ return state;
180
+ }
181
+
182
+ async function armFirefoxDownloads(conn: BrowserConn, s: DownloadState, scope: BrowserScope): Promise<void> {
183
+ await mkdir(FIREFOX_DOWNLOAD_STAGING_DIR, { recursive: true });
184
+ await mkdir(DOWNLOADS_DIR, { recursive: true });
185
+ s.stagingDirs.add(resolve(await realpath(FIREFOX_DOWNLOAD_STAGING_DIR)));
186
+ // The restore is registered BEFORE the override, so there is no window in which the browser is
187
+ // redirected with nothing scheduled to put it back.
188
+ scope.setDisposeHook("browser.downloads", async (c) => { await c.send("browser.setDownloadBehavior", { downloadBehavior: null }); });
189
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: { type: "allowed", destinationFolder: FIREFOX_DOWNLOAD_STAGING_DIR } });
190
+ }
191
+
192
+ async function disarmFirefoxDownloads(conn: BrowserConn, scope: BrowserScope): Promise<void> {
193
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: null });
194
+ scope.setDisposeHook("browser.downloads", undefined);
195
+ }
196
+
197
+ function nextFirefoxDownload(s: DownloadState, timeoutMs: number): Promise<FfDownload> {
198
+ const buffered = s.downloads.find((d) => !d.consumed);
199
+ if (buffered) {
200
+ buffered.consumed = true;
201
+ return Promise.resolve(buffered);
202
+ }
203
+ return new Promise<FfDownload>((resolvePromise, reject) => {
204
+ const waiter = (r: FfDownload): void => {
205
+ clearTimeout(timer);
206
+ resolvePromise(r);
207
+ };
208
+ const timer = setTimeout(() => {
209
+ const i = s.waiters.indexOf(waiter);
210
+ if (i >= 0) s.waiters.splice(i, 1);
211
+ reject(new Error(
212
+ `wait_for_download: no download completed within ${timeoutMs}ms. On Firefox, downloads are captured only while a wait_for_download call is armed: arm (arm:true) BEFORE the triggering click, and again before every later download, because each collecting call restores Firefox's normal download behavior when it returns.`,
213
+ ));
214
+ }, timeoutMs);
215
+ s.waiters.push(waiter);
216
+ });
217
+ }
218
+
219
+ /** Firefox `wait_for_download`. Same args, validation and result shapes as src/tools/downloads.ts. */
220
+ export async function waitForDownloadFirefox(driver: BrowserDriver, args: WaitForDownloadArgs = {}): Promise<WaitForDownloadResult | ArmDownloadResult> {
221
+ validateWaitForDownloadArgs(args);
222
+ const scope = scopeOf(driver, "wait_for_download");
223
+ const target = await targetOf(driver, args.target); // the lease gate, before any browser state is touched
224
+ return scope.withBrowserConnection(async (conn) => {
225
+ requireFirefox(conn, "browser.downloads");
226
+ const s = downloadStateFor(conn);
227
+ await armFirefoxDownloads(conn, s, scope);
228
+ if (args.arm === true) {
229
+ return { armed: true as const, downloadPath: DOWNLOADS_DIR, pending: s.downloads.filter((d) => !d.consumed).length, target };
230
+ }
231
+ let rec: FfDownload;
232
+ try {
233
+ rec = await nextFirefoxDownload(s, args.timeoutMs ?? 30_000);
234
+ } finally {
235
+ // Put the user's Firefox back to normal downloads — unless another wait is still pending on
236
+ // this connection, which still needs capture armed.
237
+ if (s.waiters.length === 0) await disarmFirefoxDownloads(conn, scope).catch(() => undefined);
238
+ }
239
+ if (!rec.filePath) {
240
+ throw new Error(`wait_for_download: download ${rec.id} completed without a file path (nothing to return)`);
241
+ }
242
+ const suggestedFilename = safeFilename(rec.suggestedFilename);
243
+ const taken = new Set(await readdir(DOWNLOADS_DIR).catch(() => [] as string[]));
244
+ taken.delete(basename(rec.filePath));
245
+ const finalName = nextFreeName(suggestedFilename, taken);
246
+ const path = join(DOWNLOADS_DIR, finalName);
247
+ await rename(rec.filePath, path);
248
+ const bytes = (await stat(path)).size;
249
+ return { path, suggestedFilename, bytes, ...(rec.url ? { url: rec.url } : {}), target };
250
+ });
251
+ }
252
+
253
+ /* ==================================== permissions ==================================== */
254
+
255
+ /**
256
+ * Chrome PermissionType name -> the W3C PermissionDescriptor Firefox 160's permissions.setPermission
257
+ * accepts. ONLY pairs measured working (setPermission succeeded AND navigator.permissions.query
258
+ * followed) are listed; everything else is refused by name. Chrome's notifications grant also covers
259
+ * push; on Firefox, granting notifications made a {name:"push"} query report "granted" too (measured).
260
+ */
261
+ export const FIREFOX_PERMISSION_DESCRIPTORS: Readonly<Record<string, PermissionsPermissionDescriptor>> = {
262
+ geolocation: { name: "geolocation" },
263
+ notifications: { name: "notifications" },
264
+ audioCapture: { name: "microphone" },
265
+ videoCapture: { name: "camera" },
266
+ durableStorage: { name: "persistent-storage" },
267
+ midi: { name: "midi" },
268
+ midiSysex: { name: "midi", sysex: true },
269
+ wakeLockScreen: { name: "screen-wake-lock" },
270
+ };
271
+
272
+ /** Map every name or throw "unsupported" naming the first unmappable one. Pure, for unit tests. */
273
+ export function mapFirefoxPermissions(names: readonly string[]): PermissionsPermissionDescriptor[] {
274
+ return names.map((n) => {
275
+ const d = Object.hasOwn(FIREFOX_PERMISSION_DESCRIPTORS, n) ? FIREFOX_PERMISSION_DESCRIPTORS[n] : undefined;
276
+ if (!d) {
277
+ throw unsupported(
278
+ `grant_permissions: permission '${n}' is not supported on Firefox (WebDriver BiDi permissions.setPermission has no measured equivalent). Supported on Firefox: ${Object.keys(FIREFOX_PERMISSION_DESCRIPTORS).join(", ")}.`,
279
+ );
280
+ }
281
+ return d;
282
+ });
283
+ }
284
+
285
+ interface TrackedGrant {
286
+ origin: string;
287
+ descriptor: PermissionsPermissionDescriptor;
288
+ /** The state to put back on reset/dispose: what the page reported before our first grant. */
289
+ previous: PermissionsPermissionState;
290
+ }
291
+
292
+ /** Grants this process made, per driver (the dispose hook is per driver endpoint). */
293
+ const trackedGrants = new WeakMap<object, Map<string, TrackedGrant>>();
294
+
295
+ function grantKey(origin: string, d: PermissionsPermissionDescriptor): string {
296
+ return `${origin} ${JSON.stringify(d)}`;
297
+ }
298
+
299
+ async function restoreGrants(conn: BrowserConn, grants: Map<string, TrackedGrant>): Promise<void> {
300
+ const all = [...grants.values()];
301
+ grants.clear();
302
+ for (const g of all) {
303
+ await conn.send("permissions.setPermission", { descriptor: g.descriptor, state: g.previous, origin: g.origin });
304
+ }
305
+ }
306
+
307
+ async function queryState(page: PageDriver, d: PermissionsPermissionDescriptor): Promise<PermissionsPermissionState> {
308
+ try {
309
+ const v = await page.evaluate(
310
+ `navigator.permissions.query(${JSON.stringify(d)}).then((p) => p.state, () => "prompt")`,
311
+ { awaitPromise: true },
312
+ );
313
+ return v === "granted" || v === "denied" ? v : "prompt";
314
+ } catch {
315
+ return "prompt";
316
+ }
317
+ }
318
+
319
+ /** Firefox `grant_permissions`. Same args, validation and result shape as src/tools/permissions.ts. */
320
+ export async function grantPermissionsFirefox(driver: BrowserDriver, args: GrantPermissionsArgs = {}): Promise<GrantPermissionsResult> {
321
+ validateGrantPermissionsArgs(args);
322
+ const reset = args.reset === true;
323
+ const permissions = args.permissions ?? [];
324
+ // Every name is mapped BEFORE anything is granted: one bad name must not leave a half-applied grant.
325
+ const descriptors = mapFirefoxPermissions(permissions);
326
+ const scope = scopeOf(driver, "grant_permissions");
327
+ let grants = trackedGrants.get(driver);
328
+ if (!grants) { grants = new Map(); trackedGrants.set(driver, grants); }
329
+ const tracked = grants;
330
+
331
+ const page = await driver.page(args.target); // the lease gate
332
+ try {
333
+ const target = { id: page.info.id, url: page.info.url, title: page.info.title };
334
+ return await scope.withBrowserConnection(async (conn) => {
335
+ requireFirefox(conn, "browser.permissions");
336
+ if (reset) await restoreGrants(conn, tracked);
337
+ if (permissions.length === 0) return { reset: true as const, target };
338
+
339
+ const origin = args.origin ?? originOf(page.info.url);
340
+ if (!origin) {
341
+ throw new Error(
342
+ `grant_permissions: cannot derive an origin from the target tab's url (${JSON.stringify(page.info.url)}); pass 'origin' explicitly, e.g. origin:"https://example.com"`,
343
+ );
344
+ }
345
+ const pageIsOrigin = originOf(page.info.url) === origin;
346
+ // Restore is registered before the first grant lands (see armFirefoxDownloads for why).
347
+ scope.setDisposeHook("browser.permissions", (c) => restoreGrants(c, tracked));
348
+ for (const d of descriptors) {
349
+ const key = grantKey(origin, d);
350
+ if (!tracked.has(key)) {
351
+ tracked.set(key, { origin, descriptor: d, previous: pageIsOrigin ? await queryState(page, d) : "prompt" });
352
+ }
353
+ await conn.send("permissions.setPermission", { descriptor: d, state: "granted", origin });
354
+ }
355
+ return { granted: [...permissions], origin, ...(reset ? { reset: true as const } : {}), target };
356
+ });
357
+ } finally {
358
+ await page.release();
359
+ }
360
+ }
361
+
362
+ /** Registered in src/firefox-tools.ts. */
363
+ export const BIDI_BROWSER_TOOLS = {
364
+ wait_for_download: waitForDownloadFirefox,
365
+ grant_permissions: grantPermissionsFirefox,
366
+ } satisfies Record<string, (driver: BrowserDriver, args: never) => Promise<unknown>>;
package/src/bidi-tools.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  import type { BrowserDriver, InterceptRule, PageDriver, PageInfo } from "./driver.ts";
11
11
  import { selectRule, buildFulfillParams, effectiveAction } from "./tools/network_mock.ts";
12
12
  import type { TargetSelector } from "./types.ts";
13
+ import { modifierBits, validateDispatchMouseArgs, type DispatchMouseArgs, type DispatchMouseResult } from "./tools/dispatch-mouse.ts";
13
14
  import { isWorkerSelector, WORKER_SELECTOR_UNSUPPORTED_MESSAGE } from "./workers.ts";
14
15
 
15
16
  class BidiToolError extends Error {}
@@ -23,6 +24,20 @@ async function withPage<T>(driver: BrowserDriver, target: TargetSelector | undef
23
24
  }
24
25
  }
25
26
 
27
+ /* ------------------------------ dispatch_mouse (Firefox 160+) ------------------------------ */
28
+ // Same schema, validator and result shape as Chrome's tools/dispatch-mouse.ts (capability "input.raw");
29
+ // the event itself rides PageDriver.dispatchMouse (bidi/driver.ts, one pointer action per call).
30
+ // A page driver without that method (Chrome's, which never reaches this registry) is "unsupported".
31
+ export async function dispatchMouse(driver: BrowserDriver, args: DispatchMouseArgs): Promise<DispatchMouseResult> {
32
+ validateDispatchMouseArgs(args);
33
+ modifierBits(args.modifiers); // validates the closed Alt/Control/Meta/Shift enum, same refusal text as Chrome
34
+ return withPage(driver, args.target, async (page) => {
35
+ if (!page.dispatchMouse) throw new BidiToolError("dispatch_mouse: this page driver has no raw mouse dispatch");
36
+ await page.dispatchMouse({ action: args.action, x: args.x, y: args.y, button: args.button, clickCount: args.clickCount, modifiers: args.modifiers });
37
+ return { dispatched: args.action, x: args.x, y: args.y };
38
+ });
39
+ }
40
+
26
41
  /* ------------------------------ console + network (4) ------------------------------ */
27
42
  // No recorder-style raw-CDP buffer exists for the neutral driver. Buffering rides
28
43
  // PageDriver.on(), scoped to the calling process's lifetime, an identical constraint
@@ -113,7 +128,7 @@ export async function listNetworkRequests(
113
128
 
114
129
  export async function getNetworkRequest(
115
130
  driver: BrowserDriver,
116
- args: { target?: TargetSelector; requestId?: string; url?: string } = {},
131
+ args: { target?: TargetSelector; requestId?: string; url?: string; includeBody?: boolean } = {},
117
132
  ): Promise<Record<string, unknown>> {
118
133
  refuseWorkerSelector(driver, args.target);
119
134
  if (!args.requestId && !args.url) throw new BidiToolError("get_network_request requires requestId or url");
@@ -122,6 +137,17 @@ export async function getNetworkRequest(
122
137
  const found = args.requestId
123
138
  ? buf.find((r) => r.requestId === args.requestId || r.request === args.requestId)
124
139
  : buf.find((r) => typeof r.url === "string" && (r.url as string).includes(args.url as string));
140
+ if (args.includeBody) {
141
+ // Firefox >= 160 retains response bodies per SESSION (network.responseBodyPostHoc, armed when
142
+ // the session is created), so a body is readable for a request made BEFORE this call, by its
143
+ // request id, with no reload. A requestId therefore needs no buffer entry; a url alone does,
144
+ // because the url -> id map is the buffer (filled by list_network_requests{reload:true}).
145
+ // A driver without the capability answers getResponseBody with "unsupported", surfaced as is.
146
+ const id = args.requestId ?? (found ? String(found.requestId ?? found.request ?? "") : "");
147
+ if (!id) throw new BidiToolError("get_network_request includeBody on this backend needs a requestId, or a url already present in the buffer (run list_network_requests with reload first)");
148
+ const { body, base64Encoded } = await page.getResponseBody(id);
149
+ return { ...(found ?? { requestId: id }), body, bodyBase64Encoded: base64Encoded };
150
+ }
125
151
  if (!found) throw new BidiToolError("no matching network request in the current buffer; run list_network_requests first");
126
152
  return found;
127
153
  });
@@ -202,7 +228,7 @@ export async function clearMocks(
202
228
  // `intercept(rules)` surface rather than re-implementing.
203
229
  void selectRule; void buildFulfillParams; void effectiveAction;
204
230
 
205
- /** The 7 Firefox-only tools: no Chrome equivalent is wired through this file (see header). */
231
+ /** The 7 Firefox-only tools, plus dispatch_mouse (a Firefox handler beside Chrome's tools/dispatch-mouse.ts). */
206
232
  export const BIDI_ONLY_TOOLS = {
207
233
  list_console_messages: listConsoleMessages,
208
234
  get_console_message: getConsoleMessage,
@@ -211,4 +237,5 @@ export const BIDI_ONLY_TOOLS = {
211
237
  mock_request: mockRequest,
212
238
  list_mocks: listMocks,
213
239
  clear_mocks: clearMocks,
240
+ dispatch_mouse: dispatchMouse,
214
241
  } satisfies Record<string, (driver: BrowserDriver, args: never) => Promise<unknown>>;