Skip to content

feat(auth): restart login on auth_error callback bounces, loop-guarded - #239

Merged
cyberantonz merged 3 commits into
constructorfabric:mainfrom
cyberantonz:feat/auth-error-loop-guard
Jul 30, 2026
Merged

feat(auth): restart login on auth_error callback bounces, loop-guarded#239
cyberantonz merged 3 commits into
constructorfabric:mainfrom
cyberantonz:feat/auth-error-loop-guard

Conversation

@cyberantonz

@cyberantonz cyberantonz commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Summary

FE half of constructorfabric/insight#2032. A failed OIDC callback used to dead-end the browser on the authenticator's problem+json — nothing is loaded at /auth/callback, so an expired login state (the 300 s Redis TTL) simply stopped the login on a raw JSON page. The authenticator now 302s such failures back to the SPA with a fixed auth_error=<reason> query parameter (backend PR to follow); this PR makes the SPA consume it and go through the whole login machinery from scratch.

Behavior

  • Boot (main.tsx) consumes ?auth_error= before the session probe and strips it from the URL (reloads, copied links, and the next login's return_to never carry it).
  • Live session (e.g. a replayed callback after a successful login) → the stale auth_error is ignored, app renders normally.
  • Retryable reasons (state_expired, idp_error, invalid_callback, exchange_failed) → one automatic signIn() restart; a sessionStorage attempt counter halts a persistent failure on a new full-page error screen with a manual "Try again" instead of looping browser → IdP.
  • access_denied (unknown person / no tenant / unknown view-as target) → error screen immediately; a silent SSO hop would just reproduce it.
  • Storage unavailable → fails closed to the error screen (never an uncounted loop).
  • Also fixes a latent bfcache issue: browser-Back from the IdP restored the page with the module-level redirecting guard stuck true, turning every later signIn() into a silent no-op; it now resets on pageshow.

Deploy order

Safe to deploy ahead of the authenticator change — without the new parameter the boot path is unchanged. The authenticator PR should not be deployed first: its access_denied bounce relies on this guard to avoid an SPA↔IdP redirect loop for unprovisioned users.

Test plan

  • npm run test — 701 passed (8 new tests in src/auth/auth-error.test.ts: consume/strip, hash preservation, empty value, retry budget, access_denied, storage-off fail-closed, budget reset).
  • npm run typecheck, eslint src/ — clean.

Part of constructorfabric/insight#2032

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a dedicated sign-in error screen with localized messaging.
    • Added a “Try again” option for recoverable authentication failures.
    • Automatically retries eligible sign-in failures once while preventing redirect loops.
    • Preserves the page URL and hash while removing handled error details.
  • Bug Fixes

    • Restores sign-in functionality after returning to the app through browser back/forward navigation.
    • Safely handles unavailable browser storage without repeated automatic retries.

cyberantonz and others added 2 commits July 30, 2026 11:46
A failed OIDC callback used to dead-end the browser on the
authenticator's problem+json — nothing was loaded at /auth/callback, so
an expired login state (the 300 s Redis TTL, insight#2032) simply
stopped the login. The authenticator now 302s such failures back to the
SPA with a fixed auth_error=<reason> query parameter.

Boot consumes the parameter before the session probe: a stale bounce on
a live session is ignored, retryable reasons (state_expired, idp_error,
invalid_callback, exchange_failed) restart the login once, and a
sessionStorage attempt counter halts persistent failures on a new
full-page error screen with a manual retry instead of looping
browser -> IdP. access_denied never auto-retries — a silent SSO hop
would just reproduce it.

Safe to deploy ahead of the authenticator change: without the new
parameter the boot path is unchanged.

Part of insight#2032

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Anton Zelenov <antonz@constructor.tech>
- signIn() with no arg on auto-retry and the error screen's button:
  return to the current URL (already stripped of auth_error) instead of
  hardcoding "/", so a non-root default_return_to survives the bounce.
- Strip an empty ?auth_error= without counting it against the retry
  budget (the authenticator always sends a reason; empty means a
  hand-crafted URL) so it can't ride into return_to and stick.
- Reset the signIn redirect guard on bfcache restores (pageshow with
  persisted) — browser Back from the IdP used to leave the module's
  redirecting flag true, turning the "Try again" button into a silent
  no-op.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Anton Zelenov <antonz@constructor.tech>
@cyberantonz
cyberantonz requested a review from a team as a code owner July 30, 2026 04:02
@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@cyberantonz, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 44 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b192d1f0-e98c-495d-9f0a-43cef633ca95

📥 Commits

Reviewing files that changed from the base of the PR and between aafbc4c and 384ab72.

📒 Files selected for processing (5)
  • src/auth/auth-error.test.ts
  • src/auth/auth-error.ts
  • src/auth/use-auth.test.ts
  • src/auth/use-auth.ts
  • src/components/login-error.tsx
📝 Walkthrough

Walkthrough

Adds bounded OIDC callback-error handling, session-backed retry tracking, auth-aware bootstrap routing, localized login-error UI, and bfcache redirect recovery.

Changes

Auth error recovery

Layer / File(s) Summary
Auth error contract and retry state
src/auth/auth-error.ts, src/auth/auth-error.test.ts, src/auth/index.ts
Adds URL consumption, session-backed retry limits, fail-closed storage handling, reset behavior, public exports, and Vitest coverage.
Bootstrap auth-error routing
src/main.tsx
Consumes callback errors during startup, coordinates session loading and refresh, retries eligible failures, and renders either the application or login-error screen.
Login-error UI and redirect recovery
src/components/login-error.tsx, src/locales/en/translation.json, src/auth/use-auth.ts
Adds localized failure messaging and retry behavior, and clears the redirect guard after bfcache restoration.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant bootstrap
  participant AuthError
  participant Session
  participant LoginError
  Browser->>bootstrap: start application
  bootstrap->>AuthError: consume auth_error
  bootstrap->>Session: load session
  Session-->>bootstrap: session state
  bootstrap->>LoginError: render failure when needed
  LoginError->>Session: signIn on retry
Loading

Possibly related PRs

Suggested reviewers: ktursunov, mitasovr

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 clearly describes the main change: restarting login on auth_error callback failures with loop protection.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/auth/auth-error.ts`:
- Around line 36-40: Update writeAttempts and its callers in auth-error.ts so it
returns whether persisting the retry counter succeeded, and require that result
when computing autoRetry in the returned object; if setItem fails, autoRetry
must be false even when the attempt count is otherwise within MAX_AUTO_RETRIES.
Add coverage for the setItem-only failure path.

In `@src/components/login-error.tsx`:
- Around line 29-33: Update the shared default return-URL calculation in useAuth
to append window.location.hash to the existing pathname-and-search value, so
signIn() preserves hash-routed destinations during manual retry from the login
error flow. Do not duplicate URL construction in the Button handler.
- Around line 20-40: Update the failure screen markup in the login error
component to use a main landmark instead of the outer div, promote the
loginFailedTitle text to an h1, and wrap the failure message in an assertive
live status region so screen readers announce it when the root is replaced.
Preserve the existing translations, styling, and retry behavior.

In `@src/main.tsx`:
- Around line 54-59: Update the retryable auth-error branch in the main
component to call signIn with the full current URL target, including
window.location.hash, so consumeAuthErrorParam()’s preserved fragment survives
login. Apply the same return-target change to the manual retry handler in the
LoginError component, preserving existing retry behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ee35236c-11b9-4d4d-ba71-00e15478b521

📥 Commits

Reviewing files that changed from the base of the PR and between 0a5cd05 and aafbc4c.

📒 Files selected for processing (7)
  • src/auth/auth-error.test.ts
  • src/auth/auth-error.ts
  • src/auth/index.ts
  • src/auth/use-auth.ts
  • src/components/login-error.tsx
  • src/locales/en/translation.json
  • src/main.tsx

Comment thread src/auth/auth-error.ts Outdated
Comment thread src/components/login-error.tsx Outdated
Comment thread src/components/login-error.tsx
Comment thread src/main.tsx
Comment on lines +54 to +59
if (authError?.autoRetry) {
// A fresh login fixes the retryable reasons (expired state after a
// slow IdP round-trip, IdP hiccup); the attempt counter halts a
// persistent failure on the error screen instead of looping. No-arg
// signIn: return to the current URL, already stripped of auth_error.
signIn();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Pass the fragment as the login return target.

Line 59 uses no-argument signIn(), whose default return target excludes window.location.hash. The retry therefore loses the fragment that consumeAuthErrorParam() preserved. Pass the full current target here; apply the same change to the manual retry in src/components/login-error.tsx.

Proposed fix
-        signIn();
+        signIn(
+          window.location.pathname +
+            window.location.search +
+            window.location.hash,
+        );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (authError?.autoRetry) {
// A fresh login fixes the retryable reasons (expired state after a
// slow IdP round-trip, IdP hiccup); the attempt counter halts a
// persistent failure on the error screen instead of looping. No-arg
// signIn: return to the current URL, already stripped of auth_error.
signIn();
if (authError?.autoRetry) {
// A fresh login fixes the retryable reasons (expired state after a
// slow IdP round-trip, IdP hiccup); the attempt counter halts a
// persistent failure on the error screen instead of looping. No-arg
// signIn: return to the current URL, already stripped of auth_error.
signIn(
window.location.pathname +
window.location.search +
window.location.hash,
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main.tsx` around lines 54 - 59, Update the retryable auth-error branch in
the main component to call signIn with the full current URL target, including
window.location.hash, so consumeAuthErrorParam()’s preserved fragment survives
login. Apply the same return-target change to the manual retry handler in the
LoginError component, preserving existing retry behavior.

- Do not auto-retry an attempt that could not be persisted (getItem
  works, setItem throws): the next bounce would read zero again and the
  loop guard would never trip. writeAttempts now reports success and
  autoRetry requires it.
- Preserve the URL hash in signIn's default return_to (covers both the
  auto-retry and the error screen's Try-again path).
- Semantic markup on the login-error screen: main landmark, h1 title,
  role=alert on the message so screen readers announce it on mount.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Anton Zelenov <antonz@constructor.tech>
@cyberantonz
cyberantonz merged commit 617e628 into constructorfabric:main Jul 30, 2026
11 checks passed
@cyberantonz
cyberantonz deleted the feat/auth-error-loop-guard branch July 30, 2026 04:43
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.

2 participants