Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: let bots sign in to websites without seeing passwords

leepokaiedb090634350
diff --git a/apps/linux/src/connections.rs b/apps/linux/src/connections.rs
index 9bb42d60..95b9bcb2 100644
--- a/apps/linux/src/connections.rs
+++ b/apps/linux/src/connections.rs
@@ -37,8 +37,20 @@ pub fn card(ui: &App, entry: &Value) -> gtk::Widget {
.show_peek_icon(true)
.placeholder_text("Credential or op:// reference")
.build();
- let secret = request["kind"] == "secret";
- if secret {
+ let username = gtk::Entry::builder()
+ .placeholder_text("Username or email")
+ .build();
+ let login = request["kind"] == "login";
+ let secret = login || request["kind"] == "secret";
+ if login {
+ input.set_placeholder_text(Some("Password or op:// reference"));
+ body.append(&username);
+ body.append(&input);
+ body.append(&label(
+ "Saved securely on this computer. The bot types it into the sign-in page but never sees it.",
+ &["small", "secondary"],
+ ));
+ } else if secret {
body.append(&label(
request["field"].as_str().unwrap_or("Credential"),
&["secondary"],
@@ -50,7 +62,9 @@ pub fn card(ui: &App, entry: &Value) -> gtk::Widget {
));
}
let actions = gtk::Box::builder().spacing(8).build();
- let connect = gtk::Button::with_label(if secret {
+ let connect = gtk::Button::with_label(if login {
+ "Save login"
+ } else if secret {
"Save and connect"
} else {
"Connect"
@@ -71,7 +85,7 @@ pub fn card(ui: &App, entry: &Value) -> gtk::Widget {
let (ui3, button, input) = (ui2.clone(), button.clone(), input.clone());
client::call(
"connectorRequestFinish",
- json!({"entryId":e["id"],"value":value}),
+ json!({"entryId":e["id"],"value":value,"username":username.text().as_str()}),
move |result| {
button.set_sensitive(true);
match result {
@@ -350,6 +364,48 @@ pub fn credentials(ui: &App) {
}
}
});
+ body.append(&label("Sign-ins", &["headline"]));
+ let logins = gtk::Box::builder()
+ .orientation(gtk::Orientation::Vertical)
+ .spacing(8)
+ .build();
+ body.append(&logins);
+ let ui2 = ui.clone();
+ client::call("credentialLogins", json!({}), move |r| {
+ let Ok(v) = r else { return };
+ for login in v["items"].as_array().into_iter().flatten() {
+ let row = gtk::Box::builder().spacing(8).build();
+ let text = format!(
+ "{} · {}",
+ login["site"].as_str().unwrap_or(""),
+ login["username"].as_str().unwrap_or("")
+ );
+ let name = label(&text, &[]);
+ name.set_hexpand(true);
+ row.append(&name);
+ let remove = gtk::Button::from_icon_name("user-trash-symbolic");
+ remove.set_tooltip_text(Some("Remove"));
+ row.append(&remove);
+ logins.append(&row);
+ let (ui, row, logins, id) = (
+ ui2.clone(),
+ row.clone(),
+ logins.clone(),
+ login["id"].clone(),
+ );
+ remove.connect_clicked(move |_| {
+ let (ui, row, logins) = (ui.clone(), row.clone(), logins.clone());
+ client::call(
+ "credentialRemoveLogin",
+ json!({"id":id}),
+ move |r| match r {
+ Ok(_) => logins.remove(&row),
+ Err(e) => toast(&ui, &e),
+ },
+ );
+ });
+ }
+ });
let input = gtk::PasswordEntry::builder()
.placeholder_text("1Password service account token")
.show_peek_icon(true)
diff --git a/apps/screen-linux/src/a11y.rs b/apps/screen-linux/src/a11y.rs
index ec0bc172..3668691d 100644
--- a/apps/screen-linux/src/a11y.rs
+++ b/apps/screen-linux/src/a11y.rs
@@ -7,7 +7,7 @@ use anyhow::{Context, Result, anyhow};
use atspi::connection::AccessibilityConnection;
use atspi::proxy::accessible::{AccessibleProxy, ObjectRefExt};
use atspi::proxy::proxy_ext::ProxyExt;
-use atspi::{CoordType, State};
+use atspi::{CoordType, Role, State};
use serde_json::{Map, Value, json};
const MAX_NODES: usize = 600;
@@ -47,6 +47,86 @@ pub async fn frontmost(d: &Display) -> Result<Value> {
))
}
+/// The focused control of the active window: whether it's a password field, and the URL
+/// of the web page it sits in (if any), so the host types a login only where it belongs.
+pub async fn focused_field() -> Result<Value> {
+ let a11y = AccessibilityConnection::new()
+ .await
+ .context("AT-SPI (accessibility) isn't running")?;
+ let conn = a11y.connection();
+ let root = a11y.root_accessible_on_registry().await?;
+ for app in root.get_children().await? {
+ let Ok(app) = app.as_accessible_proxy(conn).await else {
+ continue;
+ };
+ for win in app.get_children().await.unwrap_or_default() {
+ let Ok(win) = win.into_accessible_proxy(conn).await else {
+ continue;
+ };
+ if !win
+ .get_state()
+ .await
+ .is_ok_and(|s| s.contains(State::Active))
+ {
+ continue;
+ }
+ let mut out = json!({"app": app.name().await.unwrap_or_default(), "secure": false});
+ let mut budget = MAX_NODES;
+ let Some(mut el) = Box::pin(find_focused(conn, win, &mut budget)).await else {
+ return Ok(out);
+ };
+ out["secure"] = (el.get_role().await.ok() == Some(Role::PasswordText)).into();
+ for _ in 0..60 {
+ if el.get_role().await.ok() == Some(Role::DocumentWeb) {
+ if let Ok(proxies) = el.proxies().await
+ && let Ok(doc) = proxies.document().await
+ && let Ok(url) = doc.get_attribute_value("DocURL").await
+ && !url.is_empty()
+ {
+ out["url"] = url.into();
+ }
+ break;
+ }
+ let Ok(parent) = el.parent().await else { break };
+ let Ok(parent) = parent.into_accessible_proxy(conn).await else {
+ break;
+ };
+ el = parent;
+ }
+ return Ok(out);
+ }
+ }
+ Err(anyhow!(
+ "No window is active, or its app doesn't expose accessibility."
+ ))
+}
+
+async fn find_focused<'a>(
+ conn: &'a zbus::Connection,
+ el: AccessibleProxy<'a>,
+ budget: &mut usize,
+) -> Option<AccessibleProxy<'a>> {
+ if *budget == 0 {
+ return None;
+ }
+ *budget -= 1;
+ if el
+ .get_state()
+ .await
+ .is_ok_and(|s| s.contains(State::Focused))
+ {
+ return Some(el);
+ }
+ for child in el.get_children().await.unwrap_or_default() {
+ if let Ok(c) = child.into_accessible_proxy(conn).await
+ && let Some(found) = Box::pin(find_focused(conn, c, budget)).await
+ {
+ return Some(found);
+ }
+ }
+ None
+}
+
async fn node(
conn: &zbus::Connection,
el: &AccessibleProxy<'_>,
diff --git a/apps/screen-linux/src/main.rs b/apps/screen-linux/src/main.rs
index cbcbbbe7..0c3c7aac 100644
--- a/apps/screen-linux/src/main.rs
+++ b/apps/screen-linux/src/main.rs
@@ -162,6 +162,7 @@ async fn handle(h: &Arc<Helper>, method: &str, p: &Value) -> Result<Value> {
json!({})
}
"uiTree" => a11y::frontmost(&display()?).await?,
+ "focusedField" => a11y::focused_field().await?,
"openApp" => {
input::open_app(
p["name"]
diff --git a/apps/screen-macos/AXTree.swift b/apps/screen-macos/AXTree.swift
index 8bd58b8c..a8d83791 100644
--- a/apps/screen-macos/AXTree.swift
+++ b/apps/screen-macos/AXTree.swift
@@ -28,6 +28,34 @@ enum AXTree {
return ["app": app.localizedName ?? "", "tree": tree, "truncated": budget <= 0]
}
+ /// The focused control of the frontmost app: whether it's a password field, and the
+ /// URL of the web page it sits in (if any), so the host types a login only where it belongs.
+ static func focusedField() throws -> [String: Any] {
+ guard AXIsProcessTrusted() else {
+ throw HelperError("Codync Screen isn't allowed to read the screen's controls yet. Allow it under Privacy & Security → Accessibility.")
+ }
+ guard let app = NSWorkspace.shared.frontmostApplication else { throw HelperError("No app is in front.") }
+ let root = AXUIElementCreateApplication(app.processIdentifier)
+ AXUIElementSetMessagingTimeout(root, 1)
+ // Chromium only exposes web content to assistive apps that ask for it.
+ AXUIElementSetAttributeValue(root, "AXManualAccessibility" as CFString, kCFBooleanTrue)
+ var out: [String: Any] = ["app": app.localizedName ?? "", "secure": false]
+ guard let focused: AXUIElement = attribute(root, kAXFocusedUIElementAttribute) else { return out }
+ let role: String? = attribute(focused, kAXRoleAttribute)
+ let subrole: String? = attribute(focused, kAXSubroleAttribute)
+ out["secure"] = role == "AXSecureTextField" || subrole == kAXSecureTextFieldSubrole
+ var el = focused
+ for _ in 0..<60 {
+ if (attribute(el, kAXRoleAttribute) as String?) == "AXWebArea" {
+ if let url: URL = attribute(el, "AXURL") { out["url"] = url.absoluteString }
+ break
+ }
+ guard let parent: AXUIElement = attribute(el, kAXParentAttribute) else { break }
+ el = parent
+ }
+ return out
+ }
+
private static func node(_ el: AXUIElement, depth: Int, budget: inout Int, origin: CGPoint) -> [String: Any]? {
guard budget > 0, depth < maxDepth else { return nil }
budget -= 1
diff --git a/apps/screen-macos/ScreenHelper.swift b/apps/screen-macos/ScreenHelper.swift
index c8b9e05f..925f1050 100644
--- a/apps/screen-macos/ScreenHelper.swift
+++ b/apps/screen-macos/ScreenHelper.swift
@@ -81,6 +81,8 @@ final class ScreenHelper {
return [String: Any]()
case "uiTree":
return try AXTree.frontmost(display: display(p["display"]))
+ case "focusedField":
+ return try AXTree.focusedField()
case "openApp":
guard let name = p["name"] as? String, !name.isEmpty else { throw HelperError("name is required") }
try await openApp(name)
diff --git a/docs/features/connector-credentials.md b/docs/features/connector-credentials.md
index fe3c8633..c45855e6 100644
--- a/docs/features/connector-credentials.md
+++ b/docs/features/connector-credentials.md
@@ -67,6 +67,24 @@ MCP connection requests and runtime secret retrieval are loopback-only. Authoriz
Control devices may submit or cancel requests. No endpoint exposes a generic
credential getter to a device. Existing local-process trust boundaries still apply.
+## Website and app logins
+
+`market/logins.rs` keeps sign-ins (`site` = domain or app name, username, password
+or `op://` reference) as one vault record. Bots use `list_logins` (site and
+username only) and `request_login {site, reason}`, which becomes a login card; the
+user saves username and password there (or in Credentials → Sign-ins), and the bot
+is resumed with the login's id. The `computer` tool `type_login {login, field}`
+types it into the focused field through the screen helper and returns only a
+screenshot. Before typing, the helper's `focusedField` reports the front app, the
+page URL (macOS AX `AXWebArea`/`AXURL`, Linux AT-SPI `DocURL`) and whether the field
+is a password field. The host refuses unless the page host is the site or a
+subdomain (or, without a page, the app name equals the site), and types a password
+only into a password field. Clients manage logins with `credentialLogins`,
+`credentialSaveLogin` and `credentialRemoveLogin`; no endpoint returns a password.
+
+Terminal password prompts (sudo, ssh) are not covered: they aren't password fields
+to the accessibility API. The same-user boundary above applies.
+
## Optional 1Password
Credentials settings accepts a service-account token and checks it using the
diff --git a/host/src/api/mod.rs b/host/src/api/mod.rs
index aeabaf95..fa1df950 100644
--- a/host/src/api/mod.rs
+++ b/host/src/api/mod.rs
@@ -214,6 +214,7 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -
|| method.starts_with("composio")
|| method == "setComposioKey"
|| method.starts_with("credential")
+ || method == "computerCall"
|| matches!(method, "agentAuth" | "agentAuthenticate" | "setAgentEnv")
{
market::vault::unlock(hub.clone()).await?;
@@ -246,6 +247,20 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -
ready
}
"credentialStatus" => market::passwords::status(&hub.store)?,
+ "credentialLogins" => market::logins::list(&hub.store)?,
+ "credentialSaveLogin" => {
+ let login = market::logins::save(
+ &hub.store,
+ str_arg(&b, "site")?,
+ b["username"].as_str().unwrap_or_default(),
+ str_arg(&b, "password")?,
+ )?;
+ json!({"login": login.public()})
+ }
+ "credentialRemoveLogin" => {
+ market::logins::remove(&hub.store, str_arg(&b, "id")?)?;
+ json!({})
+ }
"credentialSetOnePassword" => {
market::passwords::set_token(&hub.store, b["token"].as_str().unwrap_or_default()).await?
}
diff --git a/host/src/market/logins.rs b/host/src/market/logins.rs
new file mode 100644
index 00000000..e201e95c
--- /dev/null
+++ b/host/src/market/logins.rs
@@ -0,0 +1,125 @@
+//! Saved sign-ins for websites and apps. A bot asks for one with `request_login` (a
+//! secure card the user fills in), then `type_login` types it into the focused field;
+//! the password reaches the screen, never the bot. Stored encrypted in the vault.
+use crate::store::Store;
+use anyhow::{Result, anyhow, bail};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+const SLOT: &str = "logins";
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct Login {
+ pub id: String,
+ /// A domain (`github.com`) or an app name (`Slack`).
+ pub site: String,
+ #[serde(default)]
+ pub username: String,
+ /// The password, or an `op://` reference resolved when it's typed.
+ pub password: String,
+}
+
+impl Login {
+ /// Everything but the password.
+ pub fn public(&self) -> Value {
+ json!({"id": self.id, "site": self.site, "username": self.username})
+ }
+}
+
+pub fn all(store: &Store) -> Result<Vec<Login>> {
+ Ok(match super::vault::read(store, SLOT)? {
+ Some(s) if !s.is_empty() => serde_json::from_str(&s)?,
+ _ => vec![],
+ })
+}
+
+fn save_all(store: &Store, items: &[Login]) -> Result<()> {
+ super::vault::write(store, SLOT, &serde_json::to_string(items)?)
+}
+
+pub fn get(store: &Store, id: &str) -> Result<Login> {
+ all(store)?
+ .into_iter()
+ .find(|l| l.id == id)
+ .ok_or_else(|| anyhow!("No saved login `{id}`; ask for one with request_login"))
+}
+
+pub fn list(store: &Store) -> Result<Value> {
+ Ok(json!({"items": all(store)?.iter().map(Login::public).collect::<Vec<_>>()}))
+}
+
+/// `https://www.GitHub.com/login` → `github.com`; an app name stays as typed.
+pub fn normalize_site(site: &str) -> String {
+ let s = site.trim();
+ let s = s.split_once("://").map_or(s, |(_, rest)| rest);
+ let s = s.split(['/', '?', '#']).next().unwrap_or(s);
+ let s = s.rsplit_once('@').map_or(s, |(_, host)| host);
+ s.strip_prefix("www.").unwrap_or(s).to_lowercase()
+}
+
+/// Saves a login, replacing the one for the same site and username.
+pub fn save(store: &Store, site: &str, username: &str, password: &str) -> Result<Login> {
+ let site = normalize_site(site);
+ if site.is_empty() || site.len() > 200 {
+ bail!("Give the website or app this login is for");
+ }
+ if password.is_empty() || password.len() > 4096 || username.len() > 512 {
+ bail!("Invalid password");
+ }
+ let mut items = all(store)?;
+ let username = username.trim().to_owned();
+ let login = if let Some(l) = items.iter_mut().find(|l| l.site == site && l.username == username) {
+ password.clone_into(&mut l.password);
+ l.clone()
+ } else {
+ let taken: Vec<String> = items.iter().map(|l| l.id.clone()).collect();
+ let l = Login { id: super::unique_id(&site, &taken), site, username, password: password.to_owned() };
+ items.push(l.clone());
+ l
+ };
+ save_all(store, &items)?;
+ Ok(login)
+}
+
+pub fn remove(store: &Store, id: &str) -> Result<()> {
+ let mut items = all(store)?;
+ items.retain(|l| l.id != id);
+ save_all(store, &items)
+}
+
+/// Whether the focused window belongs to the login's site: the page's host is the
+/// site or one of its subdomains; without a page, the app's name is the site.
+pub fn matches(site: &str, url: Option<&str>, app: &str) -> bool {
+ match url.map(normalize_site).filter(|h| !h.is_empty()) {
+ Some(host) => {
+ let host = host.split(':').next().unwrap_or(&host).to_owned();
+ host == site || host.ends_with(&format!(".{site}"))
+ }
+ None => !app.is_empty() && app.eq_ignore_ascii_case(site),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sites_normalize() {
+ assert_eq!(normalize_site("https://www.GitHub.com/login?x=1"), "github.com");
+ assert_eq!(normalize_site("Slack"), "slack");
+ assert_eq!(normalize_site("https://[email protected]"), "accounts.google.com");
+ }
+
+ #[test]
+ fn only_the_right_site_matches() {
+ assert!(matches("github.com", Some("https://github.com/login"), "Safari"));
+ assert!(matches("google.com", Some("https://accounts.google.com/signin"), "Chrome"));
+ assert!(!matches("github.com", Some("https://github.com.evil.io/login"), "Safari"));
+ assert!(!matches("github.com", Some("https://notgithub.com/"), "Safari"));
+ assert!(matches("slack", None, "Slack"));
+ assert!(!matches("github.com", None, "Terminal"));
+ // A page URL wins over the app name.
+ assert!(!matches("safari", Some("https://evil.io"), "Safari"));
+ }
+}
diff --git a/host/src/market/mod.rs b/host/src/market/mod.rs
index 31ceb9e8..40871e5b 100644
--- a/host/src/market/mod.rs
+++ b/host/src/market/mod.rs
@@ -17,6 +17,7 @@
//! on this computer; listings only say which keys are set.
pub mod composio;
+pub mod logins;
pub mod oauth;
pub mod passwords;
pub mod requests;
diff --git a/host/src/market/requests.rs b/host/src/market/requests.rs
index 97e67dda..1f0569de 100644
--- a/host/src/market/requests.rs
+++ b/host/src/market/requests.rs
@@ -11,13 +11,14 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::sync::Arc;
-pub const INSTRUCTIONS: &str = "Connect external services with search_connectors, list_connectors and request_connection. To update an installed connector's key use request_secret. Requests appear as secure cards in the user's conversation. Never ask for passwords or keys in ordinary chat or tool arguments. After requesting, finish your turn and wait; Codync resumes you after the user completes setup.";
+pub const INSTRUCTIONS: &str = "Connect external services with search_connectors, list_connectors and request_connection. To update an installed connector's key use request_secret. To sign in to a website or app on the screen, check list_logins, ask with request_login if it's missing, then type it with the computer tool type_login. Requests appear as secure cards in the user's conversation. Never ask for passwords or keys in ordinary chat or tool arguments. After requesting, finish your turn and wait; Codync resumes you after the user completes setup.";
#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
enum RequestKind {
Connection,
Secret,
App,
+ Login,
}
#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
@@ -41,6 +42,8 @@ pub fn tools() -> Value {
{"name":"list_connectors","description":"List installed connectors without credentials.","inputSchema":{"type":"object","properties":{}}},
{"name":"request_connection","description":"Invite the user to install or authorize a connector. Supply either registryName from search or connectorId from the installed list.","inputSchema":{"type":"object","properties":{"registryName":{"type":"string"},"connectorId":{"type":"string"},"reason":{"type":"string"}},"required":["reason"]}},
{"name":"request_app","description":"Invite the user to connect a hosted app through Composio, for example gmail or slack.","inputSchema":{"type":"object","properties":{"toolkit":{"type":"string"},"reason":{"type":"string"}},"required":["toolkit","reason"]}},
+ {"name":"list_logins","description":"List saved website and app logins (site and username; never passwords).","inputSchema":{"type":"object","properties":{}}},
+ {"name":"request_login","description":"Ask the user to save a login for a website or app, e.g. github.com. They fill it in on a secure card; you never see the password. Then use the computer tool type_login.","inputSchema":{"type":"object","properties":{"site":{"type":"string","description":"The website's domain, or the app's name."},"reason":{"type":"string"}},"required":["site","reason"]}},
{"name":"request_secret","description":"Ask the user to securely provide a credential for an installed connector. The value goes directly to that connector and is never returned to you.","inputSchema":{"type":"object","properties":{"connectorId":{"type":"string"},"field":{"type":"string"},"location":{"type":"string","enum":["env","header"]},"reason":{"type":"string"}},"required":["connectorId","field","location","reason"]}}
])
}
@@ -50,6 +53,24 @@ pub async fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result
match name {
"search_connectors" => super::browse_connectors(&hub.store, text(args, "query")?, "").await,
"list_connectors" => super::list_connectors(&hub.store),
+ "list_logins" => super::logins::list(&hub.store),
+ "request_login" => {
+ let site = super::logins::normalize_site(text(args, "site")?);
+ if site.is_empty() || site.len() > 200 {
+ bail!("Give the website's domain or the app's name");
+ }
+ let lane = hub.runtime(bot).lane.unwrap_or_else(|| Lane::main(bot));
+ let reason: String = text(args, "reason")?.chars().take(400).collect();
+ let entry = hub
+ .add_entry(
+ &lane,
+ EntryKind::Notice,
+ hub.store.max_turn(bot),
+ &json!({"text":reason,"connectionRequest":{"kind":RequestKind::Login,"status":RequestStatus::Pending,"title":site,"site":site,"botId":bot}}),
+ )
+ .ok_or_else(|| anyhow!("Could not save login request"))?;
+ Ok(json!({"requestId":entry.id,"status":"waitingForUser"}))
+ }
"request_app" => {
let toolkit = text(args, "toolkit")?.to_ascii_lowercase();
if toolkit.len() > 100 || !toolkit.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-') {
@@ -141,6 +162,21 @@ pub async fn finish(hub: &Arc<Hub>, args: &Value) -> Result<Value> {
data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Cancelled)?;
return Ok(json!({"entry":hub.set_entry(id, &data).ok_or_else(|| anyhow!("Could not cancel request"))?}));
}
+ if kind == RequestKind::Login {
+ let login = super::logins::save(
+ &hub.store,
+ text(request, "site")?,
+ args["username"].as_str().unwrap_or_default(),
+ text(args, "value")?,
+ )?;
+ let note = format!(
+ "[Login for {} saved as `{}`{}. Type it with the computer tool type_login; the password is never shown to you. Continue the task.]",
+ login.site,
+ login.id,
+ if login.username.is_empty() { String::new() } else { format!(" (username {})", login.username) }
+ );
+ return complete(hub, &e, id, note);
+ }
let connector_id = request["connectorId"]
.as_str()
.or(args["connectorId"].as_str())
@@ -179,22 +215,28 @@ pub async fn finish(hub: &Arc<Hub>, args: &Value) -> Result<Value> {
}
hub.update_bot(&json!({"id":bot,"connectors":enabled}))?;
hub.send_cmd(bot, Cmd::RefreshTools)?;
- let mut data = e.data.clone();
- data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Ready)?;
- let entry = hub.set_entry(id, &data).ok_or_else(|| anyhow!("Could not complete request"))?;
- let lane = Lane { chat: e.bot_id, thread: e.thread_id };
- let text = format!(
+ let note = format!(
"[Connection setup completed: {}. Credentials were submitted securely and are not in this conversation. Continue the task.]",
request["title"].as_str().unwrap_or("Connector")
);
+ complete(hub, &e, id, note)
+}
+
+/// Marks a request ready and resumes its bot once with `note`.
+fn complete(hub: &Arc<Hub>, e: &Entry, id: &str, note: String) -> Result<Value> {
+ let bot = text(&e.data["connectionRequest"], "botId")?.to_owned();
+ let mut data = e.data.clone();
+ data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Ready)?;
+ let entry = hub.set_entry(id, &data).ok_or_else(|| anyhow!("Could not complete request"))?;
+ let lane = Lane { chat: e.bot_id.clone(), thread: e.thread_id.clone() };
let (ack, added) = hub.add_entry_once(
&format!("connection-ack-{id}"),
&lane,
EntryKind::User,
- &json!({"text":text,"status":"queued"}),
+ &json!({"text":note,"status":"queued"}),
)?;
if added {
- hub.send_cmd(bot, Cmd::Send { lane, entry_id: ack.id, text })?;
+ hub.send_cmd(&bot, Cmd::Send { lane, entry_id: ack.id, text: note })?;
}
Ok(json!({"entry":entry}))
}
@@ -261,6 +303,32 @@ mod tests {
assert!(crate::api::devices::permit(&caller, "connectorRequestFinish").is_ok());
}
+ #[tokio::test]
+ async fn saved_login_resumes_the_bot_without_its_password() {
+ let (hub, dir) = fixture();
+ let r = call(
+ &hub,
+ "bot",
+ "request_login",
+ &json!({"site":"https://www.GitHub.com/login","reason":"Sign in to open the PR"}),
+ )
+ .await
+ .unwrap();
+ let id = r["requestId"].as_str().unwrap();
+ let done = finish(&hub, &json!({"entryId":id,"username":"kevin","value":"hunter2-private"})).await.unwrap();
+ assert_eq!(done["entry"]["data"]["connectionRequest"]["status"], "ready");
+ let listed = call(&hub, "bot", "list_logins", &json!({})).await.unwrap();
+ assert_eq!(listed["items"][0]["site"], "github.com");
+ assert_eq!(listed["items"][0]["username"], "kevin");
+ assert!(!listed.to_string().contains("hunter2-private"));
+ assert!(!hub.store.kv_read("logins").unwrap().unwrap().contains("hunter2-private"));
+ let history = hub.store.history("bot", i64::MAX, 100).unwrap();
+ let history = serde_json::to_string(&history).unwrap();
+ assert!(history.contains("type_login") && !history.contains("hunter2-private"));
+ hub.shutdown().await;
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
#[tokio::test]
async fn cancellation_rejects_later_secret_submission() {
let (hub, dir) = fixture();
diff --git a/host/src/mcp.rs b/host/src/mcp.rs
index 56367657..e0327c24 100644
--- a/host/src/mcp.rs
+++ b/host/src/mcp.rs
@@ -21,7 +21,7 @@ pub enum Server {
const INSTRUCTIONS: &str = "Operate this computer's desktop like a person would. Start with `screenshot` \
(or `ui_tree` to find controls precisely), then act; every action returns a fresh screenshot. \
Coordinates are pixels in the latest screenshot. Prefer keyboard shortcuts and `open_app` over hunting with the mouse. \
-Don't type passwords or approve payments: ask the user to do that from their phone.";
+Never type a password yourself: use type_login with a saved login (request_login asks the user for one). Don't approve payments: ask the user to do that from their phone.";
fn tools() -> Value {
let display = json!({"type": "integer", "description": "Display id; defaults to the main display."});
@@ -92,6 +92,18 @@ fn tools() -> Value {
"description": "Press a key or shortcut, e.g. `return`, `escape`, `tab`, `cmd+t`, `cmd+shift+4`, `ctrl+c`. On Linux `cmd` is Super. Returns a screenshot afterwards.",
"inputSchema": {"type": "object", "properties": {"keys": {"type": "string"}}, "required": ["keys"]},
},
+ {
+ "name": "type_login",
+ "description": "Type a saved login (see list_logins / request_login) into the focused field. Works only while the login's website or app is in front; `password` only into a password field. You never see the value. Returns a screenshot afterwards.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "login": {"type": "string", "description": "The login's id."},
+ "field": {"type": "string", "enum": ["username", "password"]},
+ },
+ "required": ["login", "field"],
+ },
+ },
{
"name": "open_app",
"description": "Open or bring an application to the front by name (e.g. `Safari`, `Simulator`, `firefox`). Returns a screenshot afterwards.",
@@ -522,7 +534,12 @@ mod tests {
let mut args = json!({});
for r in required {
let k = r.as_str().unwrap();
- args[k] = if t["inputSchema"]["properties"][k]["type"] == "string" { json!("x") } else { json!(1) };
+ let prop = &t["inputSchema"]["properties"][k];
+ args[k] = match prop["enum"].get(0) {
+ Some(first) => first.clone(),
+ None if prop["type"] == "string" => json!("x"),
+ None => json!(1),
+ };
}
let parsed =
serde_json::from_value::<crate::screen::ComputerTool>(json!({"name": name, "arguments": args}));
diff --git a/host/src/screen.rs b/host/src/screen.rs
index b5fa1ad0..2e393c34 100644
--- a/host/src/screen.rs
+++ b/host/src/screen.rs
@@ -289,6 +289,18 @@ pub enum ComputerTool {
OpenApp {
name: String,
},
+ TypeLogin {
+ login: String,
+ field: LoginField,
+ },
+}
+
+/// Which half of a saved login `type_login` types.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum LoginField {
+ Username,
+ Password,
}
impl ComputerTool {
@@ -571,6 +583,34 @@ pub async fn computer(hub: &Arc<Hub>, bot: &str, tool: ComputerTool) -> Result<V
);
Ok(json!([{"type": "text", "text": text}]))
}
+ ComputerTool::TypeLogin { login, field } => {
+ let login = crate::market::logins::get(&hub.store, &login)?;
+ // Type only into the login's own site, and a password only into a password field,
+ // so a misled bot can't paste it into a page or chat that would show it.
+ let focus = link.request("focusedField", json!({})).await?;
+ let app = focus["app"].as_str().unwrap_or_default();
+ let url = focus["url"].as_str();
+ if !crate::market::logins::matches(&login.site, url, app) {
+ bail!(
+ "The focused window is {}, not {}. Open {} and focus its sign-in field first.",
+ url.unwrap_or(app),
+ login.site,
+ login.site
+ );
+ }
+ let text = match field {
+ LoginField::Username => login.username,
+ LoginField::Password => {
+ if focus["secure"] != true {
+ bail!(
+ "Click into the password field first; type_login types a password only into a password field."
+ );
+ }
+ crate::market::passwords::resolve(&hub.store, &login.password).await?
+ }
+ };
+ act(None, InputEvent::Text { text }).await
+ }
ComputerTool::OpenApp { name } => {
link.request("openApp", json!({"name": name})).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
diff --git a/kit/Sources/CodyncKit/Models/Market.swift b/kit/Sources/CodyncKit/Models/Market.swift
index 26407bbf..f4d1cd9a 100644
--- a/kit/Sources/CodyncKit/Models/Market.swift
+++ b/kit/Sources/CodyncKit/Models/Market.swift
@@ -236,6 +236,15 @@ public struct ConnectionRequest: Codable, Hashable, Sendable {
public var connectorId: String?
public var field: String?
public var location: String?
+ /// Login requests: the website's domain or the app's name.
+ public var site: String?
+}
+
+/// A saved website or app login; the password stays on the computer.
+public struct SavedLogin: Codable, Hashable, Sendable, Identifiable {
+ public var id: String
+ public var site: String
+ public var username: String
}
public struct CredentialStatus: Decodable, Sendable {
@@ -253,10 +262,24 @@ public extension HostClient {
let _: Verified = try await call("connectorVerify", ["id": id], timeout: 120)
}
- func finishConnectionRequest(_ entryId: String, connectorId: String? = nil, value: String? = nil, cancel: Bool = false) async throws {
- struct Body: Encodable { var entryId: String; var connectorId: String?; var value: String?; var cancel: Bool }
+ func finishConnectionRequest(_ entryId: String, connectorId: String? = nil, value: String? = nil, username: String? = nil, cancel: Bool = false) async throws {
+ struct Body: Encodable { var entryId: String; var connectorId: String?; var value: String?; var username: String?; var cancel: Bool }
struct Response: Decodable { var entry: Entry }
- let _: Response = try await call("connectorRequestFinish", Body(entryId: entryId, connectorId: connectorId, value: value, cancel: cancel), timeout: 120)
+ let _: Response = try await call("connectorRequestFinish", Body(entryId: entryId, connectorId: connectorId, value: value, username: username, cancel: cancel), timeout: 120)
+ }
+
+ func logins() async throws -> [SavedLogin] {
+ let res: Items<SavedLogin> = try await call("credentialLogins", timeout: 60)
+ return res.items
+ }
+
+ func saveLogin(site: String, username: String, password: String) async throws {
+ struct Response: Decodable { var login: SavedLogin }
+ let _: Response = try await call("credentialSaveLogin", ["site": site, "username": username, "password": password], timeout: 60)
+ }
+
+ func removeLogin(_ id: String) async throws {
+ let _: Empty = try await call("credentialRemoveLogin", ["id": id], timeout: 60)
}
func credentialStatus() async throws -> CredentialStatus { try await call("credentialStatus", timeout: 60) }
diff --git a/kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift b/kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift
index 43f41782..e0ecf9a3 100644
--- a/kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift
+++ b/kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift
@@ -11,6 +11,7 @@ struct ConnectionRequestCard: View {
@State private var app: ComposioApp?
@State private var item: MarketConnector?
@State private var value = ""
+ @State private var username = ""
@State private var busy = false
@State private var error: String?
@@ -20,7 +21,14 @@ struct ConnectionRequestCard: View {
.font(.headline)
if let text = entry.data.text { Text(text).foregroundStyle(Palette.secondary) }
if request.status == "pending" {
- if request.kind == "secret" {
+ if request.kind == "login" {
+ TextField("Username or email", text: $username)
+ .plainTextInput()
+ SecureField("Password or op:// reference", text: $value)
+ .plainTextInput()
+ Text("Saved securely on this computer. The bot types it into the sign-in page but never sees it.")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ } else if request.kind == "secret" {
Text("\(request.field ?? "Credential") · \(request.location ?? "")")
.font(.caption).foregroundStyle(Palette.secondary)
SecureField("Credential or op:// reference", text: $value)
@@ -29,14 +37,14 @@ struct ConnectionRequestCard: View {
.font(.caption).foregroundStyle(Palette.secondary)
}
HStack {
- Button(request.kind == "secret" ? "Save and connect" : "Connect") { connect() }
+ Button(request.kind == "login" ? "Save login" : request.kind == "secret" ? "Save and connect" : "Connect") { connect() }
.buttonStyle(PrimaryButtonStyle())
- .disabled(busy || (request.kind == "secret" && value.isEmpty))
+ .disabled(busy || (["secret", "login"].contains(request.kind) && value.isEmpty))
Button("Cancel") { cancel() }.buttonStyle(SecondaryButtonStyle()).disabled(busy)
if busy { Spinner() }
}
} else {
- Text(request.status == "ready" ? "Connected" : "Cancelled").foregroundStyle(Palette.secondary)
+ Text(request.status == "ready" ? (request.kind == "login" ? "Saved" : "Connected") : "Cancelled").foregroundStyle(Palette.secondary)
}
if let error { Text(error).font(.footnote).foregroundStyle(Palette.danger) }
}
@@ -49,7 +57,7 @@ struct ConnectionRequestCard: View {
.codyncSheet(item: $app) { app in
ComposioConnectSheet(app: app, requestId: entry.id) { self.app = nil }
}
- .onDisappear { value = "" }
+ .onDisappear { value = ""; username = "" }
}
private func connect() {
@@ -61,6 +69,9 @@ struct ConnectionRequestCard: View {
do {
if request.kind == "app", let toolkit = request.toolkit {
withAnimation(Motion.layout) { app = ComposioApp(slug: toolkit, name: request.title) }
+ } else if request.kind == "login" {
+ try await client.finishConnectionRequest(entry.id, value: value, username: username)
+ value = ""
} else if request.kind == "secret" {
try await client.finishConnectionRequest(entry.id, value: value)
value = ""
@@ -116,6 +127,7 @@ struct CredentialsView: View {
Text("Values stay hidden. Select a connection to replace its credentials.")
.font(.caption).foregroundStyle(Palette.secondary)
}
+ LoginsSection()
CardSection("1Password", footer: "Use a service account with read access only to a dedicated shared vault. The 1Password CLI must be installed on the computer.") {
Text(status?.onePasswordConnected == true ? "Connected" : "Connect a shared vault")
SecureField("Service account token", text: $token).plainTextInput()
@@ -153,6 +165,68 @@ struct CredentialsView: View {
}
}
+/// Website and app logins bots type through the computer tool; passwords stay hidden.
+private struct LoginsSection: View {
+ @Environment(BotStore.self) private var model
+ @State private var logins: [SavedLogin] = []
+ @State private var site = ""
+ @State private var username = ""
+ @State private var password = ""
+ @State private var busy = false
+ @State private var error: String?
+
+ var body: some View {
+ CardSection("Sign-ins", footer: "Bots type these into the matching website or app and never see the password. You can use an op:// reference.") {
+ ForEach(logins) { login in
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(login.site)
+ if !login.username.isEmpty { Text(login.username).font(.caption).foregroundStyle(Palette.secondary) }
+ }
+ Spacer()
+ IconButton("Remove", systemImage: "trash") { remove(login) }
+ }
+ }
+ TextField("Website or app, e.g. github.com", text: $site).plainTextInput()
+ TextField("Username or email", text: $username).plainTextInput()
+ SecureField("Password or op:// reference", text: $password).plainTextInput()
+ Button("Save sign-in") { save() }
+ .buttonStyle(PrimaryButtonStyle())
+ .disabled(busy || site.isEmpty || password.isEmpty)
+ if let error { Text(error).font(.footnote).foregroundStyle(Palette.danger) }
+ }
+ .task { await load() }
+ .onDisappear { password = "" }
+ }
+
+ private func load() async {
+ do { logins = try await model.client?.logins() ?? [] } catch { self.error = error.localizedDescription }
+ }
+
+ private func save() {
+ guard let client = model.client else { return }
+ busy = true
+ error = nil
+ Task {
+ defer { busy = false }
+ do {
+ try await client.saveLogin(site: site, username: username, password: password)
+ site = ""; username = ""; password = ""
+ await load()
+ } catch { self.error = error.localizedDescription }
+ }
+ }
+
+ private func remove(_ login: SavedLogin) {
+ guard let client = model.client else { return }
+ Task {
+ do {
+ try await client.removeLogin(login.id)
+ withAnimation(Motion.layout) { logins.removeAll { $0.id == login.id } }
+ } catch { self.error = error.localizedDescription }
+ }
+ }
+}
private struct ConnectorCredentialEditor: View {
let connector: InstalledConnector