rustenium-identity 0.1.3

A versatile stealth overlay for rustenium
Documentation
pub mod identity;
pub mod ua;
pub mod tz;
pub mod error;
pub mod cdp;
pub mod script;
pub mod preset;
pub mod local_proxy_server;

use error::IdentityError;
use local_proxy_server::start_overlay;
use rustenium::browsers::chrome::browser::{ChromeBrowser, ChromeConfig};

pub use identity::*;
pub use error::IdentityError as Error;

/// Configuration for launching an identity-spoofed browser session.
pub struct IdentityConfig {
    pub identity: Identity,
    pub chrome: ChromeConfig,
}

impl From<Identity> for IdentityConfig {
    fn from(identity: Identity) -> Self {
        Self {
            identity,
            chrome: ChromeConfig {
                enable_bidi: false,
                enable_cdp: true,
                ..Default::default()
            },
        }
    }
}

impl IdentityConfig {
    pub fn new(identity: Identity, chrome: ChromeConfig) -> Self {
        Self { identity, chrome }
    }
}

/// A rustenium browser session with an identity applied.
pub struct IdentitySession {
    identity: Identity,
    browser: ChromeBrowser,
}

impl IdentitySession {
    /// Launch a new Chromium instance from the given config.
    /// Applies all CDP emulation overrides and registers the stealth
    /// bootstrap script before returning.
    pub async fn launch(config: impl Into<IdentityConfig>) -> Result<Self, IdentityError> {
        let config = config.into();
        let timezone = tz::resolve_timezone(
            config.identity.timezone.as_deref(),
            config.identity.proxy.as_deref(),
        )
        .await?;

        let mut chrome_config = config.chrome;
        chrome_config.enable_bidi = false;
        chrome_config.enable_cdp = true;

        if let Some(ref proxy_url) = config.identity.proxy {
            if !proxy_url.is_empty() {
                let local_addr = start_overlay(proxy_url)
                    .await
                    .map_err(|e| IdentityError::ProxyError(e.to_string()))?;
                let mut flags = chrome_config.browser_flags.unwrap_or_default();
                flags.push(format!("--proxy-server=http://127.0.0.1:{}", local_addr.port()));
                chrome_config.browser_flags = Some(flags);
            }
        }

        let mut browser = ChromeBrowser::new(chrome_config).await;

        cdp::apply_identity(&mut browser, &config.identity, &timezone).await?;

        Ok(Self {
            identity: config.identity,
            browser,
        })
    }

    /// Access the underlying rustenium ChromeBrowser.
    pub fn browser(&self) -> &ChromeBrowser {
        &self.browser
    }

    /// Mutable access to the underlying rustenium ChromeBrowser.
    pub fn browser_mut(&mut self) -> &mut ChromeBrowser {
        &mut self.browser
    }

    /// Get the identity.
    pub fn identity(&self) -> &Identity {
        &self.identity
    }
}