Skip to content

fix(auth): avoid setup redirect on expired token - #1435

Merged
khaira777 merged 3 commits into
mainfrom
fm/flocafe-startup-setup-redirect-r1
Nov 3, 2026
Merged

khaira777 merged 3 commits into
mainfrom
fm/flocafe-startup-setup-redirect-r1

Conversation

@khaira777

@khaira777 khaira777 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Intent

When starting the app after an update (or when the app has been closed and a previously stored token in localStorage is expired or invalidated), the app sometimes opens onto the first-run /setup screen instead of /auth/login, requiring the user to close the app and start it a second time (which then shows /auth/login). Investigate and fix this startup routing edge case (tracked in #1430).
Follow the Obra Superpowers engineering procedure end-to-end (research, spec/plan under ~/tools/firstmate/data/flocafe-startup-setup-redirect-r1/, TDD red-green-refactor, verification, and no-mistakes validation pipeline). Keep PR title <= 50 chars, single-line PR body paragraphs, and include Fixes #1430.

What Changed

  • Pass skipAuthRedirect: true on loadFromStorage's GET /auth/me startup probe and clear in-memory auth state on failure so expired or invalidated stored tokens do not race window.location.href navigation against AuthGuard's setup-status check.
  • Retry GET /auth/setup/status up to twice with a 400ms delay in AuthGuard, /setup, and /auth/login, and fall back to needsSetup = false in AuthGuard after retries are exhausted instead of routing an initialized store to /setup.
  • Add deterministic startup auth routing tests in tests/auth-ui-deterministic.test.ts and document skipAuthRedirect handling in docs/architecture/frontend.md.

Fixes #1430

Risk Assessment

✅ Low: The changes are minimal, targeted fixes that prevent competing 401 full-page unloads during auth bootstrap, add bounded retries for setup-status probes, and fall back to normal login routing rather than stranding initialized stores on /setup, backed by deterministic unit tests and updated documentation.

Testing

Ran npm run test:auth-ui-deterministic, npm run test:script-coverage, npm run build, npm run build:frontend, and live Playwright Chromium E2E tests against the running backend and static desktop frontend export covering all five startup and setup-status routing scenarios, capturing five browser screenshots as visual evidence; all checks passed.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Starting the app with an expired or invalidated JWT in localStorage clears stored session state without a competing window.location.assign redirect and lands directly on /auth/login without ever visit… ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario1-expired-token-startup-login.png
Starting the app with an expired token when the initial /api/auth/setup/status request fails transiently (HTTP 503) retries automatically and routes cleanly to /auth/login ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario2-transient-setup-status-retry.png
Adversarial: Starting the app when /api/auth/setup/status fails persistently across all retries exhausts bounded retries and falls back to /auth/login instead of routing an initialized store to /setup ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario3-persistent-failure-fallback-login.png
Opening /auth/login on a first-run store (needsSetup: true) after a transient /api/auth/setup/status error retries and redirects to /setup ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario4-first-run-routes-to-setup.png
Opening /setup on an already initialized store (needsSetup: false) after a transient /api/auth/setup/status error retries and redirects back to /auth/login ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario5-setup-redirects-initialized-to-login.png

Scenario 1: Startup with expired token in localStorage lands on /auth/login
Scenario 2: Startup with expired token and transient /api/auth/setup/status error retries and lands on /auth/login
Scenario 3: Persistent /api/auth/setup/status error across all retries falls back to /auth/login (never /setup)
Scenario 4: Uninitialized store on /auth/login retries transient setup-status failure and routes to /setup
Scenario 5: Visiting /setup on an initialized store retries transient setup-status failure and redirects back to /auth/login

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Starting the app with an expired or invalidated JWT in localStorage clears stored session state without a competing window.location.assign redirect and lands directly on /auth/login without ever visit… ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario1-expired-token-startup-login.png
Starting the app with an expired token when the initial /api/auth/setup/status request fails transiently (HTTP 503) retries automatically and routes cleanly to /auth/login ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario2-transient-setup-status-retry.png
Adversarial: Starting the app when /api/auth/setup/status fails persistently across all retries exhausts bounded retries and falls back to /auth/login instead of routing an initialized store to /setup ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario3-persistent-failure-fallback-login.png
Opening /auth/login on a first-run store (needsSetup: true) after a transient /api/auth/setup/status error retries and redirects to /setup ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario4-first-run-routes-to-setup.png
Opening /setup on an already initialized store (needsSetup: false) after a transient /api/auth/setup/status error retries and redirects back to /auth/login ✅ pass live ~/.no-mistakes/evidence/01M6HAEVSHZ5Z4DGWNQPK72MY7/scenario5-setup-redirects-initialized-to-login.png
  • npm run test:auth-ui-deterministic
  • npm run test:script-coverage
  • npm run build && npm run build:frontend
  • cd frontend && npx playwright test e2e/auth.spec.ts --config=playwright.config.ts --project=chromium
  • Live Playwright Chromium browser verification of expired-token startup, transient and persistent /api/auth/setup/status failures, first-run /setup redirect, and initialized /setup bounce-back to /auth/login with screenshot capture
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Prevent false setup redirects during auth startup

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Prevent expired startup tokens from triggering a hard redirect that competes with auth routing.
• Retry setup-status checks and route to login, not setup, when status remains unavailable.
• Add deterministic regression tests and document the startup redirect exception.
Diagram

graph TD
  Startup["App startup"] --> Store["Auth store"] --> Client["API client"] --> Endpoints["Auth endpoints"]
  Store --> Guard["Auth guard"] --> Status{"Setup needed?"}
  Guard --> Client
  Endpoints --> Status
  Status -->|Yes| Setup["Setup page"]
  Status -->|No or unavailable| Login["Login page"]
  Setup -->|Setup completed| Login
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Show a setup-status error screen
  • ➕ Avoids assuming setup is complete when its status cannot be verified.
  • ➖ Blocks access to login during a prolonged status-service failure and adds a recovery UI.

Recommendation: The bounded retries and login fallback fit the reported startup failure: a transient status error should not imply first-run setup. Reviewers should confirm that choosing normal auth routing when status remains unknown matches the product's desired failure policy; otherwise, an explicit error screen is the safer alternative.

Files changed (6) +534 / -42

Bug fix (4) +84 / -40
page.tsxRetry setup-status checks on the setup page +37/-22

Retry setup-status checks on the setup page

• Retries failed mount-time status requests twice with a delay, preserving the redirect to login when setup is already complete. Cancels a pending retry when the page unmounts.

frontend/src/app/setup/page.tsx

AuthGuard.tsxRecover from setup-status failures before routing +31/-15

Recover from setup-status failures before routing

• Retries the setup-status request twice and falls back to normal auth routing if all attempts fail, rather than sending users to setup. Explicit confirmation that setup is needed still routes to /setup.

frontend/src/components/layout/AuthGuard.tsx

api.tsAllow requests to suppress automatic 401 navigation +7/-1

Allow requests to suppress automatic 401 navigation

• Adds a typed skipAuthRedirect request option. On a 401, the interceptor still removes the stored token but leaves navigation to the caller when the option is set.

frontend/src/lib/api.ts

auth.tsClear expired startup sessions without a hard redirect +9/-2

Clear expired startup sessions without a hard redirect

• Uses skipAuthRedirect for the persisted-token /auth/me probe. On failure, removes stored credentials and clears in-memory user, token, tenant, and loading state so the guard can route to login.

frontend/src/store/auth.ts

Tests (1) +446 / -0
auth-ui-deterministic.test.tsCover startup and setup-status recovery paths +446/-0

Cover startup and setup-status recovery paths

• Adds deterministic cases for an expired startup token, continued redirects on ordinary 401s, guard retries and fallback, explicit setup routing, and setup-page recovery after a transient failure.

tests/auth-ui-deterministic.test.ts

Documentation (1) +4 / -2
frontend.mdDocument the bootstrap 401 redirect exception +4/-2

Document the bootstrap 401 redirect exception

• Explains that the startup /auth/me request opts out of the HTTP client's hard login redirect, allowing AuthGuard to route after expired credentials are cleared.

docs/architecture/frontend.md

@qodo-code-review

qodo-code-review Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. First-run users can remain on login ✓ Resolved
Description
AuthGuard sets needsSetup to false when its final setup-status request fails, treating an
unknown setup state as an initialized store. On a first-run installation, this routes the user to
/auth/login, whose own status check silently ignores a failure; if the service then recovers,
neither page checks again to send the user to setup.
Code

frontend/src/components/layout/AuthGuard.tsx[R140-142]

+            console.error('[AuthGuard] Failed to check setup status:', err);
+            // Fall back to normal auth routing rather than sending an initialized store to /setup.
+            setNeedsSetup(false);
Relevance

●● Moderate

Concrete auth-routing failure, but no close precedent confirms whether bounded setup-status failures
should retry or preserve setup state.

PR-#1425

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed exhaustion path sets a false setup state. The guard then redirects an unauthenticated
user to login; the login page only redirects to setup on a successful status response and swallows
request failures.

frontend/src/components/layout/AuthGuard.tsx[134-162]
frontend/src/app/auth/login/page.tsx[77-82]
main/routes/auth.ts[1073-1089]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
When setup status remains unavailable through the guard's retries on a first-run store, the fallback sends the user to login. If login's one status check also fails, recovery does not trigger another check or redirect to setup.

## Fix Focus Areas
- frontend/src/components/layout/AuthGuard.tsx[134-142]
- frontend/src/app/auth/login/page.tsx[77-82]

## Recommended Fix
Keep the initialized-store fallback to login, but retain an unknown-status recovery path on the login page. Retry the login page's status check after failures, including after the service becomes available, and redirect to `/setup` only when a successful response confirms `needsSetup: true`. Clean up retry timers on unmount and cover first-run recovery in a test.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #10
  🌐 PR #34
✅ Compliance rules (platform): 5 rules
✅ Cross-repo context — repo relationships
Review mode: Auto: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 10/18, lines 576/200; both must reach the floor). Router rationale: Auth routing spans multiple paths with substantial, independently subtle state and retry logic.

Grey Divider

Tip of the day
💡 Did you know, you can tweak Display settings with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Skip competing hard window.location.assign redirects on bootstrap /auth/me 401 responses, and retry /auth/setup/status before falling back to /auth/login rather than /setup.

Fixes #1430
Retry /api/auth/setup/status with bounded backoff on the login page so a first-run store still redirects to /setup after transient startup errors.

Fixes #1430
@khaira777
khaira777 force-pushed the fm/flocafe-startup-setup-redirect-r1 branch from f0c8da0 to faa4ad4 Compare November 3, 2026 18:36
@khaira777 khaira777 changed the title fix(auth): prevent false startup redirect to setup fix(auth): avoid setup redirect on expired token Nov 3, 2026
@khaira777
khaira777 merged commit 465a484 into main Nov 3, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-startup-setup-redirect-r1 branch November 3, 2026 18:49
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.

fix(auth): prevent false /setup redirect on startup when token expires or status check fails

1 participant