use super::*;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfileOverrides {
pub user_agent: String,
pub platform: String,
pub navigator_vendor: String,
pub languages: Vec<String>,
pub brands: Vec<(String, String)>,
pub mobile: bool,
pub hardware_concurrency: u32,
pub device_memory: u32,
pub screen_width: u32,
pub screen_height: u32,
pub color_depth: u8,
pub webgl_vendor: String,
pub webgl_renderer: String,
pub timezone: String,
}
impl ProfileOverrides {
#[must_use]
pub fn with_timezone(mut self, timezone: impl Into<String>) -> Self {
self.timezone = timezone.into();
self
}
#[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
}
}
#[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))
}
pub fn firefox_app_version(platform: &str) -> &'static str {
let p = platform.to_ascii_lowercase();
if p.contains("win") {
"5.0 (Windows)"
} else if p.contains("mac") {
"5.0 (Macintosh)"
} else {
"5.0 (X11)"
}
}
fn firefox_oscpu(user_agent: &str, platform: &str) -> String {
if let Some(start) = user_agent.find('(') {
if let Some(end_rel) = user_agent[start + 1..].find(')') {
let comment = &user_agent[start + 1..start + 1 + end_rel];
let os = comment.split("; rv:").next().unwrap_or(comment).trim();
let os = os.strip_prefix("X11; ").unwrap_or(os);
let os = os.strip_prefix("Macintosh; ").unwrap_or(os).trim();
if !os.is_empty() {
return os.to_string();
}
}
}
let p = platform.to_ascii_lowercase();
if p.contains("win") {
"Windows NT 10.0; Win64; x64".to_string()
} else if p.contains("mac") {
"Intel Mac OS X 10.15".to_string()
} else {
"Linux x86_64".to_string()
}
}
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()
}
pub fn profile_to_overrides(profile: &StealthProfile) -> ProfileOverrides {
let facts = profile_facts(*profile);
let hardware = profile_hardware(*profile);
let timezone = facts
.languages
.first()
.map_or("America/New_York", |lang| default_timezone_for_locale(lang))
.to_string();
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(),
timezone,
}
}
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 (_) {}
"#;
pub fn profile_js(overrides: &ProfileOverrides) -> String {
let langs_json = json_array(&overrides.languages);
let lang0_json =
serde_json::json!(overrides.languages.first().map_or("en-US", String::as_str)).to_string();
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);
let device_memory_block = if client_hints.is_some() {
format!(
" Object.defineProperty(Navigator.prototype, 'deviceMemory', {{\n\
\x20 get: __seal(() => {dm}, 'get deviceMemory'),\n\
\x20 enumerable: true,\n\
\x20 configurable: true,\n\
\x20 }});\n",
dm = overrides.device_memory
)
} else {
String::new()
};
let oscpu_block = if client_hints.is_some() {
" try { delete Navigator.prototype.oscpu; } catch (_) {}\n".to_string()
} else {
format!(
" try {{ Object.defineProperty(Navigator.prototype, 'oscpu', {{\n\
\x20 get: __seal(() => {oscpu_json}, 'get oscpu'),\n\
\x20 configurable: true,\n\
\x20 }}); }} catch (_) {{}}\n",
oscpu_json =
serde_json::json!(firefox_oscpu(&overrides.user_agent, &overrides.platform))
)
};
let webgl_getter_block = if overrides.user_agent.contains("Firefox/") {
String::new()
} else {
format!(
r#" try {{
const REND_VAL = {rend};
const VEND_VAL = {vend};
if (REND_VAL) {{
const UNMASKED_VENDOR = 0x9245, UNMASKED_RENDERER = 0x9246;
const GL_RENDERER = 0x1F01;
const wrap = (proto) => {{
const orig = proto.getParameter;
proto.getParameter = __seal(function getParameter(p) {{
if (p === UNMASKED_VENDOR) return VEND_VAL;
if (p === UNMASKED_RENDERER || p === GL_RENDERER) return REND_VAL;
return orig.call(this, p);
}}, 'getParameter');
}};
if (typeof WebGLRenderingContext !== 'undefined') wrap(WebGLRenderingContext.prototype);
if (typeof WebGL2RenderingContext !== 'undefined') wrap(WebGL2RenderingContext.prototype);
}}
}} catch (_) {{}}
"#,
rend = serde_json::json!(overrides.webgl_renderer),
vend = serde_json::json!(overrides.webgl_vendor),
)
};
let speech_block = if overrides.webgl_renderer.is_empty() {
String::new()
} else {
" try { var __sp = window.speechSynthesis; if (__sp) { var __sp_p = Object.getPrototypeOf(__sp); Object.defineProperty(__sp_p, 'getVoices', { value: __seal(function getVoices(){ return []; }, 'getVoices'), writable: true, configurable: true }); } } catch (_) {}\n".to_string()
};
let primary_locale = overrides.languages.first().map_or("en-US", String::as_str);
let timezone_block = intl_spoof_js(primary_locale, &overrides.timezone);
format!(
r#"
(() => {{{seal_prelude}
/* User-Agent + appVersion. userAgent is pinned to the persona; appVersion is
the FROZEN OS-family form a real Firefox actually returns ("5.0 (X11)" /
"5.0 (Windows)" / "5.0 (Macintosh)"). NOT userAgent-minus-"Mozilla/". The
old full-UA form was a value no real Firefox reports (verified live), and it
contradicted the bare engine AND the worker realm (which reports the frozen
native form). Both are derived from the persona so a cross-engine detector
sees a self-consistent, real-Firefox-shaped pair. */
try {{
Object.defineProperty(Navigator.prototype, 'userAgent', {{
get: __seal(() => {ua_json}, 'get userAgent'),
configurable: true,
}});
Object.defineProperty(Navigator.prototype, 'appVersion', {{
get: __seal(() => {app_version_json}, '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 (plural) AND navigator.language (singular). Pinning
only the plural is a tell: FingerprintJS/CreepJS cross-check that
navigator.language === navigator.languages[0], so the singular must be
overridden to the same primary tag or it leaks the host language. */
try {{
Object.defineProperty(Navigator.prototype, 'languages', {{
get: __seal(() => {langs_json}, 'get languages'),
configurable: true,
}});
Object.defineProperty(Navigator.prototype, 'language', {{
get: __seal(() => {lang0_json}, 'get language'),
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'),
enumerable: true,
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 (inner/outer Width/Height, screenX/screenY) are
deliberately NOT overridden (for the SAME reason as screen.* above).
Verified live (tests/surface_truth_live.rs dump_geometry_truth): pinning
window.innerWidth to the persona screen_width while the real window stays
the screen-fit size produced a TRIPLE contradiction, innerWidth !=
document.documentElement.clientWidth (the real layout viewport),
matchMedia('(width)') reporting the real size not the persona, and
innerWidth > screen.width (a window wider than its own screen). A
JS getter cannot move the real layout/matchMedia/screen surfaces, so any
pinned value that exceeds or disagrees with them is a trivially-detected
tell. Leaving the real, self-consistent geometry (identical to a bare
Firefox, which passes the matchMedia/clientWidth checks) is strictly more
coherent. maxTouchPoints is a genuine capability signal (not a dimension
contradicted by any layout surface) and is still pinned to the persona. */
try {{
Object.defineProperty(Navigator.prototype, 'maxTouchPoints', {{
get: __seal(() => {max_touch_points}, 'get maxTouchPoints'),
configurable: true,
}});
}} catch (_) {{}}
/* navigator.oscpu - Firefox-only OS-stamped string; must agree with the UA's
OS token (cross-OS personas otherwise leak the host OS) and be ABSENT for a
Chromium persona (Chrome has no oscpu). See the oscpu_block above. */
{oscpu_block}
{webgl_getter_block}{speech_block}{timezone_block}}})();
"#,
seal_prelude = NATIVE_SEAL_PRELUDE,
timezone_block = timezone_block,
speech_block = speech_block,
ua_json = serde_json::json!(overrides.user_agent),
app_version_json = serde_json::json!(firefox_app_version(&overrides.platform)),
platform_json = serde_json::json!(overrides.platform),
navigator_vendor_json = serde_json::json!(overrides.navigator_vendor),
langs_json = langs_json,
lang0_json = lang0_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,
max_touch_points = if overrides.mobile { 5 } else { 0 },
oscpu_block = oscpu_block,
webgl_getter_block = webgl_getter_block,
)
}
#[cfg(test)]
mod oscpu_unit {
use super::firefox_oscpu;
#[test]
fn extracts_the_os_token_from_each_firefox_ua_family() {
assert_eq!(
firefox_oscpu(
"Mozilla/5.0 (X11; Linux x86_64; rv:151.0) Gecko/20100101 Firefox/151.0",
"Linux x86_64"
),
"Linux x86_64"
);
assert_eq!(
firefox_oscpu(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:151.0) Gecko/20100101 Firefox/151.0",
"Win32"
),
"Windows NT 10.0; Win64; x64"
);
assert_eq!(
firefox_oscpu("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:151.0) Gecko/20100101 Firefox/151.0", "MacIntel"),
"Intel Mac OS X 10.15"
);
}
#[test]
fn never_returns_the_host_when_the_ua_is_malformed() {
assert_eq!(
firefox_oscpu("not a real ua", "Win32"),
"Windows NT 10.0; Win64; x64"
);
assert_eq!(
firefox_oscpu("not a real ua", "MacIntel"),
"Intel Mac OS X 10.15"
);
assert_eq!(
firefox_oscpu("not a real ua", "Linux x86_64"),
"Linux x86_64"
);
assert_eq!(
firefox_oscpu("Mozilla/5.0 () Firefox", "Win32"),
"Windows NT 10.0; Win64; x64"
);
}
#[test]
fn windows_persona_oscpu_never_leaks_linux() {
let oscpu = firefox_oscpu(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:151.0) Gecko/20100101 Firefox/151.0",
"Win32",
);
assert!(
!oscpu.contains("Linux"),
"windows persona oscpu leaked Linux: {oscpu}"
);
}
}