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: connectors stay signed in when a token refresh fails for a moment
leepokaie82c417424e0
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.mdindex 0f1f1999..036f2a19 100644--- a/docs/features/marketplace.md+++ b/docs/features/marketplace.md@@ -85,7 +85,7 @@ Picking a built-in command, or sending a message that is just one (`/fast`), run## Sign-in for remote connectors (`host/src/market/oauth.rs`)-Installing a remote connector probes it: a 401 to `initialize`, or (with no headers given) protected-resource metadata naming an authorization server, for servers like Call2Me that only refuse tool calls, marks it `signedOut`, and bots don't get it until someone signs in. Sign-in follows the MCP authorization spec: protected-resource metadata → authorization-server metadata → dynamic client registration (both redirect URIs at once) → PKCE. Tokens stay on the computer and are refreshed on use (or after a 401).+Installing a remote connector probes it: a 401 to `initialize`, or (with no headers given) protected-resource metadata naming an authorization server, for servers like Call2Me that only refuse tool calls, marks it `signedOut`, and bots don't get it until someone signs in. Sign-in follows the MCP authorization spec: protected-resource metadata → authorization-server metadata → dynamic client registration (both redirect URIs at once) → PKCE. Tokens stay on the computer and are refreshed on use (or after a 401); the refresh names the connector URL as `resource`, as the code exchange does. A refresh the token endpoint refuses with an OAuth `error` signs the connector out; `invalid_client` also drops the client registration, so the next sign-in registers again. A 5xx, 408 or 429, `temporarily_unavailable`, an answer that isn't an OAuth error (a proxy's page) or an unreachable server keeps the tokens: a token that hasn't expired yet is still used, otherwise the call fails with "Couldn't renew the sign-in to <name>. Try again in a moment." and the next one tries again.| Where the user signs in | Redirect URI | Who finishes || --- | --- | --- |diff --git a/host/src/market/oauth.rs b/host/src/market/oauth.rsindex e79b3398..60f23f82 100644--- a/host/src/market/oauth.rs+++ b/host/src/market/oauth.rs@@ -308,6 +308,19 @@ fn sign_out(store: &Store, c: &Connector) -> Result<Connector> {})}+/// Forgets a connector's tokens and its registration: the next sign-in registers again.+fn unregister(store: &Store, c: &Connector) -> Result<Connector> {+ update(store, &c.id, c.url.as_deref(), |c| {+ if let Some(o) = &mut c.oauth {+ *o = OAuth::default();+ }+ })+}++fn signed_out(c: &Connector) -> anyhow::Error {+ anyhow!("Sign in to {} in Extensions first.", c.name)+}+/// What the `remote` MCP proxy sends to connector `id`: its URL and headers, with a fresh token./// `stale`: the server just said 401, so refresh even if the token looks valid.pub async fn target(store: &Store, id: &str, stale: bool) -> Result<Value> {@@ -318,16 +331,16 @@ pub async fn target(store: &Store, id: &str, stale: bool) -> Result<Value> {headers.insert(k.clone(), market::passwords::resolve(store, v).await?);}if let Some(o) = &c.oauth {- let o = fresh(store, &c, o, stale).await?;+ let o = fresh(store, &c, &url, o, stale).await?;headers.insert("Authorization".into(), format!("Bearer {}", o.access_token));}Ok(json!({"url": url, "headers": headers}))}-async fn fresh(store: &Store, c: &Connector, o: &OAuth, stale: bool) -> Result<OAuth> {- let signed_out = || anyhow!("Sign in to {} in Extensions first.", c.name);+/// `o`, or a new token when it's about to expire (or `stale`). `url`: the connector's.+async fn fresh(store: &Store, c: &Connector, url: &str, o: &OAuth, stale: bool) -> Result<OAuth> {if !o.signed_in() {- return Err(signed_out());+ return Err(signed_out(c));}let expiring = o.expires_at.is_some_and(|t| t <= now() + EARLY);if !stale && !expiring {@@ -335,109 +348,79 @@ 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| is_at(x, &c.id, c.url.as_deref())).and_then(|x| x.oauth);+ let current = market::connectors(store)?.into_iter().find(|x| is_at(x, &c.id, Some(url))).and_then(|x| x.oauth);if let Some(cur) = ¤t&& cur.access_token != o.access_token&& cur.signed_in(){return Ok(cur.clone());}- let Some(refresh) = o.refresh_token.clone() else {+ renew(store, c, url, o, stale).await+}++/// Trades the refresh token for a new access token. A server that can't answer now leaves the sign-in as is.+async fn renew(store: &Store, c: &Connector, url: &str, o: &OAuth, stale: bool) -> Result<OAuth> {+ let Some(refresh) = o.refresh_token.as_deref() else {sign_out(store, c)?;- return Err(signed_out());+ return Err(signed_out(c));};- match token_request(o, &[("grant_type", "refresh_token"), ("refresh_token", &refresh)]).await {- Ok(v) => Ok(update(store, &c.id, c.url.as_deref(), |c| store_tokens(c, &v))?.oauth.unwrap_or_default()),+ // The old token still works until it expires.+ let retry = || match o.expires_at {+ Some(t) if !stale && t > now() => Ok(o.clone()),+ _ => Err(anyhow!("Couldn't renew the sign-in to {}. Try again in a moment.", c.name)),+ };+ let form = [("grant_type", "refresh_token"), ("refresh_token", refresh), ("resource", url)];+ let (status, v) = match token_post(o, &form).await {+ Ok(answer) => answer,Err(error) => {tracing::warn!(connector = %c.id, error = format!("{error:#}"), "token refresh failed");+ return retry();+ }+ };+ let renewal = renewal(status, &v);+ if renewal != Renewal::Renewed {+ tracing::warn!(connector = %c.id, %status, error = v["error"].as_str().unwrap_or_default(), "token refresh refused");+ }+ match renewal {+ Renewal::Renewed => Ok(update(store, &c.id, Some(url), |c| store_tokens(c, &v))?.oauth.unwrap_or_default()),+ Renewal::Retry => retry(),+ Renewal::Revoked => {sign_out(store, c)?;- Err(signed_out())+ Err(signed_out(c))+ }+ Renewal::Unregistered => {+ unregister(store, c)?;+ Err(signed_out(c))}}}-#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn form_values_are_encoded() {- assert_eq!(encode("a b&c=d/+"), "a+b%26c%3Dd%2F%2B");- }-- /// 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);- }+/// What the token endpoint's answer to a refresh means (RFC 6749 §5.2).+#[derive(Debug, PartialEq)]+enum Renewal {+ Renewed,+ /// The server is down or busy, or something in front of it answered: ask again later.+ Retry,+ /// The server ended the sign-in.+ Revoked,+ /// The server no longer knows Codync's client.+ Unregistered,+}- #[tokio::test]- async fn unknown_state_is_refused() {- let store = Store::open(std::path::Path::new(":memory:")).unwrap();- let err = finish(&store, "nope", Some("code"), None).await.unwrap_err();- assert!(err.to_string().contains("expired"));+fn renewal(status: reqwest::StatusCode, v: &Value) -> Renewal {+ if status.is_success() && v["access_token"].is_string() {+ return Renewal::Renewed;}-- #[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!({- "id": "notes", "name": "Notes", "url": "https://other.example/mcp",- "oauth": {"clientId": "theirs", "tokenEndpoint": "http://127.0.0.1:1/token"},- }))- .unwrap();- market::save_connectors(&store, &[c]).unwrap();- pend("replaced");- let err = finish(&store, "replaced", Some("code"), None).await.unwrap_err();- assert_eq!(err.to_string(), "unknown connector");+ if status.is_server_error() || matches!(status.as_u16(), 408 | 429) {+ return Renewal::Retry;}-- #[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");+ match v["error"].as_str() {+ // Not an OAuth error (a proxy's page, say): nothing is known about the grant.+ None | Some("temporarily_unavailable") => Renewal::Retry,+ Some("invalid_client") => Renewal::Unregistered,+ Some(_) => Renewal::Revoked,}}++#[cfg(test)]+mod tests;diff --git a/host/src/market/oauth/tests.rs b/host/src/market/oauth/tests.rsnew file mode 100644index 00000000..de1762ac--- /dev/null+++ b/host/src/market/oauth/tests.rs@@ -0,0 +1,199 @@+use super::*;++#[test]+fn form_values_are_encoded() {+ assert_eq!(encode("a b&c=d/+"), "a+b%26c%3Dd%2F%2B");+}++/// 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 err = finish(&store, "nope", Some("code"), None).await.unwrap_err();+ assert!(err.to_string().contains("expired"));+}++#[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!({+ "id": "notes", "name": "Notes", "url": "https://other.example/mcp",+ "oauth": {"clientId": "theirs", "tokenEndpoint": "http://127.0.0.1:1/token"},+ }))+ .unwrap();+ market::save_connectors(&store, &[c]).unwrap();+ pend("replaced");+ let err = finish(&store, "replaced", Some("code"), None).await.unwrap_err();+ assert_eq!(err.to_string(), "unknown connector");+}++/// Connector "notes" signed in with token "old" (refresh token "r1") until `expires_at`,+/// refreshing at `token_endpoint`.+fn notes(token_endpoint: &str, expires_at: u64) -> Store {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ let c: Connector = serde_json::from_value(json!({+ "id": "notes", "name": "Notes", "url": "https://notes.example/mcp",+ "oauth": {"clientId": "ours", "tokenEndpoint": token_endpoint,+ "accessToken": "old", "refreshToken": "r1", "expiresAt": expires_at},+ }))+ .unwrap();+ market::save_connectors(&store, &[c]).unwrap();+ store+}++/// `notes` with an expired token, refreshing at a local token endpoint+/// that answers `answer(form body)` as (status, JSON).+async fn expired_with(answer: fn(&str) -> (u16, Value)) -> Store {+ use axum::{Router, http::StatusCode, routing};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let store = notes(&format!("http://{}/token", listener.local_addr().unwrap()), 1);+ let router = Router::new().route(+ "/token",+ routing::post(move |body: String| async move {+ let (status, v) = answer(&body);+ (StatusCode::from_u16(status).unwrap(), axum::Json(v))+ }),+ );+ tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });+ store+}++fn saved(store: &Store) -> OAuth {+ market::connectors(store).unwrap().remove(0).oauth.unwrap()+}++#[tokio::test]+async fn a_temporary_refresh_failure_keeps_the_grant() {+ let store = expired_with(|_| (503, json!({}))).await;+ assert!(target(&store, "notes", false).await.is_err());+ let o = saved(&store);+ assert!(o.signed_in(), "a 503 signed the connector out");+ assert_eq!(o.refresh_token.as_deref(), Some("r1"));+}++#[tokio::test]+async fn a_refresh_names_the_resource() {+ let store = expired_with(|body| {+ if body.contains("resource=https%3A%2F%2Fnotes.example%2Fmcp") {+ (200, json!({"access_token": "new", "expires_in": 3600}))+ } else {+ (400, json!({"error": "invalid_target"}))+ }+ })+ .await;+ let t = target(&store, "notes", false).await.unwrap();+ assert_eq!(t["headers"]["Authorization"], "Bearer new");+}++#[tokio::test]+async fn a_revoked_grant_signs_out() {+ let store = expired_with(|_| (400, json!({"error": "invalid_grant"}))).await;+ assert!(target(&store, "notes", false).await.is_err());+ assert!(!saved(&store).signed_in());+}++#[tokio::test]+async fn an_unknown_client_registers_again() {+ let store = expired_with(|_| (401, json!({"error": "invalid_client"}))).await;+ assert!(target(&store, "notes", false).await.is_err());+ let o = saved(&store);+ assert!(!o.signed_in());+ assert!(o.client_id.is_empty(), "the next sign-in reuses a client the server dropped");+}++#[tokio::test]+async fn an_unreachable_token_endpoint_keeps_the_grant() {+ let store = notes("http://127.0.0.1:1/token", 1);+ assert!(target(&store, "notes", false).await.is_err());+ let o = saved(&store);+ assert!(o.signed_in(), "a dropped connection signed the connector out");+ assert_eq!(o.refresh_token.as_deref(), Some("r1"));+}++#[tokio::test]+async fn a_token_about_to_expire_works_while_the_server_is_away() {+ let store = notes("http://127.0.0.1:1/token", now() + EARLY / 2);+ let t = target(&store, "notes", false).await.unwrap();+ assert_eq!(t["headers"]["Authorization"], "Bearer old");+ assert!(target(&store, "notes", true).await.is_err(), "a token the server refused was sent again");+}++#[test]+fn refresh_answers_are_read_as_rfc_6749_says() {+ let read = |status: u16, v: Value| renewal(reqwest::StatusCode::from_u16(status).unwrap(), &v);+ assert_eq!(read(200, json!({"access_token": "new"})), Renewal::Renewed);+ for (status, v) in [+ (503, json!({})),+ (502, json!({"error": "invalid_grant"})),+ (429, json!({})),+ (408, Value::Null),+ (403, Value::Null),+ (400, json!({"error": "temporarily_unavailable"})),+ (200, Value::Null),+ ] {+ assert_eq!(read(status, v.clone()), Renewal::Retry, "{status} {v}");+ }+ for (status, v) in [+ (400, json!({"error": "invalid_grant"})),+ (400, json!({"error": "invalid_request"})),+ (403, json!({"error": "unauthorized_client"})),+ (401, json!({"error": "invalid_token"})),+ (200, json!({"error": "invalid_scope"})),+ ] {+ assert_eq!(read(status, v.clone()), Renewal::Revoked, "{status} {v}");+ }+ assert_eq!(read(401, json!({"error": "invalid_client"})), Renewal::Unregistered);+}++#[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/web/content/docs/connectors-and-skills.mdx b/web/content/docs/connectors-and-skills.mdxindex ee3dcc18..4ddb8774 100644--- a/web/content/docs/connectors-and-skills.mdx+++ b/web/content/docs/connectors-and-skills.mdx@@ -34,7 +34,7 @@ Some hosted connectors ask you to sign in with your account on that service. The- On the iPhone, it opens in the system sign-in sheet.- In the desktop app, it opens in your browser on the computer.-The tokens stay on the computer and are refreshed when they expire. Until someone signs in, bots don't get the connector, and your library shows a **Sign in** button for it.+The tokens stay on the computer and are refreshed when they expire. If the service can't be reached for a refresh, the connector stays signed in and Codync tries again on its next use; you only need to sign in again when the service ends the sign-in. Until someone signs in, bots don't get the connector, and your library shows a **Sign in** button for it.GitHub signs in with a short code instead. Codync shows the code; press **Copy and open**, paste the code on the GitHub page that opens, and authorize Codync. The connector is ready as soon as GitHub confirms. In the terminal, the code is copied and shown at the bottom while GitHub's page opens, or next to the page's address when the terminal can't open a browser.