guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
Documentation
//! Materialised profile overrides and override JavaScript.
//!
//! [`ProfileOverrides`] is the owned, pure-data fingerprint surface a
//! profile pins; [`profile_to_overrides`] builds it from the catalogue
//! and [`profile_js`] emits the CDP override script that pins those
//! values in-page.

use super::*;

/// 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 {
    /// `navigator.userAgent` string — the anchor every other surface must cohere with.
    pub user_agent: String,
    /// `navigator.platform` value. Must match the UA's OS family.
    pub platform: String,
    /// `navigator.vendor` value. Empty for engines that do not expose a vendor.
    pub navigator_vendor: 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`. Common desktop = 1920x1080.
    pub screen_width: u32,
    /// `screen.height` (paired with [`Self::screen_width`]).
    pub screen_height: u32,
    /// `screen.colorDepth` / `screen.pixelDepth`.
    pub color_depth: u8,
    /// WebGL `UNMASKED_VENDOR_WEBGL`. Must match the OS / hardware claimed by the UA.
    pub webgl_vendor: String,
    /// WebGL `UNMASKED_RENDERER_WEBGL` (paired with [`Self::webgl_vendor`]).
    pub webgl_renderer: String,
}

impl ProfileOverrides {
    /// Return these profile overrides with hardware/display surfaces replaced.
    #[must_use]
    pub fn with_hardware(mut self, hardware: ProfileHardware) -> Self {
        self.hardware_concurrency = u32::from(hardware.hardware_concurrency);
        self.device_memory = u32::from(hardware.device_memory);
        self.screen_width = hardware.screen_width;
        self.screen_height = hardware.screen_height;
        self.color_depth = hardware.color_depth;
        self.webgl_vendor = hardware.webgl_vendor.into();
        self.webgl_renderer = hardware.webgl_renderer.into();
        self
    }
}

/// Materialise profile overrides using a deterministic hardware variant index.
#[must_use]
pub fn profile_to_overrides_at(
    profile: &StealthProfile,
    hardware_index: usize,
) -> ProfileOverrides {
    profile_to_overrides(profile).with_hardware(profile_hardware_at(*profile, hardware_index))
}

fn languages_from_facts(facts: ProfileFacts) -> Vec<String> {
    facts
        .languages
        .iter()
        .map(|language| (*language).to_string())
        .collect()
}

fn client_hint_brands_for_profile(profile: StealthProfile) -> Vec<(String, String)> {
    profile_client_hint_brands(profile)
        .iter()
        .map(|brand| (brand.brand.to_string(), brand.version.to_string()))
        .collect()
}

/// Materialise the override values for a given profile. Pure.
///
/// The profile catalogue owns browser identity data; this function only
/// converts that pure data into owned values used by CDP JavaScript and tests.
pub fn profile_to_overrides(profile: &StealthProfile) -> ProfileOverrides {
    let facts = profile_facts(*profile);
    let hardware = profile_hardware(*profile);
    ProfileOverrides {
        user_agent: facts.user_agent.into(),
        platform: facts.platform.into(),
        navigator_vendor: profile_navigator_vendor(*profile).into(),
        languages: languages_from_facts(facts),
        brands: client_hint_brands_for_profile(*profile),
        mobile: facts.mobile,
        hardware_concurrency: u32::from(hardware.hardware_concurrency),
        device_memory: u32::from(hardware.device_memory),
        screen_width: hardware.screen_width,
        screen_height: hardware.screen_height,
        color_depth: hardware.color_depth,
        webgl_vendor: hardware.webgl_vendor.into(),
        webgl_renderer: hardware.webgl_renderer.into(),
    }
}

/// Native-function camouflage prelude, shared by every injected stealth
/// script (the generic `FIREFOX_STEALTH_JS` and this per-profile `profile_js`).
///
/// Every getter/method we install via `Object.defineProperty` or by replacing
/// a prototype method is an ordinary JS function whose `.toString()` would
/// otherwise reveal non-native source (e.g. `() => undefined`) — a strong
/// tamper tell that fingerprinters (CreepJS, FingerprintJS) weight heavily and
/// that guise's own probe catalogue flags High-severity.
///
/// This prelude routes `Function.prototype.toString` through a `Proxy` over the
/// *current* implementation. Functions registered via `__seal(fn, label)`
/// report `function <label>() { [native code] }`; the proxy itself reports a
/// native `toString`; every other receiver is delegated to the previous
/// `toString`. Because each preload wraps whatever `Function.prototype.toString`
/// already is, multiple independent scripts chain correctly and a genuine
/// native function still yields its real source. The registry is a `WeakMap`,
/// so membership is invisible to property enumeration (no global tell).
///
/// Injected as plain statements inside each stealth IIFE; `__seal` is then in
/// scope for the rest of that script.
pub(crate) const NATIVE_SEAL_PRELUDE: &str = r#"
    const __native = new WeakMap();
    const __seal = (fn, label) => { try { __native.set(fn, label || (fn && fn.name) || ''); } catch (_) {} return fn; };
    try {
        const __prevToString = Function.prototype.toString;
        const __tsProxy = new Proxy(__prevToString, {
            apply(target, thisArg, args) {
                try {
                    if (__native.has(thisArg)) {
                        // Strip a get/set prefix: Firefox names a native accessor
                        // by its bare property, not by the JS getter name.
                        var __n = String(__native.get(thisArg)).replace(/^(?:get|set) /, '');
                        return 'function ' + __n + '() {\n    [native code]\n}';
                    }
                } catch (_) {}
                if (thisArg === __tsProxy) { return 'function toString() {\n    [native code]\n}'; }
                return Reflect.apply(target, thisArg, args);
            },
        });
        Function.prototype.toString = __tsProxy;
        __native.set(__tsProxy, 'toString');
    } catch (_) {}
"#;

/// Build the override JS for a given profile.
///
/// Distinct from `crate::guise::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 client_hints = client_hints_from_overrides(overrides);
    let brands_json = client_hints
        .as_ref()
        .map(|hints| json_array(&hints.brands))
        .unwrap_or_else(|| "[]".into());
    let full_version_list_json = client_hints
        .as_ref()
        .map(|hints| json_array(&hints.full_version_list))
        .unwrap_or_else(|| "[]".into());
    let client_hint_platform_json = client_hints
        .as_ref()
        .map(|hints| serde_json::json!(hints.platform).to_string())
        .unwrap_or_else(|| serde_json::json!(overrides.platform).to_string());
    let platform_version_json = client_hints
        .as_ref()
        .map(|hints| serde_json::json!(hints.platform_version).to_string())
        .unwrap_or_else(|| r#""""#.into());
    let architecture_json = client_hints
        .as_ref()
        .map(|hints| serde_json::json!(hints.architecture).to_string())
        .unwrap_or_else(|| r#""""#.into());
    let bitness_json = client_hints
        .as_ref()
        .map(|hints| serde_json::json!(hints.bitness).to_string())
        .unwrap_or_else(|| r#""""#.into());
    let model_json = client_hints
        .as_ref()
        .map(|hints| serde_json::json!(hints.model).to_string())
        .unwrap_or_else(|| r#""""#.into());
    let ua_full_version_json = client_hints
        .as_ref()
        .map(|hints| serde_json::json!(hints.ua_full_version).to_string())
        .unwrap_or_else(|| r#""""#.into());
    let wow64 = client_hints.as_ref().is_some_and(|hints| hints.wow64);

    // `navigator.deviceMemory` is a Chromium-only API — real Firefox does not
    // expose it at all (the property is absent from Navigator.prototype). Pinning
    // it on a Firefox persona would ADD a property the engine never has, an
    // obvious cross-engine tell. Only emit the override for a Chromium persona
    // (one that carries client-hint brands); for Firefox, leave deviceMemory
    // genuinely absent.
    let device_memory_block = if client_hints.is_some() {
        format!(
            "        Object.defineProperty(Navigator.prototype, 'deviceMemory', {{\n\
             \x20           get: __seal(() => {dm}, 'get deviceMemory'),\n\
             \x20           configurable: true,\n\
             \x20       }});\n",
            dm = overrides.device_memory
        )
    } else {
        String::new()
    };

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

    /* navigator.vendor must match the browser engine family. */
    try {{
        Object.defineProperty(Navigator.prototype, 'vendor', {{
            get: __seal(() => {navigator_vendor_json}, 'get vendor'),
            configurable: true,
        }});
    }} catch (_) {{}}

    /* navigator.languages */
    try {{
        Object.defineProperty(Navigator.prototype, 'languages', {{
            get: __seal(() => {langs_json}, 'get languages'),
            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: __seal(() => ({{
                    brands,
                    mobile: {mobile},
                    platform: {platform_json},
                    getHighEntropyValues: __seal((hints) => Promise.resolve({{
                        brands,
                        fullVersionList: {full_version_list_json},
                        mobile: {mobile},
                        platform: {client_hint_platform_json},
                        platformVersion: {platform_version_json},
                        architecture: {architecture_json},
                        bitness: {bitness_json},
                        model: {model_json},
                        uaFullVersion: {ua_full_version_json},
                        wow64: {wow64},
                    }}), 'getHighEntropyValues'),
                    toJSON: __seal(() => ({{ brands, mobile: {mobile}, platform: {client_hint_platform_json} }}), 'toJSON'),
                }}), 'get userAgentData'),
                configurable: true,
            }});
        }}
    }} catch (_) {{}}

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

    /* screen.* (width, height, availWidth, availHeight, colorDepth, pixelDepth)
       are deliberately NOT
       overridden. A real browser's screen dimensions AGREE with the CSS
       matchMedia layer (the `device-width`/`device-height` media features), but
       overriding the JS getters does NOT change what matchMedia reports — so a
       claimed screen size that differs from the real rendering surface is an
       INCONSISTENCY a detector flags (incolumitas MQ_SCREEN). A bare Firefox
       passes those media-query checks; leaving the real, self-consistent screen
       is strictly more coherent than a pinned-but-inconsistent one. */

    /* Window dimensions and touch capability must agree with the same
       profile as screen.* and userAgentData.mobile. */
    try {{
        Object.defineProperty(window, 'outerWidth', {{
            get: __seal(() => {sw}, 'get outerWidth'),
            configurable: true,
        }});
        Object.defineProperty(window, 'outerHeight', {{
            get: __seal(() => {sh} + {outer_height_extra}, 'get outerHeight'),
            configurable: true,
        }});
        Object.defineProperty(window, 'innerWidth', {{
            get: __seal(() => {sw}, 'get innerWidth'),
            configurable: true,
        }});
        Object.defineProperty(window, 'innerHeight', {{
            get: __seal(() => {sh}, 'get innerHeight'),
            configurable: true,
        }});
        Object.defineProperty(window, 'screenX', {{
            get: __seal(() => 0, 'get screenX'),
            configurable: true,
        }});
        Object.defineProperty(window, 'screenY', {{
            get: __seal(() => {screen_y}, 'get screenY'),
            configurable: true,
        }});
        Object.defineProperty(Navigator.prototype, 'maxTouchPoints', {{
            get: __seal(() => {max_touch_points}, 'get maxTouchPoints'),
            configurable: true,
        }});
    }} catch (_) {{}}

    /* WebGL VENDOR/RENDERER and UNMASKED_* parameters. Only pinned for a
       CROSS-OS persona (one whose claimed OS differs from the host), where the
       real adapter string would contradict the UA. When the renderer is empty
       the persona is matched-host: Gecko's own sanitized adapter is exposed
       untouched (most coherent, and its pixels actually match). The
       replacement getParameter is sealed so its toString reports native. */
    try {{
        const REND_VAL = {webgl_renderer_json};
        const VEND_VAL = {webgl_vendor_json};
        if (REND_VAL) {{
            const VENDOR = 0x1F00, RENDERER = 0x1F01, VEND = 0x9245, REND = 0x9246;
            const wrap = (proto) => {{
                const orig = proto.getParameter;
                proto.getParameter = __seal(function getParameter(p) {{
                    if (p === VENDOR || p === VEND) return VEND_VAL;
                    if (p === RENDERER || p === REND) return REND_VAL;
                    return orig.call(this, p);
                }}, 'getParameter');
            }};
            if (typeof WebGLRenderingContext !== 'undefined') wrap(WebGLRenderingContext.prototype);
            if (typeof WebGL2RenderingContext !== 'undefined') wrap(WebGL2RenderingContext.prototype);
        }}
    }} catch (_) {{}}
}})();
"#,
        seal_prelude = NATIVE_SEAL_PRELUDE,
        ua_json = serde_json::json!(overrides.user_agent),
        platform_json = serde_json::json!(overrides.platform),
        navigator_vendor_json = serde_json::json!(overrides.navigator_vendor),
        langs_json = langs_json,
        brands_json = brands_json,
        full_version_list_json = full_version_list_json,
        client_hint_platform_json = client_hint_platform_json,
        platform_version_json = platform_version_json,
        architecture_json = architecture_json,
        bitness_json = bitness_json,
        model_json = model_json,
        ua_full_version_json = ua_full_version_json,
        wow64 = wow64,
        mobile = overrides.mobile,
        hwc = overrides.hardware_concurrency,
        device_memory_block = device_memory_block,
        sw = overrides.screen_width,
        sh = overrides.screen_height,
        outer_height_extra = if overrides.mobile { 0 } else { 88 },
        screen_y = if overrides.mobile { 0 } else { 30 },
        max_touch_points = if overrides.mobile { 5 } else { 0 },
        webgl_vendor_json = serde_json::json!(overrides.webgl_vendor),
        webgl_renderer_json = serde_json::json!(overrides.webgl_renderer),
    )
}