Skip to content

fix(desktop): improve auth token handling on re-authentication - #1000

Merged
saddlepaddle merged 1 commit into
mainfrom
fix/desktop-auth-reauth-handling
Jan 27, 2026
Merged

saddlepaddle merged 1 commit into
mainfrom
fix/desktop-auth-reauth-handling

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Jan 27, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes an issue where re-authenticating (e.g., switching accounts) could leave stale session state, causing data inconsistencies.

Changes

  • Subscription no longer emits on subscribe - Use getStoredToken query for initial hydration instead of relying on subscription's initial emit
  • Clear old session before setting new token - AuthProvider now explicitly clears old session state before applying new auth token
  • Documentation - Added docs for auth event emitter

Root Cause

The onTokenChanged subscription was emitting the current token on subscribe, which worked for initial load but caused issues on re-authentication. When a new OAuth callback came in, the subscription would fire with the new token, but the old session state wasn't cleared first.

Test Plan

  • Sign in with account A
  • Sign out
  • Sign in with account B
  • Verify no stale data from account A appears
  • Refresh app, verify session persists correctly

Summary by CodeRabbit

  • New Features

    • Added real-time token change subscription for immediate authentication state updates.
  • Improvements

    • Enhanced token refresh handling to clear prior session state before establishing new tokens, ensuring more reliable authentication state management.
  • Removals

    • Removed device information query.

✏️ Tip: You can customize this high-level summary in your review settings.

- Subscription no longer emits on initial subscribe (use getStoredToken query for hydration)
- Clear old session state before setting new token on re-authentication
- Add documentation for auth events

Previously, when a user re-authenticated (e.g., switching accounts), the old
session state could persist briefly causing stale data issues. Now the
AuthProvider explicitly clears the old session before setting the new token.
@coderabbitai

coderabbitai Bot commented Jan 27, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The changes introduce a new onTokenChanged subscription in the auth router to emit token updates, replace the deprecated getDeviceInfo query, and update the AuthProvider to clear session state before applying new tokens through async sign-out logic.

Changes

Cohort / File(s) Summary
Auth Router & Documentation
apps/desktop/src/lib/trpc/routers/auth/index.ts, apps/desktop/src/lib/trpc/routers/auth/utils/auth-functions.ts
Added onTokenChanged subscription to emit token updates ({ token, expiresAt } or null); removed getDeviceInfo query and related imports; expanded documentation for "token-saved" and "token-cleared" events.
AuthProvider Subscription Handler
apps/desktop/src/renderer/providers/AuthProvider/AuthProvider.tsx
Modified onTokenChanged callback to async; added explicit session clearing with setAuthToken(null) and await authClient.signOut() before applying new token.

Sequence Diagram(s)

sequenceDiagram
    participant AP as AuthProvider
    participant Sub as onTokenChanged<br/>Subscription
    participant AuthClient as AuthClient
    
    AP->>Sub: Subscribe to token changes
    Sub-->>AP: Emit token update {token, expiresAt}
    
    rect rgba(100, 150, 200, 0.5)
    Note over AP: Clear session state
    AP->>AP: setAuthToken(null)
    AP->>AuthClient: signOut(fetchOptions)
    AuthClient-->>AP: signOut complete
    end
    
    rect rgba(150, 200, 100, 0.5)
    Note over AP: Apply new token
    AP->>AP: setAuthToken(data.token)
    end
    
    alt Null token received
    Sub-->>AP: Emit null
    AP->>AP: setAuthToken(null)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • CharlieHelps

Poem

🐰 A token flows, oh what a sight!
Old sessions clear, then new ones bright,
Async awaits with grace so true,
The rabbit hops to auth anew! 🔐✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: improving auth token handling during re-authentication, which is directly addressed across all three modified files.
Description check ✅ Passed The PR description covers the required sections: summary of changes, root cause analysis, and a test plan. However, the description does not include a 'Related Issues' section or explicitly specify the 'Type of Change' as requested in the template.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/desktop/src/lib/trpc/routers/auth/index.ts (1)

93-97: Avoid silently swallowing file deletion errors.

The .catch(() => {}) on line 94 silently discards any error from fs.unlink. Per coding guidelines, errors should at minimum be logged with context.

Proposed fix
 signOut: publicProcedure.mutation(async () => {
-	await fs.unlink(TOKEN_FILE).catch(() => {});
+	await fs.unlink(TOKEN_FILE).catch((err) => {
+		// ENOENT is expected if already signed out or file never created
+		if (err.code !== "ENOENT") {
+			console.error("[auth/signOut] Failed to delete token file:", err);
+		}
+	});
 	authEvents.emit("token-cleared");
 	return { success: true };
 }),

@saddlepaddle
saddlepaddle merged commit 03aae27 into main Jan 27, 2026
4 of 5 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ⚠️ Neon database branch
  • ⚠️ Electric Fly.io app

Thank you for your contribution! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant