Skip to content

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

fix(connections): stop OAuth consent over 2 minutes dead-ending on 'Session expired' (#5222)

Ansh Grover34e5eac73906
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs
index 120607702..3bd467c5b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs
@@ -12,7 +12,8 @@ use crate::store::SettingsStore;
use base64::Engine;
use screenpipe_connect::connections::all_integrations;
use screenpipe_connect::oauth::{
- self, OAuthCallbackResult, PendingOAuth, OAUTH_REDIRECT_URI, PENDING_OAUTH,
+ self, OAuthCallbackResult, PendingOAuth, OAUTH_CALLBACK_TIMEOUT, OAUTH_REDIRECT_URI,
+ PENDING_OAUTH,
};
use serde::{Deserialize, Serialize};
use tauri::AppHandle;
@@ -96,17 +97,34 @@ pub async fn oauth_connect(
None => config.extra_auth_params,
};
- // Gate OAuth behind Pro subscription
- let is_pro = SettingsStore::get(&app_handle)
- .unwrap_or_default()
+ let settings = SettingsStore::get(&app_handle)
.unwrap_or_default()
- .user
- .cloud_subscribed
- == Some(true);
+ .unwrap_or_default();
+
+ // Gate OAuth behind Pro subscription
+ let is_pro = settings.user.cloud_subscribed == Some(true);
if !is_pro {
return Err("OAuth integrations require a Pro subscription. Please upgrade to connect third-party services.".to_string());
}
+ // The provider redirect URI is registered as localhost:3030 (Web-type
+ // OAuth clients require an exact match), so a flow started while the API
+ // server is bound elsewhere can never receive its callback. Fail fast
+ // with an explanation instead of opening a browser flow that dead-ends
+ // on a "Session expired" page.
+ if config.redirect_uri_override.is_none() {
+ let effective_port = std::env::var("SCREENPIPE_PORT")
+ .ok()
+ .and_then(|v| v.parse::<u16>().ok())
+ .unwrap_or(settings.recording.port);
+ if effective_port != 3030 {
+ return Err(format!(
+ "OAuth callbacks require the screenpipe API on port 3030, but it is configured for port {}. Reset the port in settings to use connections.",
+ effective_port
+ ));
+ }
+ }
+
// Per-account providers (Zendesk) host OAuth on the customer's own subdomain,
// so the authorization + token endpoints are per-account. When the auth_url
// carries a `{subdomain}` placeholder, the subdomain arrives as `instance`
@@ -137,11 +155,16 @@ pub async fn oauth_connect(
let (tx, rx) = oneshot::channel::<OAuthCallbackResult>();
{
let mut map = PENDING_OAUTH.lock().unwrap();
+ // Timed-out flows leave their entry behind so a late callback can be
+ // told "the app stopped waiting" (see the timeout branch below).
+ // Reclaim those tombstones here — this is the only insert point.
+ map.retain(|_, p| p.created_at.elapsed() < 2 * OAUTH_CALLBACK_TIMEOUT);
map.insert(
state.clone(),
PendingOAuth {
integration_id: integration_id.clone(),
sender: tx,
+ created_at: std::time::Instant::now(),
},
);
}
@@ -182,12 +205,25 @@ pub async fn oauth_connect(
integration_id, instance, variant
);
- let result = tokio::time::timeout(std::time::Duration::from_secs(120), rx)
+ // E2E escape hatch: shrink the wait so tests can exercise the timeout
+ // path without idling for 10 minutes.
+ let callback_timeout = std::env::var("SCREENPIPE_OAUTH_TIMEOUT_SECS")
+ .ok()
+ .and_then(|v| v.parse::<u64>().ok())
+ .map(std::time::Duration::from_secs)
+ .unwrap_or(OAUTH_CALLBACK_TIMEOUT);
+
+ let result = tokio::time::timeout(callback_timeout, rx)
.await
.map_err(|_| {
- let mut map = PENDING_OAUTH.lock().unwrap();
- map.remove(&state);
- format!("{} OAuth timed out (120s)", integration_id)
+ // Deliberately leave the PENDING_OAUTH entry in place: dropping
+ // `rx` makes the callback's send() fail, which lets it render a
+ // "took too long" page instead of "session expired". The entry is
+ // swept on the next oauth_connect.
+ format!(
+ "{} sign-in expired before the browser steps finished — click connect to try again",
+ integration_id
+ )
})?
.map_err(|_| "OAuth channel closed before code was received".to_string())?;
@@ -536,7 +572,7 @@ 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.
+/// the full callback timeout.
#[tauri::command]
#[specta::specta]
pub fn oauth_cancel(integration_id: String) -> Result<(), String> {
@@ -708,7 +744,7 @@ mod tests {
/// Canceled flow (#5092): oauth_cancel drops the pending sender, which
/// must close the channel so the awaiting oauth_connect fails fast
- /// instead of hanging for the full 120s timeout.
+ /// instead of hanging for the full callback timeout.
#[tokio::test]
async fn oauth_cancel_drops_pending_flow_and_closes_channel() {
let state = "test-cancel-state";
@@ -718,6 +754,7 @@ mod tests {
PendingOAuth {
integration_id: "test-cancel-integration".to_string(),
sender: tx,
+ created_at: std::time::Instant::now(),
},
);
@@ -738,6 +775,7 @@ mod tests {
PendingOAuth {
integration_id: "test-cancel-other-integration".to_string(),
sender: tx,
+ created_at: std::time::Instant::now(),
},
);
@@ -750,6 +788,53 @@ mod tests {
));
PENDING_OAUTH.lock().unwrap().remove(state);
}
+
+ /// Tombstones from timed-out flows are reclaimed by the sweep that runs
+ /// on the next insert: entries older than 2× the callback timeout go,
+ /// fresh ones stay.
+ #[tokio::test]
+ async fn stale_pending_entries_are_swept_fresh_ones_kept() {
+ use screenpipe_connect::oauth::OAUTH_CALLBACK_TIMEOUT;
+
+ // Instant can't represent times before boot; skip on a machine that
+ // just started (never the case in CI).
+ let Some(stale_instant) = std::time::Instant::now().checked_sub(3 * OAUTH_CALLBACK_TIMEOUT)
+ else {
+ return;
+ };
+
+ let stale_state = "test-sweep-stale-state";
+ let fresh_state = "test-sweep-fresh-state";
+ let (stale_tx, _stale_rx) = tokio::sync::oneshot::channel::<OAuthCallbackResult>();
+ let (fresh_tx, _fresh_rx) = tokio::sync::oneshot::channel::<OAuthCallbackResult>();
+ {
+ let mut map = PENDING_OAUTH.lock().unwrap();
+ map.insert(
+ stale_state.to_string(),
+ PendingOAuth {
+ integration_id: "test-sweep-integration".to_string(),
+ sender: stale_tx,
+ created_at: stale_instant,
+ },
+ );
+ map.insert(
+ fresh_state.to_string(),
+ PendingOAuth {
+ integration_id: "test-sweep-integration".to_string(),
+ sender: fresh_tx,
+ created_at: std::time::Instant::now(),
+ },
+ );
+ }
+
+ {
+ let mut map = PENDING_OAUTH.lock().unwrap();
+ map.retain(|_, p| p.created_at.elapsed() < 2 * OAUTH_CALLBACK_TIMEOUT);
+ assert!(!map.contains_key(stale_state));
+ assert!(map.contains_key(fresh_state));
+ map.remove(fresh_state);
+ }
+ }
}
/// Microsoft's well-known tenant ID for **personal** Microsoft accounts
diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rs
index 172f76513..3f6cd4d4d 100644
--- a/crates/screenpipe-connect/src/oauth.rs
+++ b/crates/screenpipe-connect/src/oauth.rs
@@ -64,6 +64,12 @@ use tokio::sync::oneshot;
pub const OAUTH_REDIRECT_URI: &str = "http://localhost:3030/connections/oauth/callback";
+/// How long `oauth_connect` waits for the browser callback. Matches the
+/// ~10-minute lifetime of provider authorization codes; consent flows with
+/// account pickers, 2FA, or "unverified app" interstitials routinely exceed
+/// shorter limits.
+pub const OAUTH_CALLBACK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
+
// ---------------------------------------------------------------------------
// Pending callback map — shared between oauth_connect (Tauri) and the
// /connections/oauth/callback HTTP handler (screenpipe-engine)
@@ -89,9 +95,15 @@ pub enum OAuthCallbackResult {
/// A pending OAuth flow: the sender that delivers the callback payload,
/// tagged with its `integration_id` so `oauth_cancel` can find and drop it.
+///
+/// Entries are deliberately left in the map when `oauth_connect` times out:
+/// the dropped receiver makes `sender.send()` fail, which lets the callback
+/// handler tell "the app stopped waiting" apart from a truly unknown state.
+/// Stale entries are swept on the next insert (see `created_at`).
pub struct PendingOAuth {
pub integration_id: String,
pub sender: oneshot::Sender<OAuthCallbackResult>,
+ pub created_at: std::time::Instant,
}
pub static PENDING_OAUTH: Lazy<Mutex<HashMap<String, PendingOAuth>>> =
diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rs
index 7d1575392..7cb3cbde3 100644
--- a/crates/screenpipe-engine/src/connections_api.rs
+++ b/crates/screenpipe-engine/src/connections_api.rs
@@ -1457,7 +1457,7 @@ pub struct OAuthCallbackQuery {
async fn oauth_callback(Query(params): Query<OAuthCallbackQuery>) -> (StatusCode, Html<String>) {
if let Some(err) = params.error {
// Provider rejection (e.g. access_denied on cancel). Resolve the waiting
- // flow immediately instead of leaving it to hit the 120s timeout.
+ // flow immediately instead of leaving it to hit the callback timeout.
let pending = params.state.as_ref().and_then(|state| {
let mut map = PENDING_OAUTH.lock().unwrap();
map.remove(state)
@@ -1469,10 +1469,19 @@ async fn oauth_callback(Query(params): Query<OAuthCallbackQuery>) -> (StatusCode
err,
pending.integration_id
);
- let _ = pending.sender.send(OAuthCallbackResult::ProviderError {
- error: err.clone(),
- error_description: params.error_description,
- });
+ if pending
+ .sender
+ .send(OAuthCallbackResult::ProviderError {
+ error: err.clone(),
+ error_description: params.error_description,
+ })
+ .is_err()
+ {
+ tracing::warn!(
+ "oauth callback: {} provider error arrived after the app stopped waiting",
+ pending.integration_id
+ );
+ }
}
None => tracing::warn!(
"oauth callback: provider returned error '{}' with {} state — no pending flow to resolve",
@@ -1512,28 +1521,46 @@ async fn oauth_callback(Query(params): Query<OAuthCallbackQuery>) -> (StatusCode
match sender {
Some(pending) => {
- tracing::info!(
- "oauth callback: authorization received for {}",
- pending.integration_id
- );
- let _ = pending.sender.send(OAuthCallbackResult::Success {
- code,
- realm_id: params.realm_id,
- });
- oauth_callback_page(
- StatusCode::OK,
- "Connected",
- "screenpipe can now use this connection.",
- "You can close this tab and return to screenpipe.",
- )
+ let delivered = pending
+ .sender
+ .send(OAuthCallbackResult::Success {
+ code,
+ realm_id: params.realm_id,
+ })
+ .is_ok();
+ if delivered {
+ tracing::info!(
+ "oauth callback: authorization received for {}",
+ pending.integration_id
+ );
+ oauth_callback_page(
+ StatusCode::OK,
+ "Connected",
+ "screenpipe can now use this connection.",
+ "You can close this tab and return to screenpipe.",
+ )
+ } else {
+ // Receiver dropped: oauth_connect timed out (or was cancelled)
+ // before the user finished the browser steps.
+ tracing::warn!(
+ "oauth callback: {} authorization arrived after the app stopped waiting",
+ pending.integration_id
+ );
+ oauth_callback_page(
+ StatusCode::BAD_REQUEST,
+ "Sign-in expired",
+ "This sign-in took a while, so screenpipe stopped waiting.",
+ "Open screenpipe and click connect again — a fresh sign-in stays valid for 10 minutes.",
+ )
+ }
}
None => {
tracing::warn!("oauth callback: unknown or stale state — no pending flow");
oauth_callback_page(
StatusCode::BAD_REQUEST,
- "Session expired",
- "screenpipe could not find the waiting app session.",
- "The authorization session was not found or already completed. Please try again.",
+ "Link already used",
+ "This authorization link was already used or has expired.",
+ "If screenpipe already shows the connection, you can close this tab. Otherwise click connect in the app to try again.",
)
}
}
@@ -4365,6 +4392,7 @@ mod tests {
PendingOAuth {
integration_id: "test-integration".to_string(),
sender: tx,
+ created_at: std::time::Instant::now(),
},
);
rx
@@ -4506,7 +4534,7 @@ mod tests {
}
#[tokio::test]
- async fn oauth_callback_success_with_stale_state_reports_session_expired() {
+ async fn oauth_callback_success_with_stale_state_reports_link_already_used() {
let (status, body) = oauth_callback(callback_query(
Some("auth-code-2"),
Some("test-cb-stale-state"),
@@ -4517,6 +4545,41 @@ mod tests {
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
- assert!(body.0.contains("Session expired"));
+ assert!(body.0.contains("already used or has expired"));
+ }
+
+ /// A callback arriving after oauth_connect stopped waiting (timeout or
+ /// cancel dropped the receiver) must get the actionable "Sign-in expired"
+ /// page — not a success page, and not the unknown-state one.
+ #[tokio::test]
+ async fn oauth_callback_after_timeout_reports_sign_in_expired() {
+ let state = "test-cb-timeout-state";
+ let rx = register_pending(state);
+ drop(rx); // simulate oauth_connect timing out / being cancelled
+
+ let (status, body) = oauth_callback(callback_query(
+ Some("auth-code-late"),
+ Some(state),
+ None,
+ None,
+ None,
+ ))
+ .await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(body.0.contains("Sign-in expired"));
+ assert!(!pending_contains(state));
+
+ // A second hit with the same state is now an unknown-state callback.
+ let (status, body) = oauth_callback(callback_query(
+ Some("auth-code-late"),
+ Some(state),
+ None,
+ None,
+ None,
+ ))
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(body.0.contains("already used or has expired"));
}
}