use runtime_foxdriver::browser::Page;
use std::sync::LazyLock;
use crate::fingerprint::NATIVE_SEAL_PRELUDE;
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 (_) {}
"#;
pub(super) static FIREFOX_STEALTH_JS: LazyLock<String> = LazyLock::new(|| {
format!("(() => {{{prelude}\n{body}\n}})();\n", prelude = NATIVE_SEAL_PRELUDE, body = FIREFOX_STEALTH_BODY)
});
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(())
}
pub async fn apply_stealth_profile(
page: &Page,
profile: &crate::StealthProfile,
) -> anyhow::Result<()> {
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:?}"))?;
page.evaluate(&profile_js)
.await
.map_err(|e| anyhow::anyhow!("stealth profile JS evaluate failed (malformed override script?): {e:?}"))?;
Ok(())
}
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() {
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() {
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() {
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() {
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 {
}
}
}
#[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() {
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("})();"));
}
}