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 LURIEN_CONFIG_ENV: &str = "LURIEN_CONFIG";
pub const REYNARD_CONFIG_ENV: &str = "REYNARD_CONFIG";
const MISSING_ENGINE: &str = "lurien engine not installed. Run install.sh or set LURIEN_BIN.";
const ENV_CHUNK_BYTES: usize = 100_000;
#[must_use]
pub fn lurien_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("locale:all".into(), json!(overrides.languages.join(", ")));
}
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));
const CHROME_BAND: u32 = 124;
cfg.insert("screen.availLeft".into(), json!(0));
cfg.insert("screen.availTop".into(), json!(0));
cfg.insert("screen.availWidth".into(), json!(overrides.screen_width));
cfg.insert("screen.availHeight".into(), json!(overrides.screen_height));
cfg.insert("window.screenX".into(), json!(0));
cfg.insert("window.screenY".into(), json!(0));
cfg.insert("window.outerWidth".into(), json!(overrides.screen_width));
cfg.insert("window.outerHeight".into(), json!(overrides.screen_height));
cfg.insert("window.innerWidth".into(), json!(overrides.screen_width));
let inner_height = if overrides.mobile {
overrides.screen_height
} else {
overrides.screen_height.saturating_sub(CHROME_BAND)
};
cfg.insert("window.innerHeight".into(), json!(inner_height));
if overrides.platform.contains("Linux") {
cfg.insert(
"fonts".into(),
json!(crate::fingerprint::font_tier_b::LINUX_STANDARD_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 lurien_config_env(overrides: &ProfileOverrides) -> Vec<(String, String)> {
let blob = lurien_config(overrides).to_string();
if blob.len() <= ENV_CHUNK_BYTES {
return vec![(LURIEN_CONFIG_ENV.to_string(), blob)];
}
blob.as_bytes()
.chunks(ENV_CHUNK_BYTES)
.enumerate()
.map(|(i, part)| {
(
format!("{LURIEN_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 lurien_wrapper_script(cfg_path: &str, engine_bin: &str) -> String {
format!(
"#!/bin/sh\n\
# guise -> lurien launch wrapper (per-launch config, no global env)\n\
_lurien_cfg=\"$(cat '{cfg_path}')\"\n\
LURIEN_CONFIG=\"$_lurien_cfg\"\n\
REYNARD_CONFIG=\"$_lurien_cfg\"\n\
CAMOU_CONFIG=\"$_lurien_cfg\"\n\
export LURIEN_CONFIG REYNARD_CONFIG CAMOU_CONFIG\n\
exec '{engine_bin}' \"$@\"\n",
)
}
#[must_use]
pub fn firefox_engine_major(bin: &str) -> Option<u32> {
let out = std::process::Command::new(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 fn resolve_lurien_bin() -> anyhow::Result<String> {
resolve_lurien_bin_from(
|k| std::env::var(k).ok(),
|p| std::path::Path::new(p).exists(),
)
}
#[must_use]
pub fn live_engine_bin() -> Option<String> {
for var in ["LURIEN_BIN", "REYNARD_BIN", "GUISE_REYNARD_BIN"] {
if let Ok(s) = std::env::var(var) {
let s = s.trim().to_string();
if !s.is_empty() {
return Some(s);
}
}
}
None
}
fn resolve_lurien_bin_from(
env: impl Fn(&str) -> Option<String>,
exists: impl Fn(&str) -> bool,
) -> anyhow::Result<String> {
for var in ["LURIEN_BIN", "REYNARD_BIN", "GUISE_REYNARD_BIN"] {
if let Some(s) = env(var) {
let s = s.trim().to_string();
if !s.is_empty() {
return Ok(s);
}
}
}
let home = env("HOME").unwrap_or_default();
[
format!("{home}/.local/share/lurien/lurien"),
format!("{home}/.local/share/reynard/reynard"),
format!("{home}/.cache/lurien/lurien"),
format!("{home}/.cache/reynard/reynard"),
"/opt/lurien/lurien".to_string(),
"/opt/reynard/reynard".to_string(),
]
.into_iter()
.find(|p| exists(p))
.ok_or_else(|| anyhow::anyhow!("{MISSING_ENGINE}"))
}
pub async fn launch_lurien(
lurien_bin: &str,
profile: &crate::StealthProfile,
headless: bool,
) -> anyhow::Result<Page> {
launch_with_config(
lurien_bin,
profile,
FoxBrowserConfig {
headless,
viewport_width: 1280,
viewport_height: 720,
..Default::default()
},
)
.await
}
pub async fn launch_with_config(
lurien_bin: &str,
profile: &crate::StealthProfile,
mut config: FoxBrowserConfig,
) -> anyhow::Result<Page> {
super::enforce_persona_launch_coherence(profile, config.proxy.is_none())?;
let mut overrides = crate::profile_to_overrides(profile);
if let Some(major) = firefox_engine_major(lurien_bin) {
overrides.user_agent = align_ua_to_engine(&overrides.user_agent, major);
}
let mut cfg = lurien_config(&overrides);
if let Value::Object(map) = &mut cfg {
let seed = match config.profile_dir.as_deref().filter(|d| !d.is_empty()) {
Some(dir_key) => identity_seed(dir_key) % 1_000_000,
None => u64::from(rand::random::<u32>()) % 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!("lurien-launch-{}-{}", std::process::id(), seq));
std::fs::create_dir_all(&dir)
.map_err(|e| anyhow::anyhow!("create lurien launch dir {dir:?}: {e}"))?;
let cfg_path = dir.join("config.json");
std::fs::write(&cfg_path, &config_json)
.map_err(|e| anyhow::anyhow!("write lurien config: {e}"))?;
let wrapper_path = dir.join("launch.sh");
let script = lurien_wrapper_script(&cfg_path.to_string_lossy(), lurien_bin);
std::fs::write(&wrapper_path, script)
.map_err(|e| anyhow::anyhow!("write lurien wrapper: {e}"))?;
let mut perms = std::fs::metadata(&wrapper_path)
.map_err(|e| anyhow::anyhow!("stat lurien wrapper: {e}"))?
.permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&wrapper_path, perms)
.map_err(|e| anyhow::anyhow!("chmod lurien wrapper: {e}"))?;
config
.env
.push(("TZ".to_string(), overrides.timezone.clone()));
config.executable_path = Some(wrapper_path.to_string_lossy().into_owned());
config.user_js_content = Some(merge_lurien_prefs(config.user_js_content.take()));
let age_key: String = config
.profile_dir
.as_deref()
.filter(|d| !d.is_empty())
.unwrap_or("guise-default-session-age")
.to_string();
let page = launch_firefox_self_managed(config).await?;
let session_age = crate::browser::generate_session_age(identity_seed(&age_key) % 1_000_000);
crate::browser::apply_session_age(&page, &session_age)
.await
.map_err(|e| anyhow::anyhow!("launch_with_config: apply session age: {e}"))?;
Ok(page)
}
fn merge_lurien_prefs(existing: Option<String>) -> String {
match existing {
Some(e) if !e.trim().is_empty() => format!("{e}\n{LURIEN_PROFILE_PREFS}"),
_ => LURIEN_PROFILE_PREFS.to_string(),
}
}
const LURIEN_PROFILE_PREFS: &str = "user_pref(\"dom.webdriver.enabled\", false);\n\
user_pref(\"security.ssl3.ecdhe_ecdsa_aes_128_sha\", true);";
#[cfg(test)]
#[path = "lurien/tests.rs"]
mod tests;