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.

Saved passwords: encrypted vault in the data dir, metadata-only list, exact-origin autofill, confirmed captures (F-1/3/5/6/7)

Lin (kwant bot)353b79bc837d
diff --git a/Cargo.lock b/Cargo.lock
index d51eeb39..8853d159 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1290,6 +1290,7 @@ dependencies = [
"pdf-extract",
"percent-encoding",
"reqwest",
+ "ring",
"rust-embed",
"serde",
"serde_json",
diff --git a/Cargo.toml b/Cargo.toml
index 1ea9e220..f7c7a6de 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -37,6 +37,7 @@ thiserror = "1.0"
dirs = "5.0"
tokio-tungstenite = { version = "0.24", features = ["connect"] }
sha2 = "0.10"
+ring = "0.17"
base64 = "0.22"
url = "2"
tz-rs = "0.7"
diff --git a/src/main.rs b/src/main.rs
index 25537ff1..252ef3a8 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -147,6 +147,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
let state = AppState::new(config.clone(), db, tools, broker, router);
+ // Saved passwords left in a bot's folder by older versions move into the vault
+ kwnt::server::passwords::migrate_all(&state).await;
kwnt::server::scheduler::spawn_background(state.clone(), shutdown.clone());
kwnt::server::engine_routes::spawn_startup_check(state.clone());
let app = create_router(state);
@@ -170,6 +172,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"🔒 Requests from other machines need the API token: run `kwnt token` and open http://<this-host>:{}/#kwnt_token=<token>",
config.port
);
+ } else {
+ println!(
+ "🔒 Saved passwords and approvals need the API token here too: run `kwnt token` and open http://localhost:{}/#kwnt_token=<token> once",
+ config.port
+ );
}
let app = app.into_make_service_with_connect_info::<std::net::SocketAddr>();
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index f97eaeda..a5377f7c 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -1,4 +1,5 @@
use futures::{SinkExt, StreamExt};
+use super::credentials::CredentialStore;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::atomic::{AtomicU64, Ordering};
@@ -127,24 +128,108 @@ pub struct NavigationResult {
pub status_code: u16,
}
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct SavedCredential {
- pub id: String,
- pub domain: String,
+/// A password the person typed into a page, waiting for them to confirm saving it. The origin is
+/// the frame's real URL as Chrome reports it, never anything the page says about itself.
+#[derive(Clone, Serialize, PartialEq)]
+pub struct PendingCapture {
pub origin: String,
pub username: String,
+ #[serde(skip)]
pub password: String,
- pub last_used: String,
+ pub captured_at: String,
}
+impl std::fmt::Debug for PendingCapture {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("PendingCapture")
+ .field("origin", &self.origin)
+ .field("username", &self.username)
+ .finish_non_exhaustive()
+ }
+}
+
+/// The store and owner (team, channel or bot id) a browser fills passwords from.
+#[derive(Clone)]
+pub struct Vault {
+ pub store: Arc<dyn CredentialStore>,
+ pub owner: String,
+}
+
+/// Name of the isolated world kwnt's autofill and capture run in: the page's own scripts share
+/// the DOM but not its JavaScript globals, so they can't read or forge the capture.
+const KWNT_WORLD: &str = "kwnt-autofill";
+
+/// Runs in [`KWNT_WORLD`]; `window` here is that world's own global, not the page's.
+const AUTOFILL_SCRIPT: &str = r#"
+(function(creds) {
+ var USER = 'input[type="text"], input[type="email"], input:not([type]), input[name*="user"], input[name*="login"], input[name*="email"], input[id*="user"], input[id*="login"]';
+ function visible(el) {
+ var r = el.getBoundingClientRect();
+ var s = window.getComputedStyle(el);
+ return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none';
+ }
+ function postsHere(input) {
+ var f = input.form;
+ if (!f || !f.getAttribute('action')) return true;
+ try { return new URL(f.action, location.href).origin === location.origin; } catch (e) { return false; }
+ }
+ function set(input, value) {
+ input.value = value;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ }
+ function fill() {
+ if (!creds || location.origin !== creds.origin) return;
+ var pass = Array.prototype.find.call(document.querySelectorAll('input[type="password"]'), function(p) {
+ return visible(p) && postsHere(p);
+ });
+ if (!pass || pass.value) return;
+ var scope = pass.form || document;
+ var user = Array.prototype.find.call(scope.querySelectorAll(USER), visible);
+ if (user && !user.value && creds.username) set(user, creds.username);
+ set(pass, creds.password);
+ }
+ fill();
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fill);
+ setTimeout(fill, 600);
+ setTimeout(fill, 1800);
+
+ if (window.__kwntCaptureInstalled) return;
+ window.__kwntCaptureInstalled = true;
+ function record(scope) {
+ if (!scope) return;
+ var pass = scope.querySelector('input[type="password"]');
+ if (!pass || !pass.value) return;
+ var user = scope.querySelector(USER);
+ window.__kwntCaptured = { username: user ? user.value : '', password: pass.value };
+ }
+ document.addEventListener('submit', function(e) { record(e.target); }, true);
+ document.addEventListener('click', function(e) {
+ var btn = e.target.closest && e.target.closest('button, input[type="submit"], [role="button"]');
+ if (btn) record(btn.closest('form') || document);
+ }, true);
+})(__KWNT_CREDS__);
+"#;
+
+const COLLECT_SCRIPT: &str = r#"
+(function() {
+ var c = window.__kwntCaptured;
+ window.__kwntCaptured = null;
+ return c ? JSON.stringify(c) : null;
+})()
+"#;
+
#[derive(Clone)]
pub struct BrowserController {
pub cdp_port: u16,
pub current_url: Arc<Mutex<Option<String>>>,
pub current_title: Arc<Mutex<Option<String>>>,
pub last_screenshot: Arc<Mutex<Option<String>>>,
- pub saved_credentials: Arc<Mutex<Vec<SavedCredential>>>,
- pub workspace_dir: Arc<Mutex<Option<std::path::PathBuf>>>,
+ vault: Arc<Mutex<Option<Vault>>>,
+ /// A password captured on the page, waiting for the person's OK.
+ pending_capture: Arc<Mutex<Option<PendingCapture>>>,
+ /// kwnt's isolated world in the current document.
+ capture_world: Arc<Mutex<Option<i64>>>,
msg_id: Arc<AtomicU64>,
ws_conn: Arc<Mutex<Option<WsStream>>>,
endpoint: String,
@@ -168,35 +253,9 @@ impl BrowserController {
current_url: Arc::new(Mutex::new(None)),
current_title: Arc::new(Mutex::new(None)),
last_screenshot: Arc::new(Mutex::new(None)),
- saved_credentials: Arc::new(Mutex::new(Vec::new())),
- workspace_dir: Arc::new(Mutex::new(None)),
- msg_id: Arc::new(AtomicU64::new(1)),
- ws_conn: Arc::new(Mutex::new(None)),
- endpoint: format!("http://127.0.0.1:{cdp_port}"),
- target_id: None,
- browser_level: false,
- control: Arc::new(RwLock::new(())),
- }
- }
-
- pub fn with_workspace(cdp_port: u16, workspace_dir: std::path::PathBuf) -> Self {
- let mut loaded = Vec::new();
- let creds_file = workspace_dir.join(".saved_passwords.json");
- if creds_file.exists() {
- if let Ok(content) = std::fs::read_to_string(&creds_file) {
- if let Ok(creds) = serde_json::from_str::<Vec<SavedCredential>>(&content) {
- loaded = creds;
- }
- }
- }
-
- Self {
- cdp_port,
- current_url: Arc::new(Mutex::new(None)),
- current_title: Arc::new(Mutex::new(None)),
- last_screenshot: Arc::new(Mutex::new(None)),
- saved_credentials: Arc::new(Mutex::new(loaded)),
- workspace_dir: Arc::new(Mutex::new(Some(workspace_dir))),
+ vault: Arc::new(Mutex::new(None)),
+ pending_capture: Arc::new(Mutex::new(None)),
+ capture_world: Arc::new(Mutex::new(None)),
msg_id: Arc::new(AtomicU64::new(1)),
ws_conn: Arc::new(Mutex::new(None)),
endpoint: format!("http://127.0.0.1:{cdp_port}"),
@@ -206,21 +265,13 @@ impl BrowserController {
}
}
- pub async fn set_workspace(&self, ws: std::path::PathBuf) {
- let creds_file = ws.join(".saved_passwords.json");
- if creds_file.exists() {
- if let Ok(content) = std::fs::read_to_string(&creds_file) {
- if let Ok(creds) = serde_json::from_str::<Vec<SavedCredential>>(&content) {
- let mut lock = self.saved_credentials.lock().await;
- *lock = creds;
- }
- }
- }
- *self.workspace_dir.lock().await = Some(ws);
+ /// Fills and captures passwords for `owner` from `store`.
+ pub async fn attach_vault(&self, store: Arc<dyn CredentialStore>, owner: &str) {
+ *self.vault.lock().await = Some(Vault { store, owner: owner.to_string() });
}
- pub fn at_endpoint(endpoint: &str, target_id: Option<String>, workspace: Option<std::path::PathBuf>, browser_level: bool) -> Self {
- let mut ctrl = workspace.map(|ws| Self::with_workspace(0, ws)).unwrap_or_else(|| Self::new(0));
+ pub fn at_endpoint(endpoint: &str, target_id: Option<String>, browser_level: bool) -> Self {
+ let mut ctrl = Self::new(0);
ctrl.endpoint = endpoint.trim_end_matches('/').to_string();
ctrl.target_id = target_id;
ctrl.browser_level = browser_level;
@@ -377,214 +428,99 @@ impl BrowserController {
}
}
- pub async fn list_saved_credentials(&self) -> Vec<SavedCredential> {
- self.saved_credentials.lock().await.clone()
+ async fn vault(&self) -> Option<Vault> {
+ self.vault.lock().await.clone()
}
- pub async fn save_credential(
- &self,
- domain: &str,
- origin: &str,
- username: &str,
- password: &str,
- ) -> SavedCredential {
- let mut lock = self.saved_credentials.lock().await;
- let now = chrono::Utc::now().to_rfc3339();
-
- let clean_domain = if domain.is_empty() {
- if let Ok(parsed) = reqwest::Url::parse(origin) {
- parsed.host_str().unwrap_or(origin).to_string()
- } else {
- origin.to_string()
- }
- } else {
- domain.to_string()
- };
-
- // Check if matching credential exists
- if let Some(existing) = lock.iter_mut().find(|c| {
- (c.domain.eq_ignore_ascii_case(&clean_domain) || (!origin.is_empty() && c.origin == origin))
- && c.username == username
- }) {
- existing.password = password.to_string();
- existing.last_used = now;
- let updated = existing.clone();
- drop(lock);
- self.persist_credentials_to_disk().await;
- return updated;
- }
-
- let new_cred = SavedCredential {
- id: uuid::Uuid::new_v4().to_string(),
- domain: clean_domain,
- origin: origin.to_string(),
- username: username.to_string(),
- password: password.to_string(),
- last_used: now,
- };
-
- lock.push(new_cred.clone());
- drop(lock);
- self.persist_credentials_to_disk().await;
- new_cred
+ /// The main frame's id and real URL, as Chrome reports them.
+ async fn main_frame(&self) -> Option<(String, String)> {
+ let tree = self.send_cdp_command("Page.getFrameTree", json!({})).await.ok()?;
+ let frame = &tree["frameTree"]["frame"];
+ Some((frame["id"].as_str()?.to_string(), frame["url"].as_str()?.to_string()))
}
- pub async fn delete_saved_credential(&self, id: &str) -> bool {
- let mut lock = self.saved_credentials.lock().await;
- let initial_len = lock.len();
- lock.retain(|c| c.id != id);
- let removed = lock.len() < initial_len;
- drop(lock);
- if removed {
- self.persist_credentials_to_disk().await;
- }
- removed
- }
-
- pub async fn get_credential_for_url(&self, target_url: &str) -> Option<SavedCredential> {
- let parsed = reqwest::Url::parse(target_url).ok();
- let target_host = parsed.as_ref().and_then(|u| u.host_str()).unwrap_or(target_url);
- let target_origin = parsed.as_ref().map(|u| u.origin().ascii_serialization()).unwrap_or_default();
-
- let lock = self.saved_credentials.lock().await;
- lock.iter().find(|c| {
- c.domain.eq_ignore_ascii_case(target_host)
- || (!c.origin.is_empty() && c.origin == target_origin)
- || target_host.ends_with(&format!(".{}", c.domain))
- }).cloned()
- }
-
- pub async fn persist_credentials_to_disk(&self) {
- let ws_opt = self.workspace_dir.lock().await.clone();
- if let Some(ws) = ws_opt {
- if tokio::fs::create_dir_all(&ws).await.is_err() { return; }
- let creds = self.saved_credentials.lock().await.clone();
- let creds_file = ws.join(".saved_passwords.json");
- if let Ok(json_str) = serde_json::to_string_pretty(&creds) {
- let _ = std::fs::write(&creds_file, json_str);
- }
- }
+ fn web_origin(url: &str) -> Option<String> {
+ let u = url::Url::parse(url).ok()?;
+ matches!(u.scheme(), "http" | "https").then(|| u.origin().ascii_serialization())
}
- pub async fn inject_autofill_and_capture(&self, target_url: &str) -> Result<(), BrowserError> {
- let cred_opt = self.get_credential_for_url(target_url).await;
- let cred_json = serde_json::to_string(&cred_opt).unwrap_or_else(|_| "null".into());
-
- let script = format!(
- r#"
- (function() {{
- var creds = {};
-
- function fillCredentials() {{
- if (!creds || !creds.password) return;
- var passInput = document.querySelector('input[type="password"]');
- var userInput = document.querySelector('input[type="text"], input[type="email"], input[name*="user"], input[name*="login"], input[name*="email"], input[id*="user"], input[id*="login"]');
- if (passInput) {{
- if (!passInput.value) {{
- passInput.value = creds.password;
- passInput.dispatchEvent(new Event('input', {{ bubbles: true }}));
- passInput.dispatchEvent(new Event('change', {{ bubbles: true }}));
- }}
- }}
- if (userInput) {{
- if (!userInput.value && creds.username) {{
- userInput.value = creds.username;
- userInput.dispatchEvent(new Event('input', {{ bubbles: true }}));
- userInput.dispatchEvent(new Event('change', {{ bubbles: true }}));
- }}
- }}
- }}
-
- fillCredentials();
- if (document.readyState === 'loading') {{
- document.addEventListener('DOMContentLoaded', fillCredentials);
- }}
- setTimeout(fillCredentials, 600);
- setTimeout(fillCredentials, 1800);
-
- if (!window.__kwnt_capture_installed) {{
- window.__kwnt_capture_installed = true;
-
- function recordForm(form) {{
- if (!form) return;
- var passInput = form.querySelector('input[type="password"]');
- if (!passInput || !passInput.value) return;
- var userInput = form.querySelector('input[type="text"], input[type="email"], input[name*="user"], input[name*="login"], input[name*="email"], input[id*="user"], input[id*="login"]');
- var username = userInput ? userInput.value : '';
- var password = passInput.value;
- if (password) {{
- window.__kwnt_captured_creds = {{
- domain: window.location.hostname || window.location.host,
- origin: window.location.origin,
- username: username,
- password: password
- }};
- }}
- }}
-
- document.addEventListener('submit', function(e) {{
- recordForm(e.target);
- }}, true);
-
- document.addEventListener('click', function(e) {{
- var btn = e.target.closest('button, input[type="submit"], [role="button"]');
- if (!btn) return;
- var form = btn.closest('form') || document;
- recordForm(form);
- }}, true);
- }}
- }})();
- "#,
- cred_json
- );
-
+ /// Sets up autofill and capture in kwnt's isolated world of the current document. The saved
+ /// password goes only to a page whose real origin (scheme, host and port) is exactly the
+ /// saved one, into a visible password field whose form posts to the same origin.
+ pub async fn inject_autofill_and_capture(&self) -> Result<(), BrowserError> {
+ *self.capture_world.lock().await = None;
+ let Some(vault) = self.vault().await else { return Ok(()) };
+ let Some((frame_id, url)) = self.main_frame().await else { return Ok(()) };
+ let Some(origin) = Self::web_origin(&url) else { return Ok(()) };
+ let world = self
+ .send_cdp_command("Page.createIsolatedWorld", json!({"frameId": frame_id, "worldName": KWNT_WORLD}))
+ .await?;
+ let Some(context) = world["executionContextId"].as_i64() else { return Ok(()) };
+ *self.capture_world.lock().await = Some(context);
+ let fill = match vault.store.for_origin(&vault.owner, &origin) {
+ Ok(Some(c)) => json!({"origin": origin, "username": c.meta.username, "password": c.password}),
+ _ => Value::Null,
+ };
+ let script = AUTOFILL_SCRIPT.replace("__KWNT_CREDS__", &fill.to_string());
let _ = self
.send_cdp_command(
"Runtime.evaluate",
- json!({ "expression": script, "returnByValue": false }),
+ json!({ "expression": script, "contextId": context, "returnByValue": false }),
)
.await;
-
Ok(())
}
- pub async fn collect_and_save_captured_credentials(&self) -> Result<Option<SavedCredential>, BrowserError> {
- let check_script = r#"
- (function() {
- if (window.__kwnt_captured_creds) {
- var c = window.__kwnt_captured_creds;
- window.__kwnt_captured_creds = null;
- return JSON.stringify(c);
- }
- return null;
- })()
- "#;
-
- let eval_res = self
+ /// Takes a password the person submitted on the page into [`Self::pending_capture`], to be
+ /// saved only when they confirm. The origin comes from the frame's URL, read before and
+ /// after, so a capture is never filed under another site. A capture that equals the saved
+ /// credential (the autofill itself) is dropped.
+ pub async fn collect_captured_credentials(&self) -> Option<PendingCapture> {
+ let context = (*self.capture_world.lock().await)?;
+ let (_, before) = self.main_frame().await?;
+ let r = self
.send_cdp_command(
"Runtime.evaluate",
- json!({ "expression": check_script, "returnByValue": true }),
+ json!({ "expression": COLLECT_SCRIPT, "contextId": context, "returnByValue": true }),
)
.await
- .ok();
-
- if let Some(r) = eval_res {
- if let Some(raw_json) = r["result"]["value"].as_str() {
- if let Ok(val) = serde_json::from_str::<Value>(raw_json) {
- let domain = val["domain"].as_str().unwrap_or("");
- let origin = val["origin"].as_str().unwrap_or("");
- let username = val["username"].as_str().unwrap_or("");
- let password = val["password"].as_str().unwrap_or("");
-
- if !password.is_empty() {
- let saved = self.save_credential(domain, origin, username, password).await;
- return Ok(Some(saved));
- }
+ .ok()?;
+ let raw = r["result"]["value"].as_str()?;
+ let (_, after) = self.main_frame().await?;
+ let origin = Self::web_origin(&before)?;
+ if Self::web_origin(&after).as_deref() != Some(origin.as_str()) {
+ return None;
+ }
+ let val: Value = serde_json::from_str(raw).ok()?;
+ let username = val["username"].as_str().unwrap_or("").to_string();
+ let password = val["password"].as_str().unwrap_or("").to_string();
+ if password.is_empty() {
+ return None;
+ }
+ if let Some(vault) = self.vault().await {
+ if let Ok(Some(saved)) = vault.store.for_origin(&vault.owner, &origin) {
+ if saved.meta.username == username && saved.password == password {
+ return None;
}
}
}
+ let capture = PendingCapture { origin, username, password, captured_at: chrono::Utc::now().to_rfc3339() };
+ self.hold_for_confirmation(capture.clone()).await;
+ Some(capture)
+ }
+
+ /// Holds a captured password until the person saves or discards it (replacing an older one).
+ pub async fn hold_for_confirmation(&self, capture: PendingCapture) {
+ *self.pending_capture.lock().await = Some(capture);
+ }
+
+ /// The capture waiting for the person, if any.
+ pub async fn pending(&self) -> Option<PendingCapture> {
+ self.pending_capture.lock().await.clone()
+ }
- Ok(None)
+ pub async fn take_pending(&self) -> Option<PendingCapture> {
+ self.pending_capture.lock().await.take()
}
pub async fn navigate(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {
@@ -593,7 +529,7 @@ impl BrowserController {
}
pub async fn navigate_unlocked(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {
- let _ = self.collect_and_save_captured_credentials().await;
+ let _ = self.collect_captured_credentials().await;
let _ = self.send_cdp_command("Page.enable", json!({})).await;
let res = self
.send_cdp_command("Page.navigate", json!({ "url": target_url }))
@@ -618,7 +554,7 @@ impl BrowserController {
};
// Automatically inject autofill and capture hooks
- let _ = self.inject_autofill_and_capture(&url).await;
+ let _ = self.inject_autofill_and_capture().await;
// Automatically capture fresh screenshot on navigation
self.capture_screenshot().await?;
@@ -688,7 +624,7 @@ impl BrowserController {
return Err(BrowserError::Protocol("Element not found for selector".into()));
}
tokio::time::sleep(Duration::from_millis(500)).await;
- let _ = self.collect_and_save_captured_credentials().await;
+ let _ = self.collect_captured_credentials().await;
let _ = self.capture_screenshot().await;
Ok(())
}
@@ -832,7 +768,7 @@ impl BrowserController {
.await?;
tokio::time::sleep(Duration::from_millis(150)).await;
- let _ = self.collect_and_save_captured_credentials().await;
+ let _ = self.collect_captured_credentials().await;
let _ = self.sync_location().await;
self.capture_screenshot().await
}
@@ -845,7 +781,7 @@ impl BrowserController {
.await?;
tokio::time::sleep(Duration::from_millis(150)).await;
- let _ = self.collect_and_save_captured_credentials().await;
+ let _ = self.collect_captured_credentials().await;
let _ = self.sync_location().await;
self.capture_screenshot().await
}
@@ -870,7 +806,7 @@ impl BrowserController {
self.send_cdp_command("Input.dispatchKeyEvent", up_params).await?;
tokio::time::sleep(Duration::from_millis(150)).await;
- let _ = self.collect_and_save_captured_credentials().await;
+ let _ = self.collect_captured_credentials().await;
let _ = self.sync_location().await;
self.capture_screenshot().await
}
diff --git a/src/sandbox/credentials.rs b/src/sandbox/credentials.rs
new file mode 100644
index 00000000..954d7590
--- /dev/null
+++ b/src/sandbox/credentials.rs
@@ -0,0 +1,448 @@
+//! Saved website passwords, kept where no bot's tools look: `<data_dir>/kwnt-vault/<owner>.bin`,
+//! each file AES-256-GCM encrypted with the key in `<data_dir>/kwnt-vault.key` (both owner-only,
+//! 0600 files in 0700 folders). An owner is the team, channel or bot whose browser uses them.
+//!
+//! [`CredentialStore`] is the seam for an external password manager (Proton Pass, Bitwarden,
+//! 1Password CLI) later; [`EncryptedFileStore`] is the built-in one.
+//!
+//! A bot running as the same OS user could still read both files with approvals off; kwnt
+//! refuses tool calls that name them ([`mentions_kwnt_secrets`]), which raises the bar but is
+//! not a wall. Only another OS user (or a container) is.
+
+use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM, NONCE_LEN};
+use ring::rand::{SecureRandom, SystemRandom};
+use serde::{Deserialize, Serialize};
+use std::path::{Path, PathBuf};
+
+pub const VAULT_DIR: &str = "kwnt-vault";
+pub const KEY_FILE: &str = "kwnt-vault.key";
+/// The legacy plaintext file browsers used to keep in a bot's folder.
+pub const LEGACY_FILE: &str = ".saved_passwords.json";
+
+#[derive(Debug, thiserror::Error)]
+pub enum StoreError {
+ #[error("credential store I/O failed: {0}")]
+ Io(#[from] std::io::Error),
+ #[error("credential store could not be decrypted")]
+ Crypto,
+ #[error("invalid origin: {0}")]
+ Origin(String),
+}
+
+/// What the app may see about a saved password: never the password itself.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct CredentialMeta {
+ pub id: String,
+ /// `scheme://host[:port]`; the password is only filled on exactly this origin.
+ pub origin: String,
+ pub username: String,
+ pub created_at: String,
+ pub last_used: String,
+}
+
+/// A saved password. `Debug` never prints the password.
+#[derive(Clone, Serialize, Deserialize, PartialEq)]
+pub struct Credential {
+ #[serde(flatten)]
+ pub meta: CredentialMeta,
+ pub password: String,
+}
+
+impl std::fmt::Debug for Credential {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Credential")
+ .field("meta", &self.meta)
+ .field("password", &"[redacted]")
+ .finish()
+ }
+}
+
+/// Where saved passwords live. Every call names its owner (team, channel or bot id).
+pub trait CredentialStore: Send + Sync {
+ fn list(&self, owner: &str) -> Result<Vec<CredentialMeta>, StoreError>;
+ fn get(&self, owner: &str, id: &str) -> Result<Option<Credential>, StoreError>;
+ /// The credential to fill on a page whose origin is exactly `origin`.
+ fn for_origin(&self, owner: &str, origin: &str) -> Result<Option<Credential>, StoreError>;
+ /// Adds a credential, or replaces the password of the same origin + username.
+ fn save(&self, owner: &str, origin: &str, username: &str, password: &str) -> Result<CredentialMeta, StoreError>;
+ fn delete(&self, owner: &str, id: &str) -> Result<bool, StoreError>;
+}
+
+/// `scheme://host[:port]` of an http(s) URL, or of a bare host (taken as https).
+pub fn normalize_origin(input: &str) -> Result<String, StoreError> {
+ let raw = input.trim();
+ let with_scheme = if raw.contains("://") { raw.to_string() } else { format!("https://{raw}") };
+ let url = url::Url::parse(&with_scheme).map_err(|_| StoreError::Origin(raw.to_string()))?;
+ if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none_or(str::is_empty) {
+ return Err(StoreError::Origin(raw.to_string()));
+ }
+ Ok(url.origin().ascii_serialization())
+}
+
+/// Whether a tool call's text names kwnt's own secret files (the vault, its key, the API token).
+pub fn mentions_kwnt_secrets(text: &str) -> bool {
+ let t = text.to_ascii_lowercase();
+ t.contains(VAULT_DIR) || t.contains("api-token") || t.contains(LEGACY_FILE) || t.contains("kwnt token")
+}
+
+/// Whether a tool call's arguments name kwnt's own secret files: in any text, or through a path
+/// argument that resolves there (a symlink, `..`), relative to `cwd`.
+pub fn call_touches_kwnt_secrets(arguments: &serde_json::Value, cwd: Option<&Path>) -> bool {
+ use serde_json::Value;
+ if mentions_kwnt_secrets(&arguments.to_string()) {
+ return true;
+ }
+ let resolves_there = |s: &str| {
+ let p = Path::new(s);
+ let p = match (p.is_absolute(), cwd) {
+ (true, _) => p.to_path_buf(),
+ (false, Some(cwd)) => cwd.join(p),
+ (false, None) => return false,
+ };
+ std::fs::canonicalize(&p).is_ok_and(|real| mentions_kwnt_secrets(&real.to_string_lossy()))
+ };
+ fn walk(v: &Value, f: &dyn Fn(&str) -> bool) -> bool {
+ match v {
+ Value::String(s) => f(s),
+ Value::Array(a) => a.iter().any(|v| walk(v, f)),
+ Value::Object(m) => m.values().any(|v| walk(v, f)),
+ _ => false,
+ }
+ }
+ walk(arguments, &|s: &str| s.len() < 4096 && !s.contains('\n') && resolves_there(s.trim()))
+}
+
+pub struct EncryptedFileStore {
+ dir: PathBuf,
+ key: LessSafeKey,
+ rng: SystemRandom,
+ lock: std::sync::Mutex<()>,
+}
+
+impl std::fmt::Debug for EncryptedFileStore {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("EncryptedFileStore").field("dir", &self.dir).finish_non_exhaustive()
+ }
+}
+
+#[cfg(unix)]
+fn private_dir(path: &Path) -> std::io::Result<()> {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::create_dir_all(path)?;
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
+}
+
+#[cfg(not(unix))]
+fn private_dir(path: &Path) -> std::io::Result<()> {
+ std::fs::create_dir_all(path)
+}
+
+/// Writes `bytes` to `path` as a new 0600 file, via a temp file and a rename.
+fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ use std::io::Write;
+ let tmp = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4().simple()));
+ let mut opts = std::fs::OpenOptions::new();
+ opts.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ opts.mode(0o600);
+ }
+ let result = (|| {
+ let mut f = opts.open(&tmp)?;
+ f.write_all(bytes)?;
+ f.sync_all()?;
+ std::fs::rename(&tmp, path)
+ })();
+ if result.is_err() {
+ let _ = std::fs::remove_file(&tmp);
+ }
+ result
+}
+
+fn load_or_create_key(path: &Path, rng: &SystemRandom) -> Result<[u8; 32], StoreError> {
+ if let Ok(bytes) = std::fs::read(path) {
+ if let Ok(key) = <[u8; 32]>::try_from(bytes.as_slice()) {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
+ }
+ return Ok(key);
+ }
+ // A key of the wrong size would make every saved password unreadable: refuse to replace it
+ return Err(StoreError::Crypto);
+ }
+ let mut key = [0u8; 32];
+ rng.fill(&mut key).map_err(|_| StoreError::Crypto)?;
+ write_private(path, &key)?;
+ Ok(key)
+}
+
+/// A file name for an owner id; ids are uuids, anything else is hashed.
+fn owner_file(owner: &str) -> String {
+ let plain = !owner.is_empty() && owner.len() <= 64 && owner.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
+ if plain {
+ format!("{owner}.bin")
+ } else {
+ use sha2::{Digest, Sha256};
+ let digest = Sha256::digest(owner.as_bytes());
+ format!("h-{}.bin", digest.iter().take(16).map(|b| format!("{b:02x}")).collect::<String>())
+ }
+}
+
+impl EncryptedFileStore {
+ /// Opens (or creates) the store under `data_dir`.
+ pub fn open(data_dir: &Path) -> Result<Self, StoreError> {
+ private_dir(data_dir)?;
+ let dir = data_dir.join(VAULT_DIR);
+ private_dir(&dir)?;
+ let rng = SystemRandom::new();
+ let key = load_or_create_key(&data_dir.join(KEY_FILE), &rng)?;
+ let key = LessSafeKey::new(UnboundKey::new(&AES_256_GCM, &key).map_err(|_| StoreError::Crypto)?);
+ Ok(Self { dir, key, rng, lock: std::sync::Mutex::new(()) })
+ }
+
+ fn path(&self, owner: &str) -> PathBuf {
+ self.dir.join(owner_file(owner))
+ }
+
+ fn read(&self, owner: &str) -> Result<Vec<Credential>, StoreError> {
+ let bytes = match std::fs::read(self.path(owner)) {
+ Ok(b) => b,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(e) => return Err(e.into()),
+ };
+ if bytes.len() < NONCE_LEN {
+ return Err(StoreError::Crypto);
+ }
+ let (nonce, sealed) = bytes.split_at(NONCE_LEN);
+ let nonce = Nonce::try_assume_unique_for_key(nonce).map_err(|_| StoreError::Crypto)?;
+ let mut sealed = sealed.to_vec();
+ // The owner is the associated data: a file copied to another owner's name won't open
+ let plain = self
+ .key
+ .open_in_place(nonce, Aad::from(owner.as_bytes()), &mut sealed)
+ .map_err(|_| StoreError::Crypto)?;
+ serde_json::from_slice(plain).map_err(|_| StoreError::Crypto)
+ }
+
+ fn write(&self, owner: &str, creds: &[Credential]) -> Result<(), StoreError> {
+ let path = self.path(owner);
+ if creds.is_empty() {
+ return match std::fs::remove_file(&path) {
+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
+ _ => Ok(()),
+ };
+ }
+ let mut nonce = [0u8; NONCE_LEN];
+ self.rng.fill(&mut nonce).map_err(|_| StoreError::Crypto)?;
+ let mut data = serde_json::to_vec(creds).map_err(|_| StoreError::Crypto)?;
+ self.key
+ .seal_in_place_append_tag(Nonce::assume_unique_for_key(nonce), Aad::from(owner.as_bytes()), &mut data)
+ .map_err(|_| StoreError::Crypto)?;
+ let mut out = nonce.to_vec();
+ out.extend_from_slice(&data);
+ write_private(&path, &out)?;
+ Ok(())
+ }
+
+ fn guard(&self) -> std::sync::MutexGuard<'_, ()> {
+ self.lock.lock().unwrap_or_else(|p| p.into_inner())
+ }
+}
+
+impl CredentialStore for EncryptedFileStore {
+ fn list(&self, owner: &str) -> Result<Vec<CredentialMeta>, StoreError> {
+ let _g = self.guard();
+ Ok(self.read(owner)?.into_iter().map(|c| c.meta).collect())
+ }
+
+ fn get(&self, owner: &str, id: &str) -> Result<Option<Credential>, StoreError> {
+ let _g = self.guard();
+ Ok(self.read(owner)?.into_iter().find(|c| c.meta.id == id))
+ }
+
+ fn for_origin(&self, owner: &str, origin: &str) -> Result<Option<Credential>, StoreError> {
+ let Ok(origin) = normalize_origin(origin) else { return Ok(None) };
+ let _g = self.guard();
+ Ok(self.read(owner)?.into_iter().find(|c| c.meta.origin == origin))
+ }
+
+ fn save(&self, owner: &str, origin: &str, username: &str, password: &str) -> Result<CredentialMeta, StoreError> {
+ let origin = normalize_origin(origin)?;
+ let _g = self.guard();
+ let mut creds = self.read(owner)?;
+ let now = chrono::Utc::now().to_rfc3339();
+ let meta = match creds.iter_mut().find(|c| c.meta.origin == origin && c.meta.username == username) {
+ Some(existing) => {
+ existing.password = password.to_string();
+ existing.meta.last_used = now;
+ existing.meta.clone()
+ }
+ None => {
+ let meta = CredentialMeta {
+ id: uuid::Uuid::new_v4().to_string(),
+ origin,
+ username: username.to_string(),
+ created_at: now.clone(),
+ last_used: now,
+ };
+ creds.push(Credential { meta: meta.clone(), password: password.to_string() });
+ meta
+ }
+ };
+ self.write(owner, &creds)?;
+ Ok(meta)
+ }
+
+ fn delete(&self, owner: &str, id: &str) -> Result<bool, StoreError> {
+ let _g = self.guard();
+ let mut creds = self.read(owner)?;
+ let before = creds.len();
+ creds.retain(|c| c.meta.id != id);
+ if creds.len() == before {
+ return Ok(false);
+ }
+ self.write(owner, &creds)?;
+ Ok(true)
+ }
+}
+
+/// Stands in when the store can't be opened (an unreadable key): every call fails, nothing is
+/// written, and the key file is left alone for the person to restore.
+#[derive(Debug)]
+pub struct UnavailableStore;
+
+impl CredentialStore for UnavailableStore {
+ fn list(&self, _: &str) -> Result<Vec<CredentialMeta>, StoreError> {
+ Err(StoreError::Crypto)
+ }
+ fn get(&self, _: &str, _: &str) -> Result<Option<Credential>, StoreError> {
+ Err(StoreError::Crypto)
+ }
+ fn for_origin(&self, _: &str, _: &str) -> Result<Option<Credential>, StoreError> {
+ Err(StoreError::Crypto)
+ }
+ fn save(&self, _: &str, _: &str, _: &str, _: &str) -> Result<CredentialMeta, StoreError> {
+ Err(StoreError::Crypto)
+ }
+ fn delete(&self, _: &str, _: &str) -> Result<bool, StoreError> {
+ Err(StoreError::Crypto)
+ }
+}
+
+/// The built-in store under `data_dir`, or [`UnavailableStore`] when it can't be opened.
+pub fn open_store(data_dir: &Path) -> std::sync::Arc<dyn CredentialStore> {
+ match EncryptedFileStore::open(data_dir) {
+ Ok(s) => std::sync::Arc::new(s),
+ Err(e) => {
+ tracing::error!(error = %e, "saved passwords are unavailable: the vault could not be opened");
+ std::sync::Arc::new(UnavailableStore)
+ }
+ }
+}
+
+/// The legacy plaintext entry shape (`.saved_passwords.json`).
+#[derive(Deserialize)]
+struct LegacyCredential {
+ #[serde(default)]
+ domain: String,
+ #[serde(default)]
+ origin: String,
+ #[serde(default)]
+ username: String,
+ #[serde(default)]
+ password: String,
+}
+
+/// Moves `<folder>/.saved_passwords.json` into the store for each of `owners`, then deletes the
+/// file. Returns how many credentials were moved. A file that can't be parsed is left in place.
+pub fn migrate_legacy(store: &dyn CredentialStore, folder: &Path, owners: &[&str]) -> Result<usize, StoreError> {
+ let file = folder.join(LEGACY_FILE);
+ let content = match std::fs::read_to_string(&file) {
+ Ok(c) => c,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
+ Err(e) => return Err(e.into()),
+ };
+ let Ok(legacy) = serde_json::from_str::<Vec<LegacyCredential>>(&content) else {
+ tracing::warn!(file = %file.display(), "a saved-passwords file could not be read; left in place");
+ return Ok(0);
+ };
+ let mut moved = 0;
+ for c in &legacy {
+ if c.password.is_empty() {
+ continue;
+ }
+ let source = if c.origin.is_empty() { c.domain.as_str() } else { c.origin.as_str() };
+ let Ok(origin) = normalize_origin(source) else { continue };
+ for owner in owners {
+ store.save(owner, &origin, &c.username, &c.password)?;
+ }
+ moved += 1;
+ }
+ std::fs::remove_file(&file)?;
+ Ok(moved)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn origins_are_exact() {
+ assert_eq!(normalize_origin("example.com").unwrap(), "https://example.com");
+ assert_eq!(normalize_origin("https://Example.com/login?x=1").unwrap(), "https://example.com");
+ assert_eq!(normalize_origin("http://127.0.0.1:8080/a").unwrap(), "http://127.0.0.1:8080");
+ assert!(normalize_origin("file:///etc/passwd").is_err());
+ assert!(normalize_origin("javascript:alert(1)").is_err());
+ }
+
+ #[test]
+ fn encrypted_round_trip_and_private_files() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = EncryptedFileStore::open(dir.path()).unwrap();
+ let meta = store.save("team-1", "https://example.com/login", "alice", "DUMMY-PW-1").unwrap();
+ assert_eq!(meta.origin, "https://example.com");
+ let raw = std::fs::read(dir.path().join(VAULT_DIR).join("team-1.bin")).unwrap();
+ assert!(!String::from_utf8_lossy(&raw).contains("DUMMY-PW-1"));
+ assert!(!String::from_utf8_lossy(&raw).contains("alice"));
+ assert_eq!(store.get("team-1", &meta.id).unwrap().unwrap().password, "DUMMY-PW-1");
+ assert!(store.list("team-2").unwrap().is_empty());
+ assert!(!format!("{:?}", store.get("team-1", &meta.id).unwrap()).contains("DUMMY"));
+ // same origin + username replaces
+ store.save("team-1", "https://example.com", "alice", "DUMMY-PW-2").unwrap();
+ assert_eq!(store.list("team-1").unwrap().len(), 1);
+ // reopen with the same key
+ let again = EncryptedFileStore::open(dir.path()).unwrap();
+ assert_eq!(again.get("team-1", &meta.id).unwrap().unwrap().password, "DUMMY-PW-2");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = |p: PathBuf| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode(dir.path().join(KEY_FILE)), 0o600);
+ assert_eq!(mode(dir.path().join(VAULT_DIR)), 0o700);
+ assert_eq!(mode(dir.path().join(VAULT_DIR).join("team-1.bin")), 0o600);
+ }
+ assert!(store.delete("team-1", &meta.id).unwrap());
+ assert!(!dir.path().join(VAULT_DIR).join("team-1.bin").exists());
+ }
+
+ #[test]
+ fn a_file_moved_to_another_owner_does_not_open() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = EncryptedFileStore::open(dir.path()).unwrap();
+ store.save("a", "https://example.com", "u", "DUMMY").unwrap();
+ let v = dir.path().join(VAULT_DIR);
+ std::fs::copy(v.join("a.bin"), v.join("b.bin")).unwrap();
+ assert!(matches!(store.list("b"), Err(StoreError::Crypto)));
+ }
+
+ #[test]
+ fn secret_mentions() {
+ assert!(mentions_kwnt_secrets("cat ~/.kwnt/kwnt-vault.key"));
+ assert!(mentions_kwnt_secrets("cat /data/API-TOKEN"));
+ assert!(mentions_kwnt_secrets("kwnt token"));
+ assert!(!mentions_kwnt_secrets("touch x"));
+ }
+}
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index 32c9aaef..3d97bf9c 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -1,8 +1,10 @@
pub mod browser;
pub mod computer;
+pub mod credentials;
pub mod manager;
pub mod service;
-pub use browser::{detect_bot_wall, BrowserController, BrowserError, NavigationResult, SavedCredential};
+pub use browser::{detect_bot_wall, BrowserController, BrowserError, NavigationResult, PendingCapture};
+pub use credentials::{Credential, CredentialMeta, CredentialStore, EncryptedFileStore};
pub use manager::{ActiveSandbox, SandboxError, SandboxManager, ShellOutput};
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rs
index 9919dcbf..7363894a 100644
--- a/src/sandbox/service.rs
+++ b/src/sandbox/service.rs
@@ -64,7 +64,7 @@ impl BrowserService {
// the page each bot had open, to reopen in the new Chrome
let mut urls: HashMap<String, String> = HashMap::new();
if let Some((endpoint, _)) = computer::running_local_chrome(&self.local_profile()).await {
- let browser = BrowserController::at_endpoint(&endpoint, None, None, true);
+ let browser = BrowserController::at_endpoint(&endpoint, None, true);
if let Ok(targets) = browser.send_cdp_command("Target.getTargets", json!({})).await {
for info in targets["targetInfos"].as_array().into_iter().flatten() {
if let (Some(id), Some(url)) = (info["targetId"].as_str(), info["url"].as_str()) {
@@ -107,7 +107,7 @@ impl BrowserService {
if let Some((endpoint, running_headless)) = computer::running_local_chrome(&profile).await {
if running_headless == headless { return Ok(endpoint); }
// the other form is running on this profile: close it first
- let _ = BrowserController::at_endpoint(&endpoint, None, None, true)
+ let _ = BrowserController::at_endpoint(&endpoint, None, true)
.send_cdp_command("Browser.close", json!({})).await;
computer::wait_local_chrome_gone(&profile).await.map_err(BrowserError::Http)?;
}
@@ -138,7 +138,7 @@ impl BrowserService {
*lock = None;
if previous == ComputerMode::Local {
if let Some((endpoint, true)) = computer::running_local_chrome(&self.local_profile()).await {
- let _ = BrowserController::at_endpoint(&endpoint, None, None, true)
+ let _ = BrowserController::at_endpoint(&endpoint, None, true)
.send_cdp_command("Browser.close", json!({})).await;
}
}
@@ -202,7 +202,7 @@ impl BrowserService {
Some(endpoint) => endpoint.trim_end_matches('/').to_string(),
None => self.managed_endpoint().await?,
};
- let browser = BrowserController::at_endpoint(&endpoint, None, None, true);
+ let browser = BrowserController::at_endpoint(&endpoint, None, true);
if self.endpoint.is_some() || local {
browser.send_cdp_command("Browser.getVersion", json!({})).await?;
} else { timeout(Duration::from_secs(30), async {
@@ -216,7 +216,7 @@ impl BrowserService {
Ok(ServiceState { browser, endpoint, sessions })
}
- pub async fn session(&self, id: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {
+ pub async fn session(&self, id: &str, _workspace: &Path) -> Result<BrowserController, BrowserError> {
let mut lock = self.state.lock().await;
if lock.is_none() { *lock = Some(self.connect().await?); }
let mut targets = lock.as_ref().unwrap().browser.send_cdp_command("Target.getTargets", json!({})).await;
@@ -263,7 +263,7 @@ impl BrowserService {
};
state.sessions.insert(id.to_string(), session.clone());
self.save_sessions(&state.sessions).await?;
- let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target), Some(workspace.to_path_buf()), false);
+ let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target), false);
// A real window keeps its own size; a windowless browser gets the viewer's fixed viewport.
if !local || !self.local_window() {
ctrl.send_cdp_command("Emulation.setDeviceMetricsOverride", json!({
diff --git a/src/server/mod.rs b/src/server/mod.rs
index a7f0bb4f..10e54bfc 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -25,6 +25,7 @@ pub mod bot_actions;
pub mod hires;
pub mod import_routes;
pub mod approval_modes;
+pub mod passwords;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -75,6 +76,8 @@ pub struct AppState {
pub claude_login: Arc<engine_login::ClaudeLogin>,
/// The MCP Registry agents search and suggest servers from (`KWNT_MCP_REGISTRY_URL`).
pub mcp_registry: Arc<crate::mcp::registry::McpRegistry>,
+ /// Saved website passwords, outside every bot's folder (see `sandbox::credentials`).
+ pub credentials: Arc<dyn crate::sandbox::CredentialStore>,
}
impl AppState {
@@ -86,6 +89,7 @@ impl AppState {
router: LayaRouter,
) -> Self {
let (event_sender, _) = broadcast::channel(128);
+ let config_data_dir = config.data_dir.clone();
let sandbox_manager = Arc::new(SandboxManager::new());
let browser_controllers = Arc::new(Mutex::new(HashMap::new()));
let profiles = Arc::new(crate::profiles::ProfileManager::new(config.data_dir.clone()));
@@ -113,6 +117,7 @@ impl AppState {
questions: Default::default(),
claude_login: Default::default(),
mcp_registry: Arc::new(crate::mcp::registry::McpRegistry::from_env()),
+ credentials: crate::sandbox::credentials::open_store(&config_data_dir),
}
}
@@ -189,8 +194,10 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/sandbox/:team_id/stream", get(browser_stream::upgrade))
.route("/api/sandbox/:team_id/page", get(routes::get_sandbox_page))
.route("/api/sandbox/:team_id/act", post(routes::act_sandbox))
- .route("/api/sandbox/:team_id/passwords", get(routes::get_saved_passwords).post(routes::save_password))
- .route("/api/sandbox/:team_id/passwords/:id", delete(routes::delete_password))
+ .route("/api/sandbox/:team_id/passwords", get(passwords::list).post(passwords::save))
+ .route("/api/sandbox/:team_id/passwords/pending", post(passwords::save_pending).delete(passwords::discard_pending))
+ .route("/api/sandbox/:team_id/passwords/:id", delete(passwords::remove))
+ .route("/api/sandbox/:team_id/passwords/:id/reveal", post(passwords::reveal))
.route("/api/mcp/servers", get(mcp_routes::list_servers).post(mcp_routes::create_server))
.route(
"/api/mcp/servers/:id",
diff --git a/src/server/passwords.rs b/src/server/passwords.rs
new file mode 100644
index 00000000..c18c87ea
--- /dev/null
+++ b/src/server/passwords.rs
@@ -0,0 +1,224 @@
+//! Saved website passwords for a team's, channel's or bot's browser. The person only: every
+//! route here needs the API token (see `auth::person_only`) and refuses bots' turn tokens.
+//!
+//! - `GET /api/sandbox/:id/passwords` → `{passwords: [{id, origin, domain, username,
+//! created_at, last_used}], pending: null | {origin, username, captured_at}}`. No passwords.
+//! - `POST /api/sandbox/:id/passwords {origin | domain, username, password}` → `{status:
+//! "saved", credential: {…metadata}}`. The password is not echoed.
+//! - `POST /api/sandbox/:id/passwords/:cid/reveal` → `{password}` (no-store).
+//! - `DELETE /api/sandbox/:id/passwords/:cid` → `{status: "deleted" | "not_found"}`.
+//! - `POST /api/sandbox/:id/passwords/pending` → saves the captured password the browser holds
+//! for confirmation → `{status: "saved", credential}`; 404 when there is none.
+//! - `DELETE /api/sandbox/:id/passwords/pending` → `{status: "discarded"}`.
+
+use super::AppState;
+use crate::db::spaces::SpaceId;
+use crate::sandbox::credentials::{migrate_legacy, normalize_origin, CredentialMeta, StoreError};
+use axum::{
+ extract::{Path, State},
+ http::{header, HeaderMap, HeaderValue, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+const REFUSAL: &str = "only the person manages saved passwords";
+
+fn error(status: StatusCode, message: &str) -> Response {
+ (status, Json(json!({"error": message}))).into_response()
+}
+
+fn unavailable(e: StoreError) -> Response {
+ tracing::warn!(error = %e, "saved-password store failed");
+ error(StatusCode::SERVICE_UNAVAILABLE, "saved passwords are unavailable right now")
+}
+
+/// The team, channel or bot an id names, with its space. Ids only: names don't resolve here.
+pub async fn password_owner(state: &AppState, id: &str) -> Option<(String, SpaceId)> {
+ if let Ok(Some(t)) = state.db.get_team(id).await {
+ return Some((t.id, SpaceId::new(&t.space_id)));
+ }
+ if let Ok(Some(c)) = state.db.get_channel(id).await {
+ return Some((c.id, SpaceId::new(&c.space_id)));
+ }
+ if let Ok(Some(k)) = state.db.get_kwant(id).await {
+ return Some((k.id, SpaceId::new(&k.space_id)));
+ }
+ None
+}
+
+#[allow(clippy::result_large_err)]
+async fn owner_or_404(state: &AppState, headers: &HeaderMap, id: &str) -> Result<String, Response> {
+ super::mcp_suggest::refuse_agent_tokens(state, headers, REFUSAL).await?;
+ match password_owner(state, id).await {
+ Some((owner, _)) => {
+ migrate_owner(state, &owner).await;
+ Ok(owner)
+ }
+ None => Err(error(StatusCode::NOT_FOUND, "no such team, channel or bot")),
+ }
+}
+
+/// Moves a legacy `.saved_passwords.json` from the owner's old browser folder into the store.
+async fn migrate_owner(state: &AppState, owner: &str) {
+ if let Some((_, folder)) = super::routes::resolve_sandbox_target_info(state, owner).await {
+ match migrate_legacy(state.credentials.as_ref(), &folder, &[owner]) {
+ Ok(0) => {}
+ Ok(n) => tracing::info!(moved = n, "moved saved passwords out of a bot folder into the vault"),
+ Err(e) => tracing::warn!(error = %e, "could not move a saved-passwords file into the vault"),
+ }
+ }
+}
+
+/// On start: every legacy `.saved_passwords.json` under a team's, channel's or bot's browser
+/// folder moves into the vault (for every owner that shared the folder) and is deleted.
+pub async fn migrate_all(state: &AppState) {
+ let Ok(spaces) = state.db.list_spaces().await else { return };
+ let mut owners: Vec<String> = Vec::new();
+ for space in spaces {
+ let space = SpaceId::new(&space.id);
+ owners.extend(state.db.list_teams(&space).await.unwrap_or_default().into_iter().map(|t| t.id));
+ owners.extend(state.db.list_channels(&space).await.unwrap_or_default().into_iter().map(|c| c.id));
+ owners.extend(state.db.list_kwants(&space).await.unwrap_or_default().into_iter().map(|k| k.id));
+ }
+ let mut by_folder: std::collections::BTreeMap<std::path::PathBuf, Vec<String>> = Default::default();
+ for owner in owners {
+ if let Some((_, folder)) = super::routes::resolve_sandbox_target_info(state, &owner).await {
+ by_folder.entry(folder).or_default().push(owner);
+ }
+ }
+ for (folder, owners) in by_folder {
+ let refs: Vec<&str> = owners.iter().map(String::as_str).collect();
+ match migrate_legacy(state.credentials.as_ref(), &folder, &refs) {
+ Ok(0) => {}
+ Ok(n) => tracing::info!(moved = n, folder = %folder.display(), "moved saved passwords into the vault"),
+ Err(e) => tracing::warn!(error = %e, folder = %folder.display(), "could not move saved passwords into the vault"),
+ }
+ }
+}
+
+fn meta_json(m: &CredentialMeta) -> Value {
+ let domain = url::Url::parse(&m.origin).ok().and_then(|u| u.host_str().map(str::to_string)).unwrap_or_default();
+ json!({
+ "id": m.id,
+ "origin": m.origin,
+ "domain": domain,
+ "username": m.username,
+ "created_at": m.created_at,
+ "last_used": m.last_used,
+ })
+}
+
+/// The browser controller already open for this target, if any; listing never starts a browser.
+async fn open_controller(state: &AppState, path_id: &str, owner: &str) -> Option<crate::sandbox::BrowserController> {
+ let controllers = state.browser_controllers.lock().await;
+ controllers.get(owner).or_else(|| controllers.get(path_id)).cloned()
+}
+
+pub async fn list(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+ let owner = match owner_or_404(&state, &headers, &id).await {
+ Ok(o) => o,
+ Err(r) => return r,
+ };
+ let list = match state.credentials.list(&owner) {
+ Ok(l) => l,
+ Err(e) => return unavailable(e),
+ };
+ let pending = match open_controller(&state, &id, &owner).await {
+ Some(c) => c.pending().await,
+ None => None,
+ };
+ Json(json!({
+ "passwords": list.iter().map(meta_json).collect::<Vec<_>>(),
+ "pending": pending,
+ }))
+ .into_response()
+}
+
+#[derive(Deserialize)]
+pub struct SaveBody {
+ pub origin: Option<String>,
+ pub domain: Option<String>,
+ pub username: String,
+ pub password: String,
+}
+
+pub async fn save(
+ State(state): State<AppState>,
+ headers: HeaderMap,
+ Path(id): Path<String>,
+ Json(body): Json<SaveBody>,
+) -> Response {
+ let owner = match owner_or_404(&state, &headers, &id).await {
+ Ok(o) => o,
+ Err(r) => return r,
+ };
+ if body.password.is_empty() {
+ return error(StatusCode::BAD_REQUEST, "password is empty");
+ }
+ let source = body.origin.filter(|o| !o.trim().is_empty()).or(body.domain).unwrap_or_default();
+ let Ok(origin) = normalize_origin(&source) else {
+ return error(StatusCode::BAD_REQUEST, "origin must be an http(s) address like https://example.com");
+ };
+ match state.credentials.save(&owner, &origin, body.username.trim(), &body.password) {
+ Ok(meta) => Json(json!({"status": "saved", "credential": meta_json(&meta)})).into_response(),
+ Err(e) => unavailable(e),
+ }
+}
+
+pub async fn reveal(State(state): State<AppState>, headers: HeaderMap, Path((id, cid)): Path<(String, String)>) -> Response {
+ let owner = match owner_or_404(&state, &headers, &id).await {
+ Ok(o) => o,
+ Err(r) => return r,
+ };
+ match state.credentials.get(&owner, &cid) {
+ Ok(Some(c)) => {
+ tracing::info!(owner = %owner, credential = %cid, "the person revealed a saved password");
+ let mut resp = Json(json!({"password": c.password})).into_response();
+ resp.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
+ resp
+ }
+ Ok(None) => error(StatusCode::NOT_FOUND, "no such saved password"),
+ Err(e) => unavailable(e),
+ }
+}
+
+pub async fn remove(State(state): State<AppState>, headers: HeaderMap, Path((id, cid)): Path<(String, String)>) -> Response {
+ let owner = match owner_or_404(&state, &headers, &id).await {
+ Ok(o) => o,
+ Err(r) => return r,
+ };
+ match state.credentials.delete(&owner, &cid) {
+ Ok(removed) => Json(json!({"status": if removed { "deleted" } else { "not_found" }})).into_response(),
+ Err(e) => unavailable(e),
+ }
+}
+
+pub async fn save_pending(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+ let owner = match owner_or_404(&state, &headers, &id).await {
+ Ok(o) => o,
+ Err(r) => return r,
+ };
+ let Some(ctrl) = open_controller(&state, &id, &owner).await else {
+ return error(StatusCode::NOT_FOUND, "no password is waiting to be saved");
+ };
+ let Some(p) = ctrl.take_pending().await else {
+ return error(StatusCode::NOT_FOUND, "no password is waiting to be saved");
+ };
+ match state.credentials.save(&owner, &p.origin, &p.username, &p.password) {
+ Ok(meta) => Json(json!({"status": "saved", "credential": meta_json(&meta)})).into_response(),
+ Err(e) => unavailable(e),
+ }
+}
+
+pub async fn discard_pending(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+ let owner = match owner_or_404(&state, &headers, &id).await {
+ Ok(o) => o,
+ Err(r) => return r,
+ };
+ if let Some(ctrl) = open_controller(&state, &id, &owner).await {
+ ctrl.take_pending().await;
+ }
+ Json(json!({"status": "discarded"})).into_response()
+}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 61648dea..9e5b2a48 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2928,6 +2928,10 @@ pub async fn get_or_create_browser_controller(
let (_, workspace) = resolve_sandbox_target_info(state, team_id).await?;
match state.browser_service.session(team_id, &workspace).await {
Ok(ctrl) => {
+ // Passwords belong to the team, channel or bot (by id), never to a folder
+ if let Some((owner, _)) = super::passwords::password_owner(state, team_id).await {
+ ctrl.attach_vault(state.credentials.clone(), &owner).await;
+ }
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,
@@ -3342,77 +3346,6 @@ pub async fn execute_tool(
Ok(result)
}
-#[derive(Deserialize)]
-pub struct SavePasswordPayload {
- pub domain: Option<String>,
- pub origin: Option<String>,
- pub username: String,
- pub password: String,
-}
-
-pub async fn get_saved_passwords(
- State(state): State<AppState>,
- Path(team_id): Path<String>,
-) -> Result<Json<serde_json::Value>, StatusCode> {
- let controller = get_or_create_browser_controller(&state, &team_id).await;
- if let Some(ctrl) = controller {
- let list = ctrl.list_saved_credentials().await;
- Ok(Json(json!({ "passwords": list })))
- } else {
- // Fallback: check workspace directly
- if let Some((_, ws_dir)) = resolve_sandbox_target_info(&state, &team_id).await {
- let creds_file = ws_dir.join(".saved_passwords.json");
- if creds_file.exists() {
- if let Ok(content) = std::fs::read_to_string(&creds_file) {
- if let Ok(creds) = serde_json::from_str::<serde_json::Value>(&content) {
- return Ok(Json(json!({ "passwords": creds })));
- }
- }
- }
- }
- Ok(Json(json!({ "passwords": [] })))
- }
-}
-
-pub async fn save_password(
- State(state): State<AppState>,
- Path(team_id): Path<String>,
- Json(payload): Json<SavePasswordPayload>,
-) -> Result<Json<serde_json::Value>, StatusCode> {
- let controller = get_or_create_browser_controller(&state, &team_id).await;
- let domain = payload.domain.unwrap_or_default();
- let origin = payload.origin.unwrap_or_default();
-
- if let Some(ctrl) = controller {
- let saved = ctrl.save_credential(&domain, &origin, &payload.username, &payload.password).await;
- Ok(Json(json!({ "status": "saved", "credential": saved })))
- } else if let Some((_, ws_dir)) = resolve_sandbox_target_info(&state, &team_id).await {
- let ctrl = crate::sandbox::BrowserController::with_workspace(19222, ws_dir);
- let saved = ctrl.save_credential(&domain, &origin, &payload.username, &payload.password).await;
- Ok(Json(json!({ "status": "saved", "credential": saved })))
- } else {
- Err(StatusCode::NOT_FOUND)
- }
-}
-
-pub async fn delete_password(
- State(state): State<AppState>,
- Path((team_id, cred_id)): Path<(String, String)>,
-) -> Result<Json<serde_json::Value>, StatusCode> {
- let controller = get_or_create_browser_controller(&state, &team_id).await;
- if let Some(ctrl) = controller {
- let removed = ctrl.delete_saved_credential(&cred_id).await;
- Ok(Json(json!({ "status": if removed { "deleted" } else { "not_found" } })))
- } else if let Some((_, ws_dir)) = resolve_sandbox_target_info(&state, &team_id).await {
- let ctrl = crate::sandbox::BrowserController::with_workspace(19222, ws_dir);
- let removed = ctrl.delete_saved_credential(&cred_id).await;
- Ok(Json(json!({ "status": if removed { "deleted" } else { "not_found" } })))
- } else {
- Err(StatusCode::NOT_FOUND)
- }
-}
-
-
#[cfg(test)]
mod tests {
use super::scrub_urls;
diff --git a/tests/browser_test.rs b/tests/browser_test.rs
index c4c652f1..a8563e84 100644
--- a/tests/browser_test.rs
+++ b/tests/browser_test.rs
@@ -494,59 +494,52 @@ async fn test_mock_cdp_protocol_error_response() {
#[tokio::test]
async fn test_browser_credential_vault_lifecycle() {
- let temp_dir = tempfile::tempdir().unwrap();
- let ws_path = temp_dir.path().to_path_buf();
-
- let controller = BrowserController::with_workspace(19222, ws_path.clone());
- assert_eq!(controller.list_saved_credentials().await.len(), 0);
-
- // Save first credential
- let cred1 = controller
- .save_credential(
- "github.com",
- "https://github.com",
- "dev_user",
- "secret_pass_123",
- )
- .await;
-
- assert_eq!(cred1.domain, "github.com");
- assert_eq!(cred1.username, "dev_user");
- assert_eq!(cred1.password, "secret_pass_123");
-
- // List credentials
- let list = controller.list_saved_credentials().await;
+ use kwnt::sandbox::credentials::open_store;
+ let data = tempfile::tempdir().unwrap();
+ let store = open_store(data.path());
+ let controller = BrowserController::new(19222);
+ controller.attach_vault(store.clone(), "team-1").await;
+ assert_eq!(store.list("team-1").unwrap().len(), 0);
+
+ let meta = store.save("team-1", "https://github.com", "dev_user", "DUMMY-secret_pass_123").unwrap();
+ assert_eq!(meta.origin, "https://github.com");
+ assert_eq!(meta.username, "dev_user");
+
+ let list = store.list("team-1").unwrap();
assert_eq!(list.len(), 1);
- assert_eq!(list[0].id, cred1.id);
-
- // Get for URL
- let found = controller
- .get_credential_for_url("https://github.com/login")
- .await;
- assert!(found.is_some());
- assert_eq!(found.unwrap().username, "dev_user");
-
- // File was written to disk
- let creds_file = ws_path.join(".saved_passwords.json");
- assert!(creds_file.exists());
- let file_content = std::fs::read_to_string(&creds_file).unwrap();
- assert!(file_content.contains("dev_user"));
- assert!(file_content.contains("secret_pass_123"));
-
- // Reloading a new controller on same workspace loads saved passwords
- let controller2 = BrowserController::with_workspace(19223, ws_path.clone());
- let reloaded = controller2.list_saved_credentials().await;
- assert_eq!(reloaded.len(), 1);
- assert_eq!(reloaded[0].username, "dev_user");
-
- // Delete credential
- let deleted = controller2.delete_saved_credential(&cred1.id).await;
- assert!(deleted);
- assert_eq!(controller2.list_saved_credentials().await.len(), 0);
-
- // File was updated
- let file_content_after = std::fs::read_to_string(&creds_file).unwrap();
- assert!(!file_content_after.contains("dev_user"));
+ assert_eq!(list[0].id, meta.id);
+
+ // Exact origin only
+ assert!(store.for_origin("team-1", "https://github.com").unwrap().is_some());
+ assert!(store.for_origin("team-1", "http://github.com").unwrap().is_none());
+ assert!(store.for_origin("team-1", "https://gist.github.com").unwrap().is_none());
+ assert!(store.for_origin("team-2", "https://github.com").unwrap().is_none());
+
+ // Nothing on disk in clear
+ for entry in walk(data.path()) {
+ let bytes = std::fs::read(&entry).unwrap();
+ assert!(!String::from_utf8_lossy(&bytes).contains("DUMMY-secret_pass_123"), "{}", entry.display());
+ assert!(!String::from_utf8_lossy(&bytes).contains("dev_user"), "{}", entry.display());
+ }
+
+ // A fresh store on the same data dir reads them back
+ let reopened = open_store(data.path());
+ assert_eq!(reopened.get("team-1", &meta.id).unwrap().unwrap().password, "DUMMY-secret_pass_123");
+ assert!(reopened.delete("team-1", &meta.id).unwrap());
+ assert_eq!(reopened.list("team-1").unwrap().len(), 0);
+}
+
+fn walk(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
+ let mut out = Vec::new();
+ for e in std::fs::read_dir(dir).unwrap().flatten() {
+ let p = e.path();
+ if p.is_dir() {
+ out.extend(walk(&p));
+ } else {
+ out.push(p);
+ }
+ }
+ out
}
#[tokio::test]
@@ -667,3 +660,117 @@ fn detects_captcha_and_bot_check_pages() {
assert!(detect_bot_wall("https://shop.example/", "Shop", "Please verify you are human to continue").is_some());
assert!(detect_bot_wall("https://www.bing.com/images/search?q=cat", "cat - Bing images", "Cat pictures, kittens").is_none());
}
+
+/// A fake Chrome whose main frame is at `url` and whose capture returns `captured`; records every
+/// CDP call.
+async fn fake_page(
+ url: Arc<tokio::sync::Mutex<String>>,
+ captured: Value,
+) -> (u16, Arc<tokio::sync::Mutex<Vec<(String, Value)>>>) {
+ let http = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let http_port = http.local_addr().unwrap().port();
+ let ws_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let ws_port = ws_listener.local_addr().unwrap().port();
+ let recorded = Arc::new(tokio::sync::Mutex::new(Vec::new()));
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = http.accept().await {
+ let mut buf = vec![0u8; 1024];
+ let _ = stream.read(&mut buf).await;
+ let body = json!({"webSocketDebuggerUrl": format!("ws://127.0.0.1:{ws_port}/devtools/page/test")}).to_string();
+ let resp = format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
+ let _ = stream.write_all(resp.as_bytes()).await;
+ }
+ });
+ let rec = recorded.clone();
+ tokio::spawn(async move {
+ while let Ok((stream, _)) = ws_listener.accept().await {
+ let (rec, url, captured) = (rec.clone(), url.clone(), captured.clone());
+ tokio::spawn(async move {
+ let Ok(mut ws) = accept_async(stream).await else { return };
+ while let Some(Ok(tokio_tungstenite::tungstenite::Message::Text(txt))) = ws.next().await {
+ let parsed: Value = serde_json::from_str(&txt).unwrap();
+ let method = parsed["method"].as_str().unwrap().to_string();
+ let params = parsed.get("params").cloned().unwrap_or(Value::Null);
+ rec.lock().await.push((method.clone(), params.clone()));
+ let result = match method.as_str() {
+ "Page.getFrameTree" => json!({"frameTree": {"frame": {"id": "F1", "url": *url.lock().await}}}),
+ "Page.createIsolatedWorld" => json!({"executionContextId": 77}),
+ "Runtime.evaluate" if params["expression"].as_str().unwrap_or("").contains("__kwntCaptured = null") => {
+ json!({"result": {"type": "string", "value": captured}})
+ }
+ _ => json!({}),
+ };
+ let resp = json!({"id": parsed["id"], "result": result}).to_string();
+ let _ = ws.send(tokio_tungstenite::tungstenite::Message::Text(resp)).await;
+ }
+ });
+ }
+ });
+ (http_port, recorded)
+}
+
+/// F-5: a password saved for example.com was filled on http://, on any port and on every
+/// subdomain, from a script in the page's own world.
+#[tokio::test]
+async fn autofill_goes_only_to_the_exact_origin_in_kwnts_own_world() {
+ use kwnt::sandbox::credentials::open_store;
+ let data = tempfile::tempdir().unwrap();
+ let store = open_store(data.path());
+ store.save("team-1", "https://example.com", "alice", "DUMMY-F5-PW").unwrap();
+ let url = Arc::new(tokio::sync::Mutex::new(String::new()));
+ let (port, recorded) = fake_page(url.clone(), Value::Null).await;
+ let ctrl = BrowserController::new(port);
+ ctrl.attach_vault(store, "team-1").await;
+
+ for (page, filled) in [
+ ("https://example.com/login", true),
+ ("http://example.com/login", false),
+ ("https://evil.example.com/login", false),
+ ("https://example.com:8443/login", false),
+ ("https://notexample.com/login", false),
+ ] {
+ *url.lock().await = page.into();
+ recorded.lock().await.clear();
+ ctrl.inject_autofill_and_capture().await.unwrap();
+ let calls = recorded.lock().await.clone();
+ let evals: Vec<&Value> = calls.iter().filter(|(m, _)| m == "Runtime.evaluate").map(|(_, p)| p).collect();
+ assert_eq!(evals.len(), 1, "{page}: {calls:?}");
+ assert_eq!(evals[0]["contextId"], 77, "{page}: runs in kwnt's isolated world, not the page's");
+ let script = evals[0]["expression"].as_str().unwrap();
+ assert_eq!(script.contains("DUMMY-F5-PW"), filled, "{page}");
+ assert!(!script.contains("window.__kwnt_captured_creds"));
+ assert!(calls.iter().any(|(m, p)| m == "Page.createIsolatedWorld" && p["frameId"] == "F1"));
+ }
+}
+
+/// F-6: the page could write `window.__kwnt_captured_creds` with any domain and have kwnt save it.
+/// The origin now comes from the frame's real URL, and nothing is saved until the person says so.
+#[tokio::test]
+async fn a_capture_is_filed_under_the_real_origin_and_waits() {
+ use kwnt::sandbox::credentials::open_store;
+ let data = tempfile::tempdir().unwrap();
+ let store = open_store(data.path());
+ let forged = json!({"domain": "victim.test", "origin": "https://victim.test", "username": "admin", "password": "DUMMY-FORGED"}).to_string();
+ let url = Arc::new(tokio::sync::Mutex::new("https://attacker.test/login".to_string()));
+ let (port, recorded) = fake_page(url.clone(), Value::String(forged)).await;
+ let ctrl = BrowserController::new(port);
+ ctrl.attach_vault(store.clone(), "team-1").await;
+ ctrl.inject_autofill_and_capture().await.unwrap();
+
+ let capture = ctrl.collect_captured_credentials().await.expect("held for the person");
+ assert_eq!(capture.origin, "https://attacker.test", "never the page's claimed origin");
+ assert_eq!(capture.username, "admin");
+ assert!(!serde_json::to_string(&capture).unwrap().contains("DUMMY-FORGED"), "the password isn't serialized");
+ assert!(!format!("{capture:?}").contains("DUMMY-FORGED"));
+ assert!(store.list("team-1").unwrap().is_empty(), "nothing saved without the person");
+ assert!(store.for_origin("team-1", "https://victim.test").unwrap().is_none());
+ assert_eq!(ctrl.pending().await.unwrap().origin, "https://attacker.test");
+ let evals: Vec<Value> = recorded.lock().await.iter().filter(|(m, _)| m == "Runtime.evaluate").map(|(_, p)| p.clone()).collect();
+ assert!(evals.iter().all(|p| p["contextId"] == 77), "{evals:?}");
+
+ // No capture world (a page kwnt never set up) or a non-web page: nothing
+ let other = BrowserController::new(port);
+ assert!(other.collect_captured_credentials().await.is_none());
+ *url.lock().await = "file:///etc/passwd".into();
+ assert!(ctrl.collect_captured_credentials().await.is_none());
+}
diff --git a/tests/local_chrome_test.rs b/tests/local_chrome_test.rs
index 002f2fe5..02a85778 100644
--- a/tests/local_chrome_test.rs
+++ b/tests/local_chrome_test.rs
@@ -74,7 +74,7 @@ async fn local_chrome_runs_windowless_and_can_open_as_a_window() {
let sessions: serde_json::Value = serde_json::from_slice(
&std::fs::read(tmp.path().join("browser-sessions-local.json")).unwrap()).unwrap();
let other_target = sessions["other"]["target"].as_str().expect("other bot's page").to_string();
- let other = kwnt::sandbox::BrowserController::at_endpoint(&endpoint, Some(other_target), None, false);
+ let other = kwnt::sandbox::BrowserController::at_endpoint(&endpoint, Some(other_target), false);
let shot = tokio::time::timeout(Duration::from_secs(5), other.capture_screenshot()).await;
assert!(matches!(shot, Ok(Ok(ref s)) if !s.is_empty()), "screenshot of the other bot's page: {shot:?}");
@@ -90,7 +90,7 @@ async fn local_chrome_runs_windowless_and_can_open_as_a_window() {
assert!(!headless, "the window form must be a real window");
// only the two bots' pages are open: Chrome's blank start window is not left on top
let (endpoint, _) = computer::running_local_chrome(&profile).await.unwrap();
- let browser = kwnt::sandbox::BrowserController::at_endpoint(&endpoint, None, None, true);
+ let browser = kwnt::sandbox::BrowserController::at_endpoint(&endpoint, None, true);
let targets = browser.send_cdp_command("Target.getTargets", serde_json::json!({})).await.unwrap();
let pages: Vec<_> = targets["targetInfos"].as_array().unwrap().iter()
.filter(|t| t["type"] == "page").map(|t| t["url"].as_str().unwrap_or("").to_string()).collect();
diff --git a/tests/server_test.rs b/tests/server_test.rs
index 818b3146..324947f8 100644
--- a/tests/server_test.rs
+++ b/tests/server_test.rs
@@ -386,11 +386,13 @@ async fn test_sandbox_password_vault_api() {
let team_id = team.id;
let state = AppState::new(config, db, tools, broker, router);
+ let bearer = format!("Bearer {}", state.api_token.reveal());
let app = create_router(state);
// 1. Initial list should be empty
let req = Request::builder()
.uri(format!("/api/sandbox/{}/passwords", team_id))
+ .header("authorization", &bearer)
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
@@ -409,6 +411,7 @@ async fn test_sandbox_password_vault_api() {
let req = Request::builder()
.method("POST")
.uri(format!("/api/sandbox/{}/passwords", team_id))
+ .header("authorization", &bearer)
.header("Content-Type", "application/json")
.body(Body::from(serde_json::to_vec(&save_payload).unwrap()))
.unwrap();
@@ -423,6 +426,7 @@ async fn test_sandbox_password_vault_api() {
// 3. List should now contain 1 item
let req = Request::builder()
.uri(format!("/api/sandbox/{}/passwords", team_id))
+ .header("authorization", &bearer)
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
@@ -433,12 +437,25 @@ async fn test_sandbox_password_vault_api() {
assert_eq!(passwords.len(), 1);
assert_eq!(passwords[0]["domain"], "example.com");
assert_eq!(passwords[0]["username"], "alex");
- assert_eq!(passwords[0]["password"], "supersecretpassword");
+ // Metadata only: the password comes back only from an explicit reveal
+ assert!(passwords[0].get("password").is_none(), "{}", passwords[0]);
+ let req = Request::builder()
+ .method("POST")
+ .uri(format!("/api/sandbox/{}/passwords/{}/reveal", team_id, cred_id))
+ .header("authorization", &bearer)
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.clone().oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(resp.into_body(), 1024 * 64).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["password"], "supersecretpassword");
// 4. Delete the credential
let req = Request::builder()
.method("DELETE")
.uri(format!("/api/sandbox/{}/passwords/{}", team_id, cred_id))
+ .header("authorization", &bearer)
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
@@ -447,6 +464,7 @@ async fn test_sandbox_password_vault_api() {
// 5. List should be empty again
let req = Request::builder()
.uri(format!("/api/sandbox/{}/passwords", team_id))
+ .header("authorization", &bearer)
.body(Body::empty())
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();