zendriver-stealth 0.8.0

Anti-detection patches and profiles for zendriver
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! Persona: the unified fingerprint configuration.

pub mod seed;
pub mod specs;
pub mod surface;
pub(crate) mod webgpu_adapter;

pub use seed::Seed;
pub use specs::{
    FontSpec, HardwareSpec, ScreenSpec, SurfaceCfg, UaMetadata, UaSpec, WebglSpec, WebrtcSpec,
};

use std::sync::OnceLock;

use serde::{Deserialize, Serialize};

use crate::Platform;

static SYSTEM: OnceLock<Persona> = OnceLock::new();

/// Mock geolocation coordinates, sent verbatim as
/// `Emulation.setGeolocationOverride` params. Field names match the CDP
/// params exactly (`latitude`, `longitude`, `accuracy`) so `GeoPos` can be
/// deserialized straight out of `persona_overlay` JSON, e.g.
/// `{"geolocation":{"latitude":21.0285,"longitude":105.8542}}`.
///
/// `accuracy` is optional — CDP accepts the override without it — and is
/// omitted from the CDP call entirely (not sent as `null`) when unset.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct GeoPos {
    pub latitude: f64,
    pub longitude: f64,
    pub accuracy: Option<f64>,
}

/// Unified fingerprint configuration. Every field optional → overlay semantics.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Persona {
    pub platform: Option<Platform>,
    pub ua: Option<UaSpec>,
    pub hardware_concurrency: Option<u32>,
    pub device_memory_gb: Option<u32>,
    pub timezone: Option<String>,
    pub locale: Option<String>,
    /// Ordered language list (e.g. `["de-DE", "de"]`). Drives
    /// `navigator.languages` and the q-weighted `Accept-Language`. When unset,
    /// derived from [`locale`](Self::locale).
    pub languages: Option<Vec<String>>,
    /// Mock coordinates for the Geolocation API (`Emulation.setGeolocationOverride`).
    /// Coherence axis alongside [`timezone`](Self::timezone) /
    /// [`locale`](Self::locale) — keeps `navigator.geolocation` in step with
    /// the exit IP's real location instead of leaking the host's.
    pub geolocation: Option<GeoPos>,
    /// Screen / device-metrics override (`Emulation.setDeviceMetricsOverride`).
    /// `None` → the observer's fixed 1920x1080 default (today's behavior).
    pub screen: Option<ScreenSpec>,
    pub webgl: Option<WebglSpec>,
    pub webgpu: Option<SurfaceCfg>,
    pub canvas: Option<SurfaceCfg>,
    pub audio: Option<SurfaceCfg>,
    pub fonts: Option<FontSpec>,
    pub client_rects: Option<SurfaceCfg>,
    pub webrtc: Option<WebrtcSpec>,
    pub hardware: Option<HardwareSpec>,
    pub seed: Option<Seed>,
}

/// Fluent builder for [`Persona`]. Every setter is optional.
#[derive(Debug, Clone, Default)]
pub struct PersonaBuilder(Persona);

impl Persona {
    pub fn try_from_json(s: &str) -> Result<Persona, serde_json::Error> {
        serde_json::from_str(s)
    }

    pub fn builder() -> PersonaBuilder {
        PersonaBuilder(Persona::default())
    }
}

impl PersonaBuilder {
    pub fn seed(mut self, s: Seed) -> Self {
        self.0.seed = Some(s);
        self
    }
    pub fn timezone(mut self, tz: impl Into<String>) -> Self {
        self.0.timezone = Some(tz.into());
        self
    }
    pub fn locale(mut self, l: impl Into<String>) -> Self {
        self.0.locale = Some(l.into());
        self
    }
    pub fn languages(mut self, langs: impl IntoIterator<Item = String>) -> Self {
        self.0.languages = Some(langs.into_iter().collect());
        self
    }
    pub fn device_memory_gb(mut self, gb: u32) -> Self {
        self.0.device_memory_gb = Some(gb);
        self
    }
    pub fn hardware_concurrency(mut self, n: u32) -> Self {
        self.0.hardware_concurrency = Some(n);
        self
    }
    pub fn webgl(mut self, w: WebglSpec) -> Self {
        self.0.webgl = Some(w);
        self
    }
    pub fn build(self) -> Persona {
        self.0
    }
}

impl std::str::FromStr for Persona {
    type Err = serde_json::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        serde_json::from_str(s)
    }
}

impl Persona {
    /// Field-wise merge: `Some` in `over` wins, `None` inherits from `self`.
    pub fn overlay(self, over: Persona) -> Persona {
        Persona {
            platform: over.platform.or(self.platform),
            // UA-CH composes field-wise (via `UaSpec::overlay`) rather than
            // one side wholesale-replacing the other, so layering two
            // personas can patch e.g. just `platform_version` without
            // clobbering a base persona's `brands`.
            ua: match (self.ua, over.ua) {
                (Some(base), Some(add)) => Some(base.overlay(add)),
                (base, add) => add.or(base),
            },
            hardware_concurrency: over.hardware_concurrency.or(self.hardware_concurrency),
            device_memory_gb: over.device_memory_gb.or(self.device_memory_gb),
            timezone: over.timezone.or(self.timezone),
            locale: over.locale.or(self.locale),
            languages: over.languages.or(self.languages),
            geolocation: over.geolocation.or(self.geolocation),
            screen: over.screen.or(self.screen),
            webgl: over.webgl.or(self.webgl),
            webgpu: over.webgpu.or(self.webgpu),
            canvas: over.canvas.or(self.canvas),
            audio: over.audio.or(self.audio),
            fonts: over.fonts.or(self.fonts),
            client_rects: over.client_rects.or(self.client_rects),
            webrtc: over.webrtc.or(self.webrtc),
            hardware: over.hardware.or(self.hardware),
            seed: over.seed.or(self.seed),
        }
    }

    /// Force a single surface's render [`Strategy`], creating the surface's
    /// spec with default values if it was unset.
    ///
    /// Used by the public browser builder's `.surface(surface, strategy)` to
    /// layer per-surface overrides on top of the resolved persona. Each surface
    /// writes the `strategy` field of its corresponding spec; the [`UaSpec`]
    /// surface family (identity, not a render strategy) has no strategy field,
    /// so this is a no-op there.
    pub fn apply_surface_override(
        &mut self,
        surface: surface::Surface,
        strategy: surface::Strategy,
    ) {
        use surface::Surface;
        match surface {
            Surface::Canvas => {
                self.canvas.get_or_insert_with(Default::default).strategy = Some(strategy)
            }
            Surface::Audio => {
                self.audio.get_or_insert_with(Default::default).strategy = Some(strategy)
            }
            Surface::ClientRects => {
                self.client_rects
                    .get_or_insert_with(Default::default)
                    .strategy = Some(strategy)
            }
            Surface::Webgl => {
                self.webgl.get_or_insert_with(Default::default).strategy = Some(strategy)
            }
            Surface::Fonts => {
                self.fonts.get_or_insert_with(Default::default).strategy = Some(strategy)
            }
            Surface::Webrtc => {
                self.webrtc.get_or_insert_with(Default::default).strategy = Some(strategy)
            }
            Surface::Hardware => {
                self.hardware.get_or_insert_with(Default::default).strategy = Some(strategy)
            }
            Surface::Webgpu => {
                self.webgpu.get_or_insert_with(Default::default).strategy = Some(strategy)
            }
        }
    }

    /// Effective `navigator.platform` JS string for patch templating.
    /// Falls back to host platform when unset.
    pub fn resolved_platform_js(&self) -> String {
        let plat = self.platform.unwrap_or_else(|| {
            Persona::system()
                .platform
                .unwrap_or(crate::Platform::LinuxX86_64)
        });
        plat.js_string().to_string()
    }

    /// Host-probed persona (sysinfo). Cached: first call probes, rest clone.
    /// Runtime — NOT a build-script const (build host != run host).
    pub fn system() -> Persona {
        SYSTEM.get_or_init(Persona::probe_system).clone()
    }

    fn probe_system() -> Persona {
        let platform = crate::fingerprint::detect_platform();
        let cpu = crate::fingerprint::clamp_cpu_count(num_cpus::get() as u32);
        let mem = crate::fingerprint::detect_memory_gb().unwrap_or(8);
        Persona {
            platform: Some(platform),
            hardware_concurrency: Some(cpu),
            device_memory_gb: Some(mem),
            timezone: None,
            locale: None,
            seed: Some(Seed::random()),
            ..Persona::default()
        }
    }
}

/// Minimal eval surface so stealth can probe a live page without depending on
/// the `zendriver` core crate (which would be a dependency cycle).
///
/// The `zendriver` crate implements this for its `Tab`, mapping its own
/// evaluation error into [`StealthError::Probe`].
#[async_trait::async_trait]
pub trait JsProbe {
    /// Evaluate `js` in the page and return the result as a JSON value.
    async fn eval_json(&self, js: &str) -> Result<serde_json::Value, crate::StealthError>;
}

/// JS run by [`Persona::from_browser`] to read the live browser's REAL
/// fingerprint-relevant values (platform, memory, timezone, locale, WebGL
/// vendor/renderer). Returns a single JSON object.
const PROBE_JS: &str = r#"(() => {
  const c = document.createElement('canvas').getContext('webgl');
  const dbg = c && c.getExtension('WEBGL_debug_renderer_info');
  return {
    platform: navigator.platform,
    deviceMemory: navigator.deviceMemory,
    hardwareConcurrency: navigator.hardwareConcurrency,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    locale: navigator.language,
    webglVendor: dbg ? c.getParameter(dbg.UNMASKED_VENDOR_WEBGL) : null,
    webglRenderer: dbg ? c.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : null,
  };
})()"#;

impl Persona {
    /// Probe the live Chrome for its REAL webgl/platform/memory/timezone
    /// values, producing a maximally coherent host persona.
    ///
    /// Runs [`PROBE_JS`] through the supplied [`JsProbe`] (the `zendriver`
    /// `Tab` implements it) and maps the resulting JSON onto a [`Persona`].
    /// Fields the browser does not expose are left `None`.
    pub async fn from_browser<P: JsProbe + Sync>(
        probe: &P,
    ) -> Result<Persona, crate::StealthError> {
        let v = probe.eval_json(PROBE_JS).await?;
        Ok(persona_from_probe(&v))
    }
}

/// Map the [`PROBE_JS`] JSON result onto a [`Persona`].
fn persona_from_probe(v: &serde_json::Value) -> Persona {
    let mut p = Persona::default();

    // `navigator.platform` strings match `Platform::js_string()`:
    // "Win32" / "MacIntel" / "Linux x86_64" (any other → Linux fallback).
    if let Some(plat) = v.get("platform").and_then(|x| x.as_str()) {
        p.platform = Some(match plat {
            "Win32" => Platform::Win32,
            "MacIntel" => Platform::MacIntel,
            _ => Platform::LinuxX86_64,
        });
    }

    // `navigator.deviceMemory` is a JS number (gigabytes).
    if let Some(mem) = v.get("deviceMemory").and_then(|x| x.as_u64()) {
        p.device_memory_gb = Some(mem as u32);
    }

    if let Some(hc) = v.get("hardwareConcurrency").and_then(|x| x.as_u64()) {
        p.hardware_concurrency = Some(hc as u32);
    }

    if let Some(tz) = v.get("timezone").and_then(|x| x.as_str()) {
        p.timezone = Some(tz.to_string());
    }

    if let Some(loc) = v.get("locale").and_then(|x| x.as_str()) {
        p.locale = Some(loc.to_string());
    }

    // WebGL vendor/renderer become a value-substitution WebglSpec when present.
    let vendor = v
        .get("webglVendor")
        .and_then(|x| x.as_str())
        .map(str::to_string);
    let renderer = v
        .get("webglRenderer")
        .and_then(|x| x.as_str())
        .map(str::to_string);
    if vendor.is_some() || renderer.is_some() {
        p.webgl = Some(WebglSpec {
            strategy: None,
            unmasked_vendor: vendor,
            unmasked_renderer: renderer,
        });
    }

    p
}

#[cfg(test)]
mod persona_tests {
    use super::*;

    #[test]
    fn default_persona_is_all_none() {
        let p = Persona::default();
        assert!(p.platform.is_none() && p.seed.is_none() && p.webgl.is_none());
    }

    #[test]
    fn persona_round_trips_json() {
        let p = Persona {
            seed: Some(Seed::from_u64(5)),
            timezone: Some("America/New_York".into()),
            ..Persona::default()
        };
        let s = serde_json::to_string(&p).unwrap();
        let back: Persona = serde_json::from_str(&s).unwrap();
        assert_eq!(back.seed, Some(Seed::from_u64(5)));
        assert_eq!(back.timezone.as_deref(), Some("America/New_York"));
    }

    #[test]
    fn persona_exposes_resolved_platform_for_patches() {
        let p = Persona::system();
        assert!(!p.resolved_platform_js().is_empty());
    }

    #[test]
    fn system_persona_is_populated_and_cached() {
        let a = Persona::system();
        // Host probe fills platform + cpu + memory.
        assert!(a.platform.is_some());
        assert!(a.hardware_concurrency.is_some());
        assert!(a.device_memory_gb.is_some());
        let b = Persona::system();
        // Cached → same values.
        assert_eq!(a.device_memory_gb, b.device_memory_gb);
    }

    #[test]
    fn builder_sets_fields() {
        let p = Persona::builder()
            .seed(Seed::from_u64(3))
            .timezone("UTC")
            .device_memory_gb(16)
            .build();
        assert_eq!(p.seed, Some(Seed::from_u64(3)));
        assert_eq!(p.device_memory_gb, Some(16));
        assert_eq!(p.timezone.as_deref(), Some("UTC"));
    }

    #[test]
    fn from_json_and_fromstr_parse() {
        let json = r#"{"timezone":"Europe/Paris","seed":99}"#;
        let a = Persona::try_from_json(json).unwrap();
        assert_eq!(a.timezone.as_deref(), Some("Europe/Paris"));
        let b: Persona = json.parse().unwrap();
        assert_eq!(b.seed, Some(Seed::from_u64(99)));
    }

    struct FakeProbe(serde_json::Value);

    #[async_trait::async_trait]
    impl JsProbe for FakeProbe {
        async fn eval_json(&self, _js: &str) -> Result<serde_json::Value, crate::StealthError> {
            Ok(self.0.clone())
        }
    }

    #[tokio::test]
    async fn from_browser_maps_probe_fields() {
        let probe = FakeProbe(serde_json::json!({
            "platform": "MacIntel",
            "deviceMemory": 16,
            "hardwareConcurrency": 10,
            "timezone": "America/New_York",
            "locale": "en-US",
            "webglVendor": "Google Inc. (Apple)",
            "webglRenderer": "ANGLE (Apple, Apple M1, OpenGL 4.1)",
        }));
        let p = Persona::from_browser(&probe).await.unwrap();
        assert_eq!(p.platform, Some(Platform::MacIntel));
        assert_eq!(p.device_memory_gb, Some(16));
        assert_eq!(p.hardware_concurrency, Some(10));
        assert_eq!(p.timezone.as_deref(), Some("America/New_York"));
        assert_eq!(p.locale.as_deref(), Some("en-US"));
        let webgl = p.webgl.expect("webgl spec populated from probe");
        assert_eq!(
            webgl.unmasked_renderer.as_deref(),
            Some("ANGLE (Apple, Apple M1, OpenGL 4.1)")
        );
        assert_eq!(
            webgl.unmasked_vendor.as_deref(),
            Some("Google Inc. (Apple)")
        );
    }

    #[tokio::test]
    async fn from_browser_handles_missing_webgl_and_linux_platform() {
        // Null WebGL (debug-info ext unavailable) + a Linux platform string
        // that isn't a literal enum name → Linux fallback, no webgl spec.
        let probe = FakeProbe(serde_json::json!({
            "platform": "Linux x86_64",
            "deviceMemory": 8,
            "hardwareConcurrency": 4,
            "timezone": "UTC",
            "locale": "en-GB",
            "webglVendor": serde_json::Value::Null,
            "webglRenderer": serde_json::Value::Null,
        }));
        let p = Persona::from_browser(&probe).await.unwrap();
        assert_eq!(p.platform, Some(Platform::LinuxX86_64));
        assert_eq!(p.device_memory_gb, Some(8));
        assert!(p.webgl.is_none(), "null webgl → no spec");
    }

    #[test]
    fn apply_surface_override_sets_strategy_creating_spec() {
        use crate::{Strategy, Surface};
        let mut p = Persona::default();
        // Surface spec absent → created with the override strategy.
        p.apply_surface_override(Surface::Webrtc, Strategy::Native);
        assert_eq!(
            p.webrtc.as_ref().and_then(|w| w.strategy),
            Some(Strategy::Native)
        );
        // Existing spec → only strategy mutated, other fields preserved.
        p.webgl = Some(WebglSpec {
            unmasked_renderer: Some("ANGLE (x)".into()),
            ..Default::default()
        });
        p.apply_surface_override(Surface::Webgl, Strategy::Value);
        let webgl = p.webgl.as_ref().unwrap();
        assert_eq!(webgl.strategy, Some(Strategy::Value));
        assert_eq!(webgl.unmasked_renderer.as_deref(), Some("ANGLE (x)"));
    }

    #[test]
    fn apply_surface_override_webgpu() {
        use crate::{Strategy, Surface};
        let mut p = Persona::default();
        p.apply_surface_override(Surface::Webgpu, Strategy::Block);
        assert_eq!(
            p.webgpu.as_ref().and_then(|c| c.strategy),
            Some(Strategy::Block)
        );
    }

    #[test]
    fn languages_overlay_and_builder() {
        let base = Persona::builder()
            .languages(["en-US".to_string(), "en".to_string()])
            .build();
        assert_eq!(
            base.languages.as_deref(),
            Some(["en-US".to_string(), "en".to_string()].as_slice())
        );
        // `Some` in the overlay wins; `None` inherits.
        let over = Persona {
            languages: Some(vec!["de-DE".into(), "de".into()]),
            ..Default::default()
        };
        let merged = base.clone().overlay(over);
        assert_eq!(merged.languages.unwrap(), vec!["de-DE", "de"]);
        let merged2 = base.overlay(Persona::default());
        assert_eq!(merged2.languages.unwrap(), vec!["en-US", "en"]);
    }

    #[test]
    fn overlay_some_wins_none_inherits() {
        let base = Persona {
            timezone: Some("UTC".into()),
            device_memory_gb: Some(8),
            seed: Some(Seed::from_u64(1)),
            ..Persona::default()
        };
        let over = Persona {
            timezone: Some("Asia/Tokyo".into()),
            ..Persona::default()
        };
        let merged = base.overlay(over);
        assert_eq!(merged.timezone.as_deref(), Some("Asia/Tokyo")); // some wins
        assert_eq!(merged.device_memory_gb, Some(8)); // none inherits
        assert_eq!(merged.seed, Some(Seed::from_u64(1)));
    }

    #[test]
    fn persona_round_trips_geolocation_json() {
        let p = Persona {
            geolocation: Some(GeoPos {
                latitude: 21.0285,
                longitude: 105.8542,
                accuracy: Some(50.0),
            }),
            ..Persona::default()
        };
        let s = serde_json::to_string(&p).unwrap();
        let back: Persona = serde_json::from_str(&s).unwrap();
        assert_eq!(
            back.geolocation,
            Some(GeoPos {
                latitude: 21.0285,
                longitude: 105.8542,
                accuracy: Some(50.0),
            })
        );
    }

    #[test]
    fn geolocation_parses_without_accuracy() {
        // `persona_overlay` accepts parsed JSON (BrowserBuilder doc example);
        // accuracy is optional and must default to None when omitted.
        let json = r#"{"geolocation":{"latitude":10.0,"longitude":20.0}}"#;
        let p: Persona = json.parse().unwrap();
        let geo = p.geolocation.expect("geolocation parsed");
        assert_eq!(geo.latitude, 10.0);
        assert_eq!(geo.longitude, 20.0);
        assert_eq!(geo.accuracy, None);
    }

    #[test]
    fn persona_round_trips_ua_metadata_and_screen_json() {
        let p = Persona {
            ua: Some(UaSpec {
                ua_string: Some("Mozilla/5.0 (Windows NT 10.0; Win64; x64)".into()),
                ua_metadata: Some(UaMetadata {
                    platform_version: Some("15.0.0".into()),
                    architecture: Some("arm".into()),
                    bitness: Some("64".into()),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            screen: Some(ScreenSpec {
                width: 1536,
                height: 864,
                device_pixel_ratio: 1.25,
            }),
            ..Persona::default()
        };
        let s = serde_json::to_string(&p).unwrap();
        let back: Persona = serde_json::from_str(&s).unwrap();
        assert_eq!(
            back.ua
                .as_ref()
                .and_then(|u| u.ua_metadata.as_ref())
                .and_then(|m| m.architecture.clone())
                .as_deref(),
            Some("arm")
        );
        assert_eq!(
            back.screen,
            Some(ScreenSpec {
                width: 1536,
                height: 864,
                device_pixel_ratio: 1.25
            })
        );
    }

    #[test]
    fn overlay_screen_some_wins_none_inherits() {
        let base = Persona {
            screen: Some(ScreenSpec {
                width: 1920,
                height: 1080,
                device_pixel_ratio: 1.0,
            }),
            ..Persona::default()
        };
        let over = Persona {
            screen: Some(ScreenSpec {
                width: 1536,
                height: 864,
                device_pixel_ratio: 1.25,
            }),
            ..Persona::default()
        };
        let merged = base.clone().overlay(over);
        assert_eq!(
            merged.screen,
            Some(ScreenSpec {
                width: 1536,
                height: 864,
                device_pixel_ratio: 1.25
            })
        ); // some wins
        let merged2 = base.overlay(Persona::default());
        assert_eq!(
            merged2.screen,
            Some(ScreenSpec {
                width: 1920,
                height: 1080,
                device_pixel_ratio: 1.0
            })
        ); // none inherits
    }

    #[test]
    fn overlay_ua_composes_field_wise_not_whole_swap() {
        // A base persona's `platform` override must survive an overlay that
        // only sets `ua_string` — whole-swap semantics would have silently
        // dropped it.
        let base = Persona {
            ua: Some(UaSpec {
                platform: Some("Windows".into()),
                ..Default::default()
            }),
            ..Persona::default()
        };
        let over = Persona {
            ua: Some(UaSpec {
                ua_string: Some("custom-ua".into()),
                ..Default::default()
            }),
            ..Persona::default()
        };
        let merged = base.overlay(over);
        let ua = merged.ua.expect("ua merged");
        assert_eq!(ua.platform.as_deref(), Some("Windows")); // inherited
        assert_eq!(ua.ua_string.as_deref(), Some("custom-ua")); // over wins
    }

    #[test]
    fn overlay_geolocation_some_wins_none_inherits() {
        let base = Persona {
            geolocation: Some(GeoPos {
                latitude: 1.0,
                longitude: 2.0,
                accuracy: None,
            }),
            ..Persona::default()
        };
        let over = Persona {
            geolocation: Some(GeoPos {
                latitude: 9.0,
                longitude: 8.0,
                accuracy: Some(5.0),
            }),
            ..Persona::default()
        };
        let merged = base.clone().overlay(over);
        assert_eq!(
            merged.geolocation,
            Some(GeoPos {
                latitude: 9.0,
                longitude: 8.0,
                accuracy: Some(5.0),
            })
        ); // some wins
        let merged2 = base.overlay(Persona::default());
        assert_eq!(
            merged2.geolocation,
            Some(GeoPos {
                latitude: 1.0,
                longitude: 2.0,
                accuracy: None,
            })
        ); // none inherits
    }
}