browser-commander 0.13.0

Universal browser automation library that supports multiple browser engines with a unified API
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
//! Connect to an already-running Chromium-family browser over CDP.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use chromiumoxide::browser::Browser as CdpBrowser;
use chromiumoxide::cdp::browser_protocol::network::CookieParam;
use futures::StreamExt;
use serde_json::Value;

use crate::browser::chromiumoxide_adapter::ChromiumoxidePage;
use crate::browser::launcher::{Browser, LaunchResult};
use crate::browser::media::ColorScheme;
use crate::browser::node_bridge::NodeBridgePage;
use crate::core::engine::EngineType;
use crate::downloads::{attach_downloads, DownloadSetting};
use crate::fingerprint::apply::{apply_fingerprint, ApplyOptions};
use crate::fingerprint::profile::FingerprintProfile;

/// Options for attaching to a running browser over CDP.
#[derive(Debug, Clone)]
pub struct ConnectOptions {
    /// Browser automation engine used for the connection.
    pub engine: EngineType,
    /// HTTP DevTools endpoint, for example `http://127.0.0.1:9222`.
    pub cdp_endpoint: Option<String>,
    /// DevTools browser WebSocket endpoint.
    pub ws_endpoint: Option<String>,
    /// Slow down Playwright/Puppeteer operations by this many milliseconds.
    pub slow_mo: u64,
    /// Optional connection timeout.
    pub timeout: Option<Duration>,
    /// Optional Puppeteer timeout for individual CDP calls.
    pub protocol_timeout: Option<Duration>,
    /// Cookies to seed after attaching, in CDP/Playwright cookie format.
    pub seed_cookies: Vec<Value>,
    /// Enable verbose bridge logging.
    pub verbose: bool,
    /// Node.js executable for Playwright/Puppeteer bridge engines.
    pub node_executable: Option<PathBuf>,
    /// Directory where Node resolves the Playwright/Puppeteer package.
    pub node_working_dir: Option<PathBuf>,
    /// Manage the attached browser's downloads.
    ///
    /// The same setting and the same manager as
    /// [`LaunchOptions`](super::launcher::LaunchOptions), because a browser
    /// somebody else started downloads files the same way — including the ones
    /// a person clicks by hand. See [`downloads`](crate::downloads).
    pub downloads: DownloadSetting,
}

impl Default for ConnectOptions {
    fn default() -> Self {
        Self {
            engine: EngineType::Chromiumoxide,
            cdp_endpoint: None,
            ws_endpoint: None,
            slow_mo: 0,
            timeout: None,
            protocol_timeout: None,
            seed_cookies: Vec::new(),
            verbose: false,
            node_executable: None,
            node_working_dir: None,
            downloads: DownloadSetting::Off,
        }
    }
}

impl ConnectOptions {
    /// Create Chromiumoxide connection options.
    pub fn chromiumoxide() -> Self {
        Self::default()
    }

    /// Create Playwright bridge connection options.
    pub fn playwright() -> Self {
        Self {
            engine: EngineType::Playwright,
            ..Self::default()
        }
    }

    /// Create Puppeteer bridge connection options.
    pub fn puppeteer() -> Self {
        Self {
            engine: EngineType::Puppeteer,
            ..Self::default()
        }
    }

    /// Select an HTTP DevTools endpoint.
    pub fn cdp_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.cdp_endpoint = Some(endpoint.into());
        self
    }

    /// Select a DevTools browser WebSocket endpoint.
    pub fn ws_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.ws_endpoint = Some(endpoint.into());
        self
    }

    /// Set the engine operation delay.
    pub fn slow_mo(mut self, milliseconds: u64) -> Self {
        self.slow_mo = milliseconds;
        self
    }

    /// Set the connection timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Set Puppeteer's timeout for individual CDP calls.
    pub fn protocol_timeout(mut self, timeout: Duration) -> Self {
        self.protocol_timeout = Some(timeout);
        self
    }

    /// Seed cookies immediately after the connection is established.
    pub fn seed_cookies(mut self, cookies: Vec<Value>) -> Self {
        self.seed_cookies = cookies;
        self
    }

    /// Enable verbose connection logging.
    pub fn verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// Override the Node.js executable for bridge engines.
    pub fn node_executable(mut self, executable: impl Into<PathBuf>) -> Self {
        self.node_executable = Some(executable.into());
        self
    }

    /// Set the directory where Node resolves Playwright or Puppeteer.
    pub fn node_working_dir(mut self, directory: impl Into<PathBuf>) -> Self {
        self.node_working_dir = Some(directory.into());
        self
    }

    /// Manage the attached browser's downloads.
    ///
    /// # Arguments
    ///
    /// * `downloads` - `true` for the defaults, `false` for none, or
    ///   [`DownloadOptions`](crate::downloads::DownloadOptions)
    pub fn downloads(mut self, downloads: impl Into<DownloadSetting>) -> Self {
        self.downloads = downloads.into();
        self
    }

    pub(crate) fn endpoint(&self) -> Result<&str, anyhow::Error> {
        match (&self.cdp_endpoint, &self.ws_endpoint) {
            (Some(endpoint), None) | (None, Some(endpoint)) if !endpoint.is_empty() => Ok(endpoint),
            _ => Err(anyhow::anyhow!(
                "connect_browser requires exactly one of cdp_endpoint or ws_endpoint"
            )),
        }
    }
}

/// Attach to a running Chromium-family browser over CDP.
///
/// Chromiumoxide connects natively. Playwright and Puppeteer use the same
/// official Node.js packages as [`launch_browser`](super::launcher::launch_browser).
/// The returned page implements the crate's shared [`EngineAdapter`](crate::core::EngineAdapter)
/// API. The browser's profile and process remain externally managed.
pub async fn connect_browser(options: ConnectOptions) -> Result<LaunchResult, anyhow::Error> {
    connect_browser_with(options, AttachSettings::default()).await
}

/// What [`launch_browser`](super::launcher::launch_browser) sets up on the
/// page it attaches to, before the caller gets it.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct AttachSettings<'a> {
    /// Applied before the caller can navigate, so the first document already
    /// sees the configured environment.
    pub(crate) fingerprint: Option<&'a FingerprintProfile>,
    /// Emulated on the attached page (best-effort).
    pub(crate) color_scheme: Option<&'a ColorScheme>,
}

/// Refuse a fingerprint profile an engine cannot apply.
///
/// The node bridge speaks its own command protocol rather than CDP, so a
/// profile handed to it would be silently dropped and the page would report
/// the real machine. Failing is the honest answer.
pub(crate) fn refuse_unappliable_fingerprint(
    engine: EngineType,
    fingerprint: Option<&FingerprintProfile>,
) -> Result<(), anyhow::Error> {
    if fingerprint.is_some() && engine != EngineType::Chromiumoxide {
        return Err(anyhow::anyhow!(
            "the {engine} engine cannot apply a fingerprint profile yet; \
             use EngineType::Chromiumoxide, or apply the profile from the \
             JavaScript package, which drives Playwright and Puppeteer directly"
        ));
    }
    Ok(())
}

/// [`connect_browser`] with the page set up as `settings` asks. Used by
/// [`launch_browser`](super::launcher::launch_browser) to attach to the
/// browser it started.
pub(crate) async fn connect_browser_with(
    options: ConnectOptions,
    settings: AttachSettings<'_>,
) -> Result<LaunchResult, anyhow::Error> {
    let endpoint = options.endpoint()?.to_string();
    refuse_unappliable_fingerprint(options.engine, settings.fingerprint)?;
    if options.verbose {
        tracing::info!(engine = %options.engine, %endpoint, "connecting to browser");
    }

    match options.engine {
        EngineType::Chromiumoxide => connect_chromiumoxide(options, endpoint, settings).await,
        EngineType::Playwright | EngineType::Puppeteer => {
            let engine = options.engine;
            let timeout = options.timeout;
            // Refused before the connection is made, for the same reason the
            // launcher refuses it: the bridge has no CDP route, so a manager
            // here would watch a directory the browser never writes into.
            crate::downloads::normalize_download_options(options.downloads.clone())
                .map(|_| crate::downloads::supported_engine(engine))
                .transpose()
                .map_err(|error| anyhow::anyhow!("{error}"))?;
            let connection = NodeBridgePage::connect(options, settings.color_scheme);
            let page = if let Some(timeout) = timeout {
                tokio::time::timeout(timeout, connection)
                    .await
                    .map_err(|_| anyhow::anyhow!("timed out connecting to browser"))??
            } else {
                connection.await?
            };
            Ok(LaunchResult::attached(
                Browser {
                    engine,
                    user_data_dir: PathBuf::new(),
                    headless: false,
                },
                Arc::new(page),
                None,
            ))
        }
        EngineType::Fantoccini => Err(anyhow::anyhow!(
            "fantoccini does not connect over CDP; use chromiumoxide, playwright, or puppeteer"
        )),
    }
}

async fn connect_chromiumoxide(
    options: ConnectOptions,
    endpoint: String,
    settings: AttachSettings<'_>,
) -> Result<LaunchResult, anyhow::Error> {
    let connection = CdpBrowser::connect(endpoint);
    let (browser, mut handler) = if let Some(timeout) = options.timeout {
        tokio::time::timeout(timeout, connection)
            .await
            .map_err(|_| anyhow::anyhow!("timed out connecting to browser"))??
    } else {
        connection.await?
    };

    let handler_task = tokio::spawn(async move {
        while let Some(event) = handler.next().await {
            if let Err(error) = event {
                tracing::debug!(%error, "chromiumoxide handler event error");
            }
        }
    });

    if !options.seed_cookies.is_empty() {
        let cookies = options
            .seed_cookies
            .iter()
            .cloned()
            .map(serde_json::from_value::<CookieParam>)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| anyhow::anyhow!("invalid seed cookie: {error}"))?;
        browser.set_cookies(cookies).await?;
    }

    let page = match pick_foreground_page(browser.pages().await?).await {
        Some(page) => page,
        None => browser.new_page("about:blank").await?,
    };
    let engine = options.engine;
    let adapter = ChromiumoxidePage::new(page, browser, handler_task, PathBuf::new());

    // A failure here is fatal rather than best-effort: a half-applied profile
    // describes a machine that does not exist, which is louder than none.
    if let Some(profile) = settings.fingerprint {
        apply_fingerprint(&adapter, profile, ApplyOptions::default()).await?;
        if options.verbose {
            tracing::info!("Fingerprint profile applied");
        }
    }
    if let Some(color_scheme) = settings.color_scheme {
        if let Err(error) = adapter.set_color_scheme(Some(color_scheme)).await {
            if options.verbose {
                tracing::warn!(%error, "could not set color scheme");
            }
        }
    }

    // `Browser.setDownloadBehavior` is browser-wide, so an attached browser's
    // downloads are managed even when a person starts them from the window
    // rather than from automation. That is the point of managing a *connected*
    // browser at all.
    let downloads = attach_downloads(engine, &adapter, options.downloads.clone())
        .await
        .map_err(|error| anyhow::anyhow!("{error}"))?;

    Ok(LaunchResult::attached(
        Browser {
            engine,
            user_data_dir: PathBuf::new(),
            headless: false,
        },
        Arc::new(adapter),
        downloads,
    ))
}

/// Pick the tab that is on screen.
///
/// A browser attached after it started can already have several tabs - a
/// fresh profile can open a welcome tab next to the New Tab page - and CDP
/// does not list them in a stable order. Driving a background tab would make
/// `document.hidden` true where a person's first navigation sees a visible
/// page, so the visible tab wins and the first tab is the fallback.
async fn pick_foreground_page(pages: Vec<chromiumoxide::Page>) -> Option<chromiumoxide::Page> {
    for page in &pages {
        let state = page
            .evaluate("document.visibilityState")
            .await
            .ok()
            .and_then(|result| result.into_value::<String>().ok());
        if state.as_deref() == Some("visible") {
            return Some(page.clone());
        }
    }
    pages.into_iter().next()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn connect_options_carry_a_download_setting() {
        assert!(matches!(
            ConnectOptions::default().downloads,
            DownloadSetting::Off
        ));
        assert!(matches!(
            ConnectOptions::chromiumoxide().downloads(true).downloads,
            DownloadSetting::On
        ));
    }

    #[tokio::test]
    async fn connect_playwright_refuses_downloads_it_cannot_manage() {
        let options = ConnectOptions::playwright()
            .cdp_endpoint("http://127.0.0.1:9222")
            .downloads(true);

        let error = connect_browser(options).await.unwrap_err();

        assert!(
            error
                .to_string()
                .contains("managed downloads are not supported"),
            "unexpected message: {error}"
        );
    }

    #[test]
    fn connect_options_builders_preserve_endpoints_and_cookies() {
        let cookies = vec![json!({"name": "SID", "value": "saved", "domain": ".example.com"})];
        let options = ConnectOptions::playwright()
            .cdp_endpoint("http://127.0.0.1:9222")
            .slow_mo(25)
            .seed_cookies(cookies.clone())
            .node_working_dir("../js");

        assert_eq!(options.engine, EngineType::Playwright);
        assert_eq!(options.endpoint().unwrap(), "http://127.0.0.1:9222");
        assert_eq!(options.slow_mo, 25);
        assert_eq!(options.seed_cookies, cookies);
        assert_eq!(options.node_working_dir, Some(PathBuf::from("../js")));
    }

    #[test]
    fn connect_options_require_exactly_one_endpoint() {
        assert!(ConnectOptions::default().endpoint().is_err());
        assert!(ConnectOptions::puppeteer()
            .cdp_endpoint("http://127.0.0.1:9222")
            .ws_endpoint("ws://127.0.0.1:9222/devtools/browser/id")
            .endpoint()
            .is_err());
    }
}