YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(connect): cancel-race in OAuth flow + decouple URL placeholder resolution from credentials
Louis Beaumont62aea9b53f1e
diff --git a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx b/apps/screenpipe-app-tauri/components/settings/connections-section.tsxindex 3feb25755..f46b5f643 100644--- a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx@@ -1019,7 +1019,7 @@ function OAuthPanel({ integrationId, integrationName }: { integrationId: string;const [status, setStatus] = useState<"idle" | "loading" | "connected">("idle");const [displayName, setDisplayName] = useState<string | null>(null);// Ref guard so a cancelled or timed-out connect attempt doesn't update state after cancel.- const connectingRef = React.useRef(false);+ const connectingRef = useRef(false);const fetchStatus = useCallback(async () => {try {@@ -1047,14 +1047,13 @@ function OAuthPanel({ integrationId, integrationName }: { integrationId: string;connectingRef.current = true;try {const res = await commands.oauthConnect(integrationId, null);+ if (!connectingRef.current) return; // cancelled — handleCancel owns the UIif (res.status === "ok" && res.data.connected) {- // always reflect a successful connection, even if user hit cancelsetStatus("connected");await fetchStatus();- } else if (connectingRef.current) {+ } else {setStatus("idle");}- // if cancelled and not connected: handleCancel already set idle, leave it} catch {if (connectingRef.current) setStatus("idle");} finally {@@ -1062,9 +1061,12 @@ function OAuthPanel({ integrationId, integrationName }: { integrationId: string;}};- const handleCancel = () => {+ const handleCancel = async () => {connectingRef.current = false;setStatus("idle");+ // Drop the pending OAuth sender on the backend so the awaiting oauth_connect+ // call returns immediately instead of hanging on the 120s timeout.+ try { await commands.oauthCancel(integrationId); } catch { /* ignore */ }};const handleDisconnect = async () => {diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.tsindex 03ee022c4..1c2971966 100644--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts@@ -862,6 +862,20 @@ async oauthConnect(integrationId: string, instance: string | null) : Promise<Reselse return { status: "error", error: e as any };}},+/**+ * Cancel any in-flight OAuth flow(s) for the given integration.+ * Dropping the stored sender makes the awaiting `oauth_connect` call fail fast+ * with "OAuth channel closed before code was received" instead of hanging for+ * the full 120s timeout.+ */+async oauthCancel(integrationId: string) : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("oauth_cancel", { integrationId }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},/*** Check whether a valid (non-expired) OAuth token exists for the given integration.*/diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex c326f0b25..d19f1d372 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -668,6 +668,7 @@ async fn main() {chatgpt_oauth::chatgpt_oauth_models,// Generic OAuth commands (works for any OAuth integration)oauth::oauth_connect,+ oauth::oauth_cancel,oauth::oauth_status,oauth::oauth_disconnect,oauth::oauth_list_instances,@@ -944,6 +945,7 @@ async fn main() {chatgpt_oauth::chatgpt_oauth_models,// Generic OAuth commands (works for any OAuth integration)oauth::oauth_connect,+ oauth::oauth_cancel,oauth::oauth_status,oauth::oauth_disconnect,oauth::oauth_list_instances,diff --git a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rsindex e7600b6f4..bce944bb8 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs@@ -11,7 +11,7 @@use crate::store::SettingsStore;use base64::Engine;use screenpipe_connect::connections::all_integrations;-use screenpipe_connect::oauth::{self, OAUTH_REDIRECT_URI, PENDING_OAUTH};+use screenpipe_connect::oauth::{self, PendingOAuth, OAUTH_REDIRECT_URI, PENDING_OAUTH};use serde::{Deserialize, Serialize};use tauri::AppHandle;use tauri_plugin_opener::OpenerExt;@@ -87,7 +87,13 @@ pub async fn oauth_connect(let (tx, rx) = oneshot::channel::<String>();{let mut map = PENDING_OAUTH.lock().unwrap();- map.insert(state.clone(), tx);+ map.insert(+ state.clone(),+ PendingOAuth {+ integration_id: integration_id.clone(),+ sender: tx,+ },+ );}let redirect_uri = config.redirect_uri_override.unwrap_or(OAUTH_REDIRECT_URI);@@ -192,8 +198,7 @@ pub async fn oauth_connect({if let Ok(body) = resp.json::<serde_json::Value>().await {if let Some(name) = body["CompanyInfo"]["CompanyName"].as_str() {- token_data["workspace_name"] =- serde_json::Value::String(name.to_string());+ token_data["workspace_name"] = serde_json::Value::String(name.to_string());}}}@@ -261,6 +266,26 @@ pub async fn oauth_connect(})}+/// Cancel any in-flight OAuth flow(s) for the given integration.+/// Dropping the stored sender makes the awaiting `oauth_connect` call fail fast+/// with "OAuth channel closed before code was received" instead of hanging for+/// the full 120s timeout.+#[tauri::command]+#[specta::specta]+pub fn oauth_cancel(integration_id: String) -> Result<(), String> {+ let mut map = PENDING_OAUTH.lock().unwrap();+ let before = map.len();+ map.retain(|_, pending| pending.integration_id != integration_id);+ let dropped = before - map.len();+ if dropped > 0 {+ info!(+ "oauth_cancel: dropped {} pending flow(s) for {}",+ dropped, integration_id+ );+ }+ Ok(())+}+/// Check whether a valid (non-expired) OAuth token exists for the given integration.#[tauri::command]#[specta::specta]diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rsindex 12df07632..52ee7a093 100644--- a/crates/screenpipe-connect/src/oauth.rs+++ b/crates/screenpipe-connect/src/oauth.rs@@ -58,7 +58,14 @@ pub const OAUTH_REDIRECT_URI: &str = "http://localhost:3030/connections/oauth/ca// /connections/oauth/callback HTTP handler (screenpipe-engine)// ----------------------------------------------------------------------------pub static PENDING_OAUTH: Lazy<Mutex<HashMap<String, oneshot::Sender<String>>>> =+/// A pending OAuth flow: the sender that delivers the callback payload,+/// tagged with its `integration_id` so `oauth_cancel` can find and drop it.+pub struct PendingOAuth {+ pub integration_id: String,+ pub sender: oneshot::Sender<String>,+}++pub static PENDING_OAUTH: Lazy<Mutex<HashMap<String, PendingOAuth>>> =Lazy::new(|| Mutex::new(HashMap::new()));// ---------------------------------------------------------------------------diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rsindex 61119aeee..703936f87 100644--- a/crates/screenpipe-engine/src/connections_api.rs+++ b/crates/screenpipe-engine/src/connections_api.rs@@ -919,14 +919,14 @@ async fn oauth_callback(Query(params): Query<OAuthCallbackQuery>) -> (StatusCode};match sender {- Some(tx) => {+ Some(pending) => {// For providers that return extra callback params (e.g. QuickBooks realmId),// encode them alongside the code as JSON so the Tauri command can extract both.let payload = match params.realm_id {Some(ref rid) => serde_json::json!({"code": code, "realmId": rid}).to_string(),None => code,};- let _ = tx.send(payload);+ let _ = pending.sender.send(payload);let html ="<html><body style=\"font-family:system-ui;text-align:center;padding:60px\">\<h2>Connected!</h2>\@@ -958,9 +958,30 @@ enum ResolvedAuth {None,}-/// Resolve base_url, replacing `{field}` placeholders with credential values.+/// Fields in the OAuth token JSON that must never be allowed to fill a URL+/// placeholder (tokens and lifecycle metadata). Everything else — `realmId`,+/// `email`, `workspace_name`, etc. — is fair game.+const OAUTH_URL_SKIP_FIELDS: &[&str] = &[+ "access_token",+ "refresh_token",+ "id_token",+ "token_type",+ "expires_in",+ "expires_at",+ "scope",+];++/// Resolve base_url, replacing `{field}` placeholders with credential values+/// and, as a fallback, non-secret fields from the OAuth token JSON (for+/// providers like QuickBooks whose `{realmId}` comes from the callback, not+/// from the credential store).+////// Returns an error if any placeholder remains unresolved.-fn resolve_base_url(template: &str, creds: Option<&Map<String, Value>>) -> Result<String, String> {+fn resolve_base_url(+ template: &str,+ creds: Option<&Map<String, Value>>,+ oauth_extras: Option<&Value>,+) -> Result<String, String> {let mut url = template.to_string();if url.contains('{') {if let Some(c) = creds {@@ -970,6 +991,18 @@ fn resolve_base_url(template: &str, creds: Option<&Map<String, Value>>) -> Resul}}}+ if url.contains('{') {+ if let Some(obj) = oauth_extras.and_then(|v| v.as_object()) {+ for (key, value) in obj.iter() {+ if OAUTH_URL_SKIP_FIELDS.contains(&key.as_str()) {+ continue;+ }+ if let Some(s) = value.as_str() {+ url = url.replace(&format!("{{{}}}", key), s);+ }+ }+ }+ }// Check for unresolved placeholdersif let Some(start) = url.find('{') {let end = url[start..].find('}').unwrap_or(0) + start + 1;@@ -1087,39 +1120,12 @@ async fn connection_proxy(}};- // Load credentials from connections.json, then merge non-secret fields from the OAuth- // token JSON so that {placeholder} patterns in base_url (e.g. {realmId} for QuickBooks)- // resolve correctly without requiring a separate credential write.- let raw_creds = mgr.get_credentials(&id).await.ok().flatten();- let creds: Option<Map<String, Value>> = {- let mut merged = raw_creds.unwrap_or_default();- if let Some(oauth_json) =- screenpipe_connect::oauth::load_oauth_json(state.secret_store.as_deref(), &id, None)- .await- {- const SKIP: &[&str] = &[- "access_token",- "refresh_token",- "id_token",- "token_type",- "expires_in",- "expires_at",- "scope",- ];- if let Some(obj) = oauth_json.as_object() {- for (k, v) in obj {- if !SKIP.contains(&k.as_str()) && !merged.contains_key(k) {- merged.insert(k.clone(), v.clone());- }- }- }- }- if merged.is_empty() {- None- } else {- Some(merged)- }- };+ // Load credentials (from connections.json) and the raw OAuth token JSON in parallel.+ // OAuth JSON is passed separately to resolve_base_url so callback-only fields like+ // QuickBooks' {realmId} can fill URL placeholders without polluting the credentials map.+ let creds = mgr.get_credentials(&id).await.ok().flatten();+ let oauth_json =+ screenpipe_connect::oauth::load_oauth_json(state.secret_store.as_deref(), &id, None).await;let oauth_token = screenpipe_connect::oauth::read_oauth_token_instance(state.secret_store.as_deref(),&id,@@ -1152,7 +1158,7 @@ async fn connection_proxy(}// Resolve dynamic base_url- let base_url = match resolve_base_url(proxy_cfg.base_url, creds.as_ref()) {+ let base_url = match resolve_base_url(proxy_cfg.base_url, creds.as_ref(), oauth_json.as_ref()) {Ok(url) => url,Err(e) => {tracing::warn!("proxy: failed to resolve base_url for '{}': {}", id, e);@@ -1356,7 +1362,7 @@ mod tests {#[test]fn test_resolve_base_url_static() {- let result = resolve_base_url("https://api.notion.com", None);+ let result = resolve_base_url("https://api.notion.com", None, None);assert_eq!(result.unwrap(), "https://api.notion.com");}@@ -1364,7 +1370,7 @@ mod tests {fn test_resolve_base_url_with_placeholder() {let mut creds = Map::new();creds.insert("domain".into(), json!("mycompany.atlassian.net"));- let result = resolve_base_url("https://{domain}/rest/api/3", Some(&creds));+ let result = resolve_base_url("https://{domain}/rest/api/3", Some(&creds), None);assert_eq!(result.unwrap(),"https://mycompany.atlassian.net/rest/api/3"@@ -1376,22 +1382,65 @@ mod tests {let mut creds = Map::new();creds.insert("subdomain".into(), json!("acme"));creds.insert("region".into(), json!("us1"));- let result = resolve_base_url("https://{subdomain}.{region}.api.com", Some(&creds));+ let result = resolve_base_url("https://{subdomain}.{region}.api.com", Some(&creds), None);assert_eq!(result.unwrap(), "https://acme.us1.api.com");}#[test]fn test_resolve_base_url_unresolved_placeholder_fails() {let creds = Map::new(); // empty — no "domain" field- let result = resolve_base_url("https://{domain}.zendesk.com/api/v2", Some(&creds));+ let result = resolve_base_url("https://{domain}.zendesk.com/api/v2", Some(&creds), None);assert!(result.is_err());assert!(result.unwrap_err().contains("{domain}"));}#[test]fn test_resolve_base_url_no_creds_with_placeholder_fails() {- let result = resolve_base_url("https://{domain}.example.com", None);+ let result = resolve_base_url("https://{domain}.example.com", None, None);+ assert!(result.is_err());+ }++ #[test]+ fn test_resolve_base_url_from_oauth_extras() {+ // QuickBooks-style: {realmId} lives in the OAuth token JSON, not in creds.+ let oauth = json!({+ "access_token": "xxx",+ "refresh_token": "yyy",+ "realmId": "9341451956283849",+ });+ let result = resolve_base_url(+ "https://quickbooks.api.intuit.com/v3/company/{realmId}",+ None,+ Some(&oauth),+ );+ assert_eq!(+ result.unwrap(),+ "https://quickbooks.api.intuit.com/v3/company/9341451956283849"+ );+ }++ #[test]+ fn test_resolve_base_url_creds_win_over_oauth_extras() {+ // If both sources define the same key, creds wins (applied first).+ let mut creds = Map::new();+ creds.insert("region".into(), json!("eu"));+ let oauth = json!({ "region": "us" });+ let result = resolve_base_url(+ "https://api.{region}.example.com",+ Some(&creds),+ Some(&oauth),+ );+ assert_eq!(result.unwrap(), "https://api.eu.example.com");+ }++ #[test]+ fn test_resolve_base_url_rejects_token_fields_from_oauth() {+ // Tokens must never be allowed to fill a URL placeholder even if a+ // malicious/misconfigured integration tried to use {access_token}.+ let oauth = json!({ "access_token": "secret-token-should-not-leak" });+ let result = resolve_base_url("https://api.example.com/{access_token}", None, Some(&oauth));assert!(result.is_err());+ assert!(result.unwrap_err().contains("{access_token}"));}// -- resolve_auth -------------------------------------------------------