Skip to content

🔁 fix: Keep the Session When the Refresh Check Is Unavailable - #18633

Draft
AtefBellaaj wants to merge 5 commits into
atef/ai-2415-bcl-02-auth-methodfrom
atef/ai-2415-bcl-02b-refresh-retryable
Draft

AtefBellaaj wants to merge 5 commits into
atef/ai-2415-bcl-02-auth-methodfrom
atef/ai-2415-bcl-02b-refresh-retryable

Conversation

@AtefBellaaj

@AtefBellaaj AtefBellaaj commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Pull Request

Before submitting, please review the Contributing Guide.

Documentation changes belong in the LibreChat documentation repository.

Summary

Part 3 of 9 in the OpenID back-channel logout stack. It is based on #18435, and #18436 builds on it. This PR holds the refresh changes that apply in every deployment, whether or not back-channel logout is configured.

Today the client signs the user out after any failed refresh. A refresh that fails because the server could not complete the check (a database error, a 5xx, a 429, a network error or a timeout) therefore looks the same as a refresh that the server denied. A short outage of the session store signs out every user whose access token expires during it.

This PR separates the two outcomes. The server answers 503 with the code AUTH_SESSION_CHECK_UNAVAILABLE when it cannot complete the check, and keeps 401/403 for a bad or expired refresh token. The client keeps the session when the check is unavailable and signs out only on a denial. On the first page load, when the session cannot be confirmed, the app shows a Retry screen instead of the login page. The screen also has a "Sign in again" button.

How it works

localRefresh returns 403 only for an invalid token (JsonWebTokenError, NotBeforeError). Any other error is now a 503 with the code. The expired paths send JSON instead of a redirect, so the client can read the response. A missing JWT_REFRESH_SECRET now throws instead of verifying against an empty secret, so it is reported as unavailable.

One classifier in packages/data-provider/src/request.ts decides the outcome for every refresh path (the response interceptor, the proactive refresh and the AuthContext mutation):

const classifyRefreshFailure = (error: unknown): RefreshFailureClassification => {
  const status = (error as { response?: { status?: unknown } } | undefined)?.response?.status;
  const isDenial = typeof status === 'number' && status >= 400 && status < 500 && status !== 429;
  return isDenial ? 'denied' : 'unavailable';
};
refresh fails
├── denied (4xx except 429)       → sign out, redirect to /login (unchanged)
└── unavailable (5xx, 429, network, timeout)
    ├── during use                → keep the session, show a warning toast,
    │                               re-throw the original 401 marked as unavailable
    └── on first load             → authSessionUnavailableAtom = true
                                    → <Retry> instead of the app
                                      ├── Retry          → silentRefresh()
                                      └── Sign in again  → clear tab auth state → /login

The Retry screen does not block public routes (/login, /share, and the others in isPublicRoute), deployments with optional auth, or test mode. "Sign in again" does not wait for a server call, because the service that is down may be the one it would call.

Type of change

  • Bug fix

Testing

Tested environments/configuration:

No configuration needed. The change applies to every deployment.

Local Chrome 158 with the LibreChat server and a separate MongoDB 8.2 test instance. I signed in with a local account, forced MongoDB reads to fail, and reloaded the chat. The refresh endpoint returned 503 AUTH_SESSION_CHECK_UNAVAILABLE and the Retry screen appeared in both themes.

While MongoDB reads still failed, clicking Retry showed a disabled Retrying… button, then returned to the Retry screen with the session cookie intact. After I restored reads, Retry returned to the chat without another sign-in. Sign in again opened the login page during the outage. A revoked session returned 401 and opened the login page.

Automated tests:

  • New cases in packages/data-provider/src/request.spec.ts and specs/request-interceptor.spec.ts for each status class and for the proactive refresh.
  • New cases in packages/api/src/auth/localRefresh.spec.ts for the 503 and the JSON expired responses.
  • New client/src/components/Auth/__tests__/Retry.spec.tsx; new cases in client/src/hooks/__tests__/AuthContext.spec.tsx for the first-load Retry, the toast, and "Sign in again".
  • AuthController.spec.js now expects 503 for an unavailable check.
  • CI runs typecheck and the full suites.
  • Locally, 328 tests passed across the six focused Jest suites. The Lighthouse startup check also passed.
  • The existing Playwright timeout test still expects a redirect to /login. It failed because the browser stayed on the chat URL and showed Retry. Timeout assertion

Screenshots / recordings

The Retry screen is new. Both screenshots show the page after the session check returned HTTP 503.

Light mode Dark mode
Session retry screen in light mode Session retry screen in dark mode

Risk / compatibility

A client that predates this change treats the new 503 as a failed refresh and signs out, which is the same result it has today. The expired paths now answer JSON instead of a redirect; the client already handles both as a denial. A deployment without JWT_REFRESH_SECRET now gets a 503 instead of a 403 on refresh.

Checklist

  • I reviewed my own changes
  • Relevant tests have been added or updated
  • Existing relevant tests pass
  • The change does not introduce new warnings or errors
  • User-facing or complex behavior is documented where necessary
  • Required dependency changes have been merged/published
  • Required documentation PR: N/A

The refresh handler answered 403 for any error, so a MongoDB outage or a
missing JWT_REFRESH_SECRET signed users out. Only a bad refresh token now
answers 403. Other failures answer 503 AUTH_SESSION_CHECK_UNAVAILABLE.

The two expired paths sent a 302 to /login, because Express ignores the
status before redirect(). They now send the status with a JSON body.

The client keeps the session on that 503. It shows a Retry screen when no
usable token is left, and a toast otherwise.
…etwork error

Both refresh paths now use one classifier. Only a 4xx other than 429
ends the session. A 5xx, a 429 or a failure without a response
dispatches the session-unavailable event, so the proactive path sends
the request with the still valid token instead of signing the user out.
…ession

The provider enables the user query only once it holds a token, and it
sets the token together with isAuthenticated. The tests now sign in
first and fail the query only when it is enabled, so they assert the
session stays and Retry does not show.
The Retry screen had no exit other than Retry. Sign in again ends the
session in this tab and opens the login page without a server call, so
it works while the session service is down. It advances the auth
generation, so a retry that settles later cannot restore the session.
@AtefBellaaj

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T09:58:08.435057Z fb1e793 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 290280024c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +338 to +341
const signInAgain = useCallback(() => {
clearAuthenticationForRedirect();
setIsAuthReady(true);
navigate(buildLoginRedirectUrl());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Clear the bearer when leaving Retry to sign in again

If Retry is reached with an existing Axios bearer—for example, after the SPA navigation from ShareView into chat mounts a new auth provider and its refresh fails—this action clears React state but leaves axios.defaults.headers.common.Authorization intact. clearAuthenticationForRedirect() does not call setTokenHeader(undefined); its previous enrollment-redirect caller cleared the header separately. Consequently, requests from the login page still carry the previous account's bearer, and a near-expiry bearer can trigger proactive refresh and a tokenUpdated event that authenticates the tab again instead of leaving it on sign-in. Clear the transport header synchronously along with the tab's auth state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid. The Retry screen shows only when this provider is not authenticated, so it never reaches Retry with its own bearer set. Another provider can leave one on the shared axios defaults, though, for example the share page's provider before an SPA navigation into chat. Fixed in fb1e793: clearAuthenticationForRedirect now clears the axios bearer together with the tab's auth state, so "Sign in again" lands on the state a replaced document would leave, and a near-expiry bearer can't start a proactive refresh from the login page. A new case in AuthContext.spec.tsx checks that the header is cleared, and it fails without the fix.

Another auth provider, such as the share page's, can leave a bearer on the shared axios defaults. Sign in again cleared only the tab's auth state, so the login page kept sending that bearer, and a near-expiry one could start a proactive refresh that signed the tab in again. clearAuthenticationForRedirect now clears the header too, which is the state a replaced document leaves.
@AtefBellaaj

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fb1e793ecc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (request.getAuthGeneration() !== refreshGeneration) {
return;
}
if (request.classifyRefreshFailure(error) === 'unavailable') {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor the unavailable marker in the refresh mutation

When this provider mounts with an Axios bearer left by another provider (for example, after navigating from a share page), its initial refresh can enter the response interceptor's 401 recovery path. If that recovery refresh fails with a 503, 429, or network error, the interceptor rejects the original 401 marked with __authSessionUnavailable. This handler checks only classifyRefreshFailure(), which ignores that marker and classifies the error as denied, clearing session state and navigating to login instead of showing Retry. Check request.isAuthSessionUnavailableError(error) as well, as the user-query handler already does, so the interceptor's unavailable classification survives this path.

Useful? React with 👍 / 👎.

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant