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    /// Persistent profile kept as one authenticated-encrypted file at rest (feature
27    /// `profile-vault`): decrypted into a private working directory when the session starts,
28    /// re-sealed and wiped when it stops, recovered after a crash. See [`crate::ProfileVault`].
29    #[cfg(feature = "profile-vault")]
30    Encrypted(crate::vault::ProfileVault),
31}
32
33#[derive(Clone)]
34pub struct LaunchOptions {
35    pub headless: bool,
36    /// Passes `--mute-audio`. Default true.
37    pub mute_audio: bool,
38    pub profile: ProfileSpec,
39    /// Explicit browser executable. When `None`, launch resolves Chrome for Testing with
40    /// [`chrome_for_testing_path`]. Ignored by [`Self::system_chrome_only`].
41    pub chrome_path: Option<PathBuf>,
42    /// Opt-in: when Chrome for Testing is not installed, fall back to the system browser
43    /// ([`find_chrome`]). Off by default: regular Google Chrome on macOS leaves an APFS
44    /// code-sign clone of its bundle behind for every instance that does not shut down cleanly.
45    pub allow_system_chrome: bool,
46    /// Resolve only through [`find_chrome`], ignoring `chrome_path` and Chrome for
47    /// Testing discovery. Off by default; enabled by [`Self::system_chrome_only`].
48    pub use_system_chrome_only: bool,
49    pub viewport: (u32, u32),
50    pub launch_timeout: Duration,
51    /// Deadline for each CDP request, including `Page.navigate`. Default 30 s (chromiumoxide's).
52    /// Raise it for dev servers whose first load is slow (e.g. Vite's cold dependency optimizer).
53    pub request_timeout: Duration,
54    /// Extra Chrome flags, with or without leading `--`.
55    pub extra_args: Vec<String>,
56    /// Defaults to `<profile>/downloads` for temporary profiles and
57    /// `<profile>/rightkit-downloads` for persistent ones.
58    pub download_dir: Option<PathBuf>,
59    /// When set, `upload` refuses files outside this root.
60    pub upload_root: Option<PathBuf>,
61    /// Gates every navigation, input, and script action before it has any effect.
62    /// `None` admits everything (trusted callers).
63    pub admission: Option<AdmissionHook>,
64    /// Network/SSRF policy. Default blocks loopback, link-local, private ranges,
65    /// `localhost`, and `file:` unless allowed.
66    pub network: NetworkPolicy,
67    /// Receives start/stop/crash/denied lifecycle events (session id, reason, time).
68    pub on_event: Option<EventSink>,
69    /// Windows: the caller's job object (see [`Self::windows_job`]). Chromium and every
70    /// helper it starts are bound to it; a clone of these options keeps the duplicate open.
71    #[cfg(windows)]
72    pub windows_job: Option<std::sync::Arc<std::os::windows::io::OwnedHandle>>,
73}
74
75impl std::fmt::Debug for LaunchOptions {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.debug_struct("LaunchOptions")
78            .field("headless", &self.headless)
79            .field("profile", &self.profile)
80            .field("network", &self.network)
81            .field("admission", &self.admission.is_some())
82            .finish_non_exhaustive()
83    }
84}
85
86impl Default for LaunchOptions {
87    fn default() -> Self {
88        Self {
89            headless: true,
90            mute_audio: true,
91            profile: ProfileSpec::Temporary,
92            chrome_path: None,
93            allow_system_chrome: false,
94            use_system_chrome_only: false,
95            viewport: (1280, 800),
96            launch_timeout: Duration::from_secs(60),
97            request_timeout: Duration::from_secs(30),
98            extra_args: Vec::new(),
99            download_dir: None,
100            upload_root: None,
101            admission: None,
102            network: NetworkPolicy::default(),
103            on_event: None,
104            #[cfg(windows)]
105            windows_job: None,
106        }
107    }
108}
109
110impl LaunchOptions {
111    /// Opt in to the system Chrome/Chromium/Edge when Chrome for Testing is missing.
112    pub fn system_chrome(mut self) -> Self {
113        self.allow_system_chrome = true;
114        self.use_system_chrome_only = false;
115        self
116    }
117    /// Use only system Chrome/Chromium/Edge via [`find_chrome`]. Ignores explicit
118    /// `chrome_path` and Chrome for Testing installs/environment overrides; errors
119    /// with [`BrowserError::ChromeNotFound`] when no system browser is found.
120    pub fn system_chrome_only(mut self) -> Self {
121        self.use_system_chrome_only = true;
122        self.allow_system_chrome = false;
123        self
124    }
125    pub fn headed(mut self) -> Self {
126        self.headless = false;
127        self
128    }
129    pub fn admission(mut self, hook: AdmissionHook) -> Self {
130        self.admission = Some(hook);
131        self
132    }
133    /// Per-request CDP deadline (navigation included).
134    pub fn request_timeout(mut self, timeout: Duration) -> Self {
135        self.request_timeout = timeout;
136        self
137    }
138    pub fn network(mut self, policy: NetworkPolicy) -> Self {
139        self.network = policy;
140        self
141    }
142    pub fn on_event(
143        mut self,
144        f: impl Fn(&crate::policy::BrowserEvent) + Send + Sync + 'static,
145    ) -> Self {
146        self.on_event = Some(std::sync::Arc::new(f));
147        self
148    }
149    /// Windows: bind Chromium to the caller's job object (an in-process host's own job).
150    /// Chromium joins it before running its first instruction, beneath RightKit's own
151    /// kill-on-close jobs, none of which allow breakaway: terminating or closing the
152    /// caller's job kills the browser and all of its helpers. The handle is duplicated; the
153    /// session closes its duplicate as soon as Chromium has been bound.
154    #[cfg(windows)]
155    pub fn windows_job(
156        mut self,
157        job: std::os::windows::io::BorrowedHandle<'_>,
158    ) -> std::io::Result<Self> {
159        self.windows_job = Some(std::sync::Arc::new(job.try_clone_to_owned()?));
160        Ok(self)
161    }
162    pub fn named_profile(mut self, root: impl Into<PathBuf>, name: impl Into<String>) -> Self {
163        self.profile = ProfileSpec::Named {
164            root: root.into(),
165            name: name.into(),
166        };
167        self
168    }
169    /// Show the browser window (`false` is the default headless mode). The action API is the
170    /// same in both modes.
171    pub fn headless(mut self, on: bool) -> Self {
172        self.headless = on;
173        self
174    }
175    /// Same as `headless(false)`.
176    pub fn visible(self) -> Self {
177        self.headless(false)
178    }
179    /// Seed a named persistent profile from the user's own browser, with consent. Pair with
180    /// the same browser's executable ([`crate::browser_executable`]) so its sign-in encryption
181    /// key applies; [`crate::BrowserSession::attach_user_browser`] does both.
182    pub fn imported_profile(
183        mut self,
184        root: impl Into<PathBuf>,
185        name: impl Into<String>,
186        import: crate::real_session::ImportSpec,
187    ) -> Self {
188        self.profile = ProfileSpec::ImportedFrom {
189            root: root.into(),
190            name: name.into(),
191            import,
192        };
193        self
194    }
195    /// Use an encrypted persistent profile (feature `profile-vault`); see [`crate::ProfileVault`].
196    #[cfg(feature = "profile-vault")]
197    pub fn encrypted_profile(mut self, vault: crate::vault::ProfileVault) -> Self {
198        self.profile = ProfileSpec::Encrypted(vault);
199        self
200    }
201    /// Use an existing absolute Chrome user-data directory, including paths with
202    /// spaces or other filesystem-supported characters. Validated at launch; never
203    /// created or deleted. The caller owns exclusive access to this directory.
204    pub fn profile_dir(mut self, path: impl Into<PathBuf>) -> Self {
205        self.profile = ProfileSpec::Directory(path.into());
206        self
207    }
208}
209
210pub(crate) fn validate_profile_dir(path: &Path) -> Result<()> {
211    if !path.is_absolute() {
212        return Err(BrowserError::Profile(format!(
213            "profile directory must be absolute: {}",
214            path.display()
215        )));
216    }
217    let metadata = std::fs::metadata(path).map_err(|e| {
218        BrowserError::Profile(format!(
219            "profile directory must exist and be accessible: {} ({e})",
220            path.display()
221        ))
222    })?;
223    if !metadata.is_dir() {
224        return Err(BrowserError::Profile(format!(
225            "profile path is not a directory: {}",
226            path.display()
227        )));
228    }
229    Ok(())
230}
231
232pub(crate) fn validate_profile_name(name: &str) -> Result<()> {
233    let ok = !name.is_empty()
234        && name.len() <= 64
235        && !name.starts_with('.')
236        && name
237            .chars()
238            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
239    if ok {
240        Ok(())
241    } else {
242        Err(BrowserError::Profile(format!(
243            "invalid profile name '{name}'"
244        )))
245    }
246}
247
248/// Environment variable naming an explicit Chrome for Testing executable. Present, and read,
249/// only with the cargo feature `host-env`: a default build reads no environment variable that
250/// selects an executable (release-switch class S3).
251#[cfg(feature = "host-env")]
252pub const CHROME_FOR_TESTING_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING";
253
254/// Override the RightKit-managed Chrome for Testing root (the folder that holds `current`).
255/// Present, and read, only with the cargo feature `host-env`.
256#[cfg(feature = "host-env")]
257pub const CHROME_FOR_TESTING_ROOT_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING_ROOT";
258
259/// Folder name of the one managed install inside the managed root.
260pub const MANAGED_CURRENT_DIR: &str = "current";
261/// Folder name of the single rollback copy kept beside [`MANAGED_CURRENT_DIR`].
262pub const MANAGED_PREVIOUS_DIR: &str = "current.previous";
263/// Folder name the installer extracts into before swapping it into `current`.
264#[cfg_attr(not(feature = "install"), allow(dead_code))]
265pub const MANAGED_STAGING_DIR: &str = "current.staging";
266
267/// How to get Chrome for Testing; part of [`BrowserError::ChromeForTestingNotFound`]. The text
268/// names the environment override only in a build with the cargo feature `host-env`.
269#[cfg(not(feature = "host-env"))]
270pub const CHROME_FOR_TESTING_INSTALL_HINT: &str = "Chrome for Testing is put in place by the app's installer or updater step, which calls \
271rightkit_browser::install::ensure_chrome_for_testing (cargo feature `install`; pinned version, SHA-256 checked) \
272into <app data>/Orthic Labs/shared/chrome-for-testing/current. For development, run \
273`rightkit-qa-chrome install` from @rightkit/qa-chrome. Regular Google Chrome is used only with \
274LaunchOptions::system_chrome(): on macOS each killed instance leaks a code-sign clone.";
275
276/// How to get Chrome for Testing; part of [`BrowserError::ChromeForTestingNotFound`]. The text
277/// names the environment override only in a build with the cargo feature `host-env`.
278#[cfg(feature = "host-env")]
279pub const CHROME_FOR_TESTING_INSTALL_HINT: &str = "Chrome for Testing is put in place by the app's installer or updater step, which calls \
280rightkit_browser::install::ensure_chrome_for_testing (cargo feature `install`; pinned version, SHA-256 checked) \
281into <app data>/Orthic Labs/shared/chrome-for-testing/current. For development, point \
282RIGHTKIT_CHROME_FOR_TESTING at an existing Chrome for Testing executable, or run \
283`rightkit-qa-chrome install` from @rightkit/qa-chrome. Regular Google Chrome is used only with \
284LaunchOptions::system_chrome(): on macOS each killed instance leaks a code-sign clone.";
285
286/// The RightKit-managed Chrome for Testing folder and its fixed layout: one `current`
287/// install, one `current.previous` rollback copy, and `current.staging` while an install runs.
288/// No per-version folders and no new id: every app resolves the same path.
289#[derive(Debug, Clone, PartialEq, Eq)]
290pub struct ManagedRoot {
291    root: PathBuf,
292}
293
294#[cfg_attr(not(feature = "install"), allow(dead_code))]
295impl ManagedRoot {
296    /// The suite-wide root (`<app data>/Orthic Labs/shared/chrome-for-testing`); with the cargo
297    /// feature `host-env`, the folder named by the managed-root environment override when set.
298    pub fn resolve() -> Self {
299        let home = home_dir().unwrap_or_default();
300        let env_path = |k: &str| {
301            std::env::var_os(k)
302                .filter(|v| !v.is_empty())
303                .map(PathBuf::from)
304        };
305        Self {
306            root: managed_chrome_for_testing_root(&home, &env_path),
307        }
308    }
309
310    /// An explicit root (tests, relocated installs).
311    pub fn at(root: impl Into<PathBuf>) -> Self {
312        Self { root: root.into() }
313    }
314
315    /// The root folder itself.
316    pub fn path(&self) -> &Path {
317        &self.root
318    }
319
320    /// `<root>/current`: the installed Chrome for Testing.
321    pub fn current(&self) -> PathBuf {
322        self.root.join(MANAGED_CURRENT_DIR)
323    }
324
325    /// `<root>/current.previous`: the one rollback copy.
326    pub fn previous(&self) -> PathBuf {
327        self.root.join(MANAGED_PREVIOUS_DIR)
328    }
329
330    /// `<root>/current.staging`: where an install extracts before it swaps into `current`.
331    pub fn staging(&self) -> PathBuf {
332        self.root.join(MANAGED_STAGING_DIR)
333    }
334
335    /// The Chrome executable inside `current` for this platform.
336    pub fn executable(&self) -> PathBuf {
337        executable_in(&self.current())
338    }
339}
340
341/// Chrome for Testing's platform key for this build, as Google names it.
342pub(crate) fn platform_key() -> &'static str {
343    if cfg!(target_os = "macos") {
344        if cfg!(target_arch = "aarch64") {
345            "mac-arm64"
346        } else {
347            "mac-x64"
348        }
349    } else if cfg!(target_os = "windows") {
350        "win64"
351    } else {
352        "linux64"
353    }
354}
355
356/// The Chrome executable inside one extracted Chrome for Testing folder, for this platform.
357pub(crate) fn executable_in(dir: &Path) -> PathBuf {
358    let sub = format!("chrome-{}", platform_key());
359    if cfg!(target_os = "macos") {
360        dir.join(sub).join(MAC_CFT_APP)
361    } else if cfg!(target_os = "windows") {
362        dir.join(sub).join("chrome.exe")
363    } else {
364        dir.join(sub).join("chrome")
365    }
366}
367
368const MAC_CFT_APP: &str = "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing";
369
370fn home_dir() -> Option<PathBuf> {
371    std::env::var_os("HOME")
372        .or_else(|| std::env::var_os("USERPROFILE"))
373        .map(PathBuf::from)
374}
375
376fn version_key(name: &str) -> Vec<u64> {
377    name.split(|c: char| !c.is_ascii_digit())
378        .filter(|p| !p.is_empty())
379        .filter_map(|p| p.parse().ok())
380        .collect()
381}
382
383/// Children of `root` whose names start with one of `prefixes`, newest version first.
384fn versioned_children(root: &Path, prefixes: &[&str]) -> Vec<PathBuf> {
385    let mut names: Vec<String> = std::fs::read_dir(root)
386        .map(|rd| {
387            rd.filter_map(|e| e.ok())
388                .map(|e| e.file_name().to_string_lossy().into_owned())
389                .filter(|n| prefixes.iter().any(|p| n.starts_with(p)))
390                .collect()
391        })
392        .unwrap_or_default();
393    names.sort_by(|a, b| version_key(b).cmp(&version_key(a)).then_with(|| b.cmp(a)));
394    names.into_iter().map(|n| root.join(n)).collect()
395}
396
397/// The managed-root environment override. Compiled only with the cargo feature `host-env`.
398#[cfg(feature = "host-env")]
399fn managed_root_override(env_path: &impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
400    env_path(CHROME_FOR_TESTING_ROOT_ENV)
401}
402
403/// Without `host-env` the managed root is never taken from the environment.
404#[cfg(not(feature = "host-env"))]
405fn managed_root_override(_env_path: &impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
406    None
407}
408
409/// The Chrome for Testing executable named by the environment, `None` when unset. Compiled only
410/// with the cargo feature `host-env`.
411#[cfg(feature = "host-env")]
412fn executable_from_env(missing: &impl Fn(String) -> BrowserError) -> Option<Result<PathBuf>> {
413    let p = std::env::var_os(CHROME_FOR_TESTING_ENV).filter(|v| !v.is_empty())?;
414    let p = PathBuf::from(p);
415    Some(if p.exists() {
416        Ok(p)
417    } else {
418        Err(missing(format!(
419            "{CHROME_FOR_TESTING_ENV} points at a missing file: {}",
420            p.display()
421        )))
422    })
423}
424
425/// Without `host-env` no environment variable selects the executable.
426#[cfg(not(feature = "host-env"))]
427fn executable_from_env(_missing: &impl Fn(String) -> BrowserError) -> Option<Result<PathBuf>> {
428    None
429}
430
431fn managed_chrome_for_testing_root(
432    home: &Path,
433    env_path: &impl Fn(&str) -> Option<PathBuf>,
434) -> PathBuf {
435    if let Some(root) = managed_root_override(env_path) {
436        return root;
437    }
438    let app_data = if cfg!(target_os = "macos") {
439        home.join("Library/Application Support")
440    } else if cfg!(target_os = "windows") {
441        env_path("LOCALAPPDATA").unwrap_or_else(|| home.join("AppData").join("Local"))
442    } else {
443        env_path("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"))
444    };
445    app_data.join("Orthic Labs/shared/chrome-for-testing")
446}
447
448/// Dotted numeric version folders of the managed root, newest first (qa-chrome's layout);
449/// staging/metadata entries are ignored.
450fn managed_version_dirs(root: &Path) -> Vec<PathBuf> {
451    versioned_children(root, &[""])
452        .into_iter()
453        .filter(|dir| {
454            dir.is_dir()
455                && dir
456                    .file_name()
457                    .and_then(|n| n.to_str())
458                    .is_some_and(|name| {
459                        name.contains('.')
460                            && name.split('.').all(|part| {
461                                !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())
462                            })
463                    })
464        })
465        .collect()
466}
467
468/// Managed candidates, best first: `current`, then `current.previous` (only reached when an
469/// interrupted swap left no `current`), then legacy per-version folders (qa-chrome before the
470/// fixed layout), newest first.
471fn managed_chrome_for_testing_candidates(root: &Path) -> Vec<PathBuf> {
472    let managed = ManagedRoot::at(root);
473    let mut out = vec![
474        executable_in(&managed.current()),
475        executable_in(&managed.previous()),
476    ];
477    out.extend(
478        managed_version_dirs(root)
479            .into_iter()
480            .map(|dir| executable_in(&dir)),
481    );
482    out
483}
484
485/// Windows fixture only: `chrome-headless-shell` of the same Chrome for Testing version, which
486/// never starts the crashpad handler (see [`chrome_headless_shell_path`]).
487#[cfg(windows)]
488pub(crate) const HEADLESS_SHELL_ENV: &str = "RIGHTKIT_CHROME_HEADLESS_SHELL";
489#[cfg(windows)]
490const HEADLESS_SHELL_WIN64: &str = "chrome-headless-shell-win64/chrome-headless-shell.exe";
491
492/// Candidate `chrome-headless-shell.exe` paths for the Windows fixture, in resolution order: the
493/// sibling of the resolved Chrome (`<version>/chrome-win64/chrome.exe` ->
494/// `<dir>/chrome-headless-shell-win64/`), then the managed `current` and `current.previous`, then
495/// each legacy managed version, newest first (the managed root is the one Chrome uses).
496#[cfg(windows)]
497fn chrome_headless_shell_candidates(chrome: &Path, managed_root: &Path) -> Vec<PathBuf> {
498    let managed = ManagedRoot::at(managed_root);
499    let mut out = Vec::new();
500    if let Some(version_dir) = chrome.parent().and_then(Path::parent) {
501        out.push(version_dir.join(HEADLESS_SHELL_WIN64));
502    }
503    out.push(managed.current().join(HEADLESS_SHELL_WIN64));
504    out.push(managed.previous().join(HEADLESS_SHELL_WIN64));
505    out.extend(
506        managed_version_dirs(managed_root)
507            .into_iter()
508            .map(|dir| dir.join(HEADLESS_SHELL_WIN64)),
509    );
510    out
511}
512
513/// Resolve `chrome-headless-shell.exe` for the Windows fixture: `RIGHTKIT_CHROME_HEADLESS_SHELL`
514/// (must exist), then [`chrome_headless_shell_candidates`]. Chrome's browser process starts the
515/// crashpad handler unconditionally, which cannot create its named pipe inside an AppContainer;
516/// the headless shell never starts it on Windows. Production launches never call this.
517#[cfg(windows)]
518pub(crate) fn chrome_headless_shell_path(chrome: &Path) -> Result<PathBuf> {
519    let missing = |what: String| {
520        BrowserError::ChromeForTestingNotFound(format!(
521            "{what}\nThe Windows fixture runs chrome-headless-shell from the same Chrome for Testing \
522             version (chrome-headless-shell-win64.zip, unpacked beside chrome-win64, or {HEADLESS_SHELL_ENV})"
523        ))
524    };
525    if let Some(p) = std::env::var_os(HEADLESS_SHELL_ENV).filter(|v| !v.is_empty()) {
526        let p = PathBuf::from(p);
527        return if p.exists() {
528            Ok(p)
529        } else {
530            Err(missing(format!(
531                "{HEADLESS_SHELL_ENV} points at a missing file: {}",
532                p.display()
533            )))
534        };
535    }
536    let home = home_dir().unwrap_or_default();
537    let env_path = |k: &str| {
538        std::env::var_os(k)
539            .filter(|v| !v.is_empty())
540            .map(PathBuf::from)
541    };
542    let root = managed_chrome_for_testing_root(&home, &env_path);
543    let candidates = chrome_headless_shell_candidates(chrome, &root);
544    if let Some(p) = candidates.iter().find(|p| p.exists()) {
545        return Ok(p.clone());
546    }
547    let searched: Vec<String> = candidates
548        .iter()
549        .map(|p| format!("  {}", p.display()))
550        .collect();
551    Err(missing(format!(
552        "chrome-headless-shell is not installed; searched:\n{}",
553        searched.join("\n")
554    )))
555}
556
557/// Known Chrome for Testing install locations, in resolution order: the RightKit-managed
558/// `current` (then `current.previous`, then legacy per-version folders; the cargo feature
559/// `host-env` lets the environment override the root), app installs, then
560/// Puppeteer's cache (`PUPPETEER_CACHE_DIR`), then Playwright's (`PLAYWRIGHT_BROWSERS_PATH`),
561/// newest version first within each cache.
562pub fn chrome_for_testing_candidates() -> Vec<PathBuf> {
563    let home = home_dir().unwrap_or_default();
564    let env_path = |k: &str| {
565        std::env::var_os(k)
566            .filter(|v| !v.is_empty())
567            .map(PathBuf::from)
568    };
569    let puppeteer = env_path("PUPPETEER_CACHE_DIR")
570        .unwrap_or_else(|| home.join(".cache").join("puppeteer"))
571        .join("chrome");
572    let managed_root = managed_chrome_for_testing_root(&home, &env_path);
573    let mut out = managed_chrome_for_testing_candidates(&managed_root);
574    if cfg!(target_os = "macos") {
575        out.push(Path::new("/Applications").join(MAC_CFT_APP));
576        out.push(home.join("Applications").join(MAC_CFT_APP));
577        let subs: [&str; 2] = if cfg!(target_arch = "aarch64") {
578            ["chrome-mac-arm64", "chrome-mac-x64"]
579        } else {
580            ["chrome-mac-x64", "chrome-mac-arm64"]
581        };
582        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
583            .unwrap_or_else(|| home.join("Library/Caches/ms-playwright"));
584        for dir in versioned_children(&puppeteer, &["mac_arm-", "mac-"])
585            .into_iter()
586            .chain(versioned_children(&playwright, &["chromium-"]))
587        {
588            for sub in subs {
589                out.push(dir.join(sub).join(MAC_CFT_APP));
590            }
591        }
592    } else if cfg!(target_os = "windows") {
593        let local = env_path("LOCALAPPDATA").unwrap_or_else(|| home.join(r"AppData\Local"));
594        for dir in versioned_children(&puppeteer, &["win64-", "win32-"]) {
595            out.push(dir.join("chrome-win64").join("chrome.exe"));
596            out.push(dir.join("chrome-win32").join("chrome.exe"));
597        }
598        let playwright =
599            env_path("PLAYWRIGHT_BROWSERS_PATH").unwrap_or_else(|| local.join("ms-playwright"));
600        for dir in versioned_children(&playwright, &["chromium-"]) {
601            out.push(dir.join("chrome-win64").join("chrome.exe"));
602        }
603    } else {
604        for dir in versioned_children(&puppeteer, &["linux-", "linux_arm-"]) {
605            out.push(dir.join("chrome-linux64").join("chrome"));
606            out.push(dir.join("chrome-linux-arm64").join("chrome"));
607        }
608        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
609            .unwrap_or_else(|| home.join(".cache").join("ms-playwright"));
610        for dir in versioned_children(&playwright, &["chromium-"]) {
611            out.push(dir.join("chrome-linux64").join("chrome"));
612        }
613    }
614    out
615}
616
617/// Resolve Chrome for Testing: `explicit`, then (only with the cargo feature `host-env`) the
618/// executable named by the environment, then [`chrome_for_testing_candidates`]. Errors with
619/// install instructions; never returns regular Chrome.
620pub fn chrome_for_testing_path(explicit: Option<&Path>) -> Result<PathBuf> {
621    let missing = |what: String| {
622        BrowserError::ChromeForTestingNotFound(format!("{what}\n{CHROME_FOR_TESTING_INSTALL_HINT}"))
623    };
624    if let Some(p) = explicit {
625        return if p.exists() {
626            Ok(p.to_path_buf())
627        } else {
628            Err(missing(format!(
629                "explicit Chrome for Testing executable does not exist: {}",
630                p.display()
631            )))
632        };
633    }
634    if let Some(found) = executable_from_env(&missing) {
635        return found;
636    }
637    let candidates = chrome_for_testing_candidates();
638    if let Some(p) = candidates.iter().find(|p| p.exists()) {
639        return Ok(p.clone());
640    }
641    let searched: Vec<String> = candidates
642        .iter()
643        .map(|p| format!("  {}", p.display()))
644        .collect();
645    Err(missing(format!(
646        "Chrome for Testing is not installed; searched:\n{}",
647        if searched.is_empty() {
648            "  (nothing)".to_string()
649        } else {
650            searched.join("\n")
651        }
652    )))
653}
654
655/// System-only selection takes priority; otherwise `chrome_path` as given, then Chrome
656/// for Testing, then (only with [`LaunchOptions::system_chrome`]) the system browser.
657pub(crate) fn resolve_executable(opts: &LaunchOptions) -> Result<PathBuf> {
658    resolve_executable_with(opts, || chrome_for_testing_path(None), find_chrome)
659}
660
661fn resolve_executable_with(
662    opts: &LaunchOptions,
663    cft: impl FnOnce() -> Result<PathBuf>,
664    system: impl FnOnce() -> Option<PathBuf>,
665) -> Result<PathBuf> {
666    if opts.use_system_chrome_only {
667        return system().ok_or(BrowserError::ChromeNotFound);
668    }
669    if let Some(p) = &opts.chrome_path {
670        return Ok(p.clone());
671    }
672    match cft() {
673        Ok(p) => Ok(p),
674        Err(e) if opts.allow_system_chrome => system().ok_or(e),
675        Err(e) => Err(e),
676    }
677}
678
679/// System Chrome, Chromium, then Edge. `CHROME` env overrides. Launch uses this only with
680/// [`LaunchOptions::system_chrome`] or [`LaunchOptions::system_chrome_only`];
681/// prefer [`chrome_for_testing_path`] for isolated automation.
682pub fn find_chrome() -> Option<PathBuf> {
683    if let Ok(p) = std::env::var("CHROME") {
684        let p = PathBuf::from(p);
685        if p.exists() {
686            return Some(p);
687        }
688    }
689    let per_user: &[&str] = if cfg!(target_os = "windows") {
690        &[
691            r"Google\Chrome\Application\chrome.exe",
692            r"Microsoft\Edge\Application\msedge.exe",
693        ]
694    } else {
695        &[]
696    };
697    let candidates: &[&str] = if cfg!(target_os = "windows") {
698        &[
699            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
700            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
701            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
702            r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
703        ]
704    } else if cfg!(target_os = "macos") {
705        &[
706            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
707            "/Applications/Chromium.app/Contents/MacOS/Chromium",
708            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
709        ]
710    } else {
711        &[
712            "/usr/bin/google-chrome",
713            "/usr/bin/chromium",
714            "/usr/bin/chromium-browser",
715            "/usr/bin/microsoft-edge",
716        ]
717    };
718    candidates
719        .iter()
720        .map(PathBuf::from)
721        .chain(windows_local_app_candidates(per_user))
722        .find(|p| Path::new(p).exists())
723}
724
725/// Per-user Windows installs: each relative path under `%LOCALAPPDATA%`, in order. Empty when
726/// `LOCALAPPDATA` is unset, and on other platforms (no per-user install layout there).
727pub(crate) fn windows_local_app_candidates(relative: &[&str]) -> Vec<PathBuf> {
728    if !cfg!(windows) {
729        return Vec::new();
730    }
731    let Some(local) = std::env::var_os("LOCALAPPDATA")
732        .filter(|v| !v.is_empty())
733        .map(PathBuf::from)
734    else {
735        return Vec::new();
736    };
737    relative.iter().map(|rel| local.join(rel)).collect()
738}
739
740/// Chrome flags a caller may not pass: they would redirect the profile to the
741/// user's real browser data or expose the debugging endpoint outside this session.
742pub(crate) fn validate_extra_args(args: &[String]) -> Result<()> {
743    const FORBIDDEN: &[&str] = &[
744        "user-data-dir",
745        "profile-directory",
746        "remote-debugging-port",
747        "remote-debugging-address",
748        "remote-debugging-pipe",
749        "remote-debugging-io-pipes",
750        "remote-allow-origins",
751        "disable-web-security",
752        "incognito-bypass",
753    ];
754    for a in args {
755        let name = a.trim_start_matches('-').split('=').next().unwrap_or("");
756        if FORBIDDEN.contains(&name) {
757            return Err(BrowserError::Invalid(format!(
758                "chrome flag '--{name}' is managed by the session"
759            )));
760        }
761    }
762    Ok(())
763}
764
765/// Refuse roots that are (or sit inside) a real browser's own user-data directory.
766pub(crate) fn reject_real_browser_profile(root: &Path) -> Result<()> {
767    let mut real: Vec<PathBuf> = Vec::new();
768    if let Some(home) = std::env::var_os("HOME")
769        .or_else(|| std::env::var_os("USERPROFILE"))
770        .map(PathBuf::from)
771    {
772        for rel in [
773            "Library/Application Support/Google/Chrome",
774            "Library/Application Support/Chromium",
775            "Library/Application Support/Microsoft Edge",
776            ".config/google-chrome",
777            ".config/chromium",
778            ".config/microsoft-edge",
779        ] {
780            real.push(home.join(rel));
781        }
782    }
783    if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
784        for rel in [
785            r"Google\Chrome\User Data",
786            r"Chromium\User Data",
787            r"Microsoft\Edge\User Data",
788        ] {
789            real.push(local.join(rel));
790        }
791    }
792    std::fs::create_dir_all(root)?;
793    let root = root.canonicalize()?;
794    for r in real {
795        if let Ok(r) = r.canonicalize() {
796            if root.starts_with(&r) {
797                return Err(BrowserError::Profile(
798                    "refusing to use the user's real browser profile".into(),
799                ));
800            }
801        }
802    }
803    Ok(())
804}