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
Browser site rules: no wait after a scroll; keep rules on create, export and import
Lin (kwant bot)131b7b2d0039
diff --git a/docs/bot-browser.md b/docs/bot-browser.mdindex ce221805..6bfcb40d 100644--- a/docs/bot-browser.md+++ b/docs/bot-browser.md@@ -122,8 +122,8 @@ 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:+Each bot has three optional settings, set by the person on `PUT /api/kwants/:id` (or when creating+the bot, `POST /api/kwants`) 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.@@ -135,7 +135,12 @@ An entry is a host: `example.com` covers the site and all its subdomains, `*.exasubdomains, 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 nameor 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.+own token can't change these settings (403); only the person can. A bot may set them when it+creates another bot, since they only narrow what the new bot may open.++A bot's export (`kwant.bundle/1`) carries the three settings when they are set, and importing it+restores them, so a copied bot keeps its limits. The import preview names them in a warning, and a+bad entry in the file stops the import as a problem naming it.With both lists empty and the setting off, nothing is checked and nothing extra runs, exactly asbefore. Otherwise every navigation the bot causes is checked: the address it opens (refused before@@ -145,6 +150,10 @@ stopped in the browser (`ERR_BLOCKED_BY_CLIENT`). The bot's action reply carriesmessage 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.+With rules on, a bot action that can load a page (a click, or the Enter or Space key) waits up to+0.3 s for a refusal before replying. A scroll, typing and other keys don't wait. A refusal that+arrives later still comes back on that reply if it's there by the end, or on the bot's next action.+Limits: only top-level pages are checked. Frames, images, scripts and `fetch`/XHR from an allowedpage are not, so this sets which sites a bot visits; it is not a network firewall. Theprivate-network check resolves the name once, so DNS rebinding between that check and Chrome's owndiff --git a/src/db/imports.rs b/src/db/imports.rsindex a4530292..6787fd60 100644--- a/src/db/imports.rs+++ b/src/db/imports.rs@@ -194,8 +194,9 @@ impl Database {let id = Uuid::new_v4().to_string();let avatar = bot.avatar_hint.as_deref().filter(|a| AVATARS.contains(a)).unwrap_or("default");sqlx::query(- "INSERT INTO kwants (id, name, title, persona_prompt, soul, avatar_sprite, driver_type, preferred_model, space_id)- VALUES (?, ?, ?, ?, ?, ?, 'api', 'auto', ?)",+ "INSERT INTO kwants (id, name, title, persona_prompt, soul, avatar_sprite, driver_type, preferred_model, space_id,+ browser_allowed_sites, browser_blocked_sites, browser_block_private_network)+ VALUES (?, ?, ?, ?, ?, ?, 'api', 'auto', ?, ?, ?, ?)",).bind(&id).bind(&bot.name)@@ -204,6 +205,9 @@ impl Database {.bind(&bot.soul).bind(avatar).bind(space.as_str())+ .bind(serde_json::to_string(&bot.browser_allowed_sites).unwrap_or_else(|_| "[]".into()))+ .bind(serde_json::to_string(&bot.browser_blocked_sites).unwrap_or_else(|_| "[]".into()))+ .bind(bot.browser_block_private_network).execute(&mut *tx).await?;// No tools: opted out of every MCP server the space has now.@@ -450,6 +454,7 @@ impl Database {}).collect();let tool_hints = self.list_active_mcp_servers_for_kwant(&k.id).await?.into_iter().map(|s| s.name).collect();+ let sites = self.browser_sites(&k.id).await?;Ok(BotSpec {ref_: k.name.clone(),name: k.name.clone(),@@ -462,6 +467,9 @@ impl Database {skills,routines,tool_hints,+ browser_allowed_sites: sites.browser_allowed_sites,+ browser_blocked_sites: sites.browser_blocked_sites,+ browser_block_private_network: sites.browser_block_private_network,..BotSpec::default()})}diff --git a/src/import/mod.rs b/src/import/mod.rsindex f93ffd91..415b0122 100644--- a/src/import/mod.rs+++ b/src/import/mod.rs@@ -13,6 +13,7 @@ pub mod scrub;use crate::db::continuity::{clean_memory_text, MAX_INSTRUCTIONS_CHARS, MAX_MEMORIES_PER_KWANT, MAX_MEMORY_CHARS};use crate::db::skills::{clean_skill_name, clean_skill_text, MAX_PENDING_PER_KWANT, MAX_SKILL_DESCRIPTION_CHARS};use crate::routines::Schedule;+use crate::sandbox::site_guard;use serde::{Deserialize, Serialize};use std::collections::HashSet;@@ -123,6 +124,14 @@ pub struct BotSpec {/// Files the bot had: "not imported, re-attach these".#[serde(default)]pub knowledge_files: Vec<String>,+ /// Which sites the bot's browser may open (see [`crate::sandbox::site_guard`]); kept so a+ /// bot never loses its limits on the way out and back in.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub browser_allowed_sites: Vec<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub browser_blocked_sites: Vec<String>,+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub browser_block_private_network: bool,}#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]@@ -485,6 +494,21 @@ pub fn suspicious(text: &str) -> Vec<&'static str> {found}+/// A bot's browser site rules in words, or `None` when it has none.+fn site_limits(bot: &BotSpec) -> Option<String> {+ let mut parts = Vec::new();+ if !bot.browser_allowed_sites.is_empty() {+ parts.push(format!("only {}", bot.browser_allowed_sites.join(", ")));+ }+ if !bot.browser_blocked_sites.is_empty() {+ parts.push(format!("never {}", bot.browser_blocked_sites.join(", ")));+ }+ if bot.browser_block_private_network {+ parts.push("no local or private network addresses".to_string());+ }+ (!parts.is_empty()).then(|| parts.join("; "))+}+/// Checks and tidies `bundle` for a space whose bots are called `existing` (any case). Pure: the/// same input always gives the same result, so apply re-runs it on what the preview returned.pub fn normalize(mut bundle: Bundle, existing: &[String]) -> Checked {@@ -583,6 +607,15 @@ pub fn normalize(mut bundle: Bundle, existing: &[String]) -> Checked {if !bot.knowledge_files.is_empty() {dropped.push(Notice::new(who, format!("Files aren't brought over: {}. Attach them again if the bot needs them.", bot.knowledge_files.join(", "))));}+ for (field, list) in [(site_guard::ALLOWED, &mut bot.browser_allowed_sites), (site_guard::BLOCKED, &mut bot.browser_blocked_sites)] {+ match site_guard::normalize_sites(list, field) {+ Ok(sites) => *list = sites,+ Err(e) => problems.push(Notice::new(who, format!("{}'s {e}. Fix it in the file, then try the import again.", bot.name))),+ }+ }+ if let Some(limits) = site_limits(bot) {+ warnings.push(Notice::new(who, format!("Its browser is limited: {limits}. Change this in the bot's settings after importing.")));+ }if !bot.starters.is_empty() {dropped.push(Notice::new(who, format!("{} conversation starter(s): kwant has no place for them yet.", bot.starters.len())));}diff --git a/src/sandbox/site_guard.rs b/src/sandbox/site_guard.rsindex 6f9a01aa..def56237 100644--- a/src/sandbox/site_guard.rs+++ b/src/sandbox/site_guard.rs@@ -181,6 +181,22 @@ fn system_resolve(name: &str, port: u16) -> Option<Vec<IpAddr>> {rx.recv_timeout(std::time::Duration::from_secs(2)).ok().flatten()}+/// How long a bot action that may load a page waits for the guard to refuse it.+pub const NAVIGATION_WAIT: std::time::Duration = std::time::Duration::from_millis(300);++/// Whether a bot action (`act`'s `action`, and `key` for a key press) can load a page: a click,+/// and Enter or Space (which follow a focused link or press a focused button). A scroll, plain+/// typing and other keys can't, so they skip [`NAVIGATION_WAIT`]. A page script that navigates on+/// some other key is still refused by the guard; the bot hears of it on the same reply if the+/// refusal arrives in time, else on its next action.+pub fn may_navigate(action: &str, key: Option<&str>) -> bool {+ match action {+ "scroll" | "type" => false,+ "key" => matches!(key.unwrap_or("Enter"), "Enter" | " " | "Space" | "Spacebar"),+ _ => true,+ }+}+/// 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 {@@ -272,6 +288,25 @@ impl SiteGuard {self.lock().task.as_ref().is_some_and(|t| !t.is_finished())}+ /// A refusal the bot's latest action caused. The guard pauses a refused request just after+ /// the action, so one that [`may_navigate`] waits up to [`NAVIGATION_WAIT`] for it; one that+ /// can't (a scroll, plain typing) only takes what is already there.+ pub async fn refusal_after(&self, may_navigate: bool) -> Option<Refusal> {+ let mut refused = self.take_refusal();+ if !may_navigate || !self.is_running() {+ return refused;+ }+ let step = NAVIGATION_WAIT / 3;+ for _ in 0..3 {+ if refused.is_some() {+ break;+ }+ tokio::time::sleep(step).await;+ refused = self.take_refusal();+ }+ refused+ }+/// 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 {@@ -463,6 +498,38 @@ async fn request(ws: &mut WsStream, id: u64, msg: Value, early: &mut Vec<Value>)mod tests {use super::*;+ #[test]+ fn only_clicks_enter_and_space_may_navigate() {+ for (action, key) in [("click", None), ("click_text", None), ("key", None), ("key", Some("Enter")), ("key", Some(" ")), ("key", Some("Space"))] {+ assert!(may_navigate(action, key), "{action} {key:?}");+ }+ for (action, key) in [("scroll", None), ("type", None), ("key", Some("Tab")), ("key", Some("Escape")), ("key", Some("ArrowDown"))] {+ assert!(!may_navigate(action, key), "{action} {key:?}");+ }+ }++ /// With rules on (the guard task running) and nothing refused, a scroll returns at once and+ /// a click waits for a refusal; a refusal already there comes back either way.+ #[tokio::test]+ async fn an_action_that_cant_navigate_skips_the_wait() {+ let guard = SiteGuard::default();+ guard.set_task(tokio::spawn(std::future::pending::<()>()));+ assert!(guard.is_running());++ let t = std::time::Instant::now();+ assert!(guard.refusal_after(may_navigate("scroll", None)).await.is_none());+ let scroll = t.elapsed();+ let t = std::time::Instant::now();+ assert!(guard.refusal_after(may_navigate("click", None)).await.is_none());+ let click = t.elapsed();+ assert!(scroll < NAVIGATION_WAIT / 3, "scroll waited {scroll:?}");+ assert!(click >= NAVIGATION_WAIT, "click waited only {click:?}");++ let refusal = Refusal { rule: ALLOWED, host: "x.com".into(), url: "https://x.com/".into(), entry: None, message: "no".into() };+ guard.refused(refusal.clone());+ assert_eq!(guard.refusal_after(false).await, Some(refusal));+ }+fn rules(allowed: &[&str], blocked: &[&str], block_private: bool) -> SiteRules {SiteRules {allowed: allowed.iter().map(|s| s.to_string()).collect(),diff --git a/src/server/routes.rs b/src/server/routes.rsindex 96d4ff88..d50fff25 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -167,6 +167,8 @@ pub struct CreateKwantRequest {base: NewKwant,#[serde(flatten)]binding: ProfileBinding,+ #[serde(flatten)]+ browser: BrowserSitesUpdate,}#[derive(Debug, Deserialize)]@@ -264,6 +266,7 @@ pub async fn create_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()?;validate_kwant_name(&state, &space, &mut payload.base.name, None).await?;check_binding(&state, &space, &payload.binding, &payload.base.preferred_model).await@@ -271,6 +274,12 @@ pub async fn create_kwant(let clash = format!("a bot called {} already exists in this space", payload.base.name);let kwant = state.db.create_kwant(&space, &payload.base).await.map_err(|e| db_error(&e, &clash))?;save_binding(&state, &kwant.id, &payload.binding).await.map_err(IntoResponse::into_response)?;+ // A new bot's site rules only narrow what it may open, so a bot creating one may set them too+ state+ .db+ .set_browser_sites(&kwant.id, allowed_sites.as_deref(), blocked_sites.as_deref(), payload.browser.browser_block_private_network)+ .await+ .map_err(|e| db_error(&e, ""))?;ensure_general(&state, &space, &kwant.id).await;kwant_view_json(&state, &kwant.id).await.map_err(IntoResponse::into_response)}@@ -4729,18 +4738,10 @@ pub async fn act_sandbox_allowed()),};// 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();- }- }+ // the request is paused just after a click, so wait a moment for it (not after a scroll or+ // plain typing, which can't navigate), then go back from Chrome's error page to where the bot was+ let may_navigate = crate::sandbox::site_guard::may_navigate(&payload.action, payload.key.as_deref());+ let mut refused = ctrl.site_guard.refusal_after(may_navigate).await;if refused.is_some() {ctrl.leave_refused_page().await;}@@ -4758,6 +4759,14 @@ pub async fn act_sandbox_allowed(after = ctrl.snapshot().await;changed = diff(&after);}+ // A refusal that arrived after the wait (or after an action that skipped it): leave that page too+ if refused.is_none() {+ refused = ctrl.site_guard.take_refusal();+ if refused.is_some() {+ ctrl.leave_refused_page().await;+ after = ctrl.snapshot().await;+ }+ }let stall = ctrl.progress.lock().unwrap_or_else(|e| e.into_inner()).after(changed.is_some());let mut page = page_state_from(&ctrl, after, "").await;page["changed"] = json!(changed.as_deref().unwrap_or("Nothing on the page changed."));@@ -4765,7 +4774,7 @@ 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()) {+ if let Some(refusal) = refused {page["error"] = json!(refusal.message);page["site_rule"] = json!(refusal);}diff --git a/tests/import_test.rs b/tests/import_test.rsindex 78933ddd..7542bbd9 100644--- a/tests/import_test.rs+++ b/tests/import_test.rs@@ -750,3 +750,63 @@ async fn routine_outcomes_are_exported_and_checks_only_when_secret_free() {assert_eq!((r["task_class"].clone(), r["acceptance"].clone(), r["checks"].clone()), (json!("reporting"), json!("report.md exists"), json!([])), "{r}");}}++/// A bot's browser site rules survive being created with them, exported and imported (kwant's+/// copy of a bot), and a bad entry is refused on create and on import, naming it.+#[tokio::test]+async fn browser_site_rules_survive_create_export_and_import() {+ let e = setup().await;+ let a = new_space(&e, "Source").await;+ let b = new_space(&e, "Copy").await;+ let bot = |name: &str, sites: Value| {+ let mut v = json!({"name": name, "title": "Researcher", "persona_prompt": "Reads.", "avatar_sprite": "default",+ "driver_type": "api", "preferred_model": "auto"});+ v.as_object_mut().unwrap().extend(sites.as_object().unwrap().clone());+ v+ };+ let rules = json!({"browser_allowed_sites": ["https://Wikipedia.org/wiki/Cat", "github.com"],+ "browser_blocked_sites": ["en.wikipedia.org"], "browser_block_private_network": true});+ let want = json!({"browser_allowed_sites": ["wikipedia.org", "github.com"],+ "browser_blocked_sites": ["en.wikipedia.org"], "browser_block_private_network": true});+ let fields = |v: &Value| json!({"browser_allowed_sites": v["browser_allowed_sites"],+ "browser_blocked_sites": v["browser_blocked_sites"], "browser_block_private_network": v["browser_block_private_network"]});++ // Create: normalized like PUT; a bad entry is a 400 naming it, and no bot is made+ let (status, made) = json_call(&e.app, "POST", &format!("/api/kwants?space={a}"), bot("Limited", rules.clone())).await;+ assert_eq!(status, StatusCode::OK, "{made}");+ assert_eq!(fields(&made), want);+ let id = made["id"].as_str().unwrap().to_string();+ let (status, err) = json_call(&e.app, "POST", &format!("/api/kwants?space={a}"), bot("Bad", json!({"browser_blocked_sites": ["a*b.com"]}))).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{err}");+ assert!(err.to_string().contains("a*b.com") && err.to_string().contains("browser_blocked_sites"), "{err}");+ assert_eq!(e.state.db.list_kwants(&SpaceId::new(a.clone())).await.unwrap().len(), 1);+ // A bot made without them has none, and its export carries no site fields at all+ let (status, plain) = json_call(&e.app, "POST", &format!("/api/kwants?space={a}"), bot("Plain", json!({}))).await;+ assert_eq!(status, StatusCode::OK, "{plain}");+ assert_eq!(fields(&plain), json!({"browser_allowed_sites": [], "browser_blocked_sites": [], "browser_block_private_network": false}));+ let (_, plain_out) = get(&e.app, &format!("/api/kwants/{}/export?space={a}", plain["id"].as_str().unwrap())).await;+ assert!(!plain_out["bots"][0].as_object().unwrap().keys().any(|k| k.starts_with("browser_")), "{plain_out}");++ // Export → import into another space: the copy has the same rules, and the preview says so+ let (status, out) = get(&e.app, &format!("/api/kwants/{id}/export?space={a}")).await;+ assert_eq!(status, StatusCode::OK, "{out}");+ assert_eq!(fields(&out["bots"][0]), want);+ let (status, p) = send(&e.app, "POST", &format!("/api/import/preview?space={b}&filename=bot.kwant.json"), "application/octet-stream", out.to_string().into_bytes()).await;+ assert_eq!(status, StatusCode::OK, "{p}");+ assert!(p["warnings"].to_string().contains("Its browser is limited: only wikipedia.org, github.com; never en.wikipedia.org; no local or private network addresses"), "{p}");+ let (status, v) = apply(&e.app, &b, &p["bundle"], &[]).await;+ assert_eq!(status, StatusCode::CREATED, "{v}");+ let copy = e.state.db.list_kwants(&SpaceId::new(b.clone())).await.unwrap()[0].id.clone();+ let sites = e.state.db.browser_sites(©).await.unwrap();+ assert_eq!(serde_json::to_value(&sites).unwrap(), want);++ // A bundle with a bad entry stops the import, naming it+ let mut bad = out.clone();+ bad["bots"][0]["browser_allowed_sites"] = json!(["ok.com", "*."]);+ let (status, p) = send(&e.app, "POST", &format!("/api/import/preview?space={b}&filename=bot.kwant.json"), "application/octet-stream", bad.to_string().into_bytes()).await;+ assert_eq!(status, StatusCode::OK, "{p}");+ assert!(p["problems"].to_string().contains("browser_allowed_sites: \\\"*.\\\" isn't a site"), "{p}");+ let (status, v) = apply(&e.app, &b, &bad, &[]).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");+ assert_eq!(e.state.db.list_kwants(&SpaceId::new(b.clone())).await.unwrap().len(), 1);+}