Skip to main content

rustenium_identity/
lib.rs

1pub mod identity;
2pub mod ua;
3pub mod tz;
4pub mod error;
5pub mod cdp;
6pub mod script;
7pub mod preset;
8
9use error::IdentityError;
10use rustenium::browsers::chrome::browser::{ChromeBrowser, ChromeConfig};
11use rustenium::browsers::cdp_browser::CdpBrowser;
12
13pub use identity::*;
14pub use error::IdentityError as Error;
15
16/// Configuration for launching an identity-spoofed browser session.
17pub struct IdentityConfig {
18    pub identity: Identity,
19    pub chrome: ChromeConfig,
20}
21
22impl From<Identity> for IdentityConfig {
23    fn from(identity: Identity) -> Self {
24        Self {
25            identity,
26            chrome: ChromeConfig {
27                enable_bidi: false,
28                enable_cdp: true,
29                ..Default::default()
30            },
31        }
32    }
33}
34
35impl IdentityConfig {
36    pub fn new(identity: Identity, chrome: ChromeConfig) -> Self {
37        Self { identity, chrome }
38    }
39}
40
41/// A rustenium browser session with an identity applied.
42pub struct IdentitySession {
43    identity: Identity,
44    browser: ChromeBrowser,
45}
46
47impl IdentitySession {
48    /// Launch a new Chromium instance from the given config.
49    /// Applies all CDP emulation overrides and registers the stealth
50    /// bootstrap script before returning.
51    pub async fn launch(config: impl Into<IdentityConfig>) -> Result<Self, IdentityError> {
52        let config = config.into();
53        let timezone = tz::resolve_timezone(
54            config.identity.timezone.as_deref(),
55            config.identity.proxy.as_deref(),
56        )
57        .await?;
58
59        let mut chrome_config = config.chrome;
60
61        // Disable BiDi
62        chrome_config.enable_bidi = false;
63        // Ensure CDP is enabled
64        chrome_config.enable_cdp = true;
65
66        // Add proxy flag if set on identity
67        if let Some(ref proxy) = config.identity.proxy {
68            if !proxy.is_empty() {
69                let mut flags = chrome_config.browser_flags.unwrap_or_default();
70                flags.push(format!("--proxy-server={}", proxy));
71                chrome_config.browser_flags = Some(flags);
72            }
73        }
74
75        let mut browser = ChromeBrowser::new(chrome_config).await;
76
77        cdp::apply_identity(&mut browser, &config.identity, &timezone).await?;
78
79        Ok(Self {
80            identity: config.identity,
81            browser,
82        })
83    }
84
85    /// Access the underlying rustenium ChromeBrowser.
86    pub fn browser(&self) -> &ChromeBrowser {
87        &self.browser
88    }
89
90    /// Mutable access to the underlying rustenium ChromeBrowser.
91    pub fn browser_mut(&mut self) -> &mut ChromeBrowser {
92        &mut self.browser
93    }
94
95    /// Get the identity.
96    pub fn identity(&self) -> &Identity {
97        &self.identity
98    }
99}