use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
static BROWSER_COUNTER: AtomicU64 = AtomicU64::new(0);
use crate::cdp::transport::launch_chrome;
use crate::cdp::types::{EmulationSetUserAgentOverride, UserAgentBrandVersion, UserAgentMetadata};
use crate::cdp::{Connection, Transport};
use crate::error::{Error, Result};
use crate::page::Page;
use crate::stealth::fingerprint::Fingerprint;
use crate::stealth::{build_evasion_script_for, find_chrome, ChromePatcher};
use crate::StealthConfig;
fn remove_dir_if_exists(path: &Path) -> std::io::Result<()> {
match std::fs::remove_dir_all(path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
result => result,
}
}
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)))?
}
fn stealth_args(config: &StealthConfig, fingerprint: &Fingerprint) -> Vec<String> {
let mut args = vec![
"--disable-blink-features=AutomationControlled".into(),
"--disable-features=IsolateOrigins,site-per-process,AutomationControlled,EnableAutomation"
.into(),
"--enable-features=NetworkService,NetworkServiceInProcess".into(),
"--disable-infobars".into(),
"--disable-dev-shm-usage".into(),
"--disable-ipc-flooding-protection".into(),
"--disable-renderer-backgrounding".into(),
"--disable-background-timer-throttling".into(),
"--disable-backgrounding-occluded-windows".into(),
"--no-first-run".into(),
"--no-default-browser-check".into(),
"--no-sandbox".into(),
"--disable-default-apps".into(),
"--disable-component-extensions-with-background-pages".into(),
"--disable-hang-monitor".into(),
"--disable-popup-blocking".into(),
"--disable-prompt-on-repost".into(),
"--disable-sync".into(),
"--disable-translate".into(),
"--metrics-recording-only".into(),
"--safebrowsing-disable-auto-update".into(),
"--disable-client-side-phishing-detection".into(),
"--password-store=basic".into(),
"--use-mock-keychain".into(),
"--lang=en-US".into(),
format!(
"--window-size={},{}",
config.viewport_width, config.viewport_height
),
format!(
"--ozone-override-screen-size={},{}",
config.viewport_width, config.viewport_height
),
];
args.push(format!("--user-agent={}", fingerprint.user_agent));
if config.headless {
args.push("--headless=new".into());
}
if let Some(ref profile_dir) = config.profile_dir {
args.push(format!("--profile-directory={}", profile_dir));
}
if let Some(ref proxy) = config.proxy {
args.push(format!("--proxy-server={}", proxy));
}
for arg in &config.extra_args {
args.push(arg.clone());
}
args
}
fn stop_unclaimed_child(child: &mut Child) -> std::io::Result<()> {
if child.try_wait()?.is_some() {
return Ok(());
}
if let Err(kill_error) = child.kill() {
if child.try_wait()?.is_none() {
return Err(kill_error);
}
return Ok(());
}
child.wait()?;
Ok(())
}
struct BrowserProfileGuard {
path: PathBuf,
owned: bool,
}
impl BrowserProfileGuard {
fn create(config: &StealthConfig) -> Result<Self> {
match config.user_data_dir.as_deref() {
Some(path) => {
let path = PathBuf::from(path);
std::fs::create_dir_all(&path)?;
Ok(Self { path, owned: false })
}
None => {
let instance_id = BROWSER_COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"eoka-browser-{}-{}",
std::process::id(),
instance_id
));
remove_dir_if_exists(&path)?;
std::fs::create_dir_all(&path)?;
Ok(Self { path, owned: true })
}
}
}
fn browser_owned_path(&mut self) -> Option<PathBuf> {
if self.owned {
self.owned = false;
Some(self.path.clone())
} else {
None
}
}
}
impl Drop for BrowserProfileGuard {
fn drop(&mut self) {
if self.owned {
if let Err(error) = remove_dir_if_exists(&self.path) {
tracing::warn!("Failed to remove unclaimed browser profile: {}", error);
}
}
}
}
struct PreparedBrowserLaunch {
child: Option<Child>,
ws_url: String,
fingerprint: Option<Fingerprint>,
profile: BrowserProfileGuard,
}
impl Drop for PreparedBrowserLaunch {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
if let Err(error) = stop_unclaimed_child(&mut child) {
tracing::warn!("Failed to clean up unclaimed Chrome launch: {}", error);
}
}
}
}
fn try_attach_existing(profile_dir: &Path, want_headless: bool) -> Result<Option<String>> {
use crate::cdp::discover;
let Some(pid) = discover::read_singleton_lock(profile_dir) else {
return Ok(None);
};
if !discover::pid_is_alive(pid) {
let _ = std::fs::remove_file(profile_dir.join("SingletonLock"));
return Ok(None);
}
if let Some(argv) = discover::read_process_argv(pid) {
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) = discover::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))
}
fn prepare_browser_launch(config: Arc<StealthConfig>) -> Result<PreparedBrowserLaunch> {
let profile = BrowserProfileGuard::create(&config)?;
if !profile.owned {
if let Some(ws_url) = try_attach_existing(&profile.path, config.headless)? {
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: Some(fingerprint),
profile,
});
}
}
let chrome_path = match &config.chrome_path {
Some(path) => PathBuf::from(path),
None => find_chrome()?,
};
let chrome_path = if config.patch_binary && profile.owned {
ChromePatcher::new(&chrome_path)?.get_patched_path()?
} else {
chrome_path
};
let detected_user_agent = if config.user_agent.is_none() {
installed_chrome_user_agent(&chrome_path)
} else {
None
};
let fingerprint = Fingerprint::resolve_for_profile(
config
.user_agent
.as_deref()
.or(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()));
tracing::info!("Launching Chrome from {:?}", chrome_path);
let (child, ws_url) = launch_chrome(&chrome_path, &args)?;
Ok(PreparedBrowserLaunch {
child: Some(child),
ws_url,
fingerprint: Some(fingerprint),
profile,
})
}
#[derive(Debug, Clone)]
pub struct TabInfo {
pub id: String,
pub title: String,
pub url: String,
}
fn ua_override_for(fp: &Fingerprint) -> EmulationSetUserAgentOverride {
let to_brands = |v: Vec<(String, String)>| -> Vec<UserAgentBrandVersion> {
v.into_iter()
.map(|(brand, version)| UserAgentBrandVersion { brand, version })
.collect()
};
let architecture = if fp.webgl_renderer.contains("Apple M") {
"arm"
} else {
"x86"
};
EmulationSetUserAgentOverride {
user_agent: fp.user_agent.clone(),
accept_language: Some("en-US,en;q=0.9".to_string()),
platform: Some(fp.nav_platform().to_string()),
user_agent_metadata: Some(UserAgentMetadata {
brands: to_brands(fp.ch_brands()),
full_version_list: to_brands(fp.ch_full_version_brands()),
platform: fp.ch_platform().to_string(),
platform_version: fp.platform_version.clone(),
architecture: architecture.to_string(),
model: String::new(),
mobile: false,
bitness: "64".to_string(),
wow64: false,
}),
}
}
pub struct Browser {
connection: Connection,
config: Arc<StealthConfig>,
user_data_dir: Option<PathBuf>,
reused: bool,
fingerprint: Option<Fingerprint>,
evasion_script: String,
}
impl Browser {
pub async fn launch() -> Result<Self> {
Self::launch_with_config(StealthConfig::default()).await
}
pub async fn launch_visible() -> Result<Self> {
Self::launch_with_config(StealthConfig::visible()).await
}
pub async fn launch_debug() -> Result<Self> {
Self::launch_with_config(StealthConfig::debug()).await
}
pub async fn launch_with(configure: impl FnOnce(&mut StealthConfig)) -> Result<Self> {
let mut config = StealthConfig::default();
configure(&mut config);
Self::launch_with_config(config).await
}
pub async fn launch_with_config(config: StealthConfig) -> Result<Self> {
let config = Arc::new(config);
let launch_config = Arc::clone(&config);
let mut prepared =
tokio::task::spawn_blocking(move || prepare_browser_launch(launch_config))
.await
.map_err(|error| {
Error::Launch(format!("Browser launch worker failed: {}", error))
})??;
let spawned = prepared.child.is_some();
let transport = match prepared.child.take() {
Some(child) => {
let proxy_auth = match (&config.proxy_username, &config.proxy_password) {
(Some(username), Some(password)) => Some((username.clone(), password.clone())),
_ => None,
};
Transport::new_with_options(child, &prepared.ws_url, proxy_auth, config.cdp_timeout)
.await?
}
None => {
Transport::connect_with_options(
&prepared.ws_url,
config.cdp_timeout,
config.filter_cdp,
)
.await?
}
};
let connection = Connection::new(transport);
let version = connection.version().await?;
tracing::info!("Connected to Chrome: {}", version.product);
let fingerprint = prepared
.fingerprint
.take()
.ok_or_else(|| Error::Launch("Browser launch lost its fingerprint".into()))?;
let user_data_dir = prepared.profile.browser_owned_path();
let evasion_script = build_evasion_script_for(&config, &fingerprint);
Ok(Self {
connection,
config,
user_data_dir,
reused: !spawned,
fingerprint: Some(fingerprint),
evasion_script,
})
}
pub async fn connect(ws_url: &str) -> Result<Self> {
Self::connect_with_config(ws_url, StealthConfig::live()).await
}
pub async fn connect_with_config(ws_url: &str, config: StealthConfig) -> Result<Self> {
let config = Arc::new(config);
let transport = crate::cdp::transport::Transport::connect_with_options(
ws_url,
config.cdp_timeout,
config.filter_cdp,
)
.await?;
let connection = Connection::new(transport);
let version = connection.version().await?;
tracing::info!("Connected to Chrome: {}", version.product);
let (fingerprint, evasion_script) = if config.live_session {
(None, String::new())
} else {
let fp = Fingerprint::resolve(config.user_agent.as_deref(), config.timezone.as_deref());
let script = build_evasion_script_for(&config, &fp);
(Some(fp), script)
};
Ok(Self {
connection,
config,
user_data_dir: None,
reused: false,
fingerprint,
evasion_script,
})
}
pub async fn connect_port(port: u16) -> Result<Self> {
let ws_url = discover_browser_ws(port).await?;
Self::connect(&ws_url).await
}
pub async fn connect_port_with_config(port: u16, config: StealthConfig) -> Result<Self> {
let ws_url = discover_browser_ws(port).await?;
Self::connect_with_config(&ws_url, config).await
}
async fn setup_session(&self, session: &crate::cdp::Session) -> Result<()> {
session.page_enable().await?;
if self.config.proxy_username.is_some() && self.config.proxy_password.is_some() {
session.fetch_enable(true).await?;
}
if self.config.ignore_cert_errors {
session.set_ignore_cert_errors(true).await?;
}
if !self.config.live_session {
if let Some(ref fp) = self.fingerprint {
session.set_user_agent_full(ua_override_for(fp)).await?;
}
session
.add_script_to_evaluate_on_new_document(&self.evasion_script)
.await?;
}
Ok(())
}
pub async fn new_page(&self, url: &str) -> Result<Page> {
let target_id = self
.connection
.create_target("about:blank", None, None)
.await?;
let session = self.connection.attach_to_target(&target_id).await?;
self.setup_session(&session).await?;
let nav_result = session.navigate(url, None).await?;
if let Some(error) = nav_result.error_text {
return Err(Error::Navigation(error));
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
Ok(Page::new(session, Arc::clone(&self.config)))
}
pub async fn new_blank_page(&self) -> Result<Page> {
let target_id = self
.connection
.create_target("about:blank", None, None)
.await?;
let session = self.connection.attach_to_target(&target_id).await?;
self.setup_session(&session).await?;
Ok(Page::new(session, Arc::clone(&self.config)))
}
pub async fn version(&self) -> Result<String> {
let v = self.connection.version().await?;
Ok(v.product)
}
pub async fn tabs(&self) -> Result<Vec<TabInfo>> {
let targets = self.connection.get_targets().await?;
Ok(targets
.into_iter()
.filter(|t| t.r#type == "page")
.map(|t| TabInfo {
id: t.target_id,
title: t.title,
url: t.url,
})
.collect())
}
pub async fn attach_page(&self, target_id: &str) -> Result<Page> {
let session = self.connection.attach_to_target(target_id).await?;
self.setup_session(&session).await?;
Ok(Page::new(session, Arc::clone(&self.config)))
}
pub async fn activate_tab(&self, target_id: &str) -> Result<()> {
self.connection.activate_target(target_id).await
}
pub async fn close_tab(&self, target_id: &str) -> Result<()> {
self.connection.close_target(target_id).await?;
Ok(())
}
pub async fn close(self) -> Result<()> {
if self.config.live_session || self.reused {
self.connection.transport().close().await?;
} else {
self.connection.close().await?;
}
if let Some(ref dir) = self.user_data_dir {
remove_dir_if_exists(dir)?;
}
Ok(())
}
pub async fn disconnect(self) -> Result<()> {
self.connection.transport().close().await
}
}
fn installed_chrome_user_agent(chrome_path: &std::path::Path) -> Option<String> {
let output = Command::new(chrome_path).arg("--version").output().ok()?;
let version = String::from_utf8_lossy(&output.stdout);
let full_version = version.split_whitespace().find(|part| {
let pieces: Vec<_> = part.split('.').collect();
pieces.len() == 4
&& pieces
.iter()
.all(|piece| !piece.is_empty() && piece.bytes().all(|byte| byte.is_ascii_digit()))
})?;
Fingerprint::native_chrome_user_agent(full_version)
}
impl Drop for Browser {
fn drop(&mut self) {
if let Some(ref dir) = self.user_data_dir {
if let Err(error) = remove_dir_if_exists(dir) {
tracing::warn!(
"Failed to remove temporary browser profile while dropping browser: {}",
error
);
}
}
}
}
#[cfg(all(test, unix))]
mod try_attach_existing_tests {
use super::*;
use std::os::unix::fs::symlink;
fn temp_profile_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"eoka-browser-test-{}-{}-{}",
std::process::id(),
name,
fastrand::u64(..)
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn lock_self(dir: &std::path::Path) {
symlink(
format!("some-host-{}", std::process::id()),
dir.join("SingletonLock"),
)
.unwrap();
}
#[test]
fn no_lock_returns_none() {
let dir = temp_profile_dir("no-lock");
assert!(try_attach_existing(&dir, true).unwrap().is_none());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn stale_lock_is_cleared_and_returns_none() {
let dir = temp_profile_dir("stale-lock");
symlink("some-host-2147483647", dir.join("SingletonLock")).unwrap();
assert!(try_attach_existing(&dir, true).unwrap().is_none());
assert!(
!dir.join("SingletonLock").exists(),
"stale lock should have been removed"
);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn headless_mismatch_errors_before_touching_the_network() {
let dir = temp_profile_dir("headless-mismatch");
lock_self(&dir);
let error = try_attach_existing(&dir, true).unwrap_err().to_string();
assert!(
error.contains("non-headless") && error.contains("requesting headless mode"),
"expected a headless/headed mismatch error, got: {}",
error
);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn live_lock_without_debug_port_errors() {
let dir = temp_profile_dir("no-port");
lock_self(&dir);
let error = try_attach_existing(&dir, false).unwrap_err().to_string();
assert!(
error.contains("debug port"),
"expected a missing-debug-port error, got: {}",
error
);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn unresponsive_port_errors() {
let dir = temp_profile_dir("bad-port");
lock_self(&dir);
std::fs::write(dir.join("DevToolsActivePort"), "0\n/devtools/browser/x\n").unwrap();
let error = try_attach_existing(&dir, false).unwrap_err().to_string();
assert!(
error.contains("isn't responding"),
"expected an unresponsive-port error, got: {}",
error
);
std::fs::remove_dir_all(&dir).unwrap();
}
}