@lenne.tech/nest-server 11.43.5 → 11.43.7

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 (29) hide show
  1. package/.claude/rules/better-auth.md +29 -0
  2. package/.claude/rules/configurable-features.md +1 -0
  3. package/.claude/rules/testing.md +4 -4
  4. package/FRAMEWORK-API.md +2 -2
  5. package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
  6. package/dist/core/common/services/email.service.d.ts +3 -0
  7. package/dist/core/common/services/email.service.js +20 -0
  8. package/dist/core/common/services/email.service.js.map +1 -1
  9. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +3 -3
  10. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  11. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.d.ts +8 -0
  12. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +97 -0
  13. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -0
  14. package/dist/core/modules/better-auth/core-better-auth.controller.js +1 -1
  15. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  16. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +4 -0
  17. package/dist/core/modules/better-auth/core-better-auth.service.js +25 -0
  18. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  19. package/dist/tsconfig.build.tsbuildinfo +1 -1
  20. package/docs/REQUEST-LIFECYCLE.md +12 -0
  21. package/migration-guides/11.43.5-to-11.43.6.md +53 -0
  22. package/migration-guides/11.43.6-to-11.43.7.md +67 -0
  23. package/package.json +1 -1
  24. package/src/core/common/interfaces/server-options.interface.ts +11 -0
  25. package/src/core/common/services/email.service.ts +33 -1
  26. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +6 -5
  27. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +157 -0
  28. package/src/core/modules/better-auth/core-better-auth.controller.ts +3 -2
  29. package/src/core/modules/better-auth/core-better-auth.service.ts +60 -2
@@ -675,6 +675,18 @@ If authentication succeeds, `req.user` is set with the authenticated user (inclu
675
675
  > must know the counterpart of the rule above — the response body it forwards is no longer
676
676
  > byte-identical to the one Better-Auth produced.
677
677
 
678
+ > **Response side, since 11.43.7 — session tokens in forwarded bodies.** A **successful** response of
679
+ > Better-Auth's handler reaches the client only through `CoreBetterAuthService.sendBetterAuthResponse()`
680
+ > (the middleware's three send sites and the controller's catch-all), which applies
681
+ > `presentSessionTokens()`: in the default cookie mode the session token leaves the body (top-level
682
+ > `token` and `session.token`), where the body may carry a token it becomes the JWT sign-in hands out.
683
+ > Before, two-factor verify, passkey verify, OTP / magic-link sign-in and `get-session` answered with the
684
+ > opaque session token in the body, also in cookie mode. The session token is recognised by the session
685
+ > cookie the response sets (under the name the instance gives it), by `session.token`, or — for a top-level
686
+ > token neither identifies, as a signed-in user's second factor returns — by a session-store lookup. A JWT
687
+ > (`/token`), arrays (`list-sessions`) and other plugins' tokens are left alone. See
688
+ > `.claude/rules/better-auth.md` §7 "Forwarded responses".
689
+
678
690
  #### 2b. SecurityHeadersMiddleware
679
691
 
680
692
  Sets the browser security headers on **every** response — `X-Content-Type-Options`,
@@ -0,0 +1,53 @@
1
+ # Migration Guide: 11.43.5 → 11.43.6
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ | -------------------- | ------------------------------------------------------------------------------------------------------- |
7
+ | **New Features** | Optional Reply-To for outgoing mail: `email.defaultReplyTo` and a per-call `replyTo` (§1) |
8
+ | **Breaking Changes** | None |
9
+ | **Migration Effort** | None. Set `email.defaultReplyTo` only if answers to your mail should go to another address (§1) |
10
+
11
+ ## Quick Migration
12
+
13
+ ```bash
14
+ pnpm add @lenne.tech/nest-server@11.43.6
15
+ pnpm run update # nest-server-starter based projects
16
+ ```
17
+
18
+ Vendor-mode projects update the core to the tag `11.43.6`: `/lt-dev:backend:update-nest-server-core --target 11.43.6`.
19
+ Without `--target` the updater syncs to the latest tag, which is on the 12.x line.
20
+
21
+ ## 1. Reply-To for outgoing mail
22
+
23
+ `EmailService.sendMail()` can set a `Reply-To` header, so a recipient's answer goes to another address than the
24
+ sender, e.g. a shared support mailbox while mail goes out from `noreply@…`. Nothing changes until you set it.
25
+
26
+ ```typescript
27
+ // config.env.ts
28
+ email: {
29
+ defaultSender: { email: 'noreply@example.com', name: 'Example' },
30
+ defaultReplyTo: 'support@example.com', // or '"Example Support" <support@example.com>'
31
+ },
32
+ ```
33
+
34
+ As an environment variable:
35
+
36
+ ```bash
37
+ NSC__EMAIL__DEFAULT_REPLY_TO=support@example.com
38
+ ```
39
+
40
+ A call can override it, or send one mail without it:
41
+
42
+ ```typescript
43
+ await this.emailService.sendMail(to, subject, { replyTo: 'sales@example.com', htmlTemplate, templateData });
44
+ await this.emailService.sendMail(to, subject, { replyTo: false, htmlTemplate, templateData });
45
+ ```
46
+
47
+ The default applies to every mail the service sends over SMTP, Better-Auth's verification and password-reset mail
48
+ included. Mail sent through Brevo (`brevo.apiKey`) or Mailjet is not affected: their templates carry their own
49
+ reply-to. A value that is not a string is ignored with one warning rather than stopping the mail.
50
+
51
+ ## Module Documentation
52
+
53
+ - Configuration reference: `email.defaultReplyTo` in `FRAMEWORK-API.md` (`IServerOptions.email`)
@@ -0,0 +1,67 @@
1
+ # Migration Guide: 11.43.6 → 11.43.7
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None for the server API. A client that read the session token from a forwarded Better-Auth response gets none in cookie mode and a JWT in token-in-body mode (§1) |
8
+ | **New Features** | None |
9
+ | **Bugfixes** | Security (backport of 12.6.1): routes forwarded to Better-Auth (two-factor verify, passkey verify, OTP and magic-link sign-in, get-session) put the opaque session token into the response body, also in the default cookie mode (§1) |
10
+ | **Migration Effort** | None on the server. Check a frontend that stores a `token` from the second factor or a passkey sign-in (§1) |
11
+
12
+ ## Quick Migration
13
+
14
+ ```bash
15
+ pnpm add @lenne.tech/nest-server@11.43.7
16
+ pnpm run update # nest-server-starter based projects
17
+ pnpm run build
18
+ pnpm test
19
+ ```
20
+
21
+ Vendor-mode projects update the core to the tag `11.43.7`: `/lt-dev:backend:update-nest-server-core --target 11.43.7`.
22
+ Without `--target` the updater syncs to the latest tag, which is on the 12.x line.
23
+
24
+ ## 1. Forwarded Better-Auth responses follow the sign-in token policy
25
+
26
+ **Why:** the framework's own sign-in (`POST /iam/sign-in/email`) never hands the opaque session token to a script. In
27
+ the default cookie mode it lives in an httpOnly cookie only, and where the body may carry a token
28
+ (`cookies: false` or `cookies.exposeTokenInBody`) it is a JWT. Routes the framework forwards to Better-Auth's own
29
+ handler bypassed both. `POST /iam/two-factor/verify-totp`, `verify-backup-code` and `verify-otp` answered
30
+ `{ token: <session token>, user }`, passkey verify and `GET /iam/get-session` carried `session.token`. A frontend that
31
+ stored that token in a cookie or storage its scripts can read handed a 7-day session to any XSS.
32
+
33
+ **What changed:** every response the API middleware or the controller's catch-all forwards from Better-Auth now goes
34
+ through `CoreBetterAuthService.presentSessionTokens()`:
35
+
36
+ | Mode | Top-level `token` (the session token) | `session.token` |
37
+ |---|---|---|
38
+ | Cookie mode (default) | removed | removed |
39
+ | `cookies: false` or `exposeTokenInBody` | the JWT, as sign-in hands out (the token itself without the JWT plugin); a session-creating response without one (passkey verify) gains it | removed |
40
+
41
+ A `token` counts as the session token when the response sets it as the session cookie, when it equals `session.token`,
42
+ or when it is the token of a live session — the last covers a signed-in user who verifies a second factor again, which
43
+ Better-Auth answers with the session they already hold and no cookie.
44
+
45
+ Untouched: the session cookie Better-Auth sets, error responses, a JWT (`/iam/token` hands one out on purpose), arrays
46
+ (`list-sessions`) and a `token` that is not the session token.
47
+
48
+ **Your frontend:** in cookie mode, rely on the session cookie after the second factor or a passkey sign-in, as after
49
+ sign-in. Do not store a `token` from these responses; there is none any more. In token-in-body mode, the `token` is now
50
+ the same kind of JWT sign-in returns, so a client that already handles sign-in needs no change.
51
+
52
+ ## Compatibility Notes
53
+
54
+ | Pattern | Status |
55
+ |---|---|
56
+ | Cookie-based sign-in, second factor and passkey | Unchanged: the session cookie authenticates |
57
+ | A client storing `token` from `two-factor/verify-*` in cookie mode | Gets no `token` any more; use the cookie |
58
+ | A client reading `session.token` from `get-session` | Gets none any more, in every mode |
59
+ | A signed-in user verifying a second factor again (step-up, adding an authenticator) | The response names the session they already hold; it gets the same treatment (no `token` in cookie mode, a JWT otherwise) |
60
+ | `betterAuth.options.advanced.useSecureCookies` / a renamed session cookie | Covered: the session cookie is matched under the name the Better-Auth instance sets |
61
+ | `POST /iam/token` (JWT for a cookie session) | Unchanged |
62
+ | A project subclass of `CoreBetterAuthService` | `presentSessionTokens()` and `sendBetterAuthResponse()` are new public methods, `sessionCookieNameOfInstance()` a new protected one; keep the cookie-mode rule when overriding |
63
+
64
+ ## References
65
+
66
+ - `src/core/modules/better-auth/core-better-auth-session-token.helper.ts` — `presentSessionTokens()`
67
+ - `src/core/modules/better-auth/core-better-auth.service.ts` — `presentSessionTokens()`, `sendBetterAuthResponse()`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.43.5",
3
+ "version": "11.43.7",
4
4
  "description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
5
5
  "keywords": [
6
6
  "node",
@@ -2510,6 +2510,17 @@ export interface IServerOptions {
2510
2510
  * SMTP and template configuration for sending emails
2511
2511
  */
2512
2512
  email?: {
2513
+ /**
2514
+ * Default Reply-To of every mail `EmailService.sendMail()` sends (11.43.6+): where a recipient's answer goes when it
2515
+ * should not reach the sender address, e.g. a shared support mailbox. An address, or `"Name" <address>`.
2516
+ *
2517
+ * Absent (the default) → no Reply-To header, exactly as before. A call overrides it with `replyTo`, and
2518
+ * `replyTo: false` sends that one mail without it. Set it through `NSC__EMAIL__DEFAULT_REPLY_TO`. Applies to the
2519
+ * SMTP path (nodemailer, `email.smtp`): Brevo and Mailjet templates carry their own reply-to.
2520
+ * @default undefined
2521
+ */
2522
+ defaultReplyTo?: string;
2523
+
2513
2524
  /**
2514
2525
  * Data for default sender
2515
2526
  */
@@ -28,6 +28,9 @@ export class EmailService implements OnModuleDestroy {
28
28
  /** Once-per-process latch for the SMTP TLS warning — a per-send warning would be noise. */
29
29
  private smtpTlsWarningEmitted = false;
30
30
 
31
+ /** Once-per-process latch for a Reply-To that is not a string. */
32
+ private replyToWarningEmitted = false;
33
+
31
34
  /**
32
35
  * Inject services
33
36
  */
@@ -76,6 +79,31 @@ export class EmailService implements OnModuleDestroy {
76
79
  );
77
80
  }
78
81
 
82
+ /**
83
+ * The Reply-To of one mail (11.43.6+): the call's `replyTo`, else `email.defaultReplyTo`, else none. `false` (or an
84
+ * empty string) sends this mail without one. A value that is not a string is dropped with a warning instead of
85
+ * failing the mail: a misconfigured default must not stop password-reset or verification mail.
86
+ */
87
+ protected resolveReplyTo(replyTo: false | string | undefined): string | undefined {
88
+ if (replyTo === false) {
89
+ return undefined;
90
+ }
91
+ const value: unknown = replyTo ?? this.configService.getFastButReadOnly('email.defaultReplyTo');
92
+ if (value === undefined || value === null) {
93
+ return undefined;
94
+ }
95
+ if (typeof value === 'string') {
96
+ return value.trim() || undefined;
97
+ }
98
+ if (!this.replyToWarningEmitted) {
99
+ this.replyToWarningEmitted = true;
100
+ this.emailServiceLogger.warn(
101
+ `Reply-To ignored: expected an address string (email.defaultReplyTo / replyTo), got ${typeof value}.`,
102
+ );
103
+ }
104
+ return undefined;
105
+ }
106
+
79
107
  onModuleDestroy(): void {
80
108
  if (this.cachedTransporter) {
81
109
  this.cachedTransporter.close();
@@ -94,6 +122,8 @@ export class EmailService implements OnModuleDestroy {
94
122
  attachments?: Attachment[];
95
123
  html?: string;
96
124
  htmlTemplate?: string;
125
+ /** Reply-To of this mail; overrides `email.defaultReplyTo`, `false` sends it without one (11.43.6+) */
126
+ replyTo?: false | string;
97
127
  senderEmail?: string;
98
128
  senderName?: string;
99
129
  smtp?: MailTransportOptions;
@@ -189,11 +219,13 @@ export class EmailService implements OnModuleDestroy {
189
219
  this.cachedSmtpConfig = smtpKey;
190
220
  }
191
221
 
192
- // Send mail
222
+ // Send mail; without a Reply-To the header is left out entirely
223
+ const replyTo = this.resolveReplyTo(config.replyTo);
193
224
  return this.cachedTransporter.sendMail({
194
225
  attachments,
195
226
  from: `"${senderName}" <${senderEmail}>`,
196
227
  html,
228
+ ...(replyTo ? { replyTo } : {}),
197
229
  subject,
198
230
  text,
199
231
  to: recipients,
@@ -9,7 +9,7 @@ import { wrapBetterAuthErrorResponse } from './core-better-auth-error-codes.help
9
9
  import { isControllerHandledPath } from './core-better-auth-openapi.helper';
10
10
  import { runWithResetPassword } from './core-better-auth-password-reset.registry';
11
11
  import { CoreBetterAuthUserMapper } from './core-better-auth-user.mapper';
12
- import { extractSessionToken, sendWebResponse, signCookieValue, toWebRequest } from './core-better-auth-web.helper';
12
+ import { extractSessionToken, signCookieValue, toWebRequest } from './core-better-auth-web.helper';
13
13
  import { CoreBetterAuthService } from './core-better-auth.service';
14
14
 
15
15
  /**
@@ -376,7 +376,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
376
376
  this.logger.debug(`Stored challenge mapping with ID: ${challengeId.substring(0, 8)}...`);
377
377
 
378
378
  // Send the enhanced response
379
- await sendWebResponse(res, enhancedResponse);
379
+ await this.betterAuthService.sendBetterAuthResponse(res, enhancedResponse);
380
380
 
381
381
  return;
382
382
  } else {
@@ -437,7 +437,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
437
437
  });
438
438
 
439
439
  this.logger.debug('Enriched passkey verify response with user data');
440
- await sendWebResponse(res, enrichedResponse);
440
+ await this.betterAuthService.sendBetterAuthResponse(res, enrichedResponse);
441
441
  return;
442
442
  }
443
443
  }
@@ -455,8 +455,9 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
455
455
  return next();
456
456
  }
457
457
 
458
- // Convert Web Standard Response to Express response using shared helper
459
- await sendWebResponse(res, response);
458
+ // Convert Web Standard Response to Express response, through the token policy (11.43.7): a forwarded route must
459
+ // not hand out what the framework's own sign-in would not
460
+ await this.betterAuthService.sendBetterAuthResponse(res, response);
460
461
  } catch (error) {
461
462
  // Log error with appropriate detail level
462
463
  if (this.isProd) {
@@ -0,0 +1,157 @@
1
+ import { isJwtShaped } from './core-better-auth-token.helper';
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
+ * - Untouched: error responses, non-JSON bodies, arrays, a JWT (`/token` hands one out on purpose), and a top-level
69
+ * `token` that is not the session token (another plugin's value).
70
+ *
71
+ * Returns the response itself when nothing changes, otherwise a new one with the same status and headers.
72
+ */
73
+ export async function presentSessionTokens(
74
+ response: globalThis.Response,
75
+ options: SessionTokenPresentation,
76
+ ): Promise<globalThis.Response> {
77
+ if (!response.ok || !(response.headers.get('content-type') ?? '').includes('application/json')) {
78
+ return response;
79
+ }
80
+ let body: unknown;
81
+ try {
82
+ body = await response.clone().json();
83
+ } catch {
84
+ return response;
85
+ }
86
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
87
+ return response;
88
+ }
89
+
90
+ const record = body as Record<string, unknown>;
91
+ const session =
92
+ record.session && typeof record.session === 'object' && !Array.isArray(record.session)
93
+ ? (record.session as Record<string, unknown>)
94
+ : undefined;
95
+ const sessionFieldToken = typeof session?.token === 'string' && session.token ? session.token : undefined;
96
+ const cookieToken = sessionTokenFromSetCookie(response, options.cookieName);
97
+ const topToken = typeof record.token === 'string' && record.token ? record.token : undefined;
98
+ const topIsSessionToken =
99
+ !!topToken &&
100
+ !isJwtShaped(topToken) &&
101
+ (topToken === cookieToken ||
102
+ topToken === sessionFieldToken ||
103
+ (await isLiveSessionToken(topToken, options.isSessionToken)));
104
+
105
+ if (!topIsSessionToken && !sessionFieldToken) {
106
+ return response;
107
+ }
108
+
109
+ const next: Record<string, unknown> = { ...record };
110
+ if (session && sessionFieldToken) {
111
+ const { token: _sessionToken, ...rest } = session;
112
+ next.session = rest;
113
+ }
114
+
115
+ if (!options.tokenInBody) {
116
+ if (topIsSessionToken) {
117
+ delete next.token;
118
+ }
119
+ } else {
120
+ // The session token the body should present: the top-level one, else the one this response just set
121
+ const source = topIsSessionToken ? topToken : !topToken ? cookieToken : undefined;
122
+ if (source) {
123
+ const presented = await options.resolveJwt(source);
124
+ if (presented) {
125
+ next.token = presented;
126
+ } else {
127
+ delete next.token;
128
+ }
129
+ }
130
+ }
131
+
132
+ const headers = new Headers();
133
+ response.headers.forEach((value, key) => {
134
+ if (key.toLowerCase() !== 'content-length' && key.toLowerCase() !== 'set-cookie') {
135
+ headers.set(key, value);
136
+ }
137
+ });
138
+ for (const cookie of response.headers.getSetCookie?.() ?? []) {
139
+ headers.append('set-cookie', cookie);
140
+ }
141
+ return new Response(JSON.stringify(next), { headers, status: response.status, statusText: response.statusText });
142
+ }
143
+
144
+ /** Asks {@link SessionTokenPresentation.isSessionToken}; a lookup that fails cannot vouch for anything */
145
+ async function isLiveSessionToken(
146
+ token: string,
147
+ isSessionToken: SessionTokenPresentation['isSessionToken'],
148
+ ): Promise<boolean> {
149
+ if (!isSessionToken) {
150
+ return false;
151
+ }
152
+ try {
153
+ return (await isSessionToken(token)) === true;
154
+ } catch {
155
+ return false;
156
+ }
157
+ }
@@ -47,7 +47,7 @@ import { CoreBetterAuthEmailVerificationService } from './core-better-auth-email
47
47
  import { CoreBetterAuthSignUpValidatorService } from './core-better-auth-signup-validator.service';
48
48
  import { isJwtShaped, isSessionToken } from './core-better-auth-token.helper';
49
49
  import { BetterAuthSessionUser, CoreBetterAuthUserMapper } from './core-better-auth-user.mapper';
50
- import { convertExpressHeaders, sendWebResponse, toWebRequest } from './core-better-auth-web.helper';
50
+ import { convertExpressHeaders, toWebRequest } from './core-better-auth-web.helper';
51
51
  import { CoreBetterAuthService } from './core-better-auth.service';
52
52
 
53
53
  // ===================================================================================================================
@@ -1092,7 +1092,8 @@ export class CoreBetterAuthController {
1092
1092
  this.logger.debug(`Better Auth handler response status: ${response.status}`);
1093
1093
 
1094
1094
  // Send the response back
1095
- await sendWebResponse(res, response);
1095
+ // Through the token policy: a forwarded route must not hand out what sign-in would not (11.43.7)
1096
+ await this.betterAuthService.sendBetterAuthResponse(res, response);
1096
1097
  } catch (error) {
1097
1098
  this.logger.error(`Better Auth handler error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1098
1099
 
@@ -15,10 +15,15 @@ import {
15
15
  sessionMiddleware,
16
16
  } from 'better-auth/api';
17
17
  import { Request } from 'express';
18
+ import type { Response as ExpressResponse } from 'express';
18
19
  import { importJWK, jwtVerify } from 'jose';
19
20
  import { Connection } from 'mongoose';
20
21
 
21
- import { shouldConvertSessionTokenToJwt } from '../../common/helpers/cookies.helper';
22
+ import {
23
+ isCookiesEnabled,
24
+ isExposeTokenInBodyEnabled,
25
+ shouldConvertSessionTokenToJwt,
26
+ } from '../../common/helpers/cookies.helper';
22
27
  import { maskEmail, maskToken } from '../../common/helpers/logging.helper';
23
28
  import { IBetterAuth, ICookiesConfig } from '../../common/interfaces/server-options.interface';
24
29
  import { ConfigService } from '../../common/services/config.service';
@@ -35,8 +40,14 @@ import {
35
40
  } from './core-better-auth-openapi.helper';
36
41
  import type { IBetterAuthOpenApiDocument, IBetterAuthRuntime } from './core-better-auth-openapi.helper';
37
42
  import { isJwtShaped } from './core-better-auth-token.helper';
43
+ import { presentSessionTokens } from './core-better-auth-session-token.helper';
38
44
  import { BetterAuthSessionUser } from './core-better-auth-user.mapper';
39
- import { convertExpressHeaders, parseCookieHeader, signCookieValueIfNeeded } from './core-better-auth-web.helper';
45
+ import {
46
+ convertExpressHeaders,
47
+ parseCookieHeader,
48
+ sendWebResponse,
49
+ signCookieValueIfNeeded,
50
+ } from './core-better-auth-web.helper';
40
51
  import {
41
52
  ACCOUNT_ISSUER_BACKFILL_ID,
42
53
  BACKFILL_MARKER_COLLECTION,
@@ -771,6 +782,53 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
771
782
  return `${this.getCookiePrefix()}.session_token`;
772
783
  }
773
784
 
785
+ /**
786
+ * Applies the sign-in token policy to a response Better-Auth's own handler produced (11.43.7).
787
+ *
788
+ * Routes the framework forwards to Better-Auth — two-factor verify, passkey verify, OTP and magic-link sign-in,
789
+ * get-session — answered with the opaque session token in the body, also in the default cookie mode, where the
790
+ * framework's own sign-in keeps it in an httpOnly cookie only, and as the raw token where sign-in hands out a JWT.
791
+ * See `presentSessionTokens()` (`core-better-auth-session-token.helper.ts`) for the rules.
792
+ *
793
+ * Override to present tokens differently; keep the cookie-mode rule, it is what keeps the session out of scripts.
794
+ */
795
+ async presentSessionTokens(response: globalThis.Response): Promise<globalThis.Response> {
796
+ const cookiesConfig = ConfigService.configFastButReadOnly?.cookies as boolean | ICookiesConfig | undefined;
797
+ return presentSessionTokens(response, {
798
+ cookieName: await this.sessionCookieNameOfInstance(),
799
+ isSessionToken: async (token) => !!(await this.getSessionByToken(token))?.session,
800
+ resolveJwt: (sessionToken) => this.resolveJwtToken(sessionToken),
801
+ tokenInBody: !isCookiesEnabled(cookiesConfig) || isExposeTokenInBodyEnabled(cookiesConfig),
802
+ });
803
+ }
804
+
805
+ /**
806
+ * The session cookie's name as the running Better-Auth instance sets it — `__Secure-` prefixed under
807
+ * `advanced.useSecureCookies`, renamed under `advanced.cookies.session_token.name` — falling back to
808
+ * {@link getSessionCookieName} when the instance cannot say.
809
+ */
810
+ protected async sessionCookieNameOfInstance(): Promise<string> {
811
+ try {
812
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
813
+ const name = context?.authCookies?.sessionToken?.name;
814
+ if (typeof name === 'string' && name) {
815
+ return name;
816
+ }
817
+ } catch {
818
+ // The configured name below is what the framework writes itself
819
+ }
820
+ return this.getSessionCookieName();
821
+ }
822
+
823
+ /**
824
+ * Sends a response of Better-Auth's handler to the client, through {@link presentSessionTokens}. Every place that
825
+ * forwards to the handler (the API middleware, the controller's catch-all) sends through here, so a forwarded route
826
+ * cannot hand a client a token the framework's own sign-in would not.
827
+ */
828
+ async sendBetterAuthResponse(res: ExpressResponse, response: globalThis.Response): Promise<void> {
829
+ await sendWebResponse(res, await this.presentSessionTokens(response));
830
+ }
831
+
774
832
  /**
775
833
  * Gets the cookie prefix (the `iam` in `iam.session_token`).
776
834
  *