Skip to content

feat!: attribute issued tokens to the client they were issued for - #3400

Closed
tada5hi wants to merge 1 commit into
masterfrom
feat/account-console-session-binding
Closed

tada5hi wants to merge 1 commit into
masterfrom
feat/account-console-session-binding

Conversation

@tada5hi

@tada5hi tada5hi commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Scope reduced. This PR originally also carried a client-side gate (a client_name token claim, a kit store ref, and an account-console check that re-minted a foreign session through a silent prompt=none flow). That was detection layered on top of a sharing problem: every surface on the IdP origin uses one set of cookies, so the account console could hold another application's tokens at all. Namespacing the store cookies per client removes the sharing outright, so the gate is unnecessary. That work moves to a follow-up; this PR keeps only the server-side attribution, which is needed either way.

Problem

auth_sessions.client_id was the only per-application attribution, and resolveSession overwrote it on every authorize that reused a session:

existing.clientId = authorizationCode.client_id || null;

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.

What the reference implementations do

Authentik's AuthenticatedSession is one per browser and carries no application or provider field; the link sits on BaseGrantModel, inherited by AuthorizationCode, AccessToken and RefreshToken. Keycloak pairs one UserSessionModel per browser login with per-client AuthenticatedClientSessionModel children.

Neither creates sibling sessions per application. Both keep the browser session client-agnostic and derive per-application facts one level down. authup already had that two-level structure in auth_session_tokens; it simply had no client column. Recorded in .agents/references/authentik.md.

Changes

  • auth_session_tokens.client_id — nullable FK to auth_clients, ON DELETE CASCADE, mirroring auth_sessions.client_id. Both issuers stamp it from the same 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 is now write-once — set only while still null, so it means "the client that first authorized on this session".
  • Migration for both dialects.

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 — that is #3401, stacked on this branch.

Unblocks

This column 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, because consent is skipped for builtIn clients, so neither console would ever be told.

Verification

  • Build 24/24 projects; check:types (test-inclusive) and ESLint clean.
  • server-core 180/180 files, 2003 tests. core-kit and client-web-kit green.
  • 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 on either, so the migration matches TypeORM's metadata. Note this contradicts a 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.
  • New session-token-attribution.spec.ts pins the core case: two applications on one browser session leave session.clientId at the first while each application's token rows carry their own.

Copilot AI lite review requested due to automatic review settings August 5, 2026 06:43
@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 per-token client attribution across OAuth flows, preserves first-authorizing client ownership on reused sessions, and updates the account console to silently obtain its own token with guarded interactive escalation.

Changes

OAuth attribution contracts and storage

Layer / File(s) Summary
Attribution contracts and storage
packages/core-kit/..., packages/specs/..., apps/server-core/src/adapters/database/..., apps/server-core/src/core/oauth2/session-token/...
Session tokens and OAuth authorization codes now carry nullable client attribution. Database entities and MySQL/Postgres migrations add auth_session_tokens.client_id with cascading client deletion.

Authorization and token propagation

Layer / File(s) Summary
Authorization and token propagation
apps/server-core/src/adapters/http/..., apps/server-core/src/core/oauth2/..., apps/server-core/test/unit/core/..., apps/server-core/test/unit/http/...
Authorization flows persist client_name, token grants propagate client claims, token rows record clientId, and reused sessions retain their first client. Tests cover grants, refresh rotation, MFA, and multiple applications.

Account-console authentication flow

Layer / File(s) Summary
Account-console authentication flow
apps/client-account-console/src/..., apps/client-account-console/test/..., docs/src/guide/deployment/account-console.md, .agents/...
The account console checks session client matching, uses silent prompt=none authorization, escalates once to interactive login, supports realm deep links, and preserves redirect state.

Client token state

Layer / File(s) Summary
Client token state
packages/client-web-kit/src/core/store/create.ts, packages/client-web-kit/test/unit/core/store/client-name.spec.ts
The web-kit store exposes clientName, updates it from matching introspection results, and clears it on logout.

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

Sequence Diagram(s)

sequenceDiagram
  participant AccountConsole
  participant AuthorizationServer
  participant SessionTokenStore
  AccountConsole->>AuthorizationServer: request silent account-console authorization
  AuthorizationServer->>SessionTokenStore: reuse existing session
  SessionTokenStore-->>AuthorizationServer: retain original session client
  AuthorizationServer->>SessionTokenStore: create account-console token attribution
  SessionTokenStore-->>AccountConsole: return account-console token
Loading

Possibly related PRs

  • authup/authup#3373: Introduces the account-console authentication flow extended by this change.
  • authup/authup#3191: Modifies OAuth authorization-code session reuse and client attribution.
  • authup/authup#3203: Adds OAuth prompt=none behavior used by silent account-console reauthentication.

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.00% 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 change: attributing issued tokens to their target client.
✨ 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/account-console-session-binding

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

@authup/client-account-console

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

@authup/client-admin-console

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

@authup/client-auth-console

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

@authup/server-core

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

@authup/access

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

@authup/client-web-kit

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

@authup/client-web-kit-theme

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

@authup/client-web-nuxt

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

@authup/client-web-theme

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

@authup/core-http-kit

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

@authup/core-kit

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

@authup/core-realtime-kit

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

@authup/errors

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

@authup/i18n

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

@authup/kit

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

@authup/server-adapter-kit

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

@authup/server-adapter-node

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

@authup/server-adapter-socket-io

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

@authup/server-adapter-web

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

@authup/server-kit

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

@authup/server-test-kit

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

@authup/specs

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

commit: 8363794

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 fixes cross-console session reuse by moving per-application attribution from the browser session row onto individual token rows, and by teaching the account console to verify that an existing session’s token was minted for its own OAuth2 client before rendering.

Changes:

  • Add a best-effort client_name claim to OAuth2 token payloads and plumb it through code issuance, grants, refresh rotation, and introspection → client-web-kit store.
  • Add auth_session_tokens.client_id and persist token-level client attribution for access/refresh tokens; make auth_sessions.client_id write-once (“first authorizing client”).
  • Update account-console gating logic + tests to force a silent prompt=none re-mint when arriving with a foreign-console session, with a bounded escalation mechanism.

Reviewed changes

Copilot reviewed 34 out of 34 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
packages/specs/src/oauth2/types.ts Adds client_name claim to the token payload type.
packages/core-kit/src/domains/session-token/entity.ts Extends session-token domain type with clientId.
packages/core-kit/src/domains/authorization-code/entity.ts Persists client_name on authorization code entities.
packages/client-web-kit/test/unit/core/store/client-name.spec.ts Adds unit coverage for mapping client_name into the store.
packages/client-web-kit/src/core/store/create.ts Stores clientName from introspection with token-currency guard.
docs/src/guide/deployment/account-console.md Updates deployment docs to describe silent re-mint + per-token attribution.
apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts Adds server tests for per-token client_id attribution behavior.
apps/server-core/test/unit/http/controllers/workflows/token/id-token-claims.spec.ts Adds tests asserting client_name emission/absence across flows (incl. MFA completion).
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts Validates shared-session continuity + per-token attribution across admin/account consoles.
apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts Tests write-once session client behavior when reusing a session across clients.
apps/server-core/test/unit/core/helpers/fake-session-token-repository.ts Updates fake repo to persist clientId.
apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts Persists refresh token rows with clientId from payload.
apps/server-core/src/core/oauth2/token/issuer/access/module.ts Persists access token rows with clientId from payload.
apps/server-core/src/core/oauth2/session-token/types.ts Extends session-token create input with optional clientId.
apps/server-core/src/core/oauth2/mfa-login/module.ts Documents intentional omission of client_name on MFA completion path.
apps/server-core/src/core/oauth2/grant-types/password.ts Stamps client_name when password grant has the client entity.
apps/server-core/src/core/oauth2/grant-types/client-credentials.ts Stamps client_name for client_credentials tokens.
apps/server-core/src/core/oauth2/grant-types/authorize.ts Stamps client_name from authorization code; makes session clientId write-once.
apps/server-core/src/core/oauth2/authorization/module.ts Passes client name into code issuance for later token stamping.
apps/server-core/src/core/oauth2/authorization/code/issuer/types.ts Adds clientName option for code issuer.
apps/server-core/src/core/oauth2/authorization/code/issuer/module.ts Persists client_name onto issued codes.
apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts Writes clientId to DB rows on session-token create.
apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts Hoists resolved client entity so federated flow can stamp client_name.
apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts Adds auth_session_tokens.client_id FK in Postgres.
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts Adds auth_session_tokens.client_id FK in MySQL.
apps/server-core/src/adapters/database/domains/session-token/entity.ts Adds clientId column + FK relation to the session-token entity.
apps/client-account-console/test/vitest.config.ts Enables Vue SFC compilation + dedupe/aliases for account-console unit tests.
apps/client-account-console/test/utils/index.ts Adds mount harness to assert redirects and gate behavior in happy-dom.
apps/client-account-console/test/unit/pages/index.spec.ts Adds page-level tests for gating, silent flow, escalation, and ref handling.
apps/client-account-console/src/silent-kick.ts Implements single-use sessionStorage marker to bound escalation behavior.
apps/client-account-console/src/pages/index.vue Gates shell on client_name, triggers silent re-mint + bounded escalation.
apps/client-account-console/package.json Adds @vue/test-utils dev dependency for new unit tests.
.agents/references/authentik.md Updates reference notes to reflect session/token attribution alignment.
.agents/architecture.md Updates architecture documentation for plan 086 attribution and gating.
Suppressed comments (2)

apps/client-account-console/src/pages/index.vue:321

  • Same as above: deferring kick() with Promise.resolve().then(...) can allow a transient render of the sign-in state before redirecting is set. Trigger the kick directly so redirecting flips synchronously and the page stays on the spinner while the authorize URL is built.
                //     nothing is asked of a visitor who is already signed in.
                const realmKey = store.realmId;
                if (!sessionMatches.value && !exchanged.value && realmKey) {
                    kicked.value = true;
                    Promise.resolve().then(() => kick(realmKey, OAuth2AuthorizationPrompt.NONE));
                }

apps/client-account-console/src/pages/index.vue:333

  • Same pattern here: using a deferred microtask for kick() means redirecting may not be set in time to prevent a brief chooser render. Invoking kick() directly keeps the render state consistent with the pending redirect.
            // 4b. No session: a deep link names its realm, anything else
            //     falls through to the chooser.
            if (unauthenticated.value && realmHint.value) {
                const hint = realmHint.value;

                kicked.value = true;
                Promise.resolve().then(() => kick(hint));
            }

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

Comment on lines +28 to +45
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE "auth_session_tokens" ADD "client_id" uuid
`);
await queryRunner.query(`
ALTER TABLE "auth_session_tokens"
ADD CONSTRAINT "FK_auth_session_tokens_client_id" FOREIGN KEY ("client_id") REFERENCES "auth_clients"("id") ON DELETE CASCADE ON UPDATE NO ACTION
`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE "auth_session_tokens" DROP CONSTRAINT "FK_auth_session_tokens_client_id"
`);
await queryRunner.query(`
ALTER TABLE "auth_session_tokens" DROP COLUMN "client_id"
`);
}
Comment on lines +28 to +45
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE \`auth_session_tokens\` ADD \`client_id\` varchar(255) NULL
`);
await queryRunner.query(`
ALTER TABLE \`auth_session_tokens\`
ADD CONSTRAINT \`FK_auth_session_tokens_client_id\` FOREIGN KEY (\`client_id\`) REFERENCES \`auth_clients\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION
`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE \`auth_session_tokens\` DROP FOREIGN KEY \`FK_auth_session_tokens_client_id\`
`);
await queryRunner.query(`
ALTER TABLE \`auth_session_tokens\` DROP COLUMN \`client_id\`
`);
}
Comment on lines +298 to +302
const realmKey = store.realmId || realmHint.value;
if (realmKey) {
kicked.value = true;
Promise.resolve().then(() => kick(realmKey));
}
Comment on lines +46 to +51
@Column({
name: 'client_id',
nullable: true,
default: null,
})
clientId: Client['id'] | null;

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
packages/client-web-kit/test/unit/core/store/client-name.spec.ts (1)

76-91: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a stale-introspection regression test.

This test covers a normal re-mint only. Start introspection for token A, replace the access token with token B before the response completes, and assert that token A cannot set clientName. This protects the token-currency check in commitSession().

🤖 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 `@packages/client-web-kit/test/unit/core/store/client-name.spec.ts` around
lines 76 - 91, Add a regression test near the existing client-name re-mint test
that begins resolving token A, replaces it with token B before token A’s
introspection completes, then completes the stale response and asserts it cannot
update store.clientName. Exercise the token-currency behavior in commitSession()
and retain the expected client name for the current token.
docs/src/guide/deployment/account-console.md (1)

29-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document the escalation from an unsatisfiable silent attempt.

Lines 31-32 state the silent hop "asks nothing of the visitor". That holds only when the server can satisfy prompt=none. If the server answers with login_required, consent_required, or interaction_required, the console escalates once to an interactive authorize request, and the visitor then sees the hosted login. Add that outcome so operators can predict the second redirect.

📝 Proposed documentation addition
 A visitor who arrives holding a session issued to a *different* application
 (the admin console, for example, which shares the IdP origin) is sent through
 a silent `prompt=none` code flow first, so the surface always runs on a token
 of its own. That costs one extra redirect and asks nothing of the visitor.
+If the server cannot satisfy the silent request (`login_required`,
+`consent_required`, or `interaction_required`), the surface escalates once to
+an interactive authorize request and the hosted login appears.
 Attribution is per token: `auth_session_tokens.client_id` names the
 `account-console` client for those tokens, while the session row keeps the
 client that first authorized on it.
🤖 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 `@docs/src/guide/deployment/account-console.md` around lines 29 - 35, Update
the silent prompt=none flow description to state that when the server returns
login_required, consent_required, or interaction_required, the console performs
one interactive authorize escalation and the visitor sees the hosted login,
while retaining the existing no-interaction behavior for satisfiable silent
requests.
apps/client-account-console/test/unit/pages/index.spec.ts (1)

232-244: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case that pairs a matching session with a present silent-kick marker.

Branch 2 in src/pages/index.vue (Line 297) requires interactionRequired, silentKickReturn, and !sessionMatches. The suite covers marker-present + mismatch (Line 175) and marker-absent + match (Line 232). It does not cover marker-present + match. If the !sessionMatches.value term were removed, a visitor holding a valid account-console session plus a stale marker would be redirected out of the shell, and every current test would still pass.

💚 Proposed additional case
     it('should keep rendering a matching session when an error param is supplied', async () => {
         // The pointed version of the case above: the visitor's own session is
         // fine, and a supplied marker must not bounce them out of the shell.
         const shell = await mountAccountShell({
             clientName: CLIENT_ACCOUNT_CONSOLE_NAME,
             query: { error: OAuth2ErrorCode.LOGIN_REQUIRED },
         });
         await shell.signIn();
         await shell.settle();
 
         expect(shell.wrapper.findComponent(AAccountShell).exists()).toBeTruthy();
         expect(shell.redirects).toHaveLength(0);
     });
+
+    it('should not escalate a matching session even with a silent-kick marker', async () => {
+        // The silent attempt succeeded and the error param is stale. The
+        // session names this console, so there is nothing to re-mint.
+        saveSilentKick();
+
+        const shell = await mountAccountShell({
+            clientName: CLIENT_ACCOUNT_CONSOLE_NAME,
+            query: { error: OAuth2ErrorCode.LOGIN_REQUIRED },
+        });
+        await shell.signIn();
+        await shell.settle();
+
+        expect(shell.wrapper.findComponent(AAccountShell).exists()).toBeTruthy();
+        expect(shell.redirects).toHaveLength(0);
+    });
🤖 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/client-account-console/test/unit/pages/index.spec.ts` around lines 232 -
244, Add a unit test in the account shell session-handling suite that combines a
valid matching session with the silent-kick/error marker, using the existing
shell setup helpers and assertions. Verify the account shell still renders and
no redirect occurs, covering the `interactionRequired` plus `silentKickReturn`
path while preserving the `sessionMatches` requirement.
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts (1)

82-105: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use S256 PKCE in the session-continuity helper.

This helper sends code_challenge: codeVerifier and the same code_verifier, which is the insecure plain PKCE method. The account console path sends code_challenge_method=S256; make the test exercise the S256 flow as well.

🤖 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 82 - 105, Update the authorization request in the
session-continuity helper to use the S256 PKCE challenge: transform codeVerifier
into its SHA-256 base64url-encoded challenge and include the corresponding
code_challenge_method value, while continuing to pass the original codeVerifier
to createWithAuthorizationCode.
🤖 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/adapters/database/domains/session-token/entity.ts`:
- Around line 46-51: Align clientId’s physical type across the entity and both
migrations: in
apps/server-core/src/adapters/database/domains/session-token/entity.ts#L46-L51,
add the explicit uuid column type; in
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts#L29-L31,
replace varchar(255) with the existing MySQL UUID width used by this table’s
referenced FK columns; and in
apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts#L28-L45,
retain the uuid definition.

In
`@apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts`:
- Around line 29-31: Update the client_id column definition added by the
SessionTokenClientId migration to use varchar(36), matching
auth_sessions.client_id, while preserving its nullable and foreign-key behavior.

---

Nitpick comments:
In `@apps/client-account-console/test/unit/pages/index.spec.ts`:
- Around line 232-244: Add a unit test in the account shell session-handling
suite that combines a valid matching session with the silent-kick/error marker,
using the existing shell setup helpers and assertions. Verify the account shell
still renders and no redirect occurs, covering the `interactionRequired` plus
`silentKickReturn` path while preserving the `sessionMatches` requirement.

In
`@apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts`:
- Around line 82-105: Update the authorization request in the session-continuity
helper to use the S256 PKCE challenge: transform codeVerifier into its SHA-256
base64url-encoded challenge and include the corresponding code_challenge_method
value, while continuing to pass the original codeVerifier to
createWithAuthorizationCode.

In `@docs/src/guide/deployment/account-console.md`:
- Around line 29-35: Update the silent prompt=none flow description to state
that when the server returns login_required, consent_required, or
interaction_required, the console performs one interactive authorize escalation
and the visitor sees the hosted login, while retaining the existing
no-interaction behavior for satisfiable silent requests.

In `@packages/client-web-kit/test/unit/core/store/client-name.spec.ts`:
- Around line 76-91: Add a regression test near the existing client-name re-mint
test that begins resolving token A, replaces it with token B before token A’s
introspection completes, then completes the stale response and asserts it cannot
update store.clientName. Exercise the token-currency behavior in commitSession()
and retain the expected client name for the current token.
🪄 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: 712018fc-0161-4e6d-b8ec-6e7a11b0557c

📥 Commits

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

📒 Files selected for processing (34)
  • .agents/architecture.md
  • .agents/references/authentik.md
  • apps/client-account-console/package.json
  • apps/client-account-console/src/pages/index.vue
  • apps/client-account-console/src/silent-kick.ts
  • apps/client-account-console/test/unit/pages/index.spec.ts
  • apps/client-account-console/test/utils/index.ts
  • apps/client-account-console/test/vitest.config.ts
  • 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/identity-provider/module.ts
  • apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts
  • apps/server-core/src/core/oauth2/authorization/code/issuer/module.ts
  • apps/server-core/src/core/oauth2/authorization/code/issuer/types.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/src/core/oauth2/grant-types/authorize.ts
  • apps/server-core/src/core/oauth2/grant-types/client-credentials.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/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/id-token-claims.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts
  • docs/src/guide/deployment/account-console.md
  • packages/client-web-kit/src/core/store/create.ts
  • packages/client-web-kit/test/unit/core/store/client-name.spec.ts
  • packages/core-kit/src/domains/authorization-code/entity.ts
  • packages/core-kit/src/domains/session-token/entity.ts
  • packages/specs/src/oauth2/types.ts

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Compare the declared column type for auth_sessions.client_id and other uuid FKs across both dialect migrations.
set -euo pipefail

fd -t f . apps/server-core/src/adapters/database/migrations --exec rg -n -C 2 'client_id' {}

echo '--- uuid columns on auth_session_tokens ---'
fd -t f . apps/server-core/src/adapters/database/migrations --exec rg -n 'auth_session_tokens' {}

echo '--- entity column declarations ---'
fd -t f entity.ts apps/server-core/src/adapters/database/domains --exec rg -n -B 2 -A 6 "name: 'client_id'" {}

Repository: authup/authup

Length of output: 38427


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- entity auth SessionTokenEntity client_id declarations ---'
fd -t f 'entity.ts$' apps/server-core/src/adapters/database/domains/session-token | while read -r f; do
  echo "FILE: $f"
  rg -n -B 4 -A 6 "name: 'client_id'|\\"client_id\\"|clientId:" "$f" || true
done

echo '--- session token entity uuid/type columns ---'
fd -t f 'entity.ts$' apps/server-core/src/adapters/database/domains/session-token | while read -r f; do
  echo "FILE: $f"
  rg -n -B 2 -A 2 "type: 'uuid'|sessionId:|parentId:|client_id" "$f" || true
done

echo '--- package TypeORM version ---'
if [ -f package-lock.json ]; then
  node - <<'JS'
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('package-lock.json','utf8'));
for (const [k,v] of Object.entries(pkg.packages || {})) {
  if (k.endsWith('node_modules/typeorm')) {
    console.log(k, v.version);
  }
}
JS
else
  echo 'no package-lock.json'
fi

echo '--- deterministic parser check: SessionTokenClientId migration column types ---'
python3 - <<'PY'
from pathlib import Path
import re
for path in [
    Path('apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts'),
    Path('apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts'),
]:
    text = path.read_text()
    matches = re.findall(r'ADD\s+["`]client_id["`]\s+([a-zA-Z0-9]+)', text, flags=re.I)
    print(f'{path}: {matches}')
PY

echo '--- deterministic parser check: entity type option ---'
python3 - <<'PY'
from pathlib import Path
import re
for path in Path('apps/server-core/src/adapters/database/domains/session-token').rglob('entity.ts'):
    text = path.read_text()
    block = re.search(r'`@Column`\(\{[\s\S]*?\}\)\s+\n?\s*clientId:', text)
    print(f'FILE: {path}')
    if not block:
        print(block)
        continue
    m = re.search(r'name:\s*[\'"\'`]client_id[\'"\'`]([\s\S]*?)clientId:', block.group(0))
    if not m:
        print(m)
        continue
    print(m.group(0))
    print('contains type uuid:', bool(re.search(r'\btype:\s*[\'"]uuid[\'"]', m.group(1))))
    print('contains type varchar/char:', bool(re.search(r'\btype:\s*[\'"][^\'"]*(varchar|character)', m.group(1))))
PY

Repository: authup/authup

Length of output: 2469


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- session token entity file ---'
cat -n apps/server-core/src/adapters/database/domains/session-token/entity.ts

echo '--- MySQL uuid column widths in the same migration package ---'
python3 - <<'PY'
from pathlib import Path
import re
for p in Path('apps/server-core/src/adapters/database/migrations').rglob('*.ts'):
    if '1785871780234-SessionTokenClientId' in p.name or 'auth_session_tokens' not in p.read_text(errors='ignore'):
        continue
    text = p.read_text(errors='ignore')
    for m in re.finditer(r'varchar\((\d+)\)\s*NULL', text):
        if p.name.startswith('17'):
            print(f'{p}:{span(m)[0]}={m.group(1)}')
PY

echo '--- exact session_id/client_id/parent_id TypeORM options ---'
python3 - <<'PY'
from pathlib import Path
for p in Path('apps/server-core/src/adapters/database/domains/session-token').rglob('*.ts'):
    text = p.read_text()
    for name in ('session_id', 'client_id', 'parent_id'):
        m = re.search(r'`@Column`\(\{[\s\S]*?name:\s*[\'\"]%s[\'\"][\s\S]*?\}\)\s+\n?\s*[^:]+:' % name, text)
        print(f'{p}: {name}')
        if m:
            block = m.group(0)
            decl = re.search(r'`@Column`\(\{[\s\S]*?\}\)\s+', block).group(0) if re.search(r'`@Column`\(\{[\s\S]*?\}\)\s+', block) else ''
            print(decl)
print('no match')
PY

Repository: authup/authup

Length of output: 4349


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- MySQL uuid column widths in migration packages ---'
python3 - <<'PY'
import re
from pathlib import Path
for p in Path('apps/server-core/src/adapters/database/migrations').rglob('*.ts'):
    text = p.read_text(errors='ignore')
    if 'auth_session_tokens' not in text or 'varchar(' not in text:
        continue
    for m in re.finditer(r'alter\s+table\s+`\s*auth_session_tokens\s*`\s+add\s+`\s*client_id\s*`\s+varchar\((\d+)\)\s+NULL', text, re.I):
        print(f"{p}:{m.start()}=varchar({m.group(1)})")
PY

echo '--- TypeORM TypeScript type default ---'
node - <<'JS'
const path = require.resolve('typeorm/browser/MetadataBuilder.js', { paths: [process.cwd(), '/tmp'] });
console.log(path);
const fs = require('fs');
const text = fs.readFileSync(path, 'utf8');
const m = text.match(new RegExp('getDefaultMetadataArgsMetadataColumn\\(([\s\\S]{1,800})\\.getDefaultMetadataArgsMetadataColumn'));
console.log(m ? m[1].match(/type[\\s\\S]{0,200}/m) : 'no match');
JS

Repository: authup/authup

Length of output: 1065


🌐 Web query:

TypeORM TypeScript string type defaults to varchar MySQL postgres uuid string type

💡 Result:

In TypeORM, the TypeScript string type is inferred as a varchar-like database type by default [1][2]. However, the exact mapping (including default lengths) is database-driver-specific and not globally consistent across all platforms [2]. Regarding UUIDs, TypeORM handles them distinctly depending on the configuration and database capabilities: 1. UUID Support: TypeORM supports a uuid column type [3][4][5]. When you use @PrimaryGeneratedColumn("uuid") or explicitly specify { type: "uuid" }, TypeORM attempts to use the database's native UUID support if available (e.g., PostgreSQL has a native uuid type) [6][4][7]. 2. MySQL and UUIDs: MySQL does not have a dedicated, native uuid column type in the same way PostgreSQL does [7]. Consequently, TypeORM's behavior in MySQL has evolved: - Historically, TypeORM mapped uuid types to varchar(36) [8][7]. - Newer versions or specific configurations may map them to char(36) or, via feature flags/configuration, to binary(16) for storage efficiency [8][7]. Because defaults can change between driver versions and are platform-dependent, it is best practice to explicitly define the column type in your entity when you require specific database behavior, such as using @Column("text"), @Column("varchar", { length: 255 }), or @Column("uuid") [1][9][2]. Relying on default inference may lead to unexpected schema migrations when upgrading dependencies [2].

Citations:


🌐 Web query:

TypeORM 1.1.0 mysql uuid type map varchar(36)

💡 Result:

In TypeORM, the mapping of the "uuid" column type to MySQL has historically fluctuated between varchar(36) and char(36) [1][2][3]. While there is no single, permanent enforcement, TypeORM generally defaults to using varchar(36) for uuid columns in MySQL [1][2]. Key context regarding this behavior: 1. Historical Context: TypeORM previously introduced a change to use char(36) for UUID representations in MySQL (as it is technically more suitable for fixed-length UUID strings) [3], but this change was subsequently reverted [2] due to compatibility concerns, returning the default to varchar(36) [1][2]. 2. Driver Differences: Different drivers for MySQL (e.g., the standard mysql driver vs. aurora-data-api) have historically exhibited inconsistencies in how they resolve the uuid type, with some defaulting to varchar(36) while others might vary [1]. 3. Configuration: You can explicitly control the database column type by using the type property in the @Column decorator if you prefer char(36) or another specific type [4]: @Column({ type: "char", length: 36 }) uuid: string; There is no dedicated UUID native data type in standard MySQL (unlike in PostgreSQL or MariaDB), which is why TypeORM maps it to a string-based type [5][6]. Some recent efforts have explored adding support for binary storage (binary(16)) to improve performance [5], but varchar(36) remains the common, safe default for string-based UUID storage [1][2].

Citations:


🌐 Web query:

TypeORM 1.1.0 Postgres uuid type string column uuid

💡 Result:

In TypeORM, you can define a column with the Postgres uuid type by explicitly specifying the type in the @Column decorator [1][2]. To define a uuid column in PostgreSQL, use the following syntax: @Column("uuid") uuid: string; If you need the UUID to be automatically generated, you have two primary options: 1. Primary Key Generation: Use @PrimaryGeneratedColumn("uuid") to create a primary key that is automatically populated with a UUID [3][4][1]. @PrimaryGeneratedColumn("uuid") id: string; 2. Standard Column Generation: Use the @Generated("uuid") decorator on a standard @Column to have TypeORM handle the generation of a UUID for that field upon insertion [3][4][2]. @Column("uuid") @Generated("uuid") uuid: string; When using PostgreSQL, TypeORM defaults to using the uuid-ossp extension to generate these values, though this can be configured to use pgcrypto if necessary [5][6].

Citations:


Align the physical type of the new auth_session_tokens.client_id column across the entity and both dialect migrations. client_id is a nullable FK into auth_clients.id, but the entity omits type, so TypeORM infers varchar. The Postgres migration already uses uuid; apply the same explicit uuid strategy to MySQL instead of varchar(255).

  • apps/server-core/src/adapters/database/domains/session-token/entity.ts#L46-L51: add type: 'uuid' to the @Column options.
  • apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts#L29-31: change varchar(255) to the MySQL width used by the existing UUID FK columns on this table, so the FK column matches the referenced auth_clients.id.
  • apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts#L28-45: keep uuid, matching the entity change.
📍 Affects 3 files
  • apps/server-core/src/adapters/database/domains/session-token/entity.ts#L46-L51 (this comment)
  • apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts#L29-L31
  • apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts#L28-L45
🤖 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, Align clientId’s physical type across the entity and both
migrations: in
apps/server-core/src/adapters/database/domains/session-token/entity.ts#L46-L51,
add the explicit uuid column type; in
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts#L29-L31,
replace varchar(255) with the existing MySQL UUID width used by this table’s
referenced FK columns; and in
apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts#L28-L45,
retain the uuid definition.

Comment on lines +29 to +31
await queryRunner.query(`
ALTER TABLE \`auth_session_tokens\` ADD \`client_id\` varchar(255) 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

echo "Repository npm scripts:"
if [ -f package.json ]; then
  node -e "const p=require('./package.json'); console.log(JSON.stringify(p.scripts,null,2))" | head -80
fi

echo
echo "Locate relevant migration files:"
fd -a '1785871780234-SessionTokenClientId\.ts|.*Session.*Client.*\.ts|.*session.*client.*\.ts' . | sed 's#^\./##' | head -100

echo
echo "Search for auth_session_tokens and auth_clients/client_id column definitions:"
rg -n "auth_session_tokens|auth_clients|SessionToken|client_id|PrimaryGeneratedColumn\\('uuid'\\)|PrimaryGeneratedColumn\\(\"uuid\"\\)|`@PrimaryGeneratedColumn`\\('uuid'\\)|`@PrimaryGeneratedColumn`\\(\"uuid\"\\)" apps/server-core -S | head -250

Repository: authup/authup

Length of output: 42105


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "List mysql migrations around auth_session_tokens/auth_sessions:"
fd -a 'migrations/mysql/.*\.ts$' apps/server-core/src/adapters/database | sort | sed -n '/1785871780234-SessionTokenClientId/,/1784460916000/p'

echo
echo "Read target migration and nearby mysql definitions:"
sed -n '1,80p' apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts
echo
sed -n '1,90p' apps/server-core/src/adapters/database/migrations/mysql/1783325495597-Default.ts
echo
sed -n '60,145p' apps/server-core/src/adapters/database/migrations/mysql/1673449341125-Default.ts
echo
rg -n "auth_sessions|auth_clients|auth_session_tokens|SESSIONS|CLIENTS|session_id|client_id" apps/server-core/src/adapters/database/migrations/mysql/1673449341125-Default.ts apps/server-core/src/adapters/database/migrations/mysql/1783325495597-Default.ts apps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.ts -S | head -220

Repository: authup/authup

Length of output: 21833


Match auth_session_tokens.client_id to auth_sessions.client_id.

MySQL creates auth_sessions.client_id as varchar(36), so this FK target should use the same width instead of varchar(255).

🤖 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 - 31, Update the client_id column definition added by the
SessionTokenClientId migration to use varchar(36), matching
auth_sessions.client_id, while preserving its nullable and foreign-key behavior.

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

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.
@tada5hi
tada5hi force-pushed the feat/account-console-session-binding branch from 29d7252 to 8363794 Compare August 5, 2026 07:35
@tada5hi tada5hi changed the title feat!: bind the account console to its own OAuth2 client feat!: attribute issued tokens to the client they were issued for Aug 5, 2026
@tada5hi

tada5hi commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #3403, which carries this work in a single PR. The stack was split while the design was still moving; #3403 also drops the account console's SSO-realm reader, which could not work (nothing writes that cookie) and is tracked as an open decision there.

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