use crate::error::{BrowserError, Result};
use crate::policy::{AdmissionHook, EventSink, NetworkPolicy};
use std::path::{Path, PathBuf};
use std::time::Duration;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProfileSpec {
Temporary,
Named { root: PathBuf, name: String },
Directory(PathBuf),
ImportedFrom {
root: PathBuf,
name: String,
import: crate::real_session::ImportSpec,
},
#[cfg(feature = "profile-vault")]
Encrypted(crate::vault::ProfileVault),
}
#[derive(Clone)]
pub struct LaunchOptions {
pub headless: bool,
pub mute_audio: bool,
pub profile: ProfileSpec,
pub chrome_path: Option<PathBuf>,
pub allow_system_chrome: bool,
pub use_system_chrome_only: bool,
pub viewport: (u32, u32),
pub launch_timeout: Duration,
pub request_timeout: Duration,
pub extra_args: Vec<String>,
pub download_dir: Option<PathBuf>,
pub upload_root: Option<PathBuf>,
pub admission: Option<AdmissionHook>,
pub network: NetworkPolicy,
pub on_event: Option<EventSink>,
#[cfg(windows)]
pub windows_job: Option<std::sync::Arc<std::os::windows::io::OwnedHandle>>,
}
impl std::fmt::Debug for LaunchOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LaunchOptions")
.field("headless", &self.headless)
.field("profile", &self.profile)
.field("network", &self.network)
.field("admission", &self.admission.is_some())
.finish_non_exhaustive()
}
}
impl Default for LaunchOptions {
fn default() -> Self {
Self {
headless: true,
mute_audio: true,
profile: ProfileSpec::Temporary,
chrome_path: None,
allow_system_chrome: false,
use_system_chrome_only: false,
viewport: (1280, 800),
launch_timeout: Duration::from_secs(60),
request_timeout: Duration::from_secs(30),
extra_args: Vec::new(),
download_dir: None,
upload_root: None,
admission: None,
network: NetworkPolicy::default(),
on_event: None,
#[cfg(windows)]
windows_job: None,
}
}
}
impl LaunchOptions {
pub fn system_chrome(mut self) -> Self {
self.allow_system_chrome = true;
self.use_system_chrome_only = false;
self
}
pub fn system_chrome_only(mut self) -> Self {
self.use_system_chrome_only = true;
self.allow_system_chrome = false;
self
}
pub fn headed(mut self) -> Self {
self.headless = false;
self
}
pub fn admission(mut self, hook: AdmissionHook) -> Self {
self.admission = Some(hook);
self
}
pub fn request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = timeout;
self
}
pub fn network(mut self, policy: NetworkPolicy) -> Self {
self.network = policy;
self
}
pub fn on_event(
mut self,
f: impl Fn(&crate::policy::BrowserEvent) + Send + Sync + 'static,
) -> Self {
self.on_event = Some(std::sync::Arc::new(f));
self
}
#[cfg(windows)]
pub fn windows_job(
mut self,
job: std::os::windows::io::BorrowedHandle<'_>,
) -> std::io::Result<Self> {
self.windows_job = Some(std::sync::Arc::new(job.try_clone_to_owned()?));
Ok(self)
}
pub fn named_profile(mut self, root: impl Into<PathBuf>, name: impl Into<String>) -> Self {
self.profile = ProfileSpec::Named {
root: root.into(),
name: name.into(),
};
self
}
pub fn headless(mut self, on: bool) -> Self {
self.headless = on;
self
}
pub fn visible(self) -> Self {
self.headless(false)
}
pub fn imported_profile(
mut self,
root: impl Into<PathBuf>,
name: impl Into<String>,
import: crate::real_session::ImportSpec,
) -> Self {
self.profile = ProfileSpec::ImportedFrom {
root: root.into(),
name: name.into(),
import,
};
self
}
#[cfg(feature = "profile-vault")]
pub fn encrypted_profile(mut self, vault: crate::vault::ProfileVault) -> Self {
self.profile = ProfileSpec::Encrypted(vault);
self
}
pub fn profile_dir(mut self, path: impl Into<PathBuf>) -> Self {
self.profile = ProfileSpec::Directory(path.into());
self
}
}
pub(crate) fn validate_profile_dir(path: &Path) -> Result<()> {
if !path.is_absolute() {
return Err(BrowserError::Profile(format!(
"profile directory must be absolute: {}",
path.display()
)));
}
let metadata = std::fs::metadata(path).map_err(|e| {
BrowserError::Profile(format!(
"profile directory must exist and be accessible: {} ({e})",
path.display()
))
})?;
if !metadata.is_dir() {
return Err(BrowserError::Profile(format!(
"profile path is not a directory: {}",
path.display()
)));
}
Ok(())
}
pub(crate) fn validate_profile_name(name: &str) -> Result<()> {
let ok = !name.is_empty()
&& name.len() <= 64
&& !name.starts_with('.')
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
if ok {
Ok(())
} else {
Err(BrowserError::Profile(format!(
"invalid profile name '{name}'"
)))
}
}
#[cfg(feature = "host-env")]
pub const CHROME_FOR_TESTING_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING";
#[cfg(feature = "host-env")]
pub const CHROME_FOR_TESTING_ROOT_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING_ROOT";
pub const MANAGED_CURRENT_DIR: &str = "current";
pub const MANAGED_PREVIOUS_DIR: &str = "current.previous";
#[cfg_attr(not(feature = "install"), allow(dead_code))]
pub const MANAGED_STAGING_DIR: &str = "current.staging";
#[cfg(not(feature = "host-env"))]
pub const CHROME_FOR_TESTING_INSTALL_HINT: &str = "Chrome for Testing is put in place by the app's installer or updater step, which calls \
rightkit_browser::install::ensure_chrome_for_testing (cargo feature `install`; pinned version, SHA-256 checked) \
into <app data>/Orthic Labs/shared/chrome-for-testing/current. For development, run \
`rightkit-qa-chrome install` from @rightkit/qa-chrome. Regular Google Chrome is used only with \
LaunchOptions::system_chrome(): on macOS each killed instance leaks a code-sign clone.";
#[cfg(feature = "host-env")]
pub const CHROME_FOR_TESTING_INSTALL_HINT: &str = "Chrome for Testing is put in place by the app's installer or updater step, which calls \
rightkit_browser::install::ensure_chrome_for_testing (cargo feature `install`; pinned version, SHA-256 checked) \
into <app data>/Orthic Labs/shared/chrome-for-testing/current. For development, point \
RIGHTKIT_CHROME_FOR_TESTING at an existing Chrome for Testing executable, or run \
`rightkit-qa-chrome install` from @rightkit/qa-chrome. Regular Google Chrome is used only with \
LaunchOptions::system_chrome(): on macOS each killed instance leaks a code-sign clone.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManagedRoot {
root: PathBuf,
}
#[cfg_attr(not(feature = "install"), allow(dead_code))]
impl ManagedRoot {
pub fn resolve() -> Self {
let home = home_dir().unwrap_or_default();
let env_path = |k: &str| {
std::env::var_os(k)
.filter(|v| !v.is_empty())
.map(PathBuf::from)
};
Self {
root: managed_chrome_for_testing_root(&home, &env_path),
}
}
pub fn at(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
pub fn path(&self) -> &Path {
&self.root
}
pub fn current(&self) -> PathBuf {
self.root.join(MANAGED_CURRENT_DIR)
}
pub fn previous(&self) -> PathBuf {
self.root.join(MANAGED_PREVIOUS_DIR)
}
pub fn staging(&self) -> PathBuf {
self.root.join(MANAGED_STAGING_DIR)
}
pub fn executable(&self) -> PathBuf {
executable_in(&self.current())
}
}
pub(crate) fn platform_key() -> &'static str {
if cfg!(target_os = "macos") {
if cfg!(target_arch = "aarch64") {
"mac-arm64"
} else {
"mac-x64"
}
} else if cfg!(target_os = "windows") {
"win64"
} else {
"linux64"
}
}
pub(crate) fn executable_in(dir: &Path) -> PathBuf {
let sub = format!("chrome-{}", platform_key());
if cfg!(target_os = "macos") {
dir.join(sub).join(MAC_CFT_APP)
} else if cfg!(target_os = "windows") {
dir.join(sub).join("chrome.exe")
} else {
dir.join(sub).join("chrome")
}
}
const MAC_CFT_APP: &str = "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing";
fn home_dir() -> Option<PathBuf> {
std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(PathBuf::from)
}
fn version_key(name: &str) -> Vec<u64> {
name.split(|c: char| !c.is_ascii_digit())
.filter(|p| !p.is_empty())
.filter_map(|p| p.parse().ok())
.collect()
}
fn versioned_children(root: &Path, prefixes: &[&str]) -> Vec<PathBuf> {
let mut names: Vec<String> = std::fs::read_dir(root)
.map(|rd| {
rd.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| prefixes.iter().any(|p| n.starts_with(p)))
.collect()
})
.unwrap_or_default();
names.sort_by(|a, b| version_key(b).cmp(&version_key(a)).then_with(|| b.cmp(a)));
names.into_iter().map(|n| root.join(n)).collect()
}
#[cfg(feature = "host-env")]
fn managed_root_override(env_path: &impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
env_path(CHROME_FOR_TESTING_ROOT_ENV)
}
#[cfg(not(feature = "host-env"))]
fn managed_root_override(_env_path: &impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
None
}
#[cfg(feature = "host-env")]
fn executable_from_env(missing: &impl Fn(String) -> BrowserError) -> Option<Result<PathBuf>> {
let p = std::env::var_os(CHROME_FOR_TESTING_ENV).filter(|v| !v.is_empty())?;
let p = PathBuf::from(p);
Some(if p.exists() {
Ok(p)
} else {
Err(missing(format!(
"{CHROME_FOR_TESTING_ENV} points at a missing file: {}",
p.display()
)))
})
}
#[cfg(not(feature = "host-env"))]
fn executable_from_env(_missing: &impl Fn(String) -> BrowserError) -> Option<Result<PathBuf>> {
None
}
fn managed_chrome_for_testing_root(
home: &Path,
env_path: &impl Fn(&str) -> Option<PathBuf>,
) -> PathBuf {
if let Some(root) = managed_root_override(env_path) {
return root;
}
let app_data = if cfg!(target_os = "macos") {
home.join("Library/Application Support")
} else if cfg!(target_os = "windows") {
env_path("LOCALAPPDATA").unwrap_or_else(|| home.join("AppData").join("Local"))
} else {
env_path("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"))
};
app_data.join("Orthic Labs/shared/chrome-for-testing")
}
fn managed_version_dirs(root: &Path) -> Vec<PathBuf> {
versioned_children(root, &[""])
.into_iter()
.filter(|dir| {
dir.is_dir()
&& dir
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|name| {
name.contains('.')
&& name.split('.').all(|part| {
!part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())
})
})
})
.collect()
}
fn managed_chrome_for_testing_candidates(root: &Path) -> Vec<PathBuf> {
let managed = ManagedRoot::at(root);
let mut out = vec![
executable_in(&managed.current()),
executable_in(&managed.previous()),
];
out.extend(
managed_version_dirs(root)
.into_iter()
.map(|dir| executable_in(&dir)),
);
out
}
#[cfg(windows)]
pub(crate) const HEADLESS_SHELL_ENV: &str = "RIGHTKIT_CHROME_HEADLESS_SHELL";
#[cfg(windows)]
const HEADLESS_SHELL_WIN64: &str = "chrome-headless-shell-win64/chrome-headless-shell.exe";
#[cfg(windows)]
fn chrome_headless_shell_candidates(chrome: &Path, managed_root: &Path) -> Vec<PathBuf> {
let managed = ManagedRoot::at(managed_root);
let mut out = Vec::new();
if let Some(version_dir) = chrome.parent().and_then(Path::parent) {
out.push(version_dir.join(HEADLESS_SHELL_WIN64));
}
out.push(managed.current().join(HEADLESS_SHELL_WIN64));
out.push(managed.previous().join(HEADLESS_SHELL_WIN64));
out.extend(
managed_version_dirs(managed_root)
.into_iter()
.map(|dir| dir.join(HEADLESS_SHELL_WIN64)),
);
out
}
#[cfg(windows)]
pub(crate) fn chrome_headless_shell_path(chrome: &Path) -> Result<PathBuf> {
let missing = |what: String| {
BrowserError::ChromeForTestingNotFound(format!(
"{what}\nThe Windows fixture runs chrome-headless-shell from the same Chrome for Testing \
version (chrome-headless-shell-win64.zip, unpacked beside chrome-win64, or {HEADLESS_SHELL_ENV})"
))
};
if let Some(p) = std::env::var_os(HEADLESS_SHELL_ENV).filter(|v| !v.is_empty()) {
let p = PathBuf::from(p);
return if p.exists() {
Ok(p)
} else {
Err(missing(format!(
"{HEADLESS_SHELL_ENV} points at a missing file: {}",
p.display()
)))
};
}
let home = home_dir().unwrap_or_default();
let env_path = |k: &str| {
std::env::var_os(k)
.filter(|v| !v.is_empty())
.map(PathBuf::from)
};
let root = managed_chrome_for_testing_root(&home, &env_path);
let candidates = chrome_headless_shell_candidates(chrome, &root);
if let Some(p) = candidates.iter().find(|p| p.exists()) {
return Ok(p.clone());
}
let searched: Vec<String> = candidates
.iter()
.map(|p| format!(" {}", p.display()))
.collect();
Err(missing(format!(
"chrome-headless-shell is not installed; searched:\n{}",
searched.join("\n")
)))
}
pub fn chrome_for_testing_candidates() -> Vec<PathBuf> {
let home = home_dir().unwrap_or_default();
let env_path = |k: &str| {
std::env::var_os(k)
.filter(|v| !v.is_empty())
.map(PathBuf::from)
};
let puppeteer = env_path("PUPPETEER_CACHE_DIR")
.unwrap_or_else(|| home.join(".cache").join("puppeteer"))
.join("chrome");
let managed_root = managed_chrome_for_testing_root(&home, &env_path);
let mut out = managed_chrome_for_testing_candidates(&managed_root);
if cfg!(target_os = "macos") {
out.push(Path::new("/Applications").join(MAC_CFT_APP));
out.push(home.join("Applications").join(MAC_CFT_APP));
let subs: [&str; 2] = if cfg!(target_arch = "aarch64") {
["chrome-mac-arm64", "chrome-mac-x64"]
} else {
["chrome-mac-x64", "chrome-mac-arm64"]
};
let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
.unwrap_or_else(|| home.join("Library/Caches/ms-playwright"));
for dir in versioned_children(&puppeteer, &["mac_arm-", "mac-"])
.into_iter()
.chain(versioned_children(&playwright, &["chromium-"]))
{
for sub in subs {
out.push(dir.join(sub).join(MAC_CFT_APP));
}
}
} else if cfg!(target_os = "windows") {
let local = env_path("LOCALAPPDATA").unwrap_or_else(|| home.join(r"AppData\Local"));
for dir in versioned_children(&puppeteer, &["win64-", "win32-"]) {
out.push(dir.join("chrome-win64").join("chrome.exe"));
out.push(dir.join("chrome-win32").join("chrome.exe"));
}
let playwright =
env_path("PLAYWRIGHT_BROWSERS_PATH").unwrap_or_else(|| local.join("ms-playwright"));
for dir in versioned_children(&playwright, &["chromium-"]) {
out.push(dir.join("chrome-win64").join("chrome.exe"));
}
} else {
for dir in versioned_children(&puppeteer, &["linux-", "linux_arm-"]) {
out.push(dir.join("chrome-linux64").join("chrome"));
out.push(dir.join("chrome-linux-arm64").join("chrome"));
}
let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
.unwrap_or_else(|| home.join(".cache").join("ms-playwright"));
for dir in versioned_children(&playwright, &["chromium-"]) {
out.push(dir.join("chrome-linux64").join("chrome"));
}
}
out
}
pub fn chrome_for_testing_path(explicit: Option<&Path>) -> Result<PathBuf> {
let missing = |what: String| {
BrowserError::ChromeForTestingNotFound(format!("{what}\n{CHROME_FOR_TESTING_INSTALL_HINT}"))
};
if let Some(p) = explicit {
return if p.exists() {
Ok(p.to_path_buf())
} else {
Err(missing(format!(
"explicit Chrome for Testing executable does not exist: {}",
p.display()
)))
};
}
if let Some(found) = executable_from_env(&missing) {
return found;
}
let candidates = chrome_for_testing_candidates();
if let Some(p) = candidates.iter().find(|p| p.exists()) {
return Ok(p.clone());
}
let searched: Vec<String> = candidates
.iter()
.map(|p| format!(" {}", p.display()))
.collect();
Err(missing(format!(
"Chrome for Testing is not installed; searched:\n{}",
if searched.is_empty() {
" (nothing)".to_string()
} else {
searched.join("\n")
}
)))
}
pub(crate) fn resolve_executable(opts: &LaunchOptions) -> Result<PathBuf> {
resolve_executable_with(opts, || chrome_for_testing_path(None), find_chrome)
}
fn resolve_executable_with(
opts: &LaunchOptions,
cft: impl FnOnce() -> Result<PathBuf>,
system: impl FnOnce() -> Option<PathBuf>,
) -> Result<PathBuf> {
if opts.use_system_chrome_only {
return system().ok_or(BrowserError::ChromeNotFound);
}
if let Some(p) = &opts.chrome_path {
return Ok(p.clone());
}
match cft() {
Ok(p) => Ok(p),
Err(e) if opts.allow_system_chrome => system().ok_or(e),
Err(e) => Err(e),
}
}
pub fn find_chrome() -> Option<PathBuf> {
if let Ok(p) = std::env::var("CHROME") {
let p = PathBuf::from(p);
if p.exists() {
return Some(p);
}
}
let per_user: &[&str] = if cfg!(target_os = "windows") {
&[
r"Google\Chrome\Application\chrome.exe",
r"Microsoft\Edge\Application\msedge.exe",
]
} else {
&[]
};
let candidates: &[&str] = if cfg!(target_os = "windows") {
&[
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
]
} else if cfg!(target_os = "macos") {
&[
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
]
} else {
&[
"/usr/bin/google-chrome",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
"/usr/bin/microsoft-edge",
]
};
candidates
.iter()
.map(PathBuf::from)
.chain(windows_local_app_candidates(per_user))
.find(|p| Path::new(p).exists())
}
pub(crate) fn windows_local_app_candidates(relative: &[&str]) -> Vec<PathBuf> {
if !cfg!(windows) {
return Vec::new();
}
let Some(local) = std::env::var_os("LOCALAPPDATA")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
else {
return Vec::new();
};
relative.iter().map(|rel| local.join(rel)).collect()
}
pub(crate) fn validate_extra_args(args: &[String]) -> Result<()> {
const FORBIDDEN: &[&str] = &[
"user-data-dir",
"profile-directory",
"remote-debugging-port",
"remote-debugging-address",
"remote-debugging-pipe",
"remote-debugging-io-pipes",
"remote-allow-origins",
"disable-web-security",
"incognito-bypass",
];
for a in args {
let name = a.trim_start_matches('-').split('=').next().unwrap_or("");
if FORBIDDEN.contains(&name) {
return Err(BrowserError::Invalid(format!(
"chrome flag '--{name}' is managed by the session"
)));
}
}
Ok(())
}
pub(crate) fn reject_real_browser_profile(root: &Path) -> Result<()> {
let mut real: Vec<PathBuf> = Vec::new();
if let Some(home) = std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(PathBuf::from)
{
for rel in [
"Library/Application Support/Google/Chrome",
"Library/Application Support/Chromium",
"Library/Application Support/Microsoft Edge",
".config/google-chrome",
".config/chromium",
".config/microsoft-edge",
] {
real.push(home.join(rel));
}
}
if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
for rel in [
r"Google\Chrome\User Data",
r"Chromium\User Data",
r"Microsoft\Edge\User Data",
] {
real.push(local.join(rel));
}
}
std::fs::create_dir_all(root)?;
let root = root.canonicalize()?;
for r in real {
if let Ok(r) = r.canonicalize() {
if root.starts_with(&r) {
return Err(BrowserError::Profile(
"refusing to use the user's real browser profile".into(),
));
}
}
}
Ok(())
}