Repository navigation
feat: session-management API (list + revoke sessions) - #3187
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.
Adds a REST surface over auth_sessions so identities can see and revoke
sessions ("active devices" / force logout). Backend + typed client only;
the client-web UI is a follow-up.
- SESSION_READ / SESSION_DELETE permissions (auto-provisioned; admin=any,
realm_admin=ownOrNull read / own delete)
- SessionService + SessionController, dual-mounted /sessions and
/realms/:realmId/sessions:
GET /sessions list (self-scoped without SESSION_READ, else realm-gated)
GET /sessions/:id read one (@me/@self = current session)
DELETE /sessions/:id revoke one (own needs no permission)
DELETE /sessions revoke all own sessions except the current one
- SessionRepository.findMany / findAllByOwner (list bypasses the id-keyed
cache); force-selects realm_id/sub/sub_kind so a client `fields` projection
cannot strip realm_id and neutralize the per-row realm_scope gate
- current session id stashed by the authorization middleware for
delete-all-but-current
- typed client.session API in @authup/core-http-kit
- deleting a session cascade-drops its auth_session_tokens rows, so a force
logout also invalidates the subject's refresh tokens
Self-service is inherent: an identity can always list/revoke its own
sessions (ownership = session.sub + sub_kind == actor identity).
📝 WalkthroughWalkthroughThis PR adds a session management API for listing and revoking sessions. It wires request-scoped session identity through authorization, adds session repository/service/controller support, exposes a typed client surface, and updates tests and documentation. ChangesSession Management API
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant SessionController
participant SessionService
participant PermissionEvaluator
participant SessionRepository
Client->>SessionController: GET /sessions/:id
SessionController->>SessionController: resolve `@me/`@self from request session id
SessionController->>SessionService: getOne(resolvedId, actor)
SessionService->>SessionRepository: findOneById(resolvedId)
SessionRepository-->>SessionService: Session
SessionService->>PermissionEvaluator: evaluate SESSION_READ
PermissionEvaluator-->>SessionService: allow/deny
SessionService-->>SessionController: Session
SessionController-->>Client: 200 + Session
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 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
This PR introduces a first-class session-management REST API in apps/server-core (backed by auth_sessions) and a corresponding typed client.session surface in @authup/core-http-kit, enabling identities to list and revoke sessions (including “log out my other devices”), with per-row realm isolation and ownership-based self-service behavior.
Changes:
- Added
SESSION_READ/SESSION_DELETEpermissions and wired session operations into server-core’s HTTP module. - Implemented
SessionController+SessionService+ repository query support (findMany,findAllByOwner) for listing and revoking sessions. - Added typed
SessionAPIto@authup/core-http-kitand introduced regression/integration tests for self-scoping + realm isolation.
Reviewed changes
Copilot reviewed 26 out of 26 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| packages/core-kit/src/domains/permission/constants.ts | Adds SESSION_READ / SESSION_DELETE permission names. |
| packages/core-http-kit/src/domains/entities/session/types.ts | Introduces typed session API contracts (list/get/delete/deleteMany). |
| packages/core-http-kit/src/domains/entities/session/module.ts | Implements SessionAPI methods hitting /sessions endpoints. |
| packages/core-http-kit/src/domains/entities/session/index.ts | Exports session entity domain module/types. |
| packages/core-http-kit/src/domains/entities/index.ts | Re-exports session domain from entities barrel. |
| packages/core-http-kit/src/client/type.ts | Adds session: ISessionAPI to the public HTTP client type. |
| packages/core-http-kit/src/client/module.ts | Instantiates and exposes SessionAPI on the HTTP client. |
| apps/server-core/test/unit/http/controllers/entities/session.spec.ts | HTTP controller tests for listing, revoke-one, revoke-many, and self scoping. |
| apps/server-core/test/unit/http/controllers/entities/session-realm-isolation.spec.ts | Regression test for realm isolation vs. fields projection. |
| apps/server-core/test/unit/core/entities/session/service.spec.ts | Unit tests for SessionService (ownership, permission gating, delete-many). |
| apps/server-core/test/unit/core/entities/session/fake-repository.ts | Fake session repository used by SessionService unit tests. |
| apps/server-core/src/core/entities/session/types.ts | Defines ISessionService and delete-many result type. |
| apps/server-core/src/core/entities/session/service.ts | Implements session list/get/revoke logic with ownership + realm gating. |
| apps/server-core/src/core/entities/session/index.ts | Exports session service/types from core entities barrel. |
| apps/server-core/src/core/entities/index.ts | Re-exports session entity module from core entities barrel. |
| apps/server-core/src/core/authentication/session/types.ts | Extends session repository interface with list/by-owner methods. |
| apps/server-core/src/app/modules/provisioning/sources/default/module.ts | Ensures realm-admin scope override includes SESSION_DELETE at own reach. |
| apps/server-core/src/app/modules/http/modules/controller.ts | Registers SessionController and wires it to SessionService. |
| apps/server-core/src/app/modules/authentication/repositories/session.ts | Adds findMany (queryable list) + findAllByOwner and force-selects realm/owner columns for gating. |
| apps/server-core/src/adapters/http/request/helpers/session-id.ts | Adds request-scoped storage for bearer token session id. |
| apps/server-core/src/adapters/http/request/helpers/index.ts | Re-exports the new session-id request helper. |
| apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts | Stashes session_id from access tokens into request store. |
| apps/server-core/src/adapters/http/controllers/entities/session/module.ts | Implements /sessions endpoints (list, get, revoke, revoke-other-devices). |
| apps/server-core/src/adapters/http/controllers/entities/session/index.ts | Exports the session controller module. |
| apps/server-core/src/adapters/http/controllers/entities/index.ts | Re-exports session controller from entities barrel. |
| .agents/architecture.md | Documents the Session Management API design and security rationale. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| export interface ISessionRepository { | ||
| findOneById(id: string): Promise<Session | null> | null; | ||
|
|
||
| findMany(query: Record<string, any>, options?: SessionFindManyOptions): Promise<EntityRepositoryFindManyResult<Session>>; |
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
|
@coderabbitai pause |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
apps/server-core/test/unit/http/controllers/entities/session.spec.ts (1)
36-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDrop the no-op assertion.
expect(second).toBeDefined()on line 59 doesn't assert anything meaningful —secondis always defined since the priorawaitwould have thrown otherwise. Looks like a debugging leftover.🧹 Proposed cleanup
expect(after.data.some((s) => s.id === currentId)).toBe(true); - expect(second).toBeDefined(); });🤖 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/test/unit/http/controllers/entities/session.spec.ts` around lines 36 - 60, Remove the no-op assertion from the session controller test. In the `it('lists an admin's sessions and reflects a per-session revoke'...)` case in `session.spec.ts`, drop the `expect(second).toBeDefined()` check since `second` is already guaranteed by the awaited token creation and it does not verify behavior. Keep the rest of the revocation and session-list assertions intact.apps/server-core/src/core/entities/session/service.ts (1)
137-160: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winSequential session removal in the loop; consider parallelizing.
Each iteration awaits
this.repository.remove(session)(which itself does a DB delete + cache drop) before starting the next, causing N sequential round-trips to revoke "all other sessions." Order doesn't matter here, so this can run concurrently.♻️ Proposed fix to parallelize removal
- let count = 0; - for (const session of sessions) { - if (currentSessionId && session.id === currentSessionId) { - continue; - } - await this.repository.remove(session); - count += 1; - } - - return { count }; + const toRemove = sessions.filter( + (session) => !currentSessionId || session.id !== currentSessionId, + ); + + await Promise.all(toRemove.map((session) => this.repository.remove(session))); + + return { count: toRemove.length };🤖 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/entities/session/service.ts` around lines 137 - 160, The deleteManyForActor method in SessionService is removing sessions one by one with await inside the loop, which makes the revocation path sequential. Update the logic to collect all sessions except currentSessionId and remove them concurrently, while keeping the actor.identity guard and the existing count semantics. Use the existing repository.remove(session) call from deleteManyForActor to identify the removal step, and make sure the returned count still reflects only successfully removed sessions.
🤖 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.
Nitpick comments:
In `@apps/server-core/src/core/entities/session/service.ts`:
- Around line 137-160: The deleteManyForActor method in SessionService is
removing sessions one by one with await inside the loop, which makes the
revocation path sequential. Update the logic to collect all sessions except
currentSessionId and remove them concurrently, while keeping the actor.identity
guard and the existing count semantics. Use the existing
repository.remove(session) call from deleteManyForActor to identify the removal
step, and make sure the returned count still reflects only successfully removed
sessions.
In `@apps/server-core/test/unit/http/controllers/entities/session.spec.ts`:
- Around line 36-60: Remove the no-op assertion from the session controller
test. In the `it('lists an admin's sessions and reflects a per-session
revoke'...)` case in `session.spec.ts`, drop the `expect(second).toBeDefined()`
check since `second` is already guaranteed by the awaited token creation and it
does not verify behavior. Keep the rest of the revocation and session-list
assertions intact.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: dd0902e2-79d4-4be2-9417-5a45b7a5ae03
📒 Files selected for processing (26)
.agents/architecture.mdapps/server-core/src/adapters/http/controllers/entities/index.tsapps/server-core/src/adapters/http/controllers/entities/session/index.tsapps/server-core/src/adapters/http/controllers/entities/session/module.tsapps/server-core/src/adapters/http/middleware/built-in/authorization/module.tsapps/server-core/src/adapters/http/request/helpers/index.tsapps/server-core/src/adapters/http/request/helpers/session-id.tsapps/server-core/src/app/modules/authentication/repositories/session.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/provisioning/sources/default/module.tsapps/server-core/src/core/authentication/session/types.tsapps/server-core/src/core/entities/index.tsapps/server-core/src/core/entities/session/index.tsapps/server-core/src/core/entities/session/service.tsapps/server-core/src/core/entities/session/types.tsapps/server-core/test/unit/core/entities/session/fake-repository.tsapps/server-core/test/unit/core/entities/session/service.spec.tsapps/server-core/test/unit/http/controllers/entities/session-realm-isolation.spec.tsapps/server-core/test/unit/http/controllers/entities/session.spec.tspackages/core-http-kit/src/client/module.tspackages/core-http-kit/src/client/type.tspackages/core-http-kit/src/domains/entities/index.tspackages/core-http-kit/src/domains/entities/session/index.tspackages/core-http-kit/src/domains/entities/session/module.tspackages/core-http-kit/src/domains/entities/session/types.tspackages/core-kit/src/domains/permission/constants.ts
✅ Action performedReviews paused. |
createFakeUser().password is typed string | null (User.password is nullable, widened by the ...data spread), which failed check:types against createWithPassword's string param. Pass a known password const instead.
|
@coderabbitai full review |
✅ Action performedFull review finished. |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/server-core/src/core/entities/session/service.ts (1)
150-157: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueConsider batch/parallel deletion for
deleteManyForActor.Sessions are removed one at a time sequentially. If session counts per actor are usually small this is fine, but a single batch delete (or
Promise.all) would reduce latency for the "revoke all other sessions" flow.🤖 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/entities/session/service.ts` around lines 150 - 157, The `deleteManyForActor` session removal loop is deleting each session sequentially, which adds unnecessary latency for the “revoke all other sessions” path. Update the logic in `SessionService.deleteManyForActor` to delete the collected sessions in batch or via parallel promises instead of awaiting `this.repository.remove(session)` inside the loop. Keep the existing `currentSessionId` skip behavior and preserve the returned `count` based on the number of deleted sessions.
🤖 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.
Nitpick comments:
In `@apps/server-core/src/core/entities/session/service.ts`:
- Around line 150-157: The `deleteManyForActor` session removal loop is deleting
each session sequentially, which adds unnecessary latency for the “revoke all
other sessions” path. Update the logic in `SessionService.deleteManyForActor` to
delete the collected sessions in batch or via parallel promises instead of
awaiting `this.repository.remove(session)` inside the loop. Keep the existing
`currentSessionId` skip behavior and preserve the returned `count` based on the
number of deleted sessions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 6817ddcc-b4f8-4c89-ae5d-d1f22df77ac0
📒 Files selected for processing (26)
.agents/architecture.mdapps/server-core/src/adapters/http/controllers/entities/index.tsapps/server-core/src/adapters/http/controllers/entities/session/index.tsapps/server-core/src/adapters/http/controllers/entities/session/module.tsapps/server-core/src/adapters/http/middleware/built-in/authorization/module.tsapps/server-core/src/adapters/http/request/helpers/index.tsapps/server-core/src/adapters/http/request/helpers/session-id.tsapps/server-core/src/app/modules/authentication/repositories/session.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/provisioning/sources/default/module.tsapps/server-core/src/core/authentication/session/types.tsapps/server-core/src/core/entities/index.tsapps/server-core/src/core/entities/session/index.tsapps/server-core/src/core/entities/session/service.tsapps/server-core/src/core/entities/session/types.tsapps/server-core/test/unit/core/entities/session/fake-repository.tsapps/server-core/test/unit/core/entities/session/service.spec.tsapps/server-core/test/unit/http/controllers/entities/session-realm-isolation.spec.tsapps/server-core/test/unit/http/controllers/entities/session.spec.tspackages/core-http-kit/src/client/module.tspackages/core-http-kit/src/client/type.tspackages/core-http-kit/src/domains/entities/index.tspackages/core-http-kit/src/domains/entities/session/index.tspackages/core-http-kit/src/domains/entities/session/module.tspackages/core-http-kit/src/domains/entities/session/types.tspackages/core-kit/src/domains/permission/constants.ts
* feat: rotate refresh tokens with replay detection and family revocation
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.
* feat: session-management API (list + revoke sessions)
Adds a REST surface over auth_sessions so identities can see and revoke
sessions ("active devices" / force logout). Backend + typed client only;
the client-web UI is a follow-up.
- SESSION_READ / SESSION_DELETE permissions (auto-provisioned; admin=any,
realm_admin=ownOrNull read / own delete)
- SessionService + SessionController, dual-mounted /sessions and
/realms/:realmId/sessions:
GET /sessions list (self-scoped without SESSION_READ, else realm-gated)
GET /sessions/:id read one (@me/@self = current session)
DELETE /sessions/:id revoke one (own needs no permission)
DELETE /sessions revoke all own sessions except the current one
- SessionRepository.findMany / findAllByOwner (list bypasses the id-keyed
cache); force-selects realm_id/sub/sub_kind so a client `fields` projection
cannot strip realm_id and neutralize the per-row realm_scope gate
- current session id stashed by the authorization middleware for
delete-all-but-current
- typed client.session API in @authup/core-http-kit
- deleting a session cascade-drops its auth_session_tokens rows, so a force
logout also invalidates the subject's refresh tokens
Self-service is inherent: an identity can always list/revoke its own
sessions (ownership = session.sub + sub_kind == actor identity).
* test: use a typed password constant for created-user logins
createFakeUser().password is typed string | null (User.password is nullable,
widened by the ...data spread), which failed check:types against
createWithPassword's string param. Pass a known password const instead.
* feat: session-management UI (plan 016 PR G2)
Client-web UI for the session-management API (#3187):
- EntityType.SESSION + EntityTypeMap entry (core-kit)
- ASessions collection component (client-web-kit)
- /settings/sessions self page ("my active sessions") + settings nav item
- /users/:id/sessions admin tab + user-detail nav item
- both list ip_address / user_agent / last-seen / expires with per-session
revoke via AEntityDelete (entity-type="session"); the self page scopes to
the current user, the admin tab filters by user_id and gates revoke on
SESSION_DELETE
- i18n: SESSION entity noun + ipAddress/userAgent/seenAt/expiresAt field
labels across en/de/fr/es
Plan 016 PR G (backend + typed client) — a REST surface over
auth_sessionsso identities can see and revoke sessions ("active devices" / force logout). Stacked on #3186 (refresh-token rotation); base isfeat/refresh-token-rotation, so this diff is the session-management change only. The client-web UI (/settings/sessions, admin/users/:id/sessions) is a follow-up (PR G2).Endpoints
Dual-mounted
@DController(['/sessions', '/realms/:realmId/sessions']):GET /sessionsSESSION_READ(force-scoped to own sessions via a mandatory ownerWHERE); withSESSION_READ, realm-gated per row.GET /sessions/:idSESSION_READ+ realm-match.@me/@self→ the caller's current session.DELETE /sessions/:idSESSION_DELETE+ realm-match.DELETE /sessionsDesign
SESSION_READ/SESSION_DELETE(not reusingUSER_*/CLIENT_*/ROBOT_*, because a session's subject is polymorphic). Auto-provisioned (enum-iterated); granted toadmin(any) andrealm_admin(ownOrNullread /owndelete).session.sub === actor.identity.data.id && session.sub_kind === actor.identity.type, so self-service is inherent (no extra permission).SessionRepositorygainsfindMany/findAllByOwner(list bypasses the id-keyed cache). Delete routes through the cache-awareremove→ the DB delete cascade-drops the session'sauth_session_tokensrows, so a force-logout also invalidates the subject's refresh tokens.client.sessionAPI in@authup/core-http-kit.Security hardening (found by an adversarial review of this PR)
SessionRepository.findManyforce-selectsrealm_id/sub/sub_kind(qb.addSelect) regardless of the clientfieldsprojection. The per-row realm gate readsrealm_id, and rapiq honors afieldsprojection overdefault— so without this, an own/ownOrNull-scopedSESSION_READholder could request?fields[session]=id,sub(omittingrealm_id) and neutralize therealm_scopereach factor, leaking cross-realm sessions.session-realm-isolation.spec.tsis the regression guard (verified: it fails without theaddSelect).Testing
Docs:
.agents/architecture.md→ Session Management API.Summary by CodeRabbit
New Features
@me/@selfsupport and force-logout of other devices.SESSION_READandSESSION_DELETEpermission names, and documented the Session Management API.Bug Fixes
Tests