Skip to content

feat: session-management API (list + revoke sessions) - #3187

Merged
tada5hi merged 4 commits into
masterfrom
feat/session-management
Jul 6, 2026
Merged

tada5hi merged 4 commits into
masterfrom
feat/session-management

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

Plan 016 PR G (backend + typed client) — a REST surface over auth_sessions so identities can see and revoke sessions ("active devices" / force logout). Stacked on #3186 (refresh-token rotation); base is feat/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']):

Route Behavior
GET /sessions List. Self-service without SESSION_READ (force-scoped to own sessions via a mandatory owner WHERE); with SESSION_READ, realm-gated per row.
GET /sessions/:id Read one. Own → no permission; else SESSION_READ + realm-match. @me/@self → the caller's current session.
DELETE /sessions/:id Revoke one. Own → no permission; else SESSION_DELETE + realm-match.
DELETE /sessions Revoke every own session except the current one ("log out my other devices"). Self-service; the current session id comes from the bearer token, never the client.

Design

  • Dedicated SESSION_READ / SESSION_DELETE (not reusing USER_*/CLIENT_*/ROBOT_*, because a session's subject is polymorphic). Auto-provisioned (enum-iterated); granted to admin (any) and realm_admin (ownOrNull read / own delete).
  • Ownership = session.sub === actor.identity.data.id && session.sub_kind === actor.identity.type, so self-service is inherent (no extra permission).
  • SessionRepository gains findMany / findAllByOwner (list bypasses the id-keyed cache). Delete routes through the cache-aware remove → the DB delete cascade-drops the session's auth_session_tokens rows, so a force-logout also invalidates the subject's refresh tokens.
  • Typed client.session API in @authup/core-http-kit.

Security hardening (found by an adversarial review of this PR)

SessionRepository.findMany force-selects realm_id / sub / sub_kind (qb.addSelect) regardless of the client fields projection. The per-row realm gate reads realm_id, and rapiq honors a fields projection over default — so without this, an own/ownOrNull-scoped SESSION_READ holder could request ?fields[session]=id,sub (omitting realm_id) and neutralize the realm_scope reach factor, leaking cross-realm sessions. session-realm-isolation.spec.ts is the regression guard (verified: it fails without the addSelect).

Note (out of scope, pre-existing): the same field-projection pattern affects the existing robot / client / user getMany paths (their resourceRealmMatch per-row gate reads a realm_id a client can project away). Not fixed here — flagged for a separate hardening pass.

Testing

  • Service spec (13) — self-scoping, per-row realm drop, self vs. permission for get/delete, delete-all-but-current.
  • HTTP specs (4) — admin list + per-session revoke, delete-all-but-current, non-admin self-scoping, and the cross-realm field-projection regression.
  • Full server-core suite 1071 tests pass; full monorepo build clean.

Docs: .agents/architecture.md → Session Management API.

Summary by CodeRabbit

  • New Features

    • Added session management API (list, get, and revoke) with @me/@self support and force-logout of other devices.
    • Extended the client with a dedicated sessions domain API.
    • Added SESSION_READ and SESSION_DELETE permission names, and documented the Session Management API.
  • Bug Fixes

    • Enforced realm-aware session access and projections isolation during session listing/reads.
    • Ensured revocation keeps the active session when revoking “all others”.
  • Tests

    • Added unit and regression tests for authorization, revocation behavior, and realm isolation.

tada5hi added 2 commits July 6, 2026 11:29
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).
Copilot AI review requested due to automatic review settings July 6, 2026 10:20
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This 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.

Changes

Session Management API

Layer / File(s) Summary
Permissions and session tracking
packages/core-kit/src/domains/permission/constants.ts, apps/server-core/src/app/modules/provisioning/sources/default/module.ts, apps/server-core/src/adapters/http/request/helpers/*, apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
Adds SESSION_READ/SESSION_DELETE, grants realm-admin session delete scope, and stores the authenticated bearer session id on the request.
Repository contracts and query shape
apps/server-core/src/core/authentication/session/types.ts, apps/server-core/src/app/modules/authentication/repositories/session.ts
Adds session ownership/query types, extends the repository interface, and implements findMany with forced session columns and owner filtering.
Session service authorization
apps/server-core/src/core/entities/session/*, apps/server-core/test/unit/core/entities/session/*
Adds the session service contract/implementation and unit coverage for scoped listing, single-session reads, deletes, and bulk revocation.
Controller endpoints and module wiring
apps/server-core/src/adapters/http/controllers/entities/session/*, apps/server-core/src/adapters/http/controllers/entities/index.ts, apps/server-core/src/app/modules/http/modules/controller.ts
Adds the session HTTP controller, resolves @me/@self, and wires the controller into the HTTP module.
Client API, tests, and documentation
packages/core-http-kit/src/domains/entities/session/*, packages/core-http-kit/src/client/*, apps/server-core/test/unit/http/controllers/entities/session*.spec.ts, .agents/architecture.md
Adds the session client API, updates client exports, adds HTTP-level tests, and documents the session API behavior.

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
Loading

Possibly related PRs

  • authup/authup#3186: Introduces session token lifecycle behavior that aligns with the session revocation flow here, including the documented token cascade on delete.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding a session-management API for listing and revoking sessions.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/session-management

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@3187

@authup/client-web

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

@authup/server-core

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

@authup/access

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

@authup/client-web-kit

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

@authup/client-web-kit-theme

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

@authup/client-web-nuxt

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

@authup/client-web-theme

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

@authup/core-http-kit

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

@authup/core-kit

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

@authup/core-realtime-kit

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

@authup/errors

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

@authup/i18n

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

@authup/kit

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

@authup/server-adapter-kit

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

@authup/server-adapter-node

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

@authup/server-adapter-socket-io

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

@authup/server-adapter-web

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

@authup/server-kit

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

@authup/server-test-kit

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

@authup/specs

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

commit: 9b41ef6

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

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_DELETE permissions 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 SessionAPI to @authup/core-http-kit and 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.

Comment on lines 24 to +27
export interface ISessionRepository {
findOneById(id: string): Promise<Session | null> | null;

findMany(query: Record<string, any>, options?: SessionFindManyOptions): Promise<EntityRepositoryFindManyResult<Session>>;
Base automatically changed from feat/refresh-token-rotation to master July 6, 2026 13:13
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
@tada5hi

tada5hi commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai pause

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

🧹 Nitpick comments (2)
apps/server-core/test/unit/http/controllers/entities/session.spec.ts (1)

36-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the no-op assertion.

expect(second).toBeDefined() on line 59 doesn't assert anything meaningful — second is always defined since the prior await would 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 win

Sequential 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

📥 Commits

Reviewing files that changed from the base of the PR and between 8595c35 and d400983.

📒 Files selected for processing (26)
  • .agents/architecture.md
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/session/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/session/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
  • apps/server-core/src/adapters/http/request/helpers/index.ts
  • apps/server-core/src/adapters/http/request/helpers/session-id.ts
  • apps/server-core/src/app/modules/authentication/repositories/session.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/core/authentication/session/types.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/entities/session/index.ts
  • apps/server-core/src/core/entities/session/service.ts
  • apps/server-core/src/core/entities/session/types.ts
  • apps/server-core/test/unit/core/entities/session/fake-repository.ts
  • apps/server-core/test/unit/core/entities/session/service.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/session-realm-isolation.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/session.spec.ts
  • packages/core-http-kit/src/client/module.ts
  • packages/core-http-kit/src/client/type.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/core-http-kit/src/domains/entities/session/index.ts
  • packages/core-http-kit/src/domains/entities/session/module.ts
  • packages/core-http-kit/src/domains/entities/session/types.ts
  • packages/core-kit/src/domains/permission/constants.ts

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews 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.
@tada5hi

tada5hi commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.

@tada5hi

tada5hi commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.

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

🧹 Nitpick comments (1)
apps/server-core/src/core/entities/session/service.ts (1)

150-157: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between 8595c35 and 9b41ef6.

📒 Files selected for processing (26)
  • .agents/architecture.md
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/session/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/session/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
  • apps/server-core/src/adapters/http/request/helpers/index.ts
  • apps/server-core/src/adapters/http/request/helpers/session-id.ts
  • apps/server-core/src/app/modules/authentication/repositories/session.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/core/authentication/session/types.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/entities/session/index.ts
  • apps/server-core/src/core/entities/session/service.ts
  • apps/server-core/src/core/entities/session/types.ts
  • apps/server-core/test/unit/core/entities/session/fake-repository.ts
  • apps/server-core/test/unit/core/entities/session/service.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/session-realm-isolation.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/session.spec.ts
  • packages/core-http-kit/src/client/module.ts
  • packages/core-http-kit/src/client/type.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/core-http-kit/src/domains/entities/session/index.ts
  • packages/core-http-kit/src/domains/entities/session/module.ts
  • packages/core-http-kit/src/domains/entities/session/types.ts
  • packages/core-kit/src/domains/permission/constants.ts

@tada5hi
tada5hi merged commit 58fcf93 into master Jul 6, 2026
13 checks passed
@tada5hi
tada5hi deleted the feat/session-management branch July 6, 2026 15:21
@github-actions github-actions Bot mentioned this pull request Jul 6, 2026
tada5hi added a commit that referenced this pull request Jul 7, 2026
* 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
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