captchaforge 0.2.28

Automatic CAPTCHA detection and multi-strategy solving for chromiumoxide-driven headless browsers (Cloudflare Turnstile, reCAPTCHA v2/v3, hCaptcha, image grids, audio, sliders).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! Named browser fingerprint profiles.
//!
//! [`crate::stealth::apply_stealth`] hardens the *generic* signals
//! that betray a headless browser — `navigator.webdriver`, empty
//! plugins, missing `window.chrome`, etc. But once those obvious
//! tells are gone, the next layer of WAF fingerprinting reads
//! *coherent* values: the `User-Agent` header, `navigator.platform`,
//! `navigator.userAgentData.brands`, screen size, hardware
//! concurrency, GPU vendor/renderer, accept-language. A "Chrome on
//! Windows" UA paired with a `MacIntel` platform and a "Mesa Intel
//! Iris" GPU is *more* suspicious than vanilla headless, because
//! real browsers don't produce that combination.
//!
//! [`StealthProfile`] bundles a coherent set of those values per
//! (browser, OS, GPU class) tuple. Apply it with
//! [`apply_stealth_profile`] in addition to (not instead of)
//! [`crate::stealth::apply_stealth`].
//!
//! Only browsers/OSes that ship enough public fingerprint detail
//! to construct a coherent set are listed. Adding a new variant
//! here is cheap (one literal) but **NEVER** copy a UA string from
//! one variant into another — the WAF cross-checks UA against
//! `userAgentData.brands` and `platform`.
//!
//! # Example
//!
//! ```
//! use captchaforge::stealth_profiles::{StealthProfile, profile_to_overrides};
//!
//! let p = StealthProfile::ChromeWindowsStable;
//! let ov = profile_to_overrides(&p);
//! assert!(ov.user_agent.contains("Windows NT"));
//! assert_eq!(ov.platform, "Win32");
//! assert!(ov.languages.contains(&"en-US".to_string()));
//! ```

use anyhow::{anyhow, Result};
use chromiumoxide::cdp::browser_protocol::page::AddScriptToEvaluateOnNewDocumentParams;
use chromiumoxide::Page;

/// Named browser fingerprint variants. Each one bundles a
/// coherent (UA, platform, brands, GPU, screen, languages) tuple.
///
/// `#[non_exhaustive]` — adding a new variant is a minor-version
/// change, removing one is major. UA strings inside each variant
/// are *also* additive (we periodically refresh them), but the
/// shape (Chrome major version, OS string family) stays stable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StealthProfile {
    /// Chrome stable on Windows 10/11, Intel iGPU. Most common
    /// real-world combination on the public internet (~60% of
    /// desktop traffic per StatCounter Q1 2026), so it blends in.
    ChromeWindowsStable,
    /// Chrome stable on macOS, Apple Silicon GPU. Second-most
    /// common desktop combination.
    ChromeMacStable,
    /// Microsoft Edge on Windows, same Chromium core but distinct
    /// brands tuple (`Microsoft Edge` ahead of `Google Chrome`).
    EdgeWindowsStable,
    /// Firefox on Linux desktop. Niche but legitimate; useful when
    /// you specifically *don't* want to look like Chromium.
    FirefoxLinux,
    /// Chrome on Android — touch-event surface, narrow screen,
    /// `Mobile` brand. For mobile-targeted bypasses.
    ChromeAndroid,
    /// Safari on iPhone — narrow screen, distinct rendering quirks,
    /// no userAgentData (Safari doesn't ship Client Hints). Highest
    /// blend-in for iOS-segment fleets.
    SafariIphone,
    /// Safari on iPad — wider tablet form-factor, also no
    /// userAgentData. Distinct from iPhone via screen + UA token.
    SafariIpad,
    /// Safari on macOS desktop. Same WebKit core, distinct UA from
    /// Chrome-on-Mac. No userAgentData.
    SafariMacStable,
    /// Chrome on Linux desktop — under-represented but real;
    /// useful as a foil to detection systems that flag any Linux
    /// user-agent as suspicious-bot.
    ChromeLinux,
    /// Brave browser on Windows — Chromium core but Brave-specific
    /// brand triplet. Anti-fingerprinting site detectors that look
    /// for Brave-shaped Client Hints will accept this profile.
    BraveWindows,
    /// Opera on Windows — Chromium core, distinct OPR brand.
    OperaWindows,
    /// Samsung Internet on Galaxy phone — distinct mobile UA,
    /// commonly forgiven by anti-bot stacks since real users use it.
    SamsungInternetAndroid,
}

/// The set of fingerprint values a profile pins.
///
/// Pure data — no IO. The CDP-bound [`apply_stealth_profile`]
/// reads this and produces the override JS.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfileOverrides {
    pub user_agent: String,
    /// `navigator.platform` value. Must match the UA's OS family.
    pub platform: String,
    /// `navigator.languages` array.
    pub languages: Vec<String>,
    /// `userAgentData.brands` — Chromium-only. Empty for Firefox.
    pub brands: Vec<(String, String)>,
    /// `userAgentData.mobile` boolean.
    pub mobile: bool,
    /// `navigator.hardwareConcurrency`. Real desktops 4–16, mobile 6–8.
    pub hardware_concurrency: u32,
    /// `navigator.deviceMemory` GB.
    pub device_memory: u32,
    /// `screen.width`, `screen.height`. Common desktop = 1920x1080.
    pub screen_width: u32,
    pub screen_height: u32,
    /// WebGL `UNMASKED_VENDOR_WEBGL` and `UNMASKED_RENDERER_WEBGL`.
    /// Must match the OS / hardware claimed by the UA.
    pub webgl_vendor: String,
    pub webgl_renderer: String,
}

/// Materialise the override values for a given profile. Pure.
///
/// Fails to compile if a new variant is added to [`StealthProfile`]
/// without a matching arm here — `#[non_exhaustive]` is for downstream
/// code, not for in-crate arms.
pub fn profile_to_overrides(profile: &StealthProfile) -> ProfileOverrides {
    match profile {
        StealthProfile::ChromeWindowsStable => ProfileOverrides {
            user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \
                         (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
                .into(),
            platform: "Win32".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: vec![
                ("Chromium".into(), "130".into()),
                ("Google Chrome".into(), "130".into()),
                ("Not?A_Brand".into(), "99".into()),
            ],
            mobile: false,
            hardware_concurrency: 8,
            device_memory: 8,
            screen_width: 1920,
            screen_height: 1080,
            webgl_vendor: "Google Inc. (Intel)".into(),
            webgl_renderer: "ANGLE (Intel, Intel(R) Iris(R) Xe Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)".into(),
        },
        StealthProfile::ChromeMacStable => ProfileOverrides {
            user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 \
                         (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
                .into(),
            platform: "MacIntel".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: vec![
                ("Chromium".into(), "130".into()),
                ("Google Chrome".into(), "130".into()),
                ("Not?A_Brand".into(), "99".into()),
            ],
            mobile: false,
            hardware_concurrency: 8,
            device_memory: 8,
            screen_width: 1728,
            screen_height: 1117,
            webgl_vendor: "Google Inc. (Apple)".into(),
            webgl_renderer: "ANGLE (Apple, ANGLE Metal Renderer: Apple M1 Pro, Unspecified Version)".into(),
        },
        StealthProfile::EdgeWindowsStable => ProfileOverrides {
            user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \
                         (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"
                .into(),
            platform: "Win32".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: vec![
                ("Chromium".into(), "130".into()),
                ("Microsoft Edge".into(), "130".into()),
                ("Not?A_Brand".into(), "99".into()),
            ],
            mobile: false,
            hardware_concurrency: 8,
            device_memory: 8,
            screen_width: 1920,
            screen_height: 1080,
            webgl_vendor: "Google Inc. (Intel)".into(),
            webgl_renderer: "ANGLE (Intel, Intel(R) UHD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)".into(),
        },
        StealthProfile::FirefoxLinux => ProfileOverrides {
            user_agent: "Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0"
                .into(),
            platform: "Linux x86_64".into(),
            languages: vec!["en-US".into(), "en".into()],
            // Firefox doesn't expose userAgentData. Empty brands
            // signals "not a Chromium" to overrides.
            brands: Vec::new(),
            mobile: false,
            hardware_concurrency: 8,
            device_memory: 8,
            screen_width: 1920,
            screen_height: 1080,
            webgl_vendor: "Mesa".into(),
            webgl_renderer: "Mesa Intel(R) Iris(R) Xe Graphics (TGL GT2)".into(),
        },
        StealthProfile::ChromeAndroid => ProfileOverrides {
            user_agent: "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 \
                         (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36"
                .into(),
            platform: "Linux armv8l".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: vec![
                ("Chromium".into(), "130".into()),
                ("Google Chrome".into(), "130".into()),
                ("Not?A_Brand".into(), "99".into()),
            ],
            mobile: true,
            hardware_concurrency: 8,
            device_memory: 6,
            screen_width: 412,
            screen_height: 915,
            webgl_vendor: "Qualcomm".into(),
            webgl_renderer: "Adreno (TM) 740".into(),
        },
        StealthProfile::SafariIphone => ProfileOverrides {
            user_agent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) \
                         AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 \
                         Mobile/15E148 Safari/604.1"
                .into(),
            platform: "iPhone".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: Vec::new(),
            mobile: true,
            hardware_concurrency: 6,
            device_memory: 4,
            screen_width: 390,
            screen_height: 844,
            webgl_vendor: "Apple Inc.".into(),
            webgl_renderer: "Apple GPU".into(),
        },
        StealthProfile::SafariIpad => ProfileOverrides {
            user_agent: "Mozilla/5.0 (iPad; CPU OS 17_5 like Mac OS X) AppleWebKit/605.1.15 \
                         (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1"
                .into(),
            platform: "iPad".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: Vec::new(),
            mobile: true,
            hardware_concurrency: 8,
            device_memory: 8,
            screen_width: 1024,
            screen_height: 1366,
            webgl_vendor: "Apple Inc.".into(),
            webgl_renderer: "Apple GPU".into(),
        },
        StealthProfile::SafariMacStable => ProfileOverrides {
            user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) \
                         AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15"
                .into(),
            platform: "MacIntel".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: Vec::new(),
            mobile: false,
            hardware_concurrency: 10,
            device_memory: 16,
            screen_width: 1728,
            screen_height: 1117,
            webgl_vendor: "Apple Inc.".into(),
            webgl_renderer: "Apple M2".into(),
        },
        StealthProfile::ChromeLinux => ProfileOverrides {
            user_agent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
                         (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
                .into(),
            platform: "Linux x86_64".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: vec![
                ("Chromium".into(), "130".into()),
                ("Google Chrome".into(), "130".into()),
                ("Not?A_Brand".into(), "99".into()),
            ],
            mobile: false,
            hardware_concurrency: 8,
            device_memory: 8,
            screen_width: 1920,
            screen_height: 1080,
            webgl_vendor: "Mesa".into(),
            webgl_renderer: "Mesa Intel(R) UHD Graphics 770 (ADL-S GT1)".into(),
        },
        StealthProfile::BraveWindows => ProfileOverrides {
            user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \
                         (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
                .into(),
            platform: "Win32".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: vec![
                ("Brave".into(), "130".into()),
                ("Chromium".into(), "130".into()),
                ("Not?A_Brand".into(), "99".into()),
            ],
            mobile: false,
            hardware_concurrency: 8,
            device_memory: 8,
            screen_width: 1920,
            screen_height: 1080,
            webgl_vendor: "Brave".into(),
            webgl_renderer: "Brave".into(),
        },
        StealthProfile::OperaWindows => ProfileOverrides {
            user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \
                         (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 OPR/115.0.0.0"
                .into(),
            platform: "Win32".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: vec![
                ("Chromium".into(), "130".into()),
                ("Opera".into(), "115".into()),
                ("Not?A_Brand".into(), "99".into()),
            ],
            mobile: false,
            hardware_concurrency: 8,
            device_memory: 8,
            screen_width: 1920,
            screen_height: 1080,
            webgl_vendor: "Google Inc. (Intel)".into(),
            webgl_renderer: "ANGLE (Intel, Intel(R) UHD Graphics 770 Direct3D11 vs_5_0 ps_5_0, D3D11)".into(),
        },
        StealthProfile::SamsungInternetAndroid => ProfileOverrides {
            user_agent: "Mozilla/5.0 (Linux; Android 14; SM-S928B) AppleWebKit/537.36 \
                         (KHTML, like Gecko) SamsungBrowser/26.0 Chrome/126.0.0.0 \
                         Mobile Safari/537.36"
                .into(),
            platform: "Linux armv8l".into(),
            languages: vec!["en-US".into(), "en".into()],
            brands: vec![
                ("Samsung Internet".into(), "26".into()),
                ("Chromium".into(), "126".into()),
                ("Not?A_Brand".into(), "99".into()),
            ],
            mobile: true,
            hardware_concurrency: 8,
            device_memory: 8,
            screen_width: 412,
            screen_height: 915,
            webgl_vendor: "Qualcomm".into(),
            webgl_renderer: "Adreno (TM) 750".into(),
        },
    }
}

/// Build the override JS for a given profile.
///
/// Distinct from `crate::stealth::STEALTH_JS` — that's the generic
/// "remove headless tells" pass. This is the "pin a coherent
/// fingerprint" pass. Apply both: stealth first, profile second,
/// so profile wins on the navigator surfaces it overrides.
pub fn profile_js(overrides: &ProfileOverrides) -> String {
    let langs_json = serde_json::to_string(&overrides.languages)
        .unwrap_or_else(|_| r#"["en-US","en"]"#.into());
    let brands_json = serde_json::to_string(
        &overrides
            .brands
            .iter()
            .map(|(b, v)| serde_json::json!({"brand": b, "version": v}))
            .collect::<Vec<_>>(),
    )
    .unwrap_or_else(|_| "[]".into());

    format!(
        r#"
(() => {{
    /* User-Agent. Overrides both userAgent and appVersion since
       some detectors look for divergence between them. */
    try {{
        Object.defineProperty(Navigator.prototype, 'userAgent', {{
            get: () => {ua_json},
            configurable: true,
        }});
        Object.defineProperty(Navigator.prototype, 'appVersion', {{
            get: () => {ua_json}.replace('Mozilla/', ''),
            configurable: true,
        }});
    }} catch (_) {{}}

    /* navigator.platform — must agree with UA. Detectors flag
       (UA: Windows, platform: MacIntel) as obvious spoofing. */
    try {{
        Object.defineProperty(Navigator.prototype, 'platform', {{
            get: () => {platform_json},
            configurable: true,
        }});
    }} catch (_) {{}}

    /* navigator.languages */
    try {{
        Object.defineProperty(Navigator.prototype, 'languages', {{
            get: () => {langs_json},
            configurable: true,
        }});
    }} catch (_) {{}}

    /* userAgentData — Chromium-only. Skip when brands is empty
       (Firefox profile). */
    try {{
        const brands = {brands_json};
        if (brands.length > 0) {{
            Object.defineProperty(Navigator.prototype, 'userAgentData', {{
                get: () => ({{
                    brands,
                    mobile: {mobile},
                    platform: {platform_json},
                    getHighEntropyValues: (hints) => Promise.resolve({{
                        brands,
                        mobile: {mobile},
                        platform: {platform_json},
                        platformVersion: '15.0.0',
                        architecture: 'x86',
                        bitness: '64',
                        model: '',
                        uaFullVersion: '130.0.0.0',
                    }}),
                    toJSON: () => ({{ brands, mobile: {mobile}, platform: {platform_json} }}),
                }}),
                configurable: true,
            }});
        }}
    }} catch (_) {{}}

    /* hardwareConcurrency / deviceMemory — coherent with the
       claimed device class. */
    try {{
        Object.defineProperty(Navigator.prototype, 'hardwareConcurrency', {{
            get: () => {hwc},
            configurable: true,
        }});
        Object.defineProperty(Navigator.prototype, 'deviceMemory', {{
            get: () => {dm},
            configurable: true,
        }});
    }} catch (_) {{}}

    /* screen.width/height. Detectors compute device-pixel ratio
       and screen aspect — pinning to known-real values blends in. */
    try {{
        Object.defineProperty(window.screen, 'width', {{
            get: () => {sw},
            configurable: true,
        }});
        Object.defineProperty(window.screen, 'height', {{
            get: () => {sh},
            configurable: true,
        }});
        Object.defineProperty(window.screen, 'availWidth', {{
            get: () => {sw},
            configurable: true,
        }});
        Object.defineProperty(window.screen, 'availHeight', {{
            get: () => {sh} - 40,
            configurable: true,
        }});
    }} catch (_) {{}}

    /* WebGL UNMASKED_* parameters. Coherent with UA platform. */
    try {{
        const VEND = 0x9245, REND = 0x9246;
        const wrap = (proto) => {{
            const orig = proto.getParameter;
            proto.getParameter = function(p) {{
                if (p === VEND) return {webgl_vendor_json};
                if (p === REND) return {webgl_renderer_json};
                return orig.call(this, p);
            }};
        }};
        if (typeof WebGLRenderingContext !== 'undefined') wrap(WebGLRenderingContext.prototype);
        if (typeof WebGL2RenderingContext !== 'undefined') wrap(WebGL2RenderingContext.prototype);
    }} catch (_) {{}}
}})();
"#,
        // serde_json::to_string on a borrowed String is infallible —
        // the only failure modes are (a) non-UTF8, which String
        // forbids by construction, and (b) custom Serialize impls
        // returning Err, which String doesn't have. The expect()
        // surfaces the impossible case loudly if the std lib's
        // contract ever changes.
        ua_json = serde_json::to_string(&overrides.user_agent)
            .expect("serde_json::to_string(&String) is infallible"),
        platform_json = serde_json::to_string(&overrides.platform)
            .expect("serde_json::to_string(&String) is infallible"),
        langs_json = langs_json,
        brands_json = brands_json,
        mobile = overrides.mobile,
        hwc = overrides.hardware_concurrency,
        dm = overrides.device_memory,
        sw = overrides.screen_width,
        sh = overrides.screen_height,
        webgl_vendor_json = serde_json::to_string(&overrides.webgl_vendor)
            .expect("serde_json::to_string(&String) is infallible"),
        webgl_renderer_json = serde_json::to_string(&overrides.webgl_renderer)
            .expect("serde_json::to_string(&String) is infallible"),
    )
}

/// Inject the profile overrides into every new document on `page`.
/// Call AFTER [`crate::stealth::apply_stealth`] so the profile's
/// pinned values win on `userAgent`/`platform`/`languages`/
/// `hardwareConcurrency`/`deviceMemory`/WebGL.
///
/// Like `apply_stealth`, must be called BEFORE the first `goto()`.
pub async fn apply_stealth_profile(page: &Page, profile: &StealthProfile) -> Result<()> {
    let overrides = profile_to_overrides(profile);
    let js = profile_js(&overrides);
    page.execute(AddScriptToEvaluateOnNewDocumentParams {
        source: js,
        world_name: None,
        include_command_line_api: None,
        run_immediately: Some(true),
    })
    .await
    .map_err(|e| anyhow!("stealth_profile: addScriptToEvaluateOnNewDocument failed: {e}"))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_chromium_profile_has_brands() {
        for p in [
            StealthProfile::ChromeWindowsStable,
            StealthProfile::ChromeMacStable,
            StealthProfile::EdgeWindowsStable,
            StealthProfile::ChromeAndroid,
            StealthProfile::ChromeLinux,
            StealthProfile::BraveWindows,
            StealthProfile::OperaWindows,
            StealthProfile::SamsungInternetAndroid,
        ] {
            let ov = profile_to_overrides(&p);
            assert!(!ov.brands.is_empty(), "{p:?} should declare userAgentData brands");
        }
    }

    #[test]
    fn safari_and_firefox_have_no_brands() {
        for p in [
            StealthProfile::FirefoxLinux,
            StealthProfile::SafariIphone,
            StealthProfile::SafariIpad,
            StealthProfile::SafariMacStable,
        ] {
            let ov = profile_to_overrides(&p);
            assert!(
                ov.brands.is_empty(),
                "{p:?} does not expose userAgentData / Client Hints"
            );
        }
    }

    #[test]
    fn ua_matches_platform() {
        // Windows UA must pair with Win32 platform; Mac with MacIntel; etc.
        // Mismatches are *more* suspicious than vanilla headless.
        let cases = [
            (StealthProfile::ChromeWindowsStable, "Windows", "Win32"),
            (StealthProfile::ChromeMacStable, "Mac OS X", "MacIntel"),
            (StealthProfile::EdgeWindowsStable, "Windows", "Win32"),
            (StealthProfile::FirefoxLinux, "Linux", "Linux x86_64"),
            (StealthProfile::ChromeAndroid, "Android", "Linux armv8l"),
            (StealthProfile::ChromeLinux, "Linux", "Linux x86_64"),
            (StealthProfile::SafariIphone, "iPhone", "iPhone"),
            (StealthProfile::SafariIpad, "iPad", "iPad"),
            (StealthProfile::SafariMacStable, "Mac OS X", "MacIntel"),
            (StealthProfile::BraveWindows, "Windows", "Win32"),
            (StealthProfile::OperaWindows, "Windows", "Win32"),
            (StealthProfile::SamsungInternetAndroid, "Android", "Linux armv8l"),
        ];
        for (p, ua_substr, platform) in cases {
            let ov = profile_to_overrides(&p);
            assert!(ov.user_agent.contains(ua_substr), "{p:?} UA missing {ua_substr}");
            assert_eq!(ov.platform, platform, "{p:?} platform mismatch");
        }
    }

    #[test]
    fn profile_js_emits_uadata_only_when_brands_present() {
        let chrome = profile_js(&profile_to_overrides(&StealthProfile::ChromeWindowsStable));
        assert!(chrome.contains("userAgentData"));
        // Firefox profile still emits the conditional but the runtime
        // brands.length check skips assignment. Source-level check:
        // the JS must always contain the guard.
        assert!(chrome.contains("brands.length > 0"));
    }

    #[test]
    fn profile_js_overrides_webgl_unmasked_params() {
        let js = profile_js(&profile_to_overrides(&StealthProfile::ChromeMacStable));
        assert!(js.contains("0x9245"), "WebGL UNMASKED_VENDOR constant must be referenced");
        assert!(js.contains("0x9246"), "WebGL UNMASKED_RENDERER constant must be referenced");
        assert!(js.contains("Apple M1 Pro"), "Mac profile must pin an Apple GPU renderer");
    }

    #[test]
    fn android_profile_is_mobile_with_narrow_screen() {
        let ov = profile_to_overrides(&StealthProfile::ChromeAndroid);
        assert!(ov.mobile);
        assert!(ov.screen_width < 500, "mobile profile should have a phone-sized screen");
    }

    #[test]
    fn languages_default_to_english() {
        // All shipped profiles start with en-US. Localised profiles are
        // a future addition; for now we ship one consistent set so
        // accept-language headers don't conflict with navigator.languages.
        for p in [
            StealthProfile::ChromeWindowsStable,
            StealthProfile::ChromeMacStable,
            StealthProfile::EdgeWindowsStable,
            StealthProfile::FirefoxLinux,
            StealthProfile::ChromeAndroid,
            StealthProfile::SafariIphone,
            StealthProfile::SafariIpad,
            StealthProfile::SafariMacStable,
            StealthProfile::ChromeLinux,
            StealthProfile::BraveWindows,
            StealthProfile::OperaWindows,
            StealthProfile::SamsungInternetAndroid,
        ] {
            let ov = profile_to_overrides(&p);
            assert_eq!(ov.languages.first().map(|s| s.as_str()), Some("en-US"));
        }
    }

    #[test]
    fn safari_profiles_have_apple_webgl_renderer() {
        for p in [
            StealthProfile::SafariIphone,
            StealthProfile::SafariIpad,
            StealthProfile::SafariMacStable,
        ] {
            let ov = profile_to_overrides(&p);
            assert!(
                ov.webgl_vendor.contains("Apple"),
                "{p:?} must claim an Apple GPU vendor"
            );
        }
    }

    #[test]
    fn brave_profile_lists_brave_brand_first() {
        let ov = profile_to_overrides(&StealthProfile::BraveWindows);
        let first = ov.brands.first().map(|(b, _)| b.as_str());
        assert_eq!(first, Some("Brave"));
    }

    #[test]
    fn samsung_internet_profile_is_mobile() {
        let ov = profile_to_overrides(&StealthProfile::SamsungInternetAndroid);
        assert!(ov.mobile);
        assert!(ov.user_agent.contains("SamsungBrowser"));
    }

    #[test]
    fn opera_profile_lists_opera_brand() {
        let ov = profile_to_overrides(&StealthProfile::OperaWindows);
        let names: Vec<&str> = ov.brands.iter().map(|(b, _)| b.as_str()).collect();
        assert!(names.contains(&"Opera"));
        assert!(ov.user_agent.contains("OPR/"));
    }

    #[test]
    fn safari_profiles_have_no_brave_or_opera_marker() {
        // Safari profiles must not accidentally inherit Brave/Opera UAs.
        for p in [
            StealthProfile::SafariIphone,
            StealthProfile::SafariIpad,
            StealthProfile::SafariMacStable,
        ] {
            let ov = profile_to_overrides(&p);
            assert!(!ov.user_agent.contains("OPR/"));
            assert!(!ov.user_agent.contains("Brave"));
            assert!(ov.user_agent.contains("Safari/"));
        }
    }

    #[test]
    fn edge_profile_lists_microsoft_brand_distinct_from_chrome() {
        let ov = profile_to_overrides(&StealthProfile::EdgeWindowsStable);
        let brand_names: Vec<&str> = ov.brands.iter().map(|(b, _)| b.as_str()).collect();
        assert!(brand_names.contains(&"Microsoft Edge"));
        assert!(!brand_names.contains(&"Google Chrome"),
            "Edge profile must not list Google Chrome — that mismatch is itself a tell");
    }
}