Repository navigation
feat: rotate refresh tokens with replay detection and family revocation - #3186
Conversation
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.
|
Note Reviews pausedUse the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR introduces durable persistence for refresh-token rotation and replay detection via a new ChangesRefresh Token Rotation & Replay Detection
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
authup
@authup/client-web
@authup/server-core
@authup/access
@authup/client-web-kit
@authup/client-web-kit-theme
@authup/client-web-nuxt
@authup/client-web-theme
@authup/core-http-kit
@authup/core-kit
@authup/core-realtime-kit
@authup/errors
@authup/i18n
@authup/kit
@authup/server-adapter-kit
@authup/server-adapter-node
@authup/server-adapter-socket-io
@authup/server-adapter-web
@authup/server-kit
@authup/server-test-kit
@authup/specs
commit: |
There was a problem hiding this comment.
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_tokensinventory (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' }) |
There was a problem hiding this comment.
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.
| @Column({ type: 'uuid' }) | ||
| session_id: Session['id']; |
| @Column({ | ||
| type: 'uuid', | ||
| nullable: true, | ||
| default: null, | ||
| }) |
| @Column({ | ||
| type: 'uuid', | ||
| nullable: true, | ||
| default: null, | ||
| }) |
There was a problem hiding this comment.
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 liftRefresh 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). IfsessionManager.verify/refreshor either issuer'sissue()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 winRevoke ordering can leave the authoritative DB row un-revoked.
repository.removeById(cache) runs beforesessionTokenRepository.revokeById(durable, DB-authoritative row). If the DB call fails after the cache call succeeds, the token is cleared from the cache but itsauth_session_tokensrow 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 winMissing index on
parent_idused by replay/grace-window lookups.
hasConsumedChild(parentId)(inrepository.ts) filters onparent_idwith no supporting index — onlysession_id,kind, andexpires_atare indexed here. Asauth_session_tokensgrows, 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 INDEXindown().🤖 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
revokeBySessionIdselect doesn't match its own "affected rows" contract.The interface docstring (
ISessionTokenRepository.revokeBySessionId) states it "returns the affected rows' jti + expiry," but thefind()here has norevoked_at IS NULLfilter, 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 valueConsider scoping
hasConsumedChildtokind = 'refresh'.The query filters only on
parent_idandconsumed_at IS NOT NULL. This currently works because only refresh rows ever getconsumed_atset, but adding an explicitkind = '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
📒 Files selected for processing (46)
.agents/architecture.md.agents/testing.mdapps/server-core/src/adapters/database/data-source/options/module.tsapps/server-core/src/adapters/database/domains/index.tsapps/server-core/src/adapters/database/domains/session-token/entity.tsapps/server-core/src/adapters/database/domains/session-token/index.tsapps/server-core/src/adapters/database/domains/session/entity.tsapps/server-core/src/adapters/database/migrations/mysql/1783325495597-Default.tsapps/server-core/src/adapters/database/migrations/postgres/1783325495597-Default.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/types.tsapps/server-core/src/app/modules/config/constants.tsapps/server-core/src/app/modules/config/normalize.tsapps/server-core/src/app/modules/config/read/env.tsapps/server-core/src/app/modules/config/types.tsapps/server-core/src/app/modules/config/validator.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/oauth2/constants.tsapps/server-core/src/app/modules/oauth2/module.tsapps/server-core/src/app/modules/oauth2/repositories/index.tsapps/server-core/src/app/modules/oauth2/repositories/session-token/index.tsapps/server-core/src/app/modules/oauth2/repositories/session-token/repository.tsapps/server-core/src/components/oauth2-cleaner/module.tsapps/server-core/src/core/authentication/session/module.tsapps/server-core/src/core/authentication/session/types.tsapps/server-core/src/core/oauth2/grant-types/refresh-token.tsapps/server-core/src/core/oauth2/grant-types/types.tsapps/server-core/src/core/oauth2/index.tsapps/server-core/src/core/oauth2/session-token/index.tsapps/server-core/src/core/oauth2/session-token/types.tsapps/server-core/src/core/oauth2/token/issuer/access/module.tsapps/server-core/src/core/oauth2/token/issuer/refresh/module.tsapps/server-core/src/core/oauth2/token/issuer/session-token.tsapps/server-core/src/core/oauth2/token/revoker/module.tsapps/server-core/test/unit/core/helpers/fake-oauth2-token-verifier.tsapps/server-core/test/unit/core/helpers/fake-session-manager.tsapps/server-core/test/unit/core/helpers/fake-session-token-repository.tsapps/server-core/test/unit/core/helpers/index.tsapps/server-core/test/unit/core/oauth2/grant-types/refresh-token.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.tsdocs/src/guide/deployment/configuration-server-core.mdpackages/core-kit/src/domains/index.tspackages/core-kit/src/domains/session-token/entity.tspackages/core-kit/src/domains/session-token/index.tspackages/specs/src/oauth2/types.ts
|
@coderabbitai pause |
✅ Action performedReviews paused. |
- 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.
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
Implements plan 016 — Option B, hard cutover. Every
/tokenrefresh_tokencall 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
auth_session_tokens(one row per issued access/refresh token):id(= jti),session_idFK →auth_sessionsON DELETE CASCADE,kind,consumed_at/revoked_at, informationalparent_id/refresh_token_idlineage,ip_address(45)/user_agent(512),expires_at. Also widensauth_sessions.ip_address15 → 45 (was IPv4-only). MySQL + Postgres migrations.session_idis present (M2M client/robot-credentials write only an access row — they mint no refresh token).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 → atomicmarkRefreshConsumed→ 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/revokesoft-revokes the DB row too, so a revoked refresh token can't refresh underskipActiveCheck.tokenRefreshGracePeriod(seconds, default0= strict), scoped to the chain tip so a stolen older token can't fork a parallel session.ISessionManager.revoke();oauth2-cleanersweeps expired token rows.tokenAccessMaxAgedefault 3600 → 900s to shrink the revocation blind spot for stateless local-JWKS adapters.Testing
tests-migrationsCI job (mysql2driver not installed locally).activein introspection after 1h).Both warrant a release-notes line.
Docs:
.agents/architecture.md→ Refresh Token Rotation & Replay Detection.Summary by CodeRabbit
New Features
Bug Fixes
Documentation