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
248#[cfg(feature = "host-env")]
252pub const CHROME_FOR_TESTING_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING";
253
254#[cfg(feature = "host-env")]
257pub const CHROME_FOR_TESTING_ROOT_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING_ROOT";
258
259pub const MANAGED_CURRENT_DIR: &str = "current";
261pub const MANAGED_PREVIOUS_DIR: &str = "current.previous";
263#[cfg_attr(not(feature = "install"), allow(dead_code))]
265pub const MANAGED_STAGING_DIR: &str = "current.staging";
266
267#[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#[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#[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 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 pub fn at(root: impl Into<PathBuf>) -> Self {
312 Self { root: root.into() }
313 }
314
315 pub fn path(&self) -> &Path {
317 &self.root
318 }
319
320 pub fn current(&self) -> PathBuf {
322 self.root.join(MANAGED_CURRENT_DIR)
323 }
324
325 pub fn previous(&self) -> PathBuf {
327 self.root.join(MANAGED_PREVIOUS_DIR)
328 }
329
330 pub fn staging(&self) -> PathBuf {
332 self.root.join(MANAGED_STAGING_DIR)
333 }
334
335 pub fn executable(&self) -> PathBuf {
337 executable_in(&self.current())
338 }
339}
340
341pub(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
356pub(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
383fn 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#[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#[cfg(not(feature = "host-env"))]
405fn managed_root_override(_env_path: &impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
406 None
407}
408
409#[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#[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
448fn 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
468fn 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#[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#[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#[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
557pub 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
617pub 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
655pub(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
679pub 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
725pub(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
740pub(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
765pub(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}