captchaforge 0.2.13

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
//! 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,
}

/// 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(),
        },
    }
}

/// 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 (_) {{}}
}})();
"#,
        ua_json = serde_json::to_string(&overrides.user_agent).unwrap(),
        platform_json = serde_json::to_string(&overrides.platform).unwrap(),
        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).unwrap(),
        webgl_renderer_json = serde_json::to_string(&overrides.webgl_renderer).unwrap(),
    )
}

/// 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,
        ] {
            let ov = profile_to_overrides(&p);
            assert!(!ov.brands.is_empty(), "{p:?} should declare userAgentData brands");
        }
    }

    #[test]
    fn firefox_profile_has_no_brands() {
        let ov = profile_to_overrides(&StealthProfile::FirefoxLinux);
        assert!(ov.brands.is_empty(), "Firefox does not expose userAgentData");
    }

    #[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"),
        ];
        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,
        ] {
            let ov = profile_to_overrides(&p);
            assert_eq!(ov.languages.first().map(|s| s.as_str()), Some("en-US"));
        }
    }

    #[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");
    }
}