@lenne.tech/nest-server 12.10.1 → 12.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/.claude/rules/better-auth.md +28 -0
  2. package/.claude/rules/configurable-features.md +11 -9
  3. package/.claude/rules/package-management.md +1 -1
  4. package/.claude/rules/role-system.md +4 -1
  5. package/.claude/rules/testing.md +4 -4
  6. package/CLAUDE.md +6 -1
  7. package/FRAMEWORK-API.md +2 -1
  8. package/dist/core/common/decorators/unified-field.decorator.js +5 -2
  9. package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
  10. package/dist/core/common/helpers/config.helper.js +31 -9
  11. package/dist/core/common/helpers/config.helper.js.map +1 -1
  12. package/dist/core/common/helpers/graceful-shutdown.helper.js +3 -1
  13. package/dist/core/common/helpers/graceful-shutdown.helper.js.map +1 -1
  14. package/dist/core/common/helpers/graphql-ws-connection.helper.d.ts +8 -3
  15. package/dist/core/common/helpers/graphql-ws-connection.helper.js +44 -0
  16. package/dist/core/common/helpers/graphql-ws-connection.helper.js.map +1 -1
  17. package/dist/core/common/helpers/http-stream-auth.helper.d.ts +13 -0
  18. package/dist/core/common/helpers/http-stream-auth.helper.js +90 -0
  19. package/dist/core/common/helpers/http-stream-auth.helper.js.map +1 -0
  20. package/dist/core/common/helpers/shutdown-state.helper.d.ts +3 -0
  21. package/dist/core/common/helpers/shutdown-state.helper.js +11 -0
  22. package/dist/core/common/helpers/shutdown-state.helper.js.map +1 -0
  23. package/dist/core/common/interfaces/cron-job-config-with-utc-offset.interface.d.ts +1 -1
  24. package/dist/core/common/interfaces/cron-job-config.interface.d.ts +1 -1
  25. package/dist/core/common/interfaces/server-options.interface.d.ts +14 -0
  26. package/dist/core/common/services/core-cron-jobs.service.d.ts +13 -0
  27. package/dist/core/common/services/core-cron-jobs.service.js +129 -4
  28. package/dist/core/common/services/core-cron-jobs.service.js.map +1 -1
  29. package/dist/core/modules/better-auth/better-auth.config.js +48 -4
  30. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  31. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +7 -3
  32. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  33. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.d.ts +8 -0
  34. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js +47 -0
  35. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js.map +1 -0
  36. package/dist/core/modules/better-auth/core-better-auth-models.d.ts +1 -0
  37. package/dist/core/modules/better-auth/core-better-auth-models.js +7 -0
  38. package/dist/core/modules/better-auth/core-better-auth-models.js.map +1 -1
  39. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.d.ts +1 -0
  40. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +3 -1
  41. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -1
  42. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.d.ts +11 -0
  43. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js +62 -0
  44. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js.map +1 -0
  45. package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +1 -0
  46. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +28 -1
  47. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  48. package/dist/core/modules/better-auth/core-better-auth.controller.js +3 -2
  49. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  50. package/dist/core/modules/better-auth/core-better-auth.middleware.js +2 -2
  51. package/dist/core/modules/better-auth/core-better-auth.middleware.js.map +1 -1
  52. package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -0
  53. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  54. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +16 -2
  55. package/dist/core/modules/better-auth/core-better-auth.service.js +109 -22
  56. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  57. package/dist/core/modules/health-check/core-health-check-readiness.controller.d.ts +6 -0
  58. package/dist/core/modules/health-check/core-health-check-readiness.controller.js +36 -0
  59. package/dist/core/modules/health-check/core-health-check-readiness.controller.js.map +1 -0
  60. package/dist/core/modules/health-check/core-health-check.helpers.d.ts +10 -0
  61. package/dist/core/modules/health-check/core-health-check.helpers.js +31 -0
  62. package/dist/core/modules/health-check/core-health-check.helpers.js.map +1 -0
  63. package/dist/core/modules/health-check/core-health-check.module.d.ts +9 -0
  64. package/dist/core/modules/health-check/core-health-check.module.js +13 -2
  65. package/dist/core/modules/health-check/core-health-check.module.js.map +1 -1
  66. package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -1
  67. package/dist/core/modules/health-check/core-health-check.service.js +66 -29
  68. package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
  69. package/dist/core/modules/sync/core-sync.service.d.ts +2 -0
  70. package/dist/core/modules/sync/core-sync.service.js +11 -1
  71. package/dist/core/modules/sync/core-sync.service.js.map +1 -1
  72. package/dist/core.module.js +5 -1
  73. package/dist/core.module.js.map +1 -1
  74. package/dist/index.d.ts +4 -0
  75. package/dist/index.js +4 -0
  76. package/dist/index.js.map +1 -1
  77. package/dist/main.js.map +1 -1
  78. package/docs/.navigation.yml +4 -0
  79. package/docs/REQUEST-LIFECYCLE.md +8 -5
  80. package/docs/choosing-a-database.md +4 -1
  81. package/docs/error-codes.md +4 -1
  82. package/docs/index.md +34 -0
  83. package/docs/{brevo-manual-test.md → internal/brevo-manual-test.md} +1 -1
  84. package/docs/native-driver-security.md +4 -1
  85. package/docs/offline-sync-protocol.md +9 -4
  86. package/docs/process-performance-optimization.md +158 -126
  87. package/docs/security-overrides.md +5 -2
  88. package/migration-guides/12.10.x-to-12.11.x.md +297 -0
  89. package/migration-guides/12.11.0-to-12.11.1.md +86 -0
  90. package/package.json +20 -20
  91. package/src/core/common/decorators/unified-field.decorator.ts +14 -4
  92. package/src/core/common/helpers/config.helper.ts +55 -8
  93. package/src/core/common/helpers/graceful-shutdown.helper.ts +10 -3
  94. package/src/core/common/helpers/graphql-ws-connection.helper.ts +99 -4
  95. package/src/core/common/helpers/http-stream-auth.helper.ts +197 -0
  96. package/src/core/common/helpers/shutdown-state.helper.ts +28 -0
  97. package/src/core/common/interfaces/cron-job-config-with-utc-offset.interface.ts +1 -1
  98. package/src/core/common/interfaces/cron-job-config.interface.ts +1 -1
  99. package/src/core/common/interfaces/server-options.interface.ts +113 -1
  100. package/src/core/common/services/core-cron-jobs.service.ts +241 -14
  101. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +27 -10
  102. package/src/core/modules/better-auth/README.md +37 -8
  103. package/src/core/modules/better-auth/better-auth.config.ts +83 -12
  104. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +8 -4
  105. package/src/core/modules/better-auth/core-better-auth-jwt-session.cache.ts +104 -0
  106. package/src/core/modules/better-auth/core-better-auth-models.ts +5 -0
  107. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +18 -1
  108. package/src/core/modules/better-auth/core-better-auth-sign-in-factors.helper.ts +105 -0
  109. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +37 -1
  110. package/src/core/modules/better-auth/core-better-auth.controller.ts +7 -4
  111. package/src/core/modules/better-auth/core-better-auth.middleware.ts +4 -3
  112. package/src/core/modules/better-auth/core-better-auth.module.ts +1 -1
  113. package/src/core/modules/better-auth/core-better-auth.resolver.ts +1 -0
  114. package/src/core/modules/better-auth/core-better-auth.service.ts +177 -31
  115. package/src/core/modules/health-check/core-health-check-readiness.controller.ts +27 -0
  116. package/src/core/modules/health-check/core-health-check.helpers.ts +65 -0
  117. package/src/core/modules/health-check/core-health-check.module.ts +37 -2
  118. package/src/core/modules/health-check/core-health-check.service.ts +154 -59
  119. package/src/core/modules/sync/README.md +18 -6
  120. package/src/core/modules/sync/core-sync.service.ts +35 -6
  121. package/src/core.module.ts +9 -1
  122. package/src/index.ts +4 -0
  123. package/src/main.ts +2 -1
@@ -357,7 +357,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
357
357
  // Extract session token from cookies or Authorization header.
358
358
  // In JWT mode, extractSessionToken correctly returns null for JWTs.
359
359
  // Fall back to the session resolved by CoreBetterAuthMiddleware (which
360
- // resolves JWTs to DB sessions via getActiveSessionForUser).
360
+ // resolves a JWT to its own DB session via getJwtSession()).
361
361
  let sessionToken = extractSessionToken(req, basePath);
362
362
  if (!sessionToken) {
363
363
  const betterAuthReq = req as any;
@@ -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
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Which sessions a Better-Auth JWT may still act for (12.11.0) — an import-free leaf, so the session-deletion hook in
3
+ * `better-auth.config.ts`, `CoreBetterAuthService` and the user mapper's Redis broadcast reach the same entries
4
+ * without importing each other.
5
+ *
6
+ * A JWT carries the id of the session it was issued from (`sid`). `CoreBetterAuthService.verifyJwtToken()` accepts it
7
+ * only while that session exists, belongs to the token's subject and has not expired; the answer is kept here for a
8
+ * few seconds, and a deleted session is forgotten at once (`jwtSessionEnded()`), on every replica where Redis
9
+ * carries the broadcast. Before 12.11.0 a JWT stayed valid until its own expiry (15 minutes by default) after a
10
+ * sign-out, a revoked session or a deleted user.
11
+ *
12
+ * Process-local and bounded: at most {@link JWT_SESSION_CACHE_MAX} entries, the oldest evicted first.
13
+ */
14
+
15
+ /** Most sessions the cache holds; beyond it the oldest entry is evicted. */
16
+ export const JWT_SESSION_CACHE_MAX = 10_000;
17
+
18
+ interface JwtSessionEntry {
19
+ live: boolean;
20
+ /** The session with its user, when a lookup fetched them (`CoreBetterAuthService.getJwtSession()`). */
21
+ record?: unknown;
22
+ /** Epoch milliseconds until which the answer stands. */
23
+ until: number;
24
+ userId: string;
25
+ }
26
+
27
+ const entries = new Map<string, JwtSessionEntry>();
28
+
29
+ let broadcaster: ((sessionId: string) => void) | undefined;
30
+
31
+ /**
32
+ * The cached answer for the session `sessionId` of `userId`: `true` / `false` while it stands, `undefined` when it has
33
+ * to be asked again. An entry for another user never answers `true`.
34
+ */
35
+ export function cachedJwtSession(sessionId: string, userId: string, now = Date.now()): boolean | undefined {
36
+ const entry = entries.get(sessionId);
37
+ if (!entry) {
38
+ return undefined;
39
+ }
40
+ if (entry.until <= now) {
41
+ entries.delete(sessionId);
42
+ return undefined;
43
+ }
44
+ return entry.live && entry.userId === userId;
45
+ }
46
+
47
+ /**
48
+ * The cached session with its user for the session `sessionId` of `userId` — only while the answer stands, the
49
+ * session lives and belongs to that user.
50
+ */
51
+ export function cachedJwtSessionRecord(sessionId: string, userId: string, now = Date.now()): unknown {
52
+ return cachedJwtSession(sessionId, userId, now) ? entries.get(sessionId)?.record : undefined;
53
+ }
54
+
55
+ /**
56
+ * Keeps the answer for the session `sessionId` of `userId` until `until` (epoch milliseconds), with the session and
57
+ * its user when the lookup fetched them. An answer without a record keeps a record already held for a live session.
58
+ */
59
+ export function rememberJwtSession(
60
+ sessionId: string,
61
+ userId: string,
62
+ live: boolean,
63
+ until: number,
64
+ record?: unknown,
65
+ ): void {
66
+ const previous = entries.get(sessionId);
67
+ const kept = record ?? (live && previous?.live && previous.userId === userId ? previous.record : undefined);
68
+ entries.delete(sessionId);
69
+ if (entries.size >= JWT_SESSION_CACHE_MAX) {
70
+ const oldest = entries.keys().next().value;
71
+ if (oldest !== undefined) {
72
+ entries.delete(oldest);
73
+ }
74
+ }
75
+ entries.set(sessionId, { live, record: kept, until, userId });
76
+ }
77
+
78
+ /** Forgets the answer for the session `sessionId` on this process only — for a broadcast received from a replica. */
79
+ export function forgetJwtSession(sessionId: string): void {
80
+ entries.delete(sessionId);
81
+ }
82
+
83
+ /**
84
+ * The session `sessionId` has ended (signed out, revoked, its user deleted): forget it here and tell the other
85
+ * replicas. Never throws — it runs inside Better-Auth's deletion.
86
+ */
87
+ export function jwtSessionEnded(sessionId: string): void {
88
+ entries.delete(sessionId);
89
+ try {
90
+ broadcaster?.(sessionId);
91
+ } catch {
92
+ // The other replicas forget it when their entry expires.
93
+ }
94
+ }
95
+
96
+ /** Registers how an ended session reaches the other replicas (the user mapper's Redis channel); `undefined` removes it. */
97
+ export function setJwtSessionBroadcaster(fn: ((sessionId: string) => void) | undefined): void {
98
+ broadcaster = fn;
99
+ }
100
+
101
+ /** Empties the cache — for tests and a module that is torn down. */
102
+ export function clearJwtSessionCache(): void {
103
+ entries.clear();
104
+ }
@@ -123,6 +123,11 @@ export class CoreBetterAuthPasskeyChallengeModel {
123
123
  @ObjectType({ description: 'Better-Auth features status' })
124
124
  @Restricted(RoleEnum.S_EVERYONE)
125
125
  export class CoreBetterAuthFeaturesModel {
126
+ @Field(() => Boolean, {
127
+ description: 'Whether e-mail and password sign-in is enabled (false: sign-in through a provider only)',
128
+ })
129
+ emailAndPassword: boolean;
130
+
126
131
  @Field(() => Boolean, { description: 'Whether email verification is required on sign-up' })
127
132
  emailVerification: boolean;
128
133
 
@@ -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
 
@@ -0,0 +1,105 @@
1
+ import type { IBetterAuth } from '../../common/interfaces/server-options.interface.js';
2
+
3
+ /**
4
+ * Whether e-mail and password sign-in is on: everything but an explicit `emailAndPassword.enabled: false`, the default
5
+ * Better-Auth receives in `better-auth.config.ts`.
6
+ */
7
+ export function isEmailAndPasswordSignInEnabled(config: IBetterAuth | undefined): boolean {
8
+ return config?.emailAndPassword?.enabled !== false;
9
+ }
10
+
11
+ /**
12
+ * The sign-in routes the project's own Better-Auth plugins add (`betterAuth.plugins`, `betterAuth.options.plugins`):
13
+ * `/sign-in/username`, `/sign-in/phone-number`, `/sign-in/magic-link`, `/sign-in/email-otp`, … — every endpoint path
14
+ * under `/sign-in/` but the social one.
15
+ */
16
+ export function projectSignInRoutes(config: IBetterAuth | undefined): string[] {
17
+ const projectPlugins: unknown = config?.plugins;
18
+ const optionPlugins: unknown = (config?.options as { plugins?: unknown } | undefined)?.plugins;
19
+ const plugins: unknown[] = [
20
+ ...(Array.isArray(projectPlugins) ? projectPlugins : []),
21
+ ...(Array.isArray(optionPlugins) ? optionPlugins : []),
22
+ ];
23
+ const routes: string[] = [];
24
+ for (const plugin of plugins) {
25
+ const endpoints = (plugin as { endpoints?: Record<string, { path?: unknown }> } | null)?.endpoints;
26
+ for (const endpoint of Object.values(endpoints ?? {})) {
27
+ const path = endpoint?.path;
28
+ if (typeof path === 'string' && path.startsWith('/sign-in/') && !path.startsWith('/sign-in/social')) {
29
+ routes.push(path);
30
+ }
31
+ }
32
+ }
33
+ return routes;
34
+ }
35
+
36
+ /**
37
+ * Whether sign-in runs through a single sign-on provider alone (12.11.0): e-mail and password sign-in is off AND no
38
+ * plugin of the project adds a sign-in route of its own. A project with `emailAndPassword.enabled: false` that signs
39
+ * in by username and password (`username()`) or by phone number is NOT one: there the two-factor plugin is what
40
+ * enforces the second factor on `/sign-in/username` and `/sign-in/phone-number`.
41
+ */
42
+ export function isProviderOnlySignIn(config: IBetterAuth | undefined): boolean {
43
+ return !isEmailAndPasswordSignInEnabled(config) && projectSignInRoutes(config).length === 0;
44
+ }
45
+
46
+ /**
47
+ * Whether a sign-in factor (Passkey, two-factor) is on, given its own switch (12.11.0).
48
+ *
49
+ * `false` or `{ enabled: false }` switches it off, as always. While the project signs in with a method of its own (e-mail
50
+ * and password, or a plugin's sign-in route), every other value switches it on (unset included), as before 12.11.0.
51
+ *
52
+ * When sign-in runs through a provider alone ({@link isProviderOnlySignIn}) it is on only when switched on EXPLICITLY:
53
+ * `true` or `{ enabled: true, … }`. Until 12.11.0 Passkey and two-factor stayed on there: whoever registered a passkey
54
+ * after a Microsoft sign-in kept signing in with it after Entra withdrew the assignment, so the provider no longer
55
+ * decided who gets in. An object without `enabled: true` (a `twoFactor: { appName }` kept from a password setup) does
56
+ * not count as that decision.
57
+ */
58
+ export function isSignInFactorEnabled(value: unknown, config: IBetterAuth | undefined): boolean {
59
+ if (value === false) {
60
+ return false;
61
+ }
62
+ const settings = typeof value === 'object' && value !== null ? (value as { enabled?: unknown }) : undefined;
63
+ if (settings?.enabled === false) {
64
+ return false;
65
+ }
66
+ if (!isProviderOnlySignIn(config)) {
67
+ return true;
68
+ }
69
+ return value === true || settings?.enabled === true;
70
+ }
71
+
72
+ /** Whether the Passkey plugin is configured on (URL resolution can still turn it off, see `normalizePasskeyConfig`). */
73
+ export function isPasskeyConfigured(config: IBetterAuth | undefined): boolean {
74
+ return isSignInFactorEnabled(config?.passkey, config);
75
+ }
76
+
77
+ /** Whether the two-factor plugin is configured on. */
78
+ export function isTwoFactorConfigured(config: IBetterAuth | undefined): boolean {
79
+ return isSignInFactorEnabled(config?.twoFactor, config);
80
+ }
81
+
82
+ /**
83
+ * The sign-in factors that are off only because sign-in runs through a provider alone — named once at boot, so a
84
+ * project that relied on them sees why they are gone and how to switch them on again. `configured` marks a factor that
85
+ * carried settings of its own (an object), which deserves a warning rather than a notice.
86
+ */
87
+ export function signInFactorsOffWithoutPassword(
88
+ config: IBetterAuth | undefined,
89
+ ): { configured: boolean; name: 'passkey' | 'twoFactor' }[] {
90
+ if (!isProviderOnlySignIn(config)) {
91
+ return [];
92
+ }
93
+ const off: { configured: boolean; name: 'passkey' | 'twoFactor' }[] = [];
94
+ for (const [name, value] of [
95
+ ['passkey', config?.passkey],
96
+ ['twoFactor', config?.twoFactor],
97
+ ] as const) {
98
+ const settings = typeof value === 'object' && value !== null ? (value as { enabled?: unknown }) : undefined;
99
+ const explicitlyOff = value === false || settings?.enabled === false;
100
+ if (!explicitlyOff && !isSignInFactorEnabled(value, config)) {
101
+ off.push({ configured: !!settings, name });
102
+ }
103
+ }
104
+ return off;
105
+ }
@@ -20,6 +20,7 @@ import { RoleEnum } from '../../common/enums/role.enum.js';
20
20
  import { revalidateWsConnectionsOf } from '../../common/helpers/graphql-ws-connection.helper.js';
21
21
  import { maskEmail } from '../../common/helpers/logging.helper.js';
22
22
  import { CoreRedisService } from '../../common/services/core-redis.service.js';
23
+ import { forgetJwtSession, setJwtSessionBroadcaster } from './core-better-auth-jwt-session.cache.js';
23
24
  import { legacyCredentialAccountIssuer } from './core-better-auth-account-issuer.helper.js';
24
25
  import { getBetterAuthSqlStore } from './core-better-auth-sql.registry.js';
25
26
  import type { BetterAuthSqlStore } from './core-better-auth-sql.store.js';
@@ -203,6 +204,8 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
203
204
  }
204
205
  };
205
206
  this.redisService.getSubscriber().on('message', this.invalidationListener);
207
+ // An ended session reaches the other replicas over the same channel, so their JWT session cache forgets it too
208
+ setJwtSessionBroadcaster((sessionId) => this.publishSessionEnded(sessionId));
206
209
  // Registered with the Redis service, so the subscription is established again after every reconnect — also when
207
210
  // this first attempt fails because Redis is down at boot.
208
211
  await this.redisService.subscribeChannel(channel);
@@ -219,6 +222,7 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
219
222
  if (!this.invalidationListener) {
220
223
  return;
221
224
  }
225
+ setJwtSessionBroadcaster(undefined);
222
226
  try {
223
227
  if (this.redisService) {
224
228
  this.redisService.getSubscriber().off('message', this.invalidationListener);
@@ -424,11 +428,19 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
424
428
  */
425
429
  protected applyInvalidation(message: string): void {
426
430
  let iamId: unknown;
431
+ let sessionId: unknown;
427
432
  try {
428
- iamId = JSON.parse(message)?.iamId;
433
+ const parsed = JSON.parse(message);
434
+ iamId = parsed?.iamId;
435
+ sessionId = parsed?.sessionId;
429
436
  } catch {
430
437
  iamId = undefined;
431
438
  }
439
+ // A session ended on another replica (12.11.0): a JWT issued from it must stop working here too
440
+ if (typeof sessionId === 'string' && sessionId) {
441
+ forgetJwtSession(sessionId);
442
+ return;
443
+ }
432
444
  if (typeof iamId !== 'string' || !iamId) {
433
445
  this.logger.debug(`Ignoring malformed IAM user cache invalidation message: ${message}`);
434
446
  return;
@@ -465,6 +477,30 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
465
477
  }
466
478
  }
467
479
 
480
+ /**
481
+ * Broadcast that a session ended (12.11.0), so every replica's JWT session cache forgets it at once instead of when
482
+ * its entry expires. Fire-and-forget; a no-op without `redis`.
483
+ */
484
+ protected publishSessionEnded(sessionId: string): void {
485
+ const redisService = this.redisService;
486
+ if (!redisService?.enabled) {
487
+ return;
488
+ }
489
+ const warn = (error: Error) =>
490
+ this.logger.warn(
491
+ `Ended session could not be broadcast: ${error.message}. JWTs issued from it keep working on other replicas ` +
492
+ 'until their session cache entry expires (10 s).',
493
+ );
494
+ try {
495
+ void redisService
496
+ .getClient()
497
+ .publish(this.invalidationChannel(redisService), JSON.stringify({ sessionId }))
498
+ .catch(warn);
499
+ } catch (error) {
500
+ warn(error as Error);
501
+ }
502
+ }
503
+
468
504
  private invalidationChannel(redisService: CoreRedisService): string {
469
505
  return redisService.key('iam-user-cache', 'invalidate');
470
506
  }
@@ -341,6 +341,7 @@ export class CoreBetterAuthController {
341
341
  @Roles(RoleEnum.S_EVERYONE)
342
342
  getFeatures(): Record<string, boolean | number | string[]> {
343
343
  return {
344
+ emailAndPassword: this.betterAuthService.isEmailAndPasswordEnabled(),
344
345
  emailVerification: this.emailVerificationService?.isEnabled() ?? false,
345
346
  enabled: this.betterAuthService.isEnabled(),
346
347
  jwt: this.betterAuthService.isJwtEnabled(),
@@ -814,8 +815,10 @@ export class CoreBetterAuthController {
814
815
  }
815
816
 
816
817
  try {
817
- // Get session token from cookies or authorization header
818
- const sessionToken = this.extractSessionToken(req);
818
+ // The session the middleware validated first — for a JWT request the JWT's own session (12.11.0) —, then the
819
+ // session cookie. Until 12.11.0 a JWT client's sign-out read the cookie alone, found none and ended nothing: the
820
+ // answer said success, and the session and every JWT issued from it lived on.
821
+ const sessionToken = this.getSessionTokenFromRequest(req);
819
822
 
820
823
  if (sessionToken) {
821
824
  await this.betterAuthService.revokeSession(sessionToken);
@@ -975,7 +978,7 @@ export class CoreBetterAuthController {
975
978
  *
976
979
  * JWTs in the Authorization header are NOT returned here because they cannot
977
980
  * be used as session tokens for BetterAuth's plugin endpoints (2FA, Passkey, etc.).
978
- * The middleware resolves JWTs to sessions separately via getActiveSessionForUser().
981
+ * The middleware resolves a JWT to its own session separately via getJwtSession().
979
982
  */
980
983
  protected extractSessionToken(req: Request): null | string {
981
984
  // Check Authorization header - only return session tokens, not JWTs
@@ -1168,7 +1171,7 @@ export class CoreBetterAuthController {
1168
1171
 
1169
1172
  // Send the response back
1170
1173
  // Through the token policy: a forwarded route must not hand out what sign-in would not (12.6.1)
1171
- await this.betterAuthService.sendBetterAuthResponse(res, response);
1174
+ await this.betterAuthService.sendBetterAuthResponse(res, response, { requestSessionToken: sessionToken });
1172
1175
  } catch (error) {
1173
1176
  this.logger.error(`Better Auth handler error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1174
1177
 
@@ -96,9 +96,10 @@ export class CoreBetterAuthMiddleware implements NestMiddleware {
96
96
 
97
97
  // Also resolve the real session from DB so that BetterAuth's plugin endpoints
98
98
  // (2FA, Passkey, etc.) can authenticate via session token.
99
- // Without this, JWT-only clients cannot use plugin routes.
99
+ // Without this, JWT-only clients cannot use plugin routes. The JWT's OWN session (its `sid`), since
100
+ // 12.11.0 — before, the user's newest one, so a sign-out with one device's JWT ended another device.
100
101
  try {
101
- const sessionResult = await this.betterAuthService.getActiveSessionForUser(jwtPayload.sub);
102
+ const sessionResult = await this.betterAuthService.getJwtSession(jwtPayload);
102
103
  if (sessionResult?.session && sessionResult?.user) {
103
104
  req.betterAuthSession = { session: sessionResult.session, user: sessionResult.user };
104
105
  }
@@ -169,7 +170,7 @@ export class CoreBetterAuthMiddleware implements NestMiddleware {
169
170
 
170
171
  // Resolve real DB session for plugin endpoints (2FA, Passkey, etc.)
171
172
  try {
172
- const sessionResult = await this.betterAuthService.getActiveSessionForUser(jwtPayload.sub);
173
+ const sessionResult = await this.betterAuthService.getJwtSession(jwtPayload);
173
174
  if (sessionResult?.session && sessionResult?.user) {
174
175
  req.betterAuthSession = { session: sessionResult.session, user: sessionResult.user };
175
176
  }
@@ -432,7 +432,7 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
432
432
  * Middleware order (important!):
433
433
  * 1. CoreBetterAuthMiddleware - Session validation and user mapping for all routes
434
434
  * Must run FIRST so that req.betterAuthSession is available for downstream middleware.
435
- * In JWT mode, this resolves the JWT to a real DB session (via getActiveSessionForUser).
435
+ * In JWT mode, this resolves the JWT to its own DB session (via getJwtSession(), by its `sid`).
436
436
  * 2. CoreBetterAuthPathGuardMiddleware - Refuses a non-canonical path under the base path (400), before
437
437
  * anything below reads it
438
438
  * 3. CoreBetterAuthRateLimitMiddleware - Rate limiting for auth endpoints
@@ -188,6 +188,7 @@ export class CoreBetterAuthResolver {
188
188
  @Roles(RoleEnum.S_EVERYONE)
189
189
  betterAuthFeatures(): CoreBetterAuthFeaturesModel {
190
190
  return {
191
+ emailAndPassword: this.betterAuthService.isEmailAndPasswordEnabled(),
191
192
  emailVerification: this.emailVerificationService?.isEnabled() ?? false,
192
193
  enabled: this.betterAuthService.isEnabled(),
193
194
  jwt: this.betterAuthService.isJwtEnabled(),