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 timeout in seconds (default: 30, increase for slow proxies)
178 pub cdp_timeout: u64,
179 /// IANA timezone (default: random from common US/EU timezones).
180 /// Set to a specific value like "America/New_York" to control the timezone.
181 pub timezone: Option<String>,
182 /// Extra Chrome command-line arguments appended after standard stealth args.
183 /// E.g. vec!["--use-fake-ui-for-media-stream".into()] to auto-grant camera.
184 pub extra_args: Vec<String>,
185 /// Enable legacy, invasive CDP-marker hiding that proxies `window.document`
186 /// and patches Object reflection APIs. It can break modern SPAs, so it is
187 /// disabled by default. Prefer the normal WebDriver and fingerprint evasions.
188 pub aggressive_cdp_evasion: bool,
189 /// Treat this as a session attached to a user-owned browser. When true,
190 /// `Browser::new_page`/`new_blank_page`/`attach_page` skip injecting the
191 /// evasion script. Defaults to false (set automatically by `Browser::connect*`).
192 pub live_session: bool,
193 /// Drop "detectable" CDP commands like `Runtime.enable` silently.
194 /// Defaults to true. Set to false in connect mode to get full DevTools-like control.
195 pub filter_cdp: bool,
196 /// Ignore TLS certificate errors on every page from creation, before the
197 /// first navigation. `Page::ignore_cert_errors` is applied too late for
198 /// `new_page`'s own initial navigate — this covers self-signed/expired
199 /// certs (e.g. .onion services) hit on the very first load. Defaults to
200 /// false.
201 pub ignore_cert_errors: bool,
202 /// Strip Chromium's `X-Client-Data` request header via CDP Fetch
203 /// interception. Chrome sends this header with field-trial variation IDs on
204 /// requests to Google-owned properties; a fresh automation profile carries
205 /// a distinctive (often empty) variation set that server-side bot scoring
206 /// can read before any JavaScript runs. Also launches Chrome with
207 /// `--disable-field-trial-config`. Defaults to true for spawned stealth
208 /// browsers; ignored (never applied) for attached live sessions.
209 pub strip_x_client_data: bool,
210 /// Resolve timezone and interface language from the browser's apparent
211 /// public IP via a one-shot navigation to Cloudflare's trace endpoint
212 /// before any real page is created. Keeps `Date`/`Intl` and the injected
213 /// `navigator.languages` consistent with IP geolocation instead of a
214 /// random timezone. Ignored when `timezone` is set explicitly and when
215 /// attaching to an existing browser. Defaults to false.
216 pub geo_align: bool,
217}
218
219impl Default for StealthConfig {
220 fn default() -> Self {
221 Self {
222 webgl_spoof: true,
223 canvas_spoof: true,
224 audio_spoof: true,
225 human_mouse: true,
226 human_typing: true,
227 user_agent: None,
228 headless: true,
229 chrome_path: None,
230 runtime_dir: None,
231 sandbox: false,
232 patch_binary: true,
233 viewport_width: 1920,
234 viewport_height: 1080,
235 device_scale_factor: 1.0,
236 debug: false,
237 debug_dir: None,
238 proxy: None,
239 user_data_dir: None,
240 profile_dir: None,
241 proxy_username: None,
242 proxy_password: None,
243 cdp_timeout: 30,
244 timezone: None, // Random from common timezones
245 extra_args: Vec::new(),
246 aggressive_cdp_evasion: false,
247 live_session: false,
248 filter_cdp: true,
249 ignore_cert_errors: false,
250 strip_x_client_data: true,
251 geo_align: false,
252 }
253 }
254}
255
256impl StealthConfig {
257 /// Create a minimal config (no spoofing, no patching)
258 pub fn minimal() -> Self {
259 Self {
260 webgl_spoof: false,
261 canvas_spoof: false,
262 audio_spoof: false,
263 human_mouse: false,
264 human_typing: false,
265 headless: false,
266 patch_binary: false,
267 ..Default::default()
268 }
269 }
270
271 /// Create a visible (non-headless) config
272 pub fn visible() -> Self {
273 Self {
274 headless: false,
275 ..Default::default()
276 }
277 }
278
279 /// Create a debug config (visible, with logging)
280 pub fn debug() -> Self {
281 Self {
282 headless: false,
283 debug: true,
284 ..Default::default()
285 }
286 }
287
288 /// Config tuned for attaching to a user-owned browser via `Browser::connect*`.
289 ///
290 /// Disables anything that touches the user's Chrome state:
291 /// - `live_session` — no evasion script injection on attached tabs
292 /// - `filter_cdp = false` — full DevTools-equivalent CDP access
293 /// - `patch_binary = false` — we don't manage the binary
294 /// - all spoofing off — the user's browser already has its own fingerprint
295 pub fn live() -> Self {
296 Self {
297 live_session: true,
298 filter_cdp: false,
299 patch_binary: false,
300 webgl_spoof: false,
301 canvas_spoof: false,
302 audio_spoof: false,
303 human_mouse: true,
304 human_typing: true,
305 ..Default::default()
306 }
307 }
308}
309
310#[cfg(test)]
311mod tests {
312 use super::StealthConfig;
313
314 #[test]
315 fn default_config_is_headless() {
316 assert!(StealthConfig::default().headless);
317 }
318
319 #[test]
320 fn visible_configs_are_explicitly_not_headless() {
321 assert!(!StealthConfig::visible().headless);
322 assert!(!StealthConfig::debug().headless);
323 }
324}