Skip to main content

stygian_browser/
stealth.rs

1//! Stealth configuration and anti-detection features
2//!
3//! Provides navigator property spoofing and CDP injection scripts that make
4//! a headless Chrome instance appear identical to a real browser.
5//!
6//! # Overview
7//!
8//! 1. **Navigator spoofing** — Override `navigator.webdriver`, `platform`,
9//!    `userAgent`, `hardwareConcurrency`, `deviceMemory`, `maxTouchPoints`,
10//!    and `vendor` via `Object.defineProperty` so properties are non-configurable
11//!    and non-writable (harder to detect the override).
12//!
13//! 2. **WebGL spoofing** — Replace `getParameter` on `WebGLRenderingContext` and
14//!    `WebGL2RenderingContext` to return controlled vendor/renderer strings.
15//!
16//! # Example
17//!
18//! ```
19//! use stygian_browser::stealth::{NavigatorProfile, StealthConfig, StealthProfile};
20//!
21//! let profile = NavigatorProfile::windows_chrome();
22//! let script = StealthProfile::new(StealthConfig::default(), profile).injection_script();
23//! assert!(script.contains("'webdriver'"));
24//! ```
25
26use serde::{Deserialize, Serialize};
27
28// ─── StealthConfig ────────────────────────────────────────────────────────────
29
30/// Feature flags controlling which stealth techniques are active.
31///
32/// # Example
33///
34/// ```
35/// use stygian_browser::stealth::StealthConfig;
36/// let cfg = StealthConfig::default();
37/// assert!(cfg.spoof_navigator);
38/// ```
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct StealthConfig {
41    /// Override navigator properties (webdriver, platform, userAgent, etc.)
42    pub spoof_navigator: bool,
43    /// Replace WebGL getParameter with controlled vendor/renderer strings.
44    pub randomize_webgl: bool,
45    /// Randomise Canvas `toDataURL` fingerprint (stub — needs canvas noise).
46    pub randomize_canvas: bool,
47    /// Enable human-like behaviour simulation.
48    pub human_behavior: bool,
49    /// Enable CDP leak protection (remove `Runtime.enable` artifacts).
50    pub protect_cdp: bool,
51}
52
53impl Default for StealthConfig {
54    fn default() -> Self {
55        Self {
56            spoof_navigator: true,
57            randomize_webgl: true,
58            randomize_canvas: true,
59            human_behavior: true,
60            protect_cdp: true,
61        }
62    }
63}
64
65impl StealthConfig {
66    /// All stealth features enabled (maximum evasion).
67    pub fn paranoid() -> Self {
68        Self::default()
69    }
70
71    /// Only navigator and CDP protection (low overhead).
72    pub const fn minimal() -> Self {
73        Self {
74            spoof_navigator: true,
75            randomize_webgl: false,
76            randomize_canvas: false,
77            human_behavior: false,
78            protect_cdp: true,
79        }
80    }
81
82    /// All stealth features disabled.
83    pub const fn disabled() -> Self {
84        Self {
85            spoof_navigator: false,
86            randomize_webgl: false,
87            randomize_canvas: false,
88            human_behavior: false,
89            protect_cdp: false,
90        }
91    }
92}
93
94// ─── NavigatorProfile ─────────────────────────────────────────────────────────
95
96/// A bundle of navigator property values that together form a convincing
97/// browser identity.
98///
99/// All properties are validated at construction time to guarantee that
100/// `platform` matches the OS fragment in `user_agent`.
101///
102/// # Example
103///
104/// ```
105/// use stygian_browser::stealth::NavigatorProfile;
106/// let p = NavigatorProfile::mac_chrome();
107/// assert_eq!(p.platform, "MacIntel");
108/// assert!(p.user_agent.contains("Mac OS X"));
109/// ```
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct NavigatorProfile {
112    /// Full `User-Agent` string (`navigator.userAgent` **and** the HTTP header).
113    pub user_agent: String,
114    /// Platform string e.g. `"Win32"`, `"MacIntel"`, `"Linux x86_64"`.
115    pub platform: String,
116    /// Browser vendor (`"Google Inc."`).
117    pub vendor: String,
118    /// Logical CPU core count. Realistic values: 4, 8, 12, 16.
119    pub hardware_concurrency: u8,
120    /// Device RAM in GiB. Realistic values: 4, 8, 16.
121    pub device_memory: u8,
122    /// Maximum simultaneous touch points (0 = no touchscreen, 10 = tablet/phone).
123    pub max_touch_points: u8,
124    /// WebGL vendor string (only used when `StealthConfig::randomize_webgl` is true).
125    pub webgl_vendor: String,
126    /// WebGL renderer string.
127    pub webgl_renderer: String,
128}
129
130impl NavigatorProfile {
131    /// A typical Windows 10 Chrome 131 profile.
132    pub fn windows_chrome() -> Self {
133        Self {
134            user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \
135                         (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
136                .to_string(),
137            platform: "Win32".to_string(),
138            vendor: "Google Inc.".to_string(),
139            hardware_concurrency: 8,
140            device_memory: 8,
141            max_touch_points: 0,
142            webgl_vendor: "Google Inc. (NVIDIA)".to_string(),
143            webgl_renderer:
144                "ANGLE (NVIDIA, NVIDIA GeForce GTX 1650 Direct3D11 vs_5_0 ps_5_0, D3D11)"
145                    .to_string(),
146        }
147    }
148
149    /// A typical macOS Chrome 131 profile.
150    pub fn mac_chrome() -> Self {
151        Self {
152            user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 \
153                         (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
154                .to_string(),
155            platform: "MacIntel".to_string(),
156            vendor: "Google Inc.".to_string(),
157            hardware_concurrency: 8,
158            device_memory: 8,
159            max_touch_points: 0,
160            webgl_vendor: "Google Inc. (Intel)".to_string(),
161            webgl_renderer: "ANGLE (Intel, Apple M1 Pro, OpenGL 4.1)".to_string(),
162        }
163    }
164
165    /// A typical Linux Chrome 131 profile (common in data-centre environments).
166    pub fn linux_chrome() -> Self {
167        Self {
168            user_agent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
169                         (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
170                .to_string(),
171            platform: "Linux x86_64".to_string(),
172            vendor: "Google Inc.".to_string(),
173            hardware_concurrency: 4,
174            device_memory: 4,
175            max_touch_points: 0,
176            webgl_vendor: "Mesa/X.org".to_string(),
177            webgl_renderer: "llvmpipe (LLVM 15.0.7, 256 bits)".to_string(),
178        }
179    }
180}
181
182impl Default for NavigatorProfile {
183    fn default() -> Self {
184        Self::mac_chrome()
185    }
186}
187
188// ─── StealthProfile ───────────────────────────────────────────────────────────
189
190/// Combines [`StealthConfig`] (feature flags) with a [`NavigatorProfile`]
191/// (identity values) and produces a single JavaScript injection script.
192///
193/// # Example
194///
195/// ```
196/// use stygian_browser::stealth::{NavigatorProfile, StealthConfig, StealthProfile};
197///
198/// let profile = StealthProfile::new(StealthConfig::default(), NavigatorProfile::windows_chrome());
199/// let script = profile.injection_script();
200/// assert!(script.contains("Win32"));
201/// assert!(script.contains("NVIDIA"));
202/// ```
203pub struct StealthProfile {
204    config: StealthConfig,
205    navigator: NavigatorProfile,
206}
207
208impl StealthProfile {
209    /// Build a new profile from config flags and identity values.
210    pub const fn new(config: StealthConfig, navigator: NavigatorProfile) -> Self {
211        Self { config, navigator }
212    }
213
214    /// Generate the JavaScript to inject via
215    /// `Page.addScriptToEvaluateOnNewDocument`.
216    ///
217    /// Returns an empty string if all stealth flags are disabled.
218    pub fn injection_script(&self) -> String {
219        let mut parts: Vec<String> = Vec::new();
220
221        if self.config.spoof_navigator {
222            parts.push(self.navigator_spoof_script());
223        }
224
225        if self.config.randomize_webgl {
226            parts.push(self.webgl_spoof_script());
227        }
228
229        // Always inject chrome-object and userAgentData spoofing when navigator
230        // spoofing is active — both are Cloudflare Turnstile detection vectors.
231        if self.config.spoof_navigator {
232            parts.push(Self::chrome_object_script());
233            parts.push(self.user_agent_data_script());
234        }
235
236        if parts.is_empty() {
237            return String::new();
238        }
239
240        // Wrap in an IIFE so nothing leaks to page scope
241        format!(
242            "(function() {{\n  'use strict';\n{}\n}})();",
243            parts.join("\n\n")
244        )
245    }
246
247    // ─── Private helpers ──────────────────────────────────────────────────────
248
249    fn navigator_spoof_script(&self) -> String {
250        let nav = &self.navigator;
251
252        // Helper: Object.defineProperty with a fixed non-configurable value
253        // so the spoofed value cannot be overwritten by anti-bot scripts.
254        format!(
255            r"  // --- Navigator spoofing ---
256  (function() {{
257    const defineReadOnly = (target, prop, value) => {{
258      try {{
259        Object.defineProperty(target, prop, {{
260          get: () => value,
261          enumerable: true,
262          configurable: false,
263        }});
264      }} catch (_) {{}}
265    }};
266
267    // Remove the webdriver flag at both the prototype and instance levels.
268    // Cloudflare and pixelscan probe Navigator.prototype directly via
269    // Object.getOwnPropertyDescriptor(Navigator.prototype, 'webdriver').
270    // In real Chrome the property is enumerable:false — matching that is
271    // essential; enumerable:true is a Turnstile detection signal.
272    // configurable:true is kept so polyfills don't throw on a second
273    // defineProperty call.
274    try {{
275      Object.defineProperty(Navigator.prototype, 'webdriver', {{
276        get: () => undefined,
277        enumerable: false,
278        configurable: true,
279      }});
280    }} catch (_) {{}}
281    defineReadOnly(navigator, 'webdriver', undefined);
282
283    // Platform / identity
284    defineReadOnly(navigator, 'platform',           {platform:?});
285    defineReadOnly(navigator, 'userAgent',          {user_agent:?});
286    defineReadOnly(navigator, 'vendor',             {vendor:?});
287    defineReadOnly(navigator, 'hardwareConcurrency', {hwc});
288    defineReadOnly(navigator, 'deviceMemory',        {dm});
289    defineReadOnly(navigator, 'maxTouchPoints',       {mtp});
290
291    // Permissions API — real browsers resolve 'notifications' as 'default'
292    if (navigator.permissions && navigator.permissions.query) {{
293      const origQuery = navigator.permissions.query.bind(navigator.permissions);
294      navigator.permissions.query = (params) => {{
295        if (params && params.name === 'notifications') {{
296          return Promise.resolve({{ state: Notification.permission, onchange: null }});
297        }}
298        return origQuery(params);
299      }};
300    }}
301  }})();",
302            platform = nav.platform,
303            user_agent = nav.user_agent,
304            vendor = nav.vendor,
305            hwc = nav.hardware_concurrency,
306            dm = nav.device_memory,
307            mtp = nav.max_touch_points,
308        )
309    }
310
311    fn chrome_object_script() -> String {
312        // Cloudflare Turnstile checks window.chrome.runtime, window.chrome.csi,
313        // and window.chrome.loadTimes — all present in real Chrome but absent
314        // in headless. Stubbing them removes these detection signals.
315        r"  // --- window.chrome object spoofing ---
316  (function() {
317    if (!window.chrome) {
318      Object.defineProperty(window, 'chrome', {
319        value: {},
320        enumerable: true,
321        configurable: false,
322        writable: false,
323      });
324    }
325    const chrome = window.chrome;
326    // chrome.runtime — checked by Turnstile; needs at least an object with
327    // id and connect stubs to pass duck-type checks.
328    if (!chrome.runtime) {
329      chrome.runtime = {
330        id: undefined,
331        connect: () => {},
332        sendMessage: () => {},
333        onMessage: { addListener: () => {}, removeListener: () => {} },
334      };
335    }
336    // chrome.csi and chrome.loadTimes — legacy APIs present in real Chrome.
337    if (!chrome.csi) {
338      chrome.csi = () => ({
339        startE: Date.now(),
340        onloadT: Date.now(),
341        pageT: 0,
342        tran: 15,
343      });
344    }
345    if (!chrome.loadTimes) {
346      chrome.loadTimes = () => ({
347        requestTime: Date.now() / 1000,
348        startLoadTime: Date.now() / 1000,
349        commitLoadTime: Date.now() / 1000,
350        finishDocumentLoadTime: Date.now() / 1000,
351        finishLoadTime: Date.now() / 1000,
352        firstPaintTime: Date.now() / 1000,
353        firstPaintAfterLoadTime: 0,
354        navigationType: 'Other',
355        wasFetchedViaSpdy: false,
356        wasNpnNegotiated: true,
357        npnNegotiatedProtocol: 'h2',
358        wasAlternateProtocolAvailable: false,
359        connectionInfo: 'h2',
360      });
361    }
362  })();"
363            .to_string()
364    }
365
366    fn user_agent_data_script(&self) -> String {
367        let nav = &self.navigator;
368        // Extract the major Chrome version from the UA string so that
369        // navigator.userAgentData.brands is consistent with navigator.userAgent.
370        // Mismatch between the two is a primary Cloudflare JA3/UA coherence check.
371        let version = nav
372            .user_agent
373            .split("Chrome/")
374            .nth(1)
375            .and_then(|s| s.split('.').next())
376            .unwrap_or("131");
377        let mobile = nav.max_touch_points > 0;
378        let platform = if nav.platform.contains("Win") {
379            "Windows"
380        } else if nav.platform.contains("Mac") {
381            "macOS"
382        } else {
383            "Linux"
384        };
385
386        format!(
387            r"  // --- navigator.userAgentData spoofing ---
388  (function() {{
389    const uaData = {{
390      brands: [
391        {{ brand: 'Google Chrome',  version: '{version}' }},
392        {{ brand: 'Chromium',       version: '{version}' }},
393        {{ brand: 'Not=A?Brand',    version: '99'        }},
394      ],
395      mobile: {mobile},
396      platform: '{platform}',
397      getHighEntropyValues: (hints) => Promise.resolve({{
398        brands: [
399          {{ brand: 'Google Chrome',  version: '{version}' }},
400          {{ brand: 'Chromium',       version: '{version}' }},
401          {{ brand: 'Not=A?Brand',    version: '99'        }},
402        ],
403        mobile: {mobile},
404        platform: '{platform}',
405        architecture: 'x86',
406        bitness: '64',
407        model: '',
408        platformVersion: '10.0.0',
409        uaFullVersion: '{version}.0.0.0',
410        fullVersionList: [
411          {{ brand: 'Google Chrome',  version: '{version}.0.0.0' }},
412          {{ brand: 'Chromium',       version: '{version}.0.0.0' }},
413          {{ brand: 'Not=A?Brand',    version: '99.0.0.0'        }},
414        ],
415      }}),
416      toJSON: () => ({{
417        brands: [
418          {{ brand: 'Google Chrome',  version: '{version}' }},
419          {{ brand: 'Chromium',       version: '{version}' }},
420          {{ brand: 'Not=A?Brand',    version: '99'        }},
421        ],
422        mobile: {mobile},
423        platform: '{platform}',
424      }}),
425    }};
426    try {{
427      Object.defineProperty(navigator, 'userAgentData', {{
428        get: () => uaData,
429        enumerable: true,
430        configurable: false,
431      }});
432    }} catch (_) {{}}
433  }})();"
434        )
435    }
436
437    fn webgl_spoof_script(&self) -> String {
438        let nav = &self.navigator;
439
440        format!(
441            r"  // --- WebGL fingerprint spoofing ---
442  (function() {{
443    const GL_VENDOR   = 0x1F00;
444    const GL_RENDERER = 0x1F01;
445
446    const spoofCtx = (ctx) => {{
447      if (!ctx) return;
448      const origGetParam = ctx.getParameter.bind(ctx);
449      ctx.getParameter = (param) => {{
450        if (param === GL_VENDOR)   return {webgl_vendor:?};
451        if (param === GL_RENDERER) return {webgl_renderer:?};
452        return origGetParam(param);
453      }};
454    }};
455
456    // Wrap HTMLCanvasElement.prototype.getContext
457    const origGetContext = HTMLCanvasElement.prototype.getContext;
458    HTMLCanvasElement.prototype.getContext = function(type, ...args) {{
459      const ctx = origGetContext.call(this, type, ...args);
460      if (type === 'webgl' || type === 'experimental-webgl' || type === 'webgl2') {{
461        spoofCtx(ctx);
462      }}
463      return ctx;
464    }};
465  }})();",
466            webgl_vendor = nav.webgl_vendor,
467            webgl_renderer = nav.webgl_renderer,
468        )
469    }
470}
471
472// ─── Stealth application ──────────────────────────────────────────────────────
473
474/// Inject all stealth scripts into a freshly opened browser page.
475///
476/// Scripts are registered with `Page.addScriptToEvaluateOnNewDocument` so they
477/// execute before any page-owned JavaScript on every subsequent navigation.
478/// Which scripts are injected is determined by
479/// [`crate::config::StealthLevel`]:
480///
481/// | Level      | Injected content                                                        |
482/// | ------------ | ------------------------------------------------------------------------- |
483/// | `None`     | Nothing                                                                 |
484/// | `Basic`    | CDP leak fix + `navigator.webdriver` removal + minimal navigator spoof  |
485/// | `Advanced` | Basic + full WebGL/navigator spoofing + fingerprint + WebRTC protection |
486///
487/// # Errors
488///
489/// Returns [`crate::error::BrowserError::CdpError`] if a CDP command fails.
490///
491/// # Example
492///
493/// ```no_run
494/// # async fn run(
495/// #     page: &chromiumoxide::Page,
496/// #     config: &stygian_browser::BrowserConfig,
497/// # ) -> stygian_browser::Result<()> {
498/// use stygian_browser::stealth::apply_stealth_to_page;
499/// apply_stealth_to_page(page, config).await?;
500/// # Ok(())
501/// # }
502/// ```
503#[allow(clippy::too_many_lines)]
504pub async fn apply_stealth_to_page(
505    page: &chromiumoxide::Page,
506    config: &crate::config::BrowserConfig,
507) -> crate::error::Result<()> {
508    use crate::cdp_protection::CdpProtection;
509    use crate::config::StealthLevel;
510    use chromiumoxide::cdp::browser_protocol::page::AddScriptToEvaluateOnNewDocumentParams;
511
512    /// Inline helper: push one script as `AddScriptToEvaluateOnNewDocument`.
513    async fn inject_one(
514        page: &chromiumoxide::Page,
515        op: &'static str,
516        source: String,
517    ) -> crate::error::Result<()> {
518        use crate::error::BrowserError;
519        page.evaluate_on_new_document(AddScriptToEvaluateOnNewDocumentParams {
520            source,
521            world_name: None,
522            include_command_line_api: None,
523            run_immediately: None,
524        })
525        .await
526        .map_err(|e| BrowserError::CdpError {
527            operation: op.to_string(),
528            message: e.to_string(),
529        })?;
530        Ok(())
531    }
532
533    if config.stealth_level == StealthLevel::None {
534        return Ok(());
535    }
536
537    // ── CDP hardening — runs FIRST to clean up binding remnants ───────────────
538    #[cfg(feature = "stealth")]
539    {
540        let hardening_script = crate::cdp_hardening::cdp_hardening_script(&config.cdp_hardening);
541        if !hardening_script.is_empty() {
542            inject_one(
543                page,
544                "AddScriptToEvaluateOnNewDocument(cdp-hardening)",
545                hardening_script,
546            )
547            .await?;
548        }
549    }
550
551    // ── Basic and above ────────────────────────────────────────────────────────
552    let cdp_script =
553        CdpProtection::new(config.cdp_fix_mode, config.source_url.clone()).build_injection_script();
554    if !cdp_script.is_empty() {
555        inject_one(page, "AddScriptToEvaluateOnNewDocument(cdp)", cdp_script).await?;
556    }
557
558    let (nav_profile, stealth_cfg) = match config.stealth_level {
559        StealthLevel::Basic => (NavigatorProfile::default(), StealthConfig::minimal()),
560        StealthLevel::Advanced => (
561            NavigatorProfile::windows_chrome(),
562            StealthConfig::paranoid(),
563        ),
564        StealthLevel::None => unreachable!(),
565    };
566    let nav_script = StealthProfile::new(stealth_cfg, nav_profile).injection_script();
567    if !nav_script.is_empty() {
568        inject_one(
569            page,
570            "AddScriptToEvaluateOnNewDocument(navigator)",
571            nav_script,
572        )
573        .await?;
574    }
575
576    // ── Advanced only ──────────────────────────────────────────────────────────
577    if config.stealth_level == StealthLevel::Advanced {
578        let fp = crate::fingerprint::Fingerprint::random();
579        // Build one engine once so all spoofed surfaces share the same per-session seed.
580        // Prefer the fingerprint profile seed when present to keep profile identity coherent.
581        let profile_seed = config.fingerprint_profile.as_ref().map(|p| p.noise_seed);
582        let noise_seed = profile_seed
583            .or(config.noise.seed)
584            .unwrap_or_else(crate::noise::NoiseSeed::random);
585        let noise_engine = crate::noise::NoiseEngine::new(noise_seed);
586        let noise_seed = noise_engine.seed();
587        let fp_script = crate::fingerprint::inject_fingerprint(&fp);
588        inject_one(
589            page,
590            "AddScriptToEvaluateOnNewDocument(fingerprint)",
591            fp_script,
592        )
593        .await?;
594
595        let webrtc_script = config.webrtc.injection_script();
596        if !webrtc_script.is_empty() {
597            inject_one(
598                page,
599                "AddScriptToEvaluateOnNewDocument(webrtc)",
600                webrtc_script,
601            )
602            .await?;
603        }
604
605        if config.noise.canvas_enabled {
606            let canvas_script = crate::canvas_noise::canvas_noise_script(&noise_engine);
607            inject_one(
608                page,
609                "AddScriptToEvaluateOnNewDocument(canvas-noise)",
610                canvas_script,
611            )
612            .await?;
613        }
614
615        // WebGL, audio, and rects noise (T39, T40, T41)
616        if config.noise.webgl_enabled {
617            let webgl_script = crate::webgl_noise::webgl_noise_script(
618                &crate::webgl_noise::WebGlProfile::nvidia_rtx_3060(),
619                &noise_engine,
620            );
621            inject_one(
622                page,
623                "AddScriptToEvaluateOnNewDocument(webgl-noise)",
624                webgl_script,
625            )
626            .await?;
627        }
628
629        if config.noise.audio_enabled {
630            let audio_script = crate::audio_noise::audio_noise_script(&noise_engine);
631            inject_one(
632                page,
633                "AddScriptToEvaluateOnNewDocument(audio-noise)",
634                audio_script,
635            )
636            .await?;
637        }
638
639        if config.noise.rects_enabled {
640            let rects_script = crate::rects_noise::rects_noise_script(&noise_engine);
641            inject_one(
642                page,
643                "AddScriptToEvaluateOnNewDocument(rects-noise)",
644                rects_script,
645            )
646            .await?;
647        }
648
649        // Navigator coherence (T43) — inject only when a fingerprint profile is configured
650        if let Some(ref fp) = config.fingerprint_profile {
651            let nav_script = crate::navigator_coherence::navigator_coherence_script(fp);
652            inject_one(
653                page,
654                "AddScriptToEvaluateOnNewDocument(navigator-coherence)",
655                nav_script,
656            )
657            .await?;
658        }
659
660        // Timing noise (T44)
661        {
662            let timing_cfg = crate::timing_noise::TimingNoiseConfig {
663                enabled: true,
664                jitter_ms: 0.3,
665                seed: noise_seed,
666            };
667            let timing_script = crate::timing_noise::timing_noise_script(&timing_cfg);
668            inject_one(
669                page,
670                "AddScriptToEvaluateOnNewDocument(timing-noise)",
671                timing_script,
672            )
673            .await?;
674        }
675
676        // Peripheral stealth (T47)
677        {
678            let peripheral_cfg =
679                crate::peripheral_stealth::PeripheralStealthConfig::default_with_seed(noise_seed);
680            let peripheral_script =
681                crate::peripheral_stealth::peripheral_stealth_script_with_profile(
682                    &peripheral_cfg,
683                    config.fingerprint_profile.as_ref(),
684                );
685            if !peripheral_script.is_empty() {
686                inject_one(
687                    page,
688                    "AddScriptToEvaluateOnNewDocument(peripheral-stealth)",
689                    peripheral_script,
690                )
691                .await?;
692            }
693        }
694    }
695
696    Ok(())
697}
698
699// ─── Tests ────────────────────────────────────────────────────────────────────
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704
705    #[test]
706    fn disabled_config_produces_empty_script() {
707        let p = StealthProfile::new(StealthConfig::disabled(), NavigatorProfile::default());
708        assert_eq!(p.injection_script(), "");
709    }
710
711    #[test]
712    fn navigator_script_contains_platform() {
713        let profile = NavigatorProfile::windows_chrome();
714        let p = StealthProfile::new(StealthConfig::minimal(), profile);
715        let script = p.injection_script();
716        assert!(script.contains("Win32"), "platform must be in script");
717        assert!(
718            script.contains("'webdriver'"),
719            "webdriver removal must be present"
720        );
721    }
722
723    #[test]
724    fn navigator_script_contains_user_agent() {
725        let p = StealthProfile::new(StealthConfig::minimal(), NavigatorProfile::mac_chrome());
726        let script = p.injection_script();
727        assert!(script.contains("Mac OS X"));
728        assert!(script.contains("MacIntel"));
729    }
730
731    #[test]
732    fn webgl_script_contains_vendor_renderer() {
733        let p = StealthProfile::new(
734            StealthConfig {
735                spoof_navigator: false,
736                randomize_webgl: true,
737                ..StealthConfig::disabled()
738            },
739            NavigatorProfile::windows_chrome(),
740        );
741        let script = p.injection_script();
742        assert!(
743            script.contains("NVIDIA"),
744            "WebGL vendor must appear in script"
745        );
746        assert!(
747            script.contains("getParameter"),
748            "WebGL method must be overridden"
749        );
750    }
751
752    #[test]
753    fn full_profile_wraps_in_iife() {
754        let p = StealthProfile::new(StealthConfig::default(), NavigatorProfile::default());
755        let script = p.injection_script();
756        assert!(script.starts_with("(function()"), "script must be an IIFE");
757        assert!(script.ends_with("})();"));
758    }
759
760    #[test]
761    fn navigator_profile_linux_has_correct_platform() {
762        assert_eq!(NavigatorProfile::linux_chrome().platform, "Linux x86_64");
763    }
764
765    #[test]
766    fn stealth_config_paranoid_equals_default() {
767        let a = StealthConfig::paranoid();
768        let b = StealthConfig::default();
769        assert_eq!(a.spoof_navigator, b.spoof_navigator);
770        assert_eq!(a.randomize_webgl, b.randomize_webgl);
771        assert_eq!(a.randomize_canvas, b.randomize_canvas);
772        assert_eq!(a.human_behavior, b.human_behavior);
773        assert_eq!(a.protect_cdp, b.protect_cdp);
774    }
775
776    #[test]
777    fn hardware_concurrency_reasonable() {
778        let p = NavigatorProfile::windows_chrome();
779        assert!(p.hardware_concurrency >= 2);
780        assert!(p.hardware_concurrency <= 64);
781    }
782
783    // ── T13: stealth level script generation ──────────────────────────────────
784
785    #[test]
786    fn none_level_is_not_active() {
787        use crate::config::StealthLevel;
788        assert!(!StealthLevel::None.is_active());
789    }
790
791    #[test]
792    fn basic_level_cdp_script_removes_webdriver() {
793        use crate::cdp_protection::{CdpFixMode, CdpProtection};
794        let script = CdpProtection::new(CdpFixMode::AddBinding, None).build_injection_script();
795        assert!(
796            script.contains("webdriver"),
797            "CDP protection script should remove navigator.webdriver"
798        );
799    }
800
801    #[test]
802    fn basic_level_minimal_config_injects_navigator() {
803        let config = StealthConfig::minimal();
804        let profile = NavigatorProfile::default();
805        let script = StealthProfile::new(config, profile).injection_script();
806        assert!(
807            !script.is_empty(),
808            "Basic stealth should produce a navigator script"
809        );
810    }
811
812    #[test]
813    fn advanced_level_paranoid_config_includes_webgl() {
814        let config = StealthConfig::paranoid();
815        let profile = NavigatorProfile::windows_chrome();
816        let script = StealthProfile::new(config, profile).injection_script();
817        assert!(
818            script.contains("webgl") && script.contains("getParameter"),
819            "Advanced stealth should spoof WebGL via getParameter patching"
820        );
821    }
822
823    #[test]
824    fn advanced_level_fingerprint_script_non_empty() {
825        use crate::fingerprint::{Fingerprint, inject_fingerprint};
826        let fp = Fingerprint::random();
827        let script = inject_fingerprint(&fp);
828        assert!(
829            !script.is_empty(),
830            "Fingerprint injection script must not be empty"
831        );
832    }
833
834    #[test]
835    fn stealth_level_ordering() {
836        use crate::config::StealthLevel;
837        assert!(!StealthLevel::None.is_active());
838        assert!(StealthLevel::Basic.is_active());
839        assert!(StealthLevel::Advanced.is_active());
840    }
841
842    #[test]
843    fn navigator_profile_basic_uses_default() {
844        // Basic → default navigator profile (mac_chrome)
845        let profile = NavigatorProfile::default();
846        assert_eq!(profile.platform, "MacIntel");
847    }
848
849    #[test]
850    fn navigator_profile_advanced_uses_windows() {
851        let profile = NavigatorProfile::windows_chrome();
852        assert_eq!(profile.platform, "Win32");
853    }
854}