use anyhow::Context;
use runtime_foxdriver::browser::{FoxBrowserConfig, Page};
use crate::fingerprint::{profile_user_agent, user_agent_facts, UserAgentBrowser};
mod inject;
mod lurien;
mod session_age;
mod userjs;
pub use inject::{
apply_default_stealth_profile, apply_stealth, apply_stealth_profile,
apply_stealth_profile_with_overrides,
};
pub use lurien::{
LURIEN_CONFIG_ENV,
REYNARD_CONFIG_ENV,
align_ua_to_engine,
firefox_engine_major,
identity_seed,
launch_lurien,
launch_with_config,
live_engine_bin,
lurien_config,
lurien_config_env,
resolve_lurien_bin,
};
pub use session_age::{apply_session_age, generate_session_age, session_age_js, SessionAgeSeed};
pub use userjs::{automation_prefs, build_user_js};
pub(crate) fn firefox_engine_family_gate(profile: &crate::StealthProfile) -> anyhow::Result<()> {
let family = user_agent_facts(profile_user_agent(*profile)).browser;
if !matches!(family, UserAgentBrowser::Firefox) {
return Err(anyhow::anyhow!(
"launch_profiled_firefox only supports Firefox-family profiles; \
{profile:?} ({family:?}) cannot be launched on a Firefox engine (G092)"
));
}
Ok(())
}
pub async fn launch_profiled_firefox(
mut config: FoxBrowserConfig,
profile: &crate::StealthProfile,
) -> anyhow::Result<Page> {
enforce_persona_launch_coherence(profile, config.proxy.is_none())?;
firefox_engine_family_gate(profile)?;
let mut overrides = crate::profile_to_overrides(profile);
if let Some(major) =
firefox_engine_major(config.executable_path.as_deref().unwrap_or("firefox"))
{
overrides.user_agent = align_ua_to_engine(&overrides.user_agent, major);
}
surface_cross_os_rendering_tell(&overrides);
let user_js = build_user_js(&overrides);
config.user_js_content = Some(match config.user_js_content {
Some(existing) => format!("{}\n{}", existing, user_js),
None => user_js,
});
let age_key: String = config
.profile_dir
.as_deref()
.filter(|d| !d.is_empty())
.unwrap_or("guise-default-session-age")
.to_string();
let persona_seed: Option<u64> = config
.profile_dir
.as_deref()
.filter(|d| !d.is_empty())
.map(identity_seed);
config
.env
.push(("TZ".to_string(), overrides.timezone.clone()));
let page = runtime_foxdriver::browser::launch_firefox_self_managed(config).await?;
apply_stealth_profile_with_overrides(&page, &overrides).await?;
let fp_config = crate::fingerprint::FingerprintConfig {
seed: persona_seed,
..crate::fingerprint::FingerprintConfig::default()
};
crate::fingerprint::apply_fingerprint(&page, &fp_config).await?;
let session_age = generate_session_age(identity_seed(&age_key) % 1_000_000);
apply_session_age(&page, &session_age)
.await
.context("launch_profiled_firefox: apply session age")?;
Ok(page)
}
pub async fn launch_default_profiled_firefox(config: FoxBrowserConfig) -> anyhow::Result<Page> {
launch_profiled_firefox(config, &crate::StealthProfile::FirefoxLinux).await
}
pub fn enforce_persona_launch_coherence(
profile: &crate::StealthProfile,
proxyless: bool,
) -> anyhow::Result<()> {
crate::http::session_coherence::persona_full_stack_coherence(*profile).map_err(|e| {
anyhow::anyhow!("refusing to launch persona {profile:?}: incoherent fingerprint. {e}")
})?;
surface_host_network_tell(proxyless, profile);
Ok(())
}
fn surface_host_network_tell(proxyless: bool, profile: &crate::StealthProfile) {
if !proxyless {
return;
}
use crate::http::session_coherence::{configured_host_initial_ttl, host_initial_ttl};
let Some(host_ttl) = configured_host_initial_ttl().or_else(host_initial_ttl) else {
return;
};
if let crate::fingerprint::NetworkOsCoherence::Mismatch {
expected_os,
expected_ttl,
observed_initial_ttl,
} = crate::fingerprint::os_network_coherence(*profile, host_ttl)
{
tracing::warn!(
"persona {profile:?} claims {expected_os:?} (initial TTL {expected_ttl}) but this \
proxyless egress host's TCP/IP stack stamps TTL {observed_initial_ttl}, the IP \
layer will betray the persona. Front the launch with a TCP-OS-normalizing proxy, \
or match the persona to the host OS."
);
}
}
pub(crate) fn cross_os_rendering_mismatch(persona_platform: &str, host_os: &str) -> bool {
fn family(s: &str) -> &'static str {
if s.contains("Win") {
"windows"
} else if s.contains("Mac") {
"macos"
} else if s.contains("Linux") || s.contains("X11") {
"linux"
} else {
"other"
}
}
let persona = family(persona_platform);
persona != "other" && persona != host_os
}
fn surface_cross_os_rendering_tell(overrides: &crate::ProfileOverrides) {
if cross_os_rendering_mismatch(&overrides.platform, std::env::consts::OS) {
tracing::warn!(
"persona platform {:?} differs from this host OS ({}) on the stock-Firefox path: \
ENGINE-RENDERED surfaces still betray the real OS, font enumeration \
(measureText/offsetWidth/document.fonts) reports the host's installed fonts, the \
scrollbar width is the host toolkit's, canvas/audio render on the host stack, and \
the WebGL DEEP PARAMETERS (getSupportedExtensions + MAX_* limits) are the host GL \
driver's even though the renderer/vendor STRINGS are persona-coherent, a detector \
cross-referencing the ANGLE/Direct3D renderer against the limits sees the mismatch. \
navigator.gpu (WebGPU) presence is also HOST/engine-conditional, absent on a Linux \
host, so a Windows/Mac persona lacks it though the real target OS (WebGPU default-on) \
has it; it is not soundly JS-spoofable (a large async API). \
The stock JS path cannot soundly spoof rendered surfaces nor the WebGL parameter set \
(a pixel/layout/getExtension/allocation oracle disproves faked values). The \
JS-readable surfaces (UA/platform/oscpu/timezone/WebGL renderer+vendor \
strings/hardwareConcurrency) ARE coherent. lurien helps at the engine level (font \
WHITELIST + GL strings/params, and it DOES farble audio + perturb the text-canvas via \
glyph spacing in every realm for per-identity UNLINKABILITY) but does NOT fix cross-OS \
MIMICRY: it does not re-render the target OS's glyph outlines/metrics, so a lurien \
Windows persona's text canvas is host glyphs + per-identity noise (matching no real \
Windows machine) and font enumeration still shows host fonts. Match the persona to the \
host OS for fully coherent rendered surfaces.",
overrides.platform,
std::env::consts::OS
);
}
}
#[cfg(test)]
mod cross_os_rendering_tell_tests {
use super::cross_os_rendering_mismatch;
#[test]
fn windows_or_mac_persona_on_linux_host_is_a_mismatch() {
assert!(cross_os_rendering_mismatch("Win32", "linux"));
assert!(cross_os_rendering_mismatch("Win64", "linux"));
assert!(cross_os_rendering_mismatch("MacIntel", "linux"));
}
#[test]
fn matched_persona_and_host_is_not_a_mismatch() {
assert!(!cross_os_rendering_mismatch("Linux x86_64", "linux"));
assert!(!cross_os_rendering_mismatch("Win32", "windows"));
assert!(!cross_os_rendering_mismatch("MacIntel", "macos"));
}
#[test]
fn unrecognized_persona_platform_makes_no_claim() {
assert!(!cross_os_rendering_mismatch("SomethingExotic", "linux"));
assert!(!cross_os_rendering_mismatch("", "linux"));
}
#[test]
fn linux_persona_on_windows_or_mac_host_is_a_mismatch() {
assert!(cross_os_rendering_mismatch("Linux x86_64", "windows"));
assert!(cross_os_rendering_mismatch("Linux x86_64", "macos"));
}
}
#[cfg(test)]
mod apply_path_law10_audit {
use std::fs;
use std::path::{Path, PathBuf};
fn rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let p = entry.path();
if p.is_dir() {
rs_files(&p, out);
} else if p.extension().and_then(|e| e.to_str()) == Some("rs") {
out.push(p);
}
}
}
fn is_full_line_comment(line: &str) -> bool {
line.trim_start().starts_with("//")
}
#[test]
fn apply_path_never_swallows_an_evaluate_or_apply() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let mut files = Vec::new();
rs_files(&root.join("src/browser"), &mut files);
rs_files(&root.join("src/fingerprint"), &mut files);
assert!(
files.len() >= 4,
"apply-path audit found only {} files, the walk is mis-rooted; it must \
cover the browser + fingerprint apply trees",
files.len()
);
let method_tokens = [
concat!(".eval", "uate("),
concat!(".add_preload", "_script("),
concat!("apply_finger", "print("),
concat!("apply_steal", "th"),
];
let swallow_tokens = [
concat!("let _", " ="),
concat!(".ok", "()"),
concat!("unwrap", "_or"),
concat!("Err(_)", " =>"),
];
let mut scanned_method_lines = 0usize;
for f in &files {
let Ok(src) = fs::read_to_string(f) else {
continue;
};
for (idx, line) in src.lines().enumerate() {
if is_full_line_comment(line) {
continue;
}
if !method_tokens.iter().any(|t| line.contains(t)) {
continue;
}
scanned_method_lines += 1;
if let Some(swallow) = swallow_tokens.iter().find(|t| line.contains(*t)) {
panic!(
"{}:{}: a Page apply/evaluate call is paired with the result-swallowing \
token {swallow:?} (Law 10 / G262). A swallowed stealth-apply error ships a \
half-stealthed page while the caller sees success. Surface it with \
`.map_err(...)?`, never bind-and-discard. Line: {}",
f.display(),
idx + 1,
line.trim()
);
}
}
}
assert!(
scanned_method_lines >= 3,
"apply-path audit matched only {scanned_method_lines} apply/eval call sites, the \
method tokens have drifted from the real apply path and the guard is now inert"
);
}
}
#[cfg(test)]
mod persona_gate_wiring_audit {
use std::fs;
use std::path::Path;
#[test]
fn every_persona_launch_entrypoint_invokes_the_coherence_gate() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let enforce = concat!("enforce_persona_launch", "_coherence(");
let gate = concat!("persona_full_stack", "_coherence(");
let checks: [(&str, &str, &str, &str); 3] = [
(
"src/browser/mod.rs",
concat!("fn launch_profiled", "_firefox("),
enforce,
"launch_profiled_firefox must call the shared enforcement primitive",
),
(
"src/browser/lurien.rs",
concat!("fn launch", "_with_config("),
enforce,
"launch_with_config must call the shared enforcement primitive",
),
(
"src/browser/mod.rs",
concat!("fn enforce_persona_launch", "_coherence("),
gate,
"the enforcement primitive must call the hard coherence gate",
),
];
for (rel, fn_sig, needed, proves) in checks {
let src = fs::read_to_string(root.join(rel))
.unwrap_or_else(|e| panic!("cannot read {rel} for the wiring audit: {e}"));
let start = src.find(fn_sig).unwrap_or_else(|| {
panic!("{rel}: fn signature {fn_sig:?} not found, the wiring audit is mis-targeted")
});
let after = &src[start + fn_sig.len()..];
let end = after
.find("\npub ")
.map_or(src.len(), |off| start + fn_sig.len() + off);
let body = &src[start..end];
assert!(
body.contains(needed),
"{rel}: {proves}: {needed} not found in the body of {fn_sig}. A launch \
boundary is UNWIRED; an incoherent persona could launch undetected."
);
}
}
}
#[cfg(test)]
mod lurien_js_spoof_separation_audit {
use std::fs;
use std::path::Path;
#[test]
fn lurien_launcher_does_not_call_js_spoof_layers() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let src = fs::read_to_string(root.join("src/browser/lurien.rs"))
.expect("lurien source must be readable");
let start = src
.find(concat!("fn launch", "_with_config("))
.expect("launch_with_config must exist");
let after = &src[start..];
let end = after.find("\npub ").map_or(src.len(), |off| start + off);
let body = &src[start..end];
let forbidden = [
concat!("apply_steal", "th_profile"),
concat!("apply_steal", "th_profile_with_overrides"),
concat!("apply_finger", "print("),
];
for token in forbidden {
assert!(
!body.contains(token),
"src/browser/lurien.rs: launch_with_config must NOT call the JS spoof \
layer (forbidden token {token:?}). The lurien engine handles these surfaces \
natively; adding the JS layer would fight the engine and create coherence tells."
);
}
}
#[test]
fn stock_firefox_launcher_calls_js_spoof_layers() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let src = fs::read_to_string(root.join("src/browser/mod.rs"))
.expect("browser/mod.rs must be readable");
let start = src
.find(concat!("fn launch_profiled", "_firefox("))
.expect("launch_profiled_firefox must exist");
let after = &src[start..];
let end = after.find("\npub ").map_or(src.len(), |off| start + off);
let body = &src[start..end];
let required = [
(
concat!("apply_steal", "th_profile_with_overrides"),
"the navigator/header/runtime stealth layer",
),
(
concat!("apply_finger", "print("),
"the canvas/audio/font/WebGL fingerprint evasion layer",
),
];
for (token, what) in required {
assert!(
body.contains(token),
"src/browser/mod.rs: launch_profiled_firefox must call {what} ({token:?}). \
Stock Firefox has no native spoofing for these surfaces; omitting the JS layer \
would ship a detectable browser."
);
}
}
}
#[cfg(test)]
mod browser_launch_profile_gate {
use super::firefox_engine_family_gate;
use crate::StealthProfile;
fn rejected_by_engine_gate(profile: &StealthProfile) -> bool {
match firefox_engine_family_gate(profile) {
Ok(()) => false,
Err(e) => format!("{e}").contains("cannot be launched on a Firefox engine"),
}
}
#[test]
fn firefox_profile_passes_engine_gate() {
assert!(
firefox_engine_family_gate(&StealthProfile::FirefoxLinux).is_ok(),
"FirefoxLinux must pass the Firefox engine-family gate"
);
assert!(!rejected_by_engine_gate(&StealthProfile::FirefoxLinux));
}
#[test]
fn chrome_profile_is_refused_by_firefox_engine_gate() {
assert!(
rejected_by_engine_gate(&StealthProfile::ChromeWindowsStable),
"Chromium profile must be refused by the Firefox engine-family gate"
);
}
#[test]
fn safari_profile_is_refused_by_firefox_engine_gate() {
assert!(
rejected_by_engine_gate(&StealthProfile::SafariMacStable),
"Safari profile must be refused by the Firefox engine-family gate"
);
}
#[test]
fn firefox_mac_profile_passes_engine_gate() {
assert!(
firefox_engine_family_gate(&StealthProfile::FirefoxMacStable).is_ok(),
"FirefoxMacStable must pass the Firefox engine-family gate"
);
assert!(!rejected_by_engine_gate(&StealthProfile::FirefoxMacStable));
}
}