ferridriver 0.3.0

Browser automation in Rust with a Playwright-compatible API. Four pluggable backends: CDP pipe, CDP WebSocket, Playwright WebKit, Firefox BiDi.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! `BiDi` session management: WebSocket connection, session creation, browser launch.
//!
//! The `BiDi` protocol connects directly via WebSocket -- no HTTP session endpoint.
//! Firefox exposes native `BiDi` at `ws://host:port/session`.
//! Chrome can also be used via chromedriver's `BiDi` endpoint.

use std::sync::Arc;

use serde_json::json;
use tracing::{debug, info};

use super::transport::BidiTransport;
use crate::error::{FerriError, Result};

/// A `BiDi` session -- holds the transport and session metadata.
#[derive(Clone)]
pub(crate) struct BidiSession {
  #[allow(dead_code)]
  pub session_id: String,
  pub transport: Arc<BidiTransport>,
  #[allow(dead_code)]
  pub browser_name: String,
  #[allow(dead_code)]
  pub browser_version: String,
}

// Event subscriptions use top-level module names (e.g. "browsingContext", "network")
// rather than individual event names. This matches Puppeteer's approach and avoids
// issues with unsupported event names breaking the session.

impl BidiSession {
  /// Connect to a `BiDi` endpoint directly via WebSocket.
  ///
  /// This is the native `BiDi` approach:
  /// 1. Connect WebSocket to `ws://host:port/session`
  /// 2. Send `session.new` to create a session
  /// 3. Subscribe to all events
  pub async fn connect(ws_url: &str) -> Result<Self> {
    info!("Connecting BiDi session to {ws_url}");

    let transport = Arc::new(BidiTransport::connect(ws_url).await?);

    // Create a new session with proper capabilities.
    // webSocketUrl: true tells Firefox to maintain the BiDi WebSocket across navigations.
    // unhandledPromptBehavior: ignore prevents dialogs from blocking automation.
    let result = transport
      .send_command(
        "session.new",
        json!({
          "capabilities": {
            "alwaysMatch": {
              "acceptInsecureCerts": true,
              "webSocketUrl": true,
              "unhandledPromptBehavior": {
                "default": "ignore"
              }
            }
          }
        }),
      )
      .await?;

    let session_id = result
      .get("sessionId")
      .and_then(|v| v.as_str())
      .unwrap_or("unknown")
      .to_string();
    let capabilities = result.get("capabilities").cloned().unwrap_or(json!({}));
    let browser_name = capabilities
      .get("browserName")
      .and_then(|v| v.as_str())
      .unwrap_or("unknown")
      .to_string();
    let browser_version = capabilities
      .get("browserVersion")
      .and_then(|v| v.as_str())
      .unwrap_or("unknown")
      .to_string();

    debug!("BiDi session created: id={session_id}, browser={browser_name} {browser_version}");

    // Subscribe to top-level event modules (matching Puppeteer's approach).
    // Using module names instead of individual events ensures we receive ALL
    // events under each module and avoids issues with unsupported event names.
    transport
      .send_command(
        "session.subscribe",
        json!({"events": ["browsingContext", "network", "log", "script", "input"]}),
      )
      .await?;

    info!("BiDi session ready: {browser_name} {browser_version}");
    Ok(Self {
      session_id,
      transport,
      browser_name,
      browser_version,
    })
  }

  /// Connect to a `BiDi` endpoint at the given port.
  /// Constructs `ws://127.0.0.1:{port}/session` and connects.
  #[allow(dead_code, reason = "public library API for external consumers")]
  pub async fn connect_to_port(port: u16) -> Result<Self> {
    Self::connect(&format!("ws://127.0.0.1:{port}/session")).await
  }

  /// Launch Firefox and create a `BiDi` session.
  ///
  /// Firefox natively supports `BiDi`: launch with `--remote-debugging-port`,
  /// read the `BiDi` WebSocket URL from stderr, connect directly.
  ///
  /// Returns `(session, child, profile_dir)`. The caller must keep
  /// `profile_dir` alive for the lifetime of the browser — its `Drop` removes
  /// the directory from disk. Firefox is launched with `kill_on_drop(true)`
  /// so the process dies before the dir vanishes.
  pub async fn launch_firefox(
    firefox_path: &str,
    flags: &[String],
    headless: bool,
  ) -> Result<(Self, tokio::process::Child, tempfile::TempDir)> {
    // Prefix the profile dir so test-harness cleanup can `pkill -f`
    // any leaked Firefox processes by their `--profile` arg —
    // mirrors the `ferridriver-pipe-` / `ferridriver-raw-` prefixes
    // used by the CDP launches in `backend::cdp::mod`.
    let profile_dir = tempfile::Builder::new()
      .prefix("ferridriver-firefox-")
      .tempdir()
      .map_err(|e| format!("tempdir: {e}"))?;

    // Pre-create the per-profile downloads dir and pin Firefox to it
    // via `browser.download.dir` + `folderList=2`. Without these prefs
    // Firefox falls back to the user's `~/Downloads` for the
    // `suggestedFilename` calculation it ships in
    // `browsingContext.downloadWillBegin`, so a `Content-Disposition:
    // filename="x.txt"` payload comes back as `x(NN).txt` whenever
    // `~/Downloads/x.txt` already exists on the host (it picks the
    // first free suffix). `browser.setDownloadBehavior`'s
    // `destinationFolder` only redirects the on-disk write, not the
    // suggested-filename deduplication scan.
    let downloads_dir = profile_dir.path().join("downloads");
    std::fs::create_dir_all(&downloads_dir).map_err(|e| format!("downloads dir: {e}"))?;

    // Write automation preferences to user.js in the profile directory.
    // Matches Playwright's firefoxPreferences + Puppeteer's essentials.
    write_firefox_prefs(profile_dir.path(), &downloads_dir).map_err(|e| format!("write prefs: {e}"))?;

    let mut command = tokio::process::Command::new(firefox_path);
    command.arg("--remote-debugging-port").arg("0");
    command.arg("--profile").arg(profile_dir.path());
    command.arg("--no-remote");
    if headless {
      command.arg("--headless");
    }

    // Translate Chrome-style --window-size=W,H to Firefox's --width/--height flags,
    // and forward any other extra flags.
    for flag in flags {
      if let Some(dims) = flag.strip_prefix("--window-size=") {
        if let Some((w, h)) = dims.split_once(',') {
          command.arg("--width").arg(w);
          command.arg("--height").arg(h);
        }
      } else if flag != "--headless" {
        command.arg(flag);
      }
    }

    command.env("MOZ_CRASHREPORTER_DISABLE", "1");
    command
      .stdin(std::process::Stdio::null())
      .stdout(std::process::Stdio::null())
      .stderr(std::process::Stdio::piped())
      .kill_on_drop(true);

    // Put Firefox into its own session+process group so content/plugin
    // subprocesses die together with the parent on teardown.
    // SAFETY: `setsid` is async-signal-safe; the closure performs no
    // allocation and captures nothing. `pre_exec` is unsafe on tokio's
    // `Command` because arbitrary code runs post-fork; our closure is
    // trivially sound.
    #[cfg(unix)]
    #[allow(unsafe_code)]
    unsafe {
      command.pre_exec(crate::backend::process::setsid_pre_exec());
    }

    debug!("Launching Firefox for BiDi: {firefox_path}");
    let mut child = command.spawn().map_err(|e| format!("Firefox launch: {e}"))?;

    // Firefox prints "WebDriver BiDi listening on ws://127.0.0.1:PORT" to stderr
    let ws_url = discover_bidi_ws_url(&mut child).await?;
    debug!("Firefox BiDi endpoint: {ws_url}");

    let session = Self::connect(&ws_url).await?;

    Ok((session, child, profile_dir))
  }

  /// Launch a browser and create a `BiDi` session.
  /// Currently supports Firefox (native `BiDi`). Chrome does not have built-in
  /// `BiDi` support -- use the CDP backend for Chrome instead.
  pub async fn launch(
    browser_path: &str,
    flags: &[String],
    headless: bool,
  ) -> Result<(Self, tokio::process::Child, tempfile::TempDir)> {
    let path_lower = browser_path.to_lowercase();
    if path_lower.contains("firefox") {
      Box::pin(Self::launch_firefox(browser_path, flags, headless)).await
    } else {
      Err(FerriError::unsupported(format!(
        "BiDi backend requires Firefox (found: {browser_path}). \
         Chrome does not have built-in BiDi support -- use the CDP backend for Chrome. \
         Set FIREFOX_PATH or install Firefox."
      )))
    }
  }

  /// End the `BiDi` session gracefully.
  #[allow(dead_code)]
  pub async fn end(&self) -> Result<()> {
    let _ = self.transport.send_command("session.end", json!({})).await;
    Ok(())
  }
}

/// Read Firefox stderr to find the `BiDi` WebSocket URL.
/// Firefox prints: "`WebDriver` `BiDi` listening on ws://127.0.0.1:PORT"
async fn discover_bidi_ws_url(child: &mut tokio::process::Child) -> Result<String> {
  use tokio::io::AsyncBufReadExt;

  let stderr = child
    .stderr
    .take()
    .ok_or_else(|| FerriError::backend("Firefox: no stderr handle"))?;
  let mut reader = tokio::io::BufReader::new(stderr);
  let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(15);

  let mut line = String::new();
  loop {
    if tokio::time::Instant::now() >= deadline {
      return Err(FerriError::timeout(
        "waiting for Firefox BiDi WebSocket URL in stderr",
        15_000,
      ));
    }

    line.clear();
    let read_result = tokio::time::timeout(std::time::Duration::from_secs(1), reader.read_line(&mut line)).await;

    match read_result {
      Ok(Ok(0)) => {
        // EOF
        if let Ok(Some(status)) = child.try_wait() {
          return Err(FerriError::Backend(format!(
            "Firefox exited during startup with status: {status}"
          )));
        }
      },
      Ok(Ok(_)) => {
        // Look for the BiDi WebSocket URL
        // Firefox prints: "WebDriver BiDi listening on ws://127.0.0.1:PORT"
        // The actual BiDi endpoint is at ws://host:port/session
        if let Some(pos) = line.find("ws://") {
          let mut ws_url = line[pos..].trim().to_string();
          // Ensure the URL ends with /session (Firefox's BiDi endpoint)
          if !ws_url.ends_with("/session") {
            if ws_url.ends_with('/') {
              ws_url.push_str("session");
            } else {
              ws_url.push_str("/session");
            }
          }
          return Ok(ws_url);
        }
      },
      Ok(Err(e)) => return Err(FerriError::Backend(format!("Firefox stderr read error: {e}"))),
      Err(_) => {
        // Timeout on this read, check if process died
        if let Ok(Some(status)) = child.try_wait() {
          return Err(FerriError::Backend(format!(
            "Firefox exited during startup with status: {status}"
          )));
        }
      },
    }
  }
}

/// Write Firefox automation preferences to `user.js` in the given profile directory.
/// Based on Playwright's `playwright.cfg` and Puppeteer's Firefox defaults.
fn write_firefox_prefs(profile_dir: &std::path::Path, downloads_dir: &std::path::Path) -> std::io::Result<()> {
  use std::io::Write;

  let prefs_path = profile_dir.join("user.js");
  let mut f = std::fs::File::create(prefs_path)?;

  write_firefox_download_prefs(&mut f, downloads_dir)?;

  // Each line: user_pref("key", value);
  // Organised by category matching Playwright's structure.
  write!(
    f,
    r#"// ── Process model ──────────────────────────────────────────────────────
// Force single content process for reliable mouse event dispatch (Playwright + Puppeteer).
user_pref("fission.webContentIsolationStrategy", 0);
user_pref("fission.bfcacheInParent", false);
user_pref("fission.autostart", false);
user_pref("dom.ipc.processCount", 1);
user_pref("dom.ipc.processPrelaunchEnabled", false);

// ── Input events ──────────────────────────────────────────────────────
// Remove minimum tick/time restrictions for synthetic input events.
user_pref("dom.input_events.security.minNumTicks", 0);
user_pref("dom.input_events.security.minTimeElapsedInMS", 0);

// ── Startup & UI ──────────────────────────────────────────────────────
user_pref("browser.startup.homepage", "about:blank");
user_pref("browser.startup.page", 0);
user_pref("browser.newtabpage.enabled", false);
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.tabs.warnOnClose", false);
user_pref("browser.tabs.warnOnCloseOtherTabs", false);
user_pref("browser.tabs.warnOnOpen", false);
user_pref("browser.warnOnQuit", false);
user_pref("browser.sessionstore.resume_from_crash", false);
user_pref("browser.uitour.enabled", false);
user_pref("toolkit.cosmeticAnimations.enabled", false);
user_pref("browser.rights.3.shown", true);

// ── Updates & telemetry (all disabled) ────────────────────────────────
user_pref("app.update.enabled", false);
user_pref("app.update.auto", false);
user_pref("app.update.mode", 0);
user_pref("app.update.service.enabled", false);
user_pref("app.update.checkInstallTime", false);
user_pref("app.update.disabledForTesting", true);
user_pref("app.normandy.enabled", false);
user_pref("app.normandy.api_url", "");
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("toolkit.telemetry.enabled", false);
user_pref("toolkit.telemetry.server", "");
user_pref("browser.translations.enable", false);

// ── Extensions ────────────────────────────────────────────────────────
user_pref("extensions.autoDisableScopes", 0);
user_pref("extensions.enabledScopes", 5);
user_pref("extensions.update.enabled", false);
user_pref("extensions.screenshots.disabled", true);
user_pref("extensions.blocklist.enabled", false);

// ── Network (isolate from external services) ──────────────────────────
user_pref("network.captive-portal-service.enabled", false);
user_pref("network.connectivity-service.enabled", false);
user_pref("network.dns.disablePrefetch", true);
user_pref("network.http.speculative-parallel-limit", 0);
user_pref("network.cookie.CHIPS.enabled", false);
user_pref("browser.pocket.enabled", false);

// ── Security (relaxed for testing) ────────────────────────────────────
user_pref("browser.safebrowsing.blockedURIs.enabled", false);
user_pref("browser.safebrowsing.downloads.enabled", false);
user_pref("browser.safebrowsing.passwords.enabled", false);
user_pref("browser.safebrowsing.malware.enabled", false);
user_pref("browser.safebrowsing.phishing.enabled", false);
user_pref("security.fileuri.strict_origin_policy", false);
user_pref("signon.autofillForms", false);
user_pref("signon.rememberSignons", false);
user_pref("privacy.trackingprotection.enabled", false);
user_pref("dom.security.https_first", false);

// ── Timeouts & hangs ──────────────────────────────────────────────────
user_pref("dom.max_script_run_time", 0);
user_pref("dom.max_chrome_script_run_time", 0);
user_pref("dom.ipc.reportProcessHangs", false);
user_pref("hangmonitor.timeout", 0);
user_pref("apz.content_response_timeout", 60000);
user_pref("toolkit.startup.max_resumed_crashes", -1);

// ── Remote / BiDi (essential) ─────────────────────────────────────────
user_pref("remote.enabled", true);
user_pref("remote.bidi.dismiss_file_pickers.enabled", true);

// ── Miscellaneous ─────────────────────────────────────────────────────
user_pref("dom.disable_open_during_load", false);
user_pref("dom.iframe_lazy_loading.enabled", false);
user_pref("dom.file.createInChild", true);
user_pref("dom.push.serverURL", "");
user_pref("focusmanager.testmode", true);
user_pref("geo.provider.testing", true);
user_pref("geo.wifi.scan", false);
user_pref("general.useragent.updates.enabled", false);
user_pref("services.settings.server", "http://dummy.test/dummy/blocklist/");
user_pref("services.sync.enabled", false);
user_pref("media.gmp-manager.updateEnabled", false);
user_pref("media.sanity-test.disabled", true);
user_pref("devtools.jsonview.enabled", false);
user_pref("webgl.forbid-software", false);
user_pref("ui.systemUsesDarkTheme", 0);
user_pref("plugin.state.flash", 0);
user_pref("javascript.options.showInConsole", true);
user_pref("network.cookie.sameSite.laxByDefault", false);
user_pref("network.http.prompt-temp-redirect", false);
user_pref("network.manage-offline-status", false);
user_pref("security.notification_enable_delay", 0);
user_pref("security.certerrors.mitm.priming.enabled", false);
user_pref("startup.homepage_welcome_url", "about:blank");
user_pref("startup.homepage_welcome_url.additional", "");
user_pref("screenshots.browser.component.enabled", false);
"#
  )?;

  Ok(())
}

/// Append download-related preferences to `user.js` so Firefox routes
/// downloads to a profile-scoped folder. Without these prefs Firefox
/// falls back to the host user's `~/Downloads` when computing the
/// `suggestedFilename` it ships in `browsingContext.downloadWillBegin`,
/// which makes the value depend on whichever leftover files happen to
/// be lying around in the developer's downloads dir.
fn write_firefox_download_prefs(f: &mut std::fs::File, downloads_dir: &std::path::Path) -> std::io::Result<()> {
  use std::io::Write;
  let dir = downloads_dir.to_string_lossy();
  writeln!(
    f,
    "// ── Downloads (profile-scoped to keep suggestedFilename deterministic)\n\
user_pref(\"browser.download.folderList\", 2);\n\
user_pref(\"browser.download.dir\", {dir:?});\n\
user_pref(\"browser.download.lastDir\", {dir:?});\n\
user_pref(\"browser.download.useDownloadDir\", true);\n\
user_pref(\"browser.download.manager.showWhenStarting\", false);\n\
user_pref(\"browser.download.alwaysOpenPanel\", false);\n\
user_pref(\"browser.helperApps.alwaysAsk.force\", false);\n\
user_pref(\"browser.helperApps.neverAsk.saveToDisk\", \"application/octet-stream, application/pdf\");"
  )
}