Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Browser: windowless Chrome sends the normal Chrome user agent

Lin (kwant bot)f6657d73c81c
diff --git a/docker/browser-entrypoint.sh b/docker/browser-entrypoint.sh
index 99873164..5e5175dd 100644
--- a/docker/browser-entrypoint.sh
+++ b/docker/browser-entrypoint.sh
@@ -1,7 +1,11 @@
#!/bin/sh
# Keep Chromium and its private network proxy in the same supervised container.
set -eu
-chromium --headless=new --no-sandbox --disable-dev-shm-usage \
+# Windowless Chromium tells sites it is "HeadlessChrome"; send the user agent the windowed
+# Chromium of this version sends instead.
+major=$(chromium --version | grep -oE '[0-9]+\.[0-9.]+' | head -n1 | cut -d. -f1)
+agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36"
+chromium --headless=new --no-sandbox --disable-dev-shm-usage --user-agent="$agent" \
--remote-debugging-port=9223 --remote-allow-origins='*' \
--window-size=1280,800 --user-data-dir=/tmp/kwnt-chromium about:blank &
chrome_pid=$!
diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rs
index b81794a8..cc9732f6 100644
--- a/src/sandbox/computer.rs
+++ b/src/sandbox/computer.rs
@@ -183,8 +183,9 @@ pub const HEADLESS_WINDOW_SIZE: &str = "1280,800";
/// Chrome's command line for local mode: its own profile, never the person's everyday one, and a
/// debugging port Chrome picks itself (it listens on 127.0.0.1). Without a window (`headless`)
-/// unless the person asked to see one.
-pub fn chrome_args(profile: &Path, headless: bool) -> Vec<String> {
+/// unless the person asked to see one. A windowless Chrome sends `user_agent` (see
+/// [`headed_user_agent`]) instead of its own, which tells every site it is "HeadlessChrome".
+pub fn chrome_args(profile: &Path, headless: bool, user_agent: Option<&str>) -> Vec<String> {
let mut args = vec![
format!("--user-data-dir={}", profile.display()),
"--remote-debugging-port=0".into(),
@@ -195,16 +196,69 @@ pub fn chrome_args(profile: &Path, headless: bool) -> Vec<String> {
if headless {
args.push("--headless=new".into());
args.push(format!("--window-size={HEADLESS_WINDOW_SIZE}"));
+ if let Some(agent) = user_agent {
+ args.push(format!("--user-agent={agent}"));
+ }
}
args.push("about:blank".into());
args
}
-/// Whether a running Chrome is windowless, from its `/json/version` user agent.
+/// The user agent Chrome sends with a window, for the Chrome whose `--version` printed
+/// `version_output` ("Google Chrome 131.0.6778.86", "Chromium 154.0.8037.92 built on ..."). Chrome
+/// fills it from a fixed template with the major version and a frozen platform, so this is the same
+/// string the windowed Chrome on `os` sends. `None` if no version is found.
+pub fn headed_user_agent(version_output: &str, os: &str) -> Option<String> {
+ let version = version_output
+ .split_whitespace()
+ .find(|word| word.split('.').count() >= 2 && word.split('.').all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))?;
+ let major = version.split('.').next()?;
+ let platform = match os {
+ "macos" => "Macintosh; Intel Mac OS X 10_15_7",
+ "windows" => "Windows NT 10.0; Win64; x64",
+ _ => "X11; Linux x86_64",
+ };
+ Some(format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36"))
+}
+
+/// [`headed_user_agent`] for the Chrome at `chrome`, from its `--version`. Not on Windows, where
+/// `chrome.exe --version` opens the browser instead of printing.
+pub fn chrome_user_agent(chrome: &Path) -> Option<String> {
+ if cfg!(windows) {
+ return None;
+ }
+ let out = std::process::Command::new(chrome)
+ .arg("--version")
+ .stdin(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .output()
+ .ok()?;
+ headed_user_agent(&String::from_utf8_lossy(&out.stdout), std::env::consts::OS)
+}
+
+/// A normal Chrome user agent for kwant's plain HTTP requests (`web_fetch`): the local Chrome's,
+/// or, without one, a recent Chrome on this platform. Worked out once per process.
+pub fn browser_user_agent() -> &'static str {
+ static AGENT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
+ AGENT.get_or_init(|| {
+ local_chrome_path()
+ .and_then(|chrome| chrome_user_agent(&chrome))
+ .or_else(|| headed_user_agent("Chrome 141.0.0.0", std::env::consts::OS))
+ .unwrap_or_default()
+ })
+}
+
+/// Whether a running Chrome is windowless, from its `/json/version` user agent. Only a fallback
+/// where its command line can't be read: kwant's windowless Chrome no longer says so there.
pub fn is_headless_user_agent(user_agent: &str) -> bool {
user_agent.contains("HeadlessChrome")
}
+/// Whether a Chrome command line (arguments joined by spaces) runs it without a window.
+pub fn is_headless_command_line(line: &str) -> bool {
+ line.split(' ').any(|arg| arg == "--headless" || arg.starts_with("--headless="))
+}
+
fn client() -> reqwest::Client {
reqwest::Client::builder()
.timeout(Duration::from_secs(2))
@@ -222,12 +276,23 @@ async fn user_agent(endpoint: &str) -> Option<String> {
Some(version["User-Agent"].as_str().unwrap_or_default().to_string())
}
-/// The kwant Chrome running on `profile`: its CDP endpoint and whether it is windowless.
+/// The kwant Chrome running on `profile`: its CDP endpoint and whether it is windowless. That comes
+/// from the `--headless` flag on its command line, since its user agent reads like a windowed one.
pub async fn running_local_chrome(profile: &Path) -> Option<(String, bool)> {
let port = read_devtools_port(profile)?;
let endpoint = format!("http://127.0.0.1:{port}");
let agent = user_agent(&endpoint).await?;
- Some((endpoint, is_headless_user_agent(&agent)))
+ let headless = match profile_owner(profile).and_then(command_line) {
+ Some(line) => is_headless_command_line(&line),
+ None => is_headless_user_agent(&agent),
+ };
+ Some((endpoint, headless))
+}
+
+/// Whether the Chrome at `endpoint` still tells sites it is "HeadlessChrome": one started before
+/// kwant set its user agent, which kwant restarts so sites see a normal Chrome.
+pub async fn says_headless(endpoint: &str) -> bool {
+ user_agent(endpoint).await.is_some_and(|agent| is_headless_user_agent(&agent))
}
/// The live Chrome holding `profile`, from the `SingletonLock` link Chrome keeps in it
@@ -268,7 +333,7 @@ fn command_line(pid: u32) -> Option<String> {
#[cfg(all(unix, not(target_os = "linux")))]
fn command_line(pid: u32) -> Option<String> {
- let out = std::process::Command::new("ps").args(["-o", "command=", "-p", &pid.to_string()]).output().ok()?;
+ let out = std::process::Command::new("ps").args(["-ww", "-o", "command=", "-p", &pid.to_string()]).output().ok()?;
let line = String::from_utf8_lossy(&out.stdout).trim().to_string();
(out.status.success() && !line.is_empty()).then_some(line)
}
@@ -471,8 +536,9 @@ fn launch_local_chrome(profile: &Path, headless: bool) -> Result<(), String> {
}
}
std::fs::create_dir_all(profile).map_err(|e| e.to_string())?;
+ let agent = if headless { chrome_user_agent(&chrome) } else { None };
let mut cmd = std::process::Command::new(&chrome);
- cmd.args(chrome_args(profile, headless))
+ cmd.args(chrome_args(profile, headless, agent.as_deref()))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
@@ -612,7 +678,7 @@ mod tests {
#[test]
fn chrome_uses_its_own_profile_and_a_loopback_port() {
for headless in [true, false] {
- let args = chrome_args(Path::new("/data/local-chrome"), headless);
+ let args = chrome_args(Path::new("/data/local-chrome"), headless, None);
assert!(args.contains(&"--user-data-dir=/data/local-chrome".to_string()));
assert!(args.contains(&"--remote-debugging-port=0".to_string()));
assert!(args.contains(&"--remote-debugging-address=127.0.0.1".to_string()));
@@ -621,16 +687,54 @@ mod tests {
#[test]
fn chrome_is_windowless_unless_a_window_is_asked_for() {
- let args = chrome_args(Path::new("/p"), true);
+ let args = chrome_args(Path::new("/p"), true, None);
assert!(args.contains(&"--headless=new".to_string()));
assert!(args.contains(&"--window-size=1280,800".to_string()));
- let args = chrome_args(Path::new("/p"), false);
+ let args = chrome_args(Path::new("/p"), false, None);
assert!(!args.iter().any(|a| a.starts_with("--headless")));
assert!(!args.iter().any(|a| a.starts_with("--window-size")));
assert!(is_headless_user_agent("Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/131.0 Safari/537.36"));
assert!(!is_headless_user_agent("Mozilla/5.0 (Macintosh) Chrome/131.0 Safari/537.36"));
}
+ #[test]
+ fn windowless_chrome_sends_the_windowed_user_agent() {
+ assert_eq!(
+ headed_user_agent("Google Chrome 131.0.6778.86 \n", "macos").as_deref(),
+ Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
+ );
+ assert_eq!(
+ headed_user_agent("Chromium 154.0.8037.92 built on Ubuntu 24.04.5 LTS", "linux").as_deref(),
+ Some("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36")
+ );
+ assert!(headed_user_agent("Google Chrome 140.0.1.2", "windows").unwrap().contains("(Windows NT 10.0; Win64; x64)"));
+ // the "24.04.5" in the build line is not taken for Chrome's version
+ assert!(headed_user_agent("Chromium 154.0.8037.92 built on Ubuntu 24.04.5", "linux").unwrap().contains("Chrome/154.0.0.0"));
+ assert_eq!(headed_user_agent("", "linux"), None);
+ assert_eq!(headed_user_agent("Chromium version unknown", "linux"), None);
+
+ let agent = headed_user_agent("Chromium 154.0.8037.92", "linux").unwrap();
+ let args = chrome_args(Path::new("/p"), true, Some(&agent));
+ assert!(args.contains(&format!("--user-agent={agent}")));
+ assert!(!args.iter().any(|a| a.contains("Headless") && a.starts_with("--user-agent")));
+ // a window already sends the normal one
+ assert!(!chrome_args(Path::new("/p"), false, Some(&agent)).iter().any(|a| a.starts_with("--user-agent")));
+ assert!(!browser_user_agent().contains("Headless"));
+ assert!(browser_user_agent().contains(" Chrome/"));
+ }
+
+ #[test]
+ fn windowless_is_read_from_the_command_line() {
+ let headless = chrome_args(Path::new("/p"), true, Some("Mozilla/5.0 (X11; Linux x86_64) Chrome/154.0.0.0"));
+ assert!(is_headless_command_line(&format!("/usr/lib/chromium/chromium {}", headless.join(" "))));
+ let window = chrome_args(Path::new("/p"), false, None);
+ assert!(!is_headless_command_line(&format!("/usr/lib/chromium/chromium {}", window.join(" "))));
+ assert!(is_headless_command_line("chrome --headless --user-data-dir=/p"));
+ // a profile or user agent that merely mentions it is not the flag
+ assert!(!is_headless_command_line("chrome --user-data-dir=/home/me/--headless-notes"));
+ assert!(!is_headless_command_line("chrome --user-agent=Mozilla/5.0 HeadlessChrome/154 --headlessly"));
+ }
+
#[test]
fn devtools_port_file() {
let dir = tempfile::tempdir().unwrap();
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rs
index d81a571c..a8c14744 100644
--- a/src/sandbox/service.rs
+++ b/src/sandbox/service.rs
@@ -118,8 +118,11 @@ impl BrowserService {
// at most one kwant Chrome per profile: reuse it, or wait for the one starting
let (endpoint, running_headless) = computer::ensure_local_chrome(&profile, headless).await
.map_err(BrowserError::Http)?;
- if running_headless == headless { return Ok(endpoint); }
- // the other form is running on this profile: close it first
+ // a windowless Chrome started before kwant set its user agent tells sites it is headless
+ let stale = running_headless && headless && computer::says_headless(&endpoint).await
+ && computer::local_chrome_path().is_some_and(|chrome| computer::chrome_user_agent(&chrome).is_some());
+ if running_headless == headless && !stale { return Ok(endpoint); }
+ // the other form (or that older one) is running on this profile: close it first
let _ = BrowserController::at_endpoint(&endpoint, None, true)
.send_cdp_command("Browser.close", json!({})).await;
computer::wait_local_chrome_gone(&profile).await.map_err(BrowserError::Http)?;
diff --git a/src/tools/web.rs b/src/tools/web.rs
index 93332b40..86abefa0 100644
--- a/src/tools/web.rs
+++ b/src/tools/web.rs
@@ -15,7 +15,7 @@ pub async fn web_fetch(args: &Value) -> Result<Value, ToolError> {
let resp = client
.get(url)
- .header("User-Agent", "KwantsBot/1.0 (Multi-Agent-Platform)")
+ .header("User-Agent", crate::sandbox::computer::browser_user_agent())
.send()
.await
.map_err(|e| ToolError::Execution(format!("Web request failed: {}", e)))?;
diff --git a/tests/local_chrome_test.rs b/tests/local_chrome_test.rs
index c0288aa6..3beb5ca3 100644
--- a/tests/local_chrome_test.rs
+++ b/tests/local_chrome_test.rs
@@ -13,6 +13,9 @@ const PAGE: &str = "<!doctype html><title>before</title><body style=margin:0>\
<button id=b style='position:absolute;left:0;top:0;width:400px;height:300px' \
onclick=\"document.title='clicked '+innerWidth+'x'+innerHeight\">press</button>";
+/// The User-Agent header of the last request the page server got.
+static REQUEST_AGENT: std::sync::Mutex<String> = std::sync::Mutex::new(String::new());
+
/// A one-page HTTP server on 127.0.0.1, so the test needs no network.
async fn serve_page() -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -21,7 +24,11 @@ async fn serve_page() -> String {
while let Ok((mut stream, _)) = listener.accept().await {
tokio::spawn(async move {
let mut buf = [0u8; 2048];
- let _ = stream.read(&mut buf).await;
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let request = String::from_utf8_lossy(&buf[..n]).to_string();
+ if let Some(line) = request.lines().find(|l| l.to_ascii_lowercase().starts_with("user-agent:")) {
+ *REQUEST_AGENT.lock().unwrap() = line[11..].trim().to_string();
+ }
let reply = format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{PAGE}",
PAGE.len()
@@ -66,6 +73,17 @@ async fn local_chrome_runs_windowless_and_can_open_as_a_window() {
assert!(headless, "local Chrome must start without a window");
ctrl.navigate(&url).await.unwrap();
assert!(!ctrl.capture_screenshot().await.unwrap().is_empty());
+ // sites see a normal Chrome: no "Headless" in the request, the page's user agent or its brands
+ let request_agent = REQUEST_AGENT.lock().unwrap().clone();
+ let seen = ctrl.send_cdp_command("Runtime.evaluate", serde_json::json!({
+ "expression": "JSON.stringify([navigator.userAgent, navigator.userAgentData ? navigator.userAgentData.brands : []])",
+ "returnByValue": true,
+ })).await.unwrap();
+ let page_agent = seen["result"]["value"].as_str().unwrap_or_default().to_string();
+ assert!(request_agent.contains(" Chrome/"), "request user agent: {request_agent:?}");
+ assert!(page_agent.contains(" Chrome/"), "page user agent: {page_agent}");
+ assert!(!request_agent.contains("Headless") && !page_agent.contains("Headless"),
+ "windowless Chrome must not say so: {request_agent} / {page_agent}");
// the same input path the in-app viewer uses
ctrl.dispatch_input(BrowserInput::Click { x: 100.0, y: 100.0 }).await.unwrap();
assert_eq!(title_becomes(&ctrl, "clicked 1280x800").await, "clicked 1280x800");