@lenne.tech/nest-server 11.43.6 → 11.43.8

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 (24) hide show
  1. package/.claude/rules/better-auth.md +36 -0
  2. package/.claude/rules/testing.md +4 -4
  3. package/FRAMEWORK-API.md +1 -1
  4. package/dist/core/modules/better-auth/core-better-auth-api.middleware.d.ts +1 -0
  5. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +21 -3
  6. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  7. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.d.ts +8 -0
  8. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +119 -0
  9. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -0
  10. package/dist/core/modules/better-auth/core-better-auth.controller.js +1 -1
  11. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  12. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +5 -0
  13. package/dist/core/modules/better-auth/core-better-auth.service.js +40 -0
  14. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  15. package/dist/tsconfig.build.tsbuildinfo +1 -1
  16. package/docs/REQUEST-LIFECYCLE.md +14 -0
  17. package/migration-guides/11.43.6-to-11.43.7.md +67 -0
  18. package/migration-guides/11.43.7-to-11.43.8.md +91 -0
  19. package/package.json +7 -7
  20. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +2 -2
  21. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +39 -5
  22. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +194 -0
  23. package/src/core/modules/better-auth/core-better-auth.controller.ts +3 -2
  24. package/src/core/modules/better-auth/core-better-auth.service.ts +89 -2
@@ -675,6 +675,20 @@ 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. Since
687
+ > 11.43.8 a session record loses its `token` also inside an array (`list-sessions` names sessions by `id`;
688
+ > `POST /revoke-session` takes `{ sessionId }`, resolved by the API middleware among the caller's own
689
+ > sessions). A JWT (`/token`) and other plugins' tokens are left alone. See `.claude/rules/better-auth.md` §7
690
+ > "Forwarded responses".
691
+
678
692
  #### 2b. SecurityHeadersMiddleware
679
693
 
680
694
  Sets the browser security headers on **every** response — `X-Content-Type-Options`,
@@ -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()`
@@ -0,0 +1,91 @@
1
+ # Migration Guide: 11.43.7 → 11.43.8
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). Pin `better-auth`, `@better-auth/core` and `@better-auth/passkey` to 1.7.16 (§2) |
11
+
12
+ 11.43.8 is a security patch on the 11.x line, published under the dist-tag `latest-11` (backport of 12.6.2 / 12.7.0).
13
+
14
+ ## Quick Migration
15
+
16
+ ```bash
17
+ pnpm add @lenne.tech/nest-server@11.43.8
18
+ pnpm run update # nest-server-starter based projects
19
+ pnpm run build
20
+ pnpm test
21
+ ```
22
+
23
+ Vendor-mode projects update the core to the tag `11.43.8`: `/lt-dev:backend:update-nest-server-core --target 11.43.8`.
24
+ Without `--target` the updater syncs to the latest tag, which is on the 12.x line.
25
+
26
+ ## 1. list-sessions names sessions by id; revoke-session takes the id
27
+
28
+ **Why:** `GET /iam/list-sessions` answered every session of the user with its `token` — the bearer credential of every
29
+ device the user is signed in on, readable by any script on the page. 11.43.7 took the session token out of the other
30
+ answers the framework forwards to Better-Auth; this was the last one.
31
+
32
+ **What changed:**
33
+
34
+ | | Until 11.43.7 | From 11.43.8 |
35
+ |---|---|---|
36
+ | `GET /iam/list-sessions` | `[{ id, token, userId, expiresAt, … }]` | `[{ id, userId, expiresAt, … }]` — no `token`, in every mode |
37
+ | `POST /iam/revoke-session` | `{ token }` | `{ sessionId }` (new) or `{ token }` (unchanged) |
38
+
39
+ `{ sessionId }` is resolved among the sessions of the signed-in user. An unknown id, or the id of another user's
40
+ session, revokes nothing — the answer is the same as for a foreign token, so it discloses nothing. Revoking by `token`
41
+ stays for clients that hold one.
42
+
43
+ **Your frontend:** a "signed-in devices" screen that revokes a session by the `token` from `list-sessions` sends the
44
+ `id` instead:
45
+
46
+ ```typescript
47
+ await fetch(`${api}/iam/revoke-session`, {
48
+ body: JSON.stringify({ sessionId: session.id }),
49
+ credentials: 'include',
50
+ headers: { 'Content-Type': 'application/json' },
51
+ method: 'POST',
52
+ });
53
+ ```
54
+
55
+ Better-Auth's client (`authClient.revokeSession({ token })`) types the body as `{ token }`; send the request yourself
56
+ as above.
57
+
58
+ ## 2. better-auth 1.7.16 or newer
59
+
60
+ The peer range of `better-auth`, `@better-auth/core` and `@better-auth/passkey` is now `>=1.7.16 <1.8.0` (was
61
+ `>=1.7.7 <1.8.0`), the same as on the 12.6 line, and this release is tested against 1.7.16. `@lenne.tech/nuxt-extensions`
62
+ 1.26.0 requires `>=1.7.16` too, so a fullstack project's workspace check (same range in API and app) passes again.
63
+
64
+ ```bash
65
+ pnpm add better-auth@1.7.16 @better-auth/passkey@1.7.16 @better-auth/core@1.7.16
66
+ ```
67
+
68
+ Keep all three on the same exact version, in the API and in the app.
69
+
70
+ ## Compatibility Notes
71
+
72
+ | Pattern | Status |
73
+ |---|---|
74
+ | A client reading `token` from `list-sessions` | Gets none; use `id` and `revoke-session` with `{ sessionId }` |
75
+ | `revoke-session` with `{ token }` | Unchanged |
76
+ | `revoke-sessions`, `revoke-other-sessions`, sign-out | Unchanged |
77
+ | better-auth pinned to 1.7.7 – 1.7.15 | Below the new peer range; raise all three packages to 1.7.16 (§2) |
78
+ | A project subclass of `CoreBetterAuthService` / `CoreBetterAuthApiMiddleware` | `sessionTokenOfUser()` (public) and `resolveRevokeSessionId()` (protected) are new |
79
+
80
+ ## Troubleshooting
81
+
82
+ | Symptom | Cause | Fix |
83
+ |---|---|---|
84
+ | Revoking a device does nothing after the update | The screen sends the `token` from `list-sessions`, which is gone | Send `{ sessionId: session.id }` |
85
+
86
+ ## References
87
+
88
+ - `src/core/modules/better-auth/core-better-auth-session-token.helper.ts` — session records
89
+ - `src/core/modules/better-auth/core-better-auth-api.middleware.ts` — `resolveRevokeSessionId()`
90
+ - `src/core/modules/better-auth/core-better-auth.service.ts` — `sessionTokenOfUser()`
91
+ - `tests/session-token-exposure.e2e-spec.ts`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.43.6",
3
+ "version": "11.43.8",
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",
@@ -145,10 +145,10 @@
145
145
  "@aws-sdk/client-s3": ">=3.1045.0 <4",
146
146
  "@aws-sdk/lib-storage": ">=3.1045.0 <4",
147
147
  "@aws-sdk/s3-request-presigner": ">=3.1045.0 <4",
148
- "@better-auth/core": ">=1.7.7 <1.8.0",
149
- "@better-auth/passkey": ">=1.7.7 <1.8.0",
148
+ "@better-auth/core": ">=1.7.16 <1.8.0",
149
+ "@better-auth/passkey": ">=1.7.16 <1.8.0",
150
150
  "@tus/s3-store": ">=2.0.5 <3",
151
- "better-auth": ">=1.7.7 <1.8.0",
151
+ "better-auth": ">=1.7.16 <1.8.0",
152
152
  "bullmq": ">=5.16.0 <7",
153
153
  "ioredis": ">=5.0.0 <7"
154
154
  },
@@ -185,8 +185,8 @@
185
185
  "@aws-sdk/client-s3": "3.1152.0",
186
186
  "@aws-sdk/lib-storage": "3.1152.0",
187
187
  "@aws-sdk/s3-request-presigner": "3.1152.0",
188
- "@better-auth/core": "1.7.7",
189
- "@better-auth/passkey": "1.7.7",
188
+ "@better-auth/core": "1.7.16",
189
+ "@better-auth/passkey": "1.7.16",
190
190
  "@compodoc/compodoc": "2.0.0",
191
191
  "@nestjs/cli": "11.0.24",
192
192
  "@nestjs/schematics": "11.1.0",
@@ -203,7 +203,7 @@
203
203
  "@types/node": "26.6.5",
204
204
  "@types/passport": "1.0.17",
205
205
  "@vitest/coverage-v8": "4.1.12",
206
- "better-auth": "1.7.7",
206
+ "better-auth": "1.7.16",
207
207
  "bullmq": "6.3.16",
208
208
  "cross-env": "10.1.0",
209
209
  "ioredis": "6.0.0",
@@ -18,14 +18,14 @@ From `@lenne.tech/nest-server` 11.37.0, better-auth is **not** a dependency of t
18
18
  non-optional **peer dependency**, so your project declares and owns the version:
19
19
 
20
20
  ```bash
21
- pnpm add better-auth@1.7.7 @better-auth/passkey@1.7.7 @better-auth/core@1.7.7
21
+ pnpm add better-auth@1.7.16 @better-auth/passkey@1.7.16 @better-auth/core@1.7.16
22
22
  ```
23
23
 
24
24
  **Pin all three to the same exact version** — no `^`, no `~`. They are one release train, and a
25
25
  mixed set fails in ways the type checker does not catch.
26
26
 
27
27
  > **Do not rely on `pnpm install` to remind you.** On pnpm's default `autoInstallPeers: true` the
28
- > packages are installed silently at whatever version satisfies `>=1.7.7 <1.8.0` — your build stays
28
+ > packages are installed silently at whatever version satisfies `>=1.7.16 <1.8.0` — your build stays
29
29
  > green while the version is unpinned and free to drift. Verify with `pnpm why better-auth`.
30
30
 
31
31
  **Why peers rather than dependencies:** in a fullstack project the frontend talks to better-auth
@@ -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
  /**
@@ -123,6 +123,37 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
123
123
  return normalized;
124
124
  }
125
125
 
126
+ /**
127
+ * `POST /revoke-session` with `{ sessionId }` (11.43.8): `list-sessions` hands out session ids and no tokens, so a
128
+ * client names the session to end by its id. Better-Auth's route takes `{ token }` only; this looks the token up among
129
+ * the sessions of the signed-in user ({@link CoreBetterAuthService.sessionTokenOfUser}) and puts it into the body.
130
+ *
131
+ * An id that is unknown or belongs to another user becomes an empty token: Better-Auth then revokes nothing and
132
+ * answers as it does for a foreign token, so the answer says nothing about other users' sessions. A body that
133
+ * already carries a `token` is left as it is (revoking by token keeps working).
134
+ */
135
+ protected async resolveRevokeSessionId(req: Request, relativePath: string): Promise<void> {
136
+ if (req.method !== 'POST' || relativePath.replace(/\/+$/, '').toLowerCase() !== '/revoke-session') {
137
+ return;
138
+ }
139
+ const body = req.body as Record<string, unknown> | undefined;
140
+ const sessionId = body?.sessionId;
141
+ if (!body || typeof sessionId !== 'string' || !sessionId || (typeof body.token === 'string' && body.token)) {
142
+ return;
143
+ }
144
+ const caller = req as unknown as {
145
+ betterAuthSession?: { user?: { id?: unknown } };
146
+ betterAuthUser?: { id?: unknown };
147
+ };
148
+ const userId = caller.betterAuthSession?.user?.id ?? caller.betterAuthUser?.id;
149
+ const token =
150
+ typeof userId === 'string' && userId
151
+ ? await this.betterAuthService.sessionTokenOfUser(userId, sessionId)
152
+ : undefined;
153
+ const { sessionId: _sessionId, ...rest } = body;
154
+ req.body = { ...rest, token: token ?? '' };
155
+ }
156
+
126
157
  /**
127
158
  * Enforces the configured password length on the value the CLIENT actually sent.
128
159
  *
@@ -283,6 +314,8 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
283
314
  // Put a reset password into the shape sign-in expects BEFORE the body is
284
315
  // serialized, and keep the value for the legacy mirror below.
285
316
  const resetPassword = this.normalizeResetPassword(req, relativePath);
317
+ // `list-sessions` hands out ids, no tokens: revoke-session takes the id (11.43.8)
318
+ await this.resolveRevokeSessionId(req, relativePath);
286
319
 
287
320
  // Convert Express request to Web Standard Request with proper cookie signing
288
321
  const webRequest = await toWebRequest(req, {
@@ -376,7 +409,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
376
409
  this.logger.debug(`Stored challenge mapping with ID: ${challengeId.substring(0, 8)}...`);
377
410
 
378
411
  // Send the enhanced response
379
- await sendWebResponse(res, enhancedResponse);
412
+ await this.betterAuthService.sendBetterAuthResponse(res, enhancedResponse);
380
413
 
381
414
  return;
382
415
  } else {
@@ -437,7 +470,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
437
470
  });
438
471
 
439
472
  this.logger.debug('Enriched passkey verify response with user data');
440
- await sendWebResponse(res, enrichedResponse);
473
+ await this.betterAuthService.sendBetterAuthResponse(res, enrichedResponse);
441
474
  return;
442
475
  }
443
476
  }
@@ -455,8 +488,9 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
455
488
  return next();
456
489
  }
457
490
 
458
- // Convert Web Standard Response to Express response using shared helper
459
- await sendWebResponse(res, response);
491
+ // Convert Web Standard Response to Express response, through the token policy (11.43.7): a forwarded route must
492
+ // not hand out what the framework's own sign-in would not
493
+ await this.betterAuthService.sendBetterAuthResponse(res, response);
460
494
  } catch (error) {
461
495
  // Log error with appropriate detail level
462
496
  if (this.isProd) {
@@ -0,0 +1,194 @@
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
+ * - 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 (11.43.8). 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';
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
  *
@@ -980,6 +1038,35 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
980
1038
  }
981
1039
  }
982
1040
 
1041
+ /**
1042
+ * The token of the session `sessionId` — only when that session belongs to `userId` (11.43.8).
1043
+ *
1044
+ * `list-sessions` hands out session ids, no tokens, so a client revokes a session by its id; the API middleware asks
1045
+ * this to turn `POST /revoke-session { sessionId }` into the `{ token }` Better-Auth expects. Asked through
1046
+ * Better-Auth's own adapter (`internalAdapter.listSessions()`), so it reads wherever Better-Auth keeps its sessions.
1047
+ *
1048
+ * @returns the token, or `undefined` for an unknown id, a session of another user, or a failed lookup
1049
+ */
1050
+ async sessionTokenOfUser(userId: string, sessionId: string): Promise<string | undefined> {
1051
+ if (!userId || !sessionId) {
1052
+ return undefined;
1053
+ }
1054
+ try {
1055
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
1056
+ // Active sessions only — the query Better-Auth's own list-sessions runs. Without the filter the adapter's default
1057
+ // cap (100 rows, oldest first) could hide every current session behind expired rows MongoDB never removes.
1058
+ const sessions: unknown = await context?.internalAdapter?.listSessions?.(userId, { onlyActiveSessions: true });
1059
+ const match = (Array.isArray(sessions) ? sessions : []).find(
1060
+ (session: { id?: unknown; userId?: unknown }) =>
1061
+ String(session?.id) === sessionId && String(session?.userId) === String(userId),
1062
+ );
1063
+ return typeof match?.token === 'string' && match.token ? match.token : undefined;
1064
+ } catch (error) {
1065
+ this.logger.debug(`sessionTokenOfUser error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1066
+ return undefined;
1067
+ }
1068
+ }
1069
+
983
1070
  /**
984
1071
  * Revokes a specific session (logout for that session)
985
1072
  *