@lenne.tech/nest-server 12.6.2 → 12.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/.claude/rules/better-auth.md +10 -2
  2. package/.claude/rules/configurable-features.md +3 -2
  3. package/.claude/rules/testing.md +7 -5
  4. package/CLAUDE.md +4 -0
  5. package/FRAMEWORK-API.md +2 -1
  6. package/dist/core/common/helpers/config.helper.js +26 -2
  7. package/dist/core/common/helpers/config.helper.js.map +1 -1
  8. package/dist/core/common/helpers/cookies.helper.js +0 -3
  9. package/dist/core/common/helpers/cookies.helper.js.map +1 -1
  10. package/dist/core/common/helpers/swagger-enabled.helper.d.ts +2 -0
  11. package/dist/core/common/helpers/swagger-enabled.helper.js +10 -0
  12. package/dist/core/common/helpers/swagger-enabled.helper.js.map +1 -0
  13. package/dist/core/common/helpers/swagger.helper.d.ts +1 -1
  14. package/dist/core/common/helpers/swagger.helper.js +10 -3
  15. package/dist/core/common/helpers/swagger.helper.js.map +1 -1
  16. package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
  17. package/dist/core/modules/ai/core-ai.controller.d.ts +1 -1
  18. package/dist/core/modules/ai/core-ai.controller.js +13 -3
  19. package/dist/core/modules/ai/core-ai.controller.js.map +1 -1
  20. package/dist/core/modules/ai/core-ai.resolver.d.ts +1 -1
  21. package/dist/core/modules/ai/core-ai.resolver.js +8 -3
  22. package/dist/core/modules/ai/core-ai.resolver.js.map +1 -1
  23. package/dist/core/modules/ai/services/core-ai-prompt.service.d.ts +3 -1
  24. package/dist/core/modules/ai/services/core-ai-prompt.service.js +3 -2
  25. package/dist/core/modules/ai/services/core-ai-prompt.service.js.map +1 -1
  26. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +7 -4
  27. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -1
  28. package/dist/index.d.ts +1 -0
  29. package/dist/index.js +1 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/main.js.map +1 -1
  32. package/docs/REQUEST-LIFECYCLE.md +9 -3
  33. package/migration-guides/12.5.x-to-12.6.x.md +10 -0
  34. package/migration-guides/12.6.x-to-12.7.x.md +307 -0
  35. package/migration-guides/12.7.0-to-12.7.1.md +99 -0
  36. package/package.json +1 -1
  37. package/src/core/common/helpers/config.helper.ts +58 -2
  38. package/src/core/common/helpers/cookies.helper.ts +13 -10
  39. package/src/core/common/helpers/swagger-enabled.helper.ts +33 -0
  40. package/src/core/common/helpers/swagger.helper.ts +30 -6
  41. package/src/core/common/interfaces/server-options.interface.ts +26 -5
  42. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +4 -1
  43. package/src/core/modules/ai/core-ai.controller.ts +18 -3
  44. package/src/core/modules/ai/core-ai.resolver.ts +14 -3
  45. package/src/core/modules/ai/services/core-ai-prompt.service.ts +11 -5
  46. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +2 -2
  47. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +24 -6
  48. package/src/core/modules/better-auth/core-better-auth.service.ts +1 -1
  49. package/src/core/modules/tus/README.md +2 -1
  50. package/src/index.ts +1 -0
  51. package/src/main.ts +3 -2
  52. package/migration-guides/12.6.1-to-12.6.2.md +0 -79
@@ -1698,9 +1698,11 @@ export interface IApiTokens {
1698
1698
  *
1699
1699
  * When cookies are enabled, the server:
1700
1700
  * - Loads `cookie-parser` middleware
1701
- * - Sets `credentials: true` in CORS configuration
1702
1701
  * - Sets signed httpOnly session cookies on authentication responses
1703
1702
  *
1703
+ * CORS answers the resolved origins with `credentials: true` in BOTH modes since 12.7.0 (`buildCorsConfig()`);
1704
+ * until then JWT mode got `*` without credentials.
1705
+ *
1704
1706
  * JWT authentication via `Authorization: Bearer` header works independently
1705
1707
  * of the cookie configuration — it is always available regardless of this setting.
1706
1708
  *
@@ -1741,8 +1743,8 @@ export interface ICookiesConfig {
1741
1743
  * - `{ allowedOrigins: [...] }`: Additional origins beyond `appUrl`/`baseUrl`
1742
1744
  * - `{ allowAll: true }`: Allow all origins (mirrors request origin — NOT recommended for production)
1743
1745
  *
1744
- * When cookies are enabled (default), CORS automatically includes `credentials: true`.
1745
- * Browsers reject `Access-Control-Allow-Origin: *` with credentials, so origins must
1746
+ * CORS includes `credentials: true` for the resolved origins — with cookies and, since 12.7.0, in JWT mode
1747
+ * (`cookies: false`) too. Browsers reject `Access-Control-Allow-Origin: *` with credentials, so origins must
1746
1748
  * be explicitly listed or `allowAll` must be set (which mirrors the request origin).
1747
1749
  *
1748
1750
  * @default undefined (enabled, origins auto-derived from appUrl/baseUrl)
@@ -3621,6 +3623,25 @@ export interface IServerOptions {
3621
3623
  */
3622
3624
  sync?: boolean | ISync;
3623
3625
 
3626
+ /**
3627
+ * Whether `setupSwagger()` serves the API documentation (12.7.0+), decided by `isSwaggerEnabled()`.
3628
+ *
3629
+ * | Value | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
3630
+ * |-------|------------------------|---------------------------------------------------------------|
3631
+ * | not set | served | **off** |
3632
+ * | `true` | served | served |
3633
+ * | `false` | off | off |
3634
+ *
3635
+ * Off mounts nothing: neither `/swagger` and `/swagger-api-tokens` nor `/api-docs-json` and
3636
+ * `/api-docs-api-tokens-json` (or the paths `setupSwagger()` was given) — they answer 404. Before 12.7.0 every
3637
+ * project that called `setupSwagger()` published its full API description on every stage. A value that is not a
3638
+ * boolean counts as not set. Environment variable: `NSC__SWAGGER=true`.
3639
+ *
3640
+ * @default undefined (served only in `local`, `ci` and `e2e`)
3641
+ * @since 12.7.0
3642
+ */
3643
+ swagger?: boolean;
3644
+
3624
3645
  /**
3625
3646
  * System setup configuration for initial admin creation.
3626
3647
  *
@@ -4186,8 +4207,8 @@ export interface ITusConfig {
4186
4207
  *
4187
4208
  * Unset, they come from the API's own CORS configuration — `buildCorsConfig()`, the function REST,
4188
4209
  * GraphQL and Better-Auth share (`appUrl`, `baseUrl`, `cors.allowedOrigins`, `cors.allowAll`).
4189
- * Without credentialed CORS configured (cookies off, or no origin resolvable) the tus server keeps
4190
- * its own default, `*`.
4210
+ * Without credentialed CORS configured (no origin resolvable) the tus server keeps its own default,
4211
+ * `*`. Since 12.7.0 JWT mode (`cookies: false`) gets the origin list too.
4191
4212
  *
4192
4213
  * The wildcard is what broke browser uploads with cookie authentication and separate app/API
4193
4214
  * origins before 11.42.1: a credentialed response with `Access-Control-Allow-Origin: *` is refused
@@ -161,7 +161,10 @@ ai: {
161
161
  permissions.
162
162
  - **User prompts ("Vorlagen"):** users author re-usable short prompts for themselves
163
163
  (private) or their tenant (public) via `aiPrompts` (`/ai/prompts`, `useLtAiPrompts`).
164
- Inserted into the chat input by a picker.
164
+ Inserted into the chat input by a picker. The list answers ENABLED prompts only — what the
165
+ picker offers; a management screen asks `GET /ai/prompts?includeDisabled=true` (GraphQL
166
+ `findAiPrompts(includeDisabled: true)`, 12.7.0), or a prompt saved with "enabled" off
167
+ disappears from it.
165
168
  - **Placeholders:** `{{placeholder}}` tokens in both system slots AND user prompts are
166
169
  resolved at run time by `CoreAiPlaceholderRegistry`. The current list is served via
167
170
  `GET /ai/placeholders` (`useLtAiPlaceholders`) — your slot/prompt editors should render
@@ -1,4 +1,5 @@
1
1
  import { Body, Controller, Delete, Get, Inject, Optional, Param, Post, Put, Query, Res } from '@nestjs/common';
2
+ import { ApiQuery } from '@nestjs/swagger';
2
3
  import type { Response } from 'express';
3
4
 
4
5
  import { RESTServiceOptions } from '../../common/decorators/rest-service-options.decorator.js';
@@ -580,11 +581,25 @@ export class CoreAiController {
580
581
  // User-facing user prompts ("Vorlagen") — own / tenant / global
581
582
  // ===================================================================================================================
582
583
 
583
- /** List user prompts visible to the current user (own + tenant + global). */
584
+ /**
585
+ * List user prompts visible to the current user (own + tenant + global). Enabled ones only — what the chat offers;
586
+ * `?includeDisabled=true` lists disabled ones too, for the management screen (12.7.0).
587
+ */
584
588
  @Get('prompts')
585
589
  @Roles(RoleEnum.S_USER)
586
- async findPrompts(@RESTServiceOptions() serviceOptions: ServiceOptions): Promise<CoreAiPrompt[]> {
587
- return this.promptService.listVisible(serviceOptions);
590
+ @ApiQuery({
591
+ description: 'Also list disabled prompts (for managing them); default: enabled prompts only',
592
+ name: 'includeDisabled',
593
+ required: false,
594
+ type: Boolean,
595
+ })
596
+ async findPrompts(
597
+ @RESTServiceOptions() serviceOptions: ServiceOptions,
598
+ @Query('includeDisabled') includeDisabled?: string,
599
+ ): Promise<CoreAiPrompt[]> {
600
+ return this.promptService.listVisible(serviceOptions, {
601
+ includeDisabled: includeDisabled === 'true' || includeDisabled === '1',
602
+ });
588
603
  }
589
604
 
590
605
  /** Create a user prompt for the current user / tenant (global requires admin). */
@@ -527,11 +527,22 @@ export class CoreAiResolver {
527
527
  // User-facing user prompts ("Vorlagen") — own / tenant / global
528
528
  // ===================================================================================================================
529
529
 
530
- /** List user prompts visible to the current user (own + tenant + global). */
530
+ /**
531
+ * List user prompts visible to the current user (own + tenant + global). Enabled ones only — what the chat offers;
532
+ * `includeDisabled: true` lists disabled ones too, for the management screen (12.7.0).
533
+ */
531
534
  @Query(() => [CoreAiPrompt], { description: 'List AI user prompts visible to the current user' })
532
535
  @Roles(RoleEnum.S_USER)
533
- async findAiPrompts(@GraphQLServiceOptions() serviceOptions: ServiceOptions): Promise<CoreAiPrompt[]> {
534
- return this.promptService.listVisible(serviceOptions);
536
+ async findAiPrompts(
537
+ @GraphQLServiceOptions() serviceOptions: ServiceOptions,
538
+ @Args('includeDisabled', {
539
+ description: 'Also list disabled prompts (for managing them); default: enabled prompts only',
540
+ nullable: true,
541
+ type: () => Boolean,
542
+ })
543
+ includeDisabled?: boolean,
544
+ ): Promise<CoreAiPrompt[]> {
545
+ return this.promptService.listVisible(serviceOptions, { includeDisabled: includeDisabled === true });
535
546
  }
536
547
 
537
548
  /** Create a user prompt for the current user / tenant (global requires admin). */
@@ -123,8 +123,15 @@ export class CoreAiPromptService extends CrudService<CoreAiPrompt, CoreAiPromptC
123
123
  /**
124
124
  * List prompts visible to the current user: own + tenant prompts of the
125
125
  * user's tenant. Ordered by `order` asc then `name`.
126
+ *
127
+ * Only enabled prompts by default — what the chat offers. `includeDisabled: true` (12.7.0) lists disabled ones too,
128
+ * for the management screen: without it a prompt saved with "enabled" switched off disappeared from the list and
129
+ * could no longer be edited or deleted. Visibility is the same either way.
126
130
  */
127
- async listVisible(serviceOptions: ServiceOptions = {}): Promise<CoreAiPrompt[]> {
131
+ async listVisible(
132
+ serviceOptions: ServiceOptions = {},
133
+ options: { includeDisabled?: boolean } = {},
134
+ ): Promise<CoreAiPrompt[]> {
128
135
  const user = serviceOptions?.currentUser;
129
136
  if (!user?.id) {
130
137
  return [];
@@ -135,10 +142,9 @@ export class CoreAiPromptService extends CrudService<CoreAiPrompt, CoreAiPromptC
135
142
  or.push({ scope: 'tenant', tenantId: String(tenantId) });
136
143
  }
137
144
  try {
138
- const rows = (await this.dataStore.find(
139
- { $or: or, enabled: { $ne: false } },
140
- { sort: { order: 1, name: 1 } },
141
- )) as CoreAiPrompt[];
145
+ const filter: Record<string, unknown> =
146
+ options.includeDisabled === true ? { $or: or } : { $or: or, enabled: { $ne: false } };
147
+ const rows = (await this.dataStore.find(filter, { sort: { order: 1, name: 1 } })) as CoreAiPrompt[];
142
148
  return rows || [];
143
149
  } catch (err) {
144
150
  this.logger.warn(`Failed to list prompts: ${(err as Error).message}`);
@@ -162,7 +162,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
162
162
  }
163
163
 
164
164
  /**
165
- * `POST /revoke-session` with `{ sessionId }` (12.6.2): `list-sessions` hands out session ids and no tokens, so a
165
+ * `POST /revoke-session` with `{ sessionId }` (12.7.0): `list-sessions` hands out session ids and no tokens, so a
166
166
  * client names the session to end by its id. Better-Auth's route takes `{ token }` only; this looks the token up among
167
167
  * the sessions of the signed-in user ({@link CoreBetterAuthService.sessionTokenOfUser}) and puts it into the body.
168
168
  *
@@ -396,7 +396,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
396
396
  const resetPassword = this.normalizeResetPassword(req, relativePath);
397
397
  // …and every password a non-reset native route carries (2FA, change-password, delete-user, …).
398
398
  this.normalizeNativePasswords(req, relativePath);
399
- // `list-sessions` hands out ids, no tokens: revoke-session takes the id (12.6.2)
399
+ // `list-sessions` hands out ids, no tokens: revoke-session takes the id (12.7.0)
400
400
  await this.resolveRevokeSessionId(req, relativePath);
401
401
 
402
402
  // Convert Express request to Web Standard Request with proper cookie signing
@@ -31,8 +31,13 @@ export interface SessionTokenPresentation {
31
31
  * A Better-Auth endpoint that CREATES a session (two-factor verify, passkey verify, OTP and magic-link sign-in, …)
32
32
  * sets this cookie; that is how the token in its body is recognised as the session token rather than some other
33
33
  * value a plugin names `token`. The cookie value is signed (`<token>.<signature>`, URL-encoded).
34
+ *
35
+ * When a response sets the cookie more than once, the LAST one counts, as in the browser: a session refresh during
36
+ * the request (Better-Auth's `getSessionFromCtx()`, once per `updateAge`) sets the current session's cookie first, and
37
+ * an endpoint that then replaces the session (enabling 2FA) sets the new one after it (12.7.1).
34
38
  */
35
39
  export function sessionTokenFromSetCookie(response: globalThis.Response, cookieName: string): string | undefined {
40
+ let token: string | undefined;
36
41
  for (const header of response.headers.getSetCookie?.() ?? []) {
37
42
  if (!header.startsWith(`${cookieName}=`)) {
38
43
  continue;
@@ -44,10 +49,9 @@ export function sessionTokenFromSetCookie(response: globalThis.Response, cookieN
44
49
  } catch {
45
50
  value = raw;
46
51
  }
47
- const token = value.split('.')[0];
48
- return token || undefined;
52
+ token = value.split('.')[0] || undefined;
49
53
  }
50
- return undefined;
54
+ return token;
51
55
  }
52
56
 
53
57
  /**
@@ -66,8 +70,12 @@ export function sessionTokenFromSetCookie(response: globalThis.Response, cookieN
66
70
  * leaves the body as in sign-in (`mapSession()`). A response that created a session without a top-level token
67
71
  * (passkey verify answers `{ session }`) gains one.
68
72
  * - Session records (an object with a `token`, a `userId` and an `expiresAt`) lose their `token` in every mode, also
69
- * inside an array: `list-sessions` answered every session of the user with its token (12.6.2). The client revokes a
73
+ * inside an array: `list-sessions` answered every session of the user with its token (12.7.0). The client revokes a
70
74
  * session by its `id` instead (`POST /revoke-session` with `{ sessionId }`).
75
+ * - A response in the shape `{ token, user }` that sets a new session cookie while its body names another opaque token
76
+ * rotated the session (the first verify-totp while enabling 2FA answers with the token of the session it deleted):
77
+ * that token is treated as the session token — removed in cookie mode, replaced by the JWT of the NEW session where
78
+ * the body carries one (12.7.1). A plugin's own `{ token }` next to a refreshed session cookie is not a rotation.
71
79
  * - Untouched: error responses, non-JSON bodies, a JWT (`/token` hands one out on purpose), and a top-level `token`
72
80
  * that is not the session token (another plugin's value).
73
81
  *
@@ -109,10 +117,19 @@ export async function presentSessionTokens(
109
117
  const sessionFieldToken = typeof session?.token === 'string' && session.token ? session.token : undefined;
110
118
  const cookieToken = sessionTokenFromSetCookie(response, options.cookieName);
111
119
  const topToken = typeof record.token === 'string' && record.token ? record.token : undefined;
120
+ // A response that sets a NEW session cookie while its body names another opaque token rotated the session: the
121
+ // body token is the one it just replaced (and deleted). Better-Auth's first verify-totp while enabling 2FA does that.
122
+ // Only in the shape of a session-creating answer, `{ token, user }`: a session refresh sets the cookie on ANY
123
+ // session-protected request, so a plugin's own token (`/one-time-token/generate` answers `{ token }`) can sit next
124
+ // to a session cookie as well, and must stay what it is.
125
+ const answersWithUser = !!record.user && typeof record.user === 'object' && !Array.isArray(record.user);
126
+ const rotatedFrom =
127
+ answersWithUser && !!topToken && !isJwtShaped(topToken) && !!cookieToken && topToken !== cookieToken;
112
128
  const topIsSessionToken =
113
129
  !!topToken &&
114
130
  !isJwtShaped(topToken) &&
115
131
  (topToken === cookieToken ||
132
+ rotatedFrom ||
116
133
  topToken === sessionFieldToken ||
117
134
  (await isLiveSessionToken(topToken, options.isSessionToken)));
118
135
 
@@ -131,8 +148,9 @@ export async function presentSessionTokens(
131
148
  delete next.token;
132
149
  }
133
150
  } else {
134
- // The session token the body should present: the top-level one, else the one this response just set
135
- const source = topIsSessionToken ? topToken : !topToken ? cookieToken : undefined;
151
+ // The session token the body should present: the one this response set when it rotated the session, else the
152
+ // top-level one, else the one this response just set
153
+ const source = rotatedFrom ? cookieToken : topIsSessionToken ? topToken : !topToken ? cookieToken : undefined;
136
154
  if (source) {
137
155
  const presented = await options.resolveJwt(source);
138
156
  if (presented) {
@@ -1072,7 +1072,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1072
1072
  }
1073
1073
 
1074
1074
  /**
1075
- * The token of the session `sessionId` — only when that session belongs to `userId` (12.6.2).
1075
+ * The token of the session `sessionId` — only when that session belongs to `userId` (12.7.0).
1076
1076
  *
1077
1077
  * `list-sessions` hands out session ids, no tokens, so a client revokes a session by its id; the API middleware asks
1078
1078
  * this to turn `POST /revoke-session { sessionId }` into the `{ token }` Better-Auth expects. Asked through
@@ -119,7 +119,8 @@ authentication and separate app and API origins the request is credentialed, and
119
119
  refuses `*` there — uploads failed in the browser although the server answered 201. The origins now
120
120
  come from `buildCorsConfig()` (`appUrl`, `baseUrl`, `cors.allowedOrigins`, `cors.allowAll`), the same
121
121
  decision REST, GraphQL and Better-Auth make; `tus.allowedOrigins` overrides. Without credentialed CORS
122
- (cookies off, or no origin resolvable) the tus default `*` stays.
122
+ (no origin resolvable) the tus default `*` stays. Since 12.7.0 JWT mode (`cookies: false`) gets the origin list as
123
+ well.
123
124
 
124
125
  The preflight (`OPTIONS`) is answered by Nest's CORS layer and was never affected — test an
125
126
  **authenticated** request with an `Origin` header when checking this.
package/src/index.ts CHANGED
@@ -57,6 +57,7 @@ export * from './core/common/helpers/redact-secrets.helper.js';
57
57
  export * from './core/common/helpers/register-enum.helper.js';
58
58
  export * from './core/common/helpers/scim.helper.js';
59
59
  export * from './core/common/helpers/service.helper.js';
60
+ export * from './core/common/helpers/swagger-enabled.helper.js';
60
61
  export * from './core/common/helpers/swagger.helper.js';
61
62
  export * from './core/common/helpers/table.helper.js';
62
63
  export * from './core/common/inputs/combined-filter.input.js';
package/src/main.ts CHANGED
@@ -84,8 +84,9 @@ async function bootstrap() {
84
84
  // Three cases:
85
85
  // 1. CORS explicitly disabled (`cors: false` or `cors.enabled: false`) → skip `enableCors()`
86
86
  // entirely. No CORS headers emitted. Same-origin requests still work.
87
- // 2. Origins resolvable (appUrl/baseUrl/allowedOrigins or allowAll) → use the computed options.
88
- // 3. Cookies disabled → permissive `enableCors()` without credentials (backward-compatible).
87
+ // 2. Origins resolvable (appUrl/baseUrl/allowedOrigins or allowAll) → use the computed options,
88
+ // with credentials — in JWT mode (`cookies: false`) too since 12.7.0.
89
+ // 3. Cookies disabled and no origin resolvable → permissive `enableCors()` without credentials.
89
90
  if (isCorsDisabled(envConfig.cors)) {
90
91
  // Case 1 — CORS explicitly disabled. Do nothing.
91
92
  } else {
@@ -1,79 +0,0 @@
1
- # Migration Guide: 12.6.1 → 12.6.2
2
-
3
- ## Overview
4
-
5
- | Category | Details |
6
- |---|---|
7
- | **Breaking Changes** | None for the server API. `GET /iam/list-sessions` no longer carries a `token` field per session (§1) |
8
- | **New Features** | `POST /iam/revoke-session` accepts `{ sessionId }` (§1) |
9
- | **Bugfixes** | Security: `GET /iam/list-sessions` answered every session of the user with its session token (§1) |
10
- | **Migration Effort** | None on the server. A "signed-in devices" screen that revokes a session by its `token` sends the `id` instead (§1) |
11
-
12
- 12.6.2 is a security patch on the 12.6 line, published under the dist-tag `latest-12.6`. The same change ships in
13
- 12.7.0 (`latest`), together with that release's breaking changes; a project that stays on 12.6 takes this patch.
14
-
15
- ## Quick Migration
16
-
17
- ```bash
18
- pnpm add @lenne.tech/nest-server@12.6.2
19
- pnpm run update # nest-server-starter based projects
20
- pnpm run build
21
- pnpm test
22
- ```
23
-
24
- Vendor-mode projects update the core to the tag `12.6.2`: `/lt-dev:backend:update-nest-server-core --target 12.6.2`.
25
- Without `--target` the updater syncs to the latest tag, which is on a newer line.
26
-
27
- ## 1. list-sessions names sessions by id; revoke-session takes the id
28
-
29
- **Why:** `GET /iam/list-sessions` answered every session of the user with its `token` — the bearer credential of every
30
- device the user is signed in on, readable by any script on the page. 12.6.1 took the session token out of the other
31
- answers the framework forwards to Better-Auth; this was the last one.
32
-
33
- **What changed:**
34
-
35
- | | Until 12.6.1 | From 12.6.2 |
36
- |---|---|---|
37
- | `GET /iam/list-sessions` | `[{ id, token, userId, expiresAt, … }]` | `[{ id, userId, expiresAt, … }]` — no `token`, in every mode |
38
- | `POST /iam/revoke-session` | `{ token }` | `{ sessionId }` (new) or `{ token }` (unchanged) |
39
-
40
- `{ sessionId }` is resolved among the sessions of the signed-in user. An unknown id, or the id of another user's
41
- session, revokes nothing — the answer is the same as for a foreign token, so it discloses nothing. Revoking by `token`
42
- stays for clients that hold one.
43
-
44
- **Your frontend:** a "signed-in devices" screen that revokes a session by the `token` from `list-sessions` sends the
45
- `id` instead:
46
-
47
- ```typescript
48
- await fetch(`${api}/iam/revoke-session`, {
49
- body: JSON.stringify({ sessionId: session.id }),
50
- credentials: 'include',
51
- headers: { 'Content-Type': 'application/json' },
52
- method: 'POST',
53
- });
54
- ```
55
-
56
- Better-Auth's client (`authClient.revokeSession({ token })`) types the body as `{ token }`; send the request yourself
57
- as above.
58
-
59
- ## Compatibility Notes
60
-
61
- | Pattern | Status |
62
- |---|---|
63
- | A client reading `token` from `list-sessions` | Gets none; use `id` and `revoke-session` with `{ sessionId }` |
64
- | `revoke-session` with `{ token }` | Unchanged |
65
- | `revoke-sessions`, `revoke-other-sessions`, sign-out | Unchanged |
66
- | A project subclass of `CoreBetterAuthService` / `CoreBetterAuthApiMiddleware` | `sessionTokenOfUser()` (public) and `resolveRevokeSessionId()` (protected) are new |
67
-
68
- ## Troubleshooting
69
-
70
- | Symptom | Cause | Fix |
71
- |---|---|---|
72
- | Revoking a device does nothing after the update | The screen sends the `token` from `list-sessions`, which is gone | Send `{ sessionId: session.id }` |
73
-
74
- ## References
75
-
76
- - `src/core/modules/better-auth/core-better-auth-session-token.helper.ts` — session records
77
- - `src/core/modules/better-auth/core-better-auth-api.middleware.ts` — `resolveRevokeSessionId()`
78
- - `src/core/modules/better-auth/core-better-auth.service.ts` — `sessionTokenOfUser()`
79
- - `tests/session-token-exposure.e2e-spec.ts`