eoka 0.14.3

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Browser Launcher
//!
//! Handles Chrome discovery, launching with stealth flags, and binary patching.

pub(crate) mod discovery;
mod geo;
mod launch;

use launch::{discover_browser_ws, prepare_browser_launch, LaunchCancellation};

use std::path::Path;
use std::sync::Arc;

use crate::cdp::types::{EmulationSetUserAgentOverride, UserAgentBrandVersion, UserAgentMetadata};
use crate::cdp::{Connection, Transport};
use crate::error::{Error, Result};
use crate::page::Page;
use crate::stealth::build_evasion_script_for;
use crate::stealth::fingerprint::Fingerprint;
use crate::StealthConfig;

/// Info about an open tab
#[derive(Debug, Clone)]
pub struct TabInfo {
    /// Target ID of the tab.
    pub id: String,
    /// Tab title.
    pub title: String,
    /// URL currently loaded in the tab.
    pub url: String,
}

/// Build the `Emulation.setUserAgentOverride` payload from the resolved fingerprint.
pub(crate) fn ua_override_for(fp: &Fingerprint) -> EmulationSetUserAgentOverride {
    let to_brands = |v: Vec<(String, String)>| -> Vec<UserAgentBrandVersion> {
        v.into_iter()
            .map(|(brand, version)| UserAgentBrandVersion { brand, version })
            .collect()
    };
    let architecture = fp.ch_architecture();
    EmulationSetUserAgentOverride {
        user_agent: fp.user_agent.clone(),
        // Chrome adds the quality values itself (`en-US,en` is sent as
        // `en-US,en;q=0.9`); passing them here would double them. The header
        // must match `navigator.languages` (filled from the same list).
        accept_language: Some(fp.languages.join(",")),
        platform: Some(fp.nav_platform().to_string()),
        user_agent_metadata: Some(UserAgentMetadata {
            brands: to_brands(fp.ch_brands()),
            full_version_list: to_brands(fp.ch_full_version_brands()),
            platform: fp.ch_platform().to_string(),
            platform_version: fp.platform_version.clone(),
            architecture: architecture.to_string(),
            model: String::new(),
            mobile: false,
            bitness: "64".to_string(),
            wow64: false,
        }),
    }
}

/// Everything needed to give a page session eoka's identity: shared by the
/// browser's own pages and by pages a CDP-proxy client opens.
#[derive(Clone)]
pub(crate) struct SessionSetup {
    config: Arc<StealthConfig>,
    fingerprint: Option<Fingerprint>,
    evasion_script: Arc<str>,
}

impl SessionSetup {
    /// The page's identity for its out-of-process iframes and workers.
    fn child_setup(
        &self,
        fp: &Fingerprint,
        proxy_auth: bool,
    ) -> crate::cdp::connection::ChildSetup {
        let concurrency = (
            "Emulation.setHardwareConcurrencyOverride",
            serde_json::json!({ "hardwareConcurrency": fp.hardware_concurrency }),
        );
        let mut frame = vec![
            (
                "Emulation.setUserAgentOverride",
                serde_json::to_value(ua_override_for(fp))
                    .expect("a user-agent override of plain strings serializes"),
            ),
            (
                "Emulation.setTimezoneOverride",
                serde_json::json!({ "timezoneId": fp.timezone }),
            ),
            concurrency.clone(),
            // Init scripts are only injected on a session with Page enabled.
            ("Page.enable", serde_json::json!({})),
            (
                "Page.addScriptToEvaluateOnNewDocument",
                // The iframe's first document may already exist when it is
                // attached; runImmediately covers it, later ones run at start.
                serde_json::json!({ "source": &*self.evasion_script, "runImmediately": true }),
            ),
        ];
        if proxy_auth {
            frame.push((
                "Fetch.enable",
                serde_json::json!({ "handleAuthRequests": true }),
            ));
        }
        let worker_script = crate::stealth::evasions::build_worker_evasion_script(&self.config, fp);
        crate::cdp::connection::ChildSetup {
            frame,
            worker: vec![
                concurrency,
                (
                    "Runtime.evaluate",
                    serde_json::json!({ "expression": worker_script }),
                ),
            ],
        }
    }

    /// Set up a session with evasion scripts, viewport emulation and proxy
    /// auth: new pages, attached pages and pages a CDP-proxy client opens.
    /// Live sessions retain existing viewport metrics and skip evasion injection.
    pub(crate) async fn apply(&self, session: &crate::cdp::Session, fresh: bool) -> Result<()> {
        session.monitor_network(fresh).await?;
        session.page_enable().await?;

        // Intercept only to answer configured proxy auth challenges.
        let proxy_auth = self.config.proxy_credentials().is_some();
        if proxy_auth {
            session.fetch_enable_interception(vec![], true).await?;
        }

        if self.config.ignore_cert_errors {
            session.set_ignore_cert_errors(true).await?;
        }

        if !self.config.live_session() {
            session
                .set_viewport(
                    self.config.viewport_width,
                    self.config.viewport_height,
                    self.config.device_scale_factor,
                )
                .await?;
            if let Some(ref fp) = self.fingerprint {
                session.set_user_agent_full(ua_override_for(fp)).await?;
                // Native ICU override: makes `Date.toString()`, `getHours()` and
                // friends consistent with the claimed timezone (a JS shim alone
                // leaves them reporting the host timezone).
                // There is no script fallback: a page that kept the host
                // timezone would contradict the identity, so failing is safer.
                session.set_timezone_override(&fp.timezone).await?;
                session
                    .set_hardware_concurrency_override(fp.hardware_concurrency)
                    .await?;
                session
                    .set_up_children(Arc::new(self.child_setup(fp, proxy_auth)))
                    .await?;
            }
            session
                .add_script_to_evaluate_on_new_document(&self.evasion_script)
                .await?;
        }

        Ok(())
    }

    /// Give a page a CDP-proxy client opened eoka's identity; see
    /// [`crate::cdp::proxy::Adopter`].
    async fn adopt(self, connection: Connection, target_id: String, fresh: bool) -> Result<()> {
        if (connection.target_lookup())(&target_id) {
            return Ok(());
        }
        // Only pages: an iframe or worker a client attaches by hand must not
        // get a page's setup.
        let info = connection.transport().target_info(&target_id).await?;
        if info["targetInfo"]["type"] != "page" {
            return Ok(());
        }
        let session = connection.attach_to_target(&target_id).await?;
        if let Err(error) = self.apply(&session, fresh).await {
            // Leave no half-set-up page behind: detaching drops the session's
            // overrides and scripts, and forgetting the target lets a later
            // attach retry.
            let _ = session.detach().await;
            connection.forget_target(&target_id).await;
            return Err(error);
        }
        Ok(())
    }
}

/// The main stealth browser
pub struct Browser {
    connection: Connection,
    download_slot: Arc<tokio::sync::Semaphore>,
    /// True when we attached to a Chrome we didn't spawn (see
    /// `try_attach_existing`). `close()` must never send `Browser.close` to
    /// a process we don't own, regardless of `config.mode`.
    reused: bool,
    /// Config, fingerprint (None in live-session mode) and evasion script
    /// every page of this browser is set up with.
    setup: SessionSetup,
}

impl Browser {
    /// Serve a loopback CDP endpoint for other clients (Playwright,
    /// Puppeteer, Browser Use) to drive this browser. Experimental.
    pub async fn serve_cdp(
        &self,
        options: crate::cdp::CdpProxyOptions,
    ) -> Result<crate::cdp::CdpProxy> {
        let endpoint = self
            .connection
            .transport()
            .browser_endpoint()
            .ok_or_else(|| Error::invalid_argument("this browser has no DevTools endpoint"))?;
        let adopter = (!self.setup.config.live_session()).then(|| {
            let connection = self.connection.clone();
            let setup = self.setup.clone();
            let adopt: crate::cdp::proxy::Adopter =
                Arc::new(move |target_id: String, fresh: bool| {
                    Box::pin(setup.clone().adopt(connection.clone(), target_id, fresh))
                });
            adopt
        });
        crate::cdp::proxy::serve(endpoint, options, adopter).await
    }

    /// Whether this handle owns the Chrome process, rather than borrowing it.
    pub fn owns_process(&self) -> bool {
        !self.reused
    }

    /// Reserve native download settings and subscribe before triggering a download.
    /// Only supported for owned processes. The directory must already exist.
    pub async fn watch_downloads(&self, directory: &Path) -> Result<crate::DownloadWatch> {
        if !self.owns_process() {
            return Err(Error::coded(
                crate::ErrorCode::DownloadUnsupported,
                "attached browsers are not supported",
            ));
        }
        crate::DownloadWatch::begin(
            self.connection.transport().clone(),
            self.download_slot.clone(),
            directory,
        )
        .await
    }

    /// Launch a new stealth browser with default config
    pub async fn launch() -> Result<Self> {
        Self::launch_with_config(StealthConfig::default()).await
    }

    /// Launch a new stealth browser with a visible window.
    pub async fn launch_visible() -> Result<Self> {
        Self::launch_with_config(StealthConfig::visible()).await
    }

    /// Launch a new visible stealth browser with debug logging behavior enabled.
    pub async fn launch_debug() -> Result<Self> {
        Self::launch_with_config(StealthConfig::debug()).await
    }

    /// Launch with the default stealth config after applying inline changes.
    ///
    /// This avoids constructing a full [`StealthConfig`] when only one or two
    /// options need to change.
    pub async fn launch_with(configure: impl FnOnce(&mut StealthConfig)) -> Result<Self> {
        let mut config = StealthConfig::default();
        configure(&mut config);
        Self::launch_with_config(config).await
    }

    /// Launch with custom config
    pub async fn launch_with_config(config: StealthConfig) -> Result<Self> {
        let mut config = Arc::new(config);
        let launch_config = Arc::clone(&config);
        let cancellation = LaunchCancellation::new();
        let cancelled = Arc::clone(&cancellation.0);
        let mut prepared =
            tokio::task::spawn_blocking(move || prepare_browser_launch(&launch_config, &cancelled))
                .await
                .map_err(|error| {
                    Error::launch(format!("Browser launch worker failed: {error}"))
                })??;

        let spawned = prepared.child.is_some();
        if !spawned {
            let config = Arc::make_mut(&mut config);
            config.mode = crate::Mode::Plain;
        }
        let transport = match prepared.child.take() {
            Some(child) => {
                Transport::new_with_runtime_options(
                    child,
                    &prepared.ws_url,
                    config.proxy_credentials(),
                    config.cdp_timeout,
                    config.filter_cdp(),
                    prepared.runtime.take(),
                )
                .await?
            }
            None => {
                Transport::connect_with_proxy_auth(
                    &prepared.ws_url,
                    config.proxy_credentials(),
                    config.cdp_timeout,
                    config.filter_cdp(),
                )
                .await?
            }
        };
        let fingerprint = prepared.fingerprint.clone();
        let mut browser =
            Self::from_transport(transport, config, Some(fingerprint), !spawned).await?;
        if spawned && browser.setup.config.geo_align && browser.setup.config.timezone.is_none() {
            browser.align_geo().await;
        }
        Ok(browser)
    }

    /// Finish a launch or connect: log the Chrome version and build the
    /// evasion script for `fingerprint` (none without one).
    async fn from_transport(
        transport: Transport,
        config: Arc<StealthConfig>,
        fingerprint: Option<Fingerprint>,
        reused: bool,
    ) -> Result<Self> {
        let connection = Connection::new(transport);
        let version = connection.version().await?;
        tracing::info!("Connected to Chrome: {}", version.product);
        let evasion_script = fingerprint.as_ref().map_or_else(
            || Arc::from(""),
            |fp| build_evasion_script_for(&config, fp).into(),
        );
        Ok(Self {
            connection,
            download_slot: Arc::new(tokio::sync::Semaphore::new(1)),
            reused,
            setup: SessionSetup {
                config,
                fingerprint,
                evasion_script,
            },
        })
    }

    /// Align timezone and languages with the browser's apparent public IP.
    /// Lookup failure preserves the current fingerprint.
    async fn align_geo(&mut self) {
        let outcome = async {
            let page = self.new_blank_page().await?;
            let result = geo::lookup(&page).await;
            let _ = self.close_tab(page.target_id()).await;
            result
        }
        .await;

        match outcome {
            Ok(geo) => {
                let setup = &mut self.setup;
                if let Some(fp) = setup.fingerprint.as_mut() {
                    if let Some(timezone) = geo.timezone {
                        fp.timezone = timezone;
                    }
                    fp.languages = geo::languages_for_country(&geo.country);
                    setup.evasion_script = build_evasion_script_for(&setup.config, fp).into();
                }
                tracing::info!(
                    "Geo-aligned languages/timezone (IP country {})",
                    geo.country
                );
            }
            Err(error) => {
                tracing::warn!("Geo alignment failed, keeping random timezone: {}", error);
            }
        }
    }

    /// Connect to an existing Chrome instance at the given WebSocket CDP URL.
    /// Obtain the URL from `curl http://localhost:9222/json/version` or use
    /// `Browser::connect_port` for HTTP discovery.
    ///
    /// Defaults to `StealthConfig::live()` so attaching to a user's real browser
    /// leaves their tabs untouched (no evasion script injection, full CDP access).
    pub async fn connect(ws_url: &str) -> Result<Self> {
        Self::connect_with_config(ws_url, StealthConfig::live()).await
    }

    /// Connect to an existing Chrome instance with a custom config.
    /// Allows customizing CDP timeout, evasion scripts, proxy auth, etc.
    pub async fn connect_with_config(ws_url: &str, config: StealthConfig) -> Result<Self> {
        let config = Arc::new(config);
        // Without these credentials, setup_session would enable auth
        // interception that nothing answers, stalling proxied requests.
        let transport = crate::cdp::transport::Transport::connect_with_proxy_auth(
            ws_url,
            config.proxy_credentials(),
            config.cdp_timeout,
            config.filter_cdp(),
        )
        .await?;
        // Skip the evasion script and fingerprint for live sessions.
        let fingerprint = (!config.live_session()).then(|| {
            Fingerprint::resolve(config.user_agent.as_deref(), config.timezone.as_deref())
        });
        Self::from_transport(transport, config, fingerprint, true).await
    }

    /// Discover the DevTools URL on `127.0.0.1:<port>` and connect.
    /// Equivalent to `curl http://127.0.0.1:<port>/json/version` then `Browser::connect`.
    pub async fn connect_port(port: u16) -> Result<Self> {
        let ws_url = discover_browser_ws(port).await?;
        Self::connect(&ws_url).await
    }

    /// `connect_port` with a custom config.
    pub async fn connect_port_with_config(port: u16, config: StealthConfig) -> Result<Self> {
        let ws_url = discover_browser_ws(port).await?;
        Self::connect_with_config(&ws_url, config).await
    }

    /// Create a new page and navigate to URL. Navigation is verified the
    /// same way as [`Page::goto`]. When setup or navigation fails, the new
    /// tab is closed before the error is returned.
    pub async fn new_page(&self, url: &str) -> Result<Page> {
        let page = self.new_blank_page().await?;
        if let Err(error) = page.goto(url).await {
            self.discard_target(page.target_id()).await;
            return Err(error);
        }
        Ok(page)
    }

    /// Create a new page without navigation (at about:blank). When setup
    /// fails, the new tab is closed before the error is returned.
    pub async fn new_blank_page(&self) -> Result<Page> {
        let target_id = self.connection.create_target("about:blank").await?;

        let setup = async {
            let session = self.connection.attach_to_target(&target_id).await?;
            self.setup.apply(&session, true).await?;
            Ok::<_, Error>(session)
        }
        .await;
        match setup {
            Ok(session) => Ok(Page::new(session, Arc::clone(&self.setup.config))),
            Err(error) => {
                self.discard_target(&target_id).await;
                Err(error)
            }
        }
    }

    /// Best-effort close of a tab this browser just created for a call that
    /// failed; the original error is what the caller sees.
    async fn discard_target(&self, target_id: &str) {
        if let Err(error) = self.connection.close_target(target_id).await {
            tracing::warn!("Failed to close tab {target_id} after a failed open: {error}");
        }
    }

    /// Get the browser version
    pub async fn version(&self) -> Result<String> {
        let v = self.connection.version().await?;
        Ok(v.product)
    }

    /// List all open tabs
    pub async fn tabs(&self) -> Result<Vec<TabInfo>> {
        let targets = self.connection.get_targets().await?;
        Ok(targets
            .into_iter()
            .filter(|t| t.r#type == "page")
            .map(|t| TabInfo {
                id: t.target_id,
                title: t.title,
                url: t.url,
            })
            .collect())
    }

    /// Attach to an existing browser target (e.g., a popup opened by window.open()).
    /// Use `tabs()` to discover popup target IDs, then call this to get a Page handle.
    pub async fn attach_page(&self, target_id: &str) -> Result<Page> {
        let session = self.connection.attach_to_target(target_id).await?;
        self.setup.apply(&session, false).await?;
        Ok(Page::new(session, Arc::clone(&self.setup.config)))
    }

    /// Activate (focus) a tab by target ID
    pub async fn activate_tab(&self, target_id: &str) -> Result<()> {
        self.connection.activate_target(target_id).await
    }

    /// Close a specific tab by target ID
    pub async fn close_tab(&self, target_id: &str) -> Result<()> {
        self.connection.close_target(target_id).await?;
        Ok(())
    }

    /// Gracefully close an owned browser, including owned live-session launches.
    /// Attached browsers are only disconnected, regardless of configuration.
    /// Chrome has a bounded opportunity to flush state before forced termination.
    pub async fn close(self) -> Result<()> {
        if self.reused {
            self.connection.disconnect().await
        } else {
            self.connection.close().await
        }
    }

    /// Drop the WebSocket without sending `Browser.close`. Use this when
    /// connected to a user-owned browser to disconnect without killing it.
    pub async fn disconnect(self) -> Result<()> {
        self.connection.disconnect().await
    }
}

impl Drop for Browser {
    fn drop(&mut self) {
        if self.owns_process() {
            if let Err(error) = self.connection.transport().cleanup_owned() {
                tracing::warn!(
                    "Failed to clean up owned browser while dropping handle: {}",
                    error
                );
            }
        }
    }
}

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

    // Audit regression: the Accept-Language header used to be hardcoded
    // en-US while navigator.languages followed the fingerprint/geo align —
    // a header-vs-JS mismatch any server can compare.
    #[test]
    fn accept_language_matches_fingerprint_languages() {
        // Chrome appends the quality values itself (en-US,en becomes
        // en-US,en;q=0.9), so the override carries the bare list. Sending
        // q-values here produced a doubled `en;q=0.9;q=0.9` header.
        let fp = Fingerprint::random();
        let override_payload = ua_override_for(&fp);
        let accept_language = override_payload.accept_language.unwrap();
        assert_eq!(accept_language, fp.languages.join(","));
        assert!(!accept_language.contains(";q="), "{accept_language}");
    }
}