eoka 0.10.1

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
//! # Eoka
//!
//! Stealth browser automation for Rust — a Puppeteer/Playwright alternative that bypasses bot detection.
//!
//! Eoka is a minimal, fast headless Chrome library built from scratch. Unlike Selenium or
//! chromiumoxide, it uses a custom CDP implementation with stealth filtering to avoid detection
//! by Cloudflare, DataDome, PerimeterX, and other anti-bot systems.
//!
//! ## Features
//!
//! - **Stealth by Default** - Binary patching, 15 JS evasions, human-like mouse/typing
//! - **Puppeteer-like API** - `click()`, `type()`, `wait_for()`, `screenshot()`, etc.
//! - **Direct CDP Transport** - No separate WebDriver server or browser-driver dependency
//! - **AI-Agent Ready** - PageState introspection, element indexing, text extraction
//! - **Fast** - Lazy evasion scripts, mmap patching, stack-allocated paths
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use eoka::{ActionOptions, Browser, Expectation, LocatorSpec};
//!
//! #[tokio::main]
//! async fn main() -> eoka::Result<()> {
//!     // Launch browser (patches Chrome, applies evasions)
//!     let browser = Browser::launch().await?;
//!
//!     // Create page and navigate
//!     let page = browser.new_page("data:text/html,<input id=name><button onclick=\"document.body.dataset.done=1\">Save</button>").await?;
//!
//!     // Human-like interactions
//!     page.fill("#name", "hello world").await?;
//!     let receipt = page.locator("button").click(ActionOptions::expecting(
//!         Expectation::Visible { target: LocatorSpec::css("body[data-done]") },
//!     )).await?;
//!     assert_eq!(receipt.outcome, eoka::ActionOutcome::VerifiedComplete);
//!
//!     // Screenshot
//!     let png = page.screenshot().await?;
//!     std::fs::write("screenshot.png", png)?;
//!
//!     browser.close().await?;
//!     Ok(())
//! }
//! ```
//!
//! ## Configuration
//!
//! ```rust,no_run
//! use eoka::Browser;
//!
//! # #[tokio::main]
//! # async fn main() -> eoka::Result<()> {
//! // The default launch path is stealthy and headless.
//! let browser = Browser::launch().await?;
//! browser.close().await?;
//!
//! // For one-off tweaks, mutate the default stealth config inline.
//! let browser = Browser::launch_with(|config| {
//!     config.proxy = Some("http://127.0.0.1:8080".into());
//! }).await?;
//! browser.close().await?;
//! # Ok(())
//! # }
//! ```

#![deny(missing_docs)]

pub mod action;
pub mod bounded_fetch;
pub mod browser;
pub mod cdp;
pub mod download;
pub mod element;
pub use action::{
    Action, ActionCall, ActionDefaults, ActionOptions, ActionOutcome, ActionReceipt, ControlState,
    Destination, DispatchObserver, DispatchState, Expectation, InputMode, Locator, LocatorQuery,
    LocatorSpec, TryActionCall,
};
pub mod error;
pub mod fetch;
mod keyboard;
pub mod network;
pub mod page;
mod recording;
pub mod session;
pub mod stealth;

// Static assertions: ensure core types are Send + Sync for use across async tasks
#[allow(dead_code)]
const _: () = {
    fn assert_send_sync<T: Send + Sync>() {}
    fn _assertions() {
        assert_send_sync::<browser::Browser>();
        assert_send_sync::<page::Page>();
        assert_send_sync::<ActionCall>();
        assert_send_sync::<TryActionCall>();
    }
};

// Re-exports
pub use bounded_fetch::{BoundedFetchRequest, BoundedFetchResponse, MAX_TEXT_FETCH_BYTES};
pub use browser::{Browser, TabInfo};
pub use download::{
    DownloadBeginning, DownloadEvent, DownloadProgress, DownloadWatch, NativeDownloadState,
};
pub use element::{BoundingBox, Element};
pub use error::{Error, Result};
pub use fetch::{BrowserFetchOutcome, BrowserFetchRequest, BrowserFetchResponse};
pub use network::{NetworkEvent, NetworkWatcher};
pub use page::{
    CaptureBodyError, CapturedFrameResponse, FrameResponseCapture, FrameResponseCaptureOptions,
    FrameResponseCaptureReport,
};
pub use page::{
    CapturedRequest, FrameInfo, MouseButton, Page, PageState, ResponseBody, ShadowClickReceipt,
    TextMatch,
};
pub use page::{ScreenshotClip, ScreenshotFormat, ScreenshotOptions};
pub use recording::{NativeRecording, NativeRecordingOptions, RecordingChunk, RecordingError};
pub use session::{BrowserSession, BrowserState, SessionCookie};
pub use stealth::{Fingerprint, HumanSpeed};

/// Configuration for stealth features. `Debug` omits proxy credentials.
#[derive(Clone)]
pub struct StealthConfig {
    /// Spoof WebGL renderer/vendor
    pub webgl_spoof: bool,
    /// Spoof canvas fingerprint
    pub canvas_spoof: bool,
    /// Spoof audio fingerprint
    pub audio_spoof: bool,
    /// Use human-like mouse movements
    pub human_mouse: bool,
    /// Use human-like typing
    pub human_typing: bool,
    /// Custom user agent (None = random realistic)
    pub user_agent: Option<String>,
    /// Headless mode
    pub headless: bool,
    /// Absolute path to Chrome/Chromium. Invalid explicit paths never fall back.
    pub chrome_path: Option<String>,
    /// Absolute parent directory for a unique private browser runtime.
    /// The parent is preserved; only Eoka's owned child is removed.
    pub runtime_dir: Option<String>,
    /// Enable Chrome's sandbox. Defaults to true. Unsupported sandbox
    /// environments (some containers/CI) fail without an unsandboxed retry;
    /// set this to false there explicitly.
    pub sandbox: bool,
    /// Patch Chrome binary to bypass detection
    pub patch_binary: bool,
    /// Viewport width in CSS pixels.
    pub viewport_width: u32,
    /// Viewport height in CSS pixels.
    pub viewport_height: u32,
    /// Physical pixels per CSS pixel. Must be finite and positive.
    pub device_scale_factor: f64,
    /// Debug mode - log actions and save screenshots on error
    pub debug: bool,
    /// Directory for debug screenshots (defaults to current directory)
    pub debug_dir: Option<String>,
    /// Proxy server URL (e.g. "http://host:port")
    pub proxy: Option<String>,
    /// Durable Chrome user-data directory. When set, Eoka preserves the
    /// profile and its full fingerprint identity across browser launches.
    ///
    /// A running instance may be borrowed only without explicit
    /// executable/runtime paths, since those cannot be applied to another
    /// process. With `sandbox` enabled, it is borrowed only when its argv is
    /// readable and carries no sandbox-disabling flag.
    pub user_data_dir: Option<String>,
    /// Named profile within `user_data_dir` (Chrome's `--profile-directory`,
    /// e.g. "Profile 1"). Only meaningful when `user_data_dir` is set;
    /// defaults to Chrome's implicit "Default" profile when `None`.
    ///
    /// Chrome's singleton lock (and thus Eoka's reuse detection above) is
    /// scoped to the whole `user_data_dir`, not the individual profile —
    /// launching a second `profile_dir` while a Chrome is already running
    /// on the same `user_data_dir` attaches to that same running instance
    /// rather than opening a separate one, matching Chrome's own behavior.
    pub profile_dir: Option<String>,
    /// Proxy username for authenticated proxies
    pub proxy_username: Option<String>,
    /// Proxy password for authenticated proxies
    pub proxy_password: Option<String>,
    /// CDP command, automatic-reply write, and WebSocket connection timeout in
    /// seconds (default: 30, increase for slow proxies).
    pub cdp_timeout: u64,
    /// IANA timezone (default: random from common US/EU timezones).
    /// Set to a specific value like "America/New_York" to control the timezone.
    pub timezone: Option<String>,
    /// Extra Chrome command-line arguments appended after standard stealth args.
    /// E.g. vec!["--use-fake-ui-for-media-stream".into()] to auto-grant camera.
    pub extra_args: Vec<String>,
    /// Enable legacy, invasive CDP-marker hiding that proxies `window.document`
    /// and patches Object reflection APIs. It can break modern SPAs, so it is
    /// disabled by default. Prefer the normal WebDriver and fingerprint evasions.
    pub aggressive_cdp_evasion: bool,
    /// Treat this as a session attached to a user-owned browser. When true,
    /// `Browser::new_page`/`new_blank_page`/`attach_page` skip injecting the
    /// evasion script. Defaults to false (set automatically by `Browser::connect*`).
    pub live_session: bool,
    /// Drop "detectable" CDP commands like `Runtime.enable` silently.
    /// Defaults to true. Set to false in connect mode to get full DevTools-like control.
    pub filter_cdp: bool,
    /// Ignore TLS certificate errors on every page from creation, before the
    /// first navigation. `Page::ignore_cert_errors` is applied too late for
    /// `new_page`'s own initial navigate — this covers self-signed/expired
    /// certs (e.g. .onion services) hit on the very first load. Defaults to
    /// false.
    pub ignore_cert_errors: bool,
    /// Strip Chromium's `X-Client-Data` request header via CDP Fetch
    /// interception. Chrome sends this header with field-trial variation IDs on
    /// requests to Google-owned properties; a fresh automation profile carries
    /// a distinctive (often empty) variation set that server-side bot scoring
    /// can read before any JavaScript runs. Also launches Chrome with
    /// `--disable-field-trial-config`. Defaults to true for spawned stealth
    /// browsers; ignored (never applied) for attached live sessions.
    pub strip_x_client_data: bool,
    /// Resolve timezone and interface language from the browser's apparent
    /// public IP via a one-shot navigation to Cloudflare's trace endpoint
    /// before any real page is created. Keeps `Date`/`Intl` and the injected
    /// `navigator.languages` consistent with IP geolocation instead of a
    /// random timezone. Ignored when `timezone` is set explicitly and when
    /// attaching to an existing browser. Defaults to false.
    pub geo_align: bool,
}

/// Prints in place of a secret in `Debug` output.
pub(crate) struct Redacted;

impl std::fmt::Debug for Redacted {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("<redacted>")
    }
}

impl std::fmt::Debug for StealthConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Exhaustive, so that adding a field forces a decision about printing it.
        let Self {
            webgl_spoof,
            canvas_spoof,
            audio_spoof,
            human_mouse,
            human_typing,
            user_agent,
            headless,
            chrome_path,
            runtime_dir,
            sandbox,
            patch_binary,
            viewport_width,
            viewport_height,
            device_scale_factor,
            debug,
            debug_dir,
            proxy,
            user_data_dir,
            profile_dir,
            proxy_username,
            proxy_password,
            cdp_timeout,
            timezone,
            extra_args,
            aggressive_cdp_evasion,
            live_session,
            filter_cdp,
            ignore_cert_errors,
            strip_x_client_data,
            geo_align,
        } = self;
        let mut output = f.debug_struct("StealthConfig");
        output
            .field("webgl_spoof", webgl_spoof)
            .field("canvas_spoof", canvas_spoof)
            .field("audio_spoof", audio_spoof)
            .field("human_mouse", human_mouse)
            .field("human_typing", human_typing)
            .field("user_agent", user_agent)
            .field("headless", headless)
            .field("chrome_path", chrome_path)
            .field("runtime_dir", runtime_dir)
            .field("sandbox", sandbox)
            .field("patch_binary", patch_binary)
            .field("viewport_width", viewport_width)
            .field("viewport_height", viewport_height)
            .field("device_scale_factor", device_scale_factor)
            .field("debug", debug)
            .field("debug_dir", debug_dir);
        // A proxy URL can embed credentials.
        match proxy {
            Some(proxy) if proxy.contains('@') => output.field("proxy", &Some(Redacted)),
            proxy => output.field("proxy", proxy),
        };
        output
            .field("user_data_dir", user_data_dir)
            .field("profile_dir", profile_dir)
            .field("proxy_username", &proxy_username.as_ref().map(|_| Redacted))
            .field("proxy_password", &proxy_password.as_ref().map(|_| Redacted))
            .field("cdp_timeout", cdp_timeout)
            .field("timezone", timezone)
            // Arguments can embed credentials, such as --proxy-server=user:pass@host.
            .field("extra_args", &extra_args.len())
            .field("aggressive_cdp_evasion", aggressive_cdp_evasion)
            .field("live_session", live_session)
            .field("filter_cdp", filter_cdp)
            .field("ignore_cert_errors", ignore_cert_errors)
            .field("strip_x_client_data", strip_x_client_data)
            .field("geo_align", geo_align)
            .finish()
    }
}

impl Default for StealthConfig {
    fn default() -> Self {
        Self {
            webgl_spoof: true,
            canvas_spoof: true,
            audio_spoof: true,
            human_mouse: true,
            human_typing: true,
            user_agent: None,
            headless: true,
            chrome_path: None,
            runtime_dir: None,
            sandbox: true,
            patch_binary: true,
            viewport_width: 1920,
            viewport_height: 1080,
            device_scale_factor: 1.0,
            debug: false,
            debug_dir: None,
            proxy: None,
            user_data_dir: None,
            profile_dir: None,
            proxy_username: None,
            proxy_password: None,
            cdp_timeout: 30,
            timezone: None, // Random from common timezones
            extra_args: Vec::new(),
            aggressive_cdp_evasion: false,
            live_session: false,
            filter_cdp: true,
            ignore_cert_errors: false,
            strip_x_client_data: true,
            geo_align: false,
        }
    }
}

impl StealthConfig {
    /// Create a minimal config (no spoofing, no patching)
    pub fn minimal() -> Self {
        Self {
            webgl_spoof: false,
            canvas_spoof: false,
            audio_spoof: false,
            human_mouse: false,
            human_typing: false,
            headless: false,
            patch_binary: false,
            ..Default::default()
        }
    }

    /// Create a visible (non-headless) config
    pub fn visible() -> Self {
        Self {
            headless: false,
            ..Default::default()
        }
    }

    /// Create a debug config (visible, with logging)
    pub fn debug() -> Self {
        Self {
            headless: false,
            debug: true,
            ..Default::default()
        }
    }

    /// Config tuned for attaching to a user-owned browser via `Browser::connect*`.
    ///
    /// Disables anything that touches the user's Chrome state:
    /// - `live_session` — no evasion script injection on attached tabs
    /// - `filter_cdp = false` — full DevTools-equivalent CDP access
    /// - `patch_binary = false` — we don't manage the binary
    /// - all spoofing off — the user's browser already has its own fingerprint
    pub fn live() -> Self {
        Self {
            live_session: true,
            filter_cdp: false,
            patch_binary: false,
            webgl_spoof: false,
            canvas_spoof: false,
            audio_spoof: false,
            human_mouse: true,
            human_typing: true,
            ..Default::default()
        }
    }
}

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

    #[test]
    fn debug_output_omits_proxy_credentials() {
        let printed = format!(
            "{:?}",
            StealthConfig {
                proxy: Some("http://embedded-user:embedded-pass@proxy.test:8080".into()),
                proxy_username: Some("named-user".into()),
                proxy_password: Some("named-pass".into()),
                extra_args: vec!["--proxy-server=arg-user:arg-pass@proxy.test".into()],
                ..Default::default()
            }
        );
        for secret in [
            "embedded-user",
            "embedded-pass",
            "named-user",
            "named-pass",
            "arg-user",
            "arg-pass",
        ] {
            assert!(!printed.contains(secret), "{secret} leaked: {printed}");
        }
        assert!(printed.contains("proxy_password: Some(<redacted>)"));

        let plain = StealthConfig {
            proxy: Some("http://proxy.test:8080".into()),
            ..Default::default()
        };
        assert!(format!("{plain:?}").contains("http://proxy.test:8080"));
        assert!(format!("{:?}", StealthConfig::default()).contains("proxy_password: None"));
    }

    #[test]
    fn debug_output_omits_values_from_actions_and_network_types() {
        use crate::{Action, BrowserFetchRequest, CapturedRequest, Expectation, LocatorSpec};
        let headers = std::collections::HashMap::from([("Cookie".into(), "header-secret".into())]);
        let printed = format!(
            "{:?} {:?} {:?} {:?} {:?} {:?} {:?}",
            Action::Fill {
                target: LocatorSpec::css("#pw"),
                value: "value-secret".into(),
                input_mode: Default::default(),
            },
            Action::NavigateWithHeaders {
                url: "https://x.test/?t=url-secret".into(),
                headers: headers.clone(),
            },
            Expectation::Value {
                target: LocatorSpec::css("#pw"),
                value: "value-secret".into(),
            },
            CapturedRequest {
                request_id: "1".into(),
                url: "https://x.test/?t=url-secret".into(),
                method: "POST".into(),
                headers: headers.clone(),
                post_data: Some("body-secret".into()),
                resource_type: None,
                status: None,
                status_text: None,
                response_headers: Some(headers.clone()),
                mime_type: None,
                timestamp: 0.0,
                complete: false,
            },
            crate::NetworkEvent::ResponseReceived {
                request_id: "1".into(),
                status: 200,
                status_text: "OK".into(),
                headers: headers.clone(),
                mime_type: None,
            },
            BrowserFetchRequest {
                headers,
                body: Some("body-secret".into()),
                ..BrowserFetchRequest::get("https://x.test/?t=url-secret")
            },
            crate::ResponseBody::Text("body-secret".into()),
        );
        for secret in ["value-secret", "url-secret", "header-secret", "body-secret"] {
            assert!(!printed.contains(secret), "{secret} leaked: {printed}");
        }
        assert!(printed.contains("Cookie"), "header names stay useful");
    }

    #[test]
    fn default_config_is_headless() {
        assert!(StealthConfig::default().headless);
    }

    #[test]
    fn visible_configs_are_explicitly_not_headless() {
        assert!(!StealthConfig::visible().headless);
        assert!(!StealthConfig::debug().headless);
    }
}