rightkit-browser 0.3.4

Shared Chrome DevTools Protocol browser runtime for Right Suite: multi-page sessions, named profiles, real CDP input, observations with stale-ref checks.
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
use crate::error::{BrowserError, Result};
use crate::policy::{AdmissionHook, EventSink, NetworkPolicy};
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Where the browser keeps cookies, storage, and logins.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProfileSpec {
    /// Throwaway profile deleted when the session drops (default).
    Temporary,
    /// Named persistent profile at `<root>/<name>`. One live session per name;
    /// a second launch fails with `ProfileInUse` instead of corrupting state.
    Named { root: PathBuf, name: String },
    /// Caller-owned, existing absolute user-data directory. Never created or deleted
    /// by the session; no named-profile validation or real-profile exclusion applies.
    Directory(PathBuf),
    /// Named persistent profile at `<root>/<name>` seeded, with the user's consent, from the
    /// sign-ins of a Chromium-family browser profile (see [`crate::ImportSpec`]). Locked like
    /// [`Self::Named`]; the browser's own files are only read, never written. Every action of
    /// the session is confined to the consented domains and stops when consent is revoked.
    ImportedFrom {
        root: PathBuf,
        name: String,
        import: crate::real_session::ImportSpec,
    },
}

#[derive(Clone)]
pub struct LaunchOptions {
    pub headless: bool,
    /// Passes `--mute-audio`. Default true.
    pub mute_audio: bool,
    pub profile: ProfileSpec,
    /// Explicit browser executable. When `None`, launch resolves Chrome for Testing with
    /// [`chrome_for_testing_path`]. Ignored by [`Self::system_chrome_only`].
    pub chrome_path: Option<PathBuf>,
    /// Opt-in: when Chrome for Testing is not installed, fall back to the system browser
    /// ([`find_chrome`]). Off by default: regular Google Chrome on macOS leaves an APFS
    /// code-sign clone of its bundle behind for every instance that does not shut down cleanly.
    pub allow_system_chrome: bool,
    /// Resolve only through [`find_chrome`], ignoring `chrome_path` and Chrome for
    /// Testing discovery. Off by default; enabled by [`Self::system_chrome_only`].
    pub use_system_chrome_only: bool,
    pub viewport: (u32, u32),
    pub launch_timeout: Duration,
    /// Deadline for each CDP request, including `Page.navigate`. Default 30 s (chromiumoxide's).
    /// Raise it for dev servers whose first load is slow (e.g. Vite's cold dependency optimizer).
    pub request_timeout: Duration,
    /// Extra Chrome flags, with or without leading `--`.
    pub extra_args: Vec<String>,
    /// Defaults to `<profile>/downloads` for temporary profiles and
    /// `<profile>/rightkit-downloads` for persistent ones.
    pub download_dir: Option<PathBuf>,
    /// When set, `upload` refuses files outside this root.
    pub upload_root: Option<PathBuf>,
    /// Gates every navigation, input, and script action before it has any effect.
    /// `None` admits everything (trusted callers).
    pub admission: Option<AdmissionHook>,
    /// Network/SSRF policy. Default blocks loopback, link-local, private ranges,
    /// `localhost`, and `file:` unless allowed.
    pub network: NetworkPolicy,
    /// Receives start/stop/crash/denied lifecycle events (session id, reason, time).
    pub on_event: Option<EventSink>,
    /// Windows: the caller's job object (see [`Self::windows_job`]). Chromium and every
    /// helper it starts are bound to it; a clone of these options keeps the duplicate open.
    #[cfg(windows)]
    pub windows_job: Option<std::sync::Arc<std::os::windows::io::OwnedHandle>>,
}

impl std::fmt::Debug for LaunchOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LaunchOptions")
            .field("headless", &self.headless)
            .field("profile", &self.profile)
            .field("network", &self.network)
            .field("admission", &self.admission.is_some())
            .finish_non_exhaustive()
    }
}

impl Default for LaunchOptions {
    fn default() -> Self {
        Self {
            headless: true,
            mute_audio: true,
            profile: ProfileSpec::Temporary,
            chrome_path: None,
            allow_system_chrome: false,
            use_system_chrome_only: false,
            viewport: (1280, 800),
            launch_timeout: Duration::from_secs(60),
            request_timeout: Duration::from_secs(30),
            extra_args: Vec::new(),
            download_dir: None,
            upload_root: None,
            admission: None,
            network: NetworkPolicy::default(),
            on_event: None,
            #[cfg(windows)]
            windows_job: None,
        }
    }
}

impl LaunchOptions {
    /// Opt in to the system Chrome/Chromium/Edge when Chrome for Testing is missing.
    pub fn system_chrome(mut self) -> Self {
        self.allow_system_chrome = true;
        self.use_system_chrome_only = false;
        self
    }
    /// Use only system Chrome/Chromium/Edge via [`find_chrome`]. Ignores explicit
    /// `chrome_path` and Chrome for Testing installs/environment overrides; errors
    /// with [`BrowserError::ChromeNotFound`] when no system browser is found.
    pub fn system_chrome_only(mut self) -> Self {
        self.use_system_chrome_only = true;
        self.allow_system_chrome = false;
        self
    }
    pub fn headed(mut self) -> Self {
        self.headless = false;
        self
    }
    pub fn admission(mut self, hook: AdmissionHook) -> Self {
        self.admission = Some(hook);
        self
    }
    /// Per-request CDP deadline (navigation included).
    pub fn request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = timeout;
        self
    }
    pub fn network(mut self, policy: NetworkPolicy) -> Self {
        self.network = policy;
        self
    }
    pub fn on_event(
        mut self,
        f: impl Fn(&crate::policy::BrowserEvent) + Send + Sync + 'static,
    ) -> Self {
        self.on_event = Some(std::sync::Arc::new(f));
        self
    }
    /// Windows: bind Chromium to the caller's job object (an in-process host's own job).
    /// Chromium joins it before running its first instruction, beneath RightKit's own
    /// kill-on-close jobs, none of which allow breakaway: terminating or closing the
    /// caller's job kills the browser and all of its helpers. The handle is duplicated; the
    /// session closes its duplicate as soon as Chromium has been bound.
    #[cfg(windows)]
    pub fn windows_job(
        mut self,
        job: std::os::windows::io::BorrowedHandle<'_>,
    ) -> std::io::Result<Self> {
        self.windows_job = Some(std::sync::Arc::new(job.try_clone_to_owned()?));
        Ok(self)
    }
    pub fn named_profile(mut self, root: impl Into<PathBuf>, name: impl Into<String>) -> Self {
        self.profile = ProfileSpec::Named {
            root: root.into(),
            name: name.into(),
        };
        self
    }
    /// Show the browser window (`false` is the default headless mode). The action API is the
    /// same in both modes.
    pub fn headless(mut self, on: bool) -> Self {
        self.headless = on;
        self
    }
    /// Same as `headless(false)`.
    pub fn visible(self) -> Self {
        self.headless(false)
    }
    /// Seed a named persistent profile from the user's own browser, with consent. Pair with
    /// the same browser's executable ([`crate::browser_executable`]) so its sign-in encryption
    /// key applies; [`crate::BrowserSession::attach_user_browser`] does both.
    pub fn imported_profile(
        mut self,
        root: impl Into<PathBuf>,
        name: impl Into<String>,
        import: crate::real_session::ImportSpec,
    ) -> Self {
        self.profile = ProfileSpec::ImportedFrom {
            root: root.into(),
            name: name.into(),
            import,
        };
        self
    }
    /// Use an existing absolute Chrome user-data directory, including paths with
    /// spaces or other filesystem-supported characters. Validated at launch; never
    /// created or deleted. The caller owns exclusive access to this directory.
    pub fn profile_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.profile = ProfileSpec::Directory(path.into());
        self
    }
}

pub(crate) fn validate_profile_dir(path: &Path) -> Result<()> {
    if !path.is_absolute() {
        return Err(BrowserError::Profile(format!(
            "profile directory must be absolute: {}",
            path.display()
        )));
    }
    let metadata = std::fs::metadata(path).map_err(|e| {
        BrowserError::Profile(format!(
            "profile directory must exist and be accessible: {} ({e})",
            path.display()
        ))
    })?;
    if !metadata.is_dir() {
        return Err(BrowserError::Profile(format!(
            "profile path is not a directory: {}",
            path.display()
        )));
    }
    Ok(())
}

pub(crate) fn validate_profile_name(name: &str) -> Result<()> {
    let ok = !name.is_empty()
        && name.len() <= 64
        && !name.starts_with('.')
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
    if ok {
        Ok(())
    } else {
        Err(BrowserError::Profile(format!(
            "invalid profile name '{name}'"
        )))
    }
}

/// Environment variable naming an explicit Chrome for Testing executable.
pub const CHROME_FOR_TESTING_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING";

/// Override the RightKit-managed Chrome for Testing root (the folder that holds `current`).
pub const CHROME_FOR_TESTING_ROOT_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING_ROOT";

/// Folder name of the one managed install inside the managed root.
pub const MANAGED_CURRENT_DIR: &str = "current";
/// Folder name of the single rollback copy kept beside [`MANAGED_CURRENT_DIR`].
pub const MANAGED_PREVIOUS_DIR: &str = "current.previous";
/// Folder name the installer extracts into before swapping it into `current`.
#[cfg_attr(not(feature = "install"), allow(dead_code))]
pub const MANAGED_STAGING_DIR: &str = "current.staging";

/// How to get Chrome for Testing; part of [`BrowserError::ChromeForTestingNotFound`].
pub const CHROME_FOR_TESTING_INSTALL_HINT: &str = "Chrome for Testing is put in place by the app's installer or updater step, which calls \
rightkit_browser::install::ensure_chrome_for_testing (cargo feature `install`; pinned version, SHA-256 checked) \
into <app data>/Orthic Labs/shared/chrome-for-testing/current. For development, point \
RIGHTKIT_CHROME_FOR_TESTING at an existing Chrome for Testing executable, or run \
`rightkit-qa-chrome install` from @rightkit/qa-chrome. Regular Google Chrome is used only with \
LaunchOptions::system_chrome(): on macOS each killed instance leaks a code-sign clone.";

/// The RightKit-managed Chrome for Testing folder and its fixed layout: one `current`
/// install, one `current.previous` rollback copy, and `current.staging` while an install runs.
/// No per-version folders and no new id: every app resolves the same path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManagedRoot {
    root: PathBuf,
}

#[cfg_attr(not(feature = "install"), allow(dead_code))]
impl ManagedRoot {
    /// The suite-wide root (`<app data>/Orthic Labs/shared/chrome-for-testing`), or
    /// `RIGHTKIT_CHROME_FOR_TESTING_ROOT` when set.
    pub fn resolve() -> Self {
        let home = home_dir().unwrap_or_default();
        let env_path = |k: &str| {
            std::env::var_os(k)
                .filter(|v| !v.is_empty())
                .map(PathBuf::from)
        };
        Self {
            root: managed_chrome_for_testing_root(&home, &env_path),
        }
    }

    /// An explicit root (tests, relocated installs).
    pub fn at(root: impl Into<PathBuf>) -> Self {
        Self { root: root.into() }
    }

    /// The root folder itself.
    pub fn path(&self) -> &Path {
        &self.root
    }

    /// `<root>/current`: the installed Chrome for Testing.
    pub fn current(&self) -> PathBuf {
        self.root.join(MANAGED_CURRENT_DIR)
    }

    /// `<root>/current.previous`: the one rollback copy.
    pub fn previous(&self) -> PathBuf {
        self.root.join(MANAGED_PREVIOUS_DIR)
    }

    /// `<root>/current.staging`: where an install extracts before it swaps into `current`.
    pub fn staging(&self) -> PathBuf {
        self.root.join(MANAGED_STAGING_DIR)
    }

    /// The Chrome executable inside `current` for this platform.
    pub fn executable(&self) -> PathBuf {
        executable_in(&self.current())
    }
}

/// Chrome for Testing's platform key for this build, as Google names it.
pub(crate) fn platform_key() -> &'static str {
    if cfg!(target_os = "macos") {
        if cfg!(target_arch = "aarch64") {
            "mac-arm64"
        } else {
            "mac-x64"
        }
    } else if cfg!(target_os = "windows") {
        "win64"
    } else {
        "linux64"
    }
}

/// The Chrome executable inside one extracted Chrome for Testing folder, for this platform.
pub(crate) fn executable_in(dir: &Path) -> PathBuf {
    let sub = format!("chrome-{}", platform_key());
    if cfg!(target_os = "macos") {
        dir.join(sub).join(MAC_CFT_APP)
    } else if cfg!(target_os = "windows") {
        dir.join(sub).join("chrome.exe")
    } else {
        dir.join(sub).join("chrome")
    }
}

const MAC_CFT_APP: &str = "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing";

fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
}

fn version_key(name: &str) -> Vec<u64> {
    name.split(|c: char| !c.is_ascii_digit())
        .filter(|p| !p.is_empty())
        .filter_map(|p| p.parse().ok())
        .collect()
}

/// Children of `root` whose names start with one of `prefixes`, newest version first.
fn versioned_children(root: &Path, prefixes: &[&str]) -> Vec<PathBuf> {
    let mut names: Vec<String> = std::fs::read_dir(root)
        .map(|rd| {
            rd.filter_map(|e| e.ok())
                .map(|e| e.file_name().to_string_lossy().into_owned())
                .filter(|n| prefixes.iter().any(|p| n.starts_with(p)))
                .collect()
        })
        .unwrap_or_default();
    names.sort_by(|a, b| version_key(b).cmp(&version_key(a)).then_with(|| b.cmp(a)));
    names.into_iter().map(|n| root.join(n)).collect()
}

fn managed_chrome_for_testing_root(
    home: &Path,
    env_path: &impl Fn(&str) -> Option<PathBuf>,
) -> PathBuf {
    if let Some(root) = env_path(CHROME_FOR_TESTING_ROOT_ENV) {
        return root;
    }
    let app_data = if cfg!(target_os = "macos") {
        home.join("Library/Application Support")
    } else if cfg!(target_os = "windows") {
        env_path("LOCALAPPDATA").unwrap_or_else(|| home.join("AppData").join("Local"))
    } else {
        env_path("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"))
    };
    app_data.join("Orthic Labs/shared/chrome-for-testing")
}

/// Dotted numeric version folders of the managed root, newest first (qa-chrome's layout);
/// staging/metadata entries are ignored.
fn managed_version_dirs(root: &Path) -> Vec<PathBuf> {
    versioned_children(root, &[""])
        .into_iter()
        .filter(|dir| {
            dir.is_dir()
                && dir
                    .file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|name| {
                        name.contains('.')
                            && name.split('.').all(|part| {
                                !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())
                            })
                    })
        })
        .collect()
}

/// Managed candidates, best first: `current`, then `current.previous` (only reached when an
/// interrupted swap left no `current`), then legacy per-version folders (qa-chrome before the
/// fixed layout), newest first.
fn managed_chrome_for_testing_candidates(root: &Path) -> Vec<PathBuf> {
    let managed = ManagedRoot::at(root);
    let mut out = vec![
        executable_in(&managed.current()),
        executable_in(&managed.previous()),
    ];
    out.extend(
        managed_version_dirs(root)
            .into_iter()
            .map(|dir| executable_in(&dir)),
    );
    out
}

/// Windows fixture only: `chrome-headless-shell` of the same Chrome for Testing version, which
/// never starts the crashpad handler (see [`chrome_headless_shell_path`]).
#[cfg(windows)]
pub(crate) const HEADLESS_SHELL_ENV: &str = "RIGHTKIT_CHROME_HEADLESS_SHELL";
#[cfg(windows)]
const HEADLESS_SHELL_WIN64: &str = "chrome-headless-shell-win64/chrome-headless-shell.exe";

/// Candidate `chrome-headless-shell.exe` paths for the Windows fixture, in resolution order: the
/// sibling of the resolved Chrome (`<version>/chrome-win64/chrome.exe` ->
/// `<dir>/chrome-headless-shell-win64/`), then the managed `current` and `current.previous`, then
/// each legacy managed version, newest first (`RIGHTKIT_CHROME_FOR_TESTING_ROOT` overrides the
/// root, as for Chrome).
#[cfg(windows)]
fn chrome_headless_shell_candidates(chrome: &Path, managed_root: &Path) -> Vec<PathBuf> {
    let managed = ManagedRoot::at(managed_root);
    let mut out = Vec::new();
    if let Some(version_dir) = chrome.parent().and_then(Path::parent) {
        out.push(version_dir.join(HEADLESS_SHELL_WIN64));
    }
    out.push(managed.current().join(HEADLESS_SHELL_WIN64));
    out.push(managed.previous().join(HEADLESS_SHELL_WIN64));
    out.extend(
        managed_version_dirs(managed_root)
            .into_iter()
            .map(|dir| dir.join(HEADLESS_SHELL_WIN64)),
    );
    out
}

/// Resolve `chrome-headless-shell.exe` for the Windows fixture: `RIGHTKIT_CHROME_HEADLESS_SHELL`
/// (must exist), then [`chrome_headless_shell_candidates`]. Chrome's browser process starts the
/// crashpad handler unconditionally, which cannot create its named pipe inside an AppContainer;
/// the headless shell never starts it on Windows. Production launches never call this.
#[cfg(windows)]
pub(crate) fn chrome_headless_shell_path(chrome: &Path) -> Result<PathBuf> {
    let missing = |what: String| {
        BrowserError::ChromeForTestingNotFound(format!(
            "{what}\nThe Windows fixture runs chrome-headless-shell from the same Chrome for Testing \
             version (chrome-headless-shell-win64.zip, unpacked beside chrome-win64, or {HEADLESS_SHELL_ENV})"
        ))
    };
    if let Some(p) = std::env::var_os(HEADLESS_SHELL_ENV).filter(|v| !v.is_empty()) {
        let p = PathBuf::from(p);
        return if p.exists() {
            Ok(p)
        } else {
            Err(missing(format!(
                "{HEADLESS_SHELL_ENV} points at a missing file: {}",
                p.display()
            )))
        };
    }
    let home = home_dir().unwrap_or_default();
    let env_path = |k: &str| {
        std::env::var_os(k)
            .filter(|v| !v.is_empty())
            .map(PathBuf::from)
    };
    let root = managed_chrome_for_testing_root(&home, &env_path);
    let candidates = chrome_headless_shell_candidates(chrome, &root);
    if let Some(p) = candidates.iter().find(|p| p.exists()) {
        return Ok(p.clone());
    }
    let searched: Vec<String> = candidates
        .iter()
        .map(|p| format!("  {}", p.display()))
        .collect();
    Err(missing(format!(
        "chrome-headless-shell is not installed; searched:\n{}",
        searched.join("\n")
    )))
}

/// Known Chrome for Testing install locations, in resolution order: the RightKit-managed
/// `current` (then `current.previous`, then legacy per-version folders;
/// `RIGHTKIT_CHROME_FOR_TESTING_ROOT` overrides the root), app installs, then
/// Puppeteer's cache (`PUPPETEER_CACHE_DIR`), then Playwright's (`PLAYWRIGHT_BROWSERS_PATH`),
/// newest version first within each cache.
pub fn chrome_for_testing_candidates() -> Vec<PathBuf> {
    let home = home_dir().unwrap_or_default();
    let env_path = |k: &str| {
        std::env::var_os(k)
            .filter(|v| !v.is_empty())
            .map(PathBuf::from)
    };
    let puppeteer = env_path("PUPPETEER_CACHE_DIR")
        .unwrap_or_else(|| home.join(".cache").join("puppeteer"))
        .join("chrome");
    let managed_root = managed_chrome_for_testing_root(&home, &env_path);
    let mut out = managed_chrome_for_testing_candidates(&managed_root);
    if cfg!(target_os = "macos") {
        out.push(Path::new("/Applications").join(MAC_CFT_APP));
        out.push(home.join("Applications").join(MAC_CFT_APP));
        let subs: [&str; 2] = if cfg!(target_arch = "aarch64") {
            ["chrome-mac-arm64", "chrome-mac-x64"]
        } else {
            ["chrome-mac-x64", "chrome-mac-arm64"]
        };
        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
            .unwrap_or_else(|| home.join("Library/Caches/ms-playwright"));
        for dir in versioned_children(&puppeteer, &["mac_arm-", "mac-"])
            .into_iter()
            .chain(versioned_children(&playwright, &["chromium-"]))
        {
            for sub in subs {
                out.push(dir.join(sub).join(MAC_CFT_APP));
            }
        }
    } else if cfg!(target_os = "windows") {
        let local = env_path("LOCALAPPDATA").unwrap_or_else(|| home.join(r"AppData\Local"));
        for dir in versioned_children(&puppeteer, &["win64-", "win32-"]) {
            out.push(dir.join("chrome-win64").join("chrome.exe"));
            out.push(dir.join("chrome-win32").join("chrome.exe"));
        }
        let playwright =
            env_path("PLAYWRIGHT_BROWSERS_PATH").unwrap_or_else(|| local.join("ms-playwright"));
        for dir in versioned_children(&playwright, &["chromium-"]) {
            out.push(dir.join("chrome-win64").join("chrome.exe"));
        }
    } else {
        for dir in versioned_children(&puppeteer, &["linux-", "linux_arm-"]) {
            out.push(dir.join("chrome-linux64").join("chrome"));
            out.push(dir.join("chrome-linux-arm64").join("chrome"));
        }
        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
            .unwrap_or_else(|| home.join(".cache").join("ms-playwright"));
        for dir in versioned_children(&playwright, &["chromium-"]) {
            out.push(dir.join("chrome-linux64").join("chrome"));
        }
    }
    out
}

/// Resolve Chrome for Testing: `explicit`, then `RIGHTKIT_CHROME_FOR_TESTING`, then
/// [`chrome_for_testing_candidates`]. Errors with install instructions; never returns
/// regular Chrome.
pub fn chrome_for_testing_path(explicit: Option<&Path>) -> Result<PathBuf> {
    let missing = |what: String| {
        BrowserError::ChromeForTestingNotFound(format!("{what}\n{CHROME_FOR_TESTING_INSTALL_HINT}"))
    };
    if let Some(p) = explicit {
        return if p.exists() {
            Ok(p.to_path_buf())
        } else {
            Err(missing(format!(
                "explicit Chrome for Testing executable does not exist: {}",
                p.display()
            )))
        };
    }
    if let Some(p) = std::env::var_os(CHROME_FOR_TESTING_ENV).filter(|v| !v.is_empty()) {
        let p = PathBuf::from(p);
        return if p.exists() {
            Ok(p)
        } else {
            Err(missing(format!(
                "{CHROME_FOR_TESTING_ENV} points at a missing file: {}",
                p.display()
            )))
        };
    }
    let candidates = chrome_for_testing_candidates();
    if let Some(p) = candidates.iter().find(|p| p.exists()) {
        return Ok(p.clone());
    }
    let searched: Vec<String> = candidates
        .iter()
        .map(|p| format!("  {}", p.display()))
        .collect();
    Err(missing(format!(
        "Chrome for Testing is not installed; searched:\n{}",
        if searched.is_empty() {
            "  (nothing)".to_string()
        } else {
            searched.join("\n")
        }
    )))
}

/// System-only selection takes priority; otherwise `chrome_path` as given, then Chrome
/// for Testing, then (only with [`LaunchOptions::system_chrome`]) the system browser.
pub(crate) fn resolve_executable(opts: &LaunchOptions) -> Result<PathBuf> {
    resolve_executable_with(opts, || chrome_for_testing_path(None), find_chrome)
}

fn resolve_executable_with(
    opts: &LaunchOptions,
    cft: impl FnOnce() -> Result<PathBuf>,
    system: impl FnOnce() -> Option<PathBuf>,
) -> Result<PathBuf> {
    if opts.use_system_chrome_only {
        return system().ok_or(BrowserError::ChromeNotFound);
    }
    if let Some(p) = &opts.chrome_path {
        return Ok(p.clone());
    }
    match cft() {
        Ok(p) => Ok(p),
        Err(e) if opts.allow_system_chrome => system().ok_or(e),
        Err(e) => Err(e),
    }
}

/// System Chrome, Chromium, then Edge. `CHROME` env overrides. Launch uses this only with
/// [`LaunchOptions::system_chrome`] or [`LaunchOptions::system_chrome_only`];
/// prefer [`chrome_for_testing_path`] for isolated automation.
pub fn find_chrome() -> Option<PathBuf> {
    if let Ok(p) = std::env::var("CHROME") {
        let p = PathBuf::from(p);
        if p.exists() {
            return Some(p);
        }
    }
    let candidates: &[&str] = if cfg!(target_os = "windows") {
        &[
            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
            r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
        ]
    } else if cfg!(target_os = "macos") {
        &[
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            "/Applications/Chromium.app/Contents/MacOS/Chromium",
            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
        ]
    } else {
        &[
            "/usr/bin/google-chrome",
            "/usr/bin/chromium",
            "/usr/bin/chromium-browser",
            "/usr/bin/microsoft-edge",
        ]
    };
    candidates
        .iter()
        .map(PathBuf::from)
        .find(|p| Path::new(p).exists())
}

/// Chrome flags a caller may not pass: they would redirect the profile to the
/// user's real browser data or expose the debugging endpoint outside this session.
pub(crate) fn validate_extra_args(args: &[String]) -> Result<()> {
    const FORBIDDEN: &[&str] = &[
        "user-data-dir",
        "profile-directory",
        "remote-debugging-port",
        "remote-debugging-address",
        "remote-debugging-pipe",
        "remote-allow-origins",
        "disable-web-security",
        "incognito-bypass",
    ];
    for a in args {
        let name = a.trim_start_matches('-').split('=').next().unwrap_or("");
        if FORBIDDEN.contains(&name) {
            return Err(BrowserError::Invalid(format!(
                "chrome flag '--{name}' is managed by the session"
            )));
        }
    }
    Ok(())
}

/// Refuse roots that are (or sit inside) a real browser's own user-data directory.
pub(crate) fn reject_real_browser_profile(root: &Path) -> Result<()> {
    let mut real: Vec<PathBuf> = Vec::new();
    if let Some(home) = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
    {
        for rel in [
            "Library/Application Support/Google/Chrome",
            "Library/Application Support/Chromium",
            "Library/Application Support/Microsoft Edge",
            ".config/google-chrome",
            ".config/chromium",
            ".config/microsoft-edge",
        ] {
            real.push(home.join(rel));
        }
    }
    if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
        for rel in [
            r"Google\Chrome\User Data",
            r"Chromium\User Data",
            r"Microsoft\Edge\User Data",
        ] {
            real.push(local.join(rel));
        }
    }
    std::fs::create_dir_all(root)?;
    let root = root.canonicalize()?;
    for r in real {
        if let Ok(r) = r.canonicalize() {
            if root.starts_with(&r) {
                return Err(BrowserError::Profile(
                    "refusing to use the user's real browser profile".into(),
                ));
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsString;
    use std::sync::{Mutex, MutexGuard};

    // Serialize resolver tests that change process environment; restore even on panic.
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    struct EnvGuard {
        saved: Vec<(&'static str, Option<OsString>)>,
        _lock: MutexGuard<'static, ()>,
    }

    impl EnvGuard {
        fn new(values: &[(&'static str, Option<&Path>)]) -> Self {
            let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            let saved = values
                .iter()
                .map(|(key, _)| (*key, std::env::var_os(key)))
                .collect();
            for (key, value) in values {
                match value {
                    Some(value) => std::env::set_var(key, value),
                    None => std::env::remove_var(key),
                }
            }
            Self { saved, _lock: lock }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            for (key, value) in &self.saved {
                match value {
                    Some(value) => std::env::set_var(key, value),
                    None => std::env::remove_var(key),
                }
            }
        }
    }

    fn write_executable(path: &Path) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, "fixture, not a browser").unwrap();
    }

    fn managed_executable(root: &Path, version: &str) -> PathBuf {
        let relative = if cfg!(target_os = "macos") {
            if cfg!(target_arch = "aarch64") {
                "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
            } else {
                "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
            }
        } else if cfg!(target_os = "windows") {
            "chrome-win64/chrome.exe"
        } else {
            "chrome-linux64/chrome"
        };
        root.join(version).join(relative)
    }

    #[test]
    fn system_chrome_only_ignores_explicit_env_and_managed_cft() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("managed CfT");
        let managed = managed_executable(&root, "130.10.0.0");
        let explicit = temp.path().join("explicit CfT");
        let system = temp.path().join("system Chrome");
        for path in [&managed, &explicit, &system] {
            write_executable(path);
        }
        let _env = EnvGuard::new(&[
            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
            (CHROME_FOR_TESTING_ENV, Some(&managed)),
            ("CHROME", Some(&system)),
        ]);
        assert_eq!(chrome_for_testing_path(None).unwrap(), managed);
        let opts = LaunchOptions {
            chrome_path: Some(explicit),
            ..LaunchOptions::default().system_chrome_only()
        };
        assert_eq!(resolve_executable(&opts).unwrap(), system);
        assert_eq!(find_chrome().unwrap(), system);
        // Also prove discovery is never called, regardless of installed CfT versions.
        assert_eq!(
            resolve_executable_with(
                &opts,
                || panic!("CfT discovery called"),
                || Some(system.clone()),
            )
            .unwrap(),
            system
        );
    }

    #[cfg(windows)]
    #[test]
    fn headless_shell_candidates_are_the_sibling_then_managed_versions() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("root");
        for v in ["154.0.1.1", "155.0.8059.39"] {
            std::fs::create_dir_all(root.join(v)).unwrap();
        }
        let chrome = root.join("155.0.8059.39/chrome-win64/chrome.exe");
        let got = chrome_headless_shell_candidates(&chrome, &root);
        let shell = "chrome-headless-shell-win64/chrome-headless-shell.exe";
        assert_eq!(
            got,
            vec![
                root.join("155.0.8059.39").join(shell),
                root.join("current").join(shell),
                root.join("current.previous").join(shell),
                root.join("155.0.8059.39").join(shell),
                root.join("154.0.1.1").join(shell),
            ]
        );
    }

    #[test]
    fn managed_layout_is_one_current_one_previous_and_a_staging_folder() {
        let root = ManagedRoot::at("/managed");
        assert_eq!(root.current(), Path::new("/managed/current"));
        assert_eq!(root.previous(), Path::new("/managed/current.previous"));
        assert_eq!(root.staging(), Path::new("/managed/current.staging"));
        assert!(root.executable().starts_with("/managed/current"));
    }

    #[test]
    fn current_beats_previous_and_legacy_versions_and_the_env_override_still_wins() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("managed");
        let playwright = temp.path().join("ms-playwright");
        std::fs::create_dir(&playwright).unwrap();
        let managed = ManagedRoot::at(&root);
        let current = managed.executable();
        let previous = executable_in(&managed.previous());
        let legacy = managed_executable(&root, "999.0.0.0");
        for path in [&current, &previous, &legacy] {
            write_executable(path);
        }
        let explicit = temp.path().join("explicit CfT");
        write_executable(&explicit);
        let _env = EnvGuard::new(&[
            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
            (CHROME_FOR_TESTING_ENV, None),
            (
                "PUPPETEER_CACHE_DIR",
                Some(&temp.path().join("no puppeteer")),
            ),
            ("PLAYWRIGHT_BROWSERS_PATH", Some(&playwright)),
        ]);
        assert_eq!(
            &chrome_for_testing_candidates()[..3],
            &[current.clone(), previous.clone(), legacy]
        );
        assert_eq!(chrome_for_testing_path(None).unwrap(), current);
        std::fs::remove_file(&current).unwrap();
        assert_eq!(chrome_for_testing_path(None).unwrap(), previous);
        std::env::set_var(CHROME_FOR_TESTING_ENV, &explicit);
        assert_eq!(chrome_for_testing_path(None).unwrap(), explicit);
        std::env::remove_var(CHROME_FOR_TESTING_ENV);
        assert_eq!(chrome_for_testing_path(Some(&explicit)).unwrap(), explicit);
    }

    #[test]
    fn install_hint_names_the_installer_api_not_pnpm_dlx() {
        assert!(CHROME_FOR_TESTING_INSTALL_HINT.contains("ensure_chrome_for_testing"));
        assert!(!CHROME_FOR_TESTING_INSTALL_HINT.contains("pnpm dlx"));
    }

    #[test]
    fn system_chrome_only_errors_when_system_browser_is_missing() {
        let opts = LaunchOptions::default().system_chrome_only();
        let err =
            resolve_executable_with(&opts, || panic!("CfT discovery called"), || None).unwrap_err();
        assert!(matches!(&err, BrowserError::ChromeNotFound));
        assert_eq!(
            err.to_string(),
            "no Chrome, Chromium, or Edge executable found"
        );
    }

    #[test]
    fn defaults_and_system_chrome_preserve_cft_preference_and_fallback() {
        let temp = tempfile::tempdir().unwrap();
        let cft = temp.path().join("CfT");
        let system = temp.path().join("system Chrome");
        write_executable(&cft);
        write_executable(&system);
        let defaults = LaunchOptions::default();
        assert!(defaults.headless && defaults.mute_audio);
        assert!(!defaults.allow_system_chrome && !defaults.use_system_chrome_only);
        for opts in [defaults.clone(), defaults.clone().system_chrome()] {
            assert_eq!(
                resolve_executable_with(
                    &opts,
                    || Ok(cft.clone()),
                    || panic!("system lookup called"),
                )
                .unwrap(),
                cft
            );
        }
        assert!(matches!(
            resolve_executable_with(
                &defaults,
                || Err(BrowserError::ChromeForTestingNotFound("missing".into())),
                || panic!("default must not fall back"),
            ),
            Err(BrowserError::ChromeForTestingNotFound(_))
        ));
        let fallback = defaults.system_chrome_only().system_chrome();
        assert!(!fallback.use_system_chrome_only);
        assert_eq!(
            resolve_executable_with(
                &fallback,
                || Err(BrowserError::ChromeForTestingNotFound("missing".into())),
                || Some(system.clone()),
            )
            .unwrap(),
            system
        );
    }

    #[test]
    fn managed_root_uses_platform_data_directory_and_env_override() {
        let temp = tempfile::tempdir().unwrap();
        let home = temp.path();
        let suffix = Path::new("Orthic Labs/shared/chrome-for-testing");
        let default_data = if cfg!(target_os = "macos") {
            home.join("Library/Application Support")
        } else if cfg!(target_os = "windows") {
            home.join("AppData/Local")
        } else {
            home.join(".local/share")
        };
        assert_eq!(
            managed_chrome_for_testing_root(home, &|_| None),
            default_data.join(suffix)
        );
        let data = home.join("custom app data");
        let with_data = |key: &str| {
            if key == "LOCALAPPDATA" || key == "XDG_DATA_HOME" {
                Some(data.clone())
            } else {
                None
            }
        };
        let expected_data = if cfg!(target_os = "macos") {
            default_data
        } else {
            data.clone()
        };
        assert_eq!(
            managed_chrome_for_testing_root(home, &with_data),
            expected_data.join(suffix)
        );
        let override_root = home.join("custom managed root");
        assert_eq!(
            managed_chrome_for_testing_root(home, &|key| {
                if key == CHROME_FOR_TESTING_ROOT_ENV {
                    Some(override_root.clone())
                } else {
                    None
                }
            }),
            override_root
        );
    }

    #[test]
    fn managed_folder_wins_with_newest_numeric_version_first() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("managed Chrome for Testing");
        let puppeteer = temp.path().join("puppeteer");
        // An empty stand-in, so discovery does not list the user's own Playwright folder.
        let playwright = temp.path().join("ms-playwright");
        std::fs::create_dir(&playwright).unwrap();
        let older = managed_executable(&root, "129.99.0.0");
        let recent = managed_executable(&root, "130.2.0.0");
        let newest = managed_executable(&root, "130.10.0.0");
        let legacy_dir = if cfg!(target_os = "macos") {
            "mac-999.0.0.0"
        } else if cfg!(target_os = "windows") {
            "win64-999.0.0.0"
        } else {
            "linux-999.0.0.0"
        };
        let legacy = managed_executable(&puppeteer.join("chrome"), legacy_dir);
        for path in [&older, &recent, &newest, &legacy] {
            write_executable(path);
        }
        std::fs::create_dir(root.join("999.staging")).unwrap();
        std::fs::write(root.join("999.0.0.0"), "not a version directory").unwrap();
        let _env = EnvGuard::new(&[
            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
            (CHROME_FOR_TESTING_ENV, None),
            ("PUPPETEER_CACHE_DIR", Some(&puppeteer)),
            ("PLAYWRIGHT_BROWSERS_PATH", Some(&playwright)),
        ]);
        let candidates = chrome_for_testing_candidates();
        // #267 layout: `current` and `current.previous` come first, then the legacy
        // per-version folders, newest numeric version first.
        let managed = ManagedRoot::at(&root);
        assert_eq!(
            &candidates[..2],
            &[
                executable_in(&managed.current()),
                executable_in(&managed.previous())
            ]
        );
        assert_eq!(&candidates[2..5], &[newest.clone(), recent.clone(), older]);
        assert!(candidates.iter().position(|p| p == &legacy).unwrap() >= 5);
        assert_eq!(chrome_for_testing_path(None).unwrap(), newest);
        std::env::set_var(CHROME_FOR_TESTING_ENV, &legacy);
        assert_eq!(chrome_for_testing_path(None).unwrap(), legacy);
        std::env::remove_var(CHROME_FOR_TESTING_ENV);
        std::fs::remove_file(&newest).unwrap();
        assert_eq!(chrome_for_testing_path(None).unwrap(), recent);
        // Explicit executable selection retains priority over managed discovery.
        assert_eq!(chrome_for_testing_path(Some(&legacy)).unwrap(), legacy);
    }
}