Skip to content

feat: rotate refresh tokens with replay detection and family revocation - #3186

Merged
tada5hi merged 3 commits into
masterfrom
feat/refresh-token-rotation
Jul 6, 2026
Merged

tada5hi merged 3 commits into
masterfrom
feat/refresh-token-rotation

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

Implements plan 016 — Option B, hard cutover. Every /token refresh_token call rotates, backed by a durable inventory table so replay detection survives cache flushes and can trigger the RFC 6819 §5.2.2.3 reaction strategy (revoke the whole token family).

Scope here is PR A–D (the security feature). PR G (session-management endpoints + client-web account UI) is a follow-up; its foundations (inventory rows, ISessionManager.revoke, findBySessionId) are all in place.

What changed

  • Schema — new auth_session_tokens (one row per issued access/refresh token): id (= jti), session_id FK → auth_sessions ON DELETE CASCADE, kind, consumed_at/revoked_at, informational parent_id/refresh_token_id lineage, ip_address(45)/user_agent(512), expires_at. Also widens auth_sessions.ip_address 15 → 45 (was IPv4-only). MySQL + Postgres migrations.
  • Issuers write a row after signing whenever session_id is present (M2M client/robot-credentials write only an access row — they mint no refresh token).
  • Refresh grant is now DB-row-authoritative: it verifies with skipActiveCheck: true (crypto + exp still enforced) and decides on the row, so family-revocation-on-replay is deterministic regardless of cache state. Flow: reject missing/wrong-kind/revoked → atomic markRefreshConsumed → on failure, grace-window check else revoke the family (soft-revoke every row + cache-blocklist their jtis with real TTL + delete the session) → invalid_grant.
  • /token/revoke soft-revokes the DB row too, so a revoked refresh token can't refresh under skipActiveCheck.
  • Grace period tokenRefreshGracePeriod (seconds, default 0 = strict), scoped to the chain tip so a stolen older token can't fork a parallel session.
  • ISessionManager.revoke(); oauth2-cleaner sweeps expired token rows.
  • Lowers tokenAccessMaxAge default 3600 → 900s to shrink the revocation blind spot for stateless local-JWKS adapters.

Testing

  • Full server-core suite: 104 files / 1054 tests pass; full monorepo build clean (22 projects).
  • New service spec for the rewritten grant (rotation, replay → family-revoke, unknown/revoked/wrong-kind rejection, grace tip vs. stale-ancestor, blocklist-TTL guard) + HTTP replay + explicit-revoke integration tests.
  • Postgres migration validated end-to-end (run → revert → re-run). MySQL is covered by the tests-migrations CI job (mysql2 driver not installed locally).
  • An adversarial multi-lens review of the diff fixed two bugs before this PR: grace scoping to the chain tip, and pinning the family-revoke blocklist TTL to each token's real expiry (a revoked 3-day RT no longer reappears as active in introspection after 1h).

⚠️ Breaking

  • All in-flight refresh tokens are invalidated on upgrade (the new table is empty), so active users sign in again once (RT horizon is 3 days).
  • The default access-token lifetime drops 3600s → 900s (operators can raise it).

Both warrant a release-notes line.

Docs: .agents/architecture.md → Refresh Token Rotation & Replay Detection.

Summary by CodeRabbit

  • New Features

    • Added refresh-token rotation with replay detection and optional grace-window support.
    • Introduced durable session-token tracking for issued, consumed, and revoked tokens.
    • Reduced default access token lifetime to 15 minutes.
  • Bug Fixes

    • Refresh-token replays now invalidate the full session family.
    • Explicit token revocation now applies consistently across stored token records.
  • Documentation

    • Updated configuration and architecture notes to reflect the new token lifecycle behavior.

Implements plan 016 (Option B, hard cutover). Every /token refresh_token
call rotates; a new auth_session_tokens table holds one durable row per
issued token so replay survives cache flushes and can trigger the RFC 6819
reaction strategy (revoke the whole token family).

- schema: auth_session_tokens (session_id FK ON DELETE CASCADE, kind,
  consumed_at/revoked_at, lineage), widen auth_sessions.ip_address 15 -> 45,
  mysql + postgres migrations
- issuers write a row per access/refresh token when session_id is present
- refresh grant is DB-row-authoritative (skipActiveCheck): atomic consume,
  replay -> soft-revoke family + blocklist jtis + delete session ->
  invalid_grant; /token/revoke soft-revokes the row too
- tokenRefreshGracePeriod (default 0 = strict) scoped to the chain tip
- ISessionManager.revoke(); oauth2-cleaner sweeps expired token rows
- lower tokenAccessMaxAge default 3600 -> 900

BREAKING CHANGE: all in-flight refresh tokens are invalidated on upgrade
(the new table is empty), so active users sign in again once. The default
access-token lifetime drops from 3600s to 900s.
Copilot AI review requested due to automatic review settings July 6, 2026 09:29
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR introduces durable persistence for refresh-token rotation and replay detection via a new auth_session_tokens table (SessionTokenEntity), backed by SessionTokenRepositoryAdapter implementing ISessionTokenRepository. The refresh grant now verifies tokens with skipActiveCheck: true, atomically consumes the refresh-token row, issues chained refresh/access tokens, and revokes the whole session family on replay, with an optional configurable grace window (tokenRefreshGracePeriod, default 0). Token issuers and revoker persist/soft-revoke session-token rows, SessionManager gains a revoke method, the OAuth2 cleaner deletes expired session-token rows, tokenAccessMaxAge default is lowered to 900s, and DI wiring, migrations, docs, and tests are updated accordingly.

Changes

Refresh Token Rotation & Replay Detection

Layer / File(s) Summary
Architecture & testing docs
.agents/architecture.md, .agents/testing.md
Documents rotation/replay design, auth_session_tokens model, family revoke, grace period, cleanup, and updates the fake-helper list in the testing guide.
Session-token data contracts
packages/core-kit/src/domains/session-token/*, packages/core-kit/src/domains/index.ts, apps/server-core/src/core/oauth2/session-token/*, apps/server-core/src/core/oauth2/index.ts, packages/specs/src/oauth2/types.ts
Adds SessionTokenKind/SessionToken types, ISessionTokenRepository interface, and parent_id/refresh_token_id fields on OAuth2TokenPayload.
Entity and migrations
apps/server-core/src/adapters/database/domains/session-token/*, .../session/entity.ts, .../data-source/options/module.ts, .../domains/index.ts, .../migrations/{mysql,postgres}/1783325495597-Default.ts
Adds SessionTokenEntity, widens auth_sessions.ip_address to 45 chars, and migrates auth_session_tokens table with indexes/FK for MySQL and Postgres.
Repository adapter, DI wiring, cleanup
apps/server-core/src/app/modules/oauth2/repositories/session-token/*, .../oauth2/constants.ts, .../oauth2/module.ts, .../oauth2/repositories/index.ts, .../components/oauth2-cleaner/module.ts
Implements SessionTokenRepositoryAdapter (create/lookup/consume/revoke/cleanup), registers it in DI, injects it into revoker/issuers, and extends cleaner to sweep expired session tokens.
Issuer & revoker persistence
apps/server-core/src/core/oauth2/token/issuer/{access,refresh}/module.ts, .../issuer/session-token.ts, .../token/revoker/module.ts
Adds persistSessionTokenRow helper used by access/refresh issuers to write inventory rows; revoker soft-revokes the durable row alongside cache blocklisting.
Refresh grant rotation/replay logic
apps/server-core/src/core/oauth2/grant-types/{refresh-token,types}.ts, .../authentication/session/{module,types}.ts, .../adapters/http/adapters/oauth2/grant-types/refresh_token.ts
Rewrites OAuth2RefreshTokenGrant.runWith for skip-active-check verification, atomic consume, chained issuance, grace-window logic, and family revoke; adds SessionManager.revoke.
Controller wiring & config
apps/server-core/src/adapters/http/controllers/workflows/token/{module,types}.ts, .../app/modules/config/{constants,normalize,read/env,types,validator}.ts, .../app/modules/http/modules/controller.ts, docs/src/guide/deployment/configuration-server-core.md
Wires tokenRepository/sessionTokenRepository/logger into TokenController, adds tokenRefreshGracePeriod config option, and lowers tokenAccessMaxAge default to 900s.
Fakes and unit tests
apps/server-core/test/unit/core/helpers/*, .../core/oauth2/grant-types/refresh-token.spec.ts, .../http/controllers/workflows/token/grant-refresh-token.spec.ts
Adds FakeOAuth2TokenVerifier, FakeSessionTokenRepository, FakeSessionManager.revoke, and tests covering rotation, replay/family revocation, grace window, and revoke endpoint behavior.

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HTTPOAuth2RefreshTokenGrant
  participant OAuth2RefreshTokenGrant
  participant SessionTokenRepositoryAdapter
  participant SessionManager
  Client->>HTTPOAuth2RefreshTokenGrant: submit refresh token
  HTTPOAuth2RefreshTokenGrant->>OAuth2RefreshTokenGrant: runWith(payload, skipActiveCheck)
  OAuth2RefreshTokenGrant->>SessionTokenRepositoryAdapter: markRefreshConsumed(jti)
  alt consume succeeds
    OAuth2RefreshTokenGrant->>OAuth2RefreshTokenGrant: issue chained refresh+access tokens
    OAuth2RefreshTokenGrant->>SessionTokenRepositoryAdapter: persist new refresh/access rows
  else consume fails, within grace window
    OAuth2RefreshTokenGrant->>OAuth2RefreshTokenGrant: allow reuse for chain tip
  else consume fails, no grace
    OAuth2RefreshTokenGrant->>SessionTokenRepositoryAdapter: revokeBySessionId(session_id)
    OAuth2RefreshTokenGrant->>SessionManager: revoke(session_id)
  end
Loading

Possibly related PRs

  • authup/authup#3020: Both PRs modify the OAuth2 refresh-token grant handler (refresh_token.ts), combining verification-semantics changes with client authentication/binding logic in the same class.
  • authup/authup#3013: Both PRs modify OAuth2AccessTokenIssuer/its issue flow, adding different constructor dependencies and issuance side effects.
  • authup/authup#2922: Both PRs modify the OAuth2 access/refresh token issuer issue() flows in the same files, with different claim/token-lifecycle changes.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the primary change: refresh token rotation with replay detection and family revocation.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/refresh-token-rotation

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.

@pkg-pr-new

pkg-pr-new Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

authup

npm i https://pkg.pr.new/authup@3186

@authup/client-web

npm i https://pkg.pr.new/@authup/client-web@3186

@authup/server-core

npm i https://pkg.pr.new/@authup/server-core@3186

@authup/access

npm i https://pkg.pr.new/@authup/access@3186

@authup/client-web-kit

npm i https://pkg.pr.new/@authup/client-web-kit@3186

@authup/client-web-kit-theme

npm i https://pkg.pr.new/@authup/client-web-kit-theme@3186

@authup/client-web-nuxt

npm i https://pkg.pr.new/@authup/client-web-nuxt@3186

@authup/client-web-theme

npm i https://pkg.pr.new/@authup/client-web-theme@3186

@authup/core-http-kit

npm i https://pkg.pr.new/@authup/core-http-kit@3186

@authup/core-kit

npm i https://pkg.pr.new/@authup/core-kit@3186

@authup/core-realtime-kit

npm i https://pkg.pr.new/@authup/core-realtime-kit@3186

@authup/errors

npm i https://pkg.pr.new/@authup/errors@3186

@authup/i18n

npm i https://pkg.pr.new/@authup/i18n@3186

@authup/kit

npm i https://pkg.pr.new/@authup/kit@3186

@authup/server-adapter-kit

npm i https://pkg.pr.new/@authup/server-adapter-kit@3186

@authup/server-adapter-node

npm i https://pkg.pr.new/@authup/server-adapter-node@3186

@authup/server-adapter-socket-io

npm i https://pkg.pr.new/@authup/server-adapter-socket-io@3186

@authup/server-adapter-web

npm i https://pkg.pr.new/@authup/server-adapter-web@3186

@authup/server-kit

npm i https://pkg.pr.new/@authup/server-kit@3186

@authup/server-test-kit

npm i https://pkg.pr.new/@authup/server-test-kit@3186

@authup/specs

npm i https://pkg.pr.new/@authup/specs@3186

commit: 8365046

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

Pull request overview

Implements refresh token rotation with durable replay detection (plan 016, Option B hard cutover) by introducing a per-token inventory table (auth_session_tokens) and reworking the refresh-token grant to be DB-row-authoritative (supporting deterministic family revocation even after cache flushes). This also adds an optional grace period for benign concurrent refresh races and reduces the default access-token lifetime to 900s.

Changes:

  • Add auth_session_tokens inventory (schema + entity + repository port/adapter) and persist rows on token issuance.
  • Rewrite refresh-token grant: always rotate, atomically consume refresh rows, detect replay, optionally grace the chain tip, and revoke the full session token family on replay.
  • Wire config/env/docs + cleaner + tests for replay detection, explicit revoke, and grace-window behavior.

Reviewed changes

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

Show a summary per file
File Description
packages/specs/src/oauth2/types.ts Adds parent_id / refresh_token_id JWT claim fields for token lineage metadata.
packages/core-kit/src/domains/session-token/index.ts Exposes the new session-token domain type exports.
packages/core-kit/src/domains/session-token/entity.ts Introduces SessionToken / SessionTokenKind domain types for durable token inventory.
packages/core-kit/src/domains/index.ts Re-exports session-token domain from core-kit.
docs/src/guide/deployment/configuration-server-core.md Documents new defaults (tokenAccessMaxAge=900) and tokenRefreshGracePeriod.
apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts Adds HTTP-level tests for replay→family-revoke and explicit revoke behavior.
apps/server-core/test/unit/core/oauth2/grant-types/refresh-token.spec.ts Adds unit tests covering rotation, replay detection, grace window, and edge cases.
apps/server-core/test/unit/core/helpers/index.ts Re-exports new fake verifier + session-token repository for tests.
apps/server-core/test/unit/core/helpers/fake-session-token-repository.ts Adds in-memory ISessionTokenRepository fake with call recording.
apps/server-core/test/unit/core/helpers/fake-session-manager.ts Adds revoke() to the fake session manager for family-revocation tests.
apps/server-core/test/unit/core/helpers/fake-oauth2-token-verifier.ts Adds verifier fake supporting skipActiveCheck semantics.
apps/server-core/src/core/oauth2/token/revoker/module.ts Extends token revoker to soft-revoke the durable session-token row on /token/revoke.
apps/server-core/src/core/oauth2/token/issuer/session-token.ts Adds helper to persist auth_session_tokens rows after signing.
apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts Wires session-token persistence into refresh token issuance.
apps/server-core/src/core/oauth2/token/issuer/access/module.ts Wires session-token persistence into access token issuance (link to refresh token).
apps/server-core/src/core/oauth2/session-token/types.ts Defines ISessionTokenRepository port + inputs/refs for rotation/revocation flows.
apps/server-core/src/core/oauth2/session-token/index.ts Exposes the session-token port types from core oauth2.
apps/server-core/src/core/oauth2/index.ts Re-exports oauth2 session-token module.
apps/server-core/src/core/oauth2/grant-types/types.ts Updates refresh-grant context (token repo + session-token repo + logger + options).
apps/server-core/src/core/oauth2/grant-types/refresh-token.ts Implements DB-row-authoritative rotation, grace logic, and family revocation.
apps/server-core/src/core/authentication/session/types.ts Adds ISessionManager.revoke() to support family/session revocation.
apps/server-core/src/core/authentication/session/module.ts Implements session revoke by deleting the session row.
apps/server-core/src/components/oauth2-cleaner/module.ts Sweeps expired session-token rows prior to session cleanup.
apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts TypeORM adapter implementing ISessionTokenRepository.
apps/server-core/src/app/modules/oauth2/repositories/session-token/index.ts Exposes the session-token repository adapter.
apps/server-core/src/app/modules/oauth2/repositories/index.ts Re-exports the new session-token repository adapter.
apps/server-core/src/app/modules/oauth2/module.ts Registers session-token repository + wires it into issuers and revoker.
apps/server-core/src/app/modules/oauth2/constants.ts Adds DI token for ISessionTokenRepository.
apps/server-core/src/app/modules/http/modules/controller.ts Wires config + logger + repos into token workflow controller context.
apps/server-core/src/app/modules/config/validator.ts Validates tokenRefreshGracePeriod as a non-negative number.
apps/server-core/src/app/modules/config/types.ts Adds tokenRefreshGracePeriod to the config type and docs.
apps/server-core/src/app/modules/config/read/env.ts Adds env var reader for TOKEN_REFRESH_GRACE_PERIOD.
apps/server-core/src/app/modules/config/normalize.ts Sets defaults: tokenAccessMaxAge=900, tokenRefreshGracePeriod=0.
apps/server-core/src/app/modules/config/constants.ts Defines TOKEN_REFRESH_GRACE_PERIOD env var name.
apps/server-core/src/adapters/http/controllers/workflows/token/types.ts Extends token controller context with repos + logger + grace config.
apps/server-core/src/adapters/http/controllers/workflows/token/module.ts Passes session-token repo + token repo + grace options into refresh grant.
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.ts Verifies refresh token with skipActiveCheck: true to allow DB-driven replay reaction.
apps/server-core/src/adapters/database/migrations/postgres/1783325495597-Default.ts Postgres migration: widen session IP + create auth_session_tokens.
apps/server-core/src/adapters/database/migrations/mysql/1783325495597-Default.ts MySQL migration: widen session IP + create auth_session_tokens.
apps/server-core/src/adapters/database/domains/session/entity.ts Widens auth_sessions.ip_address column length (15→45).
apps/server-core/src/adapters/database/domains/session-token/index.ts Exposes the session-token entity from DB domains.
apps/server-core/src/adapters/database/domains/session-token/entity.ts Adds TypeORM SessionTokenEntity mapping for auth_session_tokens.
apps/server-core/src/adapters/database/domains/index.ts Re-exports session-token DB domain.
apps/server-core/src/adapters/database/data-source/options/module.ts Registers SessionTokenEntity with the datasource options.
.agents/testing.md Updates testing guide to include new fakes for refresh-rotation grant tests.
.agents/architecture.md Documents refresh rotation design, DB-authoritative validation, grace window, and cleanup.

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


@Entity({ name: 'auth_session_tokens' })
export class SessionTokenEntity implements SessionToken {
@PrimaryColumn({ type: 'uuid' })

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.

TypeORM's MySQL driver does support type: 'uuid' — it's listed in MysqlDriver.supportedDataTypes, and when the server has no native uuid type (standard MySQL, and MariaDB < 10.7) it maps uuid → varchar(36), which is exactly what the MySQL migration declares. On Postgres it maps to uuid, matching that migration. So synchronize() (used by the CI test suite) and the hand-written migrations produce the same per-dialect types — no MySQL incompatibility and no schema divergence. Same applies to session_id, parent_id, and refresh_token_id. Keeping type: 'uuid' is also what lets the session_id FK match auth_sessions.id (a @PrimaryGeneratedColumn('uuid'), i.e. uuid on Postgres) — a varchar(36) column would mismatch it there. Leaving as-is.

Comment on lines +27 to +28
@Column({ type: 'uuid' })
session_id: Session['id'];
Comment on lines +43 to +47
@Column({
type: 'uuid',
nullable: true,
default: null,
})
Comment on lines +50 to +54
@Column({
type: 'uuid',
nullable: true,
default: null,
})

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/server-core/src/core/oauth2/grant-types/refresh-token.ts (1)

74-123: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Refresh token can be burned without a replacement on downstream failure.

markRefreshConsumed (Line 77) flips the row to consumed before the session is validated (Lines 94-99) or the new tokens are issued (Lines 109-123). If sessionManager.verify/refresh or either issuer's issue() throws afterward (transient DB/cache error, expired session, etc.), the single-use refresh token is already consumed in the DB but the client receives no new pair — forcing an unnecessary full re-authentication. There's no transactional/compensating-action wrapper around this sequence.

At minimum, move session lookup/verification before the consume call to eliminate the "expired session burns a good token" case; full protection against issuer failures would need a DB transaction spanning the consume + persisted session-token row, or a compensating "un-consume" on failure.

♻️ Partial mitigation: validate session before consuming
-        const now = new Date();
-        const nowISO = now.toISOString();
-
-        const consumed = await this.sessionTokenRepository.markRefreshConsumed(payload.jti, nowISO);
-        if (!consumed) {
-            ...
-        }
-
-        await this.tokenRepository.setInactive(payload.jti, payload.exp);
-
-        const session = await this.sessionManager.findOneById(payload.session_id);
-        if (!session) {
-            throw JWTError.payloadPropertyInvalid('session_id');
-        }
-
-        await this.sessionManager.verify(session);
+        const session = await this.sessionManager.findOneById(payload.session_id);
+        if (!session) {
+            throw JWTError.payloadPropertyInvalid('session_id');
+        }
+        await this.sessionManager.verify(session);
+
+        const now = new Date();
+        const nowISO = now.toISOString();
+
+        const consumed = await this.sessionTokenRepository.markRefreshConsumed(payload.jti, nowISO);
+        if (!consumed) {
+            ...
+        }
+
+        await this.tokenRepository.setInactive(payload.jti, payload.exp);
🤖 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 `@apps/server-core/src/core/oauth2/grant-types/refresh-token.ts` around lines
74 - 123, The refresh-token rotation flow in refresh-token.ts consumes the token
before validating the session and issuing replacements, so downstream failures
can burn a valid token without returning a new pair. Move the session lookup and
sessionManager.verify/refresh checks ahead of markRefreshConsumed in the
refresh-token grant path, and ensure refreshTokenIssuer.issue and
accessTokenIssuer.issue are covered by a transactional or compensating rollback
strategy so a failed rotation does not leave the token consumed.
apps/server-core/src/core/oauth2/token/revoker/module.ts (1)

27-39: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Revoke ordering can leave the authoritative DB row un-revoked.

repository.removeById (cache) runs before sessionTokenRepository.revokeById (durable, DB-authoritative row). If the DB call fails after the cache call succeeds, the token is cleared from the cache but its auth_session_tokens row stays active — and since the refresh grant trusts the DB row, not the cache, the "revoked" refresh token remains fully usable. Revoking the authoritative row first (so a failure there aborts before the cache side-effect) closes this gap.

🔒 Proposed reorder
     async revoke(input: OAuth2TokenPayload) : Promise<void> {
         if (!input.jti) {
             throw JWTError.payloadPropertyInvalid('jti');
         }

-        await this.repository.removeById(input.jti);
-
         // Soft-revoke the durable row so a refresh grant (which trusts the row,
         // not the cache blocklist) rejects an explicitly revoked refresh token.
         if (this.sessionTokenRepository) {
             await this.sessionTokenRepository.revokeById(input.jti, new Date().toISOString());
         }
+
+        await this.repository.removeById(input.jti);
     }
🤖 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 `@apps/server-core/src/core/oauth2/token/revoker/module.ts` around lines 27 -
39, The revoke flow in OAuth2TokenRevokerModule.revoke currently removes the
cache entry before updating the durable session row, which can leave the
authoritative token record active if the DB update fails. Reorder the operations
so sessionTokenRepository.revokeById runs before repository.removeById, and keep
the jti validation and existing revokeById semantics intact so a failure in the
DB path aborts before any cache-side effect.
🧹 Nitpick comments (3)
apps/server-core/src/adapters/database/migrations/mysql/1783325495597-Default.ts (1)

28-46: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Missing index on parent_id used by replay/grace-window lookups.

hasConsumedChild(parentId) (in repository.ts) filters on parent_id with no supporting index — only session_id, kind, and expires_at are indexed here. As auth_session_tokens grows, this becomes a full-table scan on the replay-detection path.

⚡ Proposed index addition
                 INDEX \`IDX_auth_session_tokens_session_id\` (\`session_id\`),
                 INDEX \`IDX_auth_session_tokens_kind\` (\`kind\`),
                 INDEX \`IDX_auth_session_tokens_expires_at\` (\`expires_at\`),
+                INDEX \`IDX_auth_session_tokens_parent_id\` (\`parent_id\`),
                 PRIMARY KEY (\`id\`)

And add the corresponding DROP INDEX in down().

🤖 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
`@apps/server-core/src/adapters/database/migrations/mysql/1783325495597-Default.ts`
around lines 28 - 46, Add a supporting index on auth_session_tokens.parent_id in
the MySQL migration so hasConsumedChild(parentId) in repository.ts can use an
indexed lookup instead of scanning the table. Update the create-table SQL in the
migration to include an index for parent_id alongside the existing session_id,
kind, and expires_at indexes, and add the matching DROP INDEX in down() to keep
the migration reversible.
apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts (2)

83-103: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

revokeBySessionId select doesn't match its own "affected rows" contract.

The interface docstring (ISessionTokenRepository.revokeBySessionId) states it "returns the affected rows' jti + expiry," but the find() here has no revoked_at IS NULL filter, so already-revoked/expired rows are also returned (and re-blocklisted by the caller). Functionally harmless (blocklisting a revoked token again is a no-op), but the naming/behavior mismatch could mislead future maintainers.

🤖 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
`@apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts`
around lines 83 - 103, `revokeBySessionId` is returning rows that were never
actually affected by the update because the initial `find()` in
`SessionTokenRepository.revokeBySessionId` does not match the `revoked_at IS
NULL` condition used by the update. Update the query in `revokeBySessionId` so
the returned `SessionTokenRef[]` only includes tokens eligible for revocation,
matching the contract described by `ISessionTokenRepository.revokeBySessionId`
and keeping the returned affected rows consistent with the actual update.

65-72: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider scoping hasConsumedChild to kind = 'refresh'.

The query filters only on parent_id and consumed_at IS NOT NULL. This currently works because only refresh rows ever get consumed_at set, but adding an explicit kind = 'refresh' predicate would make the invariant self-documenting and resilient to future changes (e.g., if access-token rows ever gain a "consumed" concept).

🤖 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
`@apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts`
around lines 65 - 72, The hasConsumedChild query should be scoped explicitly to
refresh tokens so the invariant is clear and future-proof. Update the
SessionTokenRepository method hasConsumedChild to add a kind = 'refresh'
predicate alongside the existing parent_id and consumed_at checks, keeping the
same createQueryBuilder flow and getCount logic. Ensure the change is applied in
the repository method named hasConsumedChild so only consumed refresh children
are counted.
🤖 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
`@apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts`:
- Around line 25-42: The SessionTokenRepository.create method returns an entity
whose created_at can be stale because this.repository.insert(entity) does not
hydrate generated columns back onto the in-memory object. Update the create flow
in SessionTokenRepository.create so callers receive the persisted timestamp,
either by reloading the entity after insert or by switching to repository.save()
if that fits the existing persistence behavior.

In `@apps/server-core/src/core/oauth2/grant-types/refresh-token.ts`:
- Around line 166-184: The revokeFamily method in refresh-token.ts should not
let a single tokenRepository.setInactive failure abort the rest of the family
revocation. Update the loop to handle per-row cache errors independently so
remaining rows still get blocklisted, then always proceed to
sessionManager.revoke(sessionId); use the revokeFamily,
tokenRepository.setInactive, and sessionManager.revoke symbols to locate the fix
and keep the family-wide revocation flow resilient to cache blips.

---

Outside diff comments:
In `@apps/server-core/src/core/oauth2/grant-types/refresh-token.ts`:
- Around line 74-123: The refresh-token rotation flow in refresh-token.ts
consumes the token before validating the session and issuing replacements, so
downstream failures can burn a valid token without returning a new pair. Move
the session lookup and sessionManager.verify/refresh checks ahead of
markRefreshConsumed in the refresh-token grant path, and ensure
refreshTokenIssuer.issue and accessTokenIssuer.issue are covered by a
transactional or compensating rollback strategy so a failed rotation does not
leave the token consumed.

In `@apps/server-core/src/core/oauth2/token/revoker/module.ts`:
- Around line 27-39: The revoke flow in OAuth2TokenRevokerModule.revoke
currently removes the cache entry before updating the durable session row, which
can leave the authoritative token record active if the DB update fails. Reorder
the operations so sessionTokenRepository.revokeById runs before
repository.removeById, and keep the jti validation and existing revokeById
semantics intact so a failure in the DB path aborts before any cache-side
effect.

---

Nitpick comments:
In
`@apps/server-core/src/adapters/database/migrations/mysql/1783325495597-Default.ts`:
- Around line 28-46: Add a supporting index on auth_session_tokens.parent_id in
the MySQL migration so hasConsumedChild(parentId) in repository.ts can use an
indexed lookup instead of scanning the table. Update the create-table SQL in the
migration to include an index for parent_id alongside the existing session_id,
kind, and expires_at indexes, and add the matching DROP INDEX in down() to keep
the migration reversible.

In
`@apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts`:
- Around line 83-103: `revokeBySessionId` is returning rows that were never
actually affected by the update because the initial `find()` in
`SessionTokenRepository.revokeBySessionId` does not match the `revoked_at IS
NULL` condition used by the update. Update the query in `revokeBySessionId` so
the returned `SessionTokenRef[]` only includes tokens eligible for revocation,
matching the contract described by `ISessionTokenRepository.revokeBySessionId`
and keeping the returned affected rows consistent with the actual update.
- Around line 65-72: The hasConsumedChild query should be scoped explicitly to
refresh tokens so the invariant is clear and future-proof. Update the
SessionTokenRepository method hasConsumedChild to add a kind = 'refresh'
predicate alongside the existing parent_id and consumed_at checks, keeping the
same createQueryBuilder flow and getCount logic. Ensure the change is applied in
the repository method named hasConsumedChild so only consumed refresh children
are counted.
🪄 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

Run ID: ef920625-40b7-4283-ad8b-ed4838b6f7c5

📥 Commits

Reviewing files that changed from the base of the PR and between b26a429 and 8298c16.

📒 Files selected for processing (46)
  • .agents/architecture.md
  • .agents/testing.md
  • apps/server-core/src/adapters/database/data-source/options/module.ts
  • apps/server-core/src/adapters/database/domains/index.ts
  • apps/server-core/src/adapters/database/domains/session-token/entity.ts
  • apps/server-core/src/adapters/database/domains/session-token/index.ts
  • apps/server-core/src/adapters/database/domains/session/entity.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1783325495597-Default.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1783325495597-Default.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/app/modules/config/constants.ts
  • apps/server-core/src/app/modules/config/normalize.ts
  • apps/server-core/src/app/modules/config/read/env.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/config/validator.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/oauth2/constants.ts
  • apps/server-core/src/app/modules/oauth2/module.ts
  • apps/server-core/src/app/modules/oauth2/repositories/index.ts
  • apps/server-core/src/app/modules/oauth2/repositories/session-token/index.ts
  • apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts
  • apps/server-core/src/components/oauth2-cleaner/module.ts
  • apps/server-core/src/core/authentication/session/module.ts
  • apps/server-core/src/core/authentication/session/types.ts
  • apps/server-core/src/core/oauth2/grant-types/refresh-token.ts
  • apps/server-core/src/core/oauth2/grant-types/types.ts
  • apps/server-core/src/core/oauth2/index.ts
  • apps/server-core/src/core/oauth2/session-token/index.ts
  • apps/server-core/src/core/oauth2/session-token/types.ts
  • apps/server-core/src/core/oauth2/token/issuer/access/module.ts
  • apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts
  • apps/server-core/src/core/oauth2/token/issuer/session-token.ts
  • apps/server-core/src/core/oauth2/token/revoker/module.ts
  • apps/server-core/test/unit/core/helpers/fake-oauth2-token-verifier.ts
  • apps/server-core/test/unit/core/helpers/fake-session-manager.ts
  • apps/server-core/test/unit/core/helpers/fake-session-token-repository.ts
  • apps/server-core/test/unit/core/helpers/index.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/refresh-token.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts
  • docs/src/guide/deployment/configuration-server-core.md
  • packages/core-kit/src/domains/index.ts
  • packages/core-kit/src/domains/session-token/entity.ts
  • packages/core-kit/src/domains/session-token/index.ts
  • packages/specs/src/oauth2/types.ts

@tada5hi

tada5hi commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews paused.

tada5hi added 2 commits July 6, 2026 13:37
- revokeFamily: settle blocklist writes (Promise.allSettled) so a cache
  failure can't skip the load-bearing session delete
- refresh grant: reject invalid_grant when the token's session_id does not
  match the inventory row's (corruption / jti-reuse defense)
- session-token repository: stamp created_at on the returned entity
  (insert() does not hydrate @CreateDateColumn)
Drop the shared persistSessionTokenRow helper (two callers, awkward
options bag) and inline the guarded create() into each issuer's issue().
No behavior change.
@tada5hi
tada5hi merged commit 8595c35 into master Jul 6, 2026
14 checks passed
@tada5hi
tada5hi deleted the feat/refresh-token-rotation branch July 6, 2026 13:13
@github-actions github-actions Bot mentioned this pull request Jul 6, 2026
tada5hi added a commit that referenced this pull request Jul 6, 2026
Integrate the merged rotation feature (#3186, squash) + SSR internal-http-client
(#3188) from master. Conflict resolutions:
- issuers / refresh grant / session-token repository / grant spec: take master's
  version (inlined row-write + review-fix hardening), dropping the now-removed
  persistSessionTokenRow helper
- architecture.md: keep master's issuer-row wording + this branch's Session
  Management API section
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