@lenne.tech/nest-server 12.6.0 → 12.7.0

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 (60) hide show
  1. package/.claude/rules/better-auth.md +36 -0
  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-api.middleware.d.ts +1 -0
  27. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +22 -4
  28. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  29. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.d.ts +8 -0
  30. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +115 -0
  31. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -0
  32. package/dist/core/modules/better-auth/core-better-auth.controller.js +2 -2
  33. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  34. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +5 -0
  35. package/dist/core/modules/better-auth/core-better-auth.service.js +42 -2
  36. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  37. package/dist/index.d.ts +1 -0
  38. package/dist/index.js +1 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/main.js.map +1 -1
  41. package/docs/REQUEST-LIFECYCLE.md +22 -2
  42. package/migration-guides/12.6.0-to-12.6.1.md +66 -0
  43. package/migration-guides/12.6.x-to-12.7.x.md +299 -0
  44. package/package.json +1 -1
  45. package/src/core/common/helpers/config.helper.ts +58 -2
  46. package/src/core/common/helpers/cookies.helper.ts +13 -10
  47. package/src/core/common/helpers/swagger-enabled.helper.ts +33 -0
  48. package/src/core/common/helpers/swagger.helper.ts +30 -6
  49. package/src/core/common/interfaces/server-options.interface.ts +26 -5
  50. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +4 -1
  51. package/src/core/modules/ai/core-ai.controller.ts +18 -3
  52. package/src/core/modules/ai/core-ai.resolver.ts +14 -3
  53. package/src/core/modules/ai/services/core-ai-prompt.service.ts +11 -5
  54. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +39 -5
  55. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +194 -0
  56. package/src/core/modules/better-auth/core-better-auth.controller.ts +3 -2
  57. package/src/core/modules/better-auth/core-better-auth.service.ts +87 -2
  58. package/src/core/modules/tus/README.md +2 -1
  59. package/src/index.ts +1 -0
  60. package/src/main.ts +3 -2
@@ -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}`);
@@ -9,7 +9,7 @@ import { wrapBetterAuthErrorResponse } from './core-better-auth-error-codes.help
9
9
  import { isControllerHandledPath } from './core-better-auth-openapi.helper.js';
10
10
  import { runWithResetPassword } from './core-better-auth-password-reset.registry.js';
11
11
  import { CoreBetterAuthUserMapper } from './core-better-auth-user.mapper.js';
12
- import { extractSessionToken, sendWebResponse, signCookieValue, toWebRequest } from './core-better-auth-web.helper.js';
12
+ import { extractSessionToken, signCookieValue, toWebRequest } from './core-better-auth-web.helper.js';
13
13
  import { CoreBetterAuthService } from './core-better-auth.service.js';
14
14
  import { openVerificationToken } from './core-better-auth-verification-link.helper.js';
15
15
 
@@ -161,6 +161,37 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
161
161
  return normalized;
162
162
  }
163
163
 
164
+ /**
165
+ * `POST /revoke-session` with `{ sessionId }` (12.7.0): `list-sessions` hands out session ids and no tokens, so a
166
+ * client names the session to end by its id. Better-Auth's route takes `{ token }` only; this looks the token up among
167
+ * the sessions of the signed-in user ({@link CoreBetterAuthService.sessionTokenOfUser}) and puts it into the body.
168
+ *
169
+ * An id that is unknown or belongs to another user becomes an empty token: Better-Auth then revokes nothing and
170
+ * answers as it does for a foreign token, so the answer says nothing about other users' sessions. A body that
171
+ * already carries a `token` is left as it is (revoking by token keeps working).
172
+ */
173
+ protected async resolveRevokeSessionId(req: Request, relativePath: string): Promise<void> {
174
+ if (req.method !== 'POST' || normalizeIamRoutePath(relativePath) !== '/revoke-session') {
175
+ return;
176
+ }
177
+ const body = req.body as Record<string, unknown> | undefined;
178
+ const sessionId = body?.sessionId;
179
+ if (!body || typeof sessionId !== 'string' || !sessionId || (typeof body.token === 'string' && body.token)) {
180
+ return;
181
+ }
182
+ const caller = req as unknown as {
183
+ betterAuthSession?: { user?: { id?: unknown } };
184
+ betterAuthUser?: { id?: unknown };
185
+ };
186
+ const userId = caller.betterAuthSession?.user?.id ?? caller.betterAuthUser?.id;
187
+ const token =
188
+ typeof userId === 'string' && userId
189
+ ? await this.betterAuthService.sessionTokenOfUser(userId, sessionId)
190
+ : undefined;
191
+ const { sessionId: _sessionId, ...rest } = body;
192
+ req.body = { ...rest, token: token ?? '' };
193
+ }
194
+
164
195
  /**
165
196
  * Brings every other password a native route carries (see {@link PASSWORD_FIELD_PATHS}) to the shape the
166
197
  * stored credential was written in. Matched like {@link normalizeResetPassword}: exact, after trimming a
@@ -365,6 +396,8 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
365
396
  const resetPassword = this.normalizeResetPassword(req, relativePath);
366
397
  // …and every password a non-reset native route carries (2FA, change-password, delete-user, …).
367
398
  this.normalizeNativePasswords(req, relativePath);
399
+ // `list-sessions` hands out ids, no tokens: revoke-session takes the id (12.7.0)
400
+ await this.resolveRevokeSessionId(req, relativePath);
368
401
 
369
402
  // Convert Express request to Web Standard Request with proper cookie signing
370
403
  const webRequest = await toWebRequest(req, {
@@ -458,7 +491,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
458
491
  this.logger.debug(`Stored challenge mapping with ID: ${challengeId.substring(0, 8)}...`);
459
492
 
460
493
  // Send the enhanced response
461
- await sendWebResponse(res, enhancedResponse);
494
+ await this.betterAuthService.sendBetterAuthResponse(res, enhancedResponse);
462
495
 
463
496
  return;
464
497
  } else {
@@ -519,7 +552,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
519
552
  });
520
553
 
521
554
  this.logger.debug('Enriched passkey verify response with user data');
522
- await sendWebResponse(res, enrichedResponse);
555
+ await this.betterAuthService.sendBetterAuthResponse(res, enrichedResponse);
523
556
  return;
524
557
  }
525
558
  }
@@ -537,8 +570,9 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
537
570
  return next();
538
571
  }
539
572
 
540
- // Convert Web Standard Response to Express response using shared helper
541
- await sendWebResponse(res, response);
573
+ // Convert Web Standard Response to Express response, through the token policy (12.6.1): a forwarded route must
574
+ // not hand out what the framework's own sign-in would not
575
+ await this.betterAuthService.sendBetterAuthResponse(res, response);
542
576
  } catch (error) {
543
577
  // A refused request (the password length policy) is an answer, not a handler failure. Nest's middleware
544
578
  // proxy hands a thrown exception to the exception filters, so it is rendered like the same refusal from a
@@ -0,0 +1,194 @@
1
+ import { isJwtShaped } from './core-better-auth-token.helper.js';
2
+
3
+ /**
4
+ * How a response Better-Auth produced itself may carry the session token (see {@link presentSessionTokens}).
5
+ */
6
+ export interface SessionTokenPresentation {
7
+ /** Name of the session cookie Better-Auth sets (`<prefix>.session_token`, `__Secure-` prefixed with secure cookies) */
8
+ cookieName: string;
9
+ /**
10
+ * Whether a value is the token of a live session — asked only for a top-level `token` the response does not
11
+ * already identify as the session token (no session cookie set, no `session.token`). A signed-in user verifying a
12
+ * second factor gets the token of the session they already hold, with no cookie; without this check that token
13
+ * would pass as another plugin's value.
14
+ */
15
+ isSessionToken?: (token: string) => Promise<boolean>;
16
+ /**
17
+ * Turns an opaque session token into what the body should carry instead — a JWT when the JWT plugin is on
18
+ * (`CoreBetterAuthService.resolveJwtToken()`), the token itself when it is off, `undefined` when a conversion failed
19
+ */
20
+ resolveJwt: (sessionToken: string) => Promise<string | undefined>;
21
+ /**
22
+ * Whether the body may carry a token at all: cookies disabled (JWT-only mode) or `cookies.exposeTokenInBody`.
23
+ * `false` in the default cookie mode, where the session lives in an httpOnly cookie and nowhere else.
24
+ */
25
+ tokenInBody: boolean;
26
+ }
27
+
28
+ /**
29
+ * The session token a response sets in its session cookie, or `undefined` when it sets none.
30
+ *
31
+ * A Better-Auth endpoint that CREATES a session (two-factor verify, passkey verify, OTP and magic-link sign-in, …)
32
+ * sets this cookie; that is how the token in its body is recognised as the session token rather than some other
33
+ * value a plugin names `token`. The cookie value is signed (`<token>.<signature>`, URL-encoded).
34
+ */
35
+ export function sessionTokenFromSetCookie(response: globalThis.Response, cookieName: string): string | undefined {
36
+ for (const header of response.headers.getSetCookie?.() ?? []) {
37
+ if (!header.startsWith(`${cookieName}=`)) {
38
+ continue;
39
+ }
40
+ const raw = header.split(';')[0].slice(cookieName.length + 1);
41
+ let value: string;
42
+ try {
43
+ value = decodeURIComponent(raw);
44
+ } catch {
45
+ value = raw;
46
+ }
47
+ const token = value.split('.')[0];
48
+ return token || undefined;
49
+ }
50
+ return undefined;
51
+ }
52
+
53
+ /**
54
+ * Applies the sign-in token policy to a response Better-Auth produced itself — every route the framework forwards
55
+ * to Better-Auth's handler instead of answering it in `CoreBetterAuthController` (two-factor verify-totp /
56
+ * verify-backup-code / verify-otp, passkey verify, OTP and magic-link sign-in, get-session, …).
57
+ *
58
+ * Better-Auth answers a session-creating route with `{ token: <session token>, user }`, and its session objects carry
59
+ * `session.token`. The framework's own sign-in never lets that reach a client: in the default cookie mode the token
60
+ * lives in an httpOnly cookie only, and where the body may carry a token it is a JWT (SEC-005). Forwarded routes
61
+ * bypassed both, so a frontend found the opaque 7-day session token in the body of the second factor and stored it
62
+ * where any script could read it.
63
+ *
64
+ * - Cookie mode: the session token leaves the body — top-level `token` and `session.token`.
65
+ * - Token in body: the session token becomes {@link SessionTokenPresentation.resolveJwt}'s answer; `session.token`
66
+ * leaves the body as in sign-in (`mapSession()`). A response that created a session without a top-level token
67
+ * (passkey verify answers `{ session }`) gains one.
68
+ * - 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.7.0). The client revokes a
70
+ * session by its `id` instead (`POST /revoke-session` with `{ sessionId }`).
71
+ * - Untouched: error responses, non-JSON bodies, a JWT (`/token` hands one out on purpose), and a top-level `token`
72
+ * that is not the session token (another plugin's value).
73
+ *
74
+ * Returns the response itself when nothing changes, otherwise a new one with the same status and headers.
75
+ */
76
+ export async function presentSessionTokens(
77
+ response: globalThis.Response,
78
+ options: SessionTokenPresentation,
79
+ ): Promise<globalThis.Response> {
80
+ if (!response.ok || !(response.headers.get('content-type') ?? '').includes('application/json')) {
81
+ return response;
82
+ }
83
+ let body: unknown;
84
+ try {
85
+ body = await response.clone().json();
86
+ } catch {
87
+ return response;
88
+ }
89
+ if (!body || typeof body !== 'object') {
90
+ return response;
91
+ }
92
+ if (Array.isArray(body)) {
93
+ return body.some(isSessionRecord)
94
+ ? rebuildResponse(
95
+ response,
96
+ body.map((item) => (isSessionRecord(item) ? withoutToken(item) : item)),
97
+ )
98
+ : response;
99
+ }
100
+ if (isSessionRecord(body)) {
101
+ return rebuildResponse(response, withoutToken(body));
102
+ }
103
+
104
+ const record = body as Record<string, unknown>;
105
+ const session =
106
+ record.session && typeof record.session === 'object' && !Array.isArray(record.session)
107
+ ? (record.session as Record<string, unknown>)
108
+ : undefined;
109
+ const sessionFieldToken = typeof session?.token === 'string' && session.token ? session.token : undefined;
110
+ const cookieToken = sessionTokenFromSetCookie(response, options.cookieName);
111
+ const topToken = typeof record.token === 'string' && record.token ? record.token : undefined;
112
+ const topIsSessionToken =
113
+ !!topToken &&
114
+ !isJwtShaped(topToken) &&
115
+ (topToken === cookieToken ||
116
+ topToken === sessionFieldToken ||
117
+ (await isLiveSessionToken(topToken, options.isSessionToken)));
118
+
119
+ if (!topIsSessionToken && !sessionFieldToken) {
120
+ return response;
121
+ }
122
+
123
+ const next: Record<string, unknown> = { ...record };
124
+ if (session && sessionFieldToken) {
125
+ const { token: _sessionToken, ...rest } = session;
126
+ next.session = rest;
127
+ }
128
+
129
+ if (!options.tokenInBody) {
130
+ if (topIsSessionToken) {
131
+ delete next.token;
132
+ }
133
+ } 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;
136
+ if (source) {
137
+ const presented = await options.resolveJwt(source);
138
+ if (presented) {
139
+ next.token = presented;
140
+ } else {
141
+ delete next.token;
142
+ }
143
+ }
144
+ }
145
+
146
+ return rebuildResponse(response, next);
147
+ }
148
+
149
+ /**
150
+ * A session as Better-Auth outputs it (`parseSessionOutput()`): its `token` is the bearer credential of that session,
151
+ * so it never belongs in a body — the `id` identifies the session to the client.
152
+ */
153
+ function isSessionRecord(value: unknown): value is Record<string, unknown> {
154
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
155
+ return false;
156
+ }
157
+ const record = value as Record<string, unknown>;
158
+ return typeof record.token === 'string' && !!record.token && 'userId' in record && 'expiresAt' in record;
159
+ }
160
+
161
+ /** The record without its `token` */
162
+ function withoutToken(record: Record<string, unknown>): Record<string, unknown> {
163
+ const { token: _token, ...rest } = record;
164
+ return rest;
165
+ }
166
+
167
+ /** The same response with another JSON body: status and headers kept, every `Set-Cookie` re-appended */
168
+ function rebuildResponse(response: globalThis.Response, body: unknown): globalThis.Response {
169
+ const headers = new Headers();
170
+ response.headers.forEach((value, key) => {
171
+ if (key.toLowerCase() !== 'content-length' && key.toLowerCase() !== 'set-cookie') {
172
+ headers.set(key, value);
173
+ }
174
+ });
175
+ for (const cookie of response.headers.getSetCookie?.() ?? []) {
176
+ headers.append('set-cookie', cookie);
177
+ }
178
+ return new Response(JSON.stringify(body), { headers, status: response.status, statusText: response.statusText });
179
+ }
180
+
181
+ /** Asks {@link SessionTokenPresentation.isSessionToken}; a lookup that fails cannot vouch for anything */
182
+ async function isLiveSessionToken(
183
+ token: string,
184
+ isSessionToken: SessionTokenPresentation['isSessionToken'],
185
+ ): Promise<boolean> {
186
+ if (!isSessionToken) {
187
+ return false;
188
+ }
189
+ try {
190
+ return (await isSessionToken(token)) === true;
191
+ } catch {
192
+ return false;
193
+ }
194
+ }
@@ -47,7 +47,7 @@ import { CoreBetterAuthEmailVerificationService } from './core-better-auth-email
47
47
  import { CoreBetterAuthSignUpValidatorService } from './core-better-auth-signup-validator.service.js';
48
48
  import { isJwtShaped, isSessionToken } from './core-better-auth-token.helper.js';
49
49
  import { BetterAuthSessionUser, CoreBetterAuthUserMapper } from './core-better-auth-user.mapper.js';
50
- import { convertExpressHeaders, sendWebResponse, toWebRequest } from './core-better-auth-web.helper.js';
50
+ import { convertExpressHeaders, toWebRequest } from './core-better-auth-web.helper.js';
51
51
  import { CoreBetterAuthService } from './core-better-auth.service.js';
52
52
  import { registerBetterAuthHandlerClass } from './core-better-auth.registry.js';
53
53
 
@@ -1154,7 +1154,8 @@ export class CoreBetterAuthController {
1154
1154
  this.logger.debug(`Better Auth handler response status: ${response.status}`);
1155
1155
 
1156
1156
  // Send the response back
1157
- await sendWebResponse(res, response);
1157
+ // Through the token policy: a forwarded route must not hand out what sign-in would not (12.6.1)
1158
+ await this.betterAuthService.sendBetterAuthResponse(res, response);
1158
1159
  } catch (error) {
1159
1160
  this.logger.error(`Better Auth handler error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1160
1161
 
@@ -16,10 +16,15 @@ import {
16
16
  sessionMiddleware,
17
17
  } from 'better-auth/api';
18
18
  import { Request } from 'express';
19
+ import type { Response as ExpressResponse } from 'express';
19
20
  import { importJWK, jwtVerify } from 'jose';
20
21
  import type { Connection } from 'mongoose';
21
22
 
22
- import { shouldConvertSessionTokenToJwt } from '../../common/helpers/cookies.helper.js';
23
+ import {
24
+ isCookiesEnabled,
25
+ isExposeTokenInBodyEnabled,
26
+ shouldConvertSessionTokenToJwt,
27
+ } from '../../common/helpers/cookies.helper.js';
23
28
  import { type ExpirySweep, scheduleExpirySweep } from '../../common/persistence/expiry-sweep.js';
24
29
  import { maskEmail, maskToken } from '../../common/helpers/logging.helper.js';
25
30
  import { type IBetterAuth, ICookiesConfig } from '../../common/interfaces/server-options.interface.js';
@@ -38,7 +43,13 @@ import {
38
43
  import type { IBetterAuthOpenApiDocument, IBetterAuthRuntime } from './core-better-auth-openapi.helper.js';
39
44
  import { isJwtShaped } from './core-better-auth-token.helper.js';
40
45
  import { BetterAuthSessionUser } from './core-better-auth-user.mapper.js';
41
- import { convertExpressHeaders, parseCookieHeader, signCookieValueIfNeeded } from './core-better-auth-web.helper.js';
46
+ import { presentSessionTokens } from './core-better-auth-session-token.helper.js';
47
+ import {
48
+ convertExpressHeaders,
49
+ parseCookieHeader,
50
+ sendWebResponse,
51
+ signCookieValueIfNeeded,
52
+ } from './core-better-auth-web.helper.js';
42
53
  import {
43
54
  ACCOUNT_ISSUER_BACKFILL_ID,
44
55
  BACKFILL_MARKER_COLLECTION,
@@ -804,6 +815,53 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
804
815
  return `${this.getCookiePrefix()}.session_token`;
805
816
  }
806
817
 
818
+ /**
819
+ * Applies the sign-in token policy to a response Better-Auth's own handler produced (12.6.1).
820
+ *
821
+ * Routes the framework forwards to Better-Auth — two-factor verify, passkey verify, OTP and magic-link sign-in,
822
+ * get-session — answered with the opaque session token in the body, also in the default cookie mode, where the
823
+ * framework's own sign-in keeps it in an httpOnly cookie only, and as the raw token where sign-in hands out a JWT.
824
+ * See `presentSessionTokens()` (`core-better-auth-session-token.helper.ts`) for the rules.
825
+ *
826
+ * Override to present tokens differently; keep the cookie-mode rule, it is what keeps the session out of scripts.
827
+ */
828
+ async presentSessionTokens(response: globalThis.Response): Promise<globalThis.Response> {
829
+ const cookiesConfig = ConfigService.configFastButReadOnly?.cookies as boolean | ICookiesConfig | undefined;
830
+ return presentSessionTokens(response, {
831
+ cookieName: await this.sessionCookieNameOfInstance(),
832
+ isSessionToken: async (token) => !!(await this.getSessionByToken(token))?.session,
833
+ resolveJwt: (sessionToken) => this.resolveJwtToken(sessionToken),
834
+ tokenInBody: !isCookiesEnabled(cookiesConfig) || isExposeTokenInBodyEnabled(cookiesConfig),
835
+ });
836
+ }
837
+
838
+ /**
839
+ * The session cookie's name as the running Better-Auth instance sets it — `__Secure-` prefixed under
840
+ * `advanced.useSecureCookies`, renamed under `advanced.cookies.session_token.name` — falling back to
841
+ * {@link getSessionCookieName} when the instance cannot say.
842
+ */
843
+ protected async sessionCookieNameOfInstance(): Promise<string> {
844
+ try {
845
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
846
+ const name = context?.authCookies?.sessionToken?.name;
847
+ if (typeof name === 'string' && name) {
848
+ return name;
849
+ }
850
+ } catch {
851
+ // The configured name below is what the framework writes itself
852
+ }
853
+ return this.getSessionCookieName();
854
+ }
855
+
856
+ /**
857
+ * Sends a response of Better-Auth's handler to the client, through {@link presentSessionTokens}. Every place that
858
+ * forwards to the handler (the API middleware, the controller's catch-all) sends through here, so a forwarded route
859
+ * cannot hand a client a token the framework's own sign-in would not.
860
+ */
861
+ async sendBetterAuthResponse(res: ExpressResponse, response: globalThis.Response): Promise<void> {
862
+ await sendWebResponse(res, await this.presentSessionTokens(response));
863
+ }
864
+
807
865
  /**
808
866
  * Gets the cookie prefix (the `iam` in `iam.session_token`).
809
867
  *
@@ -1013,6 +1071,33 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1013
1071
  }
1014
1072
  }
1015
1073
 
1074
+ /**
1075
+ * The token of the session `sessionId` — only when that session belongs to `userId` (12.7.0).
1076
+ *
1077
+ * `list-sessions` hands out session ids, no tokens, so a client revokes a session by its id; the API middleware asks
1078
+ * this to turn `POST /revoke-session { sessionId }` into the `{ token }` Better-Auth expects. Asked through
1079
+ * Better-Auth's own adapter (`internalAdapter.listSessions()`), so it reads wherever Better-Auth keeps its sessions.
1080
+ *
1081
+ * @returns the token, or `undefined` for an unknown id, a session of another user, or a failed lookup
1082
+ */
1083
+ async sessionTokenOfUser(userId: string, sessionId: string): Promise<string | undefined> {
1084
+ if (!userId || !sessionId) {
1085
+ return undefined;
1086
+ }
1087
+ try {
1088
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
1089
+ const sessions: unknown = await context?.internalAdapter?.listSessions?.(userId);
1090
+ const match = (Array.isArray(sessions) ? sessions : []).find(
1091
+ (session: { id?: unknown; userId?: unknown }) =>
1092
+ String(session?.id) === sessionId && String(session?.userId) === String(userId),
1093
+ );
1094
+ return typeof match?.token === 'string' && match.token ? match.token : undefined;
1095
+ } catch (error) {
1096
+ this.logger.debug(`sessionTokenOfUser error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1097
+ return undefined;
1098
+ }
1099
+ }
1100
+
1016
1101
  /**
1017
1102
  * Revokes a specific session (logout for that session)
1018
1103
  *
@@ -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 {