guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
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
//! JS-layer anti-detection injection for the BiDi Firefox path.
//!
//! The generic, profile-independent overrides live here as one self-invoking
//! IIFE (assembled from the shared [`NATIVE_SEAL_PRELUDE`] + [`FIREFOX_STEALTH_BODY`]),
//! plus the [`apply_stealth`] / [`apply_stealth_profile`] entry points that
//! register them as BiDi preload scripts. Pref-layer (`user.js`) configuration
//! lives in [`super::userjs`]; the launch orchestration that ties the two
//! together lives in [`super`].

use runtime_foxdriver::browser::Page;
use std::sync::LazyLock;

use crate::fingerprint::NATIVE_SEAL_PRELUDE;

/// The generic stealth override statements (everything inside the IIFE, after
/// the camouflage prelude). Each installed getter/method is wrapped in
/// `__seal(fn, 'get <name>')` so its `.toString()` reports `[native code]`
/// instead of leaking the override source — see [`NATIVE_SEAL_PRELUDE`].
///
/// WebGL is deliberately NOT touched here. A previous generic patch hard-coded
/// `UNMASKED_VENDOR_WEBGL=""` + a fixed `UNMASKED_RENDERER_WEBGL` (a 1050-Ti
/// string) for EVERY host — a measured tell: the live `headful_truth` probe
/// showed a real RTX-5090 box advertising an empty vendor and a card it does
/// not have, a string that also never matches the actual rendered pixels. On a
/// matched host (Firefox-on-Linux persona on real Firefox/Linux) Gecko already
/// sanitizes the adapter to a low-entropy, self-consistent value whose pixels
/// DO match — strictly more coherent than any constant. A genuine cross-OS
/// persona supplies its own coherent renderer through `profile_js` (gated on a
/// non-empty renderer); the generic layer must never invent one.
const FIREFOX_STEALTH_BODY: &str = r#"
    try {
        Object.defineProperty(Navigator.prototype, 'webdriver', {
            get: __seal(() => false, 'get webdriver'),
            configurable: true,
            enumerable: true,
        });
    } catch (_) {}

    try {
        Object.defineProperty(Navigator.prototype, 'maxTouchPoints', {
            get: __seal(() => 0, 'get maxTouchPoints'),
            configurable: true,
            enumerable: true,
        });
    } catch (_) {}

    try {
        const origQuery = Navigator.prototype.permissions.query;
        Navigator.prototype.permissions.query = __seal(function(parameters) {
            const name = parameters && parameters.name;
            if (name === 'notifications' || name === 'clipboard-read' || name === 'clipboard-write'
                || name === 'accelerometer' || name === 'gyroscope' || name === 'magnetometer'
                || name === 'ambient-light-sensor' || name === 'payment-handler') {
                return Promise.resolve({ state: 'prompt', onchange: null });
            }
            return origQuery.call(this, parameters);
        }, 'query');
    } catch (_) {}

    try {
        if (navigator.permissions && !navigator.permissions.request) {
            navigator.permissions.request = __seal(function(parameters) {
                return navigator.permissions.query(parameters);
            }, 'request');
        }
    } catch (_) {}

    try {
        Object.defineProperty(Notification, 'permission', {
            get: __seal(() => 'default', 'get permission'),
            configurable: true,
            enumerable: true,
        });
    } catch (_) {}

    // navigator.plugins / navigator.mimeTypes are deliberately NOT overridden.
    // A real Firefox (even headless) already exposes a genuine PluginArray (the
    // PDF viewer set) where navigator.plugins instanceof PluginArray holds. The
    // previous override replaced it with a plain JS Array, which real detectors
    // flag (the sannysoft PluginArray check) as a regression vs bare Firefox.
    // Leaving the real Firefox plugins untouched is strictly more coherent.

    // WebGL adapter: native passthrough (no generic override) — see Rust note.

    try {
        Object.defineProperty(window, 'chrome', {
            get: __seal(() => undefined, 'get chrome'),
            configurable: true,
        });
    } catch (_) {}

    try {
        const w = window;
        const iw = w.innerWidth || 1920;
        const ih = w.innerHeight || 1080;
        Object.defineProperty(w, 'outerWidth', { get: __seal(() => iw + 16, 'get outerWidth'), configurable: true });
        Object.defineProperty(w, 'outerHeight', { get: __seal(() => ih + 88, 'get outerHeight'), configurable: true });
        Object.defineProperty(w, 'devicePixelRatio', { get: __seal(() => 1, 'get devicePixelRatio'), configurable: true });
    } catch (_) {}

    // webdriver is pinned to false on Navigator.prototype ONLY (above). Do NOT
    // also define it on the `navigator` instance: that creates an OWN property,
    // which `_.has(navigator,'webdriver')` / hasOwnProperty detects (bot.sannysoft
    // "WebDriver (New)" = `navigator.webdriver || _.has(navigator,'webdriver')`).
    // A real Firefox carries webdriver only on the prototype (inherited).

    try {
        if (window.callPhantom || window._phantom) {
            Object.defineProperty(window, 'callPhantom', { get: __seal(() => undefined, 'get callPhantom'), configurable: true });
            Object.defineProperty(window, '_phantom', { get: __seal(() => undefined, 'get _phantom'), configurable: true });
        }
    } catch (_) {}

    try {
        Object.defineProperty(window, 'cdc_adoQpoasnfa76pfcZLmcfl_', { get: __seal(() => undefined, 'get cdc_adoQpoasnfa76pfcZLmcfl_'), configurable: true });
        Object.defineProperty(window, 'cdc_adoQpoasnfa76pfcZLmcfl_Array', { get: __seal(() => undefined, 'get cdc_adoQpoasnfa76pfcZLmcfl_Array'), configurable: true });
        Object.defineProperty(window, 'cdc_adoQpoasnfa76pfcZLmcfl_Promise', { get: __seal(() => undefined, 'get cdc_adoQpoasnfa76pfcZLmcfl_Promise'), configurable: true });
        Object.defineProperty(window, 'cdc_adoQpoasnfa76pfcZLmcfl_Symbol', { get: __seal(() => undefined, 'get cdc_adoQpoasnfa76pfcZLmcfl_Symbol'), configurable: true });
    } catch (_) {}

    try {
        const iframeDescriptor = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
        if (iframeDescriptor && iframeDescriptor.get) {
            const origGet = iframeDescriptor.get;
            Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', {
                get: __seal(function() {
                    try {
                        const win = origGet.call(this);
                        if (win) {
                            try { win.callPhantom; } catch(_) {}
                            try { win._phantom; } catch(_) {}
                            try { win.chrome; } catch(_) {}
                        }
                        return win;
                    } catch(_) {
                        return null;
                    }
                }, 'get contentWindow'),
                configurable: true
            });
        }
    } catch (_) {}
"#;

/// Firefox-compatible generic anti-detection JS.
///
/// Covers the tells that are universal across all Firefox profiles
/// (webdriver, permissions, plugins, WebGL, chrome runtime, etc.).
/// Profile-specific overrides (UA, platform, vendor, languages, hardware)
/// are injected separately by [`apply_stealth_profile`].
///
/// Assembled at first use from the shared [`NATIVE_SEAL_PRELUDE`] (which makes
/// every override report native via `.toString()`) followed by
/// [`FIREFOX_STEALTH_BODY`]. The result is one self-invoking IIFE so the
/// prelude's `__seal` is in scope for the body.
pub(super) static FIREFOX_STEALTH_JS: LazyLock<String> = LazyLock::new(|| {
    format!("(() => {{{prelude}\n{body}\n}})();\n", prelude = NATIVE_SEAL_PRELUDE, body = FIREFOX_STEALTH_BODY)
});

/// Apply generic anti-detection JS to `page`.
///
/// Injects via immediate `evaluate` + registers as a preload script so
/// future navigations also get the patches.
pub async fn apply_stealth(page: &Page) -> anyhow::Result<()> {
    page.evaluate(FIREFOX_STEALTH_JS.as_str())
        .await
        .map_err(|e| anyhow::anyhow!("stealth evaluate failed: {e:?}"))?;
    page.add_preload_script(FIREFOX_STEALTH_JS.as_str())
        .await
        .map_err(|e| anyhow::anyhow!("stealth preload script failed: {e:?}"))?;
    Ok(())
}

/// Apply a stealth profile's JS anti-detection patches to `page`.
///
/// 1. Injects the generic stealth script.
/// 2. Injects the profile-specific identity script (UA, platform, languages,
///    hardwareConcurrency, etc.).
/// 3. Registers both as preload scripts.
pub async fn apply_stealth_profile(
    page: &Page,
    profile: &crate::StealthProfile,
) -> anyhow::Result<()> {
    // Register preloads FIRST (they apply to every future navigation), then
    // evaluate once on the current document. Errors propagate: a silently
    // swallowed preload-registration failure is exactly how the entire stealth
    // layer became a no-op — every tell must either be hidden or surface loudly.
    page.add_preload_script(FIREFOX_STEALTH_JS.as_str())
        .await
        .map_err(|e| anyhow::anyhow!("stealth preload (generic) failed to register: {e:?}"))?;
    let _ = page.evaluate(FIREFOX_STEALTH_JS.as_str()).await;

    let overrides = crate::profile_to_overrides(profile);
    let profile_js = crate::profile_js(&overrides);
    page.add_preload_script(&profile_js)
        .await
        .map_err(|e| anyhow::anyhow!("stealth preload (profile) failed to register: {e:?}"))?;
    // Surface the immediate-evaluate error. Swallowing it (`let _ =`) is exactly
    // how a malformed override script turned the ENTIRE per-profile fingerprint
    // layer (UA, hardwareConcurrency, vendor, WebGL, client hints, …) into a
    // silent no-op: the generated JS raised a SyntaxError on every page yet the
    // profile reported success. A failure here is a real bug in the generated
    // script — it must surface, not hide.
    page.evaluate(&profile_js)
        .await
        .map_err(|e| anyhow::anyhow!("stealth profile JS evaluate failed (malformed override script?): {e:?}"))?;

    Ok(())
}

/// The canonical default disguise: **max coherence**.
///
/// Scrubs automation tells ([`apply_stealth`]) while leaving the REAL browser
/// identity — UA, platform, hardwareConcurrency, WebGL, languages — GENUINE. A
/// real Firefox's surfaces are self-consistent across JS, the HTTP `User-Agent`
/// header, and the TLS/HTTP2 fingerprint, so the least-detectable disguise is
/// the real browser with its automation fingerprint removed.
///
/// This deliberately does NOT pin a persona. The previous behaviour
/// (`apply_stealth_profile(FirefoxLinux)`) backward-spoofs `navigator.userAgent`
/// to a fixed persona while a vanilla-launched browser's HTTP header and TLS
/// stack stay at the real version — a JS-vs-HTTP-vs-TLS mismatch that
/// fingerprint scorers (e.g. incolumitas) flag. For an EXPLICIT cross-OS /
/// cross-version persona, call [`apply_stealth_profile`] and launch via
/// [`super::launch_profiled_firefox`] so the launch-time
/// `general.useragent.override` pref makes every layer agree.
pub async fn apply_default_stealth_profile(page: &Page) -> anyhow::Result<()> {
    apply_stealth(page).await
}

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

    #[test]
    fn stealth_js_contains_webdriver_patch() {
        assert!(FIREFOX_STEALTH_JS.contains("webdriver"));
    }

    #[test]
    fn stealth_js_contains_permissions_patch() {
        assert!(FIREFOX_STEALTH_JS.contains("permissions.query"));
    }

    #[test]
    fn stealth_js_contains_permissions_request_stub() {
        assert!(FIREFOX_STEALTH_JS.contains("permissions.request"));
    }

    #[test]
    fn stealth_js_contains_notification_permission_patch() {
        assert!(FIREFOX_STEALTH_JS.contains("Notification, 'permission'"));
    }

    #[test]
    fn stealth_js_does_not_override_plugins_or_mimetypes() {
        // Firefox's real navigator.plugins is a genuine PluginArray even
        // headless; overriding it with a plain Array is a detectable regression
        // (bot.sannysoft.com "Plugins is of type PluginArray"). The disguise
        // must NOT define its own plugins/mimeTypes getters.
        assert!(
            !FIREFOX_STEALTH_JS.contains("Navigator.prototype, 'plugins'"),
            "must not override navigator.plugins — real Firefox PluginArray is more coherent"
        );
        assert!(
            !FIREFOX_STEALTH_JS.contains("Navigator.prototype, 'mimeTypes'"),
            "must not override navigator.mimeTypes"
        );
    }

    #[test]
    fn stealth_js_webdriver_is_false_not_undefined() {
        // A real browser reports `navigator.webdriver === false` (property
        // present, value false). Hiding it to `undefined` is itself a tell
        // (sannysoft "WebDriver (New)" wants false). The disguise pins false.
        assert!(
            FIREFOX_STEALTH_JS.contains("'get webdriver'"),
            "webdriver getter must be present"
        );
        assert!(
            !FIREFOX_STEALTH_JS.contains("() => undefined, 'get webdriver'"),
            "webdriver must not be hidden to undefined — a real browser reports false"
        );
        assert!(FIREFOX_STEALTH_JS.contains("() => false, 'get webdriver'"));
    }

    #[test]
    fn stealth_js_does_not_hardcode_webgl_adapter() {
        // The generic layer must NOT override the WebGL adapter. A hard-coded
        // vendor/renderer is wrong on every host but the one it was written for,
        // and never matches the real rendered pixels (measured tell — see the
        // `headful_truth` probe). On a matched host the real, Gecko-sanitized
        // adapter is most coherent; a cross-OS persona supplies its own through
        // `profile_js`. So the generic stealth body installs no getParameter
        // override at all.
        assert!(
            !FIREFOX_STEALTH_JS.contains("WebGLRenderingContext.prototype.getParameter"),
            "generic layer must not hard-code a WebGL adapter (native passthrough)"
        );
        assert!(
            !FIREFOX_STEALTH_JS.contains("GTX 1050 Ti"),
            "the fabricated GTX 1050 Ti renderer must be gone"
        );
    }

    #[test]
    fn stealth_js_contains_chrome_undefine() {
        assert!(FIREFOX_STEALTH_JS.contains("Object.defineProperty(window, 'chrome'"));
    }

    #[test]
    fn stealth_js_contains_maxTouchPoints_patch() {
        assert!(FIREFOX_STEALTH_JS.contains("maxTouchPoints"));
    }

    #[test]
    fn stealth_js_contains_outerWidth_patch() {
        assert!(FIREFOX_STEALTH_JS.contains("outerWidth"));
    }

    #[test]
    fn stealth_js_contains_outerHeight_patch() {
        assert!(FIREFOX_STEALTH_JS.contains("outerHeight"));
    }

    #[test]
    fn stealth_js_contains_devicePixelRatio_patch() {
        assert!(FIREFOX_STEALTH_JS.contains("devicePixelRatio"));
    }

    #[test]
    fn stealth_js_contains_phantom_cleanup() {
        assert!(FIREFOX_STEALTH_JS.contains("callPhantom"));
        assert!(FIREFOX_STEALTH_JS.contains("_phantom"));
    }

    #[test]
    fn stealth_js_contains_cdc_cleanup() {
        assert!(FIREFOX_STEALTH_JS.contains("cdc_adoQpoasnfa76pfcZLmcfl_"));
    }

    #[test]
    fn stealth_js_contains_iframe_contentWindow_patch() {
        assert!(FIREFOX_STEALTH_JS.contains("HTMLIFrameElement.prototype"));
    }

    #[test]
    fn stealth_js_is_balanced_braces() {
        let mut depth = 0;
        let mut in_string = false;
        let mut string_char = ' ';
        let mut escape = false;
        for c in FIREFOX_STEALTH_JS.chars() {
            if in_string {
                if escape {
                    escape = false;
                    continue;
                }
                if c == '\\' {
                    escape = true;
                    continue;
                }
                if c == string_char {
                    in_string = false;
                }
                continue;
            }
            if c == '"' || c == '\'' || c == '`' {
                in_string = true;
                string_char = c;
                continue;
            }
            match c {
                '{' | '(' | '[' => depth += 1,
                '}' | ')' | ']' => depth -= 1,
                _ => {}
            }
            assert!(depth >= 0, "unbalanced braces at char '{}'", c);
        }
        assert_eq!(depth, 0, "JS has unbalanced braces");
    }

    #[test]
    fn stealth_js_no_bare_single_quotes_in_strings() {
        // Verify no unescaped single quotes inside single-quoted strings
        let mut in_single_quote = false;
        let mut escape = false;
        for c in FIREFOX_STEALTH_JS.chars() {
            if escape {
                escape = false;
                continue;
            }
            if c == '\\' {
                escape = true;
                continue;
            }
            if c == '\'' {
                in_single_quote = !in_single_quote;
                continue;
            }
            if c == '"' && !in_single_quote {
                // toggled by outer logic, skip for this simple check
            }
        }
        // If we got here without assertion failure, basic quote balance holds
    }

    #[test]
    fn stealth_js_contains_permissions_query_patch() {
        assert!(FIREFOX_STEALTH_JS.contains("permissions.query"));
    }

    #[test]
    fn stealth_js_balanced_all_brackets() {
        let mut round = 0i32;
        let mut square = 0i32;
        let mut curly = 0i32;
        let mut in_string = false;
        let mut string_char = ' ';
        let mut escape = false;
        for c in FIREFOX_STEALTH_JS.chars() {
            if in_string {
                if escape { escape = false; continue; }
                if c == '\\' { escape = true; continue; }
                if c == string_char { in_string = false; }
                continue;
            }
            if c == '"' || c == '\'' || c == '`' {
                in_string = true;
                string_char = c;
                continue;
            }
            match c {
                '(' => round += 1,
                ')' => round -= 1,
                '[' => square += 1,
                ']' => square -= 1,
                '{' => curly += 1,
                '}' => curly -= 1,
                _ => {}
            }
            assert!(round >= 0, "unbalanced parens");
            assert!(square >= 0, "unbalanced square brackets");
            assert!(curly >= 0, "unbalanced curly braces");
        }
        assert_eq!(round, 0, "unclosed parens");
        assert_eq!(square, 0, "unclosed square brackets");
        assert_eq!(curly, 0, "unclosed curly braces");
    }

    #[test]
    fn stealth_js_no_eval_calls() {
        // Stealth code should never use eval() — it's a fingerprinting vector.
        let lower = FIREFOX_STEALTH_JS.to_lowercase();
        assert!(!lower.contains("eval("), "stealth JS contains eval() call");
    }

    #[test]
    fn stealth_js_starts_with_iife() {
        assert!(FIREFOX_STEALTH_JS.trim_start().starts_with("(() =>"));
    }

    #[test]
    fn stealth_js_ends_with_iife_invocation() {
        assert!(FIREFOX_STEALTH_JS.trim_end().ends_with("})();"));
    }
}