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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
//! StealthObserver: applies a [`StealthProfile`] to each new attached target.
//!
//! Installed in the [`zendriver_transport`] actor's observer chain. On
//! `Target.attachedToTarget`, the actor pauses the new target, walks every
//! observer serially, then releases the debugger via
//! `Runtime.runIfWaitingForDebugger`. The observer's job is to push every
//! UA/screen/timezone/locale override and (for spoofed) the bootstrap script
//! _before_ the debugger releases, so the first script the page runs sees the
//! patched globals.

use serde_json::json;
use zendriver_transport::{ObserverError, PausedSession, TargetObserver};

use crate::patches::{bootstrap_script, bootstrap_script_native_webgl};
use crate::persona::GeoPos;
use crate::persona::specs::{ScreenSpec, UaMetadata};
use crate::{Fingerprint, Persona, ProfileKind, StealthProfile};

/// Observer that applies a [`StealthProfile`] + [`Fingerprint`] to every page
/// target. Workers and iframes are skipped — workers have no DOM and iframes
/// inherit patches from the parent target in flat session mode.
#[derive(Debug)]
pub struct StealthObserver {
    profile: StealthProfile,
    fingerprint: Fingerprint,
    /// Pre-rendered bootstrap source. Empty for `Off`/`Native` — we never send
    /// `Page.addScriptToEvaluateOnNewDocument` in those modes, so there is no
    /// need to pay the patches-bundle cost for them.
    bootstrap: String,
    /// Mock geolocation coordinates from the resolved [`Persona`], sent via
    /// `Emulation.setGeolocationOverride`. Unlike `timezone`/`locale` (carried
    /// on [`Fingerprint`]), geolocation has no `Fingerprint` counterpart, so
    /// it's captured here straight off the persona at construction time.
    geolocation: Option<GeoPos>,
    /// Custom UA-CH from the resolved [`Persona`]'s `ua.ua_metadata`. When
    /// set, [`UaMetadata::resolve`] fills any unset sub-field from
    /// `fingerprint.ua_metadata` and the result drives
    /// `Emulation.setUserAgentOverride.userAgentMetadata` in place of the
    /// fingerprint-derived value outright.
    ua_metadata: Option<UaMetadata>,
    /// Custom screen / device-metrics from the resolved [`Persona`]. When
    /// set, drives `Emulation.setDeviceMetricsOverride` in place of the
    /// fixed 1920x1080 default.
    screen: Option<ScreenSpec>,
}

impl StealthObserver {
    /// Build a new observer. Bootstrap source is composed eagerly so the
    /// per-target hot path only pays a `clone`/borrow.
    ///
    /// The bootstrap is driven by a [`Persona`] (surface-spoofing config) plus
    /// the [`Fingerprint`] (coherent UA / Chrome identity). This constructor
    /// uses [`Persona::default`] — no surface overrides, identity-only patches
    /// keep their current behavior. The launch path (a later task) will thread
    /// a caller-supplied persona via [`StealthObserver::with_persona`].
    #[must_use]
    pub fn new(profile: StealthProfile, fingerprint: Fingerprint) -> Self {
        Self::with_persona(profile, fingerprint, Persona::default())
    }

    /// Build a new observer with an explicit [`Persona`] driving the surface
    /// patches. `identity` still supplies the coherent UA / Chrome version.
    #[must_use]
    pub fn with_persona(
        profile: StealthProfile,
        fingerprint: Fingerprint,
        persona: Persona,
    ) -> Self {
        let bootstrap = if profile.kind() == ProfileKind::Spoofed {
            if profile.native_isolation_enabled() {
                bootstrap_script_native_webgl(&persona, &fingerprint)
            } else {
                bootstrap_script(&persona, &fingerprint)
            }
        } else {
            String::new()
        };
        let geolocation = persona.geolocation;
        let ua_metadata = persona.ua.as_ref().and_then(|u| u.ua_metadata.clone());
        let screen = persona.screen;
        Self {
            profile,
            fingerprint,
            bootstrap,
            geolocation,
            ua_metadata,
            screen,
        }
    }
}

#[async_trait::async_trait]
impl TargetObserver for StealthObserver {
    fn name(&self) -> &'static str {
        "stealth"
    }

    async fn on_target_attached(&self, session: PausedSession<'_>) -> Result<(), ObserverError> {
        // Workers + iframes are skipped — workers have no DOM; iframes inherit
        // patches via the parent in flat mode.
        if session.target_info.kind != "page" {
            return Ok(());
        }
        if self.profile.kind() == ProfileKind::Off {
            return Ok(());
        }

        session.call("Page.enable", json!({})).await?;

        // UA override — Emulation.setUserAgentOverride carries the Client-Hints
        // metadata too, so we don't have to send Network.setUserAgentOverride
        // separately.
        let accept_language = {
            let langs = crate::lang::resolve_languages(&Persona::default(), &self.fingerprint);
            // `Emulation.setUserAgentOverride.acceptLanguage` wants a PLAIN
            // comma-separated locale list (e.g. `en-US,en`) — Chrome appends the
            // `;q=` weights itself. Passing an already-weighted string (the
            // `accept_language()` header form) makes Chrome double them, yielding
            // a malformed `Accept-Language: en-US,en;q=0.9;q=0.9`. Send the bare
            // list so the emitted header is a clean `en-US,en;q=0.9`.
            langs.join(",")
        };
        // Persona UA-CH wins when supplied — field-wise, falling back to the
        // fingerprint-derived value for any sub-field the persona left
        // unset. Absent persona UA-CH → today's behavior (fingerprint's
        // UAM verbatim).
        let user_agent_metadata = match &self.ua_metadata {
            Some(custom) => custom.resolve(&self.fingerprint.ua_metadata),
            None => self.fingerprint.ua_metadata.clone(),
        };
        session
            .call(
                "Emulation.setUserAgentOverride",
                json!({
                    "userAgent": &self.fingerprint.ua_string,
                    "acceptLanguage": accept_language,
                    "platform": self.fingerprint.platform.ch_platform(),
                    "userAgentMetadata": &user_agent_metadata,
                }),
            )
            .await?;

        // Screen-size override + focus emulation: keeps headless from leaking
        // an oddly-shaped viewport and from reporting `document.hasFocus()`
        // false for the (always-backgrounded) headless tab. Persona screen
        // wins when supplied; absent → today's fixed 1920x1080 default.
        let (screen_width, screen_height, device_scale_factor) = match self.screen {
            Some(s) => (s.width, s.height, s.device_pixel_ratio),
            None => (1920, 1080, 1.0),
        };
        session
            .call(
                "Emulation.setDeviceMetricsOverride",
                json!({
                    "width": screen_width,
                    "height": screen_height,
                    "deviceScaleFactor": device_scale_factor,
                    "mobile": false,
                    "screenWidth": screen_width,
                    "screenHeight": screen_height,
                }),
            )
            .await?;

        session
            .call(
                "Emulation.setFocusEmulationEnabled",
                json!({ "enabled": true }),
            )
            .await?;

        if let Some(ref tz) = self.fingerprint.timezone {
            session
                .call("Emulation.setTimezoneOverride", json!({ "timezoneId": tz }))
                .await?;
        }
        // Keep the JS-visible locale (navigator.language, Intl) coherent with
        // the always-sent Accept-Language. Prefer an explicit fingerprint
        // locale; otherwise, if the fingerprint pins a `languages` list, derive
        // the locale from its primary entry — a `languages`-without-`locale`
        // fingerprint must not leave the JS locale at Chrome's default while the
        // Accept-Language header says otherwise. A pure-default fingerprint (no
        // locale, no languages) keeps Chrome's native locale; we don't force one.
        let effective_locale = self.fingerprint.locale.clone().or_else(|| {
            self.fingerprint
                .languages
                .as_ref()
                .and_then(|langs| langs.first())
                .cloned()
        });
        if let Some(ref locale) = effective_locale {
            session
                .call("Emulation.setLocaleOverride", json!({ "locale": locale }))
                .await?;
        }
        if let Some(ref geo) = self.geolocation {
            // Sets the value the Geolocation API *would* return — it does
            // NOT grant the `geolocation` permission. Chrome still gates the
            // API behind a permission prompt/grant; auto-granting it here
            // would be a separate (and itself suspicious) signal, so we
            // deliberately leave permissioning to the caller.
            let mut params = json!({
                "latitude": geo.latitude,
                "longitude": geo.longitude,
            });
            if let Some(accuracy) = geo.accuracy {
                params["accuracy"] = json!(accuracy);
            }
            session
                .call("Emulation.setGeolocationOverride", params)
                .await?;
        }

        if self.profile.kind() == ProfileKind::Spoofed {
            if self.profile.bypass_csp_enabled() {
                session
                    .call("Page.setBypassCSP", json!({ "enabled": true }))
                    .await?;
            }
            // Inject into the MAIN world (no `worldName`). The bootstrap's
            // patches mutate `Navigator.prototype`, `window.chrome`,
            // `WebGLRenderingContext.prototype`, etc. — every isolated
            // world gets its own copy of these prototypes, so a patch
            // applied in a named/isolated world is invisible to the
            // page's own scripts (and to `evaluate_main`, the surface
            // detection sites probe). Running the bootstrap in the main
            // world is the only way these prototype mutations actually
            // affect the document under test.
            session
                .call(
                    "Page.addScriptToEvaluateOnNewDocument",
                    json!({
                        "source": &self.bootstrap,
                        "includeCommandLineAPI": false,
                        "runImmediately": true,
                    }),
                )
                .await?;
        }

        Ok(())
    }
}

#[cfg(test)]
#[allow(clippy::panic, clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::Platform;
    use serde_json::json;
    use zendriver_transport::testing::MockConnection;

    #[tokio::test]
    async fn spoofed_observer_sends_expected_sequence_for_page_target() {
        let fp = Fingerprint {
            platform: Platform::MacIntel,
            chrome_major: 120,
            chrome_full: "120.0.6099.234".into(),
            cpu_count: 10,
            memory_gb: 8,
            ua_string: crate::ua::compose_ua_string(Platform::MacIntel, "120.0.6099.234"),
            ua_metadata: crate::UserAgentMetadata::realistic(
                Platform::MacIntel,
                120,
                "120.0.6099.234",
            ),
            timezone: None,
            locale: None,
            languages: None,
            screen: None,
        };
        let profile = StealthProfile::spoofed();
        let observer = std::sync::Arc::new(StealthObserver::new(profile, fp));

        let (mut mock, conn) = MockConnection::pair_with_observers(vec![observer.clone()]);

        // Emit a Target.attachedToTarget event.
        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S1",
                "targetInfo": {
                    "targetId": "T1",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        // Expected sequence (each followed by a reply so the observer
        // continues). The closing Runtime.runIfWaitingForDebugger is the
        // actor's debugger-release after every observer succeeds.
        for expected in [
            "Page.enable",
            "Emulation.setUserAgentOverride",
            "Emulation.setDeviceMetricsOverride",
            "Emulation.setFocusEmulationEnabled",
            "Page.setBypassCSP",
            "Page.addScriptToEvaluateOnNewDocument",
            "Runtime.runIfWaitingForDebugger",
        ] {
            let id =
                tokio::time::timeout(std::time::Duration::from_secs(2), mock.expect_cmd(expected))
                    .await
                    .unwrap_or_else(|_| panic!("did not see {expected} within 2s"));
            // `acceptLanguage` must be a PLAIN locale list — Chrome adds the
            // `;q=` weights. A weighted value here makes Chrome double them into
            // a malformed `en-US,en;q=0.9;q=0.9` header.
            if expected == "Emulation.setUserAgentOverride" {
                let al = mock.last_sent()["params"]["acceptLanguage"]
                    .as_str()
                    .unwrap_or_default()
                    .to_string();
                assert!(!al.is_empty(), "acceptLanguage must be set");
                assert!(
                    !al.contains(";q="),
                    "acceptLanguage must be a bare locale list (no q-weights); got: {al}"
                );
            }
            mock.reply(id, json!({})).await;
        }

        conn.shutdown();
    }

    #[tokio::test]
    async fn languages_without_locale_still_sets_coherent_locale_override() {
        // A fingerprint that pins `languages` but no `locale` previously sent a
        // spoofed Accept-Language while leaving the JS-visible locale
        // (navigator.language / Intl) at Chrome's default — an incoherent
        // cross-surface tell. The locale override must be derived from the
        // pinned languages so both agree.
        let fp = Fingerprint {
            platform: Platform::MacIntel,
            chrome_major: 120,
            chrome_full: "120.0.6099.234".into(),
            cpu_count: 10,
            memory_gb: 8,
            ua_string: crate::ua::compose_ua_string(Platform::MacIntel, "120.0.6099.234"),
            ua_metadata: crate::UserAgentMetadata::realistic(
                Platform::MacIntel,
                120,
                "120.0.6099.234",
            ),
            timezone: None,
            locale: None,
            languages: Some(vec!["de-DE".into(), "de".into()]),
            screen: None,
        };
        let profile = StealthProfile::spoofed();
        let observer = std::sync::Arc::new(StealthObserver::new(profile, fp));
        let (mut mock, conn) = MockConnection::pair_with_observers(vec![observer.clone()]);

        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S1",
                "targetInfo": {
                    "targetId": "T1",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        let mut locale_override: Option<String> = None;
        let mut accept_language: Option<String> = None;
        for expected in [
            "Page.enable",
            "Emulation.setUserAgentOverride",
            "Emulation.setDeviceMetricsOverride",
            "Emulation.setFocusEmulationEnabled",
            "Emulation.setLocaleOverride",
            "Page.setBypassCSP",
            "Page.addScriptToEvaluateOnNewDocument",
            "Runtime.runIfWaitingForDebugger",
        ] {
            let id =
                tokio::time::timeout(std::time::Duration::from_secs(2), mock.expect_cmd(expected))
                    .await
                    .unwrap_or_else(|_| panic!("did not see {expected} within 2s"));
            if expected == "Emulation.setUserAgentOverride" {
                accept_language = mock.last_sent()["params"]["acceptLanguage"]
                    .as_str()
                    .map(String::from);
            }
            if expected == "Emulation.setLocaleOverride" {
                locale_override = mock.last_sent()["params"]["locale"]
                    .as_str()
                    .map(String::from);
            }
            mock.reply(id, json!({})).await;
        }
        conn.shutdown();

        assert_eq!(
            accept_language.as_deref(),
            Some("de-DE,de"),
            "Accept-Language must reflect the pinned languages"
        );
        assert_eq!(
            locale_override.as_deref(),
            Some("de-DE"),
            "locale override must be derived from pinned languages so JS locale stays coherent with Accept-Language"
        );
    }

    #[tokio::test]
    async fn native_isolation_spoofed_observer_omits_webgl_patch_in_bootstrap() {
        // End-to-end wiring check (Task 10): a spoofed profile with the
        // native_isolation opt-in must send a bootstrap script that omits
        // the WebGL vendor/renderer patch, over the actual CDP payload.
        let fp = Fingerprint {
            platform: Platform::MacIntel,
            chrome_major: 120,
            chrome_full: "120.0.6099.234".into(),
            cpu_count: 10,
            memory_gb: 8,
            ua_string: crate::ua::compose_ua_string(Platform::MacIntel, "120.0.6099.234"),
            ua_metadata: crate::UserAgentMetadata::realistic(
                Platform::MacIntel,
                120,
                "120.0.6099.234",
            ),
            timezone: None,
            locale: None,
            languages: None,
            screen: None,
        };
        let profile = StealthProfile::spoofed().native_isolation(true);
        let observer = std::sync::Arc::new(StealthObserver::new(profile, fp));

        let (mut mock, conn) = MockConnection::pair_with_observers(vec![observer.clone()]);

        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S1",
                "targetInfo": {
                    "targetId": "T1",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        for expected in [
            "Page.enable",
            "Emulation.setUserAgentOverride",
            "Emulation.setDeviceMetricsOverride",
            "Emulation.setFocusEmulationEnabled",
            "Page.setBypassCSP",
            "Page.addScriptToEvaluateOnNewDocument",
            "Runtime.runIfWaitingForDebugger",
        ] {
            let id =
                tokio::time::timeout(std::time::Duration::from_secs(2), mock.expect_cmd(expected))
                    .await
                    .unwrap_or_else(|_| panic!("did not see {expected} within 2s"));
            if expected == "Page.addScriptToEvaluateOnNewDocument" {
                let source = mock.last_sent()["params"]["source"]
                    .as_str()
                    .unwrap_or_default()
                    .to_string();
                assert!(
                    !source.contains("UNMASKED_VENDOR_WEBGL") && !source.contains("37445"),
                    "native_isolation bootstrap must omit the webgl patch block"
                );
            }
            mock.reply(id, json!({})).await;
        }

        conn.shutdown();
    }

    #[tokio::test]
    async fn spoofed_observer_emits_geolocation_override_when_persona_has_geo() {
        let fp = Fingerprint {
            platform: Platform::MacIntel,
            chrome_major: 120,
            chrome_full: "120.0.6099.234".into(),
            cpu_count: 10,
            memory_gb: 8,
            ua_string: crate::ua::compose_ua_string(Platform::MacIntel, "120.0.6099.234"),
            ua_metadata: crate::UserAgentMetadata::realistic(
                Platform::MacIntel,
                120,
                "120.0.6099.234",
            ),
            timezone: None,
            locale: None,
            languages: None,
            screen: None,
        };
        let persona = crate::Persona {
            geolocation: Some(crate::persona::GeoPos {
                latitude: 21.0285,
                longitude: 105.8542,
                accuracy: Some(50.0),
            }),
            ..crate::Persona::default()
        };
        let profile = StealthProfile::spoofed();
        let observer = std::sync::Arc::new(StealthObserver::with_persona(profile, fp, persona));

        let (mut mock, conn) = MockConnection::pair_with_observers(vec![observer.clone()]);

        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S1",
                "targetInfo": {
                    "targetId": "T1",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        for expected in [
            "Page.enable",
            "Emulation.setUserAgentOverride",
            "Emulation.setDeviceMetricsOverride",
            "Emulation.setFocusEmulationEnabled",
            "Emulation.setGeolocationOverride",
            "Page.setBypassCSP",
            "Page.addScriptToEvaluateOnNewDocument",
            "Runtime.runIfWaitingForDebugger",
        ] {
            let id =
                tokio::time::timeout(std::time::Duration::from_secs(2), mock.expect_cmd(expected))
                    .await
                    .unwrap_or_else(|_| panic!("did not see {expected} within 2s"));
            if expected == "Emulation.setGeolocationOverride" {
                let params = mock.last_sent()["params"].clone();
                assert_eq!(params["latitude"].as_f64(), Some(21.0285));
                assert_eq!(params["longitude"].as_f64(), Some(105.8542));
                assert_eq!(params["accuracy"].as_f64(), Some(50.0));
            }
            mock.reply(id, json!({})).await;
        }

        conn.shutdown();
    }

    #[tokio::test]
    async fn spoofed_observer_emits_persona_ua_metadata_and_screen_when_present() {
        let fp = Fingerprint {
            platform: Platform::MacIntel,
            chrome_major: 120,
            chrome_full: "120.0.6099.234".into(),
            cpu_count: 10,
            memory_gb: 8,
            ua_string: crate::ua::compose_ua_string(Platform::MacIntel, "120.0.6099.234"),
            ua_metadata: crate::UserAgentMetadata::realistic(
                Platform::MacIntel,
                120,
                "120.0.6099.234",
            ),
            timezone: None,
            locale: None,
            languages: None,
            screen: None,
        };
        let persona = crate::Persona {
            ua: Some(crate::UaSpec {
                ua_metadata: Some(crate::persona::specs::UaMetadata {
                    platform_version: Some("15.0.0".into()),
                    architecture: Some("arm".into()),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            screen: Some(crate::persona::specs::ScreenSpec {
                width: 1536,
                height: 864,
                device_pixel_ratio: 1.25,
            }),
            ..crate::Persona::default()
        };
        let profile = StealthProfile::spoofed();
        let observer = std::sync::Arc::new(StealthObserver::with_persona(profile, fp, persona));

        let (mut mock, conn) = MockConnection::pair_with_observers(vec![observer.clone()]);

        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S1",
                "targetInfo": {
                    "targetId": "T1",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        for expected in [
            "Page.enable",
            "Emulation.setUserAgentOverride",
            "Emulation.setDeviceMetricsOverride",
            "Emulation.setFocusEmulationEnabled",
            "Page.setBypassCSP",
            "Page.addScriptToEvaluateOnNewDocument",
            "Runtime.runIfWaitingForDebugger",
        ] {
            let id =
                tokio::time::timeout(std::time::Duration::from_secs(2), mock.expect_cmd(expected))
                    .await
                    .unwrap_or_else(|_| panic!("did not see {expected} within 2s"));
            if expected == "Emulation.setUserAgentOverride" {
                let uam = mock.last_sent()["params"]["userAgentMetadata"].clone();
                // Persona-set sub-fields win.
                assert_eq!(uam["platformVersion"].as_str(), Some("15.0.0"));
                assert_eq!(uam["architecture"].as_str(), Some("arm"));
                // Unset sub-fields fall back to the fingerprint-derived UAM.
                assert_eq!(uam["platform"].as_str(), Some("macOS"));
                assert!(uam["brands"].is_array());
            }
            if expected == "Emulation.setDeviceMetricsOverride" {
                let params = mock.last_sent()["params"].clone();
                assert_eq!(params["width"].as_u64(), Some(1536));
                assert_eq!(params["height"].as_u64(), Some(864));
                assert_eq!(params["deviceScaleFactor"].as_f64(), Some(1.25));
                assert_eq!(params["screenWidth"].as_u64(), Some(1536));
                assert_eq!(params["screenHeight"].as_u64(), Some(864));
            }
            mock.reply(id, json!({})).await;
        }

        conn.shutdown();
    }

    #[tokio::test]
    async fn spoofed_observer_uses_fingerprint_uam_and_fixed_screen_when_persona_absent() {
        let fp = Fingerprint {
            platform: Platform::MacIntel,
            chrome_major: 120,
            chrome_full: "120.0.6099.234".into(),
            cpu_count: 10,
            memory_gb: 8,
            ua_string: crate::ua::compose_ua_string(Platform::MacIntel, "120.0.6099.234"),
            ua_metadata: crate::UserAgentMetadata::realistic(
                Platform::MacIntel,
                120,
                "120.0.6099.234",
            ),
            timezone: None,
            locale: None,
            languages: None,
            screen: None,
        };
        let expected_uam = fp.ua_metadata.clone();
        let profile = StealthProfile::spoofed();
        // `Persona::default()` — no ua_metadata, no screen.
        let observer = std::sync::Arc::new(StealthObserver::new(profile, fp));

        let (mut mock, conn) = MockConnection::pair_with_observers(vec![observer.clone()]);

        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S1",
                "targetInfo": {
                    "targetId": "T1",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        for expected in [
            "Page.enable",
            "Emulation.setUserAgentOverride",
            "Emulation.setDeviceMetricsOverride",
            "Emulation.setFocusEmulationEnabled",
            "Page.setBypassCSP",
            "Page.addScriptToEvaluateOnNewDocument",
            "Runtime.runIfWaitingForDebugger",
        ] {
            let id =
                tokio::time::timeout(std::time::Duration::from_secs(2), mock.expect_cmd(expected))
                    .await
                    .unwrap_or_else(|_| panic!("did not see {expected} within 2s"));
            if expected == "Emulation.setUserAgentOverride" {
                let uam = mock.last_sent()["params"]["userAgentMetadata"].clone();
                let expected_json = serde_json::to_value(&expected_uam).unwrap();
                assert_eq!(
                    uam, expected_json,
                    "absent persona UAM → fingerprint's verbatim"
                );
            }
            if expected == "Emulation.setDeviceMetricsOverride" {
                let params = mock.last_sent()["params"].clone();
                // Today's fixed default, unchanged.
                assert_eq!(params["width"].as_u64(), Some(1920));
                assert_eq!(params["height"].as_u64(), Some(1080));
                assert_eq!(params["deviceScaleFactor"].as_f64(), Some(1.0));
            }
            mock.reply(id, json!({})).await;
        }

        conn.shutdown();
    }

    #[tokio::test]
    async fn geolocation_override_omits_accuracy_when_unset() {
        let fp = Fingerprint {
            platform: Platform::MacIntel,
            chrome_major: 120,
            chrome_full: "120.0.6099.234".into(),
            cpu_count: 10,
            memory_gb: 8,
            ua_string: crate::ua::compose_ua_string(Platform::MacIntel, "120.0.6099.234"),
            ua_metadata: crate::UserAgentMetadata::realistic(
                Platform::MacIntel,
                120,
                "120.0.6099.234",
            ),
            timezone: None,
            locale: None,
            languages: None,
            screen: None,
        };
        let persona = crate::Persona {
            geolocation: Some(crate::persona::GeoPos {
                latitude: 1.0,
                longitude: 2.0,
                accuracy: None,
            }),
            ..crate::Persona::default()
        };
        let profile = StealthProfile::native();
        let observer = std::sync::Arc::new(StealthObserver::with_persona(profile, fp, persona));

        let (mut mock, conn) = MockConnection::pair_with_observers(vec![observer.clone()]);

        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S1",
                "targetInfo": {
                    "targetId": "T1",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        for expected in [
            "Page.enable",
            "Emulation.setUserAgentOverride",
            "Emulation.setDeviceMetricsOverride",
            "Emulation.setFocusEmulationEnabled",
            "Emulation.setGeolocationOverride",
            "Runtime.runIfWaitingForDebugger",
        ] {
            let id =
                tokio::time::timeout(std::time::Duration::from_secs(2), mock.expect_cmd(expected))
                    .await
                    .unwrap_or_else(|_| panic!("did not see {expected} within 2s"));
            if expected == "Emulation.setGeolocationOverride" {
                let params = mock.last_sent()["params"].clone();
                assert_eq!(params["latitude"].as_f64(), Some(1.0));
                assert_eq!(params["longitude"].as_f64(), Some(2.0));
                assert!(
                    params.get("accuracy").is_none(),
                    "accuracy must be omitted when unset, got: {params}"
                );
            }
            mock.reply(id, json!({})).await;
        }

        conn.shutdown();
    }

    #[tokio::test]
    async fn off_observer_skips_all_commands_just_releases_debugger() {
        let fp = Fingerprint {
            platform: Platform::MacIntel,
            chrome_major: 120,
            chrome_full: "120.0.6099.234".into(),
            cpu_count: 10,
            memory_gb: 8,
            ua_string: String::new(),
            ua_metadata: crate::UserAgentMetadata::realistic(
                Platform::MacIntel,
                120,
                "120.0.6099.234",
            ),
            timezone: None,
            locale: None,
            languages: None,
            screen: None,
        };
        let observer = std::sync::Arc::new(StealthObserver::new(StealthProfile::off(), fp));
        let (mut mock, conn) = MockConnection::pair_with_observers(vec![observer]);

        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S1",
                "targetInfo": {
                    "targetId": "T1",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        // Off profile: only the actor's release-debugger call.
        let id = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            mock.expect_cmd("Runtime.runIfWaitingForDebugger"),
        )
        .await
        .unwrap();
        mock.reply(id, json!({})).await;
        conn.shutdown();
    }
}