guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! guise → **reynard** engine-config bridge.
//!
//! `reynard` (our Camoufox fork — see project notes) spoofs fingerprints in
//! patched Gecko C++ rather than via injected JS. It reads one JSON config blob
//! from an environment variable at startup ([`REYNARD_CONFIG_ENV`]) and applies
//! every surface natively, so there is nothing for a page to `toString`-probe.
//!
//! This module maps guise's pure-data [`crate::ProfileOverrides`] onto that
//! config's key schema (`additions/camoucfg` `properties.json`), so the SAME
//! persona that drives the JS disguise also drives the engine — one source of
//! truth, two backends.
//!
//! The native-passthrough rule from the JS path carries over verbatim: when a
//! matched-host persona leaves `webgl_vendor`/`webgl_renderer` empty, the WebGL
//! keys are OMITTED so reynard exposes the host's real, self-consistent adapter
//! (whose pixels match) instead of a constant — see the WebGL note on
//! `FIREFOX_STEALTH_BODY`.

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};

/// Per-launch counter so concurrent launches get unique temp dirs.
static LAUNCH_SEQ: AtomicU64 = AtomicU64::new(0);

/// Environment variable reynard's patched Gecko reads its JSON config from.
///
/// The reynard fork's name. `MaskConfig.hpp` reads `REYNARD_CONFIG[_<n>]` first
/// and falls back to the upstream `CAMOU_CONFIG[_<n>]`, so this const and the
/// engine stay in lockstep while remaining compatible with any older binary.
pub const REYNARD_CONFIG_ENV: &str = "REYNARD_CONFIG";

/// Maximum bytes per env var before chunking into `REYNARD_CONFIG_1..N`.
/// Generous headroom under typical `ARG_MAX`/env limits; the engine concatenates
/// the numbered parts in order before parsing.
const ENV_CHUNK_BYTES: usize = 100_000;

/// A common standard-Linux font set (all ship on typical Ubuntu/Fedora desktops).
/// Sent as the engine's `fonts` whitelist so font-list fingerprinting sees this
/// coherent set instead of the host's full (identifying) install.
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",
];

/// Build the reynard engine config object from a persona.
///
/// Only keys guise actually owns are set; everything else (canvas/audio seeds,
/// fonts, battery, …) is left for reynard's own fingerprint generator to fill,
/// exactly as the JS path leaves untouched surfaces to the real browser.
#[must_use]
pub fn reynard_config(overrides: &ProfileOverrides) -> Value {
    let mut cfg = Map::new();

    // ── navigator ───────────────────────────────────────────────────────────
    cfg.insert("navigator.userAgent".into(), json!(overrides.user_agent));
    // Driven over BiDi, the engine's Navigator::Webdriver() otherwise returns
    // true (remote agent active) — the sannysoft "WebDriver" tell. The reynard
    // engine patch honors this REYNARD_CONFIG key; pin it false for every persona.
    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 }),
    );

    // ── screen ──────────────────────────────────────────────────────────────
    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));

    // ── fonts — restrict the visible set to a common standard-Linux list. The
    //    engine maps this to font.system.whitelist, so font-list fingerprinting
    //    sees a small coherent set instead of the host's identifying ~300-family
    //    install (which leaked CJK/extra families). Every family below ships on
    //    typical Linux desktops, so the engine's measureText enumeration stays
    //    coherent. Linux persona only (cross-OS personas need their own list). ──
    if overrides.platform.contains("Linux") {
        cfg.insert("fonts".into(), json!(LINUX_STD_FONTS));
    }

    // ── WebGL — native passthrough: only pin when the persona explicitly
    //    carries a (cross-OS) adapter. Empty = expose the real one. ──
    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));
    }

    // ── HTTP header coherence (engine emits these so the network layer matches
    //    the JS surface) ──
    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)
}

/// Render the persona as the `(env_name, value)` pairs to set on the reynard
/// process. Returns chunked `REYNARD_CONFIG_1..N` pairs when the JSON exceeds
/// [`ENV_CHUNK_BYTES`], else a single [`REYNARD_CONFIG_ENV`] pair.
#[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()
}

/// Build an `Accept-Language` header value from a language list
/// (`en-US,en;q=0.9,fr;q=0.8` style) so it coheres with `navigator.languages`.
fn accept_language(langs: &[String]) -> String {
    langs
        .iter()
        .enumerate()
        .map(|(i, lang)| {
            if i == 0 {
                lang.clone()
            } else {
                // q drops 0.1 per position, floored at 0.1.
                let q = (10 - i.min(9)) as f64 / 10.0;
                format!("{lang};q={q}")
            }
        })
        .collect::<Vec<_>>()
        .join(",")
}

/// The wrapper shell script that injects the persona config and execs the real
/// reynard binary. Pure (no IO) so the shell logic is unit-testable.
///
/// rustenium spawns the browser binary directly and exposes no per-child env
/// hook, so we front `reynard_bin` with this wrapper: it loads `REYNARD_CONFIG`
/// from `cfg_path` (a file, so any JSON byte survives shell quoting) and forwards
/// rustenium's BiDi launch flags to the binary via `"$@"`. Per-launch and
/// concurrency-safe — no process-global env, no `unsafe` set_var (guise forbids
/// unsafe).
fn reynard_wrapper_script(cfg_path: &str, reynard_bin: &str) -> String {
    // Use the REYNARD_CONFIG_ENV const so the launch path and the engine's
    // MaskConfig env name stay in lockstep across the camoufox->reynard rename.
    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,
    )
}

/// The reynard engine's Firefox **major** version, parsed from `<bin> --version`
/// (`"Mozilla Camoufox 150.0.2-beta.25"` → `150`).
///
/// reynard is a real Firefox build, so its TLS (JA3/JA4) and version-gated JS
/// features are the engine's actual version. The persona UA, by contrast, is
/// pinned to whatever the TLS-impersonate **HTTP-client** profile ships — a
/// different path. Claiming the engine's true version on the BROWSER closes the
/// gap. Returns `None` (caller keeps the persona UA) if `--version` can't run.
#[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);
    // First whitespace token that looks like a dotted version (e.g. "150.0.2").
    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())
}

/// Rewrite the Firefox **major** version in a UA string to `engine_major`,
/// preserving structure (only `rv:<n>.` and `Firefox/<n>.` change). A no-op when
/// the persona already matches or no Firefox token is present.
#[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(),
    }
}

/// Stable 64-bit seed from an account key (its `profile_dir`), so per-identity
/// canvas/audio/font noise is deterministic per account — identical across that
/// account's sessions, different across accounts. FNV-1a: no deps, well spread.
#[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
}

/// Launch the reynard engine binary, driven over BiDi, with `profile`'s
/// fingerprint applied **natively** via `REYNARD_CONFIG` (no JS injection).
///
/// Each call writes its own config + wrapper to a unique temp dir, so concurrent
/// launches with different personas never collide. Run `headless = false` on a
/// real-GPU display for zero headless tells; reynard's pointer/headless patches
/// also keep headless coherent if you must use it.
///
/// The returned [`Page`] is the same handle the JS-disguise path returns, so the
/// differential oracle ([`crate::probe::diff_pages`]) can diff a reynard page
/// against a stock-Firefox page directly — the "patched vs stock = identical"
/// gate.
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
}

/// Launch the reynard engine, MERGING the per-launch wrapper into a
/// caller-supplied [`FoxBrowserConfig`] so the caller's proxy, profile dir,
/// viewport, and any extra prefs are preserved.
///
/// This is the integration point for long-lived drivers (e.g. the guise bridge
/// that Meridian talks to): they build a `FoxBrowserConfig` with the session's
/// `profile_dir` + residential `proxy`, and reynard adds only the engine
/// wrapper (`executable_path` → the REYNARD_CONFIG-exporting launcher) and the
/// `navigator.webdriver` pref. `config.executable_path` is overridden; the
/// reynard pref is appended to any existing `user_js_content`; `config.proxy`
/// and `config.profile_dir` flow through to `launch_firefox_self_managed`
/// (which still appends the proxy prefs), so residential egress + session
/// persistence are unchanged versus the plain-Firefox path.
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);
    // Align the persona UA to the ACTUAL reynard engine version. The persona's
    // own UA major tracks the TLS-impersonate HTTP profile (a different,
    // HTTP-client path); the reynard BROWSER uses real Gecko TLS + features, so
    // claiming the engine's true version keeps navigator.userAgent coherent with
    // JA3/JA4 and version-gated JS. No-op if `--version` is unreadable.
    if let Some(major) = reynard_engine_major(reynard_bin) {
        overrides.user_agent = align_ua_to_engine(&overrides.user_agent, major);
    }
    // Per-identity device noise: derive a STABLE seed from the account's
    // profile_dir so canvas/audio/font fingerprints are deterministic per account
    // (identical across that account's own sessions) but DIFFERENT across
    // accounts. Multiple accounts created from one host therefore read as
    // different devices instead of one device making serial signups — the
    // correlation an anti-bot uses to block account #2. No profile_dir => no seed
    // (engine default).
    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));
            // NB: WebRTC IP masking is NOT a config key (the engine reads it only
            // via the content-callable window.setWebRTCIPv4); the guise-bridge
            // applies it per-launch from the same identity_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}"))?;

    // The engine wrapper replaces the executable; everything else the caller set
    // (proxy, profile_dir, viewport, headless) is preserved.
    config.executable_path = Some(wrapper_path.to_string_lossy().into_owned());
    // `navigator.webdriver` is set true by the BiDi remote agent; disable the
    // pref at the PROFILE layer so the getter reads false WITHOUT a JS override
    // that `.toString()` could leak. (`remote.enabled` is deliberately NOT
    // touched — BiDi needs it to connect.) Append rather than replace so a
    // caller's prefs survive; foxdriver still appends `config.proxy` prefs.
    config.user_js_content = Some(merge_reynard_prefs(config.user_js_content.take()));

    // Self-managed launch: foxdriver spawns the wrapper (which exports
    // REYNARD_CONFIG then execs the engine) and polls the debug port until it is
    // live before attaching. A freshly-built Camoufox binds its BiDi port in
    // ~1 s — past rustenium's fixed 500 ms post-spawn sleep — so the default
    // managed launch races to a ConnectionRefused; the readiness poll fixes it.
    launch_firefox_self_managed(config).await
}

/// Append [`REYNARD_PROFILE_PREFS`] to any caller-supplied `user.js`, so the
/// `navigator.webdriver` pref is always present without clobbering the caller's
/// prefs. Pure — unit-tested.
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(),
    }
}

/// Profile prefs written for every reynard launch. Only automation tells that
/// the engine/REYNARD_CONFIG does not already cover belong here — and nothing that
/// would break the BiDi transport (`remote.enabled` stays on).
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() {
        // The engine patch (Navigator::Webdriver honoring MaskConfig) is only
        // load-bearing if the config actually carries the key — pin it.
        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() {
        // FirefoxLinux is matched-host: empty webgl → keys MUST be absent so the
        // engine exposes the real adapter (mirrors the JS-path decision).
        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() {
        // A persona that carries an explicit adapter (cross-OS) DOES set it.
        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);
        // round-trips as valid JSON
        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"
        );
        // Gecko build token is NOT a version and must survive untouched.
        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);
        // No Firefox token → unchanged (e.g. a non-Firefox 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() {
        // Same account key → same seed: a device is stable across that account's
        // own sessions.
        assert_eq!(identity_seed("/profiles/acct-a"), identity_seed("/profiles/acct-a"));
        // Different account keys → different seed: accounts render as different
        // devices (the multi-account un-correlation contract).
        assert_ne!(identity_seed("/profiles/acct-a"), identity_seed("/profiles/acct-b"));
        // A one-char difference still diverges (FNV-1a avalanche).
        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() {
        // The bridge may pass proxy/identity prefs; reynard must ADD its pref,
        // never clobber the caller's.
        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() {
        // "$@" is load-bearing: rustenium passes --remote-debugging-port etc. and
        // they must reach the real binary, or BiDi never connects.
        assert!(reynard_wrapper_script("/c", "/b").contains("\"$@\""));
    }
}