//! The browser broker: the one process that holds Cotton's Chrome, and the //! only door to it. //! //! ## Why there is a broker at all //! //! Chrome's DevTools port is an unauthenticated TCP port. Loopback-only is not //! enough on a Mac with more than one account, or with any process of anyone's //! on it: whatever can open a socket to 127.0.0.1 can drive the signed-in //! browser — read every cookie, act on every signed-in site. So Cotton's //! Chrome has **no port at all**. It is started with //! `--remote-debugging-pipe`: its DevTools connection is two file descriptors //! (3 for what it reads, 4 for what it writes) held by exactly one process, //! this broker, which started it. //! //! The broker in turn listens only on a **Unix socket, `/browser/ //! run/broker.sock`, in a directory that is `0700`** — the filesystem says who //! may even reach it — and it also checks every connection's peer with //! `getpeereid`, refusing any user but its own. Each connection speaks //! WebSocket, as a DevTools client expects, and gets a browser session of its //! own ([`crate::browser_router`]), so one client's commands, answers and //! events never reach another. That is separation, not isolation: the //! browser and its signed-in profile are shared, and any client can list //! every tab and attach to it for itself (see the router's module doc). //! //! A session's agent reaches it through `browser mcp`'s relay //! ([`crate::browser_relay`]): a loopback listener that admits only a request //! carrying that session's token, and splices it to this socket. //! //! ## Lifetime //! //! Started on the first connection a relay makes ([`ensure_broker`]), //! detached into its own session (`setsid`) so no terminal's hang-up reaches //! it and it outlives the session that started it. It exits when Chrome does — //! the owner quitting Cotton's Chrome ends the broker, and the next tool call //! starts both again. A Chrome still running on the profile when a broker //! starts is an orphan (a broker that was killed, or a Chrome an older build //! started with a TCP port): it is stopped first, because Chrome's profile //! lock would otherwise hand the new launch to it and there would be no pipe. use std::collections::HashMap; use std::fs::File; use std::io::{BufRead as _, BufReader, Write as _}; use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd}; use std::os::unix::net::UnixStream; use std::path::{Path, PathBuf}; use std::process::{ExitCode, Stdio}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use futures_util::{SinkExt as _, StreamExt as _}; use tokio_tungstenite::tungstenite::Message; use crate::browser::{ check_profile, installed_chrome, lock, private_dir, profile_dir, CHROME_EXECUTABLE, LAUNCH_TIMEOUT, SINGLETON_LOCK, }; use crate::browser_router::{ClientId, FromClient, Router}; use crate::data_dir::{Layout, DATA_DIR_ENV}; /// One Chrome profile a broker holds: the agents' browser tool's own, or one /// signed-in account of a site the browser-session source reads (owner ruling /// 7 Oct 2026: one profile per account, under `/browser-profiles/ /// //`). Each has its own broker, socket and lock, so a /// session's agent never reaches an account's profile, nor one account /// another's. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Profile { /// The private directory everything else lives under. pub home: PathBuf, /// Chrome's `--user-data-dir`. pub profile: PathBuf, /// The broker's socket, locks and log; `0700`. pub run: PathBuf, /// `/` for an account's profile; `None` for the tool's. pub account: Option, } impl Profile { /// The browser tool's profile, `/browser/chrome-profile`. pub fn tool(layout: &Layout) -> Profile { Profile { home: layout.browser_dir(), profile: profile_dir(layout), run: layout.browser_dir().join("run"), account: None, } } /// One account's profile: `/browser-profiles/// /// chrome`, its broker's socket under `browser-profiles/_run//`. A site or account that is not a plain /// name (letters, digits, `.`, `_`, `-`) is refused, so neither can climb /// out of the directory. pub fn account(layout: &Layout, site: &str, account: &str) -> Result { let plain = |name: &str| { !name.is_empty() && name.len() <= 64 && !name.starts_with(['.', '_']) && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) }; if !plain(site) || !plain(account) { return Err(format!("{site}/{account} is not a site and account name")); } let pair = format!("{site}/{}", account.to_ascii_lowercase()); let profiles = layout.root().join("browser-profiles"); // The socket's directory is named by a digest of the pair, not the // pair: a 30-character handle under a long home would pass the 103 // bytes a socket path may hold. let digest = { use sha2::Digest as _; let sum = sha2::Sha256::digest(pair.as_bytes()); sum.iter().take(5).map(|byte| format!("{byte:02x}")).collect::() }; let home = profiles.join(site).join(account.to_ascii_lowercase()); Ok(Profile { profile: home.join("chrome"), run: profiles.join("_run").join(digest), home, account: Some(pair), }) } /// `/` as `browser broker --profile` takes it. pub fn parse(layout: &Layout, flag: Option<&str>) -> Result { match flag { None => Ok(Profile::tool(layout)), Some(pair) => { let (site, account) = pair.split_once('/').ok_or("--profile takes /")?; Profile::account(layout, site, account) } } } pub fn socket(&self) -> PathBuf { self.run.join("broker.sock") } pub fn connect(&self) -> Option { UnixStream::connect(self.socket()).ok() } } /// `/browser/run` — the broker's socket, locks and log; `0700`. pub fn run_dir(layout: &Layout) -> PathBuf { Profile::tool(layout).run } /// The broker's Unix socket. pub fn socket_path(layout: &Layout) -> PathBuf { Profile::tool(layout).socket() } /// The longest socket path macOS can bind: `sun_path` holds 104 bytes, /// the last of them the terminating NUL. pub const SOCKET_PATH_MAX: usize = 103; /// Refuse a socket path too long to bind, by name, before anything waits on /// a broker that could never answer. pub fn check_socket_path(socket: &Path) -> Result<(), String> { let length = socket.as_os_str().len(); if length > SOCKET_PATH_MAX { return Err(format!( "{} is {length} bytes, and a Unix socket's path can be at most {SOCKET_PATH_MAX} — the data directory is too deep for the browser broker", socket.display() )); } Ok(()) } /// How long a client has to be given its browser session. const ATTACH_TIMEOUT: Duration = Duration::from_secs(10); /// Chrome's command line: the executable itself (the broker must be its /// parent to hand it the pipe), and never a port. /// /// `extra` (what follows `browser broker --`; the tests pass `--headless`) /// can never bring one back: any `--remote-debugging-*` switch in it — /// `-port`, `-address`, a second `-pipe` — is dropped, so no command line, /// however the broker is started, opens Chrome's DevTools on TCP. pub fn chrome_argv(executable: &Path, profile: &Path, extra: &[String]) -> Vec { let mut argv = vec![ executable.display().to_string(), format!("--user-data-dir={}", profile.display()), // THE PIPE, and no `--remote-debugging-port` of any value (module doc). "--remote-debugging-pipe".to_string(), "--no-first-run".to_string(), "--no-default-browser-check".to_string(), ]; argv.extend( extra .iter() .filter(|arg| !arg.trim_start_matches('-').starts_with("remote-debugging")) .cloned(), ); argv } /// Whether a peer the kernel names may use the broker: only this user. /// A peer whose credentials cannot be read is refused. pub fn admits(peer_uid: std::io::Result, me: libc::uid_t) -> bool { matches!(peer_uid, Ok(uid) if uid == me) } /// A connection to the running broker, if there is one. pub fn connect(layout: &Layout) -> Option { Profile::tool(layout).connect() } /// Make sure the broker (and so Chrome) is running, starting it if not; /// the socket to dial. /// /// `host_binary` is this binary — the broker is `cotton-session-host browser /// broker`. `extra` is passed on to Chrome (the tests run it headless). /// Under `run/launch.lock`, so two sessions calling together start one broker. pub fn ensure_broker( layout: &Layout, home: &str, host_binary: &Path, extra: &[String], ) -> Result { ensure_profile(layout, &Profile::tool(layout), home, host_binary, extra) } /// [`ensure_broker`] for any [`Profile`]. pub fn ensure_profile( layout: &Layout, held: &Profile, home: &str, host_binary: &Path, extra: &[String], ) -> Result { let socket = held.socket(); if held.connect().is_some() { return Ok(socket); } check_socket_path(&socket)?; check_profile(&held.profile, home)?; if held.account.is_some() { private_dir(&layout.root().join("browser-profiles"))?; if let Some(site) = held.home.parent() { private_dir(site)?; } } private_dir(&held.home)?; if let Some(runs) = held.run.parent().filter(|_| held.account.is_some()) { private_dir(runs)?; } private_dir(&held.run)?; let _lock = lock(&held.run.join("launch.lock"))?; if held.connect().is_some() { return Ok(socket); } let log = std::fs::OpenOptions::new() .create(true) .append(true) .open(held.run.join("broker.log")) .map_err(|error| format!("the broker's log could not be opened — {error}"))?; let mut command = std::process::Command::new(host_binary); command .args(["browser", "broker"]) .args(held.account.iter().flat_map(|pair| ["--profile".to_string(), pair.clone()])) .arg("--") .args(extra) .env(DATA_DIR_ENV, layout.root()) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(log); // SAFETY: `setsid` is async-signal-safe and touches only the child. unsafe { std::os::unix::process::CommandExt::pre_exec(&mut command, || { if libc::setsid() < 0 { return Err(std::io::Error::last_os_error()); } Ok(()) }); } let mut child = command .spawn() .map_err(|error| format!("the browser broker could not start — {error}"))?; // Reaped here, so a broker that exits while this process lives is never // left a zombie; it is not waited on otherwise. std::thread::spawn(move || { let _ = child.wait(); }); let deadline = Instant::now() + LAUNCH_TIMEOUT; while Instant::now() < deadline { if held.connect().is_some() { return Ok(socket); } std::thread::sleep(Duration::from_millis(100)); } Err(format!( "the browser broker did not answer on {} within {}s — see {}", socket.display(), LAUNCH_TIMEOUT.as_secs(), held.run.join("broker.log").display() )) } /// A pipe whose two ends close on exec. fn pipe() -> Result<(OwnedFd, OwnedFd), String> { let mut fds = [0; 2]; // SAFETY: `fds` has room for the two descriptors `pipe` writes. if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 { return Err(format!("a pipe could not be made — {}", std::io::Error::last_os_error())); } for fd in fds { // SAFETY: `fd` was just returned by `pipe` and is open. unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) }; } // SAFETY: both are open, and owned by nothing else. Ok(unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }) } /// The pid of an orphan Chrome to stop: the one `lock_target` (the profile's /// `SingletonLock`, `-`) names, ONLY while the process table shows /// that pid running Google Chrome's executable. /// /// The lock outlives a Chrome that crashed, and its pid is soon another /// process's — the owner's editor, a build — which must never be signalled. pub fn orphan_pid(lock_target: &str, rows: &[crate::processes::ProcessRow]) -> Option { let pid = crate::browser::parse_singleton_lock(lock_target)?; rows.iter() .find(|row| row.pid == pid) .filter(|row| row.command.ends_with(CHROME_EXECUTABLE)) .map(|row| row.pid) } /// Stop a Chrome still running on `profile` (module doc: an orphan). fn stop_orphan(profile: &Path) { let Ok(target) = std::fs::read_link(profile.join(SINGLETON_LOCK)) else { return }; let rows = crate::processes::snapshot(); let Some(pid) = orphan_pid(&target.to_string_lossy(), &rows) else { return }; let Ok(pid) = libc::pid_t::try_from(pid) else { return }; let alive = |pid| unsafe { libc::kill(pid, 0) } == 0; if !alive(pid) { return; } eprintln!("browser broker: stopping the Chrome (pid {pid}) left running on the profile"); // SAFETY: signalling a pid; the worst case is a pid that has just gone. unsafe { libc::kill(pid, libc::SIGTERM) }; let deadline = Instant::now() + Duration::from_secs(5); while alive(pid) && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(100)); } if alive(pid) { unsafe { libc::kill(pid, libc::SIGKILL) }; } } /// What the broker's tasks share. struct Shared { router: Router, clients: HashMap>, waiters: HashMap>>, next_client: ClientId, } type State = Arc>; fn locked(state: &State) -> std::sync::MutexGuard<'_, Shared> { state.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } /// One message from Chrome, routed. fn from_chrome(state: &State, text: &str) { let mut shared = locked(state); let routed = shared.router.from_chrome(text); for (client, message) in routed.deliveries { if let Some(sender) = shared.clients.get(&client) { let _ = sender.send(message); } } if let Some((client, result)) = routed.attached { if let Some(waiter) = shared.waiters.remove(&client) { let _ = waiter.send(result); } } } /// `cotton-session-host browser profile-up --profile / /// [--visible] [--url ]` — the browser-session source's one door to an /// account's profile. Headless for reading; `--visible` puts the profile on /// this Mac's screen for the person to sign in once, so a headless Chrome /// already holding it is stopped first (a running Chrome cannot change into a /// window), and the next read starts it headless again once the person has /// closed it. Prints the broker's socket. pub async fn profile_up( layout: &Layout, held: &Profile, home: &str, host_binary: &Path, visible: bool, url: Option<&str>, ) -> Result { if held.account.is_none() { return Err("profile-up is for an account's profile".into()); } if visible && held.connect().is_some() { stop_orphan(&held.profile); let deadline = Instant::now() + Duration::from_secs(10); while held.connect().is_some() && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(100)); } } let extra: Vec = if visible { Vec::new() } else { vec!["--headless=new".into()] }; let socket = ensure_profile(layout, held, home, host_binary, &extra)?; if let Some(url) = url { let made = command_at(held, "Target.createTarget", serde_json::json!({ "url": url })).await?; // The sign-in page comes to the front of the person's screen — a // Chrome a background service started, or one already open behind // other windows, would otherwise wait unseen. if let (true, Some(target)) = (visible, made["targetId"].as_str()) { command_at(held, "Target.activateTarget", serde_json::json!({ "targetId": target })).await?; } } Ok(socket) } /// Whether `cookies` (Chrome's `Storage.getCookies` answer) hold a live /// cookie named `name` for `host` or a parent domain of it. Presence is the /// whole answer: the caller never learns a cookie's value, nor the names of /// any other cookie the profile holds. pub fn holds_session(cookies: &serde_json::Value, host: &str, name: &str, now_secs: f64) -> bool { let host = host.trim_end_matches('.').to_ascii_lowercase(); cookies.as_array().into_iter().flatten().any(|cookie| { let domain = cookie["domain"].as_str().unwrap_or("").trim_start_matches('.').to_ascii_lowercase(); let live = match cookie["expires"].as_f64() { // -1 (or none) is a session cookie: live while the profile runs. None => true, Some(at) => at <= 0.0 || at > now_secs, }; cookie["name"].as_str() == Some(name) && !domain.is_empty() && (host == domain || host.ends_with(&format!(".{domain}"))) && cookie["value"].as_str().is_some_and(|v| !v.is_empty()) && live }) } /// `cotton-session-host browser has-session --profile / /// --domain --cookie ` — whether the account's profile holds a /// live `name` cookie for `host`: `yes` or `no`, and nothing else ever /// leaves the broker. A profile not running is started headless; one open on /// the person's screen is asked as it is, never closed. pub async fn has_session( layout: &Layout, held: &Profile, home: &str, host_binary: &Path, domain: &str, cookie: &str, ) -> Result { profile_up(layout, held, home, host_binary, false, None).await?; let answer = command_at(held, "Storage.getCookies", serde_json::json!({})).await?; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs_f64()) .unwrap_or(0.0); Ok(holds_session(&answer["cookies"], domain, cookie, now)) } /// `cotton-session-host browser broker [-- ]`. pub async fn run(layout: &Layout, home: &str, extra: &[String]) -> ExitCode { run_profile(&Profile::tool(layout), home, extra).await } /// `cotton-session-host browser broker --profile / [-- …]`. pub async fn run_profile(held: &Profile, home: &str, extra: &[String]) -> ExitCode { match serve(held, home, extra).await { Ok(()) => ExitCode::SUCCESS, Err(error) => { eprintln!("browser broker: {error}"); ExitCode::FAILURE } } } async fn serve(held: &Profile, home: &str, extra: &[String]) -> Result<(), String> { let app = installed_chrome(home) .ok_or("Google Chrome is not installed in /Applications or ~/Applications")?; let profile = held.profile.clone(); check_profile(&profile, home)?; private_dir(&held.home)?; private_dir(&profile)?; if let Some(runs) = held.run.parent().filter(|_| held.account.is_some()) { private_dir(runs)?; } private_dir(&held.run)?; // ONE broker per profile, held for the broker's life. A second one exits // quietly: the first is serving. let lock_file = File::create(held.run.join("broker.lock")) .map_err(|error| format!("the broker lock could not be opened — {error}"))?; // SAFETY: `lock_file` is an open descriptor this function owns. if unsafe { libc::flock(lock_file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { return Ok(()); } stop_orphan(&profile); let socket = held.socket(); let _ = std::fs::remove_file(&socket); let listener = tokio::net::UnixListener::bind(&socket) .map_err(|error| format!("{} could not be bound — {error}", socket.display()))?; { use std::os::unix::fs::PermissionsExt as _; // The directory already keeps everyone else out; the socket says so too. std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600)) .map_err(|error| format!("{} could not be made private — {error}", socket.display()))?; } // The pipe: Chrome reads fd 3 and writes fd 4. let (chrome_reads, broker_writes) = pipe()?; let (broker_reads, chrome_writes) = pipe()?; let argv = chrome_argv(&app.join(CHROME_EXECUTABLE), &profile, extra); let mut command = tokio::process::Command::new(&argv[0]); command .args(&argv[1..]) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()); let (read_fd, write_fd) = (chrome_reads.as_raw_fd(), chrome_writes.as_raw_fd()); // SAFETY: only async-signal-safe calls. The two ends are first duplicated // ABOVE 10, so that placing one on 3 can never close the other when it // happens to be 3 or 4 already; `dup2` clears close-on-exec on 3 and 4. unsafe { command.pre_exec(move || { let read = libc::fcntl(read_fd, libc::F_DUPFD_CLOEXEC, 10); let write = libc::fcntl(write_fd, libc::F_DUPFD_CLOEXEC, 10); if read < 0 || write < 0 || libc::dup2(read, 3) < 0 || libc::dup2(write, 4) < 0 { return Err(std::io::Error::last_os_error()); } Ok(()) }); } let mut chrome = command .spawn() .map_err(|error| format!("Chrome could not be started — {error}"))?; drop((chrome_reads, chrome_writes)); eprintln!( "browser broker: Chrome (pid {}) started on {} with the DevTools pipe", chrome.id().unwrap_or_default(), profile.display() ); let state: State = Arc::new(Mutex::new(Shared { router: Router::new(), clients: HashMap::new(), waiters: HashMap::new(), next_client: 0, })); // Down the pipe: one writer, messages NUL-terminated. let (to_chrome, outbox) = std::sync::mpsc::channel::(); std::thread::spawn(move || { let mut pipe = File::from(broker_writes); for message in outbox { if pipe.write_all(message.as_bytes()).and_then(|()| pipe.write_all(b"\0")).is_err() { break; } } }); // Up the pipe: every message routed; the end of the pipe is Chrome gone. let (gone_tx, mut gone) = tokio::sync::mpsc::unbounded_channel::<&'static str>(); { let state = state.clone(); let gone_tx = gone_tx.clone(); std::thread::spawn(move || { let mut pipe = BufReader::new(File::from(broker_reads)); let mut message = Vec::new(); loop { message.clear(); match pipe.read_until(0, &mut message) { Ok(0) | Err(_) => break, Ok(_) => { if message.last() == Some(&0) { message.pop(); } from_chrome(&state, &String::from_utf8_lossy(&message)); } } } let _ = gone_tx.send("Chrome closed the DevTools pipe"); }); } tokio::spawn(async move { let _ = chrome.wait().await; let _ = gone_tx.send("Chrome exited"); }); // SAFETY: `geteuid` cannot fail. let me = unsafe { libc::geteuid() }; loop { tokio::select! { why = gone.recv() => { eprintln!("browser broker: {} — stopping", why.unwrap_or("Chrome is gone")); let _ = std::fs::remove_file(&socket); return Ok(()); } accepted = listener.accept() => { let Ok((stream, _)) = accepted else { continue }; // THE PEER'S USER, from the kernel: the directory's mode already // keeps other users out, and this holds even if it were widened. if !admits(stream.peer_cred().map(|peer| peer.uid()), me) { continue; } tokio::spawn(client(stream, state.clone(), to_chrome.clone())); } } } } /// One client: its WebSocket, its browser session, its messages both ways. async fn client( stream: tokio::net::UnixStream, state: State, to_chrome: std::sync::mpsc::Sender, ) { let Ok(socket) = tokio_tungstenite::accept_async(stream).await else { return }; let (mut sink, mut incoming) = socket.split(); let (sender, mut outbox) = tokio::sync::mpsc::unbounded_channel::(); let (waiter, attached) = tokio::sync::oneshot::channel(); let id = { let mut shared = locked(&state); shared.next_client += 1; let id = shared.next_client; shared.clients.insert(id, sender.clone()); shared.waiters.insert(id, waiter); let _ = to_chrome.send(shared.router.attach(id)); id }; let writer = tokio::spawn(async move { while let Some(message) = outbox.recv().await { if sink.send(Message::text(message)).await.is_err() { break; } } let _ = sink.close().await; }); if let Ok(Ok(Ok(()))) = tokio::time::timeout(ATTACH_TIMEOUT, attached).await { while let Some(Ok(message)) = incoming.next().await { let text = match message { Message::Text(text) => text.to_string(), Message::Binary(bytes) => String::from_utf8_lossy(&bytes).to_string(), Message::Close(_) => break, _ => continue, }; let action = locked(&state).router.from_client(id, &text); match action { FromClient::ToChrome(message) => { let _ = to_chrome.send(message); } FromClient::ToClient(message) => { let _ = sender.send(message); } } } } { let mut shared = locked(&state); shared.clients.remove(&id); shared.waiters.remove(&id); for command in shared.router.detach(id) { let _ = to_chrome.send(command); } } drop(sender); writer.abort(); } /// Send one CDP command as a client of the running broker and return its /// answer — `browser open` uses it to open a tab. pub async fn command( layout: &Layout, method: &str, params: serde_json::Value, ) -> Result { command_at(&Profile::tool(layout), method, params).await } /// [`command`] against any [`Profile`]'s broker. pub async fn command_at( held: &Profile, method: &str, params: serde_json::Value, ) -> Result { let stream = tokio::net::UnixStream::connect(held.socket()) .await .map_err(|error| format!("the browser broker is not answering — {error}"))?; let (mut socket, _) = tokio_tungstenite::client_async("ws://localhost/devtools/browser", stream) .await .map_err(|error| format!("the browser broker refused the connection — {error}"))?; let request = serde_json::json!({ "id": 1, "method": method, "params": params }); socket .send(Message::text(request.to_string())) .await .map_err(|error| format!("the command could not be sent — {error}"))?; let deadline = tokio::time::Instant::now() + LAUNCH_TIMEOUT; loop { let next = tokio::time::timeout_at(deadline, socket.next()) .await .map_err(|_| format!("{method} was not answered in time"))?; let Some(Ok(Message::Text(text))) = next else { return Err(format!("the broker closed before answering {method}")); }; let answer: serde_json::Value = serde_json::from_str(&text).unwrap_or_default(); if answer.get("id") == Some(&serde_json::Value::from(1)) { let _ = socket.close(None).await; return match answer.get("error") { Some(error) => Err(format!("{method} failed: {error}")), None => Ok(answer.get("result").cloned().unwrap_or_default()), }; } } } #[cfg(test)] #[path = "browser_broker_tests.rs"] mod tests;