Skip to content

fix(auth): harden session refresh and logout - #119

Merged
uniqueg merged 10 commits into
devfrom
fix/111-session-refresh
Nov 19, 2026
Merged

uniqueg merged 10 commits into
devfrom
fix/111-session-refresh

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes the session handling findings of the 0.1.0 pre-release review (#111), including #106.

Refresh route (POST /auth/api/refresh), per RFC 6749 §5.2:

Token endpoint answers Before Now
400 invalid_grant (expired, revoked, reused refresh token) 401, cookies kept, tab redirected to login on every visit 401 session_ended, all session cookies deleted (409 concurrent_refresh within the replay window)
401 (not invalid_client) 401, cookies deleted same as invalid_grant
invalid_client (rotated secret), 5xx, timeouts, discovery or token response errors 401 (or 500), tab redirected to login 503 unavailable, session kept, error logged
no refresh token (e.g. stale token_expires_at of a visitor) 401, tab redirected to login 401 no_refresh_token, only token_expires_at deleted, no redirect
refreshed ID token for another sub/iss accepted 401 session_ended (OIDC Core 12.2)

The route also checks the Origin like the logout (shared rejectForeignOrigin()).

Client (src/lib/token-refresh.ts, used by useTokenRefresh): refreshes 5 minutes before the real expiry, or at half the token lifetime if shorter (no double margin; token_expires_at is now <expiry>:<lifetime> in ms), leaves the page only on session_ended, stops on no_refresh_token, retries everything else with backoff (5 s, doubling, max 5 min). All tabs share a Web Lock, so only one refreshes at a time (this also removes the multi-pod race of #93/#107 for browsers with Web Locks).

Logout: stops the page's refresher and runs under the same lock, so it waits for a refresh in flight in any tab; revokes the refresh token when discovery lists a revocation_endpoint (RFC 7009); logout_marker now lives 30 days (or until the next login), and the refresh, token and user-info routes refuse a session that carries it, so cookies restored by an overtaken refresh are void. The logout now also deletes oidc_provider.

Cookies: token_expires_at holds the real expiry; it and id_token live as long as the session (refresh token lifetime, max 30 days; access token lifetime without a refresh token); without a new ID token on refresh, the session's is set again. refresh_token max-age is capped at 30 days, as the privacy notice says.

Tests: unit tests for every status mapping, the cookie lifetimes, Origin check, revocation, logout marker, and the refresher (timing, backoff, lock, stop during a refresh). The e2e mock gets a refresh failure mode (/mock/refresh: status, error, delay) and token revocation; five new Playwright tests in e2e/session.spec.ts.

Docs: login.md (Sessions and logout, with a table of the answers), helm-chart.md (Pods), upgrading.md, configuration.md (APP_ORIGIN), deployment/values.yaml (replicas), privacy notice (lifetimes, logout_marker).

Not in this PR: docs/operator-guide/deployment.md ("Origin validation" mentions only the logout) is left to the security headers PR, which owns that file.

Verification

  • bun run lint (biome check): clean
  • bunx next typegen && bunx tsc --noEmit: clean
  • npx vitest run --coverage: 346 tests passed (after merging dev), 100 % coverage
  • npx playwright test --project chromium: 24 passed after merging dev (incl. 5 new in e2e/session.spec.ts), with no CSP violations under the fixture from fix: send security response headers #120
  • mkdocs build --strict: clean
  • CI (after the Sourcery fixes and the merge of dev, 74019da): all checks pass, including CI passed, e2e on Chromium, Firefox and the image, chart install, CodeQL, Trivy, Codecov, Read the Docs, Sourcery and Vercel.

Declined review findings

Two review rounds (adversarial + quality); all high/medium findings fixed (relative refresh margin for short-lived tokens, e2e ordering assertion instead of a fixed wait, overtaken-refresh e2e test, shared marker/cookie helpers, unauthorized_client, refresh timeout 60 s, daily check cap, no cookie outliving an ended session). Declined:

  • Unit tests for useTokenRefresh and the sidebar logout handler (quality, medium): the repo has no React component test stack, and coverage is scoped to src/lib and the routes by design. The logic lives in src/lib/token-refresh.ts (unit-tested to 100 %), the hook only wires browser APIs, and the logout path is covered end to end.

  • End the session on 401 only with invalid_grant/invalid_token (adversarial, low): a 401 without an error body still ends the session, as some providers answer bad refresh tokens that way and fix: harden session refresh and logout #111 asks for it; invalid_client and unauthorized_client keep it.

  • Store the session's end time for non-rotating refreshes (adversarial, low): handled more simply: once neither refresh nor access token is left, the refresh route deletes all session cookies.

  • Unit test that a timed-out refresh request returns status 0 (quality, low): the timeout signal is asserted, and a rejected fetch returning status 0 is tested; faking AbortSignal.timeout adds little.

  • Exact count of 503s in the outage e2e test (quality, low): the retry count isn't deterministic; the test checks the first answer was 503 and that the retry renewed the token.

  • Sourcery review: fixed the failed-login marker, the 30-day cap of the access token cookie, rotated refresh tokens in invalid responses, non-object responses, sessions left without an ID token and plain 401s from older pods (6b7aec7). Declined, with reasons in the threads: a late refresh overtaking a new login in another tab (needs a session generation id), marker-unaware old pods during a rolling upgrade (rollout window only), lost responses with rotating providers (needs server state; provider reuse grace covers it), distinguishing a failed provider logout in the UI, the unknown remaining lifetime of a non-rotated refresh token, and an e2e reproduction of the response race (both halves are covered). The deployment.md Origin note is left for a follow-up, as that file was owned by another PR.

Unrelated fixes

  • docs/operator-guide/helm-chart.md: the example cloudRegistryUrl now has the API path (/ga4gh/registry/v1).

Open questions

None.

Closes #111
Closes #106
Refs #93, #107

🤖 Generated with Claude Code

uniqueg and others added 7 commits November 19, 2026 11:03
The refresh route ended a session only on 401, while RFC 6749 5.2
answers an expired, revoked or reused refresh token with 400
invalid_grant, and 401 with invalid_client meant a rotated client
secret wiped every session. It also answered 401 to every failure.

Now 400 invalid_grant and 401 (except invalid_client) end the session
and delete all its cookies (401 session_ended), unless a concurrent
refresh just succeeded (409). Provider, network and settings errors
keep the session (503 unavailable); without a refresh token, only
token_expires_at is deleted (401 no_refresh_token). A refreshed ID
token must name the session's sub and iss (OIDC Core 12.2).

token_expires_at now holds the real expiry and, like id_token, lives
as long as the session; without a new ID token on refresh, the
session's is set again. The refresh_token max-age is capped at 30
days, and the refresh route checks the Origin like the logout.

Refs #111

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The refresh hook sent the tab to /auth/login on any refresh error, so
a short provider outage, or a stale token_expires_at of an anonymous
visitor, led to the login page, and unsaved input was lost. It also
refreshed about 10 minutes early.

The new refresher (src/lib/token-refresh.ts) refreshes 5 minutes
before the real expiry, leaves the page only on session_ended, stops
on no_refresh_token, and retries other failures with backoff (5 s,
doubling, at most 5 min). All tabs of a browser share a Web Lock, so
only one refreshes at a time and the others pick up its cookies.

Refs #111

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A refresh whose response arrived after the logout's set the session
cookies again: its guard read the request's own cookie jar, the token
and user-info routes ignored logout_marker, and the logout didn't
wait for refreshes in flight.

The logout now stops the page's refresher and runs under the refresh
lock, so it waits for a refresh in any tab. It revokes the refresh
token when discovery lists a revocation_endpoint (RFC 7009), and
logout_marker lives 30 days (or until the next login): the refresh,
token and user-info routes refuse a session that carries it, and the
refresh route deletes its cookies again. The logout also deletes
oidc_provider.

Closes #106
Refs #111

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The mock provider answered every refresh token grant with 200, so no
end-to-end test could show how Krini handles refresh failures.
/mock/refresh now sets an error status and error, and a delay, until
/mock/reset; the mock also revokes refresh tokens (/oidc/revoke) and
answers revoked ones with 400 invalid_grant.

New tests: a session that the provider ended leads to the login page
once and leaves no cookies; a provider outage keeps the session and the
refresh is retried; visitors with a stale expiry stay on the page; and
a refresh in flight in another tab doesn't undo the logout.

Refs #111

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Login guide: how Krini handles each answer of the token endpoint to a
refresh, the ID token's lifetime, the tabs' lock, the Origin check of
the refresh, and what the logout does (wait, revoke, logout_marker).

Helm chart guide, upgrade guide and values.yaml: with the lock, several
pods no longer race; only browsers without Web Locks (or tabs of older
images) can still end a session that way, which sends the user to the
login page rather than "logging out".

Privacy notice: the new lifetimes of id_token, token_expires_at and
logout_marker, and what the marker does.

Refs #111

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Refresh short-lived tokens at half their lifetime (at most 5 min
  before expiry): token_expires_at now stores "<expiry>:<lifetime>" in
  ms, so 5-minute tokens no longer refresh every 30 s in every tab.
  Old values without a lifetime still parse.
- Cap the wait between checks at a day (setTimeout overflows at 24.8
  days) and time out a refresh request after 30 s, as the lock is held
  meanwhile and logouts wait for it.
- Treat 401 unauthorized_client like invalid_client: keep the session.
- Without refresh and access token, the refresh route deletes all the
  session's cookies, so no ID token outlives the session.
- One helper for the logout marker (hasLoggedOut, LOGOUT_MARKER) and
  for the cookie options; docstrings in the refresh route.
- e2e: assert that the logout request goes out only after the other
  tab's refresh answered, instead of a fixed wait; a new test restores
  the session's cookies after the logout and checks that they are void;
  forgiveProblems() for server errors a test provokes.

Refs #111

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The client's 30 s timeout equalled the refresh route's worst case
(discovery, token and JWKS requests of 10 s each): the route could
rotate the refresh token after the browser gave up on the answer, and
the next refresh would then end the session. Wait 60 s instead.

Also rewrap two comments and reword a test comment.

Refs #111

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.1.0 milestone Nov 19, 2026
@uniqueg uniqueg self-assigned this Nov 19, 2026
@vercel

vercel Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
krini Ready Ready Preview Nov 19, 2026 11:35am UTC

@sourcery-ai

sourcery-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Define shared session-cookie lifetimes, logout-marker handling, and the OIDC revocation endpoint used by the routes.

  • src/lib/oidc/discovery.ts L16, L68
  • src/lib/oidc/types.d.ts L33-34
  • src/lib/session-cookies.ts L3-17, L23-92, L120-154 (+1 small edits)

API

Harden refresh, logout, token, and user-info endpoints, including origin checks and session invalidation.

  • src/app/auth/api/callback/route.ts L12, L38-47
  • src/app/auth/api/logout/route.ts L9-61, L72-78, L104-113 (+1 small edits)
  • src/app/auth/api/refresh/route.ts L12-77, L137-171, L202-285 (+6 small edits)
  • src/app/auth/api/token/route.ts L3-9
  • src/app/auth/api/user-info/route.ts L9-15

Uses of the API

Wire the shared client refresher into page lifecycle and serialize logout behind any in-flight refresh.

  • src/components/shared/app-sidebar/app-sidebar-footer-menu.tsx L13-17, L59-68, L81
  • src/hooks/use-token-refresh.ts L3-47

Implementation

Implement browser-side expiry scheduling, cross-tab locking, refresh retries, and origin validation helpers used by the routes and client.

  • src/lib/request-origin.ts L1-26
  • src/lib/token-refresh.ts L1-213

UI

Update the privacy page to explain the revised session-cookie and logout-marker lifetimes.

  • src/app/privacy/page.tsx L22-50 (4 small edits)

Configuration

Revise the replica guidance to reflect browser refresh locking and the remaining multi-pod race conditions.

  • deployment/values.yaml L87-92

Documentation

Document refresh and logout behavior, Origin requirements, cookie lifetimes, replica guidance, and the corrected registry URL.

  • docs/operator-guide/configuration.md L90-91
  • docs/operator-guide/helm-chart.md L78, L294-303
  • docs/operator-guide/login.md L133-174
  • docs/operator-guide/upgrading.md L23-30

Tests

Add route and refresher tests for failure handling, cookie semantics, origin checks, locking, revocation, and logout races.

  • e2e/fixtures.ts L8-13, L68-107, L161-172
  • e2e/mock/server.ts L6-9, L16-19, L288-316 (+4 small edits)
  • e2e/session.spec.ts L1-138
  • e2e/settings.ts L36-45, L63
  • src/app/auth/api/callback/route.test.ts L213-227, L325-328 (+3 small edits)
  • src/app/auth/api/logout/route.test.ts L4-16, L32, L54-96
  • src/app/auth/api/refresh/route.test.ts L118-155, L267-338, L412-463 (+24 small edits)
  • src/app/auth/api/token/route.test.ts L26-32
  • src/app/auth/api/user-info/route.test.ts L108-128
  • src/lib/token-refresh.test.ts L1-402

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@read-the-docs-community

read-the-docs-community Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (ececc90) to head (74019da).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #119    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           23        25     +2     
  Lines          591       699   +108     
  Branches       163       196    +33     
==========================================
+ Hits           591       699   +108     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@uniqueg
uniqueg marked this pull request as ready for review November 19, 2026 10:59
@uniqueg
uniqueg requested a review from AnonymousXC as a code owner November 19, 2026 10:59
@sourcery-ai

sourcery-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 74019da

#106 fix: a refresh in flight can undo the logout · 0 of 1 met

# Requirement Status Notes
1 A refresh that finishes after logout doesn't restore the session, with a regression test 🟡 Partly met The logout marker and session checks prevent restored cookies from reviving a session, but the e2e test re-adds old cookies after logout instead of starting a refresh before logout and asserting its delayed response arrives afterward.

#111 fix: harden session refresh and logout · 9 of 9 met

# Requirement Status Notes
1 400 invalid_grant and 401 end the session, except when the replay window applies ✅ Met The refresh route ends the session for 400 invalid_grant and 401 responses other than invalid_client and unauthorized_client, and returns concurrent_refresh when a recent success applies.
2 invalid_client and other provider or network errors keep cookies, are logged, and return 503 ✅ Met Provider, network, discovery, and invalid-response failures return unavailable without clearing session cookies and log the error.
3 Retry transient errors with backoff; redirect only when the session ended; handle no refresh token without redirecting ✅ Met The client retries other failures with backoff, redirects only on session_ended, and stops on no_refresh_token; the route deletes the stale expiry cookie.
4 Store the real access-token expiry in token_expires_at and keep it for the session lifetime ✅ Met The cookie stores expiry and lifetime in milliseconds, and its max-age follows the session.
5 Prevent refresh-after-logout from restoring a session; refuse token and user-info requests after logout; make logout stop and wait for refreshes ✅ Met Logout stops the local refresher and uses the shared lock; the marker invalidates restored session cookies at the refresh, token, and user-info routes.
6 Keep id_token for the session lifetime and reject refreshed tokens with a different sub or iss ✅ Met The refresh route retains the existing ID token when the provider omits one and compares subject and issuer when it supplies a new one.
7 Check Origin on refresh and cap refresh_token max-age at 30 days ✅ Met The route uses rejectForeignOrigin, and refresh-token cookie lifetimes are capped at 30 days.
8 Update login.md, helm-chart.md, upgrading.md, values.yaml, and the privacy notice ✅ Met The listed operator guides, deployment values, and privacy notice are updated.
9 Add unit tests for the refresh cases and an e2e refresh-failure mode with e2e tests ✅ Met The diff adds refresh-route and refresher unit tests, mock failure modes, and Playwright coverage.

@sourcery-ai sourcery-ai 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.

Hey - I've found 14 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/app/auth/api/callback/route.ts" line_range="44" />
<code_context>
 function expireLoginArtifacts(response: NextResponse, state: string) {
     response.cookies.delete(`authState-${state}`);
-    response.cookies.delete("logout_marker");
+    response.cookies.delete(LOGOUT_MARKER);
 }

</code_context>
<issue_to_address>
**Failed login restores logged-out access**

When a refresh restores session cookies after logout and a callback with a valid state then fails, `redirectError` calls `expireLoginArtifacts`, which deletes `LOGOUT_MARKER` without clearing the restored session cookies. The token and user-info routes then accept those cookies, so the user regains access despite having logged out.

Preserve `LOGOUT_MARKER` when cleaning up artifacts for a failed callback.

Also at `src/app/auth/api/logout/route.ts:110`.
</issue_to_address>

### Comment 2
<location path="src/app/auth/api/logout/route.ts" line_range="110" />
<code_context>
+    // may rotate the refresh token.
+    response.cookies.set(LOGOUT_MARKER, Date.now().toString(), {
+        ...baseCookieOptions(),
+        maxAge: THIRTY_DAYS_SECONDS,
     });

</code_context>
<issue_to_address>
**Delayed refresh outlives logout marker**

When a refresh response restores session cookies after the logout response, the restored cookies can remain valid after `LOGOUT_MARKER` expires 30 days after logout: refresh cookies get a fresh 30-day lifetime, and access-token cookies can last longer than 30 days. The token routes then accept the session again, undoing logout.

Make the logout marker last at least as long as any session cookie a delayed refresh can restore.

Also at `src/lib/session-cookies.ts:88-91`, `src/lib/session-cookies.ts:107-135`.
</issue_to_address>

### Comment 3
<location path="src/app/auth/api/refresh/route.ts" line_range="254-260" />
<code_context>
+        // without a new ID token, the session's stays, with the session's
+        // new lifetime
+        {
+            ...response.data,
+            id_token: typeof id_token === "string" ? id_token : idToken,
+        },
+        provider.id,
+        { keepRefreshToken: true },
+    );
+    noteRefreshSuccess(refreshToken);

-        return response;
</code_context>
<issue_to_address>
**Late refresh replaces a newer login**

When a refresh response for an old session arrives after another tab completes a login, `applySessionCookies` can replace the new login’s cookies with the old session’s tokens and provider, while `failure()` can clear the new session’s cookies. The browser ends up in the wrong account or logged out.

Prevent a refresh response from changing cookies after a newer login has established a session.

Also at `src/app/auth/api/callback/route.ts:44`, `src/app/auth/api/refresh/route.ts:59`.
</issue_to_address>

### Comment 4
<location path="src/app/auth/api/token/route.ts" line_range="7-9" />
<code_context>
 export async function GET() {
     const cookieStore = await cookies();
-    const accessToken = cookieStore.get("access_token")?.value;
+    const accessToken = hasLoggedOut(cookieStore)
+        ? undefined
+        : cookieStore.get("access_token")?.value;

     if (!accessToken) {
</code_context>
<issue_to_address>
**Legacy pods accept logged-out cookies**

When old and new pods overlap and a legacy tab’s refresh response sets session cookies after a logout, the marker checks in these handlers only protect requests served by updated pods. If an older pod’s in-flight refresh restores session cookies after logout during a rolling upgrade, its token and user-info handlers ignore the marker and accept those cookies, so requests routed to that pod still see the user as logged in.

Account for marker-unaware pods during rollout, or ensure logout cannot be overtaken by refreshes from legacy clients until those pods have drained.

Also at `src/app/auth/api/user-info/route.ts:13-15`.
</issue_to_address>

### Comment 5
<location path="src/app/auth/api/refresh/route.ts" line_range="137" />
<code_context>
+            provider,
+            null,
+        );
+        if (!payload) {
+            console.error(
+                `OIDC refresh error: category=id_token_validation_failed, endpoint=${endpoints.tokenEndpoint}`,
</code_context>
<issue_to_address>
**Rotation lost on validation failure**

When the provider rotates the refresh token but ID-token validation fails transiently, the provider can rotate and invalidate the submitted refresh token in a successful response, but `validateIdToken` can fail transiently (for example, while JWKS is unavailable). The route returns `unavailable` before `applySessionCookies` stores the rotated token; a retry then sends the invalidated token, gets `invalid_grant`, and ends the session.

Preserve a rotated refresh token from an otherwise successful provider response before returning a retryable validation failure, while continuing to reject the unvalidated ID token and access token.
</issue_to_address>

### Comment 6
<location path="src/app/auth/api/refresh/route.ts" line_range="202-203" />
<code_context>
         );
+    } catch (err) {
+        logTokenError("OIDC refresh error", err, endpoints.tokenEndpoint);
+        if (!refreshTokenRejected(err)) {
+            return failure("unavailable", "Failed to refresh token");
+        }
+        if (refreshSucceededRecently(refreshToken)) {
</code_context>
<issue_to_address>
**Rotated refresh token is lost**

When the provider rotates and invalidates the old refresh token, but its response times out after processing or contains an invalid token response, the route returns `unavailable` without saving the provider's rotated refresh token. The browser retries with the old token, which the provider rejects as `invalid_grant`, so the route ends the session and sends the user to login.

Use provider-supported rotation grace or idempotency for ambiguous refresh outcomes, and handle invalid responses without leaving the browser with only the consumed refresh token.

Also at `src/app/auth/api/refresh/route.ts:213-218`, `src/app/auth/api/refresh/route.ts:231-235`.
</issue_to_address>

### Comment 7
<location path="src/app/auth/api/logout/route.ts" line_range="72" />
<code_context>
     let endSessionUrl: string | null = null;
     if (provider) {
         const endpoints = await getEndpoints(provider);
+        if (endpoints?.revocationEndpoint && refreshToken) {
+            await revokeRefreshToken(
+                endpoints.revocationEndpoint,
</code_context>
<issue_to_address>
**Provider logout failures go unnoticed**

When the provider’s discovery request fails during logout, `getEndpoints` returns null when discovery fails, so the endpoint checks are skipped and logout still returns success without a log. The provider session remains active, and a later login can silently sign the user back in.

Log discovery failure during logout and make the response or UI distinguish local logout from failure to end the provider session.
</issue_to_address>

### Comment 8
<location path="src/app/auth/api/refresh/route.ts" line_range="211" />
<code_context>
+        return failure("session_ended", "Failed to refresh token");
+    }

-        const { access_token, id_token } = response.data;
+    const { access_token, id_token } = response.data;

</code_context>
<issue_to_address>
**Malformed response crashes refresh**

When the token endpoint responds with HTTP 200 and a JSON `null` body, `response.data` is `null`, so destructuring `access_token` throws outside the token-request `try` block; the route returns an unhandled 500 instead of the documented 503 `unavailable`, and the user sees a server error.

Validate that `response.data` is a non-null object before destructuring and return the invalid-response failure otherwise.
</issue_to_address>

### Comment 9
<location path="src/app/auth/api/refresh/route.ts" line_range="255" />
<code_context>
+        // new lifetime
+        {
+            ...response.data,
+            id_token: typeof id_token === "string" ? id_token : idToken,
+        },
+        provider.id,
</code_context>
<issue_to_address>
**Older sessions lose user identity**

When a session created by an older image has outlived its ID-token cookie and the provider omits an ID token on refresh, `idToken` is undefined, so `applySessionCookies` sets no ID-token cookie when the provider omits one. `getUserSession` then cannot match the user-info subject and returns no session, so a refreshed session from an older image no longer identifies its user.

Handle sessions without either an existing or newly issued ID token explicitly, rather than returning a successful refresh that cannot identify the user.
</issue_to_address>

### Comment 10
<location path="src/app/auth/api/refresh/route.ts" line_range="205-260" />
<code_context>
+        if (refreshSucceededRecently(refreshToken)) {
</code_context>
<issue_to_address>
**Lost refresh response ends session**

When a rotating provider accepts the refresh but the response is lost before the browser receives its cookies, the provider rotates the refresh token and Krini records the success, but a lost HTTP response leaves the browser holding the old token. Retried requests receive `concurrent_refresh` without the replacement cookies; after the success window expires, the retry ends the session and redirects the user to login.

Make retries recover the successful result, for example by temporarily retaining and replaying the replacement-cookie result for that refresh token.

Also at `src/lib/token-refresh.ts:178`.
</issue_to_address>

### Comment 11
<location path="src/lib/session-cookies.ts" line_range="107" />
<code_context>
         });
+    } else if (options.keepRefreshToken) {
+        // not rotated: the refresh token's remaining lifetime is unknown
+        sessionMaxAge = THIRTY_DAYS_SECONDS;
+    } else {
+        response.cookies.delete("refresh_token");
</code_context>
<issue_to_address>
**Identity cookie outlives session**

When a provider omits both `refresh_token` and `refresh_expires_in` on refresh, while the existing refresh cookie has a finite remaining lifetime, `applySessionCookies` gives the ID token a 30-day lifetime when a refresh omits a new refresh token, but leaves the existing refresh cookie’s earlier expiry unchanged. After that cookie expires, the session can end while the ID token remains in the browser for up to 30 days.

Preserve the known session end across refreshes, or otherwise ensure the ID token expires no later than the refresh/access session.
</issue_to_address>

### Comment 12
<location path="src/lib/token-refresh.ts" line_range="169-173" />
<code_context>
+            scheduleNext();
+            return;
+        }
+        if (result.status === 401) {
+            // `no_refresh_token`: the server deleted `token_expires_at`,
+            // and the access token, if any, stays until it expires
+            if (result.code === "session_ended") deps.onSessionEnded();
+            return;
+        }
+        // the provider is unavailable, a concurrent refresh won, or no
</code_context>
<issue_to_address>
**Legacy refresh errors stop retries**

When a new client sends a refresh to an old server during a rolling upgrade and that server answers a transient failure with its legacy generic 401, a legacy server returns a generic 401 without a `code` for a transient refresh failure. The client returns without scheduling a retry or leaving the page, so the access token eventually expires and the session stays unusable until another page load or login.

Treat an unrecognized 401 response as transient during compatibility windows, or version the refresh response contract so the client can distinguish legacy failures.
</issue_to_address>

### Comment 13
<location path="e2e/session.spec.ts" line_range="127" />
<code_context>
+
+    // e.g. a browser without Web Locks: a refresh that the logout
+    // overtook sets the session's cookies again
+    await context.addCookies(session);
+    expect((await page.request.get("/auth/api/token")).status()).toBe(401);
+    expect((await page.request.get("/auth/api/user-info")).status()).toBe(401);
</code_context>
<issue_to_address>
**Exercise the response race**

The test restores pre-logout cookies after logout and verifies that the marker makes them unusable. It does not reproduce the requested ordering of a logout response followed by an in-flight refresh response; add a regression test that exercises that ordering.
</issue_to_address>

### Comment 14
<location path="src/lib/request-origin.ts" line_range="19" />
<code_context>
+            { status: 500 },
+        );
+    }
+    if (req.headers.get("origin") !== appOrigin) {
+        return NextResponse.json(
+            { error: "Invalid request origin" },
</code_context>
<issue_to_address>
**Deployment guide omits refresh protection**

Operators reading the Origin validation section see only the logout endpoint described as checking `APP_ORIGIN`, while this check also protects refresh requests; the deployment guide therefore gives an incomplete account of the app's CSRF protections.

Update the deployment guide's Origin validation section to include the refresh endpoint.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 13 findings to address first, and if the refresh or logout checks mishandle a session, someone could retain access or be logged out, and logout may also revoke the provider’s refresh token. Reverting restores the old code but cannot undo access already used or restore a refresh token the provider revoked.

Blocking findings: src/app/auth/api/callback/route.ts:44, src/app/auth/api/logout/route.ts:110, src/app/auth/api/refresh/route.ts:260, src/app/auth/api/token/route.ts:9, src/app/auth/api/refresh/route.ts:137, and 8 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/app/auth/api/callback/route.ts Resolved
Comment thread src/app/auth/api/logout/route.ts Resolved
Comment thread src/app/auth/api/refresh/route.ts Resolved
Comment thread src/app/auth/api/token/route.ts Resolved
Comment thread src/app/auth/api/refresh/route.ts Resolved
Comment thread src/app/auth/api/refresh/route.ts Resolved
Comment thread src/lib/session-cookies.ts Resolved
Comment thread src/lib/token-refresh.ts Resolved
Comment thread e2e/session.spec.ts Resolved
Comment thread src/lib/request-origin.ts Resolved
uniqueg and others added 3 commits November 19, 2026 12:29
Keep the logout marker on failed logins, cap the access token cookie
at 30 days so the marker outlives every session cookie, keep a rotated
refresh token when the rest of the token response is invalid, reject
non-object token responses with 503, end sessions that would be left
without an ID token, and retry plain 401s from pods of older versions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Helm chart example set cloudRegistryUrl to the registry's host;
Krini needs the base URL of the GA4GH Service Registry API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vercel
vercel Bot temporarily deployed to Preview – krini November 19, 2026 11:34 Inactive
@uniqueg
uniqueg merged commit a383678 into dev Nov 19, 2026
78 checks passed
@uniqueg
uniqueg deleted the fix/111-session-refresh branch November 19, 2026 11:54
uniqueg added a commit that referenced this pull request Nov 19, 2026
The security recommendations in the deployment guide named only the
logout endpoint as checked against APP_ORIGIN; since #119, token
refreshes are checked the same way (rejectForeignOrigin).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
uniqueg added a commit that referenced this pull request Nov 19, 2026
Add the fixes of the pre-release review, merged into dev since the
last refresh: security headers and self-hosted editor workers (#112,
#120), session refresh and logout (#106, #111, #119), and the registry
URL example (#113, #114).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch was previously deployed

1 inactive deployment
Preview – krini — 74019da8 Deployed Nov 19, 2026 by vercel[bot]
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: harden session refresh and logout fix: a refresh in flight can undo the logout

1 participant