1use crate::error::{BrowserError, Result};
2use crate::policy::{AdmissionHook, EventSink, NetworkPolicy};
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6#[derive(Clone, Debug, Eq, PartialEq)]
8pub enum ProfileSpec {
9 Temporary,
11 Named { root: PathBuf, name: String },
14 Directory(PathBuf),
17 ImportedFrom {
22 root: PathBuf,
23 name: String,
24 import: crate::real_session::ImportSpec,
25 },
26 #[cfg(feature = "profile-vault")]
30 Encrypted(crate::vault::ProfileVault),
31}
32
33#[derive(Clone)]
34pub struct LaunchOptions {
35 pub headless: bool,
36 pub mute_audio: bool,
38 pub profile: ProfileSpec,
39 pub chrome_path: Option<PathBuf>,
42 pub allow_system_chrome: bool,
46 pub use_system_chrome_only: bool,
49 pub viewport: (u32, u32),
50 pub launch_timeout: Duration,
51 pub request_timeout: Duration,
54 pub extra_args: Vec<String>,
56 pub download_dir: Option<PathBuf>,
59 pub upload_root: Option<PathBuf>,
61 pub admission: Option<AdmissionHook>,
64 pub network: NetworkPolicy,
67 pub on_event: Option<EventSink>,
69 #[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 pub fn system_chrome(mut self) -> Self {
113 self.allow_system_chrome = true;
114 self.use_system_chrome_only = false;
115 self
116 }
117 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 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 #[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 pub fn headless(mut self, on: bool) -> Self {
172 self.headless = on;
173 self
174 }
175 pub fn visible(self) -> Self {
177 self.headless(false)
178 }
179 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 #[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 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
248pub const CHROME_FOR_TESTING_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING";
250
251pub const CHROME_FOR_TESTING_ROOT_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING_ROOT";
253
254pub const MANAGED_CURRENT_DIR: &str = "current";
256pub const MANAGED_PREVIOUS_DIR: &str = "current.previous";
258#[cfg_attr(not(feature = "install"), allow(dead_code))]
260pub const MANAGED_STAGING_DIR: &str = "current.staging";
261
262pub 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#[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 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 pub fn at(root: impl Into<PathBuf>) -> Self {
296 Self { root: root.into() }
297 }
298
299 pub fn path(&self) -> &Path {
301 &self.root
302 }
303
304 pub fn current(&self) -> PathBuf {
306 self.root.join(MANAGED_CURRENT_DIR)
307 }
308
309 pub fn previous(&self) -> PathBuf {
311 self.root.join(MANAGED_PREVIOUS_DIR)
312 }
313
314 pub fn staging(&self) -> PathBuf {
316 self.root.join(MANAGED_STAGING_DIR)
317 }
318
319 pub fn executable(&self) -> PathBuf {
321 executable_in(&self.current())
322 }
323}
324
325pub(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
340pub(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
367fn 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
398fn 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
418fn 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#[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#[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#[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
508pub 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
568pub 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
614pub(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
638pub 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
684pub(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
699pub(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-allow-origins",
709 "disable-web-security",
710 "incognito-bypass",
711 ];
712 for a in args {
713 let name = a.trim_start_matches('-').split('=').next().unwrap_or("");
714 if FORBIDDEN.contains(&name) {
715 return Err(BrowserError::Invalid(format!(
716 "chrome flag '--{name}' is managed by the session"
717 )));
718 }
719 }
720 Ok(())
721}
722
723pub(crate) fn reject_real_browser_profile(root: &Path) -> Result<()> {
725 let mut real: Vec<PathBuf> = Vec::new();
726 if let Some(home) = std::env::var_os("HOME")
727 .or_else(|| std::env::var_os("USERPROFILE"))
728 .map(PathBuf::from)
729 {
730 for rel in [
731 "Library/Application Support/Google/Chrome",
732 "Library/Application Support/Chromium",
733 "Library/Application Support/Microsoft Edge",
734 ".config/google-chrome",
735 ".config/chromium",
736 ".config/microsoft-edge",
737 ] {
738 real.push(home.join(rel));
739 }
740 }
741 if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
742 for rel in [
743 r"Google\Chrome\User Data",
744 r"Chromium\User Data",
745 r"Microsoft\Edge\User Data",
746 ] {
747 real.push(local.join(rel));
748 }
749 }
750 std::fs::create_dir_all(root)?;
751 let root = root.canonicalize()?;
752 for r in real {
753 if let Ok(r) = r.canonicalize() {
754 if root.starts_with(&r) {
755 return Err(BrowserError::Profile(
756 "refusing to use the user's real browser profile".into(),
757 ));
758 }
759 }
760 }
761 Ok(())
762}