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(oauth): sweep shadowed default-slot entries + clean default on instanced save

Louis Beaumont9b5594338974
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 7b333784b..a0e3f7c36 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -9726,7 +9726,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.4.51"
+version = "2.4.52"
dependencies = [
"anyhow",
"arboard",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs
index ca36c24fa..9d4ff3dc8 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs
@@ -307,6 +307,25 @@ pub async fn oauth_connect(
.await
.map_err(|e| format!("failed to save token: {}", e))?;
+ // When we've just written to an instance-suffixed slot, proactively nuke
+ // the same integration's default slot. Why: `list_oauth_instances()` at
+ // connect time picks an instance-suffixed key for the new save whenever
+ // *any* existing entry is present. A stale default-slot entry (e.g. a
+ // pre-v2.4.52 partial save without refresh_token) would then linger and
+ // shadow every `instance=None` read path — which is exactly the zombie-
+ // token bug customers hit. Cleaning here means the read side only ever
+ // sees one entry per integration+identity.
+ if store_instance.is_some() {
+ if let Err(e) =
+ oauth::delete_oauth_token_instance(store.as_ref(), &integration_id, None).await
+ {
+ tracing::warn!(
+ "oauth: failed to clean stale default slot after instanced save for {}: {e:#}",
+ integration_id
+ );
+ }
+ }
+
let display_name = token_data["email"]
.as_str()
.or_else(|| token_data["workspace_name"].as_str())
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
index d62eb474e..6cd16c90c 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
@@ -355,6 +355,22 @@ impl ServerCore {
}
Err(e) => warn!("legacy secret migration failed: {}", e),
}
+
+ // One-shot cleanup for users upgrading from pre-v2.4.53:
+ // drop any `oauth:{id}` default-slot entry that's been
+ // shadowed by a same-integration `oauth:{id}:{name}`
+ // instance entry. Without this, read paths with
+ // instance=None keep hitting the stale default and
+ // reporting "not connected" even though a healthy
+ // instanced entry sits right next to it.
+ match screenpipe_connect::oauth::sweep_shadowed_default_slots(&store).await {
+ Ok(n) if n > 0 => {
+ info!("oauth: swept {} shadowed default-slot entry(ies)", n);
+ }
+ Ok(_) => {}
+ Err(e) => warn!("oauth: sweep_shadowed_default_slots failed: {}", e),
+ }
+
server.secret_store = Some(Arc::new(store));
}
Err(e) => {
diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rs
index 554adbf29..71a9a905e 100644
--- a/crates/screenpipe-connect/src/oauth.rs
+++ b/crates/screenpipe-connect/src/oauth.rs
@@ -454,6 +454,67 @@ pub async fn list_oauth_instances(
instances
}
+// ---------------------------------------------------------------------------
+// One-shot migration: sweep shadowed default-slot entries
+// ---------------------------------------------------------------------------
+
+/// For each integration that has BOTH a default-slot entry (`oauth:{id}`)
+/// AND at least one instance-suffixed entry (`oauth:{id}:{name}`), drop
+/// the default-slot entry.
+///
+/// Why: the connect flow picks an instance-suffixed key for a new save
+/// whenever any prior entry exists. Older app versions sometimes wrote a
+/// broken default-slot entry (missing `refresh_token` due to Google's
+/// re-authorization suppression). That broken entry then shadows every
+/// `instance=None` read, so pipes see "not connected" even though a
+/// healthy instanced entry sits right next to it. This sweep is the
+/// once-per-startup cleanup so users don't have to touch SQLite.
+///
+/// Safe to call on every app launch: no-op when there's no shadowing.
+/// Returns the number of entries deleted.
+pub async fn sweep_shadowed_default_slots(store: &SecretStore) -> Result<usize> {
+ use std::collections::HashSet;
+
+ let keys = store.list("oauth:").await?;
+
+ // Partition keys into "has default slot" vs "has at least one named
+ // instance" per integration id. A key like `oauth:gmail` has no colon
+ // after the prefix → default slot. `oauth:gmail:[email protected]` → named.
+ let mut has_default: HashSet<String> = HashSet::new();
+ let mut has_named: HashSet<String> = HashSet::new();
+ for key in &keys {
+ let Some(rest) = key.strip_prefix("oauth:") else {
+ continue;
+ };
+ match rest.split_once(':') {
+ Some((id, _)) => {
+ has_named.insert(id.to_string());
+ }
+ None => {
+ has_default.insert(rest.to_string());
+ }
+ }
+ }
+
+ let mut deleted = 0usize;
+ for id in has_default.intersection(&has_named) {
+ let key = format!("oauth:{}", id);
+ match store.delete(&key).await {
+ Ok(()) => {
+ tracing::info!(
+ "oauth: swept shadowed default-slot entry for {} (instance-suffixed entry still present)",
+ id
+ );
+ deleted += 1;
+ }
+ Err(e) => {
+ tracing::warn!("oauth: failed to sweep default slot for {}: {e:#}", id);
+ }
+ }
+ }
+ Ok(deleted)
+}
+
// ---------------------------------------------------------------------------
// Token refresh
// ---------------------------------------------------------------------------
@@ -704,6 +765,160 @@ mod tests {
assert!(is_oauth_instance_connected(Some(&store), id, None).await);
}
+
+ // ---- sweep_shadowed_default_slots --------------------------------
+
+ #[tokio::test]
+ async fn sweep_removes_default_when_named_exists() {
+ // The exact scenario that produced the zombie-token bug:
+ // pre-v2.4.53 left a default-slot entry, then v2.4.52's save
+ // landed a working instance-suffixed entry beside it. Sweep
+ // should drop the default so reads stop hitting the stale one.
+ let store = mem_store().await;
+ store
+ .set_json("oauth:_t_sweep1", &json!({"access_token": "stale"}))
+ .await
+ .unwrap();
+ store
+ .set_json(
+ "oauth:_t_sweep1:[email protected]",
+ &json!({"access_token": "fresh", "refresh_token": "rt"}),
+ )
+ .await
+ .unwrap();
+
+ let deleted = sweep_shadowed_default_slots(&store).await.unwrap();
+ assert_eq!(deleted, 1);
+
+ // Default slot is gone.
+ let default_key: Option<serde_json::Value> =
+ store.get_json("oauth:_t_sweep1").await.unwrap();
+ assert!(default_key.is_none());
+ // Named entry untouched.
+ let named: serde_json::Value = store
+ .get_json("oauth:_t_sweep1:[email protected]")
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(named["access_token"], "fresh");
+ }
+
+ #[tokio::test]
+ async fn sweep_leaves_lonely_default_slot() {
+ // A default-slot entry with NO companion instance entry is the
+ // normal single-account happy path — don't touch it.
+ let store = mem_store().await;
+ store
+ .set_json("oauth:_t_sweep2", &json!({"access_token": "keep"}))
+ .await
+ .unwrap();
+
+ let deleted = sweep_shadowed_default_slots(&store).await.unwrap();
+ assert_eq!(deleted, 0);
+
+ let kept: serde_json::Value = store
+ .get_json("oauth:_t_sweep2")
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(kept["access_token"], "keep");
+ }
+
+ #[tokio::test]
+ async fn sweep_leaves_named_only_state_alone() {
+ // No default slot, only named entries — also a healthy state,
+ // e.g. an explicit multi-account setup. Sweep must not touch
+ // the named entries.
+ let store = mem_store().await;
+ store
+ .set_json("oauth:_t_sweep3:[email protected]", &json!({"access_token": "A"}))
+ .await
+ .unwrap();
+ store
+ .set_json("oauth:_t_sweep3:[email protected]", &json!({"access_token": "B"}))
+ .await
+ .unwrap();
+
+ let deleted = sweep_shadowed_default_slots(&store).await.unwrap();
+ assert_eq!(deleted, 0);
+
+ // Both named entries still present.
+ assert!(store
+ .get_json::<serde_json::Value>("oauth:_t_sweep3:[email protected]")
+ .await
+ .unwrap()
+ .is_some());
+ assert!(store
+ .get_json::<serde_json::Value>("oauth:_t_sweep3:[email protected]")
+ .await
+ .unwrap()
+ .is_some());
+ }
+
+ #[tokio::test]
+ async fn sweep_handles_mixed_integrations() {
+ // Realistic state seen in production: multiple integrations, some
+ // shadowed, some not. Only the shadowed ones get swept.
+ let store = mem_store().await;
+ // shadowed
+ store.set_json("oauth:_t_mix_a", &json!({})).await.unwrap();
+ store
+ .set_json("oauth:_t_mix_a:[email protected]", &json!({}))
+ .await
+ .unwrap();
+ // lonely default — keep
+ store
+ .set_json("oauth:_t_mix_b", &json!({"access_token": "ok"}))
+ .await
+ .unwrap();
+ // lonely named — keep
+ store
+ .set_json("oauth:_t_mix_c:[email protected]", &json!({}))
+ .await
+ .unwrap();
+
+ let deleted = sweep_shadowed_default_slots(&store).await.unwrap();
+ assert_eq!(deleted, 1);
+
+ assert!(store
+ .get_json::<serde_json::Value>("oauth:_t_mix_a")
+ .await
+ .unwrap()
+ .is_none());
+ assert!(store
+ .get_json::<serde_json::Value>("oauth:_t_mix_b")
+ .await
+ .unwrap()
+ .is_some());
+ assert!(store
+ .get_json::<serde_json::Value>("oauth:_t_mix_c:[email protected]")
+ .await
+ .unwrap()
+ .is_some());
+ }
+
+ #[tokio::test]
+ async fn sweep_is_idempotent() {
+ // Running twice is a no-op on the second call.
+ let store = mem_store().await;
+ store
+ .set_json("oauth:_t_idem", &json!({}))
+ .await
+ .unwrap();
+ store
+ .set_json("oauth:_t_idem:[email protected]", &json!({}))
+ .await
+ .unwrap();
+
+ assert_eq!(sweep_shadowed_default_slots(&store).await.unwrap(), 1);
+ assert_eq!(sweep_shadowed_default_slots(&store).await.unwrap(), 0);
+ }
+
+ #[tokio::test]
+ async fn sweep_empty_store_is_noop() {
+ let store = mem_store().await;
+ assert_eq!(sweep_shadowed_default_slots(&store).await.unwrap(), 0);
+ }
}
pub async fn exchange_code(