Skip to main content

eoka/
lib.rs

1//! # Eoka
2//!
3//! Stealth browser automation for Rust — a Puppeteer/Playwright alternative that bypasses bot detection.
4//!
5//! Eoka is a minimal, fast headless Chrome library built from scratch. Unlike Selenium or
6//! chromiumoxide, it uses a custom CDP implementation with stealth filtering to avoid detection
7//! by Cloudflare, DataDome, PerimeterX, and other anti-bot systems.
8//!
9//! ## Features
10//!
11//! - **Stealth by Default** - Binary patching, 15 JS evasions, human-like mouse/typing
12//! - **Puppeteer-like API** - `click()`, `type()`, `wait_for()`, `screenshot()`, etc.
13//! - **Direct CDP Transport** - No separate WebDriver server or browser-driver dependency
14//! - **AI-Agent Ready** - PageState introspection, element indexing, text extraction
15//! - **Fast** - Lazy evasion scripts, mmap patching, stack-allocated paths
16//!
17//! ## Quick Start
18//!
19//! ```rust,no_run
20//! use eoka::{ActionOptions, Browser, Expectation, LocatorSpec};
21//!
22//! #[tokio::main]
23//! async fn main() -> eoka::Result<()> {
24//!     // Launch browser (patches Chrome, applies evasions)
25//!     let browser = Browser::launch().await?;
26//!
27//!     // Create page and navigate
28//!     let page = browser.new_page("data:text/html,<input id=name><button onclick=\"document.body.dataset.done=1\">Save</button>").await?;
29//!
30//!     // Human-like interactions
31//!     page.fill("#name", "hello world").await?;
32//!     let receipt = page.locator("button").click(ActionOptions::expecting(
33//!         Expectation::Visible { target: LocatorSpec::css("body[data-done]") },
34//!     )).await?;
35//!     assert_eq!(receipt.outcome, eoka::ActionOutcome::VerifiedComplete);
36//!
37//!     // Screenshot
38//!     let png = page.screenshot().await?;
39//!     std::fs::write("screenshot.png", png)?;
40//!
41//!     browser.close().await?;
42//!     Ok(())
43//! }
44//! ```
45//!
46//! ## Configuration
47//!
48//! ```rust,no_run
49//! use eoka::Browser;
50//!
51//! # #[tokio::main]
52//! # async fn main() -> eoka::Result<()> {
53//! // The default launch path is stealthy and headless.
54//! let browser = Browser::launch().await?;
55//! browser.close().await?;
56//!
57//! // For one-off tweaks, mutate the default stealth config inline.
58//! let browser = Browser::launch_with(|config| {
59//!     config.proxy = Some("http://127.0.0.1:8080".into());
60//! }).await?;
61//! browser.close().await?;
62//! # Ok(())
63//! # }
64//! ```
65
66#![deny(missing_docs)]
67
68pub mod action;
69pub mod bounded_fetch;
70pub mod browser;
71pub mod cdp;
72pub mod download;
73pub mod element;
74pub use action::{
75    Action, ActionOptions, ActionOutcome, ActionReceipt, DispatchObserver, DispatchState,
76    Expectation, Locator, LocatorQuery, LocatorSpec,
77};
78pub mod error;
79pub mod fetch;
80mod keyboard;
81pub mod network;
82pub mod page;
83mod recording;
84pub mod session;
85pub mod stealth;
86
87// Static assertions: ensure core types are Send + Sync for use across async tasks
88#[allow(dead_code)]
89const _: () = {
90    fn assert_send_sync<T: Send + Sync>() {}
91    fn _assertions() {
92        assert_send_sync::<browser::Browser>();
93        assert_send_sync::<page::Page>();
94    }
95};
96
97// Re-exports
98pub use bounded_fetch::{BoundedFetchRequest, BoundedFetchResponse, MAX_TEXT_FETCH_BYTES};
99pub use browser::{Browser, TabInfo};
100pub use download::{
101    DownloadBeginning, DownloadEvent, DownloadProgress, DownloadWatch, NativeDownloadState,
102};
103pub use element::{BoundingBox, Element};
104pub use error::{Error, Result};
105pub use fetch::{BrowserFetchOutcome, BrowserFetchRequest, BrowserFetchResponse};
106pub use network::{NetworkEvent, NetworkWatcher};
107pub use page::{
108    CaptureBodyError, CapturedFrameResponse, FrameResponseCapture, FrameResponseCaptureOptions,
109    FrameResponseCaptureReport,
110};
111pub use page::{CapturedRequest, FrameInfo, MouseButton, Page, PageState, ResponseBody, TextMatch};
112pub use page::{ScreenshotClip, ScreenshotFormat, ScreenshotOptions};
113pub use recording::{NativeRecording, NativeRecordingOptions, RecordingChunk, RecordingError};
114pub use session::{BrowserSession, BrowserState, SessionCookie};
115pub use stealth::{Fingerprint, HumanSpeed};
116
117/// Configuration for stealth features
118#[derive(Debug, Clone)]
119pub struct StealthConfig {
120    /// Spoof WebGL renderer/vendor
121    pub webgl_spoof: bool,
122    /// Spoof canvas fingerprint
123    pub canvas_spoof: bool,
124    /// Spoof audio fingerprint
125    pub audio_spoof: bool,
126    /// Use human-like mouse movements
127    pub human_mouse: bool,
128    /// Use human-like typing
129    pub human_typing: bool,
130    /// Custom user agent (None = random realistic)
131    pub user_agent: Option<String>,
132    /// Headless mode
133    pub headless: bool,
134    /// Absolute path to Chrome/Chromium. Invalid explicit paths never fall back.
135    pub chrome_path: Option<String>,
136    /// Absolute parent directory for a unique private browser runtime.
137    /// The parent is preserved; only Eoka's owned child is removed.
138    pub runtime_dir: Option<String>,
139    /// Enable Chrome's sandbox. Defaults to false for existing callers.
140    /// Unsupported sandbox environments fail without an unsandboxed retry.
141    pub sandbox: bool,
142    /// Patch Chrome binary to bypass detection
143    pub patch_binary: bool,
144    /// Viewport width in CSS pixels.
145    pub viewport_width: u32,
146    /// Viewport height in CSS pixels.
147    pub viewport_height: u32,
148    /// Physical pixels per CSS pixel. Must be finite and positive.
149    pub device_scale_factor: f64,
150    /// Debug mode - log actions and save screenshots on error
151    pub debug: bool,
152    /// Directory for debug screenshots (defaults to current directory)
153    pub debug_dir: Option<String>,
154    /// Proxy server URL (e.g. "http://host:port")
155    pub proxy: Option<String>,
156    /// Durable Chrome user-data directory. When set, Eoka preserves the
157    /// profile and its full fingerprint identity across browser launches.
158    ///
159    /// A running instance may be borrowed only with the legacy default launch
160    /// policy. Explicit executable/runtime paths or sandboxing reject reuse,
161    /// since those launch requirements cannot be applied to another process.
162    pub user_data_dir: Option<String>,
163    /// Named profile within `user_data_dir` (Chrome's `--profile-directory`,
164    /// e.g. "Profile 1"). Only meaningful when `user_data_dir` is set;
165    /// defaults to Chrome's implicit "Default" profile when `None`.
166    ///
167    /// Chrome's singleton lock (and thus Eoka's reuse detection above) is
168    /// scoped to the whole `user_data_dir`, not the individual profile —
169    /// launching a second `profile_dir` while a Chrome is already running
170    /// on the same `user_data_dir` attaches to that same running instance
171    /// rather than opening a separate one, matching Chrome's own behavior.
172    pub profile_dir: Option<String>,
173    /// Proxy username for authenticated proxies
174    pub proxy_username: Option<String>,
175    /// Proxy password for authenticated proxies
176    pub proxy_password: Option<String>,
177    /// CDP command, automatic-reply write, and WebSocket connection timeout in
178    /// seconds (default: 30, increase for slow proxies).
179    pub cdp_timeout: u64,
180    /// IANA timezone (default: random from common US/EU timezones).
181    /// Set to a specific value like "America/New_York" to control the timezone.
182    pub timezone: Option<String>,
183    /// Extra Chrome command-line arguments appended after standard stealth args.
184    /// E.g. vec!["--use-fake-ui-for-media-stream".into()] to auto-grant camera.
185    pub extra_args: Vec<String>,
186    /// Enable legacy, invasive CDP-marker hiding that proxies `window.document`
187    /// and patches Object reflection APIs. It can break modern SPAs, so it is
188    /// disabled by default. Prefer the normal WebDriver and fingerprint evasions.
189    pub aggressive_cdp_evasion: bool,
190    /// Treat this as a session attached to a user-owned browser. When true,
191    /// `Browser::new_page`/`new_blank_page`/`attach_page` skip injecting the
192    /// evasion script. Defaults to false (set automatically by `Browser::connect*`).
193    pub live_session: bool,
194    /// Drop "detectable" CDP commands like `Runtime.enable` silently.
195    /// Defaults to true. Set to false in connect mode to get full DevTools-like control.
196    pub filter_cdp: bool,
197    /// Ignore TLS certificate errors on every page from creation, before the
198    /// first navigation. `Page::ignore_cert_errors` is applied too late for
199    /// `new_page`'s own initial navigate — this covers self-signed/expired
200    /// certs (e.g. .onion services) hit on the very first load. Defaults to
201    /// false.
202    pub ignore_cert_errors: bool,
203    /// Strip Chromium's `X-Client-Data` request header via CDP Fetch
204    /// interception. Chrome sends this header with field-trial variation IDs on
205    /// requests to Google-owned properties; a fresh automation profile carries
206    /// a distinctive (often empty) variation set that server-side bot scoring
207    /// can read before any JavaScript runs. Also launches Chrome with
208    /// `--disable-field-trial-config`. Defaults to true for spawned stealth
209    /// browsers; ignored (never applied) for attached live sessions.
210    pub strip_x_client_data: bool,
211    /// Resolve timezone and interface language from the browser's apparent
212    /// public IP via a one-shot navigation to Cloudflare's trace endpoint
213    /// before any real page is created. Keeps `Date`/`Intl` and the injected
214    /// `navigator.languages` consistent with IP geolocation instead of a
215    /// random timezone. Ignored when `timezone` is set explicitly and when
216    /// attaching to an existing browser. Defaults to false.
217    pub geo_align: bool,
218}
219
220impl Default for StealthConfig {
221    fn default() -> Self {
222        Self {
223            webgl_spoof: true,
224            canvas_spoof: true,
225            audio_spoof: true,
226            human_mouse: true,
227            human_typing: true,
228            user_agent: None,
229            headless: true,
230            chrome_path: None,
231            runtime_dir: None,
232            sandbox: false,
233            patch_binary: true,
234            viewport_width: 1920,
235            viewport_height: 1080,
236            device_scale_factor: 1.0,
237            debug: false,
238            debug_dir: None,
239            proxy: None,
240            user_data_dir: None,
241            profile_dir: None,
242            proxy_username: None,
243            proxy_password: None,
244            cdp_timeout: 30,
245            timezone: None, // Random from common timezones
246            extra_args: Vec::new(),
247            aggressive_cdp_evasion: false,
248            live_session: false,
249            filter_cdp: true,
250            ignore_cert_errors: false,
251            strip_x_client_data: true,
252            geo_align: false,
253        }
254    }
255}
256
257impl StealthConfig {
258    /// Create a minimal config (no spoofing, no patching)
259    pub fn minimal() -> Self {
260        Self {
261            webgl_spoof: false,
262            canvas_spoof: false,
263            audio_spoof: false,
264            human_mouse: false,
265            human_typing: false,
266            headless: false,
267            patch_binary: false,
268            ..Default::default()
269        }
270    }
271
272    /// Create a visible (non-headless) config
273    pub fn visible() -> Self {
274        Self {
275            headless: false,
276            ..Default::default()
277        }
278    }
279
280    /// Create a debug config (visible, with logging)
281    pub fn debug() -> Self {
282        Self {
283            headless: false,
284            debug: true,
285            ..Default::default()
286        }
287    }
288
289    /// Config tuned for attaching to a user-owned browser via `Browser::connect*`.
290    ///
291    /// Disables anything that touches the user's Chrome state:
292    /// - `live_session` — no evasion script injection on attached tabs
293    /// - `filter_cdp = false` — full DevTools-equivalent CDP access
294    /// - `patch_binary = false` — we don't manage the binary
295    /// - all spoofing off — the user's browser already has its own fingerprint
296    pub fn live() -> Self {
297        Self {
298            live_session: true,
299            filter_cdp: false,
300            patch_binary: false,
301            webgl_spoof: false,
302            canvas_spoof: false,
303            audio_spoof: false,
304            human_mouse: true,
305            human_typing: true,
306            ..Default::default()
307        }
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::StealthConfig;
314
315    #[test]
316    fn default_config_is_headless() {
317        assert!(StealthConfig::default().headless);
318    }
319
320    #[test]
321    fn visible_configs_are_explicitly_not_headless() {
322        assert!(!StealthConfig::visible().headless);
323        assert!(!StealthConfig::debug().headless);
324    }
325}