use crate::ProfileOverrides;
use runtime_foxdriver::browser::{launch_firefox_self_managed, FoxBrowserConfig, Page};
use serde_json::{json, Map, Value};
use std::os::unix::fs::PermissionsExt;
use std::sync::atomic::{AtomicU64, Ordering};
static LAUNCH_SEQ: AtomicU64 = AtomicU64::new(0);
pub const REYNARD_CONFIG_ENV: &str = "REYNARD_CONFIG";
const ENV_CHUNK_BYTES: usize = 100_000;
const LINUX_STD_FONTS: &[&str] = &[
"DejaVu Sans",
"DejaVu Serif",
"DejaVu Sans Mono",
"Liberation Sans",
"Liberation Serif",
"Liberation Mono",
"Noto Sans",
"Noto Serif",
"Noto Mono",
"Noto Color Emoji",
"FreeSans",
"FreeSerif",
"FreeMono",
"Cantarell",
"Droid Sans Fallback",
];
#[must_use]
pub fn reynard_config(overrides: &ProfileOverrides) -> Value {
let mut cfg = Map::new();
cfg.insert("navigator.userAgent".into(), json!(overrides.user_agent));
cfg.insert("navigator.webdriver".into(), json!(false));
cfg.insert("navigator.platform".into(), json!(overrides.platform));
cfg.insert(
"navigator.hardwareConcurrency".into(),
json!(overrides.hardware_concurrency),
);
if let Some(primary) = overrides.languages.first() {
cfg.insert("navigator.language".into(), json!(primary));
}
if !overrides.languages.is_empty() {
cfg.insert("navigator.languages".into(), json!(overrides.languages));
}
cfg.insert(
"navigator.maxTouchPoints".into(),
json!(if overrides.mobile { 5 } else { 0 }),
);
cfg.insert("screen.width".into(), json!(overrides.screen_width));
cfg.insert("screen.height".into(), json!(overrides.screen_height));
cfg.insert("screen.colorDepth".into(), json!(overrides.color_depth));
cfg.insert("screen.pixelDepth".into(), json!(overrides.color_depth));
if overrides.platform.contains("Linux") {
cfg.insert("fonts".into(), json!(LINUX_STD_FONTS));
}
if !overrides.webgl_vendor.is_empty() {
cfg.insert("webGl:vendor".into(), json!(overrides.webgl_vendor));
}
if !overrides.webgl_renderer.is_empty() {
cfg.insert("webGl:renderer".into(), json!(overrides.webgl_renderer));
}
cfg.insert("headers.User-Agent".into(), json!(overrides.user_agent));
if !overrides.languages.is_empty() {
cfg.insert(
"headers.Accept-Language".into(),
json!(accept_language(&overrides.languages)),
);
}
Value::Object(cfg)
}
#[must_use]
pub fn reynard_config_env(overrides: &ProfileOverrides) -> Vec<(String, String)> {
let blob = reynard_config(overrides).to_string();
if blob.len() <= ENV_CHUNK_BYTES {
return vec![(REYNARD_CONFIG_ENV.to_string(), blob)];
}
blob.as_bytes()
.chunks(ENV_CHUNK_BYTES)
.enumerate()
.map(|(i, part)| {
(
format!("{REYNARD_CONFIG_ENV}_{}", i + 1),
String::from_utf8_lossy(part).into_owned(),
)
})
.collect()
}
fn accept_language(langs: &[String]) -> String {
langs
.iter()
.enumerate()
.map(|(i, lang)| {
if i == 0 {
lang.clone()
} else {
let q = (10 - i.min(9)) as f64 / 10.0;
format!("{lang};q={q}")
}
})
.collect::<Vec<_>>()
.join(",")
}
fn reynard_wrapper_script(cfg_path: &str, reynard_bin: &str) -> String {
format!(
"#!/bin/sh\n\
# guise -> reynard launch wrapper (per-launch {env}, no global env)\n\
{env}=\"$(cat '{cfg_path}')\"\n\
export {env}\n\
exec '{reynard_bin}' \"$@\"\n",
env = REYNARD_CONFIG_ENV,
)
}
#[must_use]
pub fn reynard_engine_major(reynard_bin: &str) -> Option<u32> {
let out = std::process::Command::new(reynard_bin)
.arg("--version")
.output()
.ok()?;
let text = String::from_utf8_lossy(&out.stdout);
text.split_whitespace()
.find(|t| t.contains('.') && t.chars().next().is_some_and(|c| c.is_ascii_digit()))
.and_then(|t| t.split('.').next())
.and_then(|n| n.parse::<u32>().ok())
}
#[must_use]
pub fn align_ua_to_engine(ua: &str, engine_major: u32) -> String {
let persona_major = ua
.rsplit("Firefox/")
.next()
.filter(|_| ua.contains("Firefox/"))
.and_then(|s| s.split('.').next())
.and_then(|s| s.parse::<u32>().ok());
match persona_major {
Some(p) if p != engine_major => ua
.replace(&format!("rv:{p}."), &format!("rv:{engine_major}."))
.replace(&format!("Firefox/{p}."), &format!("Firefox/{engine_major}.")),
_ => ua.to_string(),
}
}
#[must_use]
pub fn identity_seed(key: &str) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in key.as_bytes() {
h ^= u64::from(*b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
pub async fn launch_reynard(
reynard_bin: &str,
profile: &crate::StealthProfile,
headless: bool,
) -> anyhow::Result<Page> {
launch_reynard_with_config(
reynard_bin,
profile,
FoxBrowserConfig {
headless,
viewport_width: 1280,
viewport_height: 720,
..Default::default()
},
)
.await
}
pub async fn launch_reynard_with_config(
reynard_bin: &str,
profile: &crate::StealthProfile,
mut config: FoxBrowserConfig,
) -> anyhow::Result<Page> {
let mut overrides = crate::profile_to_overrides(profile);
if let Some(major) = reynard_engine_major(reynard_bin) {
overrides.user_agent = align_ua_to_engine(&overrides.user_agent, major);
}
let mut cfg = reynard_config(&overrides);
if let Some(dir_key) = config.profile_dir.as_deref().filter(|d| !d.is_empty()) {
if let Value::Object(map) = &mut cfg {
let seed = identity_seed(dir_key) % 1_000_000;
map.insert("canvas:seed".into(), json!(seed));
map.insert("audio:seed".into(), json!(seed));
map.insert("fonts:spacing_seed".into(), json!(seed));
}
}
let config_json = cfg.to_string();
let seq = LAUNCH_SEQ.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("reynard-launch-{}-{}", std::process::id(), seq));
std::fs::create_dir_all(&dir)
.map_err(|e| anyhow::anyhow!("create reynard launch dir {dir:?}: {e}"))?;
let cfg_path = dir.join("config.json");
std::fs::write(&cfg_path, &config_json)
.map_err(|e| anyhow::anyhow!("write reynard config: {e}"))?;
let wrapper_path = dir.join("launch.sh");
let script = reynard_wrapper_script(&cfg_path.to_string_lossy(), reynard_bin);
std::fs::write(&wrapper_path, script)
.map_err(|e| anyhow::anyhow!("write reynard wrapper: {e}"))?;
let mut perms = std::fs::metadata(&wrapper_path)
.map_err(|e| anyhow::anyhow!("stat reynard wrapper: {e}"))?
.permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&wrapper_path, perms)
.map_err(|e| anyhow::anyhow!("chmod reynard wrapper: {e}"))?;
config.executable_path = Some(wrapper_path.to_string_lossy().into_owned());
config.user_js_content = Some(merge_reynard_prefs(config.user_js_content.take()));
launch_firefox_self_managed(config).await
}
fn merge_reynard_prefs(existing: Option<String>) -> String {
match existing {
Some(e) if !e.trim().is_empty() => format!("{e}\n{REYNARD_PROFILE_PREFS}"),
_ => REYNARD_PROFILE_PREFS.to_string(),
}
}
const REYNARD_PROFILE_PREFS: &str = "user_pref(\"dom.webdriver.enabled\", false);";
#[cfg(test)]
mod tests {
use super::*;
use crate::{profile_to_overrides, StealthProfile};
fn cfg_for(profile: StealthProfile) -> Value {
reynard_config(&profile_to_overrides(&profile))
}
#[test]
fn maps_navigator_and_screen_from_persona() {
let ov = profile_to_overrides(&StealthProfile::FirefoxLinux);
let cfg = reynard_config(&ov);
assert_eq!(cfg["navigator.userAgent"], json!(ov.user_agent));
assert_eq!(cfg["navigator.platform"], json!(ov.platform));
assert_eq!(
cfg["navigator.hardwareConcurrency"],
json!(ov.hardware_concurrency)
);
assert_eq!(cfg["screen.width"], json!(ov.screen_width));
assert_eq!(cfg["screen.height"], json!(ov.screen_height));
}
#[test]
fn navigator_webdriver_pinned_false_for_every_persona() {
for p in [
StealthProfile::FirefoxLinux,
StealthProfile::FirefoxWindows,
StealthProfile::ChromeWindowsStable,
] {
assert_eq!(cfg_for(p)["navigator.webdriver"], json!(false));
}
}
#[test]
fn firefox_linux_omits_webgl_keys_for_native_passthrough() {
let cfg = cfg_for(StealthProfile::FirefoxLinux);
assert!(
cfg.get("webGl:vendor").is_none(),
"matched-host persona must not pin a WebGL vendor"
);
assert!(cfg.get("webGl:renderer").is_none());
}
#[test]
fn cross_os_persona_pins_webgl() {
let cfg = cfg_for(StealthProfile::ChromeWindowsStable);
assert!(
cfg.get("webGl:renderer").is_some(),
"a persona with a non-empty renderer must pin webGl:renderer"
);
}
#[test]
fn header_user_agent_matches_navigator() {
let cfg = cfg_for(StealthProfile::FirefoxLinux);
assert_eq!(cfg["headers.User-Agent"], cfg["navigator.userAgent"]);
}
#[test]
fn accept_language_q_values_descend() {
let al = accept_language(&["en-US".into(), "en".into(), "fr".into()]);
assert_eq!(al, "en-US,en;q=0.9,fr;q=0.8");
}
#[test]
fn env_is_single_var_for_small_config() {
let env = reynard_config_env(&profile_to_overrides(&StealthProfile::FirefoxLinux));
assert_eq!(env.len(), 1);
assert_eq!(env[0].0, REYNARD_CONFIG_ENV);
let parsed: Value = serde_json::from_str(&env[0].1).expect("config is valid JSON");
assert!(parsed.is_object());
}
#[test]
fn languages_drive_navigator_language() {
let ov = profile_to_overrides(&StealthProfile::FirefoxLinux);
let cfg = reynard_config(&ov);
if let Some(first) = ov.languages.first() {
assert_eq!(cfg["navigator.language"], json!(first));
}
}
#[test]
fn wrapper_script_loads_config_and_execs_binary() {
let s = reynard_wrapper_script("/tmp/cfg.json", "/opt/reynard/firefox");
assert!(s.starts_with("#!/bin/sh"));
assert!(
s.contains(&format!("{REYNARD_CONFIG_ENV}=\"$(cat '/tmp/cfg.json')\"")),
"wrapper must load config from the file under the reynard env name: {s}"
);
assert!(s.contains(&format!("export {REYNARD_CONFIG_ENV}")));
assert!(
s.contains("exec '/opt/reynard/firefox' \"$@\""),
"wrapper must exec the binary forwarding BiDi flags: {s}"
);
}
#[test]
fn align_ua_to_engine_rewrites_firefox_major() {
let persona = "Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0";
let aligned = align_ua_to_engine(persona, 150);
assert_eq!(
aligned,
"Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0"
);
assert!(aligned.contains("Gecko/20100101"));
}
#[test]
fn align_ua_to_engine_is_noop_when_matching_or_absent() {
let persona = "Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0";
assert_eq!(align_ua_to_engine(persona, 150), persona);
let other = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Safari/537.36";
assert_eq!(align_ua_to_engine(other, 150), other);
}
#[test]
fn identity_seed_is_stable_and_distinct() {
assert_eq!(identity_seed("/profiles/acct-a"), identity_seed("/profiles/acct-a"));
assert_ne!(identity_seed("/profiles/acct-a"), identity_seed("/profiles/acct-b"));
assert_ne!(identity_seed("acct-1"), identity_seed("acct-2"));
}
#[test]
fn merge_reynard_prefs_none_is_just_webdriver_pref() {
assert_eq!(merge_reynard_prefs(None), REYNARD_PROFILE_PREFS);
assert_eq!(merge_reynard_prefs(Some(" ".into())), REYNARD_PROFILE_PREFS);
}
#[test]
fn merge_reynard_prefs_keeps_caller_prefs() {
let merged = merge_reynard_prefs(Some("user_pref(\"network.proxy.type\", 1);".into()));
assert!(merged.contains("network.proxy.type"), "caller pref preserved");
assert!(merged.contains("dom.webdriver.enabled"), "reynard pref added");
}
#[test]
fn wrapper_forwards_bidi_flags_via_args() {
assert!(reynard_wrapper_script("/c", "/b").contains("\"$@\""));
}
}