Cotton code
526 lines · 23.7 KB · RustRaw
//! The browser tool: ONE Google Chrome on this Mac, on a profile Cotton owns,//! which every hosted session can drive over the DevTools protocol.//!//! What it is for is the work that has no API — App Store Connect, Play//! Console, a provider's sign-in page — done by an agent in a real browser//! that stays signed in between sessions.//!//! ## The shape, and why each part is the way it is//!//! - **The profile is `<dataDir>/browser/chrome-profile`, never Chrome's own//!   default directory.** Since Chrome 136, `--remote-debugging-port` is//!   ignored on the default user-data directory (a security change by the//!   Chrome team: a debugging port on the everyday profile hands its cookies//!   to anything on the machine). Chrome does not fail when that happens — it//!   starts, and the port never opens. So the profile is a directory this//!   host owns, which the owner signs into once and which keeps its logins//!   from then on. Nothing is copied from the default profile: its cookies//!   are encrypted with that profile's own key, and copying them would be the//!   very thing Chrome's change exists to stop. [`check_profile`] refuses the//!   default directory by name, so the silent failure is a sentence instead.//! - **No DevTools port at all.** Chrome's port is unauthenticated: any//!   process of any user on the Mac that can open a socket to 127.0.0.1 could//!   drive the signed-in browser. So Chrome is started with//!   `--remote-debugging-pipe` by the browser broker//!   ([`crate::browser_broker`]), which holds the pipe and is the only door://!   a Unix socket in an owner-only directory, each client confined to a//!   browser session of its own ([`crate::browser_router`]).//! - **Owner-only on disk.** `<dataDir>/browser` and the profile are `0700`//!   ([`private_dir`]), set on every start, not only on creation: the data//!   directory itself is world-readable, and a profile holds a signed-in//!   browser's local storage and history in plain files.//! - **The agent-side tool is `chrome-devtools-mcp`, pinned by version AND by//!   digest** — the Chrome team's own MCP server, not a client written here.//!   Not `npx`: npx resolves a package through whatever `.npmrc` and//!   `node_modules` the session's working directory holds, so a repository an//!   agent opens could name its own registry, or ship its own//!   "chrome-devtools-mcp@1.10.1", and have it run — at session start, before//!   the agent did anything — holding the signed-in browser. Instead//!   [`ensure_package`] fetches the one tarball from the npm registry by URL,//!   refuses it unless its sha512 is [`PACKAGE_SHA512`], unpacks it under//!   `<dataDir>/browser`, and `node` runs it from there, in that directory. The//!   package has no runtime dependencies, so the digest covers every line//!   that runs. It dials a WebSocket URL (`--wsEndpoint`) and connects//!   lazily, on the first tool call.//! - **A session gets it as one MCP server, `cotton-browser`, whose command//!   is this binary: `cotton-session-host browser mcp`.** [`run_mcp`] mints a//!   token for the session, opens the session's relay//!   ([`crate::browser_relay`]) on `127.0.0.1:0` — which admits only that//!   token — and starts `chrome-devtools-mcp` pointed at it, with the token in//!   its environment, never its argv. The handshake never waits on Chrome.//!   **Chrome starts LAZILY**: the first connection the server makes through//!   the relay (its first tool call) starts the broker, and the broker starts//!   Chrome — so a session that never touches the browser never starts one,//!   and a Chrome the owner quit stays quit until an agent next asks for it.//!   Every session shares the one Chrome through the one broker.//! - **The budget counts it** ([`budget`]): Chrome is the detached broker's//!   child, not a session's, so no session's process tree holds it. It is measured as its//!   own tree with its own peak, and while a live session could start it,//!   [`DECLARED_GB`] (or its measured peak) is held back as headroom.//!   (Each session has its own browser session in the broker, so one//!   session's commands and events never reach another's — but every session//!   can list and attach to every tab: the profile is shared, not isolated.)//! - **Chrome is the broker's child**, and the broker runs in a session of//!   its own (`setsid`): no terminal's hang-up reaches either, and they//!   outlive the session that started them.//! - **Offered only where it can work** ([`offer`]): Chrome installed in one//!   of the two places a Mac installs it, and `node` on the login PATH. A Mac//!   without either gets sessions exactly as before, with no browser server//!   that would fail on its first call.//!//! **What this deliberately is not**: a sign-in robot. The owner signs the//! profile in once, at the Mac (`cotton-session-host browser open <url>`, or//! an agent driving the window). Logins from the vault come later, once the//! passwords are in it; other Macs and a button on the phone come later too.use std::collections::BTreeMap;use std::fs::{File, OpenOptions};use std::path::{Path, PathBuf};use std::process::{Command, ExitCode, Stdio};use std::sync::Arc;use std::time::Duration;use crate::data_dir::{Flavor, Layout, DATA_DIR_ENV, FLAVOR_ENV};use crate::login_env::{resolve_program, LoginEnv};use crate::processes::{rss_gb, tree, ProcessRow};/// The MCP server's name in a session — its tools are `mcp__cotton-browser__…`.pub const MCP_SERVER_NAME: &str = "cotton-browser";/// The agent-side tool, pinned to the version this module was verified with.////// PINNED, not `@latest`: `--wsEndpoint` with `--wsHeaders`, and a lazy/// connect on the first tool call, are behaviour read out of this version's/// source, and a new version is a change to be made on purpose, with the/// real-Chrome test run again — and with [`PACKAGE_URL`] and/// [`PACKAGE_SHA512`] changed beside it.pub const CHROME_DEVTOOLS_MCP: &str = "chrome-devtools-mcp@1.10.1";/// The one tarball [`CHROME_DEVTOOLS_MCP`] is, on the npm registry.pub const PACKAGE_URL: &str =    "https://registry.npmjs.org/chrome-devtools-mcp/-/chrome-devtools-mcp-1.10.1.tgz";/// That tarball's digest, in npm's own `integrity` form — what/// `npm view chrome-devtools-mcp@1.10.1 dist.integrity` prints, and what a/// download must hash to before a byte of it is unpacked.pub const PACKAGE_SHA512: &str = "sha512-Klw6HWDqHC/XS1JwZldd2r49aUhbUJN9m9Mvcx4SEueIPXtzuQX+QelxAViobv8YUkDZ7HWDrmViR6LeYK0wAw==";/// The server's entry point inside the unpacked tarball (its `bin`).pub const PACKAGE_ENTRY: &str = "package/build/src/bin/chrome-devtools-mcp.js";/// Where Chrome is installed on a Mac, relative to `/` and to `$HOME`.pub const CHROME_APP: &str = "Applications/Google Chrome.app";/// The executable inside [`CHROME_APP`].pub const CHROME_EXECUTABLE: &str = "Contents/MacOS/Google Chrome";/// Chrome's own default profile directory, relative to `$HOME` — the one/// directory the browser tool must never use.pub const DEFAULT_CHROME_DIR: &str = "Library/Application Support/Google/Chrome";/// How long the broker has to start and answer on its socket.////// Twenty seconds: a cold broker and Chrome on a busy Mac answer in about a/// second, so this is only ever reached by one that is not going to.pub const LAUNCH_TIMEOUT: Duration = Duration::from_secs(20);/// What Chrome is declared to cost before it has ever been measured, in/// gigabytes: the browser process, its GPU and network helpers and a few/// renderers for the consoles an agent works in. Once measured, the larger of/// this and the measured peak is what the budget holds back.pub const DECLARED_GB: f64 = 1.0;/// The profile's lock, a symlink Chrome points at `<hostname>-<pid>` while it/// runs on the profile.pub const SINGLETON_LOCK: &str = "SingletonLock";/// How long Codex waits for the server's handshake.////// A minute rather than Codex's ten-second default, because the FIRST start/// on a Mac downloads and checks the pinned package ([`ensure_package`]).pub const MCP_STARTUP_TIMEOUT_SECONDS: u64 = 60;/// Cotton's own Chrome profile — [`Layout::browser_profile`].pub fn profile_dir(layout: &Layout) -> PathBuf {    layout.browser_profile()}/// Where Chrome is on this Mac: `/Applications` first, then `~/Applications`.////// The `.app` BUNDLE; the broker runs [`CHROME_EXECUTABLE`] inside it. `exists`/// is the test's seam; the real one asks whether the executable inside is one.pub fn find_chrome(home: &str, exists: impl Fn(&Path) -> bool) -> Option<PathBuf> {    let mut candidates = vec![Path::new("/").join(CHROME_APP)];    if !home.is_empty() {        candidates.push(Path::new(home).join(CHROME_APP));    }    candidates        .into_iter()        .find(|app| exists(&app.join(CHROME_EXECUTABLE)))}/// Chrome as it really is on this Mac.pub fn installed_chrome(home: &str) -> Option<PathBuf> {    find_chrome(home, |executable| {        resolve_program("", &executable.display().to_string()).is_some()    })}/// Refuse a profile that is, or is inside, or holds Chrome's default one.////// **The silent failure made loud.** Chrome 136 and later start normally on/// the default directory and simply ignore the debugging switches (the pipe/// as much as the port), so the only way a person hears about it is this/// sentence. Compared by path components, not/// through the filesystem, so it holds before either directory exists.pub fn check_profile(profile: &Path, home: &str) -> Result<(), String> {    if !profile.is_absolute() {        return Err(format!(            "the browser profile must be an absolute path, not {}",            profile.display()        ));    }    if home.is_empty() {        return Ok(());    }    let default = Path::new(home).join(DEFAULT_CHROME_DIR);    if profile.starts_with(&default) || default.starts_with(profile) {        return Err(format!(            "{} is Chrome's own default profile directory — Chrome ignores the \             debugging port there, and the browser tool never uses it",            profile.display()        ));    }    Ok(())}/// When the browser tool can be offered on this Mac, what it needs.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Offer {    /// The data directory the server resolves its profile under — handed to    /// it in [`DATA_DIR_ENV`], so a host with an overridden data directory    /// and the server it starts agree on one profile.    pub data_dir: String,    /// The host's selected flavor, independent of an agent's environment.    pub flavor: Flavor,}/// Whether this Mac can offer the browser tool: Chrome installed, and `node`/// on the login PATH to run [`CHROME_DEVTOOLS_MCP`] with.////// An empty login environment (a test's) has no HOME and offers nothing.pub fn offer(env: &LoginEnv, data_dir: &Path, flavor: Flavor) -> Option<Offer> {    let home = env.get("HOME").filter(|home| !home.is_empty())?;    installed_chrome(home)?;    resolve_program(env.path(), "node")?;    Some(Offer {        data_dir: data_dir.display().to_string(),        flavor,    })}/// One MCP server, as both agents' configurations describe one.#[derive(Debug, Clone, PartialEq, Eq)]pub struct McpServer {    /// The server's name in the session.    pub name: String,    /// The program — an absolute path.    pub command: String,    /// Its arguments.    pub args: Vec<String>,    /// Environment on top of the session's.    pub env: BTreeMap<String, String>,}/// The browser tool as a session's MCP server: this binary, `browser mcp`.////// ONE definition, which both adapters render into their own syntax.pub fn mcp_server(host_binary: &str, offer: &Offer) -> McpServer {    McpServer {        name: MCP_SERVER_NAME.to_string(),        command: host_binary.to_string(),        args: vec!["browser".to_string(), "mcp".to_string()],        env: BTreeMap::from([            (DATA_DIR_ENV.to_string(), offer.data_dir.clone()),            (FLAVOR_ENV.to_string(), offer.flavor.as_str().to_string()),        ]),    }}/// The `chrome-devtools-mcp` command line `browser mcp` runs: `node` on the/// relay's shim, which imports the entry point [`ensure_package`] unpacked/// and checked, dialing this session's relay.////// NO TOKEN HERE: the command line is readable by every user on the Mac. It/// travels in [`crate::browser_relay::TOKEN_ENV`].pub fn devtools_mcp_argv(node: &str, shim: &Path, entry: &Path, relay_port: u16) -> Vec<String> {    vec![        node.to_string(),        shim.display().to_string(),        entry.display().to_string(),        "--wsEndpoint".to_string(),        format!("ws://127.0.0.1:{relay_port}/devtools/browser"),        // The owner's signed-in browser reports nothing to anyone: no usage        // statistics, and no page URLs sent to the CrUX API from a trace.        "--no-usage-statistics".to_string(),        "--no-performance-crux".to_string(),    ]}/// Environment the server runs with, on top of the session's: no daily/// `npm view chrome-devtools-mcp` in a child process (it only ever prints an/// "update available" line — the version is pinned here on purpose).pub const DEVTOOLS_MCP_ENV: [(&str, &str); 1] = [("CHROME_DEVTOOLS_MCP_NO_UPDATE_CHECKS", "1")];/// Make `dir` (and any missing parents) exist, and make `dir` itself `0700`.////// Every time, not only when it is created: a directory made by an earlier/// build, or by hand, under the default umask is `0755`.pub fn private_dir(dir: &Path) -> Result<(), String> {    use std::os::unix::fs::PermissionsExt as _;    std::fs::create_dir_all(dir)        .map_err(|error| format!("{} could not be made — {error}", dir.display()))?;    std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))        .map_err(|error| format!("{} could not be made private — {error}", dir.display()))}/// Whether `bytes` hash to `integrity`, an npm `sha512-<base64>` string.pub fn integrity_matches(bytes: &[u8], integrity: &str) -> bool {    use base64::Engine as _;    use sha2::Digest as _;    let actual = base64::engine::general_purpose::STANDARD.encode(sha2::Sha512::digest(bytes));    integrity.strip_prefix("sha512-") == Some(actual.as_str())}/// Where the checked package is unpacked: `<dataDir>/browser/<name@version>`.pub fn package_dir(layout: &Layout) -> PathBuf {    layout.browser_dir().join(CHROME_DEVTOOLS_MCP)}/// The pinned `chrome-devtools-mcp`, unpacked and ready for `node` — fetched/// the first time, and only ever from [`PACKAGE_URL`] at [`PACKAGE_SHA512`].////// The download goes to a file beside the package, is hashed IN FULL before/// anything is unpacked, and a tarball that does not match is deleted and/// refused. It is unpacked into a scratch directory and renamed into place,/// so a half-unpacked package is never found as a whole one.pub fn ensure_package(layout: &Layout) -> Result<PathBuf, String> {    let browser = layout.browser_dir();    private_dir(&browser)?;    let dir = package_dir(layout);    let entry = dir.join(PACKAGE_ENTRY);    if entry.is_file() {        return Ok(entry);    }    let _lock = lock(&browser.join("package.lock"))?;    if entry.is_file() {        return Ok(entry);    }    let pid = std::process::id();    let tarball = browser.join(format!("download-{pid}.tgz"));    let scratch = browser.join(format!("unpack-{pid}"));    let result = fetch_and_unpack(&tarball, &scratch, &dir);    let _ = std::fs::remove_file(&tarball);    let _ = std::fs::remove_dir_all(&scratch);    result?;    if entry.is_file() {        Ok(entry)    } else {        Err(format!("{} holds no {PACKAGE_ENTRY}", dir.display()))    }}fn fetch_and_unpack(tarball: &Path, scratch: &Path, dir: &Path) -> Result<(), String> {    let status = Command::new("/usr/bin/curl")        .args(["-fsSL", "--proto", "=https", "--tlsv1.2", "-o"])        .arg(tarball)        .arg(PACKAGE_URL)        .stdin(Stdio::null())        .stdout(Stdio::null())        .status()        .map_err(|error| format!("curl could not be run — {error}"))?;    if !status.success() {        return Err(format!("{PACKAGE_URL} could not be downloaded — curl exited {status}"));    }    let bytes = std::fs::read(tarball)        .map_err(|error| format!("{} could not be read — {error}", tarball.display()))?;    if !integrity_matches(&bytes, PACKAGE_SHA512) {        return Err(format!(            "{PACKAGE_URL} is not the pinned {CHROME_DEVTOOLS_MCP}: its sha512 is not \             {PACKAGE_SHA512}, so it was deleted and nothing was run"        ));    }    let _ = std::fs::remove_dir_all(scratch);    private_dir(scratch)?;    let status = Command::new("/usr/bin/tar")        .arg("-xzf")        .arg(tarball)        .arg("-C")        .arg(scratch)        .stdin(Stdio::null())        .status()        .map_err(|error| format!("tar could not be run — {error}"))?;    if !status.success() {        return Err(format!("the checked {CHROME_DEVTOOLS_MCP} could not be unpacked"));    }    let _ = std::fs::remove_dir_all(dir);    std::fs::rename(scratch, dir)        .map_err(|error| format!("{} could not be put in place — {error}", dir.display()))}/// An exclusive `flock` on `path`, held until the file is dropped.pub(crate) fn lock(path: &Path) -> Result<File, String> {    use std::os::unix::io::AsRawFd as _;    let file = OpenOptions::new()        .create(true)        .truncate(false)        .write(true)        .open(path)        .map_err(|error| format!("{} could not be opened — {error}", path.display()))?;    // SAFETY: `file` is an open descriptor this function owns; `flock` only    // takes it. Blocking is the point — the other holder is a launch or a    // download that finishes within its own timeout.    if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {        return Err(format!("{} could not be locked", path.display()));    }    Ok(file)}/// `cotton-session-host browser mcp` — the MCP server a session is given.////// Mints the session's token, opens its relay, and runs `chrome-devtools-mcp`/// on the session's own stdin and stdout, pointed at the relay (module doc)./// The relay starts the broker — and so Chrome — on the server's first/// connection. Exits with the server's own code; the relay dies with it.////// A broker that will not start is SAID, on stderr (which the agent keeps in/// its MCP log), and the connection is answered 503: the server's "Could not/// connect to Chrome" is the truth, and the next call tries again.pub fn run_mcp(layout: &Layout, home: &str, path: &str) -> ExitCode {    match serve_mcp(layout, home, path) {        Ok(code) => code,        Err(error) => {            eprintln!("cotton-browser: {error}");            ExitCode::FAILURE        }    }}fn serve_mcp(layout: &Layout, home: &str, path: &str) -> Result<ExitCode, String> {    let node = resolve_program(path, "node")        .ok_or("`node` is not on this PATH, so chrome-devtools-mcp cannot run")?;    installed_chrome(home)        .ok_or("Google Chrome is not installed in /Applications or ~/Applications")?;    check_profile(&profile_dir(layout), home)?;    let entry = ensure_package(layout)?;    let shim = crate::browser_relay::write_shim(&layout.browser_dir())?;    let host = std::env::current_exe()        .map_err(|error| format!("this binary's own path is unknown — {error}"))?;    let token = crate::browser_relay::new_token()?;    let (dial_layout, dial_home) = (layout.clone(), home.to_string());    let dial: Arc<crate::browser_relay::Dial> = Arc::new(move || {        let socket =            crate::browser_broker::ensure_broker(&dial_layout, &dial_home, &host, &[])?;        std::os::unix::net::UnixStream::connect(&socket)            .map_err(|error| format!("the browser broker stopped answering — {error}"))    });    let port = crate::browser_relay::start(token.clone(), dial)?;    let argv = devtools_mcp_argv(&node.display().to_string(), &shim, &entry, port);    let status = Command::new(&argv[0])        .args(&argv[1..])        // Cotton's own directory, never the session's: nothing a repository        // holds is on the server's path to its own code.        .current_dir(layout.browser_dir())        .envs(DEVTOOLS_MCP_ENV)        .env(crate::browser_relay::TOKEN_ENV, &token)        .status()        .map_err(|error| format!("{} could not start — {error}", argv[0]))?;    let code = status.code().unwrap_or(1).clamp(0, 255);    Ok(ExitCode::from(u8::try_from(code).unwrap_or(1)))}/// The pid Chrome's [`SINGLETON_LOCK`] names — `<hostname>-<pid>`, split at/// the LAST hyphen, because a hostname may hold hyphens and a pid never does.pub fn parse_singleton_lock(target: &str) -> Option<u32> {    target.rsplit_once('-')?.1.parse().ok().filter(|pid| *pid > 0)}/// The pid of the Chrome running on `profile`, when the table has it.////// The lock outlives a Chrome that crashed, so a pid the process table does/// not hold is no Chrome at all.pub fn chrome_pid(profile: &Path, rows: &[ProcessRow]) -> Option<u32> {    let target = std::fs::read_link(profile.join(SINGLETON_LOCK)).ok()?;    let pid = parse_singleton_lock(&target.to_string_lossy())?;    rows.iter().any(|row| row.pid == pid).then_some(pid)}/// Chrome as the budget sees it: `(peak_gb, headroom_gb)`.////// `chrome` is its pid when it runs; `could_start` is whether a live session/// holds the tool, and so could start it with its next call.////// - **Running**: measured as its own tree (a Chrome's renderers and helpers///   are its children), the peak raised to what it holds, and the headroom is///   what it has been — or is declared — to want beyond that. Never negative./// - **Not running, but a session could start it**: the whole of the larger of///   its peak and [`DECLARED_GB`], because a single tool call brings it back./// - **Otherwise**: nothing — a Mac with no session holding the tool has not///   promised a browser to anyone.pub fn budget(    rows: &[ProcessRow],    chrome: Option<u32>,    could_start: bool,    peak_gb: f64,) -> (f64, f64) {    match chrome {        Some(pid) => {            let held = rss_gb(rows, &tree(rows, pid));            let peak = peak_gb.max(held);            (peak, (peak.max(DECLARED_GB) - held).max(0.0))        }        None if could_start => (peak_gb, peak_gb.max(DECLARED_GB)),        None => (peak_gb, 0.0),    }}/// `cotton-session-host browser open [url]` — start Cotton's Chrome and show/// `url` in it; how the owner signs the profile in, once.pub async fn run_open(layout: &Layout, home: &str, url: Option<&str>) -> ExitCode {    let started = std::env::current_exe()        .map_err(|error| format!("this binary's own path is unknown — {error}"))        .and_then(|host| crate::browser_broker::ensure_broker(layout, home, &host, &[]));    if let Err(error) = started {        eprintln!("{error}");        return ExitCode::FAILURE;    }    if let Some(url) = url {        let opened = crate::browser_broker::command(            layout,            "Target.createTarget",            serde_json::json!({ "url": url }),        )        .await;        if let Err(error) = opened {            eprintln!("{error}");            return ExitCode::FAILURE;        }    }    println!("Cotton's Chrome is running with the profile {}", profile_dir(layout).display());    ExitCode::SUCCESS}/// `cotton-session-host browser status` — what the tool would use, as JSON.pub fn status(layout: &Layout, home: &str) -> serde_json::Value {    serde_json::json!({        "chrome": installed_chrome(home).map(|app| app.display().to_string()),        "profile": profile_dir(layout).display().to_string(),        "running": crate::browser_broker::connect(layout).is_some(),        "broker": crate::browser_broker::socket_path(layout).display().to_string(),        "server": CHROME_DEVTOOLS_MCP,    })}#[cfg(test)]#[path = "browser_tests.rs"]mod browser_tests;