use super::{
cdp::{CdpNetworkGuard, CdpSession, evaluate_network_host_with_active_tab},
launcher::{
BrowserLaunchSpec, BrowserProcessHandle, BrowserProcessLauncher,
LocalBrowserProcessLauncher, ProcessRunnerBrowserLauncher,
},
ws::connect_tcp_ws,
};
use merry_runtime::{
LivePolicyHandle, NetworkAccessDecision, ProcessRunner, normalize_network_domain,
};
use serde::Deserialize;
use serde_json::json;
use std::{
path::PathBuf,
sync::{Arc, Mutex as StdMutex},
time::Duration,
};
use tempfile::TempDir;
use tokio::sync::Mutex;
const DEFAULT_TIMEOUT_SECS: u64 = 15;
const DEFAULT_VIEWPORT_WIDTH: u32 = 1280;
const DEFAULT_VIEWPORT_HEIGHT: u32 = 800;
#[derive(Debug, Clone)]
pub struct BrowserConfig {
pub(crate) allow_local: bool,
pub(crate) chrome_executable: Option<PathBuf>,
pub(crate) headless: bool,
pub(crate) default_timeout: Duration,
pub(crate) viewport_width: u32,
pub(crate) viewport_height: u32,
pub(crate) process_launcher: Option<Arc<dyn BrowserProcessLauncher>>,
pub(crate) live_network_policy: Option<LivePolicyHandle>,
}
impl Default for BrowserConfig {
fn default() -> Self {
Self {
allow_local: true,
chrome_executable: None,
headless: true,
default_timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
viewport_width: DEFAULT_VIEWPORT_WIDTH,
viewport_height: DEFAULT_VIEWPORT_HEIGHT,
process_launcher: None,
live_network_policy: None,
}
}
}
impl BrowserConfig {
#[must_use]
pub fn with_allow_local(mut self, allow_local: bool) -> Self {
self.allow_local = allow_local;
self
}
#[must_use]
pub fn with_live_network_policy(mut self, policy: LivePolicyHandle) -> Self {
self.live_network_policy = Some(policy);
self
}
#[must_use]
pub fn with_chrome_executable(mut self, path: impl Into<PathBuf>) -> Self {
self.chrome_executable = Some(path.into());
self
}
#[must_use]
pub fn with_default_timeout(mut self, timeout: Duration) -> Self {
self.default_timeout = timeout;
self
}
#[must_use]
pub fn with_viewport(mut self, width: u32, height: u32) -> Self {
self.viewport_width = width;
self.viewport_height = height;
self
}
#[must_use]
pub fn with_process_launcher(mut self, launcher: Arc<dyn BrowserProcessLauncher>) -> Self {
self.process_launcher = Some(launcher);
self
}
#[must_use]
pub fn with_process_runner(self, runner: Arc<dyn ProcessRunner>) -> Self {
self.with_process_launcher(Arc::new(ProcessRunnerBrowserLauncher::new(runner)))
}
}
struct ManagedBrowserProcess {
handle: Box<dyn BrowserProcessHandle>,
_profile_dir: TempDir,
}
pub(crate) struct ActiveBrowserSession {
pub(crate) cdp: Arc<CdpSession>,
process: Option<ManagedBrowserProcess>,
}
impl ActiveBrowserSession {
async fn shutdown(mut self) {
if let Some(mut process) = self.process.take() {
process.handle.shutdown().await;
}
if let Ok(cdp) = Arc::try_unwrap(self.cdp) {
cdp.close().await;
}
}
}
pub(crate) struct OnceDomainScope {
slot: Arc<StdMutex<Vec<String>>>,
}
impl Drop for OnceDomainScope {
fn drop(&mut self) {
self.slot
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
}
}
pub struct BrowserSessionManager {
config: BrowserConfig,
state: Mutex<Option<ActiveBrowserSession>>,
once_approved_domains: Arc<StdMutex<Vec<String>>>,
active_authorized_host: Arc<StdMutex<Option<String>>>,
}
impl std::fmt::Debug for BrowserSessionManager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BrowserSessionManager")
.field("config", &self.config)
.finish_non_exhaustive()
}
}
impl BrowserSessionManager {
#[must_use]
pub fn new(config: BrowserConfig) -> Self {
Self {
config,
state: Mutex::new(None),
once_approved_domains: Arc::new(StdMutex::new(Vec::new())),
active_authorized_host: Arc::new(StdMutex::new(None)),
}
}
#[cfg(test)]
pub(crate) fn with_test_cdp(config: BrowserConfig, cdp: CdpSession) -> Self {
Self {
config,
state: Mutex::new(Some(ActiveBrowserSession {
cdp: Arc::new(cdp),
process: None,
})),
once_approved_domains: Arc::new(StdMutex::new(Vec::new())),
active_authorized_host: Arc::new(StdMutex::new(None)),
}
}
#[cfg(test)]
pub(crate) fn with_test_ws<R, W>(
config: BrowserConfig,
ws_r: super::ws::WsReader<R>,
ws_w: super::ws::WsWriter<W>,
) -> Self
where
R: tokio::io::AsyncRead + Unpin + Send + 'static,
W: tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let once_approved_domains = Arc::new(StdMutex::new(Vec::new()));
let active_authorized_host = Arc::new(StdMutex::new(None));
let network_guard = CdpNetworkGuard {
allow_local: config.allow_local,
live_network_policy: config.live_network_policy.clone(),
once_domains: Arc::clone(&once_approved_domains),
active_authorized_host: Arc::clone(&active_authorized_host),
};
let cdp = CdpSession::from_ws_with_guard(ws_r, ws_w, Some(network_guard));
Self {
config,
state: Mutex::new(Some(ActiveBrowserSession {
cdp: Arc::new(cdp),
process: None,
})),
once_approved_domains,
active_authorized_host,
}
}
#[must_use]
pub(crate) fn config(&self) -> &BrowserConfig {
&self.config
}
#[must_use]
pub(crate) fn effective_allow_local(&self) -> bool {
self.config.allow_local
&& self
.config
.live_network_policy
.as_ref()
.is_none_or(LivePolicyHandle::network_allow_local)
}
#[must_use]
pub(crate) fn evaluate_data_url_admission(&self) -> NetworkAccessDecision {
if self.effective_allow_local() {
NetworkAccessDecision::Allow
} else {
NetworkAccessDecision::Deny
}
}
#[must_use]
pub(crate) fn evaluate_host_admission(
&self,
host: &str,
once_domains: &[String],
active_authorized_host: Option<&str>,
) -> NetworkAccessDecision {
match self.config.live_network_policy.as_ref() {
Some(policy) => evaluate_network_host_with_active_tab(
policy,
host,
once_domains,
active_authorized_host,
),
None => NetworkAccessDecision::Allow,
}
}
pub(crate) fn scope_once_domains(&self, domains: &[String]) -> OnceDomainScope {
*self
.once_approved_domains
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = domains.to_vec();
OnceDomainScope {
slot: Arc::clone(&self.once_approved_domains),
}
}
pub(crate) fn set_active_authorized_host(&self, host: Option<String>) {
let normalized = host.and_then(|value| normalize_network_domain(&value));
*self
.active_authorized_host
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = normalized;
}
#[must_use]
pub(crate) fn active_authorized_host(&self) -> Option<String> {
self.active_authorized_host
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub(crate) async fn session(&self, auto_launch: bool) -> Result<Arc<CdpSession>, String> {
let mut guard = self.state.lock().await;
if let Some(active) = guard.as_ref() {
if !active.cdp.is_closed() {
return Ok(Arc::clone(&active.cdp));
}
if let Some(dead) = guard.take() {
self.set_active_authorized_host(None);
dead.shutdown().await;
}
}
if !auto_launch {
return Err(
"No active browser session. Call `browser_tab` with `action: \"open\"` first."
.to_owned(),
);
}
let network_guard = CdpNetworkGuard {
allow_local: self.config.allow_local,
live_network_policy: self.config.live_network_policy.clone(),
once_domains: Arc::clone(&self.once_approved_domains),
active_authorized_host: Arc::clone(&self.active_authorized_host),
};
let active = launch_headless_browser(&self.config, network_guard).await?;
let cdp = Arc::clone(&active.cdp);
*guard = Some(active);
Ok(cdp)
}
pub async fn close(&self) -> bool {
self.set_active_authorized_host(None);
let mut guard = self.state.lock().await;
let Some(active) = guard.take() else {
return false;
};
active.shutdown().await;
true
}
}
impl Default for BrowserSessionManager {
fn default() -> Self {
Self::new(BrowserConfig::default())
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct DevToolsTarget {
#[serde(rename = "type", default)]
kind: String,
#[serde(default)]
web_socket_debugger_url: Option<String>,
}
async fn launch_headless_browser(
config: &BrowserConfig,
network_guard: CdpNetworkGuard,
) -> Result<ActiveBrowserSession, String> {
let executable = discover_chrome_executable(config.chrome_executable.as_deref())?;
let profile_dir = tempfile::Builder::new()
.prefix("merry-browser-")
.tempdir()
.map_err(|e| format!("failed creating temporary browser profile dir: {e}"))?;
let mut args = Vec::new();
if config.headless {
args.push("--headless=new".to_owned());
}
args.extend([
"--remote-debugging-port=0".to_owned(),
"--remote-debugging-address=127.0.0.1".to_owned(),
"--no-first-run".to_owned(),
"--no-default-browser-check".to_owned(),
"--disable-background-networking".to_owned(),
"--disable-gpu".to_owned(),
"--disable-dev-shm-usage".to_owned(),
format!(
"--window-size={},{}",
config.viewport_width, config.viewport_height
),
format!("--user-data-dir={}", profile_dir.path().display()),
"about:blank".to_owned(),
]);
let spec = BrowserLaunchSpec {
executable,
args,
profile_dir: Some(profile_dir.path().to_path_buf()),
};
let mut handle = match config.process_launcher.as_ref() {
Some(launcher) => launcher.launch(spec).await?,
None => LocalBrowserProcessLauncher.launch(spec).await?,
};
let ws_browser_url = match handle
.wait_for_devtools_ws_url(config.default_timeout)
.await
{
Ok(url) => url,
Err(err) => {
handle.shutdown().await;
return Err(err);
}
};
let process = ManagedBrowserProcess {
handle,
_profile_dir: profile_dir,
};
let page_ws_url =
discover_or_create_page_ws_url(&ws_browser_url, config.default_timeout).await?;
let (ws_reader, ws_writer) = connect_tcp_ws(&page_ws_url).await?;
let cdp = Arc::new(CdpSession::from_ws_with_guard(
ws_reader,
ws_writer,
Some(network_guard),
));
let _ = cdp
.call("Page.enable", json!({}), config.default_timeout)
.await?;
let _ = cdp
.call("Runtime.enable", json!({}), config.default_timeout)
.await?;
let _ = cdp
.call("Network.enable", json!({}), config.default_timeout)
.await?;
let _ = cdp
.call(
"Fetch.enable",
json!({
"patterns": [{ "urlPattern": "*", "requestStage": "Request" }]
}),
config.default_timeout,
)
.await;
let _ = cdp
.call(
"Emulation.setDeviceMetricsOverride",
json!({
"width": config.viewport_width,
"height": config.viewport_height,
"deviceScaleFactor": 1,
"mobile": false,
}),
config.default_timeout,
)
.await;
Ok(ActiveBrowserSession {
cdp,
process: Some(process),
})
}
async fn discover_or_create_page_ws_url(
browser_ws_url: &str,
timeout: Duration,
) -> Result<String, String> {
let parsed = url::Url::parse(browser_ws_url)
.map_err(|e| format!("invalid Chrome DevTools URL {browser_ws_url:?}: {e}"))?;
let port = parsed
.port()
.ok_or_else(|| "Chrome DevTools URL missing port".to_owned())?;
let host = parsed.host_str().unwrap_or("127.0.0.1");
let client = reqwest::Client::builder()
.timeout(timeout)
.build()
.map_err(|e| format!("failed to build loopback HTTP client: {e}"))?;
let list_url = format!("http://{host}:{port}/json/list");
if let Ok(resp) = client.get(&list_url).send().await
&& let Ok(targets) = resp.json::<Vec<DevToolsTarget>>().await
&& let Some(page_ws) = targets
.into_iter()
.find(|t| t.kind == "page")
.and_then(|t| t.web_socket_debugger_url)
{
return Ok(page_ws);
}
let new_url = format!("http://{host}:{port}/json/new?about:blank");
if let Ok(resp) = client.put(&new_url).send().await
&& let Ok(target) = resp.json::<DevToolsTarget>().await
&& let Some(page_ws) = target.web_socket_debugger_url
{
return Ok(page_ws);
}
Ok(browser_ws_url.to_owned())
}
fn discover_chrome_executable(explicit: Option<&std::path::Path>) -> Result<PathBuf, String> {
if let Some(path) = explicit {
if path.is_file() {
return Ok(path.to_path_buf());
}
return Err(format!(
"configured Chrome executable does not exist: {}",
path.display()
));
}
if let Some(env_path) = std::env::var_os("MERRY_CHROME_PATH") {
let path = PathBuf::from(env_path);
if path.is_file() {
return Ok(path);
}
}
for candidate in [
"google-chrome",
"google-chrome-stable",
"chromium",
"chromium-browser",
"chrome",
"msedge",
] {
if let Some(found) = find_in_path(candidate) {
return Ok(found);
}
}
for abs in [
"/usr/bin/google-chrome",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
] {
let p = PathBuf::from(abs);
if p.is_file() {
return Ok(p);
}
}
#[cfg(windows)]
if let Some(found) = find_windows_browser_binary() {
return Ok(found);
}
Err(
"No headless Chrome or Chromium executable found (checked MERRY_CHROME_PATH, PATH, and standard system paths)."
.to_owned(),
)
}
#[cfg(windows)]
fn find_windows_browser_binary() -> Option<PathBuf> {
let roots = [
std::env::var_os("PROGRAMFILES"),
std::env::var_os("PROGRAMFILES(X86)"),
std::env::var_os("LOCALAPPDATA"),
];
let relative_candidates = [
r"Google\Chrome\Application\chrome.exe",
r"Chromium\Application\chrome.exe",
r"Microsoft\Edge\Application\msedge.exe",
];
for root in roots.into_iter().flatten() {
let base = PathBuf::from(root);
for rel in relative_candidates {
let candidate = base.join(rel);
if candidate.is_file() {
return Some(candidate);
}
}
}
None
}
fn find_in_path(binary: &str) -> Option<PathBuf> {
let path_var = std::env::var_os("PATH")?;
merry_core::host_paths::find_executable_in_path(&path_var, &[binary], std::path::Path::is_file)
}