Skip to main content

merry_tools/browser/
session.rs

1//! Session-scoped headless Chrome/Chromium lifecycle management for browser tools.
2
3use super::{
4    cdp::{CdpNetworkGuard, CdpSession, evaluate_network_host_with_active_tab},
5    launcher::{
6        BrowserLaunchSpec, BrowserProcessHandle, BrowserProcessLauncher,
7        LocalBrowserProcessLauncher, ProcessRunnerBrowserLauncher,
8    },
9    ws::connect_tcp_ws,
10};
11use merry_runtime::{
12    LivePolicyHandle, NetworkAccessDecision, ProcessRunner, normalize_network_domain,
13};
14use serde::Deserialize;
15use serde_json::json;
16use std::{
17    path::PathBuf,
18    sync::{Arc, Mutex as StdMutex},
19    time::Duration,
20};
21use tempfile::TempDir;
22use tokio::sync::Mutex;
23
24const DEFAULT_TIMEOUT_SECS: u64 = 15;
25const DEFAULT_VIEWPORT_WIDTH: u32 = 1280;
26const DEFAULT_VIEWPORT_HEIGHT: u32 = 800;
27
28/// Configuration for the session-scoped headless Chrome/Chromium controller.
29#[derive(Debug, Clone)]
30pub struct BrowserConfig {
31    pub(crate) allow_local: bool,
32    pub(crate) chrome_executable: Option<PathBuf>,
33    pub(crate) headless: bool,
34    pub(crate) default_timeout: Duration,
35    pub(crate) viewport_width: u32,
36    pub(crate) viewport_height: u32,
37    pub(crate) process_launcher: Option<Arc<dyn BrowserProcessLauncher>>,
38    pub(crate) live_network_policy: Option<LivePolicyHandle>,
39}
40
41impl Default for BrowserConfig {
42    fn default() -> Self {
43        Self {
44            allow_local: true,
45            chrome_executable: None,
46            headless: true,
47            default_timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
48            viewport_width: DEFAULT_VIEWPORT_WIDTH,
49            viewport_height: DEFAULT_VIEWPORT_HEIGHT,
50            process_launcher: None,
51            live_network_policy: None,
52        }
53    }
54}
55
56impl BrowserConfig {
57    /// Controls whether explicit loopback targets (`localhost`, `127.0.0.1`, `::1`) may be opened.
58    #[must_use]
59    pub fn with_allow_local(mut self, allow_local: bool) -> Self {
60        self.allow_local = allow_local;
61        self
62    }
63
64    /// Attaches the live unified [`LivePolicyHandle`] shared with
65    /// session permissions, workspace `allowed_domains`, and `network` policy.
66    #[must_use]
67    pub fn with_live_network_policy(mut self, policy: LivePolicyHandle) -> Self {
68        self.live_network_policy = Some(policy);
69        self
70    }
71
72    /// Sets an explicit Chrome/Chromium executable path instead of auto-discovery.
73    #[must_use]
74    pub fn with_chrome_executable(mut self, path: impl Into<PathBuf>) -> Self {
75        self.chrome_executable = Some(path.into());
76        self
77    }
78
79    /// Overrides the default CDP action timeout.
80    #[must_use]
81    pub fn with_default_timeout(mut self, timeout: Duration) -> Self {
82        self.default_timeout = timeout;
83        self
84    }
85
86    /// Overrides the initial viewport dimensions.
87    #[must_use]
88    pub fn with_viewport(mut self, width: u32, height: u32) -> Self {
89        self.viewport_width = width;
90        self.viewport_height = height;
91        self
92    }
93
94    /// Routes headless browser launches through an explicit [`BrowserProcessLauncher`].
95    #[must_use]
96    pub fn with_process_launcher(mut self, launcher: Arc<dyn BrowserProcessLauncher>) -> Self {
97        self.process_launcher = Some(launcher);
98        self
99    }
100
101    /// Routes headless browser launches through Merry's configured [`ProcessRunner`].
102    #[must_use]
103    pub fn with_process_runner(self, runner: Arc<dyn ProcessRunner>) -> Self {
104        self.with_process_launcher(Arc::new(ProcessRunnerBrowserLauncher::new(runner)))
105    }
106}
107
108struct ManagedBrowserProcess {
109    handle: Box<dyn BrowserProcessHandle>,
110    _profile_dir: TempDir,
111}
112
113pub(crate) struct ActiveBrowserSession {
114    pub(crate) cdp: Arc<CdpSession>,
115    process: Option<ManagedBrowserProcess>,
116}
117
118impl ActiveBrowserSession {
119    async fn shutdown(mut self) {
120        if let Some(mut process) = self.process.take() {
121            process.handle.shutdown().await;
122        }
123        if let Ok(cdp) = Arc::try_unwrap(self.cdp) {
124            cdp.close().await;
125        }
126    }
127}
128
129/// RAII scope installing single-action approved domain grants for one in-flight
130/// `browser_tab` call so the CDP `Fetch` interceptor allows those exact hosts
131/// during the call and clears them on exit.
132pub(crate) struct OnceDomainScope {
133    slot: Arc<StdMutex<Vec<String>>>,
134}
135
136impl Drop for OnceDomainScope {
137    fn drop(&mut self) {
138        self.slot
139            .lock()
140            .unwrap_or_else(std::sync::PoisonError::into_inner)
141            .clear();
142    }
143}
144
145/// Shared session-scoped headless browser manager shared by `browser_tab` and `browser_network`.
146pub struct BrowserSessionManager {
147    config: BrowserConfig,
148    state: Mutex<Option<ActiveBrowserSession>>,
149    once_approved_domains: Arc<StdMutex<Vec<String>>>,
150    active_authorized_host: Arc<StdMutex<Option<String>>>,
151}
152
153impl std::fmt::Debug for BrowserSessionManager {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        f.debug_struct("BrowserSessionManager")
156            .field("config", &self.config)
157            .finish_non_exhaustive()
158    }
159}
160
161impl BrowserSessionManager {
162    /// Creates a new lazy browser session manager with the given configuration.
163    #[must_use]
164    pub fn new(config: BrowserConfig) -> Self {
165        Self {
166            config,
167            state: Mutex::new(None),
168            once_approved_domains: Arc::new(StdMutex::new(Vec::new())),
169            active_authorized_host: Arc::new(StdMutex::new(None)),
170        }
171    }
172
173    #[cfg(test)]
174    pub(crate) fn with_test_cdp(config: BrowserConfig, cdp: CdpSession) -> Self {
175        Self {
176            config,
177            state: Mutex::new(Some(ActiveBrowserSession {
178                cdp: Arc::new(cdp),
179                process: None,
180            })),
181            once_approved_domains: Arc::new(StdMutex::new(Vec::new())),
182            active_authorized_host: Arc::new(StdMutex::new(None)),
183        }
184    }
185
186    #[cfg(test)]
187    pub(crate) fn with_test_ws<R, W>(
188        config: BrowserConfig,
189        ws_r: super::ws::WsReader<R>,
190        ws_w: super::ws::WsWriter<W>,
191    ) -> Self
192    where
193        R: tokio::io::AsyncRead + Unpin + Send + 'static,
194        W: tokio::io::AsyncWrite + Unpin + Send + 'static,
195    {
196        let once_approved_domains = Arc::new(StdMutex::new(Vec::new()));
197        let active_authorized_host = Arc::new(StdMutex::new(None));
198        let network_guard = CdpNetworkGuard {
199            allow_local: config.allow_local,
200            live_network_policy: config.live_network_policy.clone(),
201            once_domains: Arc::clone(&once_approved_domains),
202            active_authorized_host: Arc::clone(&active_authorized_host),
203        };
204        let cdp = CdpSession::from_ws_with_guard(ws_r, ws_w, Some(network_guard));
205        Self {
206            config,
207            state: Mutex::new(Some(ActiveBrowserSession {
208                cdp: Arc::new(cdp),
209                process: None,
210            })),
211            once_approved_domains,
212            active_authorized_host,
213        }
214    }
215
216    #[must_use]
217    pub(crate) fn config(&self) -> &BrowserConfig {
218        &self.config
219    }
220
221    #[must_use]
222    pub(crate) fn effective_allow_local(&self) -> bool {
223        self.config.allow_local
224            && self
225                .config
226                .live_network_policy
227                .as_ref()
228                .is_none_or(LivePolicyHandle::network_allow_local)
229    }
230
231    #[must_use]
232    pub(crate) fn evaluate_data_url_admission(&self) -> NetworkAccessDecision {
233        if self.effective_allow_local() {
234            NetworkAccessDecision::Allow
235        } else {
236            NetworkAccessDecision::Deny
237        }
238    }
239
240    #[must_use]
241    pub(crate) fn evaluate_host_admission(
242        &self,
243        host: &str,
244        once_domains: &[String],
245        active_authorized_host: Option<&str>,
246    ) -> NetworkAccessDecision {
247        match self.config.live_network_policy.as_ref() {
248            Some(policy) => evaluate_network_host_with_active_tab(
249                policy,
250                host,
251                once_domains,
252                active_authorized_host,
253            ),
254            None => NetworkAccessDecision::Allow,
255        }
256    }
257
258    pub(crate) fn scope_once_domains(&self, domains: &[String]) -> OnceDomainScope {
259        *self
260            .once_approved_domains
261            .lock()
262            .unwrap_or_else(std::sync::PoisonError::into_inner) = domains.to_vec();
263        OnceDomainScope {
264            slot: Arc::clone(&self.once_approved_domains),
265        }
266    }
267
268    pub(crate) fn set_active_authorized_host(&self, host: Option<String>) {
269        let normalized = host.and_then(|value| normalize_network_domain(&value));
270        *self
271            .active_authorized_host
272            .lock()
273            .unwrap_or_else(std::sync::PoisonError::into_inner) = normalized;
274    }
275
276    #[must_use]
277    pub(crate) fn active_authorized_host(&self) -> Option<String> {
278        self.active_authorized_host
279            .lock()
280            .unwrap_or_else(std::sync::PoisonError::into_inner)
281            .clone()
282    }
283
284    /// Returns the active CDP session, returning an error if no tab has been opened yet and `auto_launch` is false.
285    pub(crate) async fn session(&self, auto_launch: bool) -> Result<Arc<CdpSession>, String> {
286        let mut guard = self.state.lock().await;
287        if let Some(active) = guard.as_ref() {
288            if !active.cdp.is_closed() {
289                return Ok(Arc::clone(&active.cdp));
290            }
291            if let Some(dead) = guard.take() {
292                self.set_active_authorized_host(None);
293                dead.shutdown().await;
294            }
295        }
296        if !auto_launch {
297            return Err(
298                "No active browser session. Call `browser_tab` with `action: \"open\"` first."
299                    .to_owned(),
300            );
301        }
302        let network_guard = CdpNetworkGuard {
303            allow_local: self.config.allow_local,
304            live_network_policy: self.config.live_network_policy.clone(),
305            once_domains: Arc::clone(&self.once_approved_domains),
306            active_authorized_host: Arc::clone(&self.active_authorized_host),
307        };
308        let active = launch_headless_browser(&self.config, network_guard).await?;
309        let cdp = Arc::clone(&active.cdp);
310        *guard = Some(active);
311        Ok(cdp)
312    }
313
314    /// Closes and terminates the active browser session if running.
315    pub async fn close(&self) -> bool {
316        self.set_active_authorized_host(None);
317        let mut guard = self.state.lock().await;
318        let Some(active) = guard.take() else {
319            return false;
320        };
321        active.shutdown().await;
322        true
323    }
324}
325
326impl Default for BrowserSessionManager {
327    fn default() -> Self {
328        Self::new(BrowserConfig::default())
329    }
330}
331
332#[derive(Deserialize)]
333#[serde(rename_all = "camelCase")]
334struct DevToolsTarget {
335    #[serde(rename = "type", default)]
336    kind: String,
337    #[serde(default)]
338    web_socket_debugger_url: Option<String>,
339}
340
341async fn launch_headless_browser(
342    config: &BrowserConfig,
343    network_guard: CdpNetworkGuard,
344) -> Result<ActiveBrowserSession, String> {
345    let executable = discover_chrome_executable(config.chrome_executable.as_deref())?;
346    let profile_dir = tempfile::Builder::new()
347        .prefix("merry-browser-")
348        .tempdir()
349        .map_err(|e| format!("failed creating temporary browser profile dir: {e}"))?;
350
351    let mut args = Vec::new();
352    if config.headless {
353        args.push("--headless=new".to_owned());
354    }
355    args.extend([
356        "--remote-debugging-port=0".to_owned(),
357        "--remote-debugging-address=127.0.0.1".to_owned(),
358        "--no-first-run".to_owned(),
359        "--no-default-browser-check".to_owned(),
360        "--disable-background-networking".to_owned(),
361        "--disable-gpu".to_owned(),
362        "--disable-dev-shm-usage".to_owned(),
363        format!(
364            "--window-size={},{}",
365            config.viewport_width, config.viewport_height
366        ),
367        format!("--user-data-dir={}", profile_dir.path().display()),
368        "about:blank".to_owned(),
369    ]);
370
371    let spec = BrowserLaunchSpec {
372        executable,
373        args,
374        profile_dir: Some(profile_dir.path().to_path_buf()),
375    };
376    let mut handle = match config.process_launcher.as_ref() {
377        Some(launcher) => launcher.launch(spec).await?,
378        None => LocalBrowserProcessLauncher.launch(spec).await?,
379    };
380    let ws_browser_url = match handle
381        .wait_for_devtools_ws_url(config.default_timeout)
382        .await
383    {
384        Ok(url) => url,
385        Err(err) => {
386            handle.shutdown().await;
387            return Err(err);
388        }
389    };
390
391    let process = ManagedBrowserProcess {
392        handle,
393        _profile_dir: profile_dir,
394    };
395
396    let page_ws_url =
397        discover_or_create_page_ws_url(&ws_browser_url, config.default_timeout).await?;
398    let (ws_reader, ws_writer) = connect_tcp_ws(&page_ws_url).await?;
399    let cdp = Arc::new(CdpSession::from_ws_with_guard(
400        ws_reader,
401        ws_writer,
402        Some(network_guard),
403    ));
404
405    let _ = cdp
406        .call("Page.enable", json!({}), config.default_timeout)
407        .await?;
408    let _ = cdp
409        .call("Runtime.enable", json!({}), config.default_timeout)
410        .await?;
411    let _ = cdp
412        .call("Network.enable", json!({}), config.default_timeout)
413        .await?;
414    // Best-effort enable CDP Fetch request interception so redirects and
415    // sub-requests undergo SSRF + domain-consistency enforcement before
416    // crossing the wire.
417    let _ = cdp
418        .call(
419            "Fetch.enable",
420            json!({
421                "patterns": [{ "urlPattern": "*", "requestStage": "Request" }]
422            }),
423            config.default_timeout,
424        )
425        .await;
426    let _ = cdp
427        .call(
428            "Emulation.setDeviceMetricsOverride",
429            json!({
430                "width": config.viewport_width,
431                "height": config.viewport_height,
432                "deviceScaleFactor": 1,
433                "mobile": false,
434            }),
435            config.default_timeout,
436        )
437        .await;
438
439    Ok(ActiveBrowserSession {
440        cdp,
441        process: Some(process),
442    })
443}
444
445async fn discover_or_create_page_ws_url(
446    browser_ws_url: &str,
447    timeout: Duration,
448) -> Result<String, String> {
449    let parsed = url::Url::parse(browser_ws_url)
450        .map_err(|e| format!("invalid Chrome DevTools URL {browser_ws_url:?}: {e}"))?;
451    let port = parsed
452        .port()
453        .ok_or_else(|| "Chrome DevTools URL missing port".to_owned())?;
454    let host = parsed.host_str().unwrap_or("127.0.0.1");
455
456    let client = reqwest::Client::builder()
457        .timeout(timeout)
458        .build()
459        .map_err(|e| format!("failed to build loopback HTTP client: {e}"))?;
460
461    let list_url = format!("http://{host}:{port}/json/list");
462    if let Ok(resp) = client.get(&list_url).send().await
463        && let Ok(targets) = resp.json::<Vec<DevToolsTarget>>().await
464        && let Some(page_ws) = targets
465            .into_iter()
466            .find(|t| t.kind == "page")
467            .and_then(|t| t.web_socket_debugger_url)
468    {
469        return Ok(page_ws);
470    }
471
472    let new_url = format!("http://{host}:{port}/json/new?about:blank");
473    if let Ok(resp) = client.put(&new_url).send().await
474        && let Ok(target) = resp.json::<DevToolsTarget>().await
475        && let Some(page_ws) = target.web_socket_debugger_url
476    {
477        return Ok(page_ws);
478    }
479
480    Ok(browser_ws_url.to_owned())
481}
482
483fn discover_chrome_executable(explicit: Option<&std::path::Path>) -> Result<PathBuf, String> {
484    if let Some(path) = explicit {
485        if path.is_file() {
486            return Ok(path.to_path_buf());
487        }
488        return Err(format!(
489            "configured Chrome executable does not exist: {}",
490            path.display()
491        ));
492    }
493    if let Some(env_path) = std::env::var_os("MERRY_CHROME_PATH") {
494        let path = PathBuf::from(env_path);
495        if path.is_file() {
496            return Ok(path);
497        }
498    }
499    for candidate in [
500        "google-chrome",
501        "google-chrome-stable",
502        "chromium",
503        "chromium-browser",
504        "chrome",
505        "msedge",
506    ] {
507        if let Some(found) = find_in_path(candidate) {
508            return Ok(found);
509        }
510    }
511    for abs in [
512        "/usr/bin/google-chrome",
513        "/usr/bin/chromium",
514        "/usr/bin/chromium-browser",
515        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
516        "/Applications/Chromium.app/Contents/MacOS/Chromium",
517    ] {
518        let p = PathBuf::from(abs);
519        if p.is_file() {
520            return Ok(p);
521        }
522    }
523    #[cfg(windows)]
524    if let Some(found) = find_windows_browser_binary() {
525        return Ok(found);
526    }
527    Err(
528        "No headless Chrome or Chromium executable found (checked MERRY_CHROME_PATH, PATH, and standard system paths)."
529            .to_owned(),
530    )
531}
532
533#[cfg(windows)]
534fn find_windows_browser_binary() -> Option<PathBuf> {
535    let roots = [
536        std::env::var_os("PROGRAMFILES"),
537        std::env::var_os("PROGRAMFILES(X86)"),
538        std::env::var_os("LOCALAPPDATA"),
539    ];
540    let relative_candidates = [
541        r"Google\Chrome\Application\chrome.exe",
542        r"Chromium\Application\chrome.exe",
543        r"Microsoft\Edge\Application\msedge.exe",
544    ];
545    for root in roots.into_iter().flatten() {
546        let base = PathBuf::from(root);
547        for rel in relative_candidates {
548            let candidate = base.join(rel);
549            if candidate.is_file() {
550                return Some(candidate);
551            }
552        }
553    }
554    None
555}
556
557fn find_in_path(binary: &str) -> Option<PathBuf> {
558    let path_var = std::env::var_os("PATH")?;
559    merry_core::host_paths::find_executable_in_path(&path_var, &[binary], std::path::Path::is_file)
560}