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.
249pub const CHROME_FOR_TESTING_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING";
250
251/// Override the RightKit-managed Chrome for Testing root (the folder that holds `current`).
252pub const CHROME_FOR_TESTING_ROOT_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING_ROOT";
253
254/// Folder name of the one managed install inside the managed root.
255pub const MANAGED_CURRENT_DIR: &str = "current";
256/// Folder name of the single rollback copy kept beside [`MANAGED_CURRENT_DIR`].
257pub const MANAGED_PREVIOUS_DIR: &str = "current.previous";
258/// Folder name the installer extracts into before swapping it into `current`.
259#[cfg_attr(not(feature = "install"), allow(dead_code))]
260pub const MANAGED_STAGING_DIR: &str = "current.staging";
261
262/// How to get Chrome for Testing; part of [`BrowserError::ChromeForTestingNotFound`].
263pub const CHROME_FOR_TESTING_INSTALL_HINT: &str = "Chrome for Testing is put in place by the app's installer or updater step, which calls \
264rightkit_browser::install::ensure_chrome_for_testing (cargo feature `install`; pinned version, SHA-256 checked) \
265into <app data>/Orthic Labs/shared/chrome-for-testing/current. For development, point \
266RIGHTKIT_CHROME_FOR_TESTING at an existing Chrome for Testing executable, or run \
267`rightkit-qa-chrome install` from @rightkit/qa-chrome. Regular Google Chrome is used only with \
268LaunchOptions::system_chrome(): on macOS each killed instance leaks a code-sign clone.";
269
270/// The RightKit-managed Chrome for Testing folder and its fixed layout: one `current`
271/// install, one `current.previous` rollback copy, and `current.staging` while an install runs.
272/// No per-version folders and no new id: every app resolves the same path.
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct ManagedRoot {
275    root: PathBuf,
276}
277
278#[cfg_attr(not(feature = "install"), allow(dead_code))]
279impl ManagedRoot {
280    /// The suite-wide root (`<app data>/Orthic Labs/shared/chrome-for-testing`), or
281    /// `RIGHTKIT_CHROME_FOR_TESTING_ROOT` when set.
282    pub fn resolve() -> Self {
283        let home = home_dir().unwrap_or_default();
284        let env_path = |k: &str| {
285            std::env::var_os(k)
286                .filter(|v| !v.is_empty())
287                .map(PathBuf::from)
288        };
289        Self {
290            root: managed_chrome_for_testing_root(&home, &env_path),
291        }
292    }
293
294    /// An explicit root (tests, relocated installs).
295    pub fn at(root: impl Into<PathBuf>) -> Self {
296        Self { root: root.into() }
297    }
298
299    /// The root folder itself.
300    pub fn path(&self) -> &Path {
301        &self.root
302    }
303
304    /// `<root>/current`: the installed Chrome for Testing.
305    pub fn current(&self) -> PathBuf {
306        self.root.join(MANAGED_CURRENT_DIR)
307    }
308
309    /// `<root>/current.previous`: the one rollback copy.
310    pub fn previous(&self) -> PathBuf {
311        self.root.join(MANAGED_PREVIOUS_DIR)
312    }
313
314    /// `<root>/current.staging`: where an install extracts before it swaps into `current`.
315    pub fn staging(&self) -> PathBuf {
316        self.root.join(MANAGED_STAGING_DIR)
317    }
318
319    /// The Chrome executable inside `current` for this platform.
320    pub fn executable(&self) -> PathBuf {
321        executable_in(&self.current())
322    }
323}
324
325/// Chrome for Testing's platform key for this build, as Google names it.
326pub(crate) fn platform_key() -> &'static str {
327    if cfg!(target_os = "macos") {
328        if cfg!(target_arch = "aarch64") {
329            "mac-arm64"
330        } else {
331            "mac-x64"
332        }
333    } else if cfg!(target_os = "windows") {
334        "win64"
335    } else {
336        "linux64"
337    }
338}
339
340/// The Chrome executable inside one extracted Chrome for Testing folder, for this platform.
341pub(crate) fn executable_in(dir: &Path) -> PathBuf {
342    let sub = format!("chrome-{}", platform_key());
343    if cfg!(target_os = "macos") {
344        dir.join(sub).join(MAC_CFT_APP)
345    } else if cfg!(target_os = "windows") {
346        dir.join(sub).join("chrome.exe")
347    } else {
348        dir.join(sub).join("chrome")
349    }
350}
351
352const MAC_CFT_APP: &str = "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing";
353
354fn home_dir() -> Option<PathBuf> {
355    std::env::var_os("HOME")
356        .or_else(|| std::env::var_os("USERPROFILE"))
357        .map(PathBuf::from)
358}
359
360fn version_key(name: &str) -> Vec<u64> {
361    name.split(|c: char| !c.is_ascii_digit())
362        .filter(|p| !p.is_empty())
363        .filter_map(|p| p.parse().ok())
364        .collect()
365}
366
367/// Children of `root` whose names start with one of `prefixes`, newest version first.
368fn versioned_children(root: &Path, prefixes: &[&str]) -> Vec<PathBuf> {
369    let mut names: Vec<String> = std::fs::read_dir(root)
370        .map(|rd| {
371            rd.filter_map(|e| e.ok())
372                .map(|e| e.file_name().to_string_lossy().into_owned())
373                .filter(|n| prefixes.iter().any(|p| n.starts_with(p)))
374                .collect()
375        })
376        .unwrap_or_default();
377    names.sort_by(|a, b| version_key(b).cmp(&version_key(a)).then_with(|| b.cmp(a)));
378    names.into_iter().map(|n| root.join(n)).collect()
379}
380
381fn managed_chrome_for_testing_root(
382    home: &Path,
383    env_path: &impl Fn(&str) -> Option<PathBuf>,
384) -> PathBuf {
385    if let Some(root) = env_path(CHROME_FOR_TESTING_ROOT_ENV) {
386        return root;
387    }
388    let app_data = if cfg!(target_os = "macos") {
389        home.join("Library/Application Support")
390    } else if cfg!(target_os = "windows") {
391        env_path("LOCALAPPDATA").unwrap_or_else(|| home.join("AppData").join("Local"))
392    } else {
393        env_path("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"))
394    };
395    app_data.join("Orthic Labs/shared/chrome-for-testing")
396}
397
398/// Dotted numeric version folders of the managed root, newest first (qa-chrome's layout);
399/// staging/metadata entries are ignored.
400fn managed_version_dirs(root: &Path) -> Vec<PathBuf> {
401    versioned_children(root, &[""])
402        .into_iter()
403        .filter(|dir| {
404            dir.is_dir()
405                && dir
406                    .file_name()
407                    .and_then(|n| n.to_str())
408                    .is_some_and(|name| {
409                        name.contains('.')
410                            && name.split('.').all(|part| {
411                                !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())
412                            })
413                    })
414        })
415        .collect()
416}
417
418/// Managed candidates, best first: `current`, then `current.previous` (only reached when an
419/// interrupted swap left no `current`), then legacy per-version folders (qa-chrome before the
420/// fixed layout), newest first.
421fn managed_chrome_for_testing_candidates(root: &Path) -> Vec<PathBuf> {
422    let managed = ManagedRoot::at(root);
423    let mut out = vec![
424        executable_in(&managed.current()),
425        executable_in(&managed.previous()),
426    ];
427    out.extend(
428        managed_version_dirs(root)
429            .into_iter()
430            .map(|dir| executable_in(&dir)),
431    );
432    out
433}
434
435/// Windows fixture only: `chrome-headless-shell` of the same Chrome for Testing version, which
436/// never starts the crashpad handler (see [`chrome_headless_shell_path`]).
437#[cfg(windows)]
438pub(crate) const HEADLESS_SHELL_ENV: &str = "RIGHTKIT_CHROME_HEADLESS_SHELL";
439#[cfg(windows)]
440const HEADLESS_SHELL_WIN64: &str = "chrome-headless-shell-win64/chrome-headless-shell.exe";
441
442/// Candidate `chrome-headless-shell.exe` paths for the Windows fixture, in resolution order: the
443/// sibling of the resolved Chrome (`<version>/chrome-win64/chrome.exe` ->
444/// `<dir>/chrome-headless-shell-win64/`), then the managed `current` and `current.previous`, then
445/// each legacy managed version, newest first (`RIGHTKIT_CHROME_FOR_TESTING_ROOT` overrides the
446/// root, as for Chrome).
447#[cfg(windows)]
448fn chrome_headless_shell_candidates(chrome: &Path, managed_root: &Path) -> Vec<PathBuf> {
449    let managed = ManagedRoot::at(managed_root);
450    let mut out = Vec::new();
451    if let Some(version_dir) = chrome.parent().and_then(Path::parent) {
452        out.push(version_dir.join(HEADLESS_SHELL_WIN64));
453    }
454    out.push(managed.current().join(HEADLESS_SHELL_WIN64));
455    out.push(managed.previous().join(HEADLESS_SHELL_WIN64));
456    out.extend(
457        managed_version_dirs(managed_root)
458            .into_iter()
459            .map(|dir| dir.join(HEADLESS_SHELL_WIN64)),
460    );
461    out
462}
463
464/// Resolve `chrome-headless-shell.exe` for the Windows fixture: `RIGHTKIT_CHROME_HEADLESS_SHELL`
465/// (must exist), then [`chrome_headless_shell_candidates`]. Chrome's browser process starts the
466/// crashpad handler unconditionally, which cannot create its named pipe inside an AppContainer;
467/// the headless shell never starts it on Windows. Production launches never call this.
468#[cfg(windows)]
469pub(crate) fn chrome_headless_shell_path(chrome: &Path) -> Result<PathBuf> {
470    let missing = |what: String| {
471        BrowserError::ChromeForTestingNotFound(format!(
472            "{what}\nThe Windows fixture runs chrome-headless-shell from the same Chrome for Testing \
473             version (chrome-headless-shell-win64.zip, unpacked beside chrome-win64, or {HEADLESS_SHELL_ENV})"
474        ))
475    };
476    if let Some(p) = std::env::var_os(HEADLESS_SHELL_ENV).filter(|v| !v.is_empty()) {
477        let p = PathBuf::from(p);
478        return if p.exists() {
479            Ok(p)
480        } else {
481            Err(missing(format!(
482                "{HEADLESS_SHELL_ENV} points at a missing file: {}",
483                p.display()
484            )))
485        };
486    }
487    let home = home_dir().unwrap_or_default();
488    let env_path = |k: &str| {
489        std::env::var_os(k)
490            .filter(|v| !v.is_empty())
491            .map(PathBuf::from)
492    };
493    let root = managed_chrome_for_testing_root(&home, &env_path);
494    let candidates = chrome_headless_shell_candidates(chrome, &root);
495    if let Some(p) = candidates.iter().find(|p| p.exists()) {
496        return Ok(p.clone());
497    }
498    let searched: Vec<String> = candidates
499        .iter()
500        .map(|p| format!("  {}", p.display()))
501        .collect();
502    Err(missing(format!(
503        "chrome-headless-shell is not installed; searched:\n{}",
504        searched.join("\n")
505    )))
506}
507
508/// Known Chrome for Testing install locations, in resolution order: the RightKit-managed
509/// `current` (then `current.previous`, then legacy per-version folders;
510/// `RIGHTKIT_CHROME_FOR_TESTING_ROOT` overrides the root), app installs, then
511/// Puppeteer's cache (`PUPPETEER_CACHE_DIR`), then Playwright's (`PLAYWRIGHT_BROWSERS_PATH`),
512/// newest version first within each cache.
513pub fn chrome_for_testing_candidates() -> Vec<PathBuf> {
514    let home = home_dir().unwrap_or_default();
515    let env_path = |k: &str| {
516        std::env::var_os(k)
517            .filter(|v| !v.is_empty())
518            .map(PathBuf::from)
519    };
520    let puppeteer = env_path("PUPPETEER_CACHE_DIR")
521        .unwrap_or_else(|| home.join(".cache").join("puppeteer"))
522        .join("chrome");
523    let managed_root = managed_chrome_for_testing_root(&home, &env_path);
524    let mut out = managed_chrome_for_testing_candidates(&managed_root);
525    if cfg!(target_os = "macos") {
526        out.push(Path::new("/Applications").join(MAC_CFT_APP));
527        out.push(home.join("Applications").join(MAC_CFT_APP));
528        let subs: [&str; 2] = if cfg!(target_arch = "aarch64") {
529            ["chrome-mac-arm64", "chrome-mac-x64"]
530        } else {
531            ["chrome-mac-x64", "chrome-mac-arm64"]
532        };
533        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
534            .unwrap_or_else(|| home.join("Library/Caches/ms-playwright"));
535        for dir in versioned_children(&puppeteer, &["mac_arm-", "mac-"])
536            .into_iter()
537            .chain(versioned_children(&playwright, &["chromium-"]))
538        {
539            for sub in subs {
540                out.push(dir.join(sub).join(MAC_CFT_APP));
541            }
542        }
543    } else if cfg!(target_os = "windows") {
544        let local = env_path("LOCALAPPDATA").unwrap_or_else(|| home.join(r"AppData\Local"));
545        for dir in versioned_children(&puppeteer, &["win64-", "win32-"]) {
546            out.push(dir.join("chrome-win64").join("chrome.exe"));
547            out.push(dir.join("chrome-win32").join("chrome.exe"));
548        }
549        let playwright =
550            env_path("PLAYWRIGHT_BROWSERS_PATH").unwrap_or_else(|| local.join("ms-playwright"));
551        for dir in versioned_children(&playwright, &["chromium-"]) {
552            out.push(dir.join("chrome-win64").join("chrome.exe"));
553        }
554    } else {
555        for dir in versioned_children(&puppeteer, &["linux-", "linux_arm-"]) {
556            out.push(dir.join("chrome-linux64").join("chrome"));
557            out.push(dir.join("chrome-linux-arm64").join("chrome"));
558        }
559        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
560            .unwrap_or_else(|| home.join(".cache").join("ms-playwright"));
561        for dir in versioned_children(&playwright, &["chromium-"]) {
562            out.push(dir.join("chrome-linux64").join("chrome"));
563        }
564    }
565    out
566}
567
568/// Resolve Chrome for Testing: `explicit`, then `RIGHTKIT_CHROME_FOR_TESTING`, then
569/// [`chrome_for_testing_candidates`]. Errors with install instructions; never returns
570/// regular Chrome.
571pub fn chrome_for_testing_path(explicit: Option<&Path>) -> Result<PathBuf> {
572    let missing = |what: String| {
573        BrowserError::ChromeForTestingNotFound(format!("{what}\n{CHROME_FOR_TESTING_INSTALL_HINT}"))
574    };
575    if let Some(p) = explicit {
576        return if p.exists() {
577            Ok(p.to_path_buf())
578        } else {
579            Err(missing(format!(
580                "explicit Chrome for Testing executable does not exist: {}",
581                p.display()
582            )))
583        };
584    }
585    if let Some(p) = std::env::var_os(CHROME_FOR_TESTING_ENV).filter(|v| !v.is_empty()) {
586        let p = PathBuf::from(p);
587        return if p.exists() {
588            Ok(p)
589        } else {
590            Err(missing(format!(
591                "{CHROME_FOR_TESTING_ENV} points at a missing file: {}",
592                p.display()
593            )))
594        };
595    }
596    let candidates = chrome_for_testing_candidates();
597    if let Some(p) = candidates.iter().find(|p| p.exists()) {
598        return Ok(p.clone());
599    }
600    let searched: Vec<String> = candidates
601        .iter()
602        .map(|p| format!("  {}", p.display()))
603        .collect();
604    Err(missing(format!(
605        "Chrome for Testing is not installed; searched:\n{}",
606        if searched.is_empty() {
607            "  (nothing)".to_string()
608        } else {
609            searched.join("\n")
610        }
611    )))
612}
613
614/// System-only selection takes priority; otherwise `chrome_path` as given, then Chrome
615/// for Testing, then (only with [`LaunchOptions::system_chrome`]) the system browser.
616pub(crate) fn resolve_executable(opts: &LaunchOptions) -> Result<PathBuf> {
617    resolve_executable_with(opts, || chrome_for_testing_path(None), find_chrome)
618}
619
620fn resolve_executable_with(
621    opts: &LaunchOptions,
622    cft: impl FnOnce() -> Result<PathBuf>,
623    system: impl FnOnce() -> Option<PathBuf>,
624) -> Result<PathBuf> {
625    if opts.use_system_chrome_only {
626        return system().ok_or(BrowserError::ChromeNotFound);
627    }
628    if let Some(p) = &opts.chrome_path {
629        return Ok(p.clone());
630    }
631    match cft() {
632        Ok(p) => Ok(p),
633        Err(e) if opts.allow_system_chrome => system().ok_or(e),
634        Err(e) => Err(e),
635    }
636}
637
638/// System Chrome, Chromium, then Edge. `CHROME` env overrides. Launch uses this only with
639/// [`LaunchOptions::system_chrome`] or [`LaunchOptions::system_chrome_only`];
640/// prefer [`chrome_for_testing_path`] for isolated automation.
641pub fn find_chrome() -> Option<PathBuf> {
642    if let Ok(p) = std::env::var("CHROME") {
643        let p = PathBuf::from(p);
644        if p.exists() {
645            return Some(p);
646        }
647    }
648    let per_user: &[&str] = if cfg!(target_os = "windows") {
649        &[
650            r"Google\Chrome\Application\chrome.exe",
651            r"Microsoft\Edge\Application\msedge.exe",
652        ]
653    } else {
654        &[]
655    };
656    let candidates: &[&str] = if cfg!(target_os = "windows") {
657        &[
658            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
659            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
660            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
661            r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
662        ]
663    } else if cfg!(target_os = "macos") {
664        &[
665            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
666            "/Applications/Chromium.app/Contents/MacOS/Chromium",
667            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
668        ]
669    } else {
670        &[
671            "/usr/bin/google-chrome",
672            "/usr/bin/chromium",
673            "/usr/bin/chromium-browser",
674            "/usr/bin/microsoft-edge",
675        ]
676    };
677    candidates
678        .iter()
679        .map(PathBuf::from)
680        .chain(windows_local_app_candidates(per_user))
681        .find(|p| Path::new(p).exists())
682}
683
684/// Per-user Windows installs: each relative path under `%LOCALAPPDATA%`, in order. Empty when
685/// `LOCALAPPDATA` is unset, and on other platforms (no per-user install layout there).
686pub(crate) fn windows_local_app_candidates(relative: &[&str]) -> Vec<PathBuf> {
687    if !cfg!(windows) {
688        return Vec::new();
689    }
690    let Some(local) = std::env::var_os("LOCALAPPDATA")
691        .filter(|v| !v.is_empty())
692        .map(PathBuf::from)
693    else {
694        return Vec::new();
695    };
696    relative.iter().map(|rel| local.join(rel)).collect()
697}
698
699/// Chrome flags a caller may not pass: they would redirect the profile to the
700/// user's real browser data or expose the debugging endpoint outside this session.
701pub(crate) fn validate_extra_args(args: &[String]) -> Result<()> {
702    const FORBIDDEN: &[&str] = &[
703        "user-data-dir",
704        "profile-directory",
705        "remote-debugging-port",
706        "remote-debugging-address",
707        "remote-debugging-pipe",
708        "remote-debugging-io-pipes",
709        "remote-allow-origins",
710        "disable-web-security",
711        "incognito-bypass",
712    ];
713    for a in args {
714        let name = a.trim_start_matches('-').split('=').next().unwrap_or("");
715        if FORBIDDEN.contains(&name) {
716            return Err(BrowserError::Invalid(format!(
717                "chrome flag '--{name}' is managed by the session"
718            )));
719        }
720    }
721    Ok(())
722}
723
724/// Refuse roots that are (or sit inside) a real browser's own user-data directory.
725pub(crate) fn reject_real_browser_profile(root: &Path) -> Result<()> {
726    let mut real: Vec<PathBuf> = Vec::new();
727    if let Some(home) = std::env::var_os("HOME")
728        .or_else(|| std::env::var_os("USERPROFILE"))
729        .map(PathBuf::from)
730    {
731        for rel in [
732            "Library/Application Support/Google/Chrome",
733            "Library/Application Support/Chromium",
734            "Library/Application Support/Microsoft Edge",
735            ".config/google-chrome",
736            ".config/chromium",
737            ".config/microsoft-edge",
738        ] {
739            real.push(home.join(rel));
740        }
741    }
742    if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
743        for rel in [
744            r"Google\Chrome\User Data",
745            r"Chromium\User Data",
746            r"Microsoft\Edge\User Data",
747        ] {
748            real.push(local.join(rel));
749        }
750    }
751    std::fs::create_dir_all(root)?;
752    let root = root.canonicalize()?;
753    for r in real {
754        if let Ok(r) = r.canonicalize() {
755            if root.starts_with(&r) {
756                return Err(BrowserError::Profile(
757                    "refusing to use the user's real browser profile".into(),
758                ));
759            }
760        }
761    }
762    Ok(())
763}