eoka 0.16.0

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! Chrome launch preparation, profile ownership and identity selection.

mod args;
mod version_cache;

use super::discovery::find_chrome;
use crate::cdp::transport::{
    chrome_version_output, launch_chrome_with_profile_dir, stop_child, RuntimeDirectory,
};
use crate::stealth::{fingerprint::Fingerprint, ChromePatcher};
use crate::{Error, Result, StealthConfig};
use args::stealth_args;
use std::{
    path::{Path, PathBuf},
    process::Child,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

pub(super) struct LaunchCancellation(pub(super) Arc<AtomicBool>);

impl LaunchCancellation {
    pub(super) fn new() -> Self {
        Self(Arc::new(AtomicBool::new(false)))
    }
}

impl Drop for LaunchCancellation {
    fn drop(&mut self) {
        self.0.store(true, Ordering::Release);
    }
}

pub(super) async fn discover_browser_ws(port: u16) -> Result<String> {
    tokio::task::spawn_blocking(move || {
        crate::cdp::discover::discover_browser_ws("127.0.0.1", port)
    })
    .await
    .map_err(|error| Error::transport(format!("Browser discovery worker failed: {error}")))?
}

/// Profile location; ephemeral profiles are owned by the runtime directory.
pub(super) struct BrowserProfile {
    path: PathBuf,
    owned: bool,
}

impl BrowserProfile {
    fn create(config: &StealthConfig, runtime: &RuntimeDirectory) -> Result<Self> {
        let (path, owned) = match config.user_data_dir.as_deref() {
            Some(path) => (PathBuf::from(path), false),
            None => (runtime.path().join("profile"), true),
        };
        if owned {
            #[cfg(unix)]
            {
                use std::os::unix::fs::DirBuilderExt;
                std::fs::DirBuilder::new().mode(0o700).create(&path)?;
            }
            #[cfg(not(unix))]
            std::fs::create_dir(&path)?;
        } else {
            std::fs::create_dir_all(&path)?;
        }
        Ok(Self { path, owned })
    }
}

/// Result of synchronous browser preparation. Until the child is transferred
/// to `Transport`, dropping this value kills Chrome and reclaims its profile.
/// `child` is `None` when we attached to an already-running Chrome instead
/// of spawning one (see `try_attach_existing`).
pub(super) struct PreparedBrowserLaunch {
    pub(super) child: Option<Child>,
    pub(super) ws_url: String,
    pub(super) fingerprint: Fingerprint,
    pub(super) runtime: Option<RuntimeDirectory>,
}

impl Drop for PreparedBrowserLaunch {
    fn drop(&mut self) {
        if let Some(mut child) = self.child.take() {
            if let Err(error) = stop_child(&mut child) {
                tracing::warn!("Failed to clean up unclaimed Chrome launch: {}", error);
            }
        }
    }
}

/// Check whether a Chrome instance is already running on `profile_dir` and,
/// if so, return the ws:// URL to attach to instead of spawning a second
/// process. A second `--user-data-dir=<same dir>` launch would silently be
/// handed off to the running instance over Chrome's `SingletonSocket` and
/// exit without ever printing a DevTools URL, so this must run first.
///
/// Returns `Ok(None)` when there's nothing to attach to (no lock, a stale
/// lock that was just cleared, or a platform where reuse detection isn't
/// implemented) — the caller should spawn normally. Returns `Err` when a
/// live instance exists but can't safely be attached to (headless/headed
/// mismatch, no debug port, or an unresponsive port).
fn try_attach_existing(
    profile_dir: &Path,
    want_headless: bool,
    require_sandbox: bool,
) -> Result<Option<String>> {
    use crate::cdp::{discover, profile};

    let Some(pid) = profile::read_singleton_lock(profile_dir) else {
        return Ok(None);
    };

    if !profile::pid_is_alive(pid) {
        // Stale lock left behind by a crashed/killed Chrome. Clear it so a
        // normal spawn below can proceed, mirroring what Chrome itself does.
        let _ = std::fs::remove_file(profile_dir.join("SingletonLock"));
        return Ok(None);
    }

    let argv = profile::read_process_argv(pid);
    // Sandboxing is the default, so reuse stays possible, but only of the
    // same pid we attach to, verifiably launched without sandbox-disabling
    // flags. Unreadable argv is unverified, never assumed sandboxed.
    if require_sandbox
        && argv
            .as_ref()
            .is_none_or(|argv| argv.iter().any(|arg| disables_sandbox(arg)))
    {
        return Err(Error::launch(format!(
            "A Chrome instance (pid {}) is already running on profile {} without a verifiable \
             sandbox; close it, or set StealthConfig.sandbox = false to borrow it",
            pid,
            profile_dir.display()
        )));
    }
    // Check the cheap local signal before touching the network — a
    // headless/headed mismatch always fails the attach, so there's no
    // reason to round-trip to Chrome's DevTools port first.
    if let Some(argv) = argv {
        let running_headless = argv.iter().any(|arg| arg.starts_with("--headless"));
        if running_headless != want_headless {
            let (running, requested) = if running_headless {
                ("headless", "headed")
            } else {
                ("non-headless", "headless")
            };
            return Err(Error::launch(format!(
                "A {} Chrome instance (pid {}) is already running on profile {}; close it \
                 before requesting {} mode, or drop that flag for this launch",
                running,
                pid,
                profile_dir.display(),
                requested
            )));
        }
    }

    let Some(port) = profile::read_devtools_active_port(profile_dir) else {
        return Err(Error::launch(format!(
            "A Chrome instance (pid {}) is already running on profile {}, but it wasn't \
             launched with a debug port; close it first or relaunch it with \
             --remote-debugging-port",
            pid,
            profile_dir.display()
        )));
    };

    let ws_url = discover::discover_browser_ws("127.0.0.1", port).map_err(|e| {
        Error::launch(format!(
            "A Chrome instance (pid {}) is already running on profile {}, but its DevTools \
             port {} isn't responding: {}",
            pid,
            profile_dir.display(),
            port,
            e
        ))
    })?;

    Ok(Some(ws_url))
}

pub(super) fn prepare_browser_launch(
    config: &StealthConfig,
    cancelled: &AtomicBool,
) -> Result<PreparedBrowserLaunch> {
    if cancelled.load(Ordering::Acquire) {
        return Err(Error::launch("Browser launch was cancelled"));
    }
    crate::cdp::types::EmulationSetDeviceMetricsOverride::new(
        config.viewport_width,
        config.viewport_height,
        config.device_scale_factor,
    )?;
    validate_sandbox_args(config)?;
    let explicit_chrome = config
        .chrome_path
        .as_deref()
        .map(|path| validate_executable(Path::new(path)))
        .transpose()?;
    let runtime = RuntimeDirectory::create(config.runtime_dir.as_deref())?;
    let profile = BrowserProfile::create(config, &runtime)?;

    // Only a durable, user-owned profile can already have a live Chrome on
    // it — ephemeral profiles are freshly created above and can't collide.
    if !profile.owned {
        if (config.chrome_path.is_some() || config.runtime_dir.is_some())
            && crate::cdp::profile::read_singleton_lock(&profile.path)
                .is_some_and(crate::cdp::profile::pid_is_alive)
        {
            return Err(Error::launch(
                "A Chrome instance is already running on this profile; explicit executable or runtime policy requires a new process",
            ));
        }
        if let Some(ws_url) = try_attach_existing(&profile.path, config.headless, config.sandbox)? {
            tracing::info!("Reusing running Chrome on profile {:?}", profile.path);
            let fingerprint = Fingerprint::resolve_for_profile(
                config.user_agent.as_deref(),
                config.timezone.as_deref(),
                Some(profile.path.as_path()),
            )?;
            return Ok(PreparedBrowserLaunch {
                child: None,
                ws_url,
                fingerprint,
                runtime: None,
            });
        }
    }

    let chrome_path = match explicit_chrome {
        Some(path) => path,
        None => validate_executable(&find_chrome()?)?,
    };

    // Patching a browser binary is not appropriate for a durable user-owned
    // profile. Let that profile provide continuity instead of fresh spoofing.
    let chrome_path = if config.patch_binary && profile.owned {
        ChromePatcher::for_launch(&chrome_path, runtime.path())?.get_patched_path()?
    } else {
        chrome_path
    };

    let detected_user_agent = if config.user_agent.is_none() {
        installed_chrome_user_agent(&chrome_path, runtime.path(), cancelled)
    } else {
        None
    };
    let fingerprint = Fingerprint::resolve_for_launch(
        config.user_agent.as_deref(),
        detected_user_agent.as_deref(),
        config.timezone.as_deref(),
        (!profile.owned).then_some(profile.path.as_path()),
    )?;

    let mut args = stealth_args(config, &fingerprint);
    args.push(format!("--user-data-dir={}", profile.path.display()));
    // An eoka-owned profile has no tabs to restore and every page is opened
    // through CDP, so skip the startup window: Chrome then answers DevTools
    // about 30ms sooner, and the first page opens no later.
    if profile.owned && !config.live_session() && !args.iter().any(|a| a == "--no-startup-window") {
        args.push("--no-startup-window".into());
    }

    tracing::info!("Launching Chrome from {:?}", chrome_path);
    let (child, ws_url) = launch_chrome_with_profile_dir(
        &chrome_path,
        &args,
        &profile.path,
        config.live_session(),
        runtime.path(),
        cancelled,
    )?;
    Ok(PreparedBrowserLaunch {
        child: Some(child),
        ws_url,
        fingerprint,
        runtime: Some(runtime),
    })
}

fn validate_executable(path: &Path) -> Result<PathBuf> {
    if !path.is_absolute() {
        return Err(Error::invalid_argument("chrome_path must be absolute"));
    }
    let metadata = std::fs::metadata(path).map_err(|error| {
        Error::invalid_argument(format!(
            "Invalid Chrome executable {}: {}",
            path.display(),
            error
        ))
    })?;
    if !metadata.is_file() {
        return Err(Error::invalid_argument(format!(
            "Chrome executable is not a file: {}",
            path.display()
        )));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if metadata.permissions().mode() & 0o111 == 0 {
            return Err(Error::invalid_argument(format!(
                "Chrome executable is not executable: {}",
                path.display()
            )));
        }
    }
    std::fs::File::open(path).map_err(|error| {
        Error::invalid_argument(format!(
            "Cannot read Chrome executable {}: {}",
            path.display(),
            error
        ))
    })?;
    Ok(std::fs::canonicalize(path)?)
}

/// Chromium accepts `--`, `-` (and `/` on Windows) switch prefixes and
/// matches names case-insensitively on Windows, so normalize before matching.
/// Includes switches that run sandboxed code in the browser process.
fn disables_sandbox(arg: &str) -> bool {
    let name = arg.split('=').next().unwrap_or(arg);
    let name = name.trim_start_matches(['-', '/']).to_ascii_lowercase();
    matches!(
        name.as_str(),
        "no-sandbox"
            | "no-sandbox-and-elevated"
            | "disable-sandbox"
            | "disable-setuid-sandbox"
            | "disable-seccomp-filter-sandbox"
            | "disable-namespace-sandbox"
            | "disable-gpu-sandbox"
            | "no-zygote"
            | "single-process"
            | "in-process-gpu"
    )
}

fn validate_sandbox_args(config: &StealthConfig) -> Result<()> {
    for arg in &config.extra_args {
        if disables_sandbox(arg) {
            return Err(Error::invalid_argument(format!(
                "Sandbox arguments must use StealthConfig.sandbox, not extra_args: {arg}",
            )));
        }
    }
    Ok(())
}

fn installed_chrome_user_agent(
    chrome_path: &Path,
    runtime: &Path,
    cancelled: &AtomicBool,
) -> Option<String> {
    let version = version_cache::lookup(chrome_path, || {
        let output = chrome_version_output(chrome_path, runtime, cancelled)?;
        parse_full_version(&String::from_utf8_lossy(&output))
    })?;
    Fingerprint::native_chrome_user_agent(&version)
}

/// The first `a.b.c.d` token of `chrome --version` output.
fn parse_full_version(output: &str) -> Option<String> {
    output
        .split_whitespace()
        .find(|part| is_full_version(part))
        .map(str::to_owned)
}

/// Whether `version` is exactly four dot-separated runs of ASCII digits.
fn is_full_version(version: &str) -> bool {
    version.split('.').count() == 4
        && version
            .split('.')
            .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
}

#[cfg(all(test, unix))]
mod tests;