@lenne.tech/nest-server 12.11.0 → 12.11.2

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 (46) hide show
  1. package/.claude/rules/better-auth.md +11 -1
  2. package/.claude/rules/configurable-features.md +1 -1
  3. package/.claude/rules/testing.md +4 -4
  4. package/CLAUDE.md +1 -1
  5. package/FRAMEWORK-API.md +1 -1
  6. package/dist/core/common/helpers/http-stream-auth.helper.js +2 -2
  7. package/dist/core/common/helpers/http-stream-auth.helper.js.map +1 -1
  8. package/dist/core/modules/better-auth/better-auth-cookie-prefix.helper.d.ts +2 -0
  9. package/dist/core/modules/better-auth/better-auth-cookie-prefix.helper.js +5 -0
  10. package/dist/core/modules/better-auth/better-auth-cookie-prefix.helper.js.map +1 -1
  11. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +7 -3
  12. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  13. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.d.ts +1 -0
  14. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +3 -1
  15. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -1
  16. package/dist/core/modules/better-auth/core-better-auth.controller.js +1 -1
  17. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  18. package/dist/core/modules/better-auth/core-better-auth.middleware.js +4 -2
  19. package/dist/core/modules/better-auth/core-better-auth.middleware.js.map +1 -1
  20. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +6 -2
  21. package/dist/core/modules/better-auth/core-better-auth.service.js +4 -3
  22. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  23. package/docs/.navigation.yml +4 -0
  24. package/docs/REQUEST-LIFECYCLE.md +4 -1
  25. package/docs/choosing-a-database.md +4 -1
  26. package/docs/error-codes.md +4 -1
  27. package/docs/index.md +34 -0
  28. package/docs/{brevo-manual-test.md → internal/brevo-manual-test.md} +1 -1
  29. package/docs/native-driver-security.md +4 -1
  30. package/docs/offline-sync-protocol.md +4 -1
  31. package/docs/process-performance-optimization.md +158 -126
  32. package/docs/security-overrides.md +5 -2
  33. package/migration-guides/12.10.x-to-12.11.x.md +2 -0
  34. package/migration-guides/12.11.0-to-12.11.1.md +86 -0
  35. package/migration-guides/12.11.1-to-12.11.2.md +76 -0
  36. package/package.json +9 -9
  37. package/src/core/common/helpers/http-stream-auth.helper.ts +6 -6
  38. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +1 -0
  39. package/src/core/modules/better-auth/README.md +6 -6
  40. package/src/core/modules/better-auth/better-auth-cookie-prefix.helper.ts +17 -0
  41. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +7 -3
  42. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +18 -1
  43. package/src/core/modules/better-auth/core-better-auth.controller.ts +1 -1
  44. package/src/core/modules/better-auth/core-better-auth.middleware.ts +9 -4
  45. package/src/core/modules/better-auth/core-better-auth.service.ts +17 -4
  46. package/src/core/modules/sync/README.md +1 -1
@@ -0,0 +1,76 @@
1
+ # Migration Guide: 12.11.1 → 12.11.2
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | None. `resolveJwtCookieName()` and `DEFAULT_JWT_COOKIE_NAME` name the JWT cookie |
9
+ | **Bugfixes** | With `COOKIE_PREFIX`, the API reads a JWT-mode frontend's JWT cookie under `<prefix>-jwt-token`, the name `@lenne.tech/nuxt-extensions` writes (§1) |
10
+ | **Security** | None |
11
+ | **Migration Effort** | Package update. Only projects that set `COOKIE_PREFIX` and run in JWT mode (`cookies: false`) notice a difference |
12
+
13
+ ## Quick Migration
14
+
15
+ ```bash
16
+ pnpm add @lenne.tech/nest-server@12.11.2
17
+ pnpm run update # nest-server-starter based projects
18
+ pnpm run build
19
+ pnpm test
20
+ ```
21
+
22
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
23
+
24
+ ## 1. Bugfix: the JWT cookie follows `COOKIE_PREFIX`
25
+
26
+ **No action needed.** Keep `COOKIE_PREFIX` (API) and `NUXT_PUBLIC_COOKIE_PREFIX` (app) equal, as before.
27
+
28
+ In JWT mode the frontend keeps the Better-Auth JWT in a cookie as well as sending it as a bearer token. A request that
29
+ carries the cookie but no `Authorization` header is authenticated by `CoreBetterAuthMiddleware` from that cookie: a
30
+ server-side rendered page that forwards the browser's cookies, a passkey request from the app, and the in-place re-check
31
+ of an SSE stream (`registerHttpStream()`).
32
+
33
+ `@lenne.tech/nuxt-extensions` names that cookie `<NUXT_PUBLIC_COOKIE_PREFIX>-jwt-token` when a prefix is set. Up to
34
+ 12.11.1 the API read `lt-jwt-token` only. With a prefix such a request was anonymous, and Better-Auth's plugin routes
35
+ (passkey registration, two-factor) answered `401`.
36
+
37
+ | `COOKIE_PREFIX` | JWT cookie read since 12.11.2 | Before |
38
+ |---|---|---|
39
+ | not set | `lt-jwt-token` | `lt-jwt-token` |
40
+ | `acme` | `acme-jwt-token` | `lt-jwt-token` |
41
+
42
+ The prefix is sanitised by the same rule as on the frontend (`[A-Za-z0-9._-]`). The base path does not enter the name,
43
+ unlike the session cookie (`<prefix>.session_token`, else `iam.session_token`). There is no fallback to `lt-jwt-token`
44
+ while `COOKIE_PREFIX` is set: the prefix keeps the apps on one host apart, and the session cookie does not fall back
45
+ either.
46
+
47
+ ## 2. Dependencies
48
+
49
+ | Package | 12.11.1 | 12.11.2 |
50
+ |---|---|---|
51
+ | `ai` (optional peer) | 7.0.179 | 7.0.181 |
52
+ | `@aws-sdk/client-s3`, `@aws-sdk/lib-storage`, `@aws-sdk/s3-request-presigner` (optional peers) | 3.1175.0 | 3.1176.0 |
53
+
54
+ Maintenance releases without advisories; the peer ranges are unchanged. The dated `minimumReleaseAgeExclude` entry for
55
+ `mongoose@9.13.0` from 12.11.1 is removed; mongoose 9.13.0 has cleared the release-age gate.
56
+
57
+ ## Compatibility Notes
58
+
59
+ | Pattern | Status |
60
+ |---|---|
61
+ | No `COOKIE_PREFIX` | Unchanged |
62
+ | `COOKIE_PREFIX` with cookies (the default `cookies: true`) | Unchanged; the session cookie already followed the prefix |
63
+ | `COOKIE_PREFIX` with `cookies: false` and a matching `NUXT_PUBLIC_COOKIE_PREFIX` | Fixed: the JWT cookie is read |
64
+ | A frontend that sets `COOKIE_PREFIX` on the API but writes `lt-jwt-token` | No longer authenticated through the cookie. Set the same prefix on both sides |
65
+
66
+ ## Troubleshooting
67
+
68
+ | Symptom | Cause | Fix |
69
+ |---|---|---|
70
+ | Passkey or 2FA routes answer `401` in JWT mode with a cookie prefix | 12.11.1 or older read only `lt-jwt-token` | Update to 12.11.2 |
71
+ | Still `401` after the update | The API and the app use different prefixes | Set `COOKIE_PREFIX` and `NUXT_PUBLIC_COOKIE_PREFIX` to the same value |
72
+
73
+ ## Module Documentation
74
+
75
+ - `src/core/modules/better-auth/better-auth-cookie-prefix.helper.ts`: `resolveJwtCookieName()`, `resolveBetterAuthCookiePrefix()`
76
+ - `migration-guides/11.26.1-to-11.26.2.md`, §1: `COOKIE_PREFIX` and the frontend pairing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.11.0",
3
+ "version": "12.11.2",
4
4
  "type": "module",
5
5
  "description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
6
6
  "keywords": [
@@ -100,7 +100,7 @@
100
100
  "node": ">= 22.15",
101
101
  "pnpm": "^11.0.0"
102
102
  },
103
- "packageManager": "pnpm@11.28.13+sha512.d5caa9cdcd6067ac2902f9f44daa00b1288a73babf1e98f4f375b3a7583b1894b4d49f7527da8f5e1530198bb10e03adba321a1f015429dc2946ce8a7a9a8c65",
103
+ "packageManager": "pnpm@11.29.0+sha512.d913f9b37cd5fe6780052e809774edabb7bdcf69a6e6d9b8fd3b38bc052fa8a7d891b6c201a38fb504a07ffce2e5e8c262ef54fb8f57db62f22d353a30bc8a96",
104
104
  "dependencies": {
105
105
  "@apollo/server": "5.5.1",
106
106
  "@as-integrations/express5": "1.1.2",
@@ -244,9 +244,9 @@
244
244
  }
245
245
  },
246
246
  "devDependencies": {
247
- "@aws-sdk/client-s3": "3.1175.0",
248
- "@aws-sdk/lib-storage": "3.1175.0",
249
- "@aws-sdk/s3-request-presigner": "3.1175.0",
247
+ "@aws-sdk/client-s3": "3.1176.0",
248
+ "@aws-sdk/lib-storage": "3.1176.0",
249
+ "@aws-sdk/s3-request-presigner": "3.1176.0",
250
250
  "@better-auth/core": "1.7.23",
251
251
  "@better-auth/passkey": "1.7.23",
252
252
  "@compodoc/compodoc": "2.0.0",
@@ -274,15 +274,15 @@
274
274
  "@types/passport": "1.0.17",
275
275
  "@types/pg": "8.23.1",
276
276
  "@vitest/coverage-v8": "5.1.1",
277
- "ai": "7.0.179",
277
+ "ai": "7.0.181",
278
278
  "better-auth": "1.7.23",
279
279
  "bullmq": "6.7.8",
280
280
  "cross-env": "10.1.0",
281
281
  "drizzle-orm": "1.0.0-rc.5",
282
- "ioredis": "6.0.0",
282
+ "ioredis": "6.1.0",
283
283
  "kysely": "0.29.9",
284
- "mongodb": "7.8.0",
285
- "mongoose": "9.12.3",
284
+ "mongodb": "7.9.1",
285
+ "mongoose": "9.13.0",
286
286
  "mysql2": "3.24.6",
287
287
  "nodemon": "3.1.14",
288
288
  "otpauth": "9.6.0",
@@ -1,4 +1,5 @@
1
1
  import { hasApiTokenCredential } from '../../modules/api-token/core-api-token.helpers.js';
2
+ import { resolveJwtCookieName } from '../../modules/better-auth/better-auth-cookie-prefix.helper.js';
2
3
  import { isLegacyJwt } from '../../modules/better-auth/core-better-auth-token.helper.js';
3
4
  import { extractSessionToken, parseCookieHeader } from '../../modules/better-auth/core-better-auth-web.helper.js';
4
5
  import { getBetterAuthTokenService } from '../../modules/better-auth/core-better-auth.registry.js';
@@ -25,15 +26,13 @@ import type { ResolvedTenantContext } from '../services/core-tenant-context.regi
25
26
  * re-checked in place like a GraphQL WebSocket (`recheckHttpStreamInPlace()`).
26
27
  *
27
28
  * WHICH CREDENTIALS: the ones `CoreBetterAuthMiddleware` resolves, in its order — the bearer token of the
28
- * `Authorization` header (a Better-Auth JWT or session token), the `lt-jwt-token` cookie when no header was sent, then
29
+ * `Authorization` header (a Better-Auth JWT or session token), the JWT cookie when no header was sent (`lt-jwt-token`, or
30
+ * `<COOKIE_PREFIX>-jwt-token` with a prefix), then
29
31
  * the Better-Auth session cookie (`<prefix>.session_token`, signed or not) — each verified and loaded through
30
32
  * Better-Auth's token service, the one the IAM role guard uses. A legacy JWT is Passport's and an API token has checks
31
33
  * of its own: neither can be re-run here, and such a stream keeps ending on every re-check.
32
34
  */
33
35
 
34
- /** The cookie a JWT-mode frontend keeps the Better-Auth JWT in — the one `CoreBetterAuthMiddleware` reads. */
35
- const JWT_COOKIE_NAME = 'lt-jwt-token';
36
-
37
36
  /** What a request carried to authenticate, as it was when the stream was opened. */
38
37
  interface HttpStreamCredential {
39
38
  authorization?: string;
@@ -73,7 +72,8 @@ function credentialTokens(credential: HttpStreamCredential): string[] {
73
72
  add(token);
74
73
  }
75
74
  } else {
76
- const jwt = cookies?.[JWT_COOKIE_NAME];
75
+ // The cookie `CoreBetterAuthMiddleware` reads: `<COOKIE_PREFIX>-jwt-token`, else `lt-jwt-token` (12.11.2)
76
+ const jwt = cookies?.[resolveJwtCookieName()];
77
77
  if (typeof jwt === 'string' && jwt.split('.').length === 3 && !isLegacy(jwt)) {
78
78
  add(jwt);
79
79
  }
@@ -90,7 +90,7 @@ function credentialTokens(credential: HttpStreamCredential): string[] {
90
90
 
91
91
  /**
92
92
  * Build the re-authentication of an HTTP stream from the request that opened it: a function that re-runs the
93
- * request's Better-Auth credential (bearer token, `lt-jwt-token` cookie, session cookie — see the file comment) and
93
+ * request's Better-Auth credential (bearer token, JWT cookie, session cookie — see the file comment) and
94
94
  * resolves to the user it authenticates as NOW, or to `null` when it no longer does (a signed-out or expired session,
95
95
  * an expired JWT).
96
96
  *
@@ -505,6 +505,7 @@ assignment (README → "Sign-in through a provider alone"):
505
505
  | Missing `signUpValidator` in custom Resolver (v11.13.0+) | Sign-up validation not working | Add `@Optional() signUpValidator?: CoreBetterAuthSignUpValidatorService` to constructor and pass to `super()` |
506
506
  | Missing `termsAndPrivacyAccepted` parameter in Resolver (v11.13.0+) | GraphQL error "Unknown argument" | Add `@Args('termsAndPrivacyAccepted', { nullable: true })` to `betterAuthSignUp` method |
507
507
  | A JWT client keeps the JWT it had before `verify-totp` while enabling 2FA (12.11.0+) | `401` right after 2FA was switched on | Use the `token` of the `verify-totp` answer: the first confirmation replaces the session, and a JWT is bound to its session |
508
+ | A JWT client keeps the JWT it had before `two-factor/disable` (12.11.0) | Signed out right after 2FA was switched off | Update to 12.11.1 and use the `token` of the answer: turning 2FA off replaces the session |
508
509
  | An SSO-only project (`emailAndPassword.enabled: false`) expects Passkey or 2FA (12.11.0+) | Passkey and 2FA routes answer `404` | Switch them on deliberately with `passkey: true` / `twoFactor: true` — they keep a user signed in after the provider withdrew the assignment |
509
510
 
510
511
  ---
@@ -712,12 +712,12 @@ A project that signs in through a single sign-on provider alone (`emailAndPasswo
712
712
  Microsoft Entra) expects the provider to decide who gets in. Since 12.11.0 nothing the framework offers keeps someone
713
713
  in after the provider withdrew the assignment or role:
714
714
 
715
- | What | Since 12.11.0 | Before |
716
- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
717
- | Passkey and two-factor | Off while sign-in runs through a provider alone (`emailAndPassword` off and no plugin with a sign-in route of its own — `username()` / `phoneNumber()` keep both on); `passkey: true` / `twoFactor: true` (or `{ enabled: true, … }`) switches them on deliberately. Their routes answer 404, also for a passkey registered earlier. The boot names what it switched off, as a warning for a factor with settings of its own | On: a passkey registered once after a provider sign-in kept signing its owner in |
718
- | A client-submitted id token (`POST /iam/sign-in/social` / `/iam/link-social` with `idToken`) | Refused with `ID_TOKEN_NOT_SUPPORTED` for every provider unless the provider sets `disableIdTokenSignIn: false` (native apps, Google One Tap). The redirect flow is unaffected | Accepted: an id token kept from an earlier sign-in (`/iam/get-access-token` hands it out) signed its owner in again for about an hour, without asking the provider |
719
- | The Better-Auth JWT | Bound to the session it was issued from (claim `sid`): refused once that session is signed out, revoked, expired or its user deleted — at once on this replica and, with `redis`, on every replica; otherwise within 10 s. A JWT without `sid` (issued before 12.11.0) is refused, and the client fetches a new one with its session (`GET /iam/token`). After a session rotation (the first `verify-totp` while enabling 2FA) the answer carries the JWT of the new session | Valid until its own expiry (15 minutes) after a sign-out, and a JWT client's sign-out ended no session at all |
720
- | `GET /iam/features` | Reports `emailAndPassword` (also in the GraphQL `betterAuthFeatures`), so a frontend can hide the e-mail form | — |
715
+ | What | Since 12.11.0 | Before |
716
+ | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
717
+ | Passkey and two-factor | Off while sign-in runs through a provider alone (`emailAndPassword` off and no plugin with a sign-in route of its own — `username()` / `phoneNumber()` keep both on); `passkey: true` / `twoFactor: true` (or `{ enabled: true, … }`) switches them on deliberately. Their routes answer 404, also for a passkey registered earlier. The boot names what it switched off, as a warning for a factor with settings of its own | On: a passkey registered once after a provider sign-in kept signing its owner in |
718
+ | A client-submitted id token (`POST /iam/sign-in/social` / `/iam/link-social` with `idToken`) | Refused with `ID_TOKEN_NOT_SUPPORTED` for every provider unless the provider sets `disableIdTokenSignIn: false` (native apps, Google One Tap). The redirect flow is unaffected | Accepted: an id token kept from an earlier sign-in (`/iam/get-access-token` hands it out) signed its owner in again for about an hour, without asking the provider |
719
+ | The Better-Auth JWT | Bound to the session it was issued from (claim `sid`): refused once that session is signed out, revoked, expired or its user deleted — at once on this replica and, with `redis`, on every replica; otherwise within 10 s. A JWT without `sid` (issued before 12.11.0) is refused, and the client fetches a new one with its session (`GET /iam/token`). After a session rotation (the first `verify-totp` while enabling 2FA; since 12.11.1 also `two-factor/disable` and enabling with OTP) the answer carries the JWT of the new session | Valid until its own expiry (15 minutes) after a sign-out, and a JWT client's sign-out ended no session at all |
720
+ | `GET /iam/features` | Reports `emailAndPassword` (also in the GraphQL `betterAuthFeatures`), so a frontend can hide the e-mail form | — |
721
721
 
722
722
  A session that is not extended while it is used ends a fixed time after the sign-in, so a withdrawal at the provider
723
723
  reaches it at the latest then:
@@ -58,6 +58,23 @@ export function resolveBetterAuthSessionCookieName(basePath: string, env: NodeJS
58
58
  return `${resolveBetterAuthCookiePrefix(basePath, env)}.session_token`;
59
59
  }
60
60
 
61
+ /** The name of the JWT cookie without `COOKIE_PREFIX`, the one `@lenne.tech/nuxt-extensions` writes by default. */
62
+ export const DEFAULT_JWT_COOKIE_NAME = 'lt-jwt-token';
63
+
64
+ /**
65
+ * The cookie a JWT-mode frontend keeps the Better-Auth JWT in (12.11.2): `<COOKIE_PREFIX>-jwt-token` when `COOKIE_PREFIX`
66
+ * is set, otherwise `lt-jwt-token`. `@lenne.tech/nuxt-extensions` names it the same way from `NUXT_PUBLIC_COOKIE_PREFIX`,
67
+ * sanitised by the same rule. Unlike the session cookie, the basePath never enters the name.
68
+ *
69
+ * There is no fallback to `lt-jwt-token` while `COOKIE_PREFIX` is set: the prefix isolates the apps on one host, and
70
+ * the session cookie does not fall back either. Before 12.11.2 the API read `lt-jwt-token` only, so with a prefix
71
+ * every request without an `Authorization` header (SSR with forwarded cookies, a stream re-check) was anonymous.
72
+ */
73
+ export function resolveJwtCookieName(env: NodeJS.ProcessEnv = process.env): string {
74
+ const explicit = sanitizeCookiePrefix(typeof env.COOKIE_PREFIX === 'string' ? env.COOKIE_PREFIX : '');
75
+ return explicit ? `${explicit}-jwt-token` : DEFAULT_JWT_COOKIE_NAME;
76
+ }
77
+
61
78
  /**
62
79
  * Detect a Better-Auth cookie-prefix drift between the value the NestJS layer
63
80
  * resolves (via {@link resolveBetterAuthCookiePrefix}) and a programmatic
@@ -504,7 +504,9 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
504
504
  this.logger.debug(`Stored challenge mapping with ID: ${challengeId.substring(0, 8)}...`);
505
505
 
506
506
  // Send the enhanced response
507
- await this.betterAuthService.sendBetterAuthResponse(res, enhancedResponse);
507
+ await this.betterAuthService.sendBetterAuthResponse(res, enhancedResponse, {
508
+ requestSessionToken: sessionToken,
509
+ });
508
510
 
509
511
  return;
510
512
  } else {
@@ -565,7 +567,9 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
565
567
  });
566
568
 
567
569
  this.logger.debug('Enriched passkey verify response with user data');
568
- await this.betterAuthService.sendBetterAuthResponse(res, enrichedResponse);
570
+ await this.betterAuthService.sendBetterAuthResponse(res, enrichedResponse, {
571
+ requestSessionToken: sessionToken,
572
+ });
569
573
  return;
570
574
  }
571
575
  }
@@ -585,7 +589,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
585
589
 
586
590
  // Convert Web Standard Response to Express response, through the token policy (12.6.1): a forwarded route must
587
591
  // not hand out what the framework's own sign-in would not
588
- await this.betterAuthService.sendBetterAuthResponse(res, response);
592
+ await this.betterAuthService.sendBetterAuthResponse(res, response, { requestSessionToken: sessionToken });
589
593
  } catch (error) {
590
594
  // A refused request (the password length policy) is an answer, not a handler failure. Nest's middleware
591
595
  // proxy hands a thrown exception to the exception filters, so it is rendered like the same refusal from a
@@ -18,6 +18,14 @@ export interface SessionTokenPresentation {
18
18
  * (`CoreBetterAuthService.resolveJwtToken()`), the token itself when it is off, `undefined` when a conversion failed
19
19
  */
20
20
  resolveJwt: (sessionToken: string) => Promise<string | undefined>;
21
+ /**
22
+ * The session token the request was made with: its session cookie, a bearer session token, or the session of its
23
+ * JWT (`getJwtSession()`). It tells a rotation from a refresh in an answer that names no token itself: a session
24
+ * cookie with ANOTHER token replaced the request's session (`/two-factor/disable` answers `{ status: true }`,
25
+ * `/two-factor/enable` with OTP `{ method: 'otp' }`), a refresh sets the cookie of the same session (12.11.1).
26
+ * Unset or empty: such answers stay as they are.
27
+ */
28
+ requestSessionToken?: null | string;
21
29
  /**
22
30
  * Whether the body may carry a token at all: cookies disabled (JWT-only mode) or `cookies.exposeTokenInBody`.
23
31
  * `false` in the default cookie mode, where the session lives in an httpOnly cookie and nowhere else.
@@ -76,6 +84,10 @@ export function sessionTokenFromSetCookie(response: globalThis.Response, cookieN
76
84
  * rotated the session (the first verify-totp while enabling 2FA answers with the token of the session it deleted):
77
85
  * that token is treated as the session token — removed in cookie mode, replaced by the JWT of the NEW session where
78
86
  * the body carries one (12.7.1). A plugin's own `{ token }` next to a refreshed session cookie is not a rotation.
87
+ * - A response without a top-level token that sets a session cookie for another session than the request's
88
+ * ({@link SessionTokenPresentation.requestSessionToken}) replaced the request's session: two-factor disable, and
89
+ * enable with OTP or `skipVerificationOnEnable`. Where the body carries a token it gains the JWT of the new session;
90
+ * the JWT the client holds names the deleted one, and without a session cookie it cannot fetch another (12.11.1).
79
91
  * - Untouched: error responses, non-JSON bodies, a JWT (`/token` hands one out on purpose), and a top-level `token`
80
92
  * that is not the session token (another plugin's value).
81
93
  *
@@ -125,6 +137,11 @@ export async function presentSessionTokens(
125
137
  const answersWithUser = !!record.user && typeof record.user === 'object' && !Array.isArray(record.user);
126
138
  const rotatedFrom =
127
139
  answersWithUser && !!topToken && !isJwtShaped(topToken) && !!cookieToken && topToken !== cookieToken;
140
+ // An answer naming no token that replaced the REQUEST's session (12.11.1): two-factor disable answers
141
+ // `{ status: true }`, the client's JWT names the session that was just deleted. A refresh sets the cookie of the
142
+ // request's own session, so only another token counts.
143
+ const requestToken = typeof options.requestSessionToken === 'string' ? options.requestSessionToken : '';
144
+ const replacedRequestSession = !topToken && !!requestToken && !!cookieToken && cookieToken !== requestToken;
128
145
  const topIsSessionToken =
129
146
  !!topToken &&
130
147
  !isJwtShaped(topToken) &&
@@ -133,7 +150,7 @@ export async function presentSessionTokens(
133
150
  topToken === sessionFieldToken ||
134
151
  (await isLiveSessionToken(topToken, options.isSessionToken)));
135
152
 
136
- if (!topIsSessionToken && !sessionFieldToken) {
153
+ if (!topIsSessionToken && !sessionFieldToken && !(options.tokenInBody && replacedRequestSession)) {
137
154
  return response;
138
155
  }
139
156
 
@@ -1171,7 +1171,7 @@ export class CoreBetterAuthController {
1171
1171
 
1172
1172
  // Send the response back
1173
1173
  // Through the token policy: a forwarded route must not hand out what sign-in would not (12.6.1)
1174
- await this.betterAuthService.sendBetterAuthResponse(res, response);
1174
+ await this.betterAuthService.sendBetterAuthResponse(res, response, { requestSessionToken: sessionToken });
1175
1175
  } catch (error) {
1176
1176
  this.logger.error(`Better Auth handler error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1177
1177
 
@@ -2,6 +2,7 @@ import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
2
2
  import { NextFunction, Request, Response } from 'express';
3
3
 
4
4
  import { hasApiTokenCredential } from '../api-token/core-api-token.helpers.js';
5
+ import { resolveJwtCookieName } from './better-auth-cookie-prefix.helper.js';
5
6
  import { isLegacyJwt } from './core-better-auth-token.helper.js';
6
7
  import { BetterAuthSessionUser, CoreBetterAuthUserMapper, MappedUser } from './core-better-auth-user.mapper.js';
7
8
  import { convertExpressHeaders, extractSessionToken } from './core-better-auth-web.helper.js';
@@ -143,14 +144,18 @@ export class CoreBetterAuthMiddleware implements NestMiddleware {
143
144
 
144
145
  // Strategy 2: Try JWT from cookie (for JWT mode when frontend stores JWT as cookie)
145
146
  // In JWT mode (cookies=false), the frontend may store the JWT in a cookie
146
- // (e.g., lt-jwt-token) instead of sending it as an Authorization header.
147
+ // (`lt-jwt-token`, `<COOKIE_PREFIX>-jwt-token` with a prefix) instead of sending it as an Authorization header.
147
148
  // This bridges the gap between cookie-based frontend storage and JWT verification.
148
149
  if (!req.user && !req.headers.authorization && this.betterAuthService.isJwtEnabled()) {
149
150
  try {
150
- // Try parsed cookies first, then raw header (cookie-parser may not have run yet)
151
- let jwtFromCookie = req.cookies?.['lt-jwt-token'];
151
+ // Try parsed cookies first, then raw header (cookie-parser may not have run yet). The name follows
152
+ // COOKIE_PREFIX like the frontend's (`<prefix>-jwt-token`, else `lt-jwt-token`; 12.11.2).
153
+ const jwtCookieName = resolveJwtCookieName();
154
+ let jwtFromCookie = req.cookies?.[jwtCookieName];
152
155
  if (!jwtFromCookie && req.headers.cookie) {
153
- const match = req.headers.cookie.match(/(?:^|;\s*)lt-jwt-token=([^;]+)/);
156
+ const match = req.headers.cookie.match(
157
+ new RegExp(`(?:^|;\\s*)${jwtCookieName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}=([^;]+)`),
158
+ );
154
159
  if (match) {
155
160
  jwtFromCookie = decodeURIComponent(match[1]);
156
161
  }
@@ -828,13 +828,21 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
828
828
  * framework's own sign-in keeps it in an httpOnly cookie only, and as the raw token where sign-in hands out a JWT.
829
829
  * See `presentSessionTokens()` (`core-better-auth-session-token.helper.ts`) for the rules.
830
830
  *
831
+ * `requestSessionToken` is the session token the request was forwarded with (12.11.1): an answer that replaced that
832
+ * session without naming a token (two-factor disable) then carries the JWT of the new session where the body may carry
833
+ * a token.
834
+ *
831
835
  * Override to present tokens differently; keep the cookie-mode rule, it is what keeps the session out of scripts.
832
836
  */
833
- async presentSessionTokens(response: globalThis.Response): Promise<globalThis.Response> {
837
+ async presentSessionTokens(
838
+ response: globalThis.Response,
839
+ options?: { requestSessionToken?: null | string },
840
+ ): Promise<globalThis.Response> {
834
841
  const cookiesConfig = ConfigService.configFastButReadOnly?.cookies as boolean | ICookiesConfig | undefined;
835
842
  return presentSessionTokens(response, {
836
843
  cookieName: await this.sessionCookieNameOfInstance(),
837
844
  isSessionToken: async (token) => !!(await this.getSessionByToken(token))?.session,
845
+ requestSessionToken: options?.requestSessionToken,
838
846
  resolveJwt: (sessionToken) => this.resolveJwtToken(sessionToken),
839
847
  tokenInBody: !isCookiesEnabled(cookiesConfig) || isExposeTokenInBodyEnabled(cookiesConfig),
840
848
  });
@@ -861,10 +869,15 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
861
869
  /**
862
870
  * Sends a response of Better-Auth's handler to the client, through {@link presentSessionTokens}. Every place that
863
871
  * forwards to the handler (the API middleware, the controller's catch-all) sends through here, so a forwarded route
864
- * cannot hand a client a token the framework's own sign-in would not.
872
+ * cannot hand a client a token the framework's own sign-in would not. Pass the session token the request was
873
+ * forwarded with (`requestSessionToken`), so an answer that replaced that session carries the new one's JWT (12.11.1).
865
874
  */
866
- async sendBetterAuthResponse(res: ExpressResponse, response: globalThis.Response): Promise<void> {
867
- await sendWebResponse(res, await this.presentSessionTokens(response));
875
+ async sendBetterAuthResponse(
876
+ res: ExpressResponse,
877
+ response: globalThis.Response,
878
+ options?: { requestSessionToken?: null | string },
879
+ ): Promise<void> {
880
+ await sendWebResponse(res, await this.presentSessionTokens(response, options));
868
881
  }
869
882
 
870
883
  /**
@@ -141,7 +141,7 @@ A hint tells a connected client that pulling is worthwhile; sync works without t
141
141
  stream is registered in the same registry and re-checked at once on an invalidation naming the caller or their
142
142
  tenant, and otherwise before the first hint after `graphQl.subscriptionRevalidationMs`.
143
143
  - **In place (12.11.0)** when the stream was opened with a Better-Auth credential — the session cookie, a bearer
144
- session token or Better-Auth JWT, the `lt-jwt-token` cookie: the re-check runs that credential again
144
+ session token or Better-Auth JWT, the JWT cookie (`lt-jwt-token`, `<COOKIE_PREFIX>-jwt-token` with a prefix): the re-check runs that credential again
145
145
  (`createHttpStreamReauthenticator()`) and the tenant resolution, like a WebSocket's. Unchanged rights keep the
146
146
  stream open and the hint is delivered without a reconnect; changed user id, roles, verification or tenant scope
147
147
  close it (`Closing SSE hint stream of user …: User authorization changed` / `Session no longer valid` /