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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix: connector sign-ins and refreshes save only to the same server
leepokaibdc60bd96b50
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.mdindex d35451dd..0f1f1999 100644--- a/docs/features/marketplace.md+++ b/docs/features/marketplace.md@@ -93,7 +93,7 @@ Installing a remote connector probes it: a 401 to `initialize`, or (with no head| On the phone (E2E channel caller) | `<cloud>/v1/oauth/callback` → 302 `codync://oauth?…` | the app's system sign-in sheet sends `connectorSignInFinish` || Anywhere, with a code (GitHub) | none | the host polls the token endpoint |-The cloud page is stateless and the code is useless without the PKCE verifier held by the host. The host trades it only if the connector still has the URL the sign-in started for.+The cloud page is stateless and the code is useless without the PKCE verifier held by the host. The host trades it, and saves the token, only while the connector still has the URL the sign-in started for; a token refresh is saved the same way.GitHub has no dynamic client registration, so it signs in through Codync's own OAuth App (the "Codync" app on leepokai's account that Clerk's GitHub sign-in also uses; Device Flow enabled; client id in `oauth/device.rs`) with the device flow (RFC 8628). The app is used only for a connector whose URL starts with its `resource` and whose metadata names its issuer, and asks for its own fixed scopes, never the server's: any server can name GitHub as its issuer, and the token goes to the connector's URL. `connectorSignIn {id, showsCode: true}` answers `{url, callback: "host", code}`. The iPhone, Android and desktop apps show the code in a dialog whose **Copy and open** copies it and opens GitHub's page (GitHub can't prefill it), then wait for the connector to read signed in, as with the loopback page; its Cancel ends the sign-in quietly, and an Add or a connection request started from it stops there too. The terminal UI has no dialog: it copies the code, opens the page and keeps the code in its hint (Extensions) or note (connection request), with the page's address when no browser opened. The host polls in the background until the code is entered, refused or expired (15 minutes), and saves the token only if the connector still has the URL the sign-in started for (it can be removed and another added under its id meanwhile). The token doesn't expire and has no refresh token, so a 401 signs the connector out. A client that doesn't send `showsCode` gets "Update Codync on this device to sign in to GitHub." A GitHub connector set up with a token header before this (no `oauth`; its URL starts with the app's `resource`) lists `canSignIn: true`: the installed list says *Sign in instead of using a saved token* beside a Sign in button (terminal UI: `↵ sign in instead of the token`). Its token keeps working until the device sign-in lands; then the host stores the sign-in and drops the `Authorization` header (`device::signed_in`), so clients wait for `auth: "signedIn"`, not merely not signed out. An organization that restricts OAuth Apps hides its repositories from the new token until an owner approves Codync; the user manual says so, since the old token is gone by then. Other servers without dynamic client registration need a token header instead (custom connector, URL + headers). `connectorTarget` (loopback only) hands the proxy the URL and headers.diff --git a/host/src/market/oauth.rs b/host/src/market/oauth.rsindex 59c2bb91..e79b3398 100644--- a/host/src/market/oauth.rs+++ b/host/src/market/oauth.rs@@ -106,9 +106,16 @@ fn text(v: &Value) -> Option<String> {v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)}-fn update(store: &Store, id: &str, f: impl FnOnce(&mut Connector)) -> Result<Connector> {+/// `c` is connector `id` still pointing at `url`: while a request to its server is in flight, it+/// can be removed and another added under its id.+fn is_at(c: &Connector, id: &str, url: Option<&str>) -> bool {+ c.id == id && c.url.as_deref() == url+}++/// Changes connector `id` while it still points at `url`: every change here follows a request to its server.+fn update(store: &Store, id: &str, url: Option<&str>, f: impl FnOnce(&mut Connector)) -> Result<Connector> {market::update_connectors(store, |all| {- let c = all.iter_mut().find(|c| c.id == id).ok_or_else(|| anyhow!("unknown connector"))?;+ let c = all.iter_mut().find(|c| is_at(c, id, url)).ok_or_else(|| anyhow!("unknown connector"))?;f(c);Ok(c.clone())})@@ -175,7 +182,7 @@ pub async fn start(hub: &Arc<Hub>, id: &str, callback: Callback, shows_code: boo}oauth.token_endpoint = token_endpoint;let client_id = oauth.client_id.clone();- update(store, id, |c| c.oauth = Some(oauth))?;+ update(store, id, Some(&url), |c| c.oauth = Some(oauth))?;let verifier = crate::remote::crypto::b64(&crate::remote::crypto::random::<32>());let challenge = crate::remote::crypto::b64(&crate::remote::crypto::sha256(&[verifier.as_bytes()]));@@ -224,8 +231,7 @@ pub async fn finish(store: &Store, state: &str, code: Option<&str>, error: Optiolet code = code.ok_or_else(|| anyhow!("Sign-in didn't return a code"))?;let c = market::connectors(store)?.into_iter()- // Still the server the sign-in started for: it can be removed and another added under its id meanwhile.- .find(|c| c.id == p.connector && c.url.as_deref() == Some(p.resource.as_str()))+ .find(|c| is_at(c, &p.connector, Some(&p.resource))).ok_or_else(|| anyhow!("unknown connector"))?;let oauth = c.oauth.ok_or_else(|| anyhow!("unknown connector"))?;let v = token_request(@@ -239,7 +245,7 @@ pub async fn finish(store: &Store, state: &str, code: Option<&str>, error: Optio],).await?;- update(store, &p.connector, |c| store_tokens(c, &v))+ update(store, &p.connector, Some(&p.resource), |c| store_tokens(c, &v))}async fn token_request(oauth: &OAuth, form: &[(&str, &str)]) -> Result<Value> {@@ -292,8 +298,8 @@ fn store_tokens(c: &mut Connector, v: &Value) {}/// Forgets a connector's tokens (keeps its registration).-fn sign_out(store: &Store, id: &str) -> Result<Connector> {- update(store, id, |c| {+fn sign_out(store: &Store, c: &Connector) -> Result<Connector> {+ update(store, &c.id, c.url.as_deref(), |c| {if let Some(o) = &mut c.oauth {o.access_token.clear();o.refresh_token = None;@@ -329,7 +335,8 @@ async fn fresh(store: &Store, c: &Connector, o: &OAuth, stale: bool) -> Result<O}let _one = REFRESH.lock().await;// Someone else may have refreshed while we waited.- let current = market::connectors(store)?.into_iter().find(|x| x.id == c.id).and_then(|x| x.oauth);+ let current =+ market::connectors(store)?.into_iter().find(|x| is_at(x, &c.id, c.url.as_deref())).and_then(|x| x.oauth);if let Some(cur) = ¤t&& cur.access_token != o.access_token&& cur.signed_in()@@ -337,14 +344,14 @@ async fn fresh(store: &Store, c: &Connector, o: &OAuth, stale: bool) -> Result<Oreturn Ok(cur.clone());}let Some(refresh) = o.refresh_token.clone() else {- sign_out(store, &c.id)?;+ sign_out(store, c)?;return Err(signed_out());};match token_request(o, &[("grant_type", "refresh_token"), ("refresh_token", &refresh)]).await {- Ok(v) => Ok(update(store, &c.id, |c| store_tokens(c, &v))?.oauth.unwrap_or_default()),+ Ok(v) => Ok(update(store, &c.id, c.url.as_deref(), |c| store_tokens(c, &v))?.oauth.unwrap_or_default()),Err(error) => {tracing::warn!(connector = %c.id, error = format!("{error:#}"), "token refresh failed");- sign_out(store, &c.id)?;+ sign_out(store, c)?;Err(signed_out())}}@@ -359,16 +366,27 @@ mod tests {assert_eq!(encode("a b&c=d/+"), "a+b%26c%3Dd%2F%2B");}- #[test]- fn unknown_state_is_refused() {+ /// A sign-in to "notes" at `https://notes.example/mcp`, waiting for its code under `state`.+ fn pend(state: &str) {+ let pending = Pending {+ connector: "notes".into(),+ verifier: "v".into(),+ redirect_uri: loopback_uri(1),+ resource: "https://notes.example/mcp".into(),+ started: Instant::now(),+ };+ PENDING.locked().get_or_insert_with(HashMap::new).insert(state.into(), pending);+ }++ #[tokio::test]+ async fn unknown_state_is_refused() {let store = Store::open(std::path::Path::new(":memory:")).unwrap();- let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();- let err = rt.block_on(finish(&store, "nope", Some("code"), None)).unwrap_err();+ let err = finish(&store, "nope", Some("code"), None).await.unwrap_err();assert!(err.to_string().contains("expired"));}- #[test]- fn a_connector_replaced_during_sign_in_gets_no_code() {+ #[tokio::test]+ async fn a_connector_replaced_during_sign_in_gets_no_code() {let store = Store::open(std::path::Path::new(":memory:")).unwrap();// Removed while the sign-in page was open, and another server added under the same id.let c: Connector = serde_json::from_value(json!({@@ -377,16 +395,49 @@ mod tests {})).unwrap();market::save_connectors(&store, &[c]).unwrap();- let pending = Pending {- connector: "notes".into(),- verifier: "v".into(),- redirect_uri: loopback_uri(1),- resource: "https://notes.example/mcp".into(),- started: Instant::now(),- };- PENDING.locked().get_or_insert_with(HashMap::new).insert("replaced".into(), pending);- let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();- let err = rt.block_on(finish(&store, "replaced", Some("code"), None)).unwrap_err();+ pend("replaced");+ let err = finish(&store, "replaced", Some("code"), None).await.unwrap_err();+ assert_eq!(err.to_string(), "unknown connector");+ }++ #[tokio::test]+ async fn the_token_is_saved_only_while_the_connector_is_unchanged() {+ use axum::{Json, Router, routing};+ use std::sync::atomic::{AtomicBool, Ordering};+ let store = Arc::new(Store::open(std::path::Path::new(":memory:")).unwrap());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let token_endpoint = format!("http://{}/token", listener.local_addr().unwrap());+ let original: Connector = serde_json::from_value(json!({+ "id": "notes", "name": "Notes", "url": "https://notes.example/mcp",+ "oauth": {"clientId": "ours", "tokenEndpoint": token_endpoint},+ }))+ .unwrap();+ market::save_connectors(&store, &[original]).unwrap();+ // The second answer comes only after the connector was removed and another added under its id.+ let shared = store.clone();+ let answered = Arc::new(AtomicBool::new(false));+ let router = Router::new().route(+ "/token",+ routing::post(move || async move {+ if answered.swap(true, Ordering::SeqCst) {+ let other: Connector = serde_json::from_value(json!({+ "id": "notes", "name": "Notes", "url": "https://other.example/mcp",+ }))+ .unwrap();+ market::save_connectors(&shared, &[other]).unwrap();+ }+ Json(json!({"access_token": "notes-token"}))+ }),+ );+ tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });+ pend("unchanged");+ let saved = finish(&store, "unchanged", Some("code"), None).await.unwrap();+ assert_eq!(saved.oauth.unwrap().access_token, "notes-token");+ pend("replaced-mid-request");+ let err = finish(&store, "replaced-mid-request", Some("code"), None).await.unwrap_err();assert_eq!(err.to_string(), "unknown connector");+ let left = market::connectors(&store).unwrap();+ assert_eq!(left[0].url.as_deref(), Some("https://other.example/mcp"));+ assert!(left[0].oauth.is_none(), "the replacement got the token");}}diff --git a/host/src/market/oauth/device.rs b/host/src/market/oauth/device.rsindex 1f4761d8..194a5fbe 100644--- a/host/src/market/oauth/device.rs+++ b/host/src/market/oauth/device.rs@@ -126,15 +126,9 @@ async fn poll(hub: Arc<Hub>, target: Target, oauth: OAuth, device_code: String,};match step(&v, interval) {Step::Done => {- let mut saved = false;- match update(&hub.store, id, |c| saved = signed_in(c, &target, &oauth, &v)) {- Err(error) => {- tracing::warn!(connector = %id, error = format!("{error:#}"), "couldn't save the sign-in");- }- Ok(_) if !saved => {- tracing::warn!(connector = %id, "connector changed during sign-in; token dropped");- }- Ok(_) => {}+ // Fails, dropping the token, when the connector no longer points where the sign-in started.+ if let Err(error) = update(&hub.store, id, target.url.as_deref(), |c| signed_in(c, &oauth, &v)) {+ tracing::warn!(connector = %id, error = format!("{error:#}"), "couldn't save the sign-in");}return;}@@ -148,15 +142,10 @@ async fn poll(hub: Arc<Hub>, target: Target, oauth: OAuth, device_code: String,}/// Keeps the token, and drops the token header the connector was set up with before it could sign in.-/// `false`, with nothing changed, when the connector no longer points where the sign-in started.-fn signed_in(c: &mut Connector, target: &Target, app: &OAuth, v: &Value) -> bool {- if c.url != target.url {- return false;- }+fn signed_in(c: &mut Connector, app: &OAuth, v: &Value) {c.oauth = Some(app.clone());store_tokens(c, v);c.headers.retain(|k, _| !k.eq_ignore_ascii_case("authorization"));- true}#[cfg(test)]@@ -172,27 +161,12 @@ mod tests {.unwrap();assert!(offers_sign_in(c.url.as_deref().unwrap()));let app = OAuth { client_id: "id".into(), token_endpoint: "https://github.com/t".into(), ..OAuth::default() };- let target = Target { id: c.id.clone(), url: c.url.clone() };- assert!(signed_in(&mut c, &target, &app, &json!({"access_token": "gho_new"})));+ signed_in(&mut c, &app, &json!({"access_token": "gho_new"}));let o = c.oauth.unwrap();assert_eq!((o.client_id.as_str(), o.access_token.as_str()), ("id", "gho_new"));assert_eq!(c.headers.keys().collect::<Vec<_>>(), ["X-MCP-Toolsets"]);}- #[test]- fn a_connector_replaced_during_sign_in_gets_no_token() {- let target = Target { id: "github".into(), url: Some("https://api.githubcopilot.com/mcp/".into()) };- // Removed while GitHub waited for the code, and another server added under the same id.- let mut c: Connector = serde_json::from_value(json!({- "id": "github", "name": "GitHub", "url": "https://evil.example/mcp",- "headers": {"Authorization": "Bearer theirs"},- }))- .unwrap();- assert!(!signed_in(&mut c, &target, &OAuth::default(), &json!({"access_token": "gho_new"})));- assert!(c.oauth.is_none());- assert_eq!(c.headers.keys().collect::<Vec<_>>(), ["Authorization"]);- }-#[test]fn only_github_s_own_server_gets_codync_s_github_app() {let github = "https://github.com/login/oauth";diff --git a/tools/check-connectors.py b/tools/check-connectors.pyindex 7f165a0d..0e97b42e 100644--- a/tools/check-connectors.py+++ b/tools/check-connectors.py@@ -361,8 +361,10 @@ def main():with sqlite3.connect(home / "codync.db") as db:row = db.execute("SELECT v FROM kv WHERE k='vault.id'").fetchone()if row:- removed = subprocess.run(["security", "delete-generic-password", "-s", "dev.codync.credentials", "-a", row[0]], capture_output=True)- assert removed.returncode == 0, "Could not remove temporary Keychain entry: " + row[0]+ # The vault's service name follows the host's environment (vault.rs).+ removed = [subprocess.run(["security", "delete-generic-password", "-s", service, "-a", row[0]], capture_output=True)+ for service in ("dev.codync.development.credentials", "dev.codync.credentials")]+ assert any(r.returncode == 0 for r in removed), "Could not remove temporary Keychain entry: " + row[0]print("Temporary host, data and Keychain key cleaned up.", flush=True)failed = sum(not ok for _, ok in results)print(f"{len(results) - failed}/{len(results)} passed", flush=True)