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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Leave hidden tabs alone, look in shadow roots, open host:port and refuse phone links (#287)
Oleksandr Ivanchenko3898f1abbc16
diff --git a/src/sandbox/app_links.rs b/src/sandbox/app_links.rsindex 68be0ee8..4f4f9c47 100644--- a/src/sandbox/app_links.rs+++ b/src/sandbox/app_links.rs@@ -64,13 +64,30 @@ pub fn app_scheme(url: &str) -> Option<String> {(!IN_BROWSER.contains(&scheme.as_str())).then_some(scheme)}+/// Schemes that take a phone number (`tel:+38640123456`, `sms:5551234`): digits after the colon+/// are the number, never a port, so `tel:555` is a call, not a host called `tel`.+const NUMBERS: &[&str] = &["tel", "sms", "mms", "callto", "facetime", "facetime-audio", "fax", "sip", "sips"];++/// The port of `url` when it is a web address written without its scheme, `host:port` with an+/// optional path (`localhost:8080/x`, `127.0.0.1:9381`, `example.com:443`). Chrome would read the+/// host as a scheme (`localhost:`) and hand it to the operating system.+pub fn host_port(url: &str) -> Option<u16> {+ let (host, rest) = url.trim().split_once(':')?;+ if host.is_empty() || !host.chars().all(|c| c.is_ascii_alphanumeric() || "-.".contains(c)) { return None; }+ if NUMBERS.iter().any(|n| host.eq_ignore_ascii_case(n)) { return None; }+ let digits = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());+ let (port, after) = rest.split_at(digits);+ if !(after.is_empty() || after.starts_with(['/', '?', '#'])) { return None; }+ port.parse::<u16>().ok().filter(|p| *p > 0)+}+/// The scheme of `url` when it is a link to another app a bot must not open: Chrome would hand it/// to the operating system or freeze the tab behind an "Open <app>?" prompt. `host:port` without-/// a scheme (`localhost:8080`) isn't one, and neither is a Windows drive (`C:\…`, `c:/…`).+/// a scheme (`localhost:8080`, see [`host_port`]) isn't one, and neither is a Windows drive+/// (`C:\…`, `c:/…`). A phone number is (`tel:5551234`), digits or not.pub fn refused_scheme(url: &str) -> Option<String> {- let scheme = app_scheme(url).filter(|s| s.len() > 1)?;- let rest = url.trim_start()[scheme.len() + 1..].trim_start_matches('/');- (!rest.starts_with(|c: char| c.is_ascii_digit())).then_some(scheme)+ if host_port(url).is_some() { return None; }+ app_scheme(url).filter(|s| s.len() > 1)}/// Why a bot's browser didn't open `url`, a link to another app.@@ -112,12 +129,23 @@ pub enum Verdict {/// Marks where a mouse move should land in the page and starts counting the moves that reach/// it: `[x, y]`, or `null` when there is no point to probe (the page is all frames, or has no-/// size). Runs in the page's main world; the probe removes itself in [`PROBE_READ_JS`].+/// size, or no one sees it). Runs in the page's main world; the probe removes itself in+/// [`PROBE_READ_JS`]. A frame in a closed shadow root can't be seen from the page, so a point+/// over one is still probed.pub const PROBE_ARM_JS: &str = r#"(() => {const w = innerWidth, h = innerHeight, key = Symbol.for('kwnt.inputProbe');+ // Chrome holds mouse moves for a page no one sees until its next frame, which a hidden page+ // doesn't draw: they would never arrive, and a live background tab would look stuck+ if (document.visibilityState !== 'visible') return null;if (!(w > 32 && h > 32)) return null;for (const [x, y] of [[8, 8], [w - 9, h - 9], [8, h - 9], [w - 9, 8], [w >> 1, h >> 1]]) {- const el = document.elementFromPoint(x, y);+ let el = document.elementFromPoint(x, y);+ // a frame inside a web component: the page sees its host, the move goes to the frame+ for (let i = 0; el && el.shadowRoot && i < 16; i++) {+ const inner = el.shadowRoot.elementFromPoint(x, y);+ if (!inner || inner === el) break;+ el = inner;+ }if (!el || /^(IFRAME|FRAME|EMBED|OBJECT|FENCEDFRAME|PORTAL)$/.test(el.tagName)) continue;if (self[key]) removeEventListener('mousemove', self[key].on, true);const probe = { n: 0, on: () => { probe.n++; } };@@ -308,6 +336,58 @@ mod tests {assert!(refused_text(&"x".repeat(500), "x").len() < 400, "a long link is cut short");}+ #[test]+ fn a_phone_number_opens_another_app_and_host_port_is_a_web_address() {+ // digits after the colon are a number to call or text, not a port+ for (url, scheme) in [("tel:5551234", "tel"), ("tel:+38640123456", "tel"), ("TEL:555", "tel"), ("sms:5551234", "sms"), ("sms:+38640123456?body=hi", "sms"),+ ("tel:555/1", "tel"), ("callto:5551234", "callto"), ("facetime:5551234", "facetime"), ("zoommtg:123456789", "zoommtg"), ("tiktok:12x", "tiktok")] {+ assert_eq!(refused_scheme(url).as_deref(), Some(scheme), "{url}");+ assert_eq!(host_port(url), None, "{url}");+ }+ // a host and a port with no scheme: Chrome must not read the host as one+ for (url, port) in [("localhost:8080", 8080), ("localhost:8080/target.html", 8080), (" LocalHost:3000?x=1", 3000), ("127.0.0.1:9411/a", 9411),+ ("example.com:443/x", 443), ("dev-box:5173#top", 5173)] {+ assert_eq!(host_port(url), Some(port), "{url}");+ assert_eq!(refused_scheme(url), None, "{url}");+ }+ for url in ["localhost", "localhost:", "localhost:0", "localhost:70000", "localhost:80abc", "http://localhost:8080", "a b:80", ":80", "C:\\x"] {+ assert_eq!(host_port(url), None, "{url}");+ }+ }++ /// Runs [`PROBE_ARM_JS`] in Node against a stand-in page: `page` sets `visibilityState` and+ /// what `elementFromPoint` finds. Gives the probe's answer as JSON.+ fn arm_probe_in(page: &str) -> String {+ let script = format!(r#"+ globalThis.self = globalThis; globalThis.innerWidth = 800; globalThis.innerHeight = 600;+ globalThis.addEventListener = () => {{}}; globalThis.removeEventListener = () => {{}};+ const el = (tagName, shadow) => ({{ tagName, shadowRoot: shadow ? {{ elementFromPoint: () => shadow }} : null }});+ globalThis.document = {{ visibilityState: 'visible', elementFromPoint: () => el('DIV') }};+ {page}+ console.log(JSON.stringify({PROBE_ARM_JS}));"#);+ let out = std::process::Command::new("node").args(["-e", &script]).output().expect("node runs the probe (CI and dev machines have it)");+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ String::from_utf8_lossy(&out.stdout).trim().to_string()+ }++ #[test]+ fn the_input_probe_leaves_a_page_no_one_sees_alone() {+ assert_eq!(arm_probe_in(""), "[8,8]", "a page on screen is probed");+ // a background tab gets no mouse moves until it is shown, so it would read as stuck+ assert_eq!(arm_probe_in("document.visibilityState = 'hidden';"), "null");+ assert_eq!(arm_probe_in("document.visibilityState = 'prerender';"), "null");+ }++ #[test]+ fn the_input_probe_skips_a_frame_inside_a_web_component() {+ // the page sees the component's host; the move goes to the frame inside it+ assert_eq!(arm_probe_in("document.elementFromPoint = () => el('EMBED-WIDGET', el('IFRAME'));"), "null");+ assert_eq!(arm_probe_in("document.elementFromPoint = () => el('OUTER-X', el('INNER-Y', el('IFRAME')));"), "null", "nested components");+ // a component with ordinary content is still probed, and one whose root finds itself ends the walk+ assert_eq!(arm_probe_in("document.elementFromPoint = () => el('MY-APP', el('DIV'));"), "[8,8]");+ assert_eq!(arm_probe_in("const host = el('MY-APP'); host.shadowRoot = { elementFromPoint: () => host }; document.elementFromPoint = () => host;"), "[8,8]");+ }+#[test]fn the_input_probe_skips_frames_and_cleans_up() {assert!(PROBE_ARM_JS.contains("elementFromPoint") && PROBE_ARM_JS.contains("IFRAME"));diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex f98e0c25..3d039855 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -456,6 +456,20 @@ pub fn refuse_app_link(target: &str) -> Result<(), BrowserError> {}}+/// The address a navigate hands Chrome, the same for a bot and for the live view. A file path is+/// refused first (`C:\Users\…` would otherwise read as a link to an app called `c:`), then a+/// link to another app; a web address written as `host:port` (`localhost:8080/x`) gets its+/// scheme, because Chrome would read `localhost:` as one and hand it to the operating system.+pub fn web_address(target: &str) -> Result<std::borrow::Cow<'_, str>, BrowserError> {+ refuse_file_path(target)?;+ refuse_app_link(target)?;+ Ok(match super::app_links::host_port(target) {+ Some(443) => format!("https://{}", target.trim()).into(),+ Some(_) => format!("http://{}", target.trim()).into(),+ None => target.into(),+ })+}+/// Recognises CAPTCHA / anti-bot interstitials that replace the requested content.pub fn detect_bot_wall(url: &str, title: &str, text: &str) -> Option<&'static str> {let url = url.to_lowercase();@@ -1312,13 +1326,11 @@ impl BrowserController {/// fails the same way. The person's own navigation is [`Self::navigate_unlocked`].pub async fn navigate(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {let _permit = self.control.try_read().map_err(|_| BrowserError::HumanControl)?;- // a path first: `C:\Users\…` would otherwise read as a link to an app called `c:`- refuse_file_path(target_url)?;- refuse_app_link(target_url)?;+ let address = web_address(target_url)?;self.site_guard.set_actor(super::site_guard::Actor::Bot);- self.site_guard.check(target_url).await.map_err(BrowserError::SiteRule)?;+ self.site_guard.check(&address).await.map_err(BrowserError::SiteRule)?;let _ = self.site_guard.take_refusal();- let navigated = self.navigate_unlocked(target_url).await;+ let navigated = self.navigate_unlocked(&address).await;if let Some(refusal) = self.site_guard.take_refusal() {self.leave_refused_page().await;return Err(BrowserError::SiteRule(refusal));@@ -1364,8 +1376,8 @@ impl BrowserController {}pub async fn navigate_unlocked(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {- refuse_file_path(target_url)?;- refuse_app_link(target_url)?;+ let address = web_address(target_url)?;+ let target_url: &str = &address;self.progress.lock().unwrap_or_else(|e| e.into_inner()).reset();let _ = self.collect_captured_credentials().await;let _ = self.send_cdp_command("Page.enable", json!({})).await;diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex d67c3387..41564035 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -12,7 +12,7 @@ pub mod service;pub mod site_guard;pub mod vault;-pub use browser::{detect_bot_wall, ref_line, refuse_file_path, BrowserController, ClickTarget, BrowserError, NavigationResult, PendingCapture};+pub use browser::{detect_bot_wall, ref_line, refuse_file_path, web_address, BrowserController, ClickTarget, BrowserError, NavigationResult, PendingCapture};pub use credentials::{Credential, CredentialMeta, CredentialStore, EncryptedFileStore};pub use manager::{ActiveSandbox, SandboxError, SandboxManager, ShellOutput};diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rsindex 86674070..b4735273 100644--- a/src/server/browser_stream.rs+++ b/src/server/browser_stream.rs@@ -8,7 +8,7 @@use super::browser_input::{self as bi, KeyEvent, KeyKind, MouseButton, RateLimit};use super::{routes::get_or_create_browser_controller, AppState};use crate::sandbox::app_links::{self, AppLinkWatch, Verdict};-use crate::sandbox::browser::{BrowserController, BrowserError, HeldPointer, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};+use crate::sandbox::browser::{web_address, BrowserController, BrowserError, HeldPointer, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};use crate::sandbox::browser_history::HistoryDirection;use axum::{extract::{Path, State, WebSocketUpgrade, ws::{Message, WebSocket}}, http::{HeaderMap, StatusCode}, response::Response};use futures::{SinkExt, StreamExt};@@ -184,9 +184,11 @@ impl BrowserController {}}BrowserInput::Navigate { url } => {- let parsed = reqwest::Url::parse(&url).map_err(|e| BrowserError::Protocol(e.to_string()))?;+ // told apart as a bot's navigate tells them: a path, another app, then the scheme+ let address = web_address(&url)?;+ let parsed = reqwest::Url::parse(&address).map_err(|e| BrowserError::Protocol(e.to_string()))?;if !matches!(parsed.scheme(), "http"|"https") { return Err(protocol("Use an HTTP or HTTPS URL")); }- self.navigate_unlocked(&url).await?;+ self.navigate_unlocked(&address).await?;}BrowserInput::History { direction } => self.navigate_history(direction).await?,_ => return Err(protocol("This action needs the live view")),@@ -596,9 +598,11 @@ impl Worker {self.cdp.fire("Input.dispatchMouseEvent", json!({"type":"mouseWheel","x":x,"y":y,"deltaX":delta_x,"deltaY":delta_y,"modifiers":modifiers,"buttons":buttons}));}BrowserInput::Navigate { url } => {- let parsed = reqwest::Url::parse(&url).map_err(|e| BrowserError::Protocol(e.to_string()))?;+ // told apart as a bot's navigate tells them: a path, another app, then the scheme+ let address = web_address(&url)?;+ let parsed = reqwest::Url::parse(&address).map_err(|e| BrowserError::Protocol(e.to_string()))?;if !matches!(parsed.scheme(), "http"|"https") { return Err(protocol("Use an HTTP or HTTPS URL")); }- self.ctrl.navigate_unlocked(&url).await?;+ self.ctrl.navigate_unlocked(&address).await?;refresh_location(&self.cdp, &self.ctrl, &self.shared, &self.client);let _ = self.client.send(ack(id, json!({})));}diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rsindex 8fa58394..e50e167b 100644--- a/tests/browser_stream_test.rs+++ b/tests/browser_stream_test.rs@@ -846,3 +846,41 @@ async fn a_bot_navigating_to_another_app_is_refused_before_the_browser_sees_it()ctrl.navigate("https://www.tiktok.com/login").await.expect("a web page still opens");app_task.abort(); cdp_task.abort();}++/// F3: a bot and the live view tell addresses apart the same way. `localhost:8080` is a web+/// address without its scheme (Chromium would read `localhost:` as a scheme and freeze the tab+/// behind its "Open app?" prompt), so it opens over http; `tel:` and `sms:` with a number open+/// another app, so neither reaches the browser.+#[tokio::test]+async fn a_host_and_port_open_as_a_web_page_and_a_phone_number_is_refused_by_both_navigates() {+ let (mock, cdp_task) = mock().await;+ let tmp = tempfile::tempdir().unwrap();+ let (mut ws, ctrl, app_task) = open_stream(&mock, tmp.path()).await;+ let navigated = || async { mock.commands.lock().await.iter().filter(|c| c["method"] == "Page.navigate").map(|c| c["params"]["url"].clone()).collect::<Vec<_>>() };++ for url in ["tel:5551234", "tel:+38640123456", "sms:5551234"] {+ let error = ctrl.navigate(url).await.expect_err(url);+ assert!(matches!(error, kwnt::sandbox::BrowserError::NotWebAddress(_)), "{url}: {error:?}");+ assert!(error.to_string().contains("opens another app ("), "{url}: {error}");+ }+ assert!(navigated().await.is_empty(), "no number reached the browser");+ ctrl.navigate("localhost:9411/target.html").await.expect("a host and port opens");+ ctrl.navigate("127.0.0.1:9411").await.expect("an address and port opens");+ assert_eq!(navigated().await, vec![json!("http://localhost:9411/target.html"), json!("http://127.0.0.1:9411")]);++ // the person's live view: the same addresses, the same answers+ ws.send(WsMessage::Text(json!({"action":"take_control"}).to_string())).await.unwrap();+ assert_eq!(receive(&mut ws, "control").await["active"], true);+ for (i, url) in ["tel:5551234", "sms:+38640123456"].into_iter().enumerate() {+ let id = format!("n{i}");+ ws.send(WsMessage::Text(json!({"action":"navigate","url":url,"id":id}).to_string())).await.unwrap();+ let reply = until_reply(&mut ws, &id).await.pop().unwrap();+ assert_eq!(reply["type"], "error", "{url}: {reply}");+ assert!(reply["error"].as_str().unwrap().contains("opens another app ("), "{url}: {reply}");+ }+ assert_eq!(navigated().await.len(), 2, "no number reached the browser from the live view");+ ws.send(WsMessage::Text(json!({"action":"navigate","url":"localhost:9411/target.html","id":"n9"}).to_string())).await.unwrap();+ assert_eq!(until_reply(&mut ws, "n9").await.pop().unwrap()["type"], "ack");+ assert_eq!(navigated().await.last(), Some(&json!("http://localhost:9411/target.html")));+ app_task.abort(); cdp_task.abort();+}