Skip to content

fix(auth): clear invalid login token to prevent setup wizard loop#38468

Open
jaiswalism wants to merge 3 commits into
RocketChat:developfrom
jaiswalism:fix/invalid-auth-token-redirect-loop
Open

fix(auth): clear invalid login token to prevent setup wizard loop#38468
jaiswalism wants to merge 3 commits into
RocketChat:developfrom
jaiswalism:fix/invalid-auth-token-redirect-loop

Conversation

@jaiswalism

@jaiswalism jaiswalism commented Feb 2, 2026

Copy link
Copy Markdown

Fix: Clear Invalid Auth Tokens to Prevent Registration Page Redirect Loop

Closes #38467

Problem

Users with stale or invalid authentication tokens (e.g., after a MongoDB restore, workspace ID change, or token corruption) could get stuck in a redirect loop where they were continuously sent to the Registration/Setup Wizard instead of the login page.

The sequence was:

  1. An invalid auth token existed in localStorage
  2. Token-based login failed, leaving userId === null
  3. useRedirectToSetupWizard redirected to /setup-wizard when !userId && setupWizardState === 'pending'
  4. The invalid token was never cleared
  5. On reload, the same flow repeated (infinite loop)

Root Cause

The useLoginViaQuery hook attempted to resume login using an invalid token but did not clear the token when login failed. This left the application in an inconsistent state: logged out but still holding an auth token that kept triggering resume attempts and setup redirects.

Solution

This PR ensures that invalid authentication tokens are properly cleared when a token-based login attempt fails.

Changes

1. client/views/root/hooks/useLoginViaQuery.ts

  • Import Accounts from meteor/accounts-base
  • When token login fails:
    • Call Accounts._unstoreLoginToken() to clear invalid auth state
    • Remove invalid resumeToken and userId from URL query parameters
  • This aligns with Meteor's expected auth lifecycle: failed resume requires token cleanup
} catch (error) {
    console.error('Failed to login with token', error);
    
    // Clear invalid tokens to prevent redirect loops
    Accounts._unstoreLoginToken();
    
    const { resumeToken: _, userId: __, ...search } = router.getSearchParameters();
    router.navigate({
        pathname: router.getLocationPathname(),
        search,
        replace: true,
    });
}

2. client/startup/startup.ts

Wrapped synchronizeUserData() in a try/catch block. If user data synchronization fails (commonly due to invalid auth state):

  • Clear local user data
  • Log the user out
  • Prevent startup crashes and protect against corrupted auth state

This is defensive cleanup and does not change normal startup behavior.

Impact

  • Prevents infinite redirect loops caused by invalid auth tokens
  • Improves resilience after DB restores, workspace migrations, or token corruption
  • Aligns auth cleanup with Meteor account lifecycle expectations
  • No breaking changes to normal login or setup flows

Files Changed

  • apps/meteor/client/views/root/hooks/useLoginViaQuery.ts
  • apps/meteor/client/startup/startup.ts

Related Issues

Summary by CodeRabbit

  • Bug Fixes
    • More robust user synchronization on startup with centralized error handling; if authentication errors occur the local session is cleared and the user is logged out to prevent inconsistent state.
    • Improved login-via-query recovery: invalid or failed login tokens are removed and URL query parameters are cleaned up to avoid stale or repeated login attempts.

@jaiswalism jaiswalism requested a review from a team as a code owner February 2, 2026 20:17
Copilot AI review requested due to automatic review settings February 2, 2026 20:17
@dionisio-bot

dionisio-bot Bot commented Feb 2, 2026

Copy link
Copy Markdown
Contributor

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@CLAassistant

CLAassistant commented Feb 2, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@changeset-bot

changeset-bot Bot commented Feb 2, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 9788ced

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Feb 2, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

Wraps startup user synchronization in a try/catch to centralize error handling; classifies auth errors to clear local auth state and logout when needed. Also clears stored login tokens and removes resumeToken/userId from URL on login-via-query failures.

Changes

Cohort / File(s) Summary
Startup sync error handling
apps/meteor/client/startup/startup.ts
Adds isAuthError helper; wraps user sync flow in try/catch; on auth errors clears local auth state and calls Meteor.logout(); preserves UTC offset update and status-change emission on success.
Login-via-query token handling
apps/meteor/client/views/root/hooks/useLoginViaQuery.ts
Imports useUnstoreLoginToken and calls it on login failure; clears resumeToken/userId from URL search and navigates with replace: true; adjusts effect deps and calls handleLogin() with void.

Sequence Diagram(s)

(Skipped — changes are limited and do not introduce a new multi-component control flow requiring visualization.)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

stat: ready to merge, stat: QA assured

Suggested reviewers

  • MartinSchoeler
  • lucas-a-pelegrino

Poem

🐰 I sniffed a stale token in the hay,
I hopped and cleared the crumbs away.
Try/catch stitched, the logout done,
Fresh auth dawns with morning sun. 🥕✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fixing invalid login token clearing to prevent setup wizard loops, which is the core objective.
Linked Issues check ✅ Passed The PR implementation meets all coding objectives from #38467: clearing invalid tokens on login failure and clearing auth state on sync failure prevents stale tokens from trapping users in the setup wizard.
Out of Scope Changes check ✅ Passed All changes directly address the root cause of the setup wizard loop issue; no out-of-scope modifications detected beyond the required token cleanup and error handling.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

Copilot AI 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.

Pull request overview

This PR fixes an infinite redirect loop that occurred when users had invalid authentication tokens (e.g., after MongoDB restore or workspace ID changes). The fix ensures invalid tokens are properly cleared when login attempts fail, preventing users from getting stuck on the registration/setup wizard page.

Changes:

  • Clear invalid authentication tokens when token-based login fails
  • Add error handling for user data synchronization failures during startup
  • Remove invalid URL parameters after failed login attempts

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
apps/meteor/client/views/root/hooks/useLoginViaQuery.ts Clears invalid tokens and URL parameters when token login fails; marks async function call as void
apps/meteor/client/startup/startup.ts Wraps user data synchronization in try/catch to handle auth failures gracefully

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread apps/meteor/client/views/root/hooks/useLoginViaQuery.ts Outdated
Comment thread apps/meteor/client/startup/startup.ts

@cubic-dev-ai cubic-dev-ai 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.

No issues found across 2 files

@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: 1

🤖 Fix all issues with AI agents
In `@apps/meteor/client/views/root/hooks/useLoginViaQuery.ts`:
- Line 38: Replace the direct call to the internal Meteor API
Accounts._unstoreLoginToken() in useLoginViaQuery with the project's established
wrapper; import and call the wrapper exported from
apps/meteor/client/meteor/overrides/unstoreLoginToken.ts (the same wrapper used
by AuthenticationProvider.tsx) instead of calling Accounts._unstoreLoginToken()
directly so the internal API is accessed consistently via the override.
🧹 Nitpick comments (2)
apps/meteor/client/views/root/hooks/useLoginViaQuery.ts (2)

37-38: Remove the code comment per coding guidelines.

The comment on line 37 should be removed as per the coding guidelines for TypeScript/JavaScript files which state to avoid code comments in the implementation.

♻️ Proposed fix
 			} catch (error) {
 				console.error('Failed to login with token', error);
-				// Clear invalid tokens, this prevents getting stuck on registration page
 				Accounts._unstoreLoginToken();

As per coding guidelines: **/*.{ts,tsx,js}: Avoid code comments in the implementation.


26-46: Consider extracting duplicate search parameter cleanup logic.

The search parameter cleanup logic (lines 26-34 and 39-46) is duplicated between the success and error paths. You could extract this into a helper function to reduce duplication.

♻️ Optional refactor to reduce duplication
 	useEffect(() => {
+		const clearSearchParams = () => {
+			const { resumeToken: _, userId: __, ...search } = router.getSearchParameters();
+			router.navigate(
+				{
+					pathname: router.getLocationPathname(),
+					search,
+				},
+				{ replace: true },
+			);
+		};
+
 		const handleLogin = async () => {
 			const { resumeToken } = router.getSearchParameters();

 			if (!resumeToken) {
 				return;
 			}

 			try {
 				await loginWithToken(resumeToken);

 				const routeName = router.getRouteName();

 				if (!routeName) {
 					router.navigate('/home');
 				}

-				const { resumeToken: _, userId: __, ...search } = router.getSearchParameters();
-
-				router.navigate(
-					{
-						pathname: router.getLocationPathname(),
-						search,
-					},
-					{ replace: true },
-				);
+				clearSearchParams();
 			} catch (error) {
 				console.error('Failed to login with token', error);
 				Accounts._unstoreLoginToken();
-				const { resumeToken: _, userId: __, ...search } = router.getSearchParameters();
-				router.navigate(
-					{
-						pathname: router.getLocationPathname(),
-						search,
-					},
-					{ replace: true },
-				);
+				clearSearchParams();
 			}
 		};

Comment thread apps/meteor/client/views/root/hooks/useLoginViaQuery.ts Outdated
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

@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: 1

🤖 Fix all issues with AI agents
In `@apps/meteor/client/startup/startup.ts`:
- Around line 29-50: The catch block around synchronizeUserData currently clears
auth and calls removeLocalUserData() + Meteor.logout() for any error; instead,
inspect the caught error for authentication-specific indicators (e.g.,
error.error === 'unauthorized', error.code === 401, or other auth flags returned
by sdk.stream().ready()/sdk.rest.get('/v1/me')) and only perform
removeLocalUserData() and Meteor.logout() when an auth failure is detected; for
non-auth errors, log the error and allow retries without clearing local state.
Ensure this logic is implemented in the same catch handling surrounding
synchronizeUserData so only genuine auth failures trigger logout.

Comment thread apps/meteor/client/startup/startup.ts Outdated
@jaiswalism

Copy link
Copy Markdown
Author

Updated startup error handling to only clear auth state and log out on authentication-specific failures. Non-auth errors are now logged and allowed to retry without clearing local state. Also refactored auth error detection into a small helper for clarity.

@jaiswalism

Copy link
Copy Markdown
Author

@MartinSchoeler @lucas-a-pelegrino could you please take a look when you have time? Thanks!

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.

Use of old authentication token leads to Registration page instead of existing content

3 participants