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.

fix(host): keep the host running while a locked keyring waits to be unlocked

leepokai25202822c17e
diff --git a/docs/features/connector-credentials.md b/docs/features/connector-credentials.md
index 82da9336..408f807b 100644
--- a/docs/features/connector-credentials.md
+++ b/docs/features/connector-credentials.md
@@ -20,8 +20,11 @@ its selected host.
service user. An unavailable keyring gives an actionable error. There is no
plaintext, kernel-keyring-only or automatic ephemeral fallback.
-Unlocking runs on a blocking worker. The key is cached in zeroizing memory until
-host exit. Locking the desktop keyring after unlock does not evict that cache;
+Unlocking runs on a blocking worker, one read at a time; callers that arrive
+meanwhile share its outcome. A locked Linux keyring gets one unlock prompt that
+is dismissed after a minute (nobody sees it on a headless host), and the calls
+waiting on it fail with the keyring error instead of hanging the host. The key is
+cached in zeroizing memory until host exit. Locking the desktop keyring after unlock does not evict that cache;
stop the host to remove it. The implementation does not claim to isolate secrets
from arbitrary code running as the same OS user.
diff --git a/host/Cargo.lock b/host/Cargo.lock
index aefab499..b14d26b7 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -722,6 +722,7 @@ dependencies = [
"codync-network",
"croner",
"crossterm",
+ "dbus-secret-service",
"dirs",
"ed25519-dalek",
"flate2",
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 87a38532..00b0adb2 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -70,6 +70,7 @@ keyring = { version = "3.6.3", features = ["apple-native"] }
[target.'cfg(target_os = "linux")'.dependencies]
keyring = { version = "3.6.3", features = ["sync-secret-service", "crypto-rust", "vendored"] }
+dbus-secret-service = { version = "4.1.0", features = ["vendored"] }
[target.'cfg(windows)'.dependencies]
keyring = { version = "3.6.3", features = ["windows-native"] }
diff --git a/host/src/main.rs b/host/src/main.rs
index 168e407f..627ba9d9 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -540,7 +540,8 @@ async fn serve(bind: &str, port: u16) -> Result<()> {
agent::acp::stopped().await;
analytics::flush_before_exit(&hub).await;
tracing::info!("codync-host stopped");
- Ok(())
+ // A keychain read may still wait on an unlock prompt; dropping the runtime would wait for it.
+ std::process::exit(0)
}
/// Resolves on Ctrl-C or SIGTERM.
diff --git a/host/src/market/vault.rs b/host/src/market/vault.rs
index db0cece3..3680b102 100644
--- a/host/src/market/vault.rs
+++ b/host/src/market/vault.rs
@@ -7,7 +7,7 @@ use chacha20poly1305::{
XChaCha20Poly1305, XNonce,
aead::{Aead, KeyInit, Payload},
};
-use std::sync::Arc;
+use std::{sync::Arc, time::Duration};
use zeroize::Zeroizing;
const PREFIX: &str = "vault:v1:";
@@ -16,39 +16,79 @@ const SERVICE: &str = match crate::environment::Environment::current() {
crate::environment::Environment::Dev => "dev.codync.development.credentials",
};
+/// How long an unlock prompt (Keychain, Secret Service) may wait for an answer.
+const PROMPT_TIMEOUT: Duration = Duration::from_mins(1);
+
+/// Loads the master key once. The keyring read can wait on an unlock prompt nobody
+/// sees (a headless Linux host), so it never holds `secret_key`, which async code
+/// locks on runtime workers. One read runs at a time and owns `vault_unlock`: callers
+/// arriving meanwhile share its outcome instead of prompting again.
pub async fn unlock(hub: Arc<crate::hub::Hub>) -> Result<()> {
if hub.store.secret_key.locked().is_some() {
return Ok(());
}
- tokio::task::spawn_blocking(move || {
- let store = &hub.store;
- let mut cache = store.secret_key.locked();
- if cache.is_some() { return Ok(()); }
- let id = if let Some(id) = store.kv_read("vault.id")? { id } else {
- let id = uuid::Uuid::new_v4().to_string();
- store.kv_set("vault.id", &id)?;
- id
- };
- let entry = keyring::Entry::new(SERVICE, &id).map_err(|_| unavailable())?;
- let key = match entry.get_secret() {
- Ok(key) => key,
- Err(keyring::Error::NoEntry) => {
- if store.kv_read("vault.initialized")?.is_some() {
- bail!("The credential key is missing. Restore this computer's keychain; encrypted credentials were preserved.");
- }
- let mut key = vec![0; 32];
- getrandom::fill(&mut key).map_err(|_| anyhow!("Could not generate credential key"))?;
- entry.set_secret(&key).map_err(|_| unavailable())?;
- key
- }
- Err(_) => return Err(unavailable()),
- };
- if key.len() != 32 { bail!("Invalid credential key; restore this computer's keychain."); }
- store.kv_set("vault.initialized", "true")?;
- *cache = Some(Zeroizing::new(key));
+ // The read's own prompt is bounded too; this margin covers the D-Bus calls around it.
+ let wait = PROMPT_TIMEOUT + Duration::from_secs(5);
+ let Ok(guard) = Arc::clone(&hub.store.vault_unlock).try_lock_owned() else {
+ let _ = tokio::time::timeout(wait, hub.store.vault_unlock.lock()).await;
+ return if hub.store.secret_key.locked().is_some() { Ok(()) } else { Err(unavailable()) };
+ };
+ let read = tokio::task::spawn_blocking(move || {
+ let _guard = guard;
+ if hub.store.secret_key.locked().is_some() {
+ return Ok(());
+ }
+ let key = read_key(&hub.store)?;
+ *hub.store.secret_key.locked() = Some(key);
Ok(())
- }).await??;
- Ok(())
+ });
+ tokio::time::timeout(wait, read).await.map_err(|_| unavailable())??
+}
+
+fn read_key(store: &Store) -> Result<Zeroizing<Vec<u8>>> {
+ let id = if let Some(id) = store.kv_read("vault.id")? {
+ id
+ } else {
+ let id = uuid::Uuid::new_v4().to_string();
+ store.kv_set("vault.id", &id)?;
+ id
+ };
+ #[cfg(target_os = "linux")]
+ unlock_secret_service().map_err(|_| unavailable())?;
+ let entry = keyring::Entry::new(SERVICE, &id).map_err(|_| unavailable())?;
+ let key = match entry.get_secret() {
+ Ok(key) => key,
+ Err(keyring::Error::NoEntry) => {
+ if store.kv_read("vault.initialized")?.is_some() {
+ bail!(
+ "The credential key is missing. Restore this computer's keychain; encrypted credentials were preserved."
+ );
+ }
+ let mut key = vec![0; 32];
+ getrandom::fill(&mut key).map_err(|_| anyhow!("Could not generate credential key"))?;
+ entry.set_secret(&key).map_err(|_| unavailable())?;
+ key
+ }
+ Err(_) => return Err(unavailable()),
+ };
+ if key.len() != 32 {
+ bail!("Invalid credential key; restore this computer's keychain.");
+ }
+ store.kv_set("vault.initialized", "true")?;
+ Ok(Zeroizing::new(key))
+}
+
+/// keyring keeps its item in the default collection and prompts to unlock it with no
+/// time limit. Unlocking it first, with one, means keyring never prompts itself.
+#[cfg(target_os = "linux")]
+fn unlock_secret_service() -> Result<(), dbus_secret_service::Error> {
+ use dbus_secret_service::{EncryptionType, SecretService};
+ let service = SecretService::connect_with_max_prompt_timeout(EncryptionType::Plain, PROMPT_TIMEOUT.as_secs())?;
+ match service.get_default_collection() {
+ Ok(collection) => collection.ensure_unlocked(),
+ // No default collection: keyring reports that without prompting.
+ Err(_) => Ok(()),
+ }
}
fn unavailable() -> anyhow::Error {
diff --git a/host/src/store/mod.rs b/host/src/store/mod.rs
index ce497950..9e18d9cc 100644
--- a/host/src/store/mod.rs
+++ b/host/src/store/mod.rs
@@ -27,6 +27,8 @@ pub struct Store {
db: Mutex<Connection>,
pub(crate) connector_lock: Mutex<()>,
pub(crate) secret_key: Mutex<Option<zeroize::Zeroizing<Vec<u8>>>>,
+ /// Held by the one keyring read in flight (`market::vault::unlock`).
+ pub(crate) vault_unlock: std::sync::Arc<tokio::sync::Mutex<()>>,
}
pub fn now_ms() -> i64 {
diff --git a/host/src/store/schema.rs b/host/src/store/schema.rs
index d729ce97..5ad5e79a 100644
--- a/host/src/store/schema.rs
+++ b/host/src/store/schema.rs
@@ -158,7 +158,12 @@ impl Store {
} else {
None
};
- Ok(Self { db: Mutex::new(c), connector_lock: Mutex::new(()), secret_key: Mutex::new(secret_key) })
+ Ok(Self {
+ db: Mutex::new(c),
+ connector_lock: Mutex::new(()),
+ secret_key: Mutex::new(secret_key),
+ vault_unlock: std::sync::Arc::default(),
+ })
}
}
diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdx
index c3962b37..fc838016 100644
--- a/web/content/docs/linux-servers.mdx
+++ b/web/content/docs/linux-servers.mdx
@@ -102,7 +102,7 @@ codync-host devices revoke <key> # removes one; it disconnects at once
## Limits on a headless server
- **Remote screen and computer use need a desktop session.** They turn on only while a graphical session (Wayland or X11) runs, so on a server they stay off and nothing else is affected. On a Linux desktop, the screen helper needs glibc 2.39 or newer and GStreamer 1.22 or newer with the base, good and bad plugins, PipeWire and xdg-desktop-portal. See [Computer use](/docs/computer-use).
-- **Saved secrets need a keyring.** Connector credentials, voice API keys and agent API keys are encrypted with a key kept in the Secret Service (for example GNOME Keyring). The host's user needs a session D-Bus and an unlocked Secret Service; without one, saving such a secret fails with an error, and new bots start with no connectors turned on. Codync never falls back to storing them in plain text.
+- **Saved secrets need a keyring.** Connector credentials, voice API keys and agent API keys are encrypted with a key kept in the Secret Service (for example GNOME Keyring). The host's user needs a session D-Bus and an unlocked Secret Service; without one, saving such a secret fails with an error, and new bots start with no connectors turned on. If the keyring is locked, the host shows its unlock prompt for a minute and then gives the same error; on a server nobody logs in to graphically, unlock the keyring yourself (for example `gnome-keyring-daemon --unlock`) or give it an empty password. Codync never falls back to storing them in plain text.
- **No desktop app on the server itself.** The Linux desktop app needs a graphical session. Use the phone, the desktop app on another computer over SSH, or the terminal UI.
- **Keeping the machine awake does nothing.** VMs don't sleep; if the host can't hold off sleep, it only logs a warning.
- **Usage limits** come from the agents installed on the server, the same as on a desktop. Cursor asks cursor.com with the sign-in saved on that server.