Repository navigation
Conversation
|
Note Reviews pausedUse the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe 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. ChangesOAuth attribution contracts and storage
Authorization and token propagation
Account-console authentication flow
Client token state
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
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
authup
@authup/client-account-console
@authup/client-admin-console
@authup/client-auth-console
@authup/server-core
@authup/access
@authup/client-web-kit
@authup/client-web-kit-theme
@authup/client-web-nuxt
@authup/client-web-theme
@authup/core-http-kit
@authup/core-kit
@authup/core-realtime-kit
@authup/errors
@authup/i18n
@authup/kit
@authup/server-adapter-kit
@authup/server-adapter-node
@authup/server-adapter-socket-io
@authup/server-adapter-web
@authup/server-kit
@authup/server-test-kit
@authup/specs
commit: |
There was a problem hiding this comment.
Pull request overview
This PR 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_nameclaim to OAuth2 token payloads and plumb it through code issuance, grants, refresh rotation, and introspection → client-web-kit store. - Add
auth_session_tokens.client_idand persist token-level client attribution for access/refresh tokens; makeauth_sessions.client_idwrite-once (“first authorizing client”). - Update account-console gating logic + tests to force a silent
prompt=nonere-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()withPromise.resolve().then(...)can allow a transient render of the sign-in state beforeredirectingis set. Trigger the kick directly soredirectingflips 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()meansredirectingmay not be set in time to prevent a brief chooser render. Invokingkick()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.
| 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" | ||
| `); | ||
| } |
| 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\` | ||
| `); | ||
| } |
| const realmKey = store.realmId || realmHint.value; | ||
| if (realmKey) { | ||
| kicked.value = true; | ||
| Promise.resolve().then(() => kick(realmKey)); | ||
| } |
| @Column({ | ||
| name: 'client_id', | ||
| nullable: true, | ||
| default: null, | ||
| }) | ||
| clientId: Client['id'] | null; |
There was a problem hiding this comment.
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 winAdd 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 incommitSession().🤖 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 valueDocument 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 withlogin_required,consent_required, orinteraction_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 winAdd a case that pairs a matching session with a present silent-kick marker.
Branch 2 in
src/pages/index.vue(Line 297) requiresinteractionRequired,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.valueterm 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 winUse S256 PKCE in the session-continuity helper.
This helper sends
code_challenge: codeVerifierand the samecode_verifier, which is the insecureplainPKCE method. The account console path sendscode_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
📒 Files selected for processing (34)
.agents/architecture.md.agents/references/authentik.mdapps/client-account-console/package.jsonapps/client-account-console/src/pages/index.vueapps/client-account-console/src/silent-kick.tsapps/client-account-console/test/unit/pages/index.spec.tsapps/client-account-console/test/utils/index.tsapps/client-account-console/test/vitest.config.tsapps/server-core/src/adapters/database/domains/session-token/entity.tsapps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.tsapps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.tsapps/server-core/src/adapters/http/controllers/entities/identity-provider/module.tsapps/server-core/src/app/modules/oauth2/repositories/session-token/repository.tsapps/server-core/src/core/oauth2/authorization/code/issuer/module.tsapps/server-core/src/core/oauth2/authorization/code/issuer/types.tsapps/server-core/src/core/oauth2/authorization/module.tsapps/server-core/src/core/oauth2/grant-types/authorize.tsapps/server-core/src/core/oauth2/grant-types/client-credentials.tsapps/server-core/src/core/oauth2/grant-types/password.tsapps/server-core/src/core/oauth2/mfa-login/module.tsapps/server-core/src/core/oauth2/session-token/types.tsapps/server-core/src/core/oauth2/token/issuer/access/module.tsapps/server-core/src/core/oauth2/token/issuer/refresh/module.tsapps/server-core/test/unit/core/helpers/fake-session-token-repository.tsapps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/id-token-claims.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.tsdocs/src/guide/deployment/account-console.mdpackages/client-web-kit/src/core/store/create.tspackages/client-web-kit/test/unit/core/store/client-name.spec.tspackages/core-kit/src/domains/authorization-code/entity.tspackages/core-kit/src/domains/session-token/entity.tspackages/specs/src/oauth2/types.ts
| @Column({ | ||
| name: 'client_id', | ||
| nullable: true, | ||
| default: null, | ||
| }) | ||
| clientId: Client['id'] | null; |
There was a problem hiding this comment.
🗄️ 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))))
PYRepository: 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')
PYRepository: 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');
JSRepository: 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:
- 1: https://typeorm.io/docs/getting-started/
- 2: docs: add column type inference explanation typeorm/typeorm#12317
- 3: https://typeorm.io/docs/drivers/mysql.md
- 4: https://typeorm.io/docs/drivers/postgres/
- 5: https://typeorm.io/docs/drivers/postgres.md
- 6: https://typeorm.io/docs/entity/entities/
- 7: Store UUIDs as binary in MySQL typeorm/typeorm#10542
- 8: @Column({ type: "uuid" }) should be varchar(36) on MySQL instead of varchar(255) typeorm/typeorm#7228
- 9: Set @Column() default db type for string properties to 'text' instead of 'varchar' typeorm/typeorm#7979
🌐 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:
- 1: uuid column type differs between the mysql and aurora-data-api (mysql) drivers typeorm/typeorm#8286
- 2: typeorm/typeorm@1588c58
- 3: feat: use char(36) for uuid representation in mysql typeorm/typeorm#7853
- 4: @Column({ type: "uuid" }) should be varchar(36) on MySQL instead of varchar(255) typeorm/typeorm#7228
- 5: Store UUIDs as binary in MySQL typeorm/typeorm#10542
- 6: https://typeorm.io/docs/drivers/mysql.md
🌐 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:
- 1: https://typeorm.io/docs/help/decorator-reference.md
- 2: https://typeorm.io/docs/help/decorator-reference/
- 3: https://typeorm.io/docs/entity/entities/
- 4: https://typeorm.io/docs/entity/entities.md
- 5: https://typeorm.io/docs/drivers/postgres.md
- 6: https://typeorm.io/docs/drivers/postgres/
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: addtype: 'uuid'to the@Columnoptions.apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts#L29-31: changevarchar(255)to the MySQL width used by the existing UUID FK columns on this table, so the FK column matches the referencedauth_clients.id.apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts#L28-45: keepuuid, 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-L31apps/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.
| await queryRunner.query(` | ||
| ALTER TABLE \`auth_session_tokens\` ADD \`client_id\` varchar(255) NULL | ||
| `); |
There was a problem hiding this comment.
🗄️ 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 -250Repository: 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 -220Repository: 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.
|
@coderabbitai pause |
✅ Action performedReviews 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.
29d7252 to
8363794
Compare
Problem
auth_sessions.client_idwas the only per-application attribution, andresolveSessionoverwrote 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.
What the reference implementations do
Authentik's
AuthenticatedSessionis one per browser and carries no application or provider field; the link sits onBaseGrantModel, inherited byAuthorizationCode,AccessTokenandRefreshToken. Keycloak pairs oneUserSessionModelper browser login with per-clientAuthenticatedClientSessionModelchildren.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 toauth_clients,ON DELETE CASCADE, mirroringauth_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_idis now write-once — set only while still null, so it means "the client that first authorized on this session".Breaking change
auth_sessions.client_idnow names the client that first authorized on a session rather than the most recent one, soGET/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 filterauth_session_tokens.client_idinstead — 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_idalone is correct only for single-RP sessions; approximating from consent rows under-notifies, because consent is skipped forbuiltInclients, so neither console would ever be told.Verification
check:types(test-inclusive) and ESLint clean.migrationstable at full revert.createSchemaBuilder().log()) on both dialects:client_idproduces no column statement on either, so the migration matches TypeORM's metadata. Note this contradicts a review suggestion to usevarchar(36)on MySQL —auth_sessions.client_idisvarchar(255)there (1766830857009-Default.ts), andvarchar(36)would introduce drift.session-token-attribution.spec.tspins the core case: two applications on one browser session leavesession.clientIdat the first while each application's token rows carry their own.