Skip to main content

rightkit_browser/
config.rs

1use crate::error::{BrowserError, Result};
2use crate::policy::{AdmissionHook, EventSink, NetworkPolicy};
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6/// Where the browser keeps cookies, storage, and logins.
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub enum ProfileSpec {
9    /// Throwaway profile deleted when the session drops (default).
10    Temporary,
11    /// Named persistent profile at `<root>/<name>`. One live session per name;
12    /// a second launch fails with `ProfileInUse` instead of corrupting state.
13    Named { root: PathBuf, name: String },
14    /// Caller-owned, existing absolute user-data directory. Never created or deleted
15    /// by the session; no named-profile validation or real-profile exclusion applies.
16    Directory(PathBuf),
17    /// Named persistent profile at `<root>/<name>` seeded, with the user's consent, from the
18    /// sign-ins of a Chromium-family browser profile (see [`crate::ImportSpec`]). Locked like
19    /// [`Self::Named`]; the browser's own files are only read, never written. Every action of
20    /// the session is confined to the consented domains and stops when consent is revoked.
21    ImportedFrom {
22        root: PathBuf,
23        name: String,
24        import: crate::real_session::ImportSpec,
25    },
26}
27
28#[derive(Clone)]
29pub struct LaunchOptions {
30    pub headless: bool,
31    /// Passes `--mute-audio`. Default true.
32    pub mute_audio: bool,
33    pub profile: ProfileSpec,
34    /// Explicit browser executable. When `None`, launch resolves Chrome for Testing with
35    /// [`chrome_for_testing_path`]. Ignored by [`Self::system_chrome_only`].
36    pub chrome_path: Option<PathBuf>,
37    /// Opt-in: when Chrome for Testing is not installed, fall back to the system browser
38    /// ([`find_chrome`]). Off by default: regular Google Chrome on macOS leaves an APFS
39    /// code-sign clone of its bundle behind for every instance that does not shut down cleanly.
40    pub allow_system_chrome: bool,
41    /// Resolve only through [`find_chrome`], ignoring `chrome_path` and Chrome for
42    /// Testing discovery. Off by default; enabled by [`Self::system_chrome_only`].
43    pub use_system_chrome_only: bool,
44    pub viewport: (u32, u32),
45    pub launch_timeout: Duration,
46    /// Deadline for each CDP request, including `Page.navigate`. Default 30 s (chromiumoxide's).
47    /// Raise it for dev servers whose first load is slow (e.g. Vite's cold dependency optimizer).
48    pub request_timeout: Duration,
49    /// Extra Chrome flags, with or without leading `--`.
50    pub extra_args: Vec<String>,
51    /// Defaults to `<profile>/downloads` for temporary profiles and
52    /// `<profile>/rightkit-downloads` for persistent ones.
53    pub download_dir: Option<PathBuf>,
54    /// When set, `upload` refuses files outside this root.
55    pub upload_root: Option<PathBuf>,
56    /// Gates every navigation, input, and script action before it has any effect.
57    /// `None` admits everything (trusted callers).
58    pub admission: Option<AdmissionHook>,
59    /// Network/SSRF policy. Default blocks loopback, link-local, private ranges,
60    /// `localhost`, and `file:` unless allowed.
61    pub network: NetworkPolicy,
62    /// Receives start/stop/crash/denied lifecycle events (session id, reason, time).
63    pub on_event: Option<EventSink>,
64    /// Windows: the caller's job object (see [`Self::windows_job`]). Chromium and every
65    /// helper it starts are bound to it; a clone of these options keeps the duplicate open.
66    #[cfg(windows)]
67    pub windows_job: Option<std::sync::Arc<std::os::windows::io::OwnedHandle>>,
68}
69
70impl std::fmt::Debug for LaunchOptions {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("LaunchOptions")
73            .field("headless", &self.headless)
74            .field("profile", &self.profile)
75            .field("network", &self.network)
76            .field("admission", &self.admission.is_some())
77            .finish_non_exhaustive()
78    }
79}
80
81impl Default for LaunchOptions {
82    fn default() -> Self {
83        Self {
84            headless: true,
85            mute_audio: true,
86            profile: ProfileSpec::Temporary,
87            chrome_path: None,
88            allow_system_chrome: false,
89            use_system_chrome_only: false,
90            viewport: (1280, 800),
91            launch_timeout: Duration::from_secs(60),
92            request_timeout: Duration::from_secs(30),
93            extra_args: Vec::new(),
94            download_dir: None,
95            upload_root: None,
96            admission: None,
97            network: NetworkPolicy::default(),
98            on_event: None,
99            #[cfg(windows)]
100            windows_job: None,
101        }
102    }
103}
104
105impl LaunchOptions {
106    /// Opt in to the system Chrome/Chromium/Edge when Chrome for Testing is missing.
107    pub fn system_chrome(mut self) -> Self {
108        self.allow_system_chrome = true;
109        self.use_system_chrome_only = false;
110        self
111    }
112    /// Use only system Chrome/Chromium/Edge via [`find_chrome`]. Ignores explicit
113    /// `chrome_path` and Chrome for Testing installs/environment overrides; errors
114    /// with [`BrowserError::ChromeNotFound`] when no system browser is found.
115    pub fn system_chrome_only(mut self) -> Self {
116        self.use_system_chrome_only = true;
117        self.allow_system_chrome = false;
118        self
119    }
120    pub fn headed(mut self) -> Self {
121        self.headless = false;
122        self
123    }
124    pub fn admission(mut self, hook: AdmissionHook) -> Self {
125        self.admission = Some(hook);
126        self
127    }
128    /// Per-request CDP deadline (navigation included).
129    pub fn request_timeout(mut self, timeout: Duration) -> Self {
130        self.request_timeout = timeout;
131        self
132    }
133    pub fn network(mut self, policy: NetworkPolicy) -> Self {
134        self.network = policy;
135        self
136    }
137    pub fn on_event(
138        mut self,
139        f: impl Fn(&crate::policy::BrowserEvent) + Send + Sync + 'static,
140    ) -> Self {
141        self.on_event = Some(std::sync::Arc::new(f));
142        self
143    }
144    /// Windows: bind Chromium to the caller's job object (an in-process host's own job).
145    /// Chromium joins it before running its first instruction, beneath RightKit's own
146    /// kill-on-close jobs, none of which allow breakaway: terminating or closing the
147    /// caller's job kills the browser and all of its helpers. The handle is duplicated; the
148    /// session closes its duplicate as soon as Chromium has been bound.
149    #[cfg(windows)]
150    pub fn windows_job(
151        mut self,
152        job: std::os::windows::io::BorrowedHandle<'_>,
153    ) -> std::io::Result<Self> {
154        self.windows_job = Some(std::sync::Arc::new(job.try_clone_to_owned()?));
155        Ok(self)
156    }
157    pub fn named_profile(mut self, root: impl Into<PathBuf>, name: impl Into<String>) -> Self {
158        self.profile = ProfileSpec::Named {
159            root: root.into(),
160            name: name.into(),
161        };
162        self
163    }
164    /// Show the browser window (`false` is the default headless mode). The action API is the
165    /// same in both modes.
166    pub fn headless(mut self, on: bool) -> Self {
167        self.headless = on;
168        self
169    }
170    /// Same as `headless(false)`.
171    pub fn visible(self) -> Self {
172        self.headless(false)
173    }
174    /// Seed a named persistent profile from the user's own browser, with consent. Pair with
175    /// the same browser's executable ([`crate::browser_executable`]) so its sign-in encryption
176    /// key applies; [`crate::BrowserSession::attach_user_browser`] does both.
177    pub fn imported_profile(
178        mut self,
179        root: impl Into<PathBuf>,
180        name: impl Into<String>,
181        import: crate::real_session::ImportSpec,
182    ) -> Self {
183        self.profile = ProfileSpec::ImportedFrom {
184            root: root.into(),
185            name: name.into(),
186            import,
187        };
188        self
189    }
190    /// Use an existing absolute Chrome user-data directory, including paths with
191    /// spaces or other filesystem-supported characters. Validated at launch; never
192    /// created or deleted. The caller owns exclusive access to this directory.
193    pub fn profile_dir(mut self, path: impl Into<PathBuf>) -> Self {
194        self.profile = ProfileSpec::Directory(path.into());
195        self
196    }
197}
198
199pub(crate) fn validate_profile_dir(path: &Path) -> Result<()> {
200    if !path.is_absolute() {
201        return Err(BrowserError::Profile(format!(
202            "profile directory must be absolute: {}",
203            path.display()
204        )));
205    }
206    let metadata = std::fs::metadata(path).map_err(|e| {
207        BrowserError::Profile(format!(
208            "profile directory must exist and be accessible: {} ({e})",
209            path.display()
210        ))
211    })?;
212    if !metadata.is_dir() {
213        return Err(BrowserError::Profile(format!(
214            "profile path is not a directory: {}",
215            path.display()
216        )));
217    }
218    Ok(())
219}
220
221pub(crate) fn validate_profile_name(name: &str) -> Result<()> {
222    let ok = !name.is_empty()
223        && name.len() <= 64
224        && !name.starts_with('.')
225        && name
226            .chars()
227            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
228    if ok {
229        Ok(())
230    } else {
231        Err(BrowserError::Profile(format!(
232            "invalid profile name '{name}'"
233        )))
234    }
235}
236
237/// Environment variable naming an explicit Chrome for Testing executable.
238pub const CHROME_FOR_TESTING_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING";
239
240/// Override the RightKit-managed Chrome for Testing root (the folder that holds `current`).
241pub const CHROME_FOR_TESTING_ROOT_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING_ROOT";
242
243/// Folder name of the one managed install inside the managed root.
244pub const MANAGED_CURRENT_DIR: &str = "current";
245/// Folder name of the single rollback copy kept beside [`MANAGED_CURRENT_DIR`].
246pub const MANAGED_PREVIOUS_DIR: &str = "current.previous";
247/// Folder name the installer extracts into before swapping it into `current`.
248#[cfg_attr(not(feature = "install"), allow(dead_code))]
249pub const MANAGED_STAGING_DIR: &str = "current.staging";
250
251/// How to get Chrome for Testing; part of [`BrowserError::ChromeForTestingNotFound`].
252pub const CHROME_FOR_TESTING_INSTALL_HINT: &str = "Chrome for Testing is put in place by the app's installer or updater step, which calls \
253rightkit_browser::install::ensure_chrome_for_testing (cargo feature `install`; pinned version, SHA-256 checked) \
254into <app data>/Orthic Labs/shared/chrome-for-testing/current. For development, point \
255RIGHTKIT_CHROME_FOR_TESTING at an existing Chrome for Testing executable, or run \
256`rightkit-qa-chrome install` from @rightkit/qa-chrome. Regular Google Chrome is used only with \
257LaunchOptions::system_chrome(): on macOS each killed instance leaks a code-sign clone.";
258
259/// The RightKit-managed Chrome for Testing folder and its fixed layout: one `current`
260/// install, one `current.previous` rollback copy, and `current.staging` while an install runs.
261/// No per-version folders and no new id: every app resolves the same path.
262#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct ManagedRoot {
264    root: PathBuf,
265}
266
267#[cfg_attr(not(feature = "install"), allow(dead_code))]
268impl ManagedRoot {
269    /// The suite-wide root (`<app data>/Orthic Labs/shared/chrome-for-testing`), or
270    /// `RIGHTKIT_CHROME_FOR_TESTING_ROOT` when set.
271    pub fn resolve() -> Self {
272        let home = home_dir().unwrap_or_default();
273        let env_path = |k: &str| {
274            std::env::var_os(k)
275                .filter(|v| !v.is_empty())
276                .map(PathBuf::from)
277        };
278        Self {
279            root: managed_chrome_for_testing_root(&home, &env_path),
280        }
281    }
282
283    /// An explicit root (tests, relocated installs).
284    pub fn at(root: impl Into<PathBuf>) -> Self {
285        Self { root: root.into() }
286    }
287
288    /// The root folder itself.
289    pub fn path(&self) -> &Path {
290        &self.root
291    }
292
293    /// `<root>/current`: the installed Chrome for Testing.
294    pub fn current(&self) -> PathBuf {
295        self.root.join(MANAGED_CURRENT_DIR)
296    }
297
298    /// `<root>/current.previous`: the one rollback copy.
299    pub fn previous(&self) -> PathBuf {
300        self.root.join(MANAGED_PREVIOUS_DIR)
301    }
302
303    /// `<root>/current.staging`: where an install extracts before it swaps into `current`.
304    pub fn staging(&self) -> PathBuf {
305        self.root.join(MANAGED_STAGING_DIR)
306    }
307
308    /// The Chrome executable inside `current` for this platform.
309    pub fn executable(&self) -> PathBuf {
310        executable_in(&self.current())
311    }
312}
313
314/// Chrome for Testing's platform key for this build, as Google names it.
315pub(crate) fn platform_key() -> &'static str {
316    if cfg!(target_os = "macos") {
317        if cfg!(target_arch = "aarch64") {
318            "mac-arm64"
319        } else {
320            "mac-x64"
321        }
322    } else if cfg!(target_os = "windows") {
323        "win64"
324    } else {
325        "linux64"
326    }
327}
328
329/// The Chrome executable inside one extracted Chrome for Testing folder, for this platform.
330pub(crate) fn executable_in(dir: &Path) -> PathBuf {
331    let sub = format!("chrome-{}", platform_key());
332    if cfg!(target_os = "macos") {
333        dir.join(sub).join(MAC_CFT_APP)
334    } else if cfg!(target_os = "windows") {
335        dir.join(sub).join("chrome.exe")
336    } else {
337        dir.join(sub).join("chrome")
338    }
339}
340
341const MAC_CFT_APP: &str = "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing";
342
343fn home_dir() -> Option<PathBuf> {
344    std::env::var_os("HOME")
345        .or_else(|| std::env::var_os("USERPROFILE"))
346        .map(PathBuf::from)
347}
348
349fn version_key(name: &str) -> Vec<u64> {
350    name.split(|c: char| !c.is_ascii_digit())
351        .filter(|p| !p.is_empty())
352        .filter_map(|p| p.parse().ok())
353        .collect()
354}
355
356/// Children of `root` whose names start with one of `prefixes`, newest version first.
357fn versioned_children(root: &Path, prefixes: &[&str]) -> Vec<PathBuf> {
358    let mut names: Vec<String> = std::fs::read_dir(root)
359        .map(|rd| {
360            rd.filter_map(|e| e.ok())
361                .map(|e| e.file_name().to_string_lossy().into_owned())
362                .filter(|n| prefixes.iter().any(|p| n.starts_with(p)))
363                .collect()
364        })
365        .unwrap_or_default();
366    names.sort_by(|a, b| version_key(b).cmp(&version_key(a)).then_with(|| b.cmp(a)));
367    names.into_iter().map(|n| root.join(n)).collect()
368}
369
370fn managed_chrome_for_testing_root(
371    home: &Path,
372    env_path: &impl Fn(&str) -> Option<PathBuf>,
373) -> PathBuf {
374    if let Some(root) = env_path(CHROME_FOR_TESTING_ROOT_ENV) {
375        return root;
376    }
377    let app_data = if cfg!(target_os = "macos") {
378        home.join("Library/Application Support")
379    } else if cfg!(target_os = "windows") {
380        env_path("LOCALAPPDATA").unwrap_or_else(|| home.join("AppData").join("Local"))
381    } else {
382        env_path("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"))
383    };
384    app_data.join("Orthic Labs/shared/chrome-for-testing")
385}
386
387/// Dotted numeric version folders of the managed root, newest first (qa-chrome's layout);
388/// staging/metadata entries are ignored.
389fn managed_version_dirs(root: &Path) -> Vec<PathBuf> {
390    versioned_children(root, &[""])
391        .into_iter()
392        .filter(|dir| {
393            dir.is_dir()
394                && dir
395                    .file_name()
396                    .and_then(|n| n.to_str())
397                    .is_some_and(|name| {
398                        name.contains('.')
399                            && name.split('.').all(|part| {
400                                !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())
401                            })
402                    })
403        })
404        .collect()
405}
406
407/// Managed candidates, best first: `current`, then `current.previous` (only reached when an
408/// interrupted swap left no `current`), then legacy per-version folders (qa-chrome before the
409/// fixed layout), newest first.
410fn managed_chrome_for_testing_candidates(root: &Path) -> Vec<PathBuf> {
411    let managed = ManagedRoot::at(root);
412    let mut out = vec![
413        executable_in(&managed.current()),
414        executable_in(&managed.previous()),
415    ];
416    out.extend(
417        managed_version_dirs(root)
418            .into_iter()
419            .map(|dir| executable_in(&dir)),
420    );
421    out
422}
423
424/// Windows fixture only: `chrome-headless-shell` of the same Chrome for Testing version, which
425/// never starts the crashpad handler (see [`chrome_headless_shell_path`]).
426#[cfg(windows)]
427pub(crate) const HEADLESS_SHELL_ENV: &str = "RIGHTKIT_CHROME_HEADLESS_SHELL";
428#[cfg(windows)]
429const HEADLESS_SHELL_WIN64: &str = "chrome-headless-shell-win64/chrome-headless-shell.exe";
430
431/// Candidate `chrome-headless-shell.exe` paths for the Windows fixture, in resolution order: the
432/// sibling of the resolved Chrome (`<version>/chrome-win64/chrome.exe` ->
433/// `<dir>/chrome-headless-shell-win64/`), then the managed `current` and `current.previous`, then
434/// each legacy managed version, newest first (`RIGHTKIT_CHROME_FOR_TESTING_ROOT` overrides the
435/// root, as for Chrome).
436#[cfg(windows)]
437fn chrome_headless_shell_candidates(chrome: &Path, managed_root: &Path) -> Vec<PathBuf> {
438    let managed = ManagedRoot::at(managed_root);
439    let mut out = Vec::new();
440    if let Some(version_dir) = chrome.parent().and_then(Path::parent) {
441        out.push(version_dir.join(HEADLESS_SHELL_WIN64));
442    }
443    out.push(managed.current().join(HEADLESS_SHELL_WIN64));
444    out.push(managed.previous().join(HEADLESS_SHELL_WIN64));
445    out.extend(
446        managed_version_dirs(managed_root)
447            .into_iter()
448            .map(|dir| dir.join(HEADLESS_SHELL_WIN64)),
449    );
450    out
451}
452
453/// Resolve `chrome-headless-shell.exe` for the Windows fixture: `RIGHTKIT_CHROME_HEADLESS_SHELL`
454/// (must exist), then [`chrome_headless_shell_candidates`]. Chrome's browser process starts the
455/// crashpad handler unconditionally, which cannot create its named pipe inside an AppContainer;
456/// the headless shell never starts it on Windows. Production launches never call this.
457#[cfg(windows)]
458pub(crate) fn chrome_headless_shell_path(chrome: &Path) -> Result<PathBuf> {
459    let missing = |what: String| {
460        BrowserError::ChromeForTestingNotFound(format!(
461            "{what}\nThe Windows fixture runs chrome-headless-shell from the same Chrome for Testing \
462             version (chrome-headless-shell-win64.zip, unpacked beside chrome-win64, or {HEADLESS_SHELL_ENV})"
463        ))
464    };
465    if let Some(p) = std::env::var_os(HEADLESS_SHELL_ENV).filter(|v| !v.is_empty()) {
466        let p = PathBuf::from(p);
467        return if p.exists() {
468            Ok(p)
469        } else {
470            Err(missing(format!(
471                "{HEADLESS_SHELL_ENV} points at a missing file: {}",
472                p.display()
473            )))
474        };
475    }
476    let home = home_dir().unwrap_or_default();
477    let env_path = |k: &str| {
478        std::env::var_os(k)
479            .filter(|v| !v.is_empty())
480            .map(PathBuf::from)
481    };
482    let root = managed_chrome_for_testing_root(&home, &env_path);
483    let candidates = chrome_headless_shell_candidates(chrome, &root);
484    if let Some(p) = candidates.iter().find(|p| p.exists()) {
485        return Ok(p.clone());
486    }
487    let searched: Vec<String> = candidates
488        .iter()
489        .map(|p| format!("  {}", p.display()))
490        .collect();
491    Err(missing(format!(
492        "chrome-headless-shell is not installed; searched:\n{}",
493        searched.join("\n")
494    )))
495}
496
497/// Known Chrome for Testing install locations, in resolution order: the RightKit-managed
498/// `current` (then `current.previous`, then legacy per-version folders;
499/// `RIGHTKIT_CHROME_FOR_TESTING_ROOT` overrides the root), app installs, then
500/// Puppeteer's cache (`PUPPETEER_CACHE_DIR`), then Playwright's (`PLAYWRIGHT_BROWSERS_PATH`),
501/// newest version first within each cache.
502pub fn chrome_for_testing_candidates() -> Vec<PathBuf> {
503    let home = home_dir().unwrap_or_default();
504    let env_path = |k: &str| {
505        std::env::var_os(k)
506            .filter(|v| !v.is_empty())
507            .map(PathBuf::from)
508    };
509    let puppeteer = env_path("PUPPETEER_CACHE_DIR")
510        .unwrap_or_else(|| home.join(".cache").join("puppeteer"))
511        .join("chrome");
512    let managed_root = managed_chrome_for_testing_root(&home, &env_path);
513    let mut out = managed_chrome_for_testing_candidates(&managed_root);
514    if cfg!(target_os = "macos") {
515        out.push(Path::new("/Applications").join(MAC_CFT_APP));
516        out.push(home.join("Applications").join(MAC_CFT_APP));
517        let subs: [&str; 2] = if cfg!(target_arch = "aarch64") {
518            ["chrome-mac-arm64", "chrome-mac-x64"]
519        } else {
520            ["chrome-mac-x64", "chrome-mac-arm64"]
521        };
522        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
523            .unwrap_or_else(|| home.join("Library/Caches/ms-playwright"));
524        for dir in versioned_children(&puppeteer, &["mac_arm-", "mac-"])
525            .into_iter()
526            .chain(versioned_children(&playwright, &["chromium-"]))
527        {
528            for sub in subs {
529                out.push(dir.join(sub).join(MAC_CFT_APP));
530            }
531        }
532    } else if cfg!(target_os = "windows") {
533        let local = env_path("LOCALAPPDATA").unwrap_or_else(|| home.join(r"AppData\Local"));
534        for dir in versioned_children(&puppeteer, &["win64-", "win32-"]) {
535            out.push(dir.join("chrome-win64").join("chrome.exe"));
536            out.push(dir.join("chrome-win32").join("chrome.exe"));
537        }
538        let playwright =
539            env_path("PLAYWRIGHT_BROWSERS_PATH").unwrap_or_else(|| local.join("ms-playwright"));
540        for dir in versioned_children(&playwright, &["chromium-"]) {
541            out.push(dir.join("chrome-win64").join("chrome.exe"));
542        }
543    } else {
544        for dir in versioned_children(&puppeteer, &["linux-", "linux_arm-"]) {
545            out.push(dir.join("chrome-linux64").join("chrome"));
546            out.push(dir.join("chrome-linux-arm64").join("chrome"));
547        }
548        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
549            .unwrap_or_else(|| home.join(".cache").join("ms-playwright"));
550        for dir in versioned_children(&playwright, &["chromium-"]) {
551            out.push(dir.join("chrome-linux64").join("chrome"));
552        }
553    }
554    out
555}
556
557/// Resolve Chrome for Testing: `explicit`, then `RIGHTKIT_CHROME_FOR_TESTING`, then
558/// [`chrome_for_testing_candidates`]. Errors with install instructions; never returns
559/// regular Chrome.
560pub fn chrome_for_testing_path(explicit: Option<&Path>) -> Result<PathBuf> {
561    let missing = |what: String| {
562        BrowserError::ChromeForTestingNotFound(format!("{what}\n{CHROME_FOR_TESTING_INSTALL_HINT}"))
563    };
564    if let Some(p) = explicit {
565        return if p.exists() {
566            Ok(p.to_path_buf())
567        } else {
568            Err(missing(format!(
569                "explicit Chrome for Testing executable does not exist: {}",
570                p.display()
571            )))
572        };
573    }
574    if let Some(p) = std::env::var_os(CHROME_FOR_TESTING_ENV).filter(|v| !v.is_empty()) {
575        let p = PathBuf::from(p);
576        return if p.exists() {
577            Ok(p)
578        } else {
579            Err(missing(format!(
580                "{CHROME_FOR_TESTING_ENV} points at a missing file: {}",
581                p.display()
582            )))
583        };
584    }
585    let candidates = chrome_for_testing_candidates();
586    if let Some(p) = candidates.iter().find(|p| p.exists()) {
587        return Ok(p.clone());
588    }
589    let searched: Vec<String> = candidates
590        .iter()
591        .map(|p| format!("  {}", p.display()))
592        .collect();
593    Err(missing(format!(
594        "Chrome for Testing is not installed; searched:\n{}",
595        if searched.is_empty() {
596            "  (nothing)".to_string()
597        } else {
598            searched.join("\n")
599        }
600    )))
601}
602
603/// System-only selection takes priority; otherwise `chrome_path` as given, then Chrome
604/// for Testing, then (only with [`LaunchOptions::system_chrome`]) the system browser.
605pub(crate) fn resolve_executable(opts: &LaunchOptions) -> Result<PathBuf> {
606    resolve_executable_with(opts, || chrome_for_testing_path(None), find_chrome)
607}
608
609fn resolve_executable_with(
610    opts: &LaunchOptions,
611    cft: impl FnOnce() -> Result<PathBuf>,
612    system: impl FnOnce() -> Option<PathBuf>,
613) -> Result<PathBuf> {
614    if opts.use_system_chrome_only {
615        return system().ok_or(BrowserError::ChromeNotFound);
616    }
617    if let Some(p) = &opts.chrome_path {
618        return Ok(p.clone());
619    }
620    match cft() {
621        Ok(p) => Ok(p),
622        Err(e) if opts.allow_system_chrome => system().ok_or(e),
623        Err(e) => Err(e),
624    }
625}
626
627/// System Chrome, Chromium, then Edge. `CHROME` env overrides. Launch uses this only with
628/// [`LaunchOptions::system_chrome`] or [`LaunchOptions::system_chrome_only`];
629/// prefer [`chrome_for_testing_path`] for isolated automation.
630pub fn find_chrome() -> Option<PathBuf> {
631    if let Ok(p) = std::env::var("CHROME") {
632        let p = PathBuf::from(p);
633        if p.exists() {
634            return Some(p);
635        }
636    }
637    let candidates: &[&str] = if cfg!(target_os = "windows") {
638        &[
639            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
640            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
641            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
642            r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
643        ]
644    } else if cfg!(target_os = "macos") {
645        &[
646            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
647            "/Applications/Chromium.app/Contents/MacOS/Chromium",
648            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
649        ]
650    } else {
651        &[
652            "/usr/bin/google-chrome",
653            "/usr/bin/chromium",
654            "/usr/bin/chromium-browser",
655            "/usr/bin/microsoft-edge",
656        ]
657    };
658    candidates
659        .iter()
660        .map(PathBuf::from)
661        .find(|p| Path::new(p).exists())
662}
663
664/// Chrome flags a caller may not pass: they would redirect the profile to the
665/// user's real browser data or expose the debugging endpoint outside this session.
666pub(crate) fn validate_extra_args(args: &[String]) -> Result<()> {
667    const FORBIDDEN: &[&str] = &[
668        "user-data-dir",
669        "profile-directory",
670        "remote-debugging-port",
671        "remote-debugging-address",
672        "remote-debugging-pipe",
673        "remote-allow-origins",
674        "disable-web-security",
675        "incognito-bypass",
676    ];
677    for a in args {
678        let name = a.trim_start_matches('-').split('=').next().unwrap_or("");
679        if FORBIDDEN.contains(&name) {
680            return Err(BrowserError::Invalid(format!(
681                "chrome flag '--{name}' is managed by the session"
682            )));
683        }
684    }
685    Ok(())
686}
687
688/// Refuse roots that are (or sit inside) a real browser's own user-data directory.
689pub(crate) fn reject_real_browser_profile(root: &Path) -> Result<()> {
690    let mut real: Vec<PathBuf> = Vec::new();
691    if let Some(home) = std::env::var_os("HOME")
692        .or_else(|| std::env::var_os("USERPROFILE"))
693        .map(PathBuf::from)
694    {
695        for rel in [
696            "Library/Application Support/Google/Chrome",
697            "Library/Application Support/Chromium",
698            "Library/Application Support/Microsoft Edge",
699            ".config/google-chrome",
700            ".config/chromium",
701            ".config/microsoft-edge",
702        ] {
703            real.push(home.join(rel));
704        }
705    }
706    if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
707        for rel in [
708            r"Google\Chrome\User Data",
709            r"Chromium\User Data",
710            r"Microsoft\Edge\User Data",
711        ] {
712            real.push(local.join(rel));
713        }
714    }
715    std::fs::create_dir_all(root)?;
716    let root = root.canonicalize()?;
717    for r in real {
718        if let Ok(r) = r.canonicalize() {
719            if root.starts_with(&r) {
720                return Err(BrowserError::Profile(
721                    "refusing to use the user's real browser profile".into(),
722                ));
723            }
724        }
725    }
726    Ok(())
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732    use std::ffi::OsString;
733    use std::sync::{Mutex, MutexGuard};
734
735    // Serialize resolver tests that change process environment; restore even on panic.
736    static ENV_LOCK: Mutex<()> = Mutex::new(());
737
738    struct EnvGuard {
739        saved: Vec<(&'static str, Option<OsString>)>,
740        _lock: MutexGuard<'static, ()>,
741    }
742
743    impl EnvGuard {
744        fn new(values: &[(&'static str, Option<&Path>)]) -> Self {
745            let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
746            let saved = values
747                .iter()
748                .map(|(key, _)| (*key, std::env::var_os(key)))
749                .collect();
750            for (key, value) in values {
751                match value {
752                    Some(value) => std::env::set_var(key, value),
753                    None => std::env::remove_var(key),
754                }
755            }
756            Self { saved, _lock: lock }
757        }
758    }
759
760    impl Drop for EnvGuard {
761        fn drop(&mut self) {
762            for (key, value) in &self.saved {
763                match value {
764                    Some(value) => std::env::set_var(key, value),
765                    None => std::env::remove_var(key),
766                }
767            }
768        }
769    }
770
771    fn write_executable(path: &Path) {
772        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
773        std::fs::write(path, "fixture, not a browser").unwrap();
774    }
775
776    fn managed_executable(root: &Path, version: &str) -> PathBuf {
777        let relative = if cfg!(target_os = "macos") {
778            if cfg!(target_arch = "aarch64") {
779                "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
780            } else {
781                "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
782            }
783        } else if cfg!(target_os = "windows") {
784            "chrome-win64/chrome.exe"
785        } else {
786            "chrome-linux64/chrome"
787        };
788        root.join(version).join(relative)
789    }
790
791    #[test]
792    fn system_chrome_only_ignores_explicit_env_and_managed_cft() {
793        let temp = tempfile::tempdir().unwrap();
794        let root = temp.path().join("managed CfT");
795        let managed = managed_executable(&root, "130.10.0.0");
796        let explicit = temp.path().join("explicit CfT");
797        let system = temp.path().join("system Chrome");
798        for path in [&managed, &explicit, &system] {
799            write_executable(path);
800        }
801        let _env = EnvGuard::new(&[
802            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
803            (CHROME_FOR_TESTING_ENV, Some(&managed)),
804            ("CHROME", Some(&system)),
805        ]);
806        assert_eq!(chrome_for_testing_path(None).unwrap(), managed);
807        let opts = LaunchOptions {
808            chrome_path: Some(explicit),
809            ..LaunchOptions::default().system_chrome_only()
810        };
811        assert_eq!(resolve_executable(&opts).unwrap(), system);
812        assert_eq!(find_chrome().unwrap(), system);
813        // Also prove discovery is never called, regardless of installed CfT versions.
814        assert_eq!(
815            resolve_executable_with(
816                &opts,
817                || panic!("CfT discovery called"),
818                || Some(system.clone()),
819            )
820            .unwrap(),
821            system
822        );
823    }
824
825    #[cfg(windows)]
826    #[test]
827    fn headless_shell_candidates_are_the_sibling_then_managed_versions() {
828        let temp = tempfile::tempdir().unwrap();
829        let root = temp.path().join("root");
830        for v in ["154.0.1.1", "155.0.8059.39"] {
831            std::fs::create_dir_all(root.join(v)).unwrap();
832        }
833        let chrome = root.join("155.0.8059.39/chrome-win64/chrome.exe");
834        let got = chrome_headless_shell_candidates(&chrome, &root);
835        let shell = "chrome-headless-shell-win64/chrome-headless-shell.exe";
836        assert_eq!(
837            got,
838            vec![
839                root.join("155.0.8059.39").join(shell),
840                root.join("current").join(shell),
841                root.join("current.previous").join(shell),
842                root.join("155.0.8059.39").join(shell),
843                root.join("154.0.1.1").join(shell),
844            ]
845        );
846    }
847
848    #[test]
849    fn managed_layout_is_one_current_one_previous_and_a_staging_folder() {
850        let root = ManagedRoot::at("/managed");
851        assert_eq!(root.current(), Path::new("/managed/current"));
852        assert_eq!(root.previous(), Path::new("/managed/current.previous"));
853        assert_eq!(root.staging(), Path::new("/managed/current.staging"));
854        assert!(root.executable().starts_with("/managed/current"));
855    }
856
857    #[test]
858    fn current_beats_previous_and_legacy_versions_and_the_env_override_still_wins() {
859        let temp = tempfile::tempdir().unwrap();
860        let root = temp.path().join("managed");
861        let playwright = temp.path().join("ms-playwright");
862        std::fs::create_dir(&playwright).unwrap();
863        let managed = ManagedRoot::at(&root);
864        let current = managed.executable();
865        let previous = executable_in(&managed.previous());
866        let legacy = managed_executable(&root, "999.0.0.0");
867        for path in [&current, &previous, &legacy] {
868            write_executable(path);
869        }
870        let explicit = temp.path().join("explicit CfT");
871        write_executable(&explicit);
872        let _env = EnvGuard::new(&[
873            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
874            (CHROME_FOR_TESTING_ENV, None),
875            (
876                "PUPPETEER_CACHE_DIR",
877                Some(&temp.path().join("no puppeteer")),
878            ),
879            ("PLAYWRIGHT_BROWSERS_PATH", Some(&playwright)),
880        ]);
881        assert_eq!(
882            &chrome_for_testing_candidates()[..3],
883            &[current.clone(), previous.clone(), legacy]
884        );
885        assert_eq!(chrome_for_testing_path(None).unwrap(), current);
886        std::fs::remove_file(&current).unwrap();
887        assert_eq!(chrome_for_testing_path(None).unwrap(), previous);
888        std::env::set_var(CHROME_FOR_TESTING_ENV, &explicit);
889        assert_eq!(chrome_for_testing_path(None).unwrap(), explicit);
890        std::env::remove_var(CHROME_FOR_TESTING_ENV);
891        assert_eq!(chrome_for_testing_path(Some(&explicit)).unwrap(), explicit);
892    }
893
894    #[test]
895    fn install_hint_names_the_installer_api_not_pnpm_dlx() {
896        assert!(CHROME_FOR_TESTING_INSTALL_HINT.contains("ensure_chrome_for_testing"));
897        assert!(!CHROME_FOR_TESTING_INSTALL_HINT.contains("pnpm dlx"));
898    }
899
900    #[test]
901    fn system_chrome_only_errors_when_system_browser_is_missing() {
902        let opts = LaunchOptions::default().system_chrome_only();
903        let err =
904            resolve_executable_with(&opts, || panic!("CfT discovery called"), || None).unwrap_err();
905        assert!(matches!(&err, BrowserError::ChromeNotFound));
906        assert_eq!(
907            err.to_string(),
908            "no Chrome, Chromium, or Edge executable found"
909        );
910    }
911
912    #[test]
913    fn defaults_and_system_chrome_preserve_cft_preference_and_fallback() {
914        let temp = tempfile::tempdir().unwrap();
915        let cft = temp.path().join("CfT");
916        let system = temp.path().join("system Chrome");
917        write_executable(&cft);
918        write_executable(&system);
919        let defaults = LaunchOptions::default();
920        assert!(defaults.headless && defaults.mute_audio);
921        assert!(!defaults.allow_system_chrome && !defaults.use_system_chrome_only);
922        for opts in [defaults.clone(), defaults.clone().system_chrome()] {
923            assert_eq!(
924                resolve_executable_with(
925                    &opts,
926                    || Ok(cft.clone()),
927                    || panic!("system lookup called"),
928                )
929                .unwrap(),
930                cft
931            );
932        }
933        assert!(matches!(
934            resolve_executable_with(
935                &defaults,
936                || Err(BrowserError::ChromeForTestingNotFound("missing".into())),
937                || panic!("default must not fall back"),
938            ),
939            Err(BrowserError::ChromeForTestingNotFound(_))
940        ));
941        let fallback = defaults.system_chrome_only().system_chrome();
942        assert!(!fallback.use_system_chrome_only);
943        assert_eq!(
944            resolve_executable_with(
945                &fallback,
946                || Err(BrowserError::ChromeForTestingNotFound("missing".into())),
947                || Some(system.clone()),
948            )
949            .unwrap(),
950            system
951        );
952    }
953
954    #[test]
955    fn managed_root_uses_platform_data_directory_and_env_override() {
956        let temp = tempfile::tempdir().unwrap();
957        let home = temp.path();
958        let suffix = Path::new("Orthic Labs/shared/chrome-for-testing");
959        let default_data = if cfg!(target_os = "macos") {
960            home.join("Library/Application Support")
961        } else if cfg!(target_os = "windows") {
962            home.join("AppData/Local")
963        } else {
964            home.join(".local/share")
965        };
966        assert_eq!(
967            managed_chrome_for_testing_root(home, &|_| None),
968            default_data.join(suffix)
969        );
970        let data = home.join("custom app data");
971        let with_data = |key: &str| {
972            if key == "LOCALAPPDATA" || key == "XDG_DATA_HOME" {
973                Some(data.clone())
974            } else {
975                None
976            }
977        };
978        let expected_data = if cfg!(target_os = "macos") {
979            default_data
980        } else {
981            data.clone()
982        };
983        assert_eq!(
984            managed_chrome_for_testing_root(home, &with_data),
985            expected_data.join(suffix)
986        );
987        let override_root = home.join("custom managed root");
988        assert_eq!(
989            managed_chrome_for_testing_root(home, &|key| {
990                if key == CHROME_FOR_TESTING_ROOT_ENV {
991                    Some(override_root.clone())
992                } else {
993                    None
994                }
995            }),
996            override_root
997        );
998    }
999
1000    #[test]
1001    fn managed_folder_wins_with_newest_numeric_version_first() {
1002        let temp = tempfile::tempdir().unwrap();
1003        let root = temp.path().join("managed Chrome for Testing");
1004        let puppeteer = temp.path().join("puppeteer");
1005        // An empty stand-in, so discovery does not list the user's own Playwright folder.
1006        let playwright = temp.path().join("ms-playwright");
1007        std::fs::create_dir(&playwright).unwrap();
1008        let older = managed_executable(&root, "129.99.0.0");
1009        let recent = managed_executable(&root, "130.2.0.0");
1010        let newest = managed_executable(&root, "130.10.0.0");
1011        let legacy_dir = if cfg!(target_os = "macos") {
1012            "mac-999.0.0.0"
1013        } else if cfg!(target_os = "windows") {
1014            "win64-999.0.0.0"
1015        } else {
1016            "linux-999.0.0.0"
1017        };
1018        let legacy = managed_executable(&puppeteer.join("chrome"), legacy_dir);
1019        for path in [&older, &recent, &newest, &legacy] {
1020            write_executable(path);
1021        }
1022        std::fs::create_dir(root.join("999.staging")).unwrap();
1023        std::fs::write(root.join("999.0.0.0"), "not a version directory").unwrap();
1024        let _env = EnvGuard::new(&[
1025            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
1026            (CHROME_FOR_TESTING_ENV, None),
1027            ("PUPPETEER_CACHE_DIR", Some(&puppeteer)),
1028            ("PLAYWRIGHT_BROWSERS_PATH", Some(&playwright)),
1029        ]);
1030        let candidates = chrome_for_testing_candidates();
1031        // #267 layout: `current` and `current.previous` come first, then the legacy
1032        // per-version folders, newest numeric version first.
1033        let managed = ManagedRoot::at(&root);
1034        assert_eq!(
1035            &candidates[..2],
1036            &[
1037                executable_in(&managed.current()),
1038                executable_in(&managed.previous())
1039            ]
1040        );
1041        assert_eq!(&candidates[2..5], &[newest.clone(), recent.clone(), older]);
1042        assert!(candidates.iter().position(|p| p == &legacy).unwrap() >= 5);
1043        assert_eq!(chrome_for_testing_path(None).unwrap(), newest);
1044        std::env::set_var(CHROME_FOR_TESTING_ENV, &legacy);
1045        assert_eq!(chrome_for_testing_path(None).unwrap(), legacy);
1046        std::env::remove_var(CHROME_FOR_TESTING_ENV);
1047        std::fs::remove_file(&newest).unwrap();
1048        assert_eq!(chrome_for_testing_path(None).unwrap(), recent);
1049        // Explicit executable selection retains priority over managed discovery.
1050        assert_eq!(chrome_for_testing_path(Some(&legacy)).unwrap(), legacy);
1051    }
1052}