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: sites each bot may open

Lin (kwant bot)a1b98098b550
diff --git a/docs/bot-browser.md b/docs/bot-browser.md
index 3a43a8f2..ce221805 100644
--- a/docs/bot-browser.md
+++ b/docs/bot-browser.md
@@ -120,8 +120,41 @@ browser's own matching follows the page's blocks, which `innerText` lines only a
link can occasionally highlight nothing (it then opens at the top); pages that change text on load
or per visit can make a link miss later.
+## Sites a bot may open
+
+Each bot has three optional settings, set by the person on `PUT /api/kwants/:id` and shown on the
+bot's read routes:
+
+- `browser_allowed_sites`: when not empty, the bot's browser opens only these sites.
+- `browser_blocked_sites`: never these. The block-list wins over the allow-list.
+- `browser_block_private_network` (off by default): no loopback, private, link-local or other
+ internal addresses, also by a hostname that resolves to one. It uses the rules in
+ `src/mcp/fetch_risk.rs`.
+
+An entry is a host: `example.com` covers the site and all its subdomains, `*.example.com` only the
+subdomains, and an IP matches only itself. Entries are lowercased, a pasted URL keeps only its host,
+and international names are stored as punycode. A bad entry (empty, `*`, a wildcard inside a name
+or on an IP) refuses the whole update with a 400. There are at most 200 entries per list. A bot's
+own token can't change these settings (403); only the person can.
+
+With both lists empty and the setting off, nothing is checked and nothing extra runs, exactly as
+before. Otherwise every navigation the bot causes is checked: the address it opens (refused before
+loading, 403 with `site_rule`), and through Chrome request interception (`Fetch`, top-level
+documents) the link it clicks, any redirect and any new tab the page opens. A refused page is
+stopped in the browser (`ERR_BLOCKED_BY_CLIENT`). The bot's action reply carries `error` with a
+message that names the rule, and a `site_rule` with `rule`, `host`, `url`, `entry` and `message`.
+Whatever the person does in live control (`/interact`, the stream, take control) is never checked.
+
+Limits: only top-level pages are checked. Frames, images, scripts and `fetch`/XHR from an allowed
+page are not, so this sets which sites a bot visits; it is not a network firewall. The
+private-network check resolves the name once, so DNS rebinding between that check and Chrome's own
+lookup isn't caught. In VM mode the name is resolved on the kwnt host, not inside the VM. A
+navigation started by the page on its own (a timer) after the person's last input counts as theirs
+until the bot acts again. In a browser several bots share, the rules of the bot that drove it last
+apply.
+
## Tests
-`tests/browser_refs_test.rs`, `tests/browser_progress_test.rs` and `tests/browser_reads_test.rs` and `tests/browser_cite_test.rs` (real Chrome, skipped without one;
+`tests/browser_refs_test.rs`, `tests/browser_progress_test.rs` and `tests/browser_reads_test.rs` `tests/browser_cite_test.rs` and `tests/browser_site_rules_test.rs` (real Chrome, skipped without one;
the `saucedemo_*` and `a_public_page_*` tests are ignored and need the network), `ref_tests` in `src/sandbox/browser.rs`
-and the tests in `src/sandbox/progress.rs`, `src/sandbox/reads.rs` and `src/sandbox/cite.rs`.
+and the tests in `src/sandbox/progress.rs`, `src/sandbox/reads.rs`, `src/sandbox/cite.rs` and `src/sandbox/site_guard.rs`.
diff --git a/src/db/browser_sites.rs b/src/db/browser_sites.rs
new file mode 100644
index 00000000..4d30f309
--- /dev/null
+++ b/src/db/browser_sites.rs
@@ -0,0 +1,94 @@
+//! Each bot's browser site rules (see [`crate::sandbox::site_guard`]): `browser_allowed_sites`
+//! and `browser_blocked_sites` (JSON lists of normalized entries) and
+//! `browser_block_private_network`. Empty lists and off, the default, change nothing.
+
+use super::{Database, DbError};
+use crate::sandbox::site_guard::SiteRules;
+use serde::{Deserialize, Serialize};
+
+/// A bot's site rules as the bot routes show and take them.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct BrowserSites {
+ #[serde(default)]
+ pub browser_allowed_sites: Vec<String>,
+ #[serde(default)]
+ pub browser_blocked_sites: Vec<String>,
+ #[serde(default)]
+ pub browser_block_private_network: bool,
+}
+
+impl BrowserSites {
+ pub fn rules(&self) -> SiteRules {
+ SiteRules {
+ allowed: self.browser_allowed_sites.clone(),
+ blocked: self.browser_blocked_sites.clone(),
+ block_private: self.browser_block_private_network,
+ }
+ }
+}
+
+fn list(json: &str) -> Vec<String> {
+ serde_json::from_str(json).unwrap_or_default()
+}
+
+impl Database {
+ pub(super) async fn migrate_browser_sites(&self) -> Result<(), DbError> {
+ for column in [
+ "browser_allowed_sites TEXT NOT NULL DEFAULT '[]'",
+ "browser_blocked_sites TEXT NOT NULL DEFAULT '[]'",
+ "browser_block_private_network INTEGER NOT NULL DEFAULT 0",
+ ] {
+ let _ = sqlx::query(&format!("ALTER TABLE kwants ADD COLUMN {column};")).execute(&self.pool).await;
+ }
+ Ok(())
+ }
+
+ /// The bot's site rules; a missing bot has none.
+ pub async fn browser_sites(&self, kwant_id: &str) -> Result<BrowserSites, DbError> {
+ let row: Option<(String, String, bool)> = sqlx::query_as(
+ "SELECT browser_allowed_sites, browser_blocked_sites, browser_block_private_network FROM kwants WHERE id = ?",
+ )
+ .bind(kwant_id)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row
+ .map(|(allowed, blocked, private)| BrowserSites {
+ browser_allowed_sites: list(&allowed),
+ browser_blocked_sites: list(&blocked),
+ browser_block_private_network: private,
+ })
+ .unwrap_or_default())
+ }
+
+ /// Sets the given fields (already normalized); `None` leaves one as it is.
+ pub async fn set_browser_sites(
+ &self,
+ kwant_id: &str,
+ allowed: Option<&[String]>,
+ blocked: Option<&[String]>,
+ block_private: Option<bool>,
+ ) -> Result<(), DbError> {
+ if let Some(allowed) = allowed {
+ sqlx::query("UPDATE kwants SET browser_allowed_sites = ? WHERE id = ?")
+ .bind(serde_json::to_string(allowed).unwrap_or_else(|_| "[]".into()))
+ .bind(kwant_id)
+ .execute(&self.pool)
+ .await?;
+ }
+ if let Some(blocked) = blocked {
+ sqlx::query("UPDATE kwants SET browser_blocked_sites = ? WHERE id = ?")
+ .bind(serde_json::to_string(blocked).unwrap_or_else(|_| "[]".into()))
+ .bind(kwant_id)
+ .execute(&self.pool)
+ .await?;
+ }
+ if let Some(block_private) = block_private {
+ sqlx::query("UPDATE kwants SET browser_block_private_network = ? WHERE id = ?")
+ .bind(block_private)
+ .bind(kwant_id)
+ .execute(&self.pool)
+ .await?;
+ }
+ Ok(())
+ }
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 04a88c53..b7ad0fa3 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -1,5 +1,6 @@
pub mod models;
pub mod profiles;
+pub mod browser_sites;
pub mod continuity;
pub mod threads;
pub mod zombie;
@@ -151,6 +152,7 @@ impl Database {
let db = Self { pool };
db.migrate_profiles().await?;
+ db.migrate_browser_sites().await?;
db.migrate_continuity().await?;
db.migrate_threads().await?;
db.migrate_skills().await?;
diff --git a/src/db/models.rs b/src/db/models.rs
index e15d3bed..11721e16 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -344,6 +344,9 @@ pub struct KwantView {
pub profile_id: Option<String>,
/// Whether a turn may move to the engine's next profile when this one is out of quota or signed out.
pub profile_failover: bool,
+ /// Which sites the bot's browser may open.
+ #[serde(flatten)]
+ pub browser: super::browser_sites::BrowserSites,
}
/// One LLM account for an engine. Holds no secret: API keys live in `llm_profile_secrets`.
diff --git a/src/db/profiles.rs b/src/db/profiles.rs
index ac7294c4..d7406ef0 100644
--- a/src/db/profiles.rs
+++ b/src/db/profiles.rs
@@ -308,18 +308,13 @@ impl Database {
pub async fn kwant_views(&self, space: &SpaceId) -> Result<Vec<KwantView>, DbError> {
let kwants = self.list_kwants(space).await?;
let mut bindings = self.list_kwant_bindings(space).await?;
- Ok(kwants
- .into_iter()
- .map(|kwant| {
- let (profile_id, profile_failover) =
- bindings.remove(&kwant.id).unwrap_or((None, true));
- KwantView {
- kwant,
- profile_id,
- profile_failover,
- }
- })
- .collect())
+ let mut views = Vec::with_capacity(kwants.len());
+ for kwant in kwants {
+ let (profile_id, profile_failover) = bindings.remove(&kwant.id).unwrap_or((None, true));
+ let browser = self.browser_sites(&kwant.id).await?;
+ views.push(KwantView { kwant, profile_id, profile_failover, browser });
+ }
+ Ok(views)
}
pub async fn kwant_view(&self, id: &str) -> Result<Option<KwantView>, DbError> {
@@ -328,10 +323,12 @@ impl Database {
};
let (profile_id, profile_failover) =
self.get_kwant_binding(id).await?.unwrap_or((None, true));
+ let browser = self.browser_sites(id).await?;
Ok(Some(KwantView {
kwant,
profile_id,
profile_failover,
+ browser,
}))
}
}
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index aa3c9e07..c45fca70 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -321,6 +321,9 @@ pub enum BrowserError {
/// A ref from the control list that can't be clicked any more (gone, hidden, covered).
#[error("{0}")]
StaleRef(String),
+ /// The driving bot's site rules refused the page (see [`super::site_guard`]).
+ #[error("{}", .0.message)]
+ SiteRule(super::site_guard::Refusal),
}
/// What a click aims at: a label to match, or a numbered ref from the last control list.
@@ -814,6 +817,8 @@ pub struct BrowserController {
pub progress: Arc<std::sync::Mutex<super::progress::Tracker>>,
/// Which read each bot saw last, for "unchanged since your last read" (see [`super::reads`]).
pub reads: Arc<std::sync::Mutex<super::reads::Reads>>,
+ /// The driving bot's site rules and the task enforcing them (see [`super::site_guard`]).
+ pub site_guard: Arc<super::site_guard::SiteGuard>,
}
/// Widest screenshot a bot gets, in pixels, and the narrowest width it may ask for.
@@ -876,6 +881,7 @@ impl BrowserController {
viewport: Arc::default(),
progress: Arc::default(),
reads: Arc::default(),
+ site_guard: Arc::default(),
}
}
@@ -996,6 +1002,57 @@ impl BrowserController {
self.reachable_ws_url(advertised)
}
+ /// GET `{endpoint}{path}` as JSON (the DevTools `/json/...` routes).
+ async fn devtools_json(&self, path: &str) -> Result<Value, BrowserError> {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(3))
+ .build()
+ .map_err(|e| BrowserError::Http(e.to_string()))?;
+ let resp = client
+ .get(format!("{}{path}", self.endpoint))
+ .header(reqwest::header::HOST, "localhost")
+ .send()
+ .await
+ .map_err(|e| BrowserError::Http(e.to_string()))?;
+ resp.json().await.map_err(|e| BrowserError::Http(e.to_string()))
+ }
+
+ /// The DevTools target id of this controller's page.
+ async fn page_target_id(&self) -> Result<String, BrowserError> {
+ if let Some(id) = &self.target_id {
+ return Ok(id.clone());
+ }
+ let targets = self.devtools_json("/json/list").await?;
+ targets
+ .as_array()
+ .and_then(|t| t.iter().find(|t| t["type"] == "page"))
+ .and_then(|t| t["id"].as_str())
+ .map(str::to_string)
+ .ok_or_else(|| BrowserError::Protocol("No page to guard".into()))
+ }
+
+ /// Applies the driving bot's site rules: empty rules stop the guard; others start it if it
+ /// isn't running, and return once it intercepts. `Err` when it couldn't be started, so the
+ /// bot's action isn't done unguarded.
+ pub async fn apply_site_rules(&self, rules: super::site_guard::SiteRules) -> Result<(), BrowserError> {
+ if !self.site_guard.set_rules(rules) {
+ return Ok(());
+ }
+ let page = self.page_target_id().await?;
+ let version = self.devtools_json("/json/version").await?;
+ let advertised = version["webSocketDebuggerUrl"]
+ .as_str()
+ .ok_or_else(|| BrowserError::Protocol("Missing webSocketDebuggerUrl".into()))?;
+ let browser_ws = self.reachable_ws_url(advertised)?;
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let task = tokio::spawn(super::site_guard::run(Arc::downgrade(&self.site_guard), browser_ws, page, self.control.clone(), tx));
+ self.site_guard.set_task(task);
+ match timeout(Duration::from_secs(8), rx).await {
+ Ok(Ok(true)) => Ok(()),
+ _ => Err(BrowserError::Protocol("The browser couldn't turn on this bot's site rules".into())),
+ }
+ }
+
async fn ensure_connected(
&self,
guard: &mut tokio::sync::MutexGuard<'_, Option<WsStream>>,
@@ -1169,9 +1226,19 @@ impl BrowserController {
self.pending_capture.lock().await.take()
}
+ /// A bot opens `target_url`: its site rules are checked first, and a redirect they refuse
+ /// 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)?;
- let result = self.navigate_unlocked(target_url).await?;
+ self.site_guard.set_actor(super::site_guard::Actor::Bot);
+ self.site_guard.check(target_url).await.map_err(BrowserError::SiteRule)?;
+ let _ = self.site_guard.take_refusal();
+ let navigated = self.navigate_unlocked(target_url).await;
+ if let Some(refusal) = self.site_guard.take_refusal() {
+ self.leave_refused_page().await;
+ return Err(BrowserError::SiteRule(refusal));
+ }
+ let result = navigated?;
// Bot navigation only: the person decides banners themselves in the live view
if let Some(clicked) = self.reject_consent().await {
tracing::debug!("Declined cookie banner via \"{}\"", clicked);
@@ -1181,6 +1248,36 @@ impl BrowserController {
Ok(result)
}
+ /// After a page the site rules refused: Chrome shows its own error page in its place, so
+ /// go back to the page before it (when there is one), where the bot was.
+ pub async fn leave_refused_page(&self) {
+ let on_error = |v: &Value| v["result"]["value"].as_str().is_some_and(|u| u.starts_with("chrome-error:"));
+ let href = json!({"expression": "location.href", "returnByValue": true});
+ // The error page commits just after the refused request
+ let mut erred = false;
+ for _ in 0..10 {
+ if self.send_cdp_command("Runtime.evaluate", href.clone()).await.is_ok_and(|v| on_error(&v)) {
+ erred = true;
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ if !erred {
+ return;
+ }
+ let Ok(history) = self.send_cdp_command("Page.getNavigationHistory", json!({})).await else { return };
+ let index = history["currentIndex"].as_u64().unwrap_or(0) as usize;
+ let Some(entry) = index.checked_sub(1).and_then(|i| history["entries"].get(i)) else { return };
+ let _ = self.send_cdp_command("Page.navigateToHistoryEntry", json!({"entryId": entry["id"]})).await;
+ for _ in 0..30 {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ if self.send_cdp_command("Runtime.evaluate", href.clone()).await.is_ok_and(|v| !on_error(&v)) {
+ break;
+ }
+ }
+ let _ = self.refresh_location().await;
+ }
+
pub async fn navigate_unlocked(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {
refuse_file_path(target_url)?;
self.progress.lock().unwrap_or_else(|e| e.into_inner()).reset();
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index f96cbe20..31398830 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -7,6 +7,7 @@ pub mod cite;
pub mod progress;
pub mod reads;
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};
diff --git a/src/sandbox/site_guard.rs b/src/sandbox/site_guard.rs
new file mode 100644
index 00000000..6f9a01aa
--- /dev/null
+++ b/src/sandbox/site_guard.rs
@@ -0,0 +1,564 @@
+//! Which sites a bot's browser may open: a per-bot allow-list and block-list of domains, and an
+//! opt-in block on private and loopback addresses. The idea comes from browser-use's security
+//! watchdog (MIT); no code is shared.
+//!
+//! The rules hold for every top-level page a bot's actions load: `browser_open`, a link it clicks,
+//! a redirect, a form it submits, and a new tab its page opens. The person's own live control is
+//! never checked. A guard task intercepts top-level document requests over its own DevTools
+//! connection ([`run`]); it runs only while the driving bot has rules, so a bot without rules
+//! browses exactly as before.
+//!
+//! What it doesn't cover: subframes (an iframe on an allowed page loads from anywhere), a page's
+//! own fetches, images and scripts, and a name whose DNS answer changes between the check and
+//! Chrome's own lookup (DNS rebinding). The private-address check resolves names on the computer
+//! running kwnt, which in VM mode may answer differently from the browser container.
+
+use futures::{SinkExt, StreamExt};
+use serde::Serialize;
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::net::IpAddr;
+use std::sync::{Arc, Mutex, Weak};
+use tokio::sync::RwLock;
+use tokio_tungstenite::tungstenite::Message;
+
+/// Most entries one list may hold.
+pub const MAX_SITES: usize = 200;
+
+/// Rule names, as the bot's settings call them and errors name them.
+pub const ALLOWED: &str = "browser_allowed_sites";
+pub const BLOCKED: &str = "browser_blocked_sites";
+pub const PRIVATE: &str = "browser_block_private_network";
+
+/// One bot's site rules. All empty and off: no checks at all.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct SiteRules {
+ /// When not empty, only these sites (and their subdomains) open.
+ pub allowed: Vec<String>,
+ /// These never open; wins over `allowed`.
+ pub blocked: Vec<String>,
+ /// Refuse loopback, private, link-local and CGNAT addresses, and names that resolve to them.
+ pub block_private: bool,
+}
+
+/// Why a page wasn't opened.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct Refusal {
+ /// [`ALLOWED`], [`BLOCKED`] or [`PRIVATE`].
+ pub rule: &'static str,
+ pub host: String,
+ pub url: String,
+ /// The block-list entry that matched.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub entry: Option<String>,
+ pub message: String,
+}
+
+/// An entry as stored: lowercase host (`example.com`), or `*.example.com` for subdomains only.
+/// A pasted URL keeps its host. `Err` says what's wrong with it.
+pub fn normalize_site(entry: &str) -> Result<String, String> {
+ let raw = entry.trim().to_ascii_lowercase();
+ let bad = || format!("\"{}\" isn't a site: use a domain such as example.com or *.example.com", entry.trim());
+ let (wild, rest) = match raw.strip_prefix("*.") {
+ Some(rest) => (true, rest),
+ None => (false, raw.as_str()),
+ };
+ if rest.is_empty() || rest.contains('*') {
+ return Err(bad());
+ }
+ let with_scheme = if rest.contains("://") { rest.to_string() } else { format!("http://{rest}") };
+ let parsed = url::Url::parse(&with_scheme).map_err(|_| bad())?;
+ let host = match parsed.host() {
+ Some(url::Host::Domain(d)) => d.trim_end_matches('.').to_string(),
+ Some(url::Host::Ipv4(ip)) if !wild => ip.to_string(),
+ Some(url::Host::Ipv6(ip)) if !wild => format!("[{ip}]"),
+ _ => return Err(bad()),
+ };
+ if host.is_empty() || host.starts_with('.') {
+ return Err(bad());
+ }
+ Ok(if wild { format!("*.{host}") } else { host })
+}
+
+/// [`normalize_site`] for a whole list, without duplicates, in the given order.
+pub fn normalize_sites(entries: &[String], field: &str) -> Result<Vec<String>, String> {
+ if entries.len() > MAX_SITES {
+ return Err(format!("{field} holds at most {MAX_SITES} sites"));
+ }
+ let mut out: Vec<String> = Vec::new();
+ for entry in entries {
+ let site = normalize_site(entry).map_err(|e| format!("{field}: {e}"))?;
+ if !out.contains(&site) {
+ out.push(site);
+ }
+ }
+ Ok(out)
+}
+
+/// Whether `entry` covers `host`: `example.com` covers it and its subdomains, `*.example.com`
+/// only the subdomains.
+pub fn site_matches(entry: &str, host: &str) -> bool {
+ match entry.strip_prefix("*.") {
+ Some(base) => host.ends_with(&format!(".{base}")),
+ // An address is only itself; a name covers its subdomains
+ None => host == entry || (!entry.starts_with('[') && entry.parse::<IpAddr>().is_err() && host.ends_with(&format!(".{entry}"))),
+ }
+}
+
+impl SiteRules {
+ pub fn is_empty(&self) -> bool {
+ self.allowed.is_empty() && self.blocked.is_empty() && !self.block_private
+ }
+
+ /// Whether the bot may open `url` as a page. Only web addresses are checked; `about:blank`,
+ /// `data:` and the like reach no site.
+ pub fn check(&self, url: &str) -> Result<(), Refusal> {
+ self.check_with(url, &system_resolve)
+ }
+
+ /// [`Self::check`] with the name lookup supplied (tests).
+ pub fn check_with(&self, url: &str, resolve: &dyn Fn(&str, u16) -> Option<Vec<IpAddr>>) -> Result<(), Refusal> {
+ if self.is_empty() {
+ return Ok(());
+ }
+ let Ok(parsed) = url::Url::parse(url.trim()) else {
+ return Ok(());
+ };
+ if !matches!(parsed.scheme(), "http" | "https" | "ws" | "wss") {
+ return Ok(());
+ }
+ let host = match parsed.host() {
+ Some(url::Host::Domain(d)) => d.trim_end_matches('.').to_ascii_lowercase(),
+ Some(url::Host::Ipv4(ip)) => ip.to_string(),
+ Some(url::Host::Ipv6(ip)) => format!("[{ip}]"),
+ None => String::new(),
+ };
+ let refuse = |rule, entry: Option<String>, message: String| Refusal {
+ rule,
+ host: host.clone(),
+ url: url.to_string(),
+ entry,
+ message,
+ };
+ if let Some(entry) = self.blocked.iter().find(|e| site_matches(e, &host)) {
+ return Err(refuse(
+ BLOCKED,
+ Some(entry.clone()),
+ format!("Not opened: {host} is on this bot's blocked sites ({BLOCKED} has \"{entry}\")."),
+ ));
+ }
+ if !self.allowed.is_empty() && !self.allowed.iter().any(|e| site_matches(e, &host)) {
+ return Err(refuse(
+ ALLOWED,
+ None,
+ format!(
+ "Not opened: {host} isn't on this bot's allowed sites ({ALLOWED}: {}). Work within those sites, or ask the person to add this one.",
+ self.allowed.join(", ")
+ ),
+ ));
+ }
+ if self.block_private && matches!(parsed.scheme(), "http" | "https") {
+ if let Err(why) = crate::mcp::fetch_risk::public_only_with(url, resolve) {
+ return Err(refuse(
+ PRIVATE,
+ None,
+ format!("Not opened: {why}, and this bot may not open local or private network addresses ({PRIVATE} is on)."),
+ ));
+ }
+ }
+ Ok(())
+ }
+}
+
+fn system_resolve(name: &str, port: u16) -> Option<Vec<IpAddr>> {
+ use std::net::ToSocketAddrs;
+ let (tx, rx) = std::sync::mpsc::channel();
+ let target = format!("{name}:{port}");
+ std::thread::spawn(move || {
+ let found = target.to_socket_addrs().map(|a| a.map(|s| s.ip()).collect::<Vec<_>>()).ok();
+ let _ = tx.send(found);
+ });
+ rx.recv_timeout(std::time::Duration::from_secs(2)).ok().flatten()
+}
+
+/// Who caused the browser's latest action: the bot (checked) or the person (never checked).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum Actor {
+ #[default]
+ Bot,
+ Person,
+}
+
+#[derive(Default)]
+struct GuardState {
+ /// The bot whose rules apply: the last one to act in this browser.
+ driver: Option<String>,
+ rules: Option<Arc<SiteRules>>,
+ actor: Actor,
+ refusal: Option<Refusal>,
+ task: Option<tokio::task::JoinHandle<()>>,
+}
+
+/// A browser's site rules and the task that enforces them; see the module docs.
+#[derive(Default)]
+pub struct SiteGuard {
+ state: Mutex<GuardState>,
+}
+
+impl Drop for SiteGuard {
+ fn drop(&mut self) {
+ if let Some(task) = self.lock().task.take() {
+ task.abort();
+ }
+ }
+}
+
+impl SiteGuard {
+ fn lock(&self) -> std::sync::MutexGuard<'_, GuardState> {
+ self.state.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ pub fn driver(&self) -> Option<String> {
+ self.lock().driver.clone()
+ }
+
+ pub fn set_driver(&self, kwant_id: &str) {
+ self.lock().driver = Some(kwant_id.to_string());
+ }
+
+ pub fn rules(&self) -> Option<Arc<SiteRules>> {
+ self.lock().rules.clone()
+ }
+
+ pub fn actor(&self) -> Actor {
+ self.lock().actor
+ }
+
+ pub fn set_actor(&self, actor: Actor) {
+ self.lock().actor = actor;
+ }
+
+ /// The last page the guard refused, taken (each refusal is reported once).
+ pub fn take_refusal(&self) -> Option<Refusal> {
+ self.lock().refusal.take()
+ }
+
+ fn refused(&self, refusal: Refusal) {
+ self.lock().refusal = Some(refusal);
+ }
+
+ /// Sets the rules; `true` when the guard task must (re)start for them.
+ pub(crate) fn set_rules(&self, rules: SiteRules) -> bool {
+ let mut s = self.lock();
+ if rules.is_empty() {
+ s.rules = None;
+ if let Some(task) = s.task.take() {
+ task.abort();
+ }
+ return false;
+ }
+ s.rules = Some(Arc::new(rules));
+ s.task.as_ref().is_none_or(|t| t.is_finished())
+ }
+
+ pub(crate) fn set_task(&self, task: tokio::task::JoinHandle<()>) {
+ if let Some(old) = self.lock().task.replace(task) {
+ old.abort();
+ }
+ }
+
+ /// Whether the guard task is intercepting now.
+ pub fn is_running(&self) -> bool {
+ self.lock().task.as_ref().is_some_and(|t| !t.is_finished())
+ }
+
+ /// The bot's rules on `url`, with the name lookup off the async runtime.
+ pub async fn check(&self, url: &str) -> Result<(), Refusal> {
+ let Some(rules) = self.rules() else {
+ return Ok(());
+ };
+ let url = url.to_string();
+ match tokio::task::spawn_blocking(move || rules.check(&url)).await {
+ Ok(result) => result,
+ Err(_) => Ok(()),
+ }
+ }
+}
+
+type WsStream = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
+type Sink = futures::stream::SplitSink<WsStream, Message>;
+
+const DOCUMENTS: &str = r#"{"patterns":[{"urlPattern":"*","resourceType":"Document","requestStage":"Request"}]}"#;
+
+async fn send(sink: &tokio::sync::Mutex<Sink>, id: u64, method: &str, params: Value, session: Option<&str>) -> bool {
+ let mut msg = json!({"id": id, "method": method, "params": params});
+ if let Some(s) = session {
+ msg["sessionId"] = json!(s);
+ }
+ sink.lock().await.send(Message::Text(msg.to_string())).await.is_ok()
+}
+
+/// The guard task: one browser-level DevTools connection, attached to the bot's page (`page`)
+/// and, paused before they load anything, to every tab that page (or one of its tabs) opens.
+/// Each pauses top-level document requests; the driving bot's rules decide them while the
+/// person isn't in control (`control` write-locked, or the person acted last). `ready` gets
+/// `true` once interception is on. Returns when the connection or the page goes away.
+pub(crate) async fn run(
+ guard: Weak<SiteGuard>,
+ browser_ws: String,
+ page: String,
+ control: Arc<RwLock<()>>,
+ ready: tokio::sync::oneshot::Sender<bool>,
+) {
+ let Ok(mut ws) = super::browser::connect_cdp(&browser_ws).await else {
+ tracing::warn!("site guard: couldn't connect to the browser");
+ let _ = ready.send(false);
+ return;
+ };
+ let documents: Value = serde_json::from_str(DOCUMENTS).unwrap_or_default();
+ // Set up in order, keeping the events that arrive meanwhile for the loop
+ let mut early: Vec<Value> = Vec::new();
+ let mut id = 0u64;
+ let mut call = |method: &str, params: Value, session: Option<&str>| {
+ id += 1;
+ let mut msg = json!({"id": id, "method": method, "params": params});
+ if let Some(s) = session {
+ msg["sessionId"] = json!(s);
+ }
+ (id, msg)
+ };
+ let (attach, msg) = call("Target.attachToTarget", json!({"targetId": page, "flatten": true}), None);
+ let Some(reply) = request(&mut ws, attach, msg, &mut early).await else {
+ let _ = ready.send(false);
+ return;
+ };
+ let Some(main) = reply["result"]["sessionId"].as_str().map(str::to_string) else {
+ tracing::warn!("site guard: couldn't attach to the bot's page: {}", reply["error"]);
+ let _ = ready.send(false);
+ return;
+ };
+ let (enable, msg) = call("Fetch.enable", documents.clone(), Some(&main));
+ let enabled = request(&mut ws, enable, msg, &mut early).await.is_some_and(|r| r.get("error").is_none());
+ let (auto, msg) = call("Target.setAutoAttach", json!({"autoAttach": true, "waitForDebuggerOnStart": true, "flatten": true}), None);
+ let auto_on = request(&mut ws, auto, msg, &mut early).await.is_some_and(|r| r.get("error").is_none());
+ let _ = ready.send(enabled && auto_on);
+ if !(enabled && auto_on) {
+ tracing::warn!("site guard: the browser refused interception");
+ return;
+ }
+
+ let (sink, stream) = ws.split();
+ let sink = Arc::new(tokio::sync::Mutex::new(sink));
+ let ids = Arc::new(std::sync::atomic::AtomicU64::new(id + 1));
+ let next = || ids.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ // session id -> target id, for the bot's page and the tabs it opened
+ let mut ours: HashMap<String, String> = HashMap::from([(main.clone(), page.clone())]);
+ let later = stream.filter_map(|msg| async move {
+ match msg {
+ Ok(Message::Text(text)) => Some(serde_json::from_str::<Value>(&text).unwrap_or_default()),
+ Ok(_) => Some(Value::Null),
+ Err(_) => None,
+ }
+ });
+ let mut messages = futures::stream::iter(early).chain(later).boxed();
+ while let Some(m) = messages.next().await {
+ let params = &m["params"];
+ let session = m["sessionId"].as_str();
+ match m["method"].as_str().unwrap_or_default() {
+ "Target.attachedToTarget" => {
+ let info = &params["targetInfo"];
+ let (Some(child), Some(target)) = (params["sessionId"].as_str(), info["targetId"].as_str()) else { continue };
+ if child == main {
+ continue;
+ }
+ let opener = info["openerId"].as_str().unwrap_or_default();
+ let opened_by_ours = !opener.is_empty() && ours.values().any(|t| t == opener);
+ if info["type"] == "page" && opened_by_ours {
+ ours.insert(child.to_string(), target.to_string());
+ let _ = send(&sink, next(), "Fetch.enable", documents.clone(), Some(child)).await;
+ let _ = send(&sink, next(), "Runtime.runIfWaitingForDebugger", json!({}), Some(child)).await;
+ } else {
+ // Another bot's tab, a worker, the browser's own UI or a second view of the
+ // bot's page: let it go untouched
+ if params["waitingForDebugger"] == json!(true) {
+ let _ = send(&sink, next(), "Runtime.runIfWaitingForDebugger", json!({}), Some(child)).await;
+ }
+ let _ = send(&sink, next(), "Target.detachFromTarget", json!({"sessionId": child}), None).await;
+ }
+ }
+ "Target.detachedFromTarget" => {
+ if let Some(s) = params["sessionId"].as_str() {
+ if s == main {
+ return;
+ }
+ ours.remove(s);
+ }
+ }
+ "Fetch.requestPaused" => {
+ let Some(session) = session.map(str::to_string) else { continue };
+ let request_id = params["requestId"].as_str().unwrap_or_default().to_string();
+ let url = params["request"]["url"].as_str().unwrap_or_default().to_string();
+ let top = ours.get(&session).is_some_and(|t| params["frameId"] == json!(t));
+ // A tab the bot's page opened, not the page itself
+ let opened = (session != main).then(|| ours.get(&session).cloned()).flatten();
+ let Some(g) = guard.upgrade() else { return };
+ let person = g.actor() == Actor::Person || control.try_read().is_err();
+ let rules = if top && !person { g.rules() } else { None };
+ drop(g);
+ let (sink, guard, id, page) = (sink.clone(), guard.clone(), next(), page.clone());
+ let (close_id, front_id) = (next(), next());
+ tokio::spawn(async move {
+ let verdict = match rules {
+ Some(rules) => {
+ let u = url.clone();
+ tokio::task::spawn_blocking(move || rules.check(&u)).await.unwrap_or(Ok(()))
+ }
+ None => Ok(()),
+ };
+ match verdict {
+ Ok(()) => {
+ send(&sink, id, "Fetch.continueRequest", json!({"requestId": request_id}), Some(&session)).await;
+ }
+ Err(refusal) => {
+ tracing::info!(rule = refusal.rule, host = %refusal.host, "site guard refused a page");
+ if let Some(g) = guard.upgrade() {
+ g.refused(refusal);
+ }
+ send(&sink, id, "Fetch.failRequest", json!({"requestId": request_id, "errorReason": "BlockedByClient"}), Some(&session)).await;
+ // A refused new tab would only show an error, and in front it stops the
+ // bot's page (now in the background) from drawing: close it
+ if let Some(tab) = opened {
+ send(&sink, close_id, "Target.closeTarget", json!({"targetId": tab}), None).await;
+ send(&sink, front_id, "Target.activateTarget", json!({"targetId": page}), None).await;
+ }
+ }
+ }
+ });
+ }
+ _ => {}
+ }
+ }
+}
+
+/// Sends `msg` and waits up to 5 s for its reply, keeping the events that come first.
+async fn request(ws: &mut WsStream, id: u64, msg: Value, early: &mut Vec<Value>) -> Option<Value> {
+ ws.send(Message::Text(msg.to_string())).await.ok()?;
+ let wait = async {
+ while let Some(Ok(reply)) = ws.next().await {
+ let Message::Text(text) = reply else { continue };
+ let Ok(v) = serde_json::from_str::<Value>(&text) else { continue };
+ if v["id"].as_u64() == Some(id) {
+ return Some(v);
+ }
+ if v.get("method").is_some() {
+ early.push(v);
+ }
+ }
+ None
+ };
+ tokio::time::timeout(std::time::Duration::from_secs(5), wait).await.ok().flatten()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn rules(allowed: &[&str], blocked: &[&str], block_private: bool) -> SiteRules {
+ SiteRules {
+ allowed: allowed.iter().map(|s| s.to_string()).collect(),
+ blocked: blocked.iter().map(|s| s.to_string()).collect(),
+ block_private,
+ }
+ }
+
+ /// `localtest.me` points at 127.0.0.1, `nas.example` at 192.168.1.20, `example.com` is
+ /// public, anything else doesn't resolve.
+ fn fake(name: &str, _port: u16) -> Option<Vec<IpAddr>> {
+ match name {
+ "localtest.me" => Some(vec!["127.0.0.1".parse().unwrap()]),
+ "nas.example" => Some(vec!["192.168.1.20".parse().unwrap()]),
+ "example.com" | "docs.example.com" => Some(vec!["93.184.216.34".parse().unwrap()]),
+ _ => None,
+ }
+ }
+
+ #[test]
+ fn entries_are_stored_as_lowercase_hosts() {
+ assert_eq!(normalize_site(" Example.COM ").unwrap(), "example.com");
+ assert_eq!(normalize_site("https://docs.example.com/a/b?x").unwrap(), "docs.example.com");
+ assert_eq!(normalize_site("*.Example.com").unwrap(), "*.example.com");
+ assert_eq!(normalize_site("example.com.").unwrap(), "example.com");
+ assert_eq!(normalize_site("bücher.de").unwrap(), "xn--bcher-kva.de");
+ assert_eq!(normalize_site("10.0.0.1").unwrap(), "10.0.0.1");
+ for bad in ["", "*", "*.", "a.*.com", "*.10.0.0.1", "http://"] {
+ assert!(normalize_site(bad).is_err(), "{bad:?} should be refused");
+ }
+ let list = normalize_sites(&["a.com".into(), "A.com".into(), "b.com".into()], ALLOWED).unwrap();
+ assert_eq!(list, ["a.com", "b.com"]);
+ }
+
+ #[test]
+ fn a_domain_covers_its_subdomains_and_a_wildcard_only_those() {
+ assert!(site_matches("example.com", "example.com"));
+ assert!(site_matches("example.com", "docs.example.com"));
+ assert!(!site_matches("example.com", "badexample.com"));
+ assert!(site_matches("*.example.com", "a.b.example.com"));
+ assert!(!site_matches("*.example.com", "example.com"));
+ assert!(!site_matches("10.0.0.1", "x.10.0.0.1"));
+ }
+
+ #[test]
+ fn no_rules_means_no_checks() {
+ let none = SiteRules::default();
+ assert!(none.is_empty());
+ for url in ["http://127.0.0.1:8080/", "http://169.254.169.254/latest", "https://anything.example/"] {
+ assert_eq!(none.check_with(url, &fake), Ok(()));
+ }
+ }
+
+ #[test]
+ fn the_allow_list_refuses_an_off_list_site_and_names_the_rule() {
+ let r = rules(&["example.com"], &[], false);
+ assert_eq!(r.check_with("https://example.com/", &fake), Ok(()));
+ assert_eq!(r.check_with("https://docs.example.com/x", &fake), Ok(()));
+ let no = r.check_with("https://evil.test/login", &fake).unwrap_err();
+ assert_eq!(no.rule, ALLOWED);
+ assert_eq!(no.host, "evil.test");
+ assert!(no.message.contains("browser_allowed_sites: example.com"), "{}", no.message);
+ // Not a site: nothing to check
+ assert_eq!(r.check_with("about:blank", &fake), Ok(()));
+ }
+
+ #[test]
+ fn the_block_list_wins_over_the_allow_list() {
+ let r = rules(&["example.com"], &["ads.example.com"], false);
+ assert_eq!(r.check_with("https://docs.example.com/", &fake), Ok(()));
+ let no = r.check_with("https://x.ads.example.com/", &fake).unwrap_err();
+ assert_eq!((no.rule, no.entry.as_deref()), (BLOCKED, Some("ads.example.com")));
+ assert!(no.message.contains("\"ads.example.com\""), "{}", no.message);
+ // A block-list alone blocks only what it names
+ let r = rules(&[], &["*.example.com"], false);
+ assert_eq!(r.check_with("https://example.com/", &fake), Ok(()));
+ assert_eq!(r.check_with("https://docs.example.com/", &fake).unwrap_err().rule, BLOCKED);
+ }
+
+ #[test]
+ fn the_private_network_block_catches_local_and_internal_addresses() {
+ let r = rules(&[], &[], true);
+ for url in [
+ "http://127.0.0.1:3000/",
+ "http://10.1.2.3/",
+ "http://169.254.169.254/latest/meta-data/",
+ "http://[::1]/",
+ "http://localtest.me/",
+ "http://nas.example/",
+ "http://2130706433/",
+ "http://unresolvable.invalid/",
+ ] {
+ let no = r.check_with(url, &fake).unwrap_err();
+ assert_eq!(no.rule, PRIVATE, "{url}");
+ assert!(no.message.contains("browser_block_private_network"), "{}", no.message);
+ }
+ assert_eq!(r.check_with("https://example.com/", &fake), Ok(()));
+ }
+}
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 03477f98..7f5856b7 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -209,7 +209,11 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
_ => {
let result = if lease.is_none() && !ctrl.is_held_for_person() { Err(BrowserError::HumanControl) } else {
match serde_json::from_value::<BrowserInput>(value.clone()) {
- Ok(input) => ctrl.dispatch_input(input).await,
+ Ok(input) => {
+ // The person's own input: never held to a bot's site rules
+ ctrl.site_guard.set_actor(crate::sandbox::site_guard::Actor::Person);
+ ctrl.dispatch_input(input).await
+ }
Err(_) => Err(BrowserError::Protocol("Invalid browser input".into())),
}
};
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 753837ef..37bdae80 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -676,6 +676,10 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, na
// Each turn is its own reader: a new turn gets the whole page on its first read. A turn
// without an id always gets the whole page
let reader = scope.turn_id.clone().unwrap_or_default();
+ // This bot drives the browser now, so its site rules are the ones that hold
+ if let Some(ctrl) = super::routes::get_or_create_browser_controller(state, target).await {
+ ctrl.site_guard.set_driver(&scope.kwant_id);
+ }
let (text, is_error) = run_browser_tool(state, target, &reader, name, args).await;
// A CAPTCHA wall: ask the person to solve it, then show the agent the page they left
if !is_error {
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 9f8dc4fc..75f9dc80 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -217,7 +217,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/engines/:id", post(engine_routes::set_enabled).put(engine_routes::set_enabled))
.route("/api/laya/status", get(routes::laya_status))
.route("/api/kwants", get(routes::list_kwants).post(routes::create_kwant))
- .route("/api/kwants/:id", put(routes::update_kwant).delete(routes::delete_kwant))
+ .route("/api/kwants/:id", put(routes::put_kwant).delete(routes::delete_kwant))
.route("/api/kwants/:id/usage", get(routes::kwant_usage))
.route("/api/kwants/:id/export", get(import_routes::export_kwant))
.route("/api/export", get(import_routes::export_space))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 53eebda0..96d4ff88 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -175,6 +175,34 @@ pub struct UpdateKwantRequest {
base: UpdateKwant,
#[serde(flatten)]
binding: ProfileBinding,
+ #[serde(flatten)]
+ browser: BrowserSitesUpdate,
+}
+
+type SiteList = Option<Vec<String>>;
+
+/// Which sites the bot's browser may open; a field left out stays as it is.
+#[derive(Debug, Default, Deserialize)]
+pub struct BrowserSitesUpdate {
+ browser_allowed_sites: Option<Vec<String>>,
+ browser_blocked_sites: Option<Vec<String>>,
+ browser_block_private_network: Option<bool>,
+}
+
+impl BrowserSitesUpdate {
+ fn is_empty(&self) -> bool {
+ self.browser_allowed_sites.is_none() && self.browser_blocked_sites.is_none() && self.browser_block_private_network.is_none()
+ }
+
+ /// The lists normalized, or the 400 naming the bad entry.
+ #[allow(clippy::result_large_err)]
+ fn normalized(&self) -> Result<(SiteList, SiteList), Response> {
+ use crate::sandbox::site_guard::{normalize_sites, ALLOWED, BLOCKED};
+ let norm = |list: &Option<Vec<String>>, field| {
+ list.as_ref().map(|l| normalize_sites(l, field)).transpose().map_err(|e| api_error(StatusCode::BAD_REQUEST, &e))
+ };
+ Ok((norm(&self.browser_allowed_sites, ALLOWED)?, norm(&self.browser_blocked_sites, BLOCKED)?))
+ }
}
/// The pinned profile must exist, be in the kwant's space and be for the engine of its model.
@@ -265,6 +293,21 @@ async fn ensure_general(state: &AppState, space: &SpaceId, lead: &str) {
}
}
+/// `PUT /api/kwants/:id`: [`update_kwant`], where only the person may change which sites the
+/// bot's browser may open (a bot can't loosen its own rules).
+#[allow(clippy::result_large_err)]
+pub async fn put_kwant(
+ State(state): State<AppState>,
+ headers: axum::http::HeaderMap,
+ Path(id): Path<String>,
+ Json(payload): Json<UpdateKwantRequest>,
+) -> Result<Json<KwantView>, Response> {
+ if !payload.browser.is_empty() {
+ super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person sets which sites a bot's browser may open").await?;
+ }
+ update_kwant(State(state), Path(id), Json(payload)).await
+}
+
#[allow(clippy::result_large_err)]
pub async fn update_kwant(
State(state): State<AppState>,
@@ -274,6 +317,7 @@ pub async fn update_kwant(
if let Some(msg) = crate::import::check_persona_caps(&payload.base.persona_prompt, &payload.base.soul) {
return Err(api_error(StatusCode::BAD_REQUEST, &msg));
}
+ let (allowed_sites, blocked_sites) = payload.browser.normalized()?;
let space = state
.db
.space_of_kwant(&id)
@@ -291,6 +335,11 @@ pub async fn update_kwant(
Err(e) => return Err(db_error(&e, &clash)),
}
save_binding(&state, &id, &payload.binding).await.map_err(IntoResponse::into_response)?;
+ state
+ .db
+ .set_browser_sites(&id, allowed_sites.as_deref(), blocked_sites.as_deref(), payload.browser.browser_block_private_network)
+ .await
+ .map_err(|e| db_error(&e, ""))?;
kwant_view_json(&state, &id).await.map_err(IntoResponse::into_response)
}
@@ -2095,7 +2144,12 @@ async fn run_kwant_turn_inner(
target_url
)));
if let Some(ctrl) = get_or_create_browser_controller(state, &sandbox_target).await {
- match ctrl.navigate(&target_url).await {
+ ctrl.site_guard.set_driver(&target_kwant.id);
+ let navigated = match guard_bot_action(state, &ctrl, &sandbox_target).await {
+ Ok(()) => ctrl.navigate(&target_url).await,
+ Err(e) => Err(e),
+ };
+ match navigated {
Ok(nav) => {
let page_text = ctrl.extract_content().await.unwrap_or_default();
let preview = truncate_chars(&page_text, 3000);
@@ -2143,6 +2197,12 @@ async fn run_kwant_turn_inner(
prompt, target_url, reason
);
}
+ Err(crate::sandbox::BrowserError::SiteRule(refusal)) => {
+ final_prompt = format!(
+ "{}\n\n[Sandbox Browser State: {} Tell the user this address is outside the sites your browser may open; don't try another way to reach it.]",
+ prompt, refusal.message
+ );
+ }
Err(_) => {}
}
}
@@ -4119,9 +4179,11 @@ pub async fn get_or_create_browser_controller(
// keeps the browser container from being stopped as idle while bots use it
state.browser_service.note_use();
let mut controllers = state.browser_controllers.lock().await;
+ let mut driver = None;
if let Some(ctrl) = controllers.get(team_id) {
if !ctrl.is_managed_session() || ctrl.refresh_location().await.is_ok() { return Some(ctrl.clone()); }
if ctrl.control.try_write().is_err() { return None; }
+ driver = ctrl.site_guard.driver();
controllers.remove(team_id);
}
let (_, workspace) = resolve_sandbox_target_info(state, team_id).await?;
@@ -4131,6 +4193,10 @@ pub async fn get_or_create_browser_controller(
if let Some((owner, _)) = super::passwords::password_owner(state, team_id).await {
ctrl.attach_vault(state.credentials.clone(), &owner).await;
}
+ // The new page keeps the old one's driving bot, so its site rules still hold
+ if let Some(driver) = driver {
+ ctrl.site_guard.set_driver(&driver);
+ }
controllers.insert(team_id.to_string(), ctrl.clone());
let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
team_id: team_id.to_string(), container_name: "browser-service".into(), is_running: true,
@@ -4141,6 +4207,32 @@ pub async fn get_or_create_browser_controller(
}
}
+/// Before a bot's browser action: marks the bot as acting and applies its site rules (the
+/// driving bot's, else the target's when the browser is a bot's own). `Err` when the rules
+/// couldn't be read or turned on, so the action isn't done unguarded.
+pub(crate) async fn guard_bot_action(
+ state: &AppState,
+ ctrl: &crate::sandbox::BrowserController,
+ team_id: &str,
+) -> Result<(), crate::sandbox::BrowserError> {
+ use crate::sandbox::site_guard::Actor;
+ ctrl.site_guard.set_actor(Actor::Bot);
+ let driver = match ctrl.site_guard.driver() {
+ Some(driver) => Some(driver),
+ None => state.db.get_kwant(team_id).await.ok().flatten().map(|k| k.id),
+ };
+ let rules = match &driver {
+ Some(kwant) => state
+ .db
+ .browser_sites(kwant)
+ .await
+ .map_err(|e| crate::sandbox::BrowserError::Protocol(format!("couldn't read the bot's site rules: {e}")))?
+ .rules(),
+ None => Default::default(),
+ };
+ ctrl.apply_site_rules(rules).await
+}
+
pub async fn get_sandbox_status(
State(state): State<AppState>, Path(team_id): Path<String>,
) -> Result<Json<serde_json::Value>, StatusCode> {
@@ -4160,6 +4252,9 @@ fn browser_unavailable(state: &AppState) -> (StatusCode, Json<serde_json::Value>
fn browser_request_failed(error: crate::sandbox::BrowserError) -> (StatusCode, Json<serde_json::Value>) {
if matches!(error, crate::sandbox::BrowserError::HumanControl) { return (StatusCode::CONFLICT, Json(json!({"error": error.to_string()}))); }
if matches!(error, crate::sandbox::BrowserError::NotWebAddress(_)) { return (StatusCode::BAD_REQUEST, Json(json!({"error": error.to_string()}))); }
+ if let crate::sandbox::BrowserError::SiteRule(refusal) = &error {
+ return (StatusCode::FORBIDDEN, Json(json!({"error": refusal.message, "site_rule": refusal})));
+ }
if let crate::sandbox::BrowserError::Navigation(reason) = &error {
return (StatusCode::UNPROCESSABLE_ENTITY, Json(json!({
"error": format!("The site could not be reached ({}). The browser is working; check the address.", reason)
@@ -4233,6 +4328,7 @@ pub async fn navigate_sandbox(
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let ctrl = get_or_create_browser_controller(&state, &team_id).await
.ok_or_else(|| browser_unavailable(&state))?;
+ guard_bot_action(&state, &ctrl, &team_id).await.map_err(browser_request_failed)?;
let nav = ctrl.navigate(&payload.url).await.map_err(browser_request_failed)?;
let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {
@@ -4295,6 +4391,8 @@ pub async fn interact_sandbox(
let ctrl = get_or_create_browser_controller(&state, &team_id).await.ok_or_else(|| browser_unavailable(&state))?;
let _permit = ctrl.control.try_read().map_err(|_| (StatusCode::CONFLICT, Json(json!({"error":"Browser is controlled by a person."}))))?;
+ // The person's own input: their navigation is never held to a bot's site rules
+ ctrl.site_guard.set_actor(crate::sandbox::site_guard::Actor::Person);
let shot_res = match payload.action.as_str() {
"click" => ctrl.interact_click(payload.x.unwrap(), payload.y.unwrap()).await,
"type" => ctrl.interact_type(payload.text.as_deref().unwrap()).await,
@@ -4568,6 +4666,8 @@ pub async fn act_sandbox_allowed(
.await
.ok_or_else(|| browser_unavailable(&state))?;
let _permit = ctrl.control.try_read().map_err(|_| browser_request_failed(crate::sandbox::BrowserError::HumanControl))?;
+ guard_bot_action(&state, &ctrl, &team_id).await.map_err(browser_request_failed)?;
+ let _ = ctrl.site_guard.take_refusal();
let text = payload.text.clone().unwrap_or_default();
let clicks = crate::sandbox::ClickTarget::from_args(&json!({"ref": payload.ref_, "text": payload.text}));
// The loop stop: the same action a 3rd time in a row on this page is refused
@@ -4628,6 +4728,22 @@ pub async fn act_sandbox_allowed(
other
)),
};
+ // A page the action led to that the bot's site rules refused (a link, redirect or new tab):
+ // the request is paused just after the click, so wait a moment for it, then go back from
+ // Chrome's error page to where the bot was
+ let mut refused = ctrl.site_guard.take_refusal();
+ if ctrl.site_guard.is_running() {
+ for _ in 0..3 {
+ if refused.is_some() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ refused = ctrl.site_guard.take_refusal();
+ }
+ }
+ if refused.is_some() {
+ ctrl.leave_refused_page().await;
+ }
broadcast_sandbox_screenshot(&state, &team_id, &ctrl).await;
// What changed; a page that hasn't yet gets one more moment (a slow submit, an animation)
let focus = !matches!(payload.action.as_str(), "click" | "click_text");
@@ -4649,6 +4765,10 @@ pub async fn act_sandbox_allowed(
Ok(done) => page["result"] = json!(done),
Err(err) => page["error"] = json!(err),
}
+ if let Some(refusal) = refused.or_else(|| ctrl.site_guard.take_refusal()) {
+ page["error"] = json!(refusal.message);
+ page["site_rule"] = json!(refusal);
+ }
if let Some(stop) = stall {
page["stalled"] = json!(true);
if page.get("error").is_none() {
diff --git a/tests/browser_site_rules_test.rs b/tests/browser_site_rules_test.rs
new file mode 100644
index 00000000..65f60adf
--- /dev/null
+++ b/tests/browser_site_rules_test.rs
@@ -0,0 +1,262 @@
+//! Which sites a bot's browser may open, through a real Chrome: the rules are set on the bot
+//! (only by the person, normalized, a bad entry refused), and then hold on every navigation the
+//! bot causes (opening an address, a link click, a redirect, a new tab), while the person's own
+//! clicks are never held to them. With no rules the guard doesn't run at all. Skipped when no
+//! Chrome is installed.
+#[path = "support/chrome_guard.rs"]
+mod chrome_guard;
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrome_guard::ChromeGuard;
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::Kwant, spaces::SpaceId, Database},
+ router::LayaRouter,
+ sandbox::computer,
+ server::{create_router, routes::get_or_create_browser_controller, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use tempfile::{tempdir, TempDir};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tower::ServiceExt;
+
+/// Pages on 127.0.0.1, reached as `localhost`, `shop.localhost` (Chrome resolves every
+/// `*.localhost` to loopback) or `127.0.0.1`: three sites without any network.
+async fn serve() -> u16 {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = [0u8; 4096];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let req = String::from_utf8_lossy(&buf[..n]).to_string();
+ let path = req.split_whitespace().nth(1).unwrap_or("/").to_string();
+ let off = format!("http://127.0.0.1:{port}/plain");
+ let reply = if path == "/redir" {
+ format!("HTTP/1.1 302 Found\r\nlocation: {off}\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
+ } else {
+ let page = match path.as_str() {
+ "/links" => format!(
+ "<!doctype html><title>links</title><a href='{off}'>Off list</a> \
+ <a href='{off}' target=_blank>New tab</a> <a href='/plain'>Same site</a>"
+ ),
+ "/person" => format!(
+ "<!doctype html><title>person</title><style>body{{margin:0}}</style>\
+ <a href='{off}' style='display:block;height:400px;background:#eee'>Go</a>"
+ ),
+ _ => "<!doctype html><title>plain</title><p>plain</p>".to_string(),
+ };
+ format!("HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{page}", page.len())
+ };
+ let _ = stream.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ port
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ bot: Kwant,
+ tmp: TempDir,
+}
+
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.set_setting(computer::SETTING_KEY, "local").await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ Env { app: create_router(state.clone()), state, bot, tmp }
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>, token: Option<&str>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ if let Some(token) = token {
+ req = req.header("authorization", format!("Bearer {token}"));
+ }
+ let req = req.body(body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty)).unwrap();
+ let resp = app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+/// The bot's update body (the route takes the whole bot) with `sites` on top.
+fn with_bot(e: &Env, sites: Value) -> Value {
+ let b = &e.bot;
+ let mut body = json!({"name": b.name, "title": b.title, "persona_prompt": b.persona_prompt, "soul": b.soul,
+ "avatar_sprite": b.avatar_sprite, "preferred_model": b.preferred_model});
+ body.as_object_mut().unwrap().extend(sites.as_object().unwrap().clone());
+ body
+}
+
+async fn set_sites(e: &Env, sites: Value) -> (StatusCode, Value) {
+ call(&e.app, "PUT", &format!("/api/kwants/{}", e.bot.id), Some(with_bot(e, sites)), None).await
+}
+
+async fn bot_open(e: &Env, url: &str) -> (StatusCode, Value) {
+ call(&e.app, "POST", &format!("/api/sandbox/{}/navigate", e.bot.id), Some(json!({"url": url})), None).await
+}
+
+async fn bot_click(e: &Env, label: &str) -> Value {
+ let (_, page) = call(&e.app, "GET", &format!("/api/sandbox/{}/page", e.bot.id), None, None).await;
+ let lines = page["clickable"].as_array().unwrap_or_else(|| panic!("a clickable list in {page}"));
+ let line = lines.iter().filter_map(Value::as_str).find(|l| l.contains(label)).unwrap_or_else(|| panic!("{label} in {page}"));
+ let start = line.find('[').unwrap() + 1;
+ let r: u64 = line[start..line.find(']').unwrap()].parse().unwrap();
+ let (status, page) = call(&e.app, "POST", &format!("/api/sandbox/{}/act", e.bot.id), Some(json!({"action": "click", "ref": r})), None).await;
+ assert_eq!(status, StatusCode::OK, "{page}");
+ page
+}
+
+async fn href(ctrl: &kwnt::sandbox::BrowserController) -> String {
+ let v = ctrl
+ .send_cdp_command("Runtime.evaluate", json!({"expression": "location.href", "returnByValue": true}))
+ .await
+ .unwrap();
+ v["result"]["value"].as_str().unwrap_or_default().to_string()
+}
+
+#[tokio::test]
+async fn a_bots_site_rules_hold_on_every_navigation_it_causes() {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let e = setup().await;
+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));
+ let port = serve().await;
+ let off = format!("http://127.0.0.1:{port}/plain");
+
+ // Defaults: no rules, nothing checked and no guard running, as before
+ let (_, list) = call(&e.app, "GET", "/api/kwants", None, None).await;
+ let view = list.as_array().and_then(|l| l.iter().find(|k| k["id"] == json!(e.bot.id))).cloned().unwrap_or_else(|| panic!("{list}"));
+ assert_eq!(view["browser_allowed_sites"], json!([]), "{view}");
+ assert_eq!(view["browser_blocked_sites"], json!([]));
+ assert_eq!(view["browser_block_private_network"], json!(false));
+ let (status, nav) = bot_open(&e, &off).await;
+ assert_eq!(status, StatusCode::OK, "{nav}");
+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.unwrap();
+ assert!(!ctrl.site_guard.is_running());
+
+ // Only the person sets the rules; entries are normalized, a bad one refused whole
+ let (status, _) = call(
+ &e.app,
+ "PUT",
+ &format!("/api/kwants/{}", e.bot.id),
+ Some(with_bot(&e, json!({"browser_allowed_sites": ["example.com"]}))),
+ Some("some-bot-token"),
+ )
+ .await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ let (status, err) = set_sites(&e, json!({"browser_allowed_sites": ["ok.com", "a*b.com"]})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{err}");
+ assert!(err["error"].as_str().unwrap().contains("a*b.com"), "{err}");
+ let (status, view) = set_sites(&e, json!({"browser_allowed_sites": ["LOCALHOST.", "http://localhost/x"]})).await;
+ assert_eq!(status, StatusCode::OK, "{view}");
+ assert_eq!(view["browser_allowed_sites"], json!(["localhost"]));
+
+ // The allow-list refuses an off-list site, naming the rule
+ let (status, refused) = bot_open(&e, &off).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{refused}");
+ assert_eq!(refused["site_rule"]["rule"], "browser_allowed_sites");
+ assert!(refused["error"].as_str().unwrap().contains("isn't on this bot's allowed sites"), "{refused}");
+
+ // A subdomain of an allowed site opens
+ let (status, nav) = bot_open(&e, &format!("http://shop.localhost:{port}/links")).await;
+ assert_eq!(status, StatusCode::OK, "{nav}");
+ assert!(ctrl.site_guard.is_running());
+
+ // A link click off the list is stopped and said; the bot stays where it was
+ let page = bot_click(&e, "Off list").await;
+ assert_eq!(page["site_rule"]["rule"], "browser_allowed_sites", "{page}");
+ let at = href(&ctrl).await;
+ assert!(at.starts_with("http://shop.localhost"), "{at}");
+ // A same-site link still works
+ let page = bot_click(&e, "Same site").await;
+ assert!(page.get("site_rule").is_none(), "{page}");
+ assert_eq!(href(&ctrl).await, format!("http://shop.localhost:{port}/plain"));
+
+ // A new tab off the list is stopped too
+ bot_open(&e, &format!("http://shop.localhost:{port}/links")).await;
+ let pages = || async {
+ let list = ctrl.send_cdp_command("Target.getTargets", json!({})).await.unwrap();
+ list["targetInfos"].as_array().map(|l| l.iter().filter(|t| t["type"] == "page").count()).unwrap_or(0)
+ };
+ let before = pages().await;
+ let page = bot_click(&e, "New tab").await;
+ assert_eq!(page["site_rule"]["host"], "127.0.0.1", "{page}");
+ // ...and the refused tab is closed, so only the bot's own page is left
+ let mut tabs = 0;
+ for _ in 0..20 {
+ tabs = pages().await;
+ if tabs == before {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+ assert_eq!(tabs, before, "the refused tab was closed");
+
+ // A redirect from an allowed site into an off-list one is stopped
+ let (status, refused) = bot_open(&e, &format!("http://localhost:{port}/redir")).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{refused}");
+ assert_eq!(refused["site_rule"]["host"], "127.0.0.1");
+
+ // The block-list wins over the allow-list
+ let (status, _) = set_sites(&e, json!({"browser_blocked_sites": ["shop.localhost"]})).await;
+ assert_eq!(status, StatusCode::OK);
+ let (status, refused) = bot_open(&e, &format!("http://shop.localhost:{port}/plain")).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{refused}");
+ assert_eq!(refused["site_rule"]["rule"], "browser_blocked_sites");
+ assert_eq!(refused["site_rule"]["entry"], "shop.localhost");
+
+ // The person's own click is never held to the bot's rules
+ let (status, _) = bot_open(&e, &format!("http://localhost:{port}/person")).await;
+ assert_eq!(status, StatusCode::OK);
+ let (status, body) =
+ call(&e.app, "POST", &format!("/api/sandbox/{}/interact", e.bot.id), Some(json!({"action": "click", "x": 50, "y": 50})), None).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let mut landed = String::new();
+ for _ in 0..30 {
+ landed = href(&ctrl).await;
+ if landed == off {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+ assert_eq!(landed, off, "the person's click went through");
+
+ // Blocking private addresses: loopback by address or by a name resolving to it, internal
+ // ranges and the cloud metadata address
+ let (status, _) =
+ set_sites(&e, json!({"browser_allowed_sites": [], "browser_blocked_sites": [], "browser_block_private_network": true})).await;
+ assert_eq!(status, StatusCode::OK);
+ for url in [off.clone(), format!("http://localhost:{port}/plain"), "http://10.1.2.3/".into(), "http://169.254.169.254/latest/meta-data/".into()] {
+ let (status, refused) = bot_open(&e, &url).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{url}: {refused}");
+ assert_eq!(refused["site_rule"]["rule"], "browser_block_private_network", "{url}");
+ }
+
+ // Everything off again: today's behaviour, and the guard stops
+ let (status, view) = set_sites(&e, json!({"browser_block_private_network": false})).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(view["browser_block_private_network"], json!(false));
+ let (status, nav) = bot_open(&e, &off).await;
+ assert_eq!(status, StatusCode::OK, "{nav}");
+ assert!(!ctrl.site_guard.is_running());
+}