eoka 0.15.0

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! Launch and session configuration: [`StealthConfig`], [`Mode`] and [`Proxy`].

use crate::util::Redacted;

/// How eoka drives a browser.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
    /// Fingerprint, evasion scripts and viewport on every page, and the
    /// transport refuses detectable CDP commands such as `Runtime.enable`.
    #[default]
    Stealth,
    /// A plain attached session: no fingerprint, evasions or viewport
    /// override, full CDP access, and `restore_state` merges cookies and
    /// storage. Used for a Chrome eoka did not spawn.
    Plain,
}

/// A proxy server, optionally with credentials. `Debug` redacts the
/// credentials, including any embedded in `server`.
#[derive(Clone, PartialEq, Eq)]
pub struct Proxy {
    /// Proxy server URL (e.g. "http://host:port"), passed to `--proxy-server`.
    pub server: String,
    /// Username answered to explicit `Proxy` auth challenges.
    pub username: Option<String>,
    /// Password answered to explicit `Proxy` auth challenges.
    pub password: Option<String>,
}

impl Proxy {
    /// A proxy without credentials.
    pub fn new(server: impl Into<String>) -> Self {
        Self {
            server: server.into(),
            username: None,
            password: None,
        }
    }

    /// Answer `Proxy` auth challenges with these credentials.
    #[must_use]
    pub fn with_credentials(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        self.username = Some(username.into());
        self.password = Some(password.into());
        self
    }
}

impl std::fmt::Debug for Proxy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self {
            server,
            username,
            password,
        } = self;
        let mut output = f.debug_struct("Proxy");
        // A proxy URL can embed credentials.
        if server.contains('@') {
            output.field("server", &Redacted);
        } else {
            output.field("server", server);
        }
        output
            .field("username", &username.as_ref().map(|_| Redacted))
            .field("password", &password.as_ref().map(|_| Redacted))
            .finish()
    }
}

/// Configuration for stealth features. `Debug` omits proxy credentials.
#[derive(Clone)]
pub struct StealthConfig {
    /// Stealth (default) or a plain session. See [`Mode`].
    pub mode: Mode,
    /// Spoof the WebGL vendor/renderer and add canvas and audio noise.
    /// Defaults to true.
    pub fingerprint_spoofing: 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,
    /// Opt-in: rewrite ChromeDriver automation markers in a cached private
    /// copy of Chrome. Defaults to false; stock Chrome has none, so it then
    /// launches the original binary unchanged. See `stealth::patcher`.
    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,
    /// Directory for debug screenshots (defaults to current directory)
    pub debug_dir: Option<String>,
    /// Proxy server and optional credentials.
    pub proxy: Option<Proxy>,
    /// 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>,
    /// CDP command, automatic-reply write, and WebSocket connection timeout
    /// (default: 30s, increase for slow proxies). Used as given, without rounding.
    pub cdp_timeout: std::time::Duration,
    /// 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>,
    /// 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,
    /// 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,
}

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 {
            mode,
            fingerprint_spoofing,
            user_agent,
            headless,
            chrome_path,
            runtime_dir,
            sandbox,
            patch_binary,
            viewport_width,
            viewport_height,
            device_scale_factor,
            debug_dir,
            proxy,
            user_data_dir,
            profile_dir,
            cdp_timeout,
            timezone,
            extra_args,
            ignore_cert_errors,
            geo_align,
        } = self;
        let mut output = f.debug_struct("StealthConfig");
        output
            .field("mode", mode)
            .field("fingerprint_spoofing", fingerprint_spoofing)
            .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_dir", debug_dir)
            // `Proxy`'s Debug redacts its credentials.
            .field("proxy", proxy)
            .field("user_data_dir", user_data_dir)
            .field("profile_dir", profile_dir)
            .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("ignore_cert_errors", ignore_cert_errors)
            .field("geo_align", geo_align)
            .finish()
    }
}

impl Default for StealthConfig {
    fn default() -> Self {
        Self {
            mode: Mode::Stealth,
            fingerprint_spoofing: true,
            user_agent: None,
            headless: true,
            chrome_path: None,
            runtime_dir: None,
            sandbox: true,
            patch_binary: false,
            viewport_width: 1920,
            viewport_height: 1080,
            device_scale_factor: 1.0,
            debug_dir: None,
            proxy: None,
            user_data_dir: None,
            profile_dir: None,
            cdp_timeout: crate::cdp::transport::DEFAULT_CDP_TIMEOUT,
            timezone: None, // Random from common timezones
            extra_args: Vec::new(),
            ignore_cert_errors: false,
            geo_align: false,
        }
    }
}

impl StealthConfig {
    /// Proxy credentials the transport answers `Proxy` challenges with.
    pub(crate) fn proxy_credentials(&self) -> Option<(String, String)> {
        let proxy = self.proxy.as_ref()?;
        proxy.username.clone().zip(proxy.password.clone())
    }

    /// [`Mode::Plain`]: no fingerprint, evasions or viewport override, and
    /// live-attach semantics.
    pub(crate) fn live_session(&self) -> bool {
        self.mode == Mode::Plain
    }

    /// [`Mode::Stealth`]: the transport refuses detectable CDP commands.
    pub(crate) fn filter_cdp(&self) -> bool {
        self.mode == Mode::Stealth
    }

    /// Create a minimal config (no spoofing, no patching)
    pub fn minimal() -> Self {
        Self {
            fingerprint_spoofing: false,
            headless: false,
            ..Default::default()
        }
    }

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

    /// Config tuned for attaching to a user-owned browser via `Browser::connect*`.
    ///
    /// Disables anything that touches the user's Chrome state:
    /// - [`Mode::Plain`] — no evasion script injection on attached tabs and
    ///   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 {
            mode: Mode::Plain,
            fingerprint_spoofing: false,
            ..Default::default()
        }
    }
}

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

    #[test]
    fn debug_output_omits_proxy_credentials() {
        let printed = format!(
            "{:?}",
            StealthConfig {
                proxy: Some(
                    Proxy::new("http://embedded-user:embedded-pass@proxy.test:8080")
                        .with_credentials("named-user", "named-pass")
                ),
                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("password: Some(<redacted>)"));

        let plain = StealthConfig {
            proxy: Some(Proxy::new("http://proxy.test:8080")),
            ..Default::default()
        };
        let printed = format!("{plain:?}");
        assert!(printed.contains("http://proxy.test:8080"), "{printed}");
        assert!(printed.contains("password: None"), "{printed}");
        assert!(format!("{:?}", StealthConfig::default()).contains("proxy: 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,
            },
            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 binary_patching_is_opt_in() {
        assert!(!StealthConfig::default().patch_binary);
        assert!(!StealthConfig::visible().patch_binary);
    }

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