Skip to content

feat!: per-application session token attribution, inventory API and revocation - #3404

Merged
tada5hi merged 8 commits into
masterfrom
feat/session-client-attribution
Aug 5, 2026
Merged

tada5hi merged 8 commits into
masterfrom
feat/session-client-attribution

Conversation

@tada5hi

@tada5hi tada5hi commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Makes per-application session state real: attributed on the server, queryable over the API, and acted on by the account console. Four commits, reviewable in order.

1. Attribute issued tokens to their client (feat!)

auth_sessions.client_id was the only per-application attribution, and resolveSession overwrote it on every authorize that reused a session. One browser session serves several applications (the hosted auth pages and the account console share the IdP origin by design), so the column was last-writer-wins and accurate for none of them. Per-app attribution, one of the two stated reasons #3371 split the per-realm system clients, did not hold in this topology.

  • auth_session_tokens gains a nullable client_id (FK to auth_clients, ON DELETE CASCADE). Both issuers stamp it from the client already on the token payload, so no lookups are added. Null where the minting path has no client (an MFA-login completion rides a client-less session) and on pre-existing rows.
  • auth_sessions.client_id becomes write-once: "the client that first authorized on this session".
  • Migration for both dialects.

This is the shape both reference implementations use. Authentik's AuthenticatedSession is one per browser and carries no provider field, with the link on BaseGrantModel; Keycloak pairs one UserSessionModel with per-client AuthenticatedClientSessionModel children. Neither creates sibling sessions per application. Recorded in .agents/references/authentik.md.

2. Expose the token inventory as a resource

auth_session_tokens was the one table with no query surface, so questions about it had to be answered by bolting parameters onto /sessions. An earlier revision did exactly that with ?usedClientId=: a session-shaped endpoint answering a token-shaped question, implemented as a repository option carrying raw cross-table SQL. It also could not express the thing that matters, revoking one application while the session keeps serving the others. It has been replaced.

/session-tokens is read and revoke only, since rows are created solely by the grants.

Query Answers
filter[sessionId] which applications rode this session (the back-channel logout audience)
filter[clientId] every session an application served, which sessions.client_id cannot: it names only the first authorizer
both revoke one application on one session, leaving the session alive

DELETE means revoke, not remove. The row is stamped and the jti is blocklisted with a TTL pinned to the token's real expiry. Dropping the row would block refresh (the row is the authority for refresh validity since plan 016) while leaving an already-issued access token verifying against a stateless JWKS adapter until its own exp.

Authorization resolves through the session, since the rows carry neither realm nor subject. The repository joins it unconditionally and pins the columns the gate reads, so a fields projection cannot neutralize it (the plan-039 discipline, through a relation instead of a column). An actor without SESSION_READ is scoped to its own sessions' tokens by an AND-injected condition no client filter can displace. A bulk revoke must carry a target filter and is rejected otherwise: unlike DELETE /sessions there is no self-service fallback to degrade to, so an unscoped call has to fail loudly rather than widen.

3. Typed client

client.sessionToken.{getMany,getOne,delete,deleteMany}. Named after the EntityTypeMap key, so it joins the derived entity-API registry automatically; the cast-free assignment in pickEntityAPI is the compile-time proof that it serves the SessionToken record type.

deleteMany takes its query as a required argument, unlike the session counterpart: the server rejects an unscoped bulk revoke, and an optional parameter would invite writing the one call shape that always fails.

4. The account console actually signs out of a revoked application

"Revoke access" removed consent rows only. Consent is prompt-level, so it stops the next silent issue and leaves already-issued tokens working — the application the user just revoked kept working. It now revokes that application's tokens too, and because the rows hang off the session rather than being it, the other applications on the same session stay signed in.

The call is scoped to the user's own sessions explicitly, by id. The server force-scopes a caller that lacks SESSION_DELETE, but an administrator holds it, so relying on that would have an admin revoke the application for every user from their own account page.

Breaking change

auth_sessions.client_id is no longer written for user-subject sessions.

It carries a nullable user_id and a nullable client_id, and SessionManager.create populates exactly one of them from sub according to subKind — the same trick auth_consents uses. They are typed foreign keys for a polymorphic subject, so ON DELETE CASCADE can drop a subject's own sessions.

Three writers were instead putting the application into client_id on user sessions (the password grant, the MFA-login ticket, and the authorize grant). That placed an unrelated id behind a cascade meaning "this client owns this row", so deleting an application deleted a user's session and, through auth_session_tokens.session_id, every other application's tokens riding it. Deleting the account console would have signed users out of the admin console.

The column now has exactly one meaning: the client-subject FK. Consequences:

  • GET/DELETE /sessions?filter[clientId]= now selects sessions whose subject is that client, symmetric with filter[userId]. It no longer returns a user's sessions because some application authorized on them.
  • "Which application served this session" is /session-tokens?filter[clientId]=, where a session serving several applications can say so.

Unblocks

Resolves the open "audience resolution" decision for OIDC back-channel logout, whose correct audience is every RP that rode the ending session. Notifying session.client_id alone is correct only for single-RP sessions; approximating from consent rows under-notifies, since consent is skipped for builtIn clients, so neither console would ever be told.

Verification

  • Build 24/24; ESLint and check:types (test-inclusive) clean.
  • server-core 181 files / 2008 tests; core-http-kit 24; account console 14.
  • Migration round-trip on MySQL and PostgreSQL against fresh databases: run → revert ×15 → run, leaving only the migrations table at full revert.
  • Entity-vs-schema drift check (createSchemaBuilder().log()) on both dialects: client_id produces no column statement, so the migration matches TypeORM's metadata. This contradicts an earlier review suggestion to use varchar(36) on MySQL — auth_sessions.client_id is varchar(255) there (1766830857009-Default.ts), and varchar(36) would introduce drift.
  • session-token-attribution.spec.ts pins two applications on one session leaving session.clientId at the first while each application's rows carry their own. session-token.spec.ts pins the resource: the audience query, finding every session an application served, a per-application revoke that leaves the session and the other application intact, rejection of an unscoped bulk revoke, and single-token revoke.

Not verified by execution: apps/client-account-console/src/pages/applications.vue has no spec, and I did not run the app to watch a revoke sign the user out. The endpoint it calls is covered end to end (including that the revoked application's refresh is rejected while the untouched one still works), and the change is ~26 lines, but the UI path itself was verified by reading, not by running.

One caveat on the suite: the provisioning.spec.ts wildcard-realm case flakes intermittently under parallel workers against the shared sqlite file. It passes in isolation and on re-run, and this branch does not touch provisioning.

Summary by CodeRabbit

  • New Features
    • Added session-token APIs for listing, viewing, and revoking individual or multiple tokens.
    • Added filtering, pagination, ownership scoping, and application/session-based access controls.
    • Issued access and refresh tokens now retain application attribution for clearer activity tracking.
  • Bug Fixes
    • Revoking an application’s consent now signs the user out of that application without affecting others.
    • Reused sessions retain their original authorization context while newly issued tokens are attributed correctly.
  • Documentation
    • Clarified session and account-console attribution behavior.

auth_sessions.client_id was the only per-application attribution, and
resolveSession overwrote it on every authorize that reused a session. One
browser session serves several applications (the hosted auth pages and the
account console share the IdP origin by design), so the column was
last-writer-wins and accurate for none of them. Per-app attribution, one of
the two reasons per-realm system clients were split, did not hold.

Attribution moves one level down, onto the token:

- auth_session_tokens gains a nullable client_id (FK to auth_clients, ON
  DELETE CASCADE). Every issuer stamps it from the same client it already
  puts on the payload, so no lookups are added.
- auth_sessions.client_id becomes write-once: it now means "the client that
  first authorized on this session" and is never overwritten.

This is the shape both reference implementations use. Authentik's
AuthenticatedSession is one per browser and carries no provider field, with
the link on BaseGrantModel (AuthorizationCode / AccessToken / RefreshToken);
Keycloak pairs one UserSessionModel with per-client
AuthenticatedClientSessionModel children. Neither creates sibling sessions
per application, and both derive per-application facts below the browser
session. It is also the audience source OIDC back-channel logout needs.

BREAKING CHANGE: auth_sessions.client_id now names the client that first
authorized on a session rather than the most recent one, so
GET/DELETE /sessions?filter[clientId] selects on that basis. The two differ
only where several applications share one session. Revocation that should
reach every session an application served must filter
auth_session_tokens.client_id instead.
Copilot AI lite review requested due to automatic review settings August 5, 2026 08:24
@coderabbitai

coderabbitai Bot commented Aug 5, 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

The change adds nullable per-client attribution to session tokens, preserves first-client ownership on reused sessions, adds session-token management APIs, and updates account-console revocation to remove only the selected application’s tokens.

Changes

Per-client session-token attribution

Layer / File(s) Summary
Token attribution storage and issuance
apps/server-core/src/adapters/database/..., packages/core-kit/src/domains/session-token/*, apps/server-core/src/core/oauth2/token/issuer/*
Session-token rows now store nullable client_id. Access and refresh token issuers persist the originating client.
Authorization session lifecycle
apps/server-core/src/core/oauth2/grant-types/*, apps/server-core/src/core/oauth2/mfa-login/*, apps/server-core/test/unit/http/controllers/workflows/token/*
Shared sessions retain their existing client subject. Issued tokens retain each application’s client attribution across authorization, password, hosted, refresh, account-console, and MFA flows.
Session-token querying and revocation
apps/server-core/src/core/entities/session-token/*, apps/server-core/src/adapters/http/controllers/entities/session-token/*, packages/core-http-kit/src/domains/entities/session-token/*
Added actor-scoped listing, retrieval, single revocation, targeted bulk revocation, HTTP endpoints, and client SDK methods.
Account-console application revocation
apps/client-account-console/src/pages/applications.vue
Application revocation uses a stable subject and removes tokens for the selected client only.

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

Sequence Diagram(s)

sequenceDiagram
  participant AccountConsole
  participant SessionTokenController
  participant SessionTokenService
  participant SessionTokenRepositoryAdapter
  AccountConsole->>SessionTokenController: request token revocation
  SessionTokenController->>SessionTokenService: pass actor context and client filter
  SessionTokenService->>SessionTokenRepositoryAdapter: load authorized matching tokens
  SessionTokenService->>SessionTokenRepositoryAdapter: timestamp token rows
  SessionTokenController-->>AccountConsole: return revocation result
Loading

Possibly related PRs

  • authup/authup#3186: Modified the session-token persistence model extended here with client attribution.
  • authup/authup#3191: Modified OAuth authorization session reuse and client attribution.
  • authup/authup#3373: Modified the account-console OAuth session flow updated here.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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 clearly summarizes the main changes: per-application token attribution, the inventory API, and revocation.
✨ Finishing Touches 💡 1
📝 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-client-attribution

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 Aug 5, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

authup

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

@authup/client-account-console

npm i https://pkg.pr.new/@authup/client-account-console@3404

@authup/client-admin-console

npm i https://pkg.pr.new/@authup/client-admin-console@3404

@authup/client-auth-console

npm i https://pkg.pr.new/@authup/client-auth-console@3404

@authup/server-core

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

@authup/access

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

@authup/client-web-kit

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

@authup/client-web-kit-theme

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

@authup/client-web-nuxt

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

@authup/client-web-theme

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

@authup/core-http-kit

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

@authup/core-kit

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

@authup/core-realtime-kit

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

@authup/errors

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

@authup/i18n

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

@authup/kit

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

@authup/server-adapter-kit

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

@authup/server-adapter-node

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

@authup/server-adapter-socket-io

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

@authup/server-adapter-web

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

@authup/server-kit

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

@authup/server-test-kit

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

@authup/specs

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

commit: d789039

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 refines Authup’s session attribution model so that per-application attribution lives on issued token rows (auth_session_tokens.client_id) instead of being “last-writer-wins” on the shared browser session (auth_sessions.client_id). It also introduces an admin-safe way to list/revoke sessions by the applications they actually served via ?usedClientId=—a key prerequisite for correct OIDC back-channel logout audience resolution.

Changes:

  • Add nullable clientId attribution to session-token domain/entity + persist it from token payloads in both access/refresh issuers.
  • Make auth_sessions.client_id write-once (“first client to authorize on this browser session”) by updating authorize grant behavior and tests.
  • Add usedClientId query parameter support to GET/DELETE /sessions, wired through controller → service → repository with an EXISTS reach over auth_session_tokens.client_id.

Reviewed changes

Copilot reviewed 21 out of 21 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
packages/core-kit/src/domains/session-token/entity.ts Extends SessionToken with nullable clientId attribution.
docs/src/guide/deployment/account-console.md Updates account-console deployment docs to reflect per-token attribution + write-once session client.
apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts Adds end-to-end tests covering token-row attribution, write-once session client, and usedClientId reach for revoke/list.
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts Extends console continuity tests to cover forced account-console re-mint on shared session with per-token attribution.
apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts Updates/extends authorize-grant unit tests for write-once session client semantics.
apps/server-core/test/unit/core/helpers/fake-session-token-repository.ts Ensures fake repository persists clientId (defaulting to null).
apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts Persists clientId onto refresh token inventory rows from payload.
apps/server-core/src/core/oauth2/token/issuer/access/module.ts Persists clientId onto access token inventory rows from payload.
apps/server-core/src/core/oauth2/session-token/types.ts Extends session-token create input to accept optional nullable clientId.
apps/server-core/src/core/oauth2/grant-types/authorize.ts Makes auth_sessions.client_id write-once when reusing sessions.
apps/server-core/src/core/entities/session/types.ts Adds service options for usedClientId-driven reads and deletes.
apps/server-core/src/core/entities/session/service.ts Threads clientIds option through getMany/deleteMany; treats usedClientId as an admin-path selector for deletes.
apps/server-core/src/core/authentication/session/types.ts Extends repository query options to carry clientIds constraints.
apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts Persists clientId for DB-backed session-token inventory rows.
apps/server-core/src/app/modules/authentication/repositories/session.ts Implements usedClientId reach: session.client_id IN (...) OR EXISTS(auth_session_tokens ...).
apps/server-core/src/adapters/http/controllers/entities/session/module.ts Adds parsing for usedClientId request parameter and wires it into GET/DELETE handlers.
apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts Adds nullable auth_session_tokens.client_id + FK for Postgres.
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts Adds nullable auth_session_tokens.client_id + FK for MySQL.
apps/server-core/src/adapters/database/domains/session-token/entity.ts Adds clientId column + nullable FK relation to ClientEntity on session-token table.
.agents/references/authentik.md Records the reference-model alignment (Authentik/Keycloak) for session vs per-token attribution.
.agents/architecture.md Updates architecture docs to reflect attribution now living on token rows and session client being write-once.

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

Comment on lines +80 to +92
protected applyClientIds(qb: SelectQueryBuilder<Session>, ids?: string[]) {
if (!ids || ids.length === 0) {
return;
}

qb.andWhere(new Brackets((where) => {
where.where('session.client_id IN (:...usedClientIds)', { usedClientIds: ids })
.orWhere(
'EXISTS (SELECT 1 FROM auth_session_tokens ust' +
' WHERE ust.session_id = session.id' +
' AND ust.client_id IN (:...usedClientIds))',
{ usedClientIds: ids },
);

@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

🧹 Nitpick comments (3)
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts (1)

34-37: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated token-row test helpers across both new specs. Both files implement identical decodeJwtPayload and readTokenRow helpers to assert the new SessionTokenEntity.clientId attribution. One shared test helper removes the duplication and keeps the two suites in agreement when the token row changes.

  • apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts#L34-L37: move decodeJwtPayload and the readTokenRow body at lines 108-118 into a shared test helper module and import them.
  • apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts#L79-L89: import the same shared helpers and delete the local decodeJwtPayload at lines 28-31 and readTokenRow at lines 79-89.
🤖 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/workflows/token/account-console-session.spec.ts`
around lines 34 - 37, Create one shared test helper module containing
decodeJwtPayload and the readTokenRow implementation currently used by both
suites. In
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts#L34-L37
and its readTokenRow body at lines 108-118, replace the local helpers with
imports; in
apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts#L79-L89,
import the same helpers and remove both local implementations, preserving
existing assertions and behavior.
apps/server-core/src/adapters/database/domains/session-token/entity.ts (1)

46-51: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Declare an explicit column type for client_id.

The property type is Client['id'] | null, so the emitted design:type metadata is Object, not String. TypeORM cannot derive a column type from that. Every sibling id column in this entity (session_id, parent_id, refresh_token_id) declares type: 'uuid'. An implicit type also risks drift against the column type the new migrations create.

♻️ Proposed change
     `@Column`({
         name: 'client_id',
+        type: 'uuid',
         nullable: true,
         default: null,
     })
     clientId: Client['id'] | null;

Run the following script to compare the entity column type with the migration column type:

#!/bin/bash
set -euo pipefail
fd -t f 'SessionTokenClientId' apps/server-core/src/adapters/database/migrations --exec cat -n
# how sibling nullable id columns declare their type
rg -n -B3 -A6 "name: 'client_id'" apps/server-core/src/adapters/database/domains --glob '*.ts'
🤖 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/domains/session-token/entity.ts`
around lines 46 - 51, Update the clientId column definition in the session-token
entity to explicitly declare type: 'uuid', matching the sibling session_id,
parent_id, and refresh_token_id columns and the migration schema. Preserve its
nullable and default: null settings.
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts (1)

29-35: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Add an index on auth_session_tokens.client_id.

The new client-based session lookup and revocation use token attribution. PostgreSQL does not create a lookup index for a foreign-key column. Add an explicit index in both migrations. Declare the index in SessionTokenEntity if schema-drift tooling derives indexes from ORM metadata.

  • apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts#L29-L35: add the matching named index in up and remove it in down.
  • apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts#L29-L35: add the matching named index in up and remove it 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/1785871780234-SessionTokenClientId.ts`
around lines 29 - 35, Introduce a named index for auth_session_tokens.client_id
in both migration files: add it during up alongside the foreign key, and remove
the same index during down. Update SessionTokenEntity with the matching index
metadata if ORM schema-drift tooling derives indexes from it. Affected sites:
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts
lines 29-35 and
apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts
lines 29-35.
🤖 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 @.agents/architecture.md:
- Around line 2736-2740: Update the column description in the schema
documentation so parent_id is explicitly described as a plain nullable UUID with
no self-FK, while client_id alone carries the nullable auth_clients foreign-key
and ON DELETE CASCADE details; keep refresh_token_id’s informational-lineage
description separate.

In `@apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts`:
- Around line 166-175: Ensure the refresh assertion targets this test’s
invocation rather than stale shared state: clear sessionManager.refreshCalls
alongside createCalls before grant.runWith, or assert against the final
refreshCalls entry. Preserve the expectation that the refreshed session has
sessionId and firstClientId.

---

Nitpick comments:
In `@apps/server-core/src/adapters/database/domains/session-token/entity.ts`:
- Around line 46-51: Update the clientId column definition in the session-token
entity to explicitly declare type: 'uuid', matching the sibling session_id,
parent_id, and refresh_token_id columns and the migration schema. Preserve its
nullable and default: null settings.

In
`@apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts`:
- Around line 29-35: Introduce a named index for auth_session_tokens.client_id
in both migration files: add it during up alongside the foreign key, and remove
the same index during down. Update SessionTokenEntity with the matching index
metadata if ORM schema-drift tooling derives indexes from it. Affected sites:
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts
lines 29-35 and
apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts
lines 29-35.

In
`@apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts`:
- Around line 34-37: Create one shared test helper module containing
decodeJwtPayload and the readTokenRow implementation currently used by both
suites. In
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts#L34-L37
and its readTokenRow body at lines 108-118, replace the local helpers with
imports; in
apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts#L79-L89,
import the same helpers and remove both local implementations, preserving
existing assertions and behavior.
🪄 Autofix

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 Plus

Run ID: 1829697c-6992-48db-8f94-7486647a97d7

📥 Commits

Reviewing files that changed from the base of the PR and between 1aaa52b and ff72c5f.

📒 Files selected for processing (21)
  • .agents/architecture.md
  • .agents/references/authentik.md
  • apps/server-core/src/adapters/database/domains/session-token/entity.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts
  • apps/server-core/src/adapters/http/controllers/entities/session/module.ts
  • apps/server-core/src/app/modules/authentication/repositories/session.ts
  • apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts
  • apps/server-core/src/core/authentication/session/types.ts
  • apps/server-core/src/core/entities/session/service.ts
  • apps/server-core/src/core/entities/session/types.ts
  • apps/server-core/src/core/oauth2/grant-types/authorize.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/test/unit/core/helpers/fake-session-token-repository.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts
  • docs/src/guide/deployment/account-console.md
  • packages/core-kit/src/domains/session-token/entity.ts

Comment thread .agents/architecture.md Resolved
@tada5hi
tada5hi force-pushed the feat/session-client-attribution branch from ff72c5f to ffe4963 Compare August 5, 2026 08:34
tada5hi added 3 commits August 5, 2026 10:53
auth_session_tokens was the one table with no query surface, so questions
about it had to be answered by bolting parameters onto /sessions. That is
how `?usedClientId=` came about: a session-shaped endpoint answering a
token-shaped question, implemented as a repository option carrying raw
cross-table SQL. It also could not express the thing that actually matters,
revoking one application while the session keeps serving the others.

`/session-tokens` is the resource instead. Read and revoke only, since rows
are created solely by the grants.

- `filter[sessionId]` lists the applications that rode one session, which is
  the audience OIDC back-channel logout needs.
- `filter[clientId]` finds every session an application served, which the
  session column cannot: it names only the first authorizer.
- The pair scopes a revoke to one application on one session, leaving the
  session alive so the others stay signed in.

DELETE means revoke, not remove. The row is stamped and the jti is
blocklisted with a TTL pinned to the token's real expiry. Dropping the row
would block refresh, since the row is the authority for refresh validity,
while leaving an already-issued access token verifying against a stateless
JWKS adapter until its own exp.

Authorization resolves through the session, because the rows carry neither
realm nor subject: the repository joins it unconditionally and pins the
columns the gate reads, so a `fields` projection cannot neutralize it. An
actor without SESSION_READ is scoped to its own sessions' tokens by an
AND-injected condition a client filter cannot displace. A bulk revoke must
carry a target filter and is rejected otherwise, since unlike the session
bulk revoke there is no self-service fallback to degrade to.
Typed access to the token inventory resource: getMany, getOne, delete and
deleteMany over `/session-tokens`.

`deleteMany` takes its query as a REQUIRED argument, unlike the session
counterpart. The server rejects an unscoped bulk revoke, and an optional
parameter would invite writing the one call shape that always fails.

The sub-API is named `sessionToken`, matching the `EntityTypeMap` key, so it
joins the derived entity-API registry automatically. The cast-free assignment
in `pickEntityAPI` is the compile-time proof that it serves the `SessionToken`
record type.
"Revoke access" removed the consent rows only. Consent is prompt-level: it
stops the next silent issue and leaves already-issued tokens working until
they expire, so the application the user just revoked kept working.

It now also revokes that application's tokens. Because the rows hang off the
session rather than being the session, the other applications on the same
session stay signed in, which is what makes this per-application rather than
a logout.

The call is scoped to this user's own sessions explicitly, by id. The server
force-scopes a caller that lacks SESSION_DELETE, but an administrator holds
it, so relying on that would have an admin revoke the application for every
user from their own account page.
@tada5hi tada5hi changed the title feat!: attribute issued tokens to the client they were issued for feat!: per-application session token attribution, inventory API and revocation Aug 5, 2026
…m dialog

`revokeAll` awaits a confirmation dialog and then read `userId` from the
store, defaulting to `undefined` when absent. The template only renders the
control while a user is present, but the await is a window: a logout or an
expired session while the dialog is open clears the store, and every filter
below then widens to "no subject".

That matters because the server force-scopes only callers WITHOUT the
relevant permission. An administrator holds it, so an unscoped call from
their own account page would revoke the application's consent rows, and now
its tokens, for every user.

The subject is captured once after the dialog resolves and the handler bails
when it is gone.

Also adds the session-token coverage the resource was missing: a
non-privileged reader is scoped to its own sessions (the path that fails open
if the injected ownership condition ever stops resolving), a cross-subject
bulk revoke leaves the other subject's rows untouched, the unconditional
session join survives `include=session` / `include=client`, and the typed
client's array filter serializes as the console sends it.
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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

🤖 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/core/entities/session-token/service.ts`:
- Around line 284-295: Update SessionTokenService.hasTargetCondition to require
an equality-style operator for target fields id, sessionId, and clientId, rather
than accepting every operator. Explicitly reject empty array values such as $in:
[] while preserving recursive filter-group handling and valid non-empty equality
targets.

In `@apps/server-core/test/unit/http/controllers/entities/session-token.spec.ts`:
- Around line 192-201: Update buildTwoAppSession to return firstSecret and
secondSecret, then replace the permissive refresh assertions with strict checks:
verify the untouched application successfully refreshes using firstSecret and
verify the revoked application’s refresh attempt using secondSecret fails.
Remove the catch that converts failures to undefined and assert the revoked
flow’s actual error outcome.
🪄 Autofix

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 Plus

Run ID: 4efa96ac-0e19-4273-bb88-8c0028def771

📥 Commits

Reviewing files that changed from the base of the PR and between 1aaa52b and 03e88f8.

📒 Files selected for processing (38)
  • .agents/architecture.md
  • .agents/references/authentik.md
  • apps/client-account-console/src/pages/applications.vue
  • apps/server-core/src/adapters/database/domains/session-token/entity.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/session-token/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/session-token/module.ts
  • apps/server-core/src/app/modules/database/repositories/schema-validation.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts
  • apps/server-core/src/core/entities/event/entity-event-handler.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/entities/session-token/index.ts
  • apps/server-core/src/core/entities/session-token/schema.ts
  • apps/server-core/src/core/entities/session-token/service.ts
  • apps/server-core/src/core/entities/session-token/types.ts
  • apps/server-core/src/core/oauth2/grant-types/authorize.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/query/module.ts
  • apps/server-core/test/unit/core/helpers/fake-session-token-repository.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/session-token.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts
  • docs/src/guide/deployment/account-console.md
  • 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-token/index.ts
  • packages/core-http-kit/src/domains/entities/session-token/module.ts
  • packages/core-http-kit/src/domains/entities/session-token/types.ts
  • packages/core-kit/src/domains/contstants.ts
  • packages/core-kit/src/domains/session-token/entity.ts
  • packages/core-kit/src/domains/types.ts
🚧 Files skipped from review as they are similar to previous changes (10)
  • apps/server-core/src/core/oauth2/grant-types/authorize.ts
  • apps/server-core/src/core/oauth2/token/issuer/access/module.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts
  • apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts
  • packages/core-kit/src/domains/session-token/entity.ts
  • docs/src/guide/deployment/account-console.md
  • apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts
  • .agents/references/authentik.md
  • .agents/architecture.md
  • apps/server-core/src/adapters/database/domains/session-token/entity.ts

@tada5hi

tada5hi commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews paused.

…voke

`hasTargetCondition` asked whether a target KEY appeared anywhere in the
filter tree. That is not the same question as whether the query is BOUNDED by
one, and the difference is a mass revoke:

- `filter[id]=!<uuid>` decodes to `ne` and selects every row but one.
- `filter[id]=~x` decodes to `endsWith`.
- `not(and(eq(id,'a'),eq(clientId,'b')))` keeps a compound `not` node whose
  inner leaves are ordinary `eq`, so a walker that recurses into every
  compound finds one and authorizes the complement.
- `or(eq(id,'a'),eq(kind,'access'))` names a target key in one branch while
  the other selects every access token.

The last two are reachable only through the expression dialect, since rapiq
collapses `not(eq(..))` into an `ne` leaf but leaves a negated conjunction
compound, and `or` has no bracket spelling.

The guard now asks about boundedness: `and` is bounded when any conjunct is,
`or` only when every branch is, `not` never, and a leaf only under `eq` or a
non-empty `in`.

This is inverted relative to the session bulk revoke it was modelled on:
there, failing the check falls back to the SELF-service path, so permissive
is the safe direction. Here, passing it IS the destructive path.

Also strictens two assertions that could not fail. The revoke test mapped
every refresh failure to `undefined` and then accepted either outcome, and
asserted only that an earlier grant had returned a refresh token. They now
assert that the untouched application refreshes and the revoked one is
rejected, which is what proves the feature works.

Reworded the migration docstrings: NULL means "not attributable to an
application" and covers both pre-existing rows and minting paths with no
client, rather than "never no client" as they claimed.
auth_sessions carries a nullable user_id AND a nullable client_id, and
SessionManager.create populates exactly one from `sub` according to
`subKind` (the same trick auth_consents uses). They are typed foreign keys
for a polymorphic subject, so ON DELETE CASCADE can drop a subject's own
sessions.

Three other writers were putting the APPLICATION into client_id on
user-subject sessions: the password grant, the MFA-login ticket, and the
authorize grant. That placed an unrelated id behind a cascade meaning "this
client owns this row", so deleting an application deleted a USER's session
and, through auth_session_tokens.session_id, every other application's
tokens riding it. Deleting the account console would have signed users out
of the admin console.

The column now has one meaning. The authorize grant leaves it alone, the
password grant and the ticket no longer set it, and the MFA-login completion
takes the client from the verified ticket payload, which already carries it,
rather than from the session row.

Which application authorized is auth_session_tokens.client_id, where a
session serving several applications can say so.

This also removes the write-once branch introduced earlier in this PR: with
no one writing the column, there is nothing to make idempotent.
@tada5hi

tada5hi commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 5, 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.

Actionable comments posted: 4

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

297-324: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The array-serialization claim is not covered by the assertions.

The comment states that the test proves an array of session ids serializes as a comma list. The assertions do not prove it. clientId is first.secondApp.id, and second uses a different client, so no row of second.sessionId can match the scope. An implementation that dropped every array element after the first would still pass this test.

Use the same client for both sessions, or assert on rows of second.sessionId with a client that appears in both.

♻️ Suggested strengthening
         expect(result.count).toBeGreaterThan(0);
 
         const revoked = await suite.dataSource
             .getRepository(SessionTokenEntity)
             .find({ where: { sessionId: first.sessionId } });
 
         for (const row of revoked) {
             if (row.clientId === first.secondApp.id) {
                 expect(row.revokedAt).not.toBeNull();
             } else {
                 expect(row.revokedAt).toBeNull();
             }
         }
+
+        // Proves the second array element stayed in scope.
+        const secondRows = await suite.dataSource
+            .getRepository(SessionTokenEntity)
+            .find({ where: { sessionId: second.sessionId } });
+        expect(secondRows.length).toBeGreaterThan(0);

Note: this additional assertion only works if a shared client serves both sessions. buildTwoAppSession currently creates fresh clients per call, so extend it to accept existing clients, or reuse one client across the two sessions.

🤖 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-token.spec.ts`
around lines 297 - 324, Strengthen the “revokes across several sessions through
the typed client” test by ensuring both sessions share the same client scope:
update buildTwoAppSession to accept existing clients or otherwise reuse first’s
client when creating second. Keep the sessionId array containing both session
IDs, and assert that rows for second.sessionId with the shared client are
revoked while non-matching rows remain unrevoked.
apps/server-core/src/core/entities/session-token/service.ts (1)

199-219: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

The bulk revoke loop is unbounded and fully sequential.

decodeQuery is limited to parameters: ['filters'], so pagination is dropped and findAllByQuery returns every matching row. A privileged caller who passes only filter[clientId]=<busy-app> loads all tokens for that client, then performs one permission evaluation and two awaited I/O calls per row in sequence. For a high-traffic client this holds the request thread for a long time.

Consider processing in batches and revoking each batch concurrently with a bounded concurrency, or cap the number of rows the repository returns per call.

🤖 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-token/service.ts` around lines 199
- 219, Update the bulk revoke flow around decodeQuery, findAllByQuery, and the
entity loop to avoid loading and processing an unbounded result set
sequentially. Preserve permission checks and counting while introducing
repository pagination or a fixed result cap, and process each batch with bounded
concurrency rather than awaiting every entity serially.
🤖 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 @.agents/references/authentik.md:
- Line 23: Correct the session attribution descriptions so user-subject sessions
keep auth_sessions.client_id null and application attribution exists only on
auth_session_tokens.client_id. In .agents/references/authentik.md:23 replace the
first-authorizing-client claim with client-subject FK semantics; in
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts:165-168
state that the user session remains client-less; at :215-216 remove the claim
that it retains the admin-console client; and in
docs/src/guide/deployment/account-console.md:27-30 state that the user session’s
clientId remains null.

In `@apps/client-account-console/src/pages/applications.vue`:
- Around line 196-209: Update the session revocation flow around
httpClient.session.getMany to page through all sessions rather than fetching
only the first 50. Repeatedly fetch batches, collect each batch’s IDs, and call
httpClient.sessionToken.deleteMany for each batch using the existing clientId
filter, stopping when no sessions remain.

In `@apps/server-core/src/adapters/database/domains/session-token/entity.ts`:
- Around line 46-51: Update the clientId column decorator in the session-token
entity to explicitly set type: 'uuid', preserving its existing name, nullable,
and default settings.

In
`@apps/server-core/src/adapters/http/controllers/entities/session-token/module.ts`:
- Around line 90-100: Update the session-token deletion flow around drop and
SessionTokenService.revoke so the returned entity includes the newly assigned
revokedAt value. Either have the service return the re-read row after
revocation, or stamp revokedAt on the object returned by revoke, while
preserving the existing 202 response contract.

---

Nitpick comments:
In `@apps/server-core/src/core/entities/session-token/service.ts`:
- Around line 199-219: Update the bulk revoke flow around decodeQuery,
findAllByQuery, and the entity loop to avoid loading and processing an unbounded
result set sequentially. Preserve permission checks and counting while
introducing repository pagination or a fixed result cap, and process each batch
with bounded concurrency rather than awaiting every entity serially.

In `@apps/server-core/test/unit/http/controllers/entities/session-token.spec.ts`:
- Around line 297-324: Strengthen the “revokes across several sessions through
the typed client” test by ensuring both sessions share the same client scope:
update buildTwoAppSession to accept existing clients or otherwise reuse first’s
client when creating second. Keep the sessionId array containing both session
IDs, and assert that rows for second.sessionId with the shared client are
revoked while non-matching rows remain unrevoked.
🪄 Autofix

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 Plus

Run ID: efa68bc8-ddd6-4c8f-8c64-c29cb62f61b8

📥 Commits

Reviewing files that changed from the base of the PR and between 1aaa52b and f1436aa.

📒 Files selected for processing (41)
  • .agents/architecture.md
  • .agents/references/authentik.md
  • apps/client-account-console/src/pages/applications.vue
  • apps/server-core/src/adapters/database/domains/session-token/entity.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/session-token/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/session-token/module.ts
  • apps/server-core/src/app/modules/database/repositories/schema-validation.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts
  • apps/server-core/src/core/entities/event/entity-event-handler.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/entities/session-token/index.ts
  • apps/server-core/src/core/entities/session-token/schema.ts
  • apps/server-core/src/core/entities/session-token/service.ts
  • apps/server-core/src/core/entities/session-token/types.ts
  • apps/server-core/src/core/oauth2/grant-types/authorize.ts
  • apps/server-core/src/core/oauth2/grant-types/password.ts
  • apps/server-core/src/core/oauth2/mfa-login/module.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/query/module.ts
  • apps/server-core/test/unit/core/helpers/fake-session-token-repository.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/session-token.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize-session.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts
  • docs/src/guide/deployment/account-console.md
  • 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-token/index.ts
  • packages/core-http-kit/src/domains/entities/session-token/module.ts
  • packages/core-http-kit/src/domains/entities/session-token/types.ts
  • packages/core-kit/src/domains/contstants.ts
  • packages/core-kit/src/domains/session-token/entity.ts
  • packages/core-kit/src/domains/types.ts

Comment thread .agents/references/authentik.md Resolved
Comment on lines +46 to +51
@Column({
name: 'client_id',
nullable: true,
default: null,
})
clientId: Client['id'] | null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 4 'client_id|SessionTokenClientId' \
  apps/server-core/src/adapters/database/domains/session-token/entity.ts \
  apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts \
  apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts \
  apps/server-core/src/app/modules/database/repositories/schema-validation.ts

Repository: authup/authup

Length of output: 15397


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== session-token entity =="
cat -n apps/server-core/src/adapters/database/domains/session-token/entity.ts | sed -n '1,90p'

echo
echo "== client entity =="
rg -n -C 5 '`@Entity`|class Client|id:' apps/server-core/src/adapters/database/domains -g '*client*.ts' -g 'entity.ts' || true

echo
echo "== schema validation references =="
cat -n apps/server-core/src/app/modules/database/repositories/schema-validation.ts | sed -n '1,220p'

Repository: authup/authup

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Client entity =="
cat -n apps/server-core/src/adapters/database/domains/client/entity.ts | sed -n '31,38p'

echo
echo "== schema-validation file =="
wc -l apps/server-core/src/app/modules/database/repositories/schema-validation.ts
cat -n apps/server-core/src/app/modules/database/repositories/schema-validation.ts | sed -n '1,260p'

echo
echo "== TypeORM version/package references =="
for f in package.json apps/server-core/package.json; do
  if [ -f "$f" ]; then
    echo "-- $f"
    node -e "const p=require('./$f'); console.log({dependencies:p.dependencies?.typeorm, devDependencies:p.devDependencies?.typeorm})" 2>/dev/null || true
  fi
done

echo
echo "== local TypeScript/TypeORM available? =="
node - <<'JS'
try {
  const ts = require('typescript');
  const typeorm = require('typeorm');
  console.log(JSON.stringify({typescript: ts.version, typeorm: typeorm.VERSION}));
} catch (e) {
  console.log('node_modules may be missing: ' + String(e && e.code));
}
JS

Repository: authup/authup

Length of output: 6923


Set the postgres client_id column type to uuid.

auth_clients.id is generated as uuid, and the PostgreSQL migration creates auth_session_tokens.client_id as uuid. The current TypeORM inference may leave type: undefined, which can drift from the migration and break boot-time schema validation. Add type: 'uuid' to the client_id column decorator.

🤖 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/domains/session-token/entity.ts`
around lines 46 - 51, Update the clientId column decorator in the session-token
entity to explicitly set type: 'uuid', preserving its existing name, nullable,
and default settings.

@tada5hi

tada5hi commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews paused.

Two defects from review, plus the descriptions the subject-FK change left
stale.

The account console fetched one page of sessions before revoking, while the
consent deletion directly above loops. A user with more than the server's
page cap kept the application signed in on every session past the first page.
It now pages and revokes per batch, which also keeps the session id list out
of an unbounded query string.

Offset paging rather than the fetch-until-empty loop the consents use: those
rows are deleted as they are read, so that loop converges. Sessions survive
this operation, so the same shape would never terminate.

`SessionTokenService.delete` returned the entity as it was read, so the
response reported `revokedAt: null` for a token it had just revoked. The
revoke now stamps the in-memory row as well, and a test pins the response
body rather than only the database.

Corrected `.agents/references/authentik.md` and the account console
deployment guide, which still described `auth_sessions.client_id` as "the
client that first authorized". It is a subject foreign key and is null for a
user's session.
@tada5hi
tada5hi merged commit 6027f84 into master Aug 5, 2026
15 checks passed
@tada5hi
tada5hi deleted the feat/session-client-attribution branch August 5, 2026 11:55
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