@lenne.tech/nest-server 12.10.1 → 12.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/.claude/rules/better-auth.md +19 -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 +5 -0
  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-jwt-session.cache.d.ts +8 -0
  32. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js +47 -0
  33. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js.map +1 -0
  34. package/dist/core/modules/better-auth/core-better-auth-models.d.ts +1 -0
  35. package/dist/core/modules/better-auth/core-better-auth-models.js +7 -0
  36. package/dist/core/modules/better-auth/core-better-auth-models.js.map +1 -1
  37. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.d.ts +11 -0
  38. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js +62 -0
  39. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js.map +1 -0
  40. package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +1 -0
  41. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +28 -1
  42. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  43. package/dist/core/modules/better-auth/core-better-auth.controller.js +2 -1
  44. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  45. package/dist/core/modules/better-auth/core-better-auth.middleware.js +2 -2
  46. package/dist/core/modules/better-auth/core-better-auth.middleware.js.map +1 -1
  47. package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -0
  48. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  49. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +10 -0
  50. package/dist/core/modules/better-auth/core-better-auth.service.js +105 -19
  51. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  52. package/dist/core/modules/health-check/core-health-check-readiness.controller.d.ts +6 -0
  53. package/dist/core/modules/health-check/core-health-check-readiness.controller.js +36 -0
  54. package/dist/core/modules/health-check/core-health-check-readiness.controller.js.map +1 -0
  55. package/dist/core/modules/health-check/core-health-check.helpers.d.ts +10 -0
  56. package/dist/core/modules/health-check/core-health-check.helpers.js +31 -0
  57. package/dist/core/modules/health-check/core-health-check.helpers.js.map +1 -0
  58. package/dist/core/modules/health-check/core-health-check.module.d.ts +9 -0
  59. package/dist/core/modules/health-check/core-health-check.module.js +13 -2
  60. package/dist/core/modules/health-check/core-health-check.module.js.map +1 -1
  61. package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -1
  62. package/dist/core/modules/health-check/core-health-check.service.js +66 -29
  63. package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
  64. package/dist/core/modules/sync/core-sync.service.d.ts +2 -0
  65. package/dist/core/modules/sync/core-sync.service.js +11 -1
  66. package/dist/core/modules/sync/core-sync.service.js.map +1 -1
  67. package/dist/core.module.js +5 -1
  68. package/dist/core.module.js.map +1 -1
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +4 -0
  71. package/dist/index.js.map +1 -1
  72. package/dist/main.js.map +1 -1
  73. package/docs/REQUEST-LIFECYCLE.md +4 -4
  74. package/docs/offline-sync-protocol.md +5 -3
  75. package/migration-guides/12.10.x-to-12.11.x.md +295 -0
  76. package/package.json +17 -17
  77. package/src/core/common/decorators/unified-field.decorator.ts +14 -4
  78. package/src/core/common/helpers/config.helper.ts +55 -8
  79. package/src/core/common/helpers/graceful-shutdown.helper.ts +10 -3
  80. package/src/core/common/helpers/graphql-ws-connection.helper.ts +99 -4
  81. package/src/core/common/helpers/http-stream-auth.helper.ts +197 -0
  82. package/src/core/common/helpers/shutdown-state.helper.ts +28 -0
  83. package/src/core/common/interfaces/cron-job-config-with-utc-offset.interface.ts +1 -1
  84. package/src/core/common/interfaces/cron-job-config.interface.ts +1 -1
  85. package/src/core/common/interfaces/server-options.interface.ts +113 -1
  86. package/src/core/common/services/core-cron-jobs.service.ts +241 -14
  87. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +26 -10
  88. package/src/core/modules/better-auth/README.md +37 -8
  89. package/src/core/modules/better-auth/better-auth.config.ts +83 -12
  90. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +1 -1
  91. package/src/core/modules/better-auth/core-better-auth-jwt-session.cache.ts +104 -0
  92. package/src/core/modules/better-auth/core-better-auth-models.ts +5 -0
  93. package/src/core/modules/better-auth/core-better-auth-sign-in-factors.helper.ts +105 -0
  94. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +37 -1
  95. package/src/core/modules/better-auth/core-better-auth.controller.ts +6 -3
  96. package/src/core/modules/better-auth/core-better-auth.middleware.ts +4 -3
  97. package/src/core/modules/better-auth/core-better-auth.module.ts +1 -1
  98. package/src/core/modules/better-auth/core-better-auth.resolver.ts +1 -0
  99. package/src/core/modules/better-auth/core-better-auth.service.ts +160 -27
  100. package/src/core/modules/health-check/core-health-check-readiness.controller.ts +27 -0
  101. package/src/core/modules/health-check/core-health-check.helpers.ts +65 -0
  102. package/src/core/modules/health-check/core-health-check.module.ts +37 -2
  103. package/src/core/modules/health-check/core-health-check.service.ts +154 -59
  104. package/src/core/modules/sync/README.md +18 -6
  105. package/src/core/modules/sync/core-sync.service.ts +35 -6
  106. package/src/core.module.ts +9 -1
  107. package/src/index.ts +4 -0
  108. package/src/main.ts +2 -1
@@ -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
 
@@ -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
@@ -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(),
@@ -42,6 +42,12 @@ import {
42
42
  unavailableBetterAuthOperations,
43
43
  } from './core-better-auth-openapi.helper.js';
44
44
  import type { IBetterAuthOpenApiDocument, IBetterAuthRuntime } from './core-better-auth-openapi.helper.js';
45
+ import { cachedJwtSession, cachedJwtSessionRecord, rememberJwtSession } from './core-better-auth-jwt-session.cache.js';
46
+ import {
47
+ isEmailAndPasswordSignInEnabled,
48
+ isPasskeyConfigured,
49
+ isTwoFactorConfigured,
50
+ } from './core-better-auth-sign-in-factors.helper.js';
45
51
  import { isJwtShaped } from './core-better-auth-token.helper.js';
46
52
  import { BetterAuthSessionUser } from './core-better-auth-user.mapper.js';
47
53
  import { presentSessionTokens } from './core-better-auth-session-token.helper.js';
@@ -657,31 +663,29 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
657
663
  }
658
664
 
659
665
  /**
660
- * Checks if 2FA is enabled.
661
- * 2FA is enabled by default when BetterAuth is enabled.
662
- * Only disabled when explicitly set to:
663
- * - `false`
664
- * - `{ enabled: false }`
666
+ * Checks if 2FA is enabled: on by default, off with `false` / `{ enabled: false }` — and since 12.11.0 off while
667
+ * sign-in runs through a provider alone, unless switched on with `true` / `{ enabled: true }` (`isSignInFactorEnabled()`).
665
668
  */
666
669
  isTwoFactorEnabled(): boolean {
667
- if (!this.isEnabled()) return false;
668
- if (this.config.twoFactor === false) return false;
669
- if (typeof this.config.twoFactor === 'object' && this.config.twoFactor?.enabled === false) return false;
670
- return true;
670
+ return this.isEnabled() && isTwoFactorConfigured(this.config);
671
671
  }
672
672
 
673
673
  /**
674
- * Checks if Passkey/WebAuthn is enabled.
675
- * Passkey is enabled by default when BetterAuth is enabled.
676
- * Only disabled when explicitly set to:
677
- * - `false`
678
- * - `{ enabled: false }`
674
+ * Checks if Passkey/WebAuthn is enabled: on by default, off with `false` / `{ enabled: false }` — and since 12.11.0
675
+ * off while sign-in runs through a provider alone, unless switched on with `true` / `{ enabled: true }`
676
+ * (`isSignInFactorEnabled()`).
679
677
  */
680
678
  isPasskeyEnabled(): boolean {
681
- if (!this.isEnabled()) return false;
682
- if (this.config.passkey === false) return false;
683
- if (typeof this.config.passkey === 'object' && this.config.passkey?.enabled === false) return false;
684
- return true;
679
+ return this.isEnabled() && isPasskeyConfigured(this.config);
680
+ }
681
+
682
+ /**
683
+ * Checks if e-mail and password sign-in is enabled: on by default, off with `emailAndPassword.enabled: false`
684
+ * (reported by `GET /iam/features` as `emailAndPassword` since 12.11.0, so a frontend that signs in through a
685
+ * provider alone can hide the form).
686
+ */
687
+ isEmailAndPasswordEnabled(): boolean {
688
+ return this.isEnabled() && isEmailAndPasswordSignInEnabled(this.config);
685
689
  }
686
690
 
687
691
  /**
@@ -1534,24 +1538,153 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1534
1538
  const alg = header.alg;
1535
1539
  const kid = header.kid;
1536
1540
 
1537
- // For HS256 (symmetric), verify with the BetterAuth secret
1541
+ let payload: null | { [key: string]: any; email?: string; sub: string } = null;
1538
1542
  if (alg === 'HS256') {
1539
- return this.verifyHs256Token(token);
1540
- }
1541
-
1542
- // For asymmetric algorithms (EdDSA, RS256, ES256), use JWKS — from MongoDB or the SQL source, whichever holds them
1543
- if (kid) {
1544
- return this.verifyJwksToken(token, kid, alg);
1543
+ // For HS256 (symmetric), verify with the BetterAuth secret
1544
+ payload = await this.verifyHs256Token(token);
1545
+ } else if (kid) {
1546
+ // For asymmetric algorithms (EdDSA, RS256, ES256), use JWKS — from MongoDB or the SQL source, whichever holds them
1547
+ payload = await this.verifyJwksToken(token, kid, alg);
1548
+ } else {
1549
+ this.logger.debug(`JWT verification: unsupported algorithm=${alg} or missing kid`);
1550
+ return null;
1545
1551
  }
1546
1552
 
1547
- this.logger.debug(`JWT verification: unsupported algorithm=${alg} or missing kid`);
1548
- return null;
1553
+ // A signature and an expiry are not enough (12.11.0): the session the JWT was issued from must still live
1554
+ return payload && (await this.isJwtSessionLive(payload)) ? payload : null;
1549
1555
  } catch (error) {
1550
1556
  this.logger.debug(`JWT verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
1551
1557
  return null;
1552
1558
  }
1553
1559
  }
1554
1560
 
1561
+ /**
1562
+ * The session a Better-Auth JWT was issued from, with its user (12.11.0) — what the middleware hands Better-Auth's
1563
+ * plugin routes (`req.betterAuthSession`) for a JWT request.
1564
+ *
1565
+ * Before 12.11.0 the middleware took the user's NEWEST active session instead (`getActiveSessionForUser()`), whatever
1566
+ * session the JWT came from: `POST /iam/sign-out` with the JWT of one device signed out the device that signed in
1567
+ * last, and the first device's JWT kept working. Asked through Better-Auth's own adapter by the JWT's `sid`, and
1568
+ * cached with the liveness answer of {@link isJwtSessionLive} for {@link jwtSessionCacheTtlMs}.
1569
+ *
1570
+ * @returns the session and its user, or nulls for a JWT without `sid`, a session that is gone, expired or belongs to
1571
+ * another user, and a failed lookup
1572
+ */
1573
+ async getJwtSession(payload: { [key: string]: any; sub: string } | null | undefined): Promise<SessionResult> {
1574
+ const none: SessionResult = { session: null, user: null };
1575
+ const sessionId: unknown = payload?.sid;
1576
+ const userId = payload?.sub ? String(payload.sub) : '';
1577
+ if (!this.isEnabled() || typeof sessionId !== 'string' || !sessionId || !userId) {
1578
+ return none;
1579
+ }
1580
+ const now = Date.now();
1581
+ if (this.jwtSessionCacheTtlMs > 0) {
1582
+ const cached = cachedJwtSessionRecord(sessionId, userId, now) as SessionResult | undefined;
1583
+ if (cached) {
1584
+ return cached;
1585
+ }
1586
+ }
1587
+ try {
1588
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
1589
+ const session = await context?.adapter?.findOne?.({
1590
+ model: 'session',
1591
+ where: [{ field: 'id', value: sessionId }],
1592
+ });
1593
+ const expiresAt = session?.expiresAt ? new Date(session.expiresAt).getTime() : NaN;
1594
+ if (!session || String(session.userId) !== userId || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
1595
+ return none;
1596
+ }
1597
+ const user = await context.internalAdapter?.findUserById?.(userId);
1598
+ if (!user) {
1599
+ return none;
1600
+ }
1601
+ const result: SessionResult = {
1602
+ session: {
1603
+ expiresAt: new Date(expiresAt),
1604
+ id: String(session.id),
1605
+ token: session.token,
1606
+ userId,
1607
+ },
1608
+ user: { email: user.email, emailVerified: user.emailVerified, id: String(user.id), name: user.name },
1609
+ };
1610
+ if (this.jwtSessionCacheTtlMs > 0) {
1611
+ rememberJwtSession(sessionId, userId, true, Math.min(now + this.jwtSessionCacheTtlMs, expiresAt), result);
1612
+ }
1613
+ return result;
1614
+ } catch (error) {
1615
+ this.logger.debug(`getJwtSession error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1616
+ return none;
1617
+ }
1618
+ }
1619
+
1620
+ /**
1621
+ * How long the answer "this JWT's session lives" is kept before the session is asked again, in milliseconds
1622
+ * (12.11.0). A deleted session is forgotten at once, so this bounds only what no deletion hook reports — a session
1623
+ * removed directly in the database, a broadcast lost while Redis was down. A subclass may set another value; `0`
1624
+ * asks for every request.
1625
+ */
1626
+ protected jwtSessionCacheTtlMs = 10_000;
1627
+
1628
+ /**
1629
+ * Whether the session a Better-Auth JWT was issued from still lives (12.11.0): it exists, belongs to the token's
1630
+ * subject and has not expired.
1631
+ *
1632
+ * Before 12.11.0 the JWT carried no reference to its session and was accepted on its signature and expiry alone:
1633
+ * after `POST /iam/sign-out`, a revoked session or a deleted user it kept reading and writing for the rest of its
1634
+ * lifetime (15 minutes by default), and so did a copy of it. A JWT without `sid` — issued before 12.11.0 — is refused;
1635
+ * a client fetches a new one with its session (`GET /iam/token`), which the frontend libraries do on the 401.
1636
+ *
1637
+ * Asked through Better-Auth's own adapter by the session id, so it reads wherever Better-Auth keeps its sessions;
1638
+ * with sessions held only in `secondaryStorage` through the user's session list. The answer is cached for
1639
+ * {@link jwtSessionCacheTtlMs} in `core-better-auth-jwt-session.cache.ts`, and a deleted session is forgotten at once
1640
+ * there (on every replica with `redis`). A failed lookup refuses the JWT and is not cached.
1641
+ */
1642
+ protected async isJwtSessionLive(payload: { [key: string]: any; sub: string }): Promise<boolean> {
1643
+ const sessionId: unknown = payload.sid;
1644
+ const userId = String(payload.sub);
1645
+ if (typeof sessionId !== 'string' || !sessionId) {
1646
+ this.logger.debug('JWT without a session reference refused (issued before 12.11.0)');
1647
+ return false;
1648
+ }
1649
+ const now = Date.now();
1650
+ const cached = this.jwtSessionCacheTtlMs > 0 ? cachedJwtSession(sessionId, userId, now) : undefined;
1651
+ if (cached !== undefined) {
1652
+ return cached;
1653
+ }
1654
+
1655
+ let session: undefined | { expiresAt?: unknown; id?: unknown; userId?: unknown };
1656
+ try {
1657
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
1658
+ if (!context) {
1659
+ return false;
1660
+ }
1661
+ const options = context.options ?? {};
1662
+ if (options.secondaryStorage && !options.session?.storeSessionInDatabase) {
1663
+ const sessions: unknown = await context.internalAdapter?.listSessions?.(userId, { onlyActiveSessions: true });
1664
+ session = (Array.isArray(sessions) ? sessions : []).find(
1665
+ (candidate: { id?: unknown }) => String(candidate?.id) === sessionId,
1666
+ );
1667
+ } else {
1668
+ session =
1669
+ (await context.adapter?.findOne?.({ model: 'session', where: [{ field: 'id', value: sessionId }] })) ??
1670
+ undefined;
1671
+ }
1672
+ } catch (error) {
1673
+ this.logger.warn(
1674
+ `JWT refused: its session could not be looked up (${error instanceof Error ? error.message : 'Unknown error'})`,
1675
+ );
1676
+ return false;
1677
+ }
1678
+
1679
+ const expiresAt = session?.expiresAt ? new Date(session.expiresAt as Date | number | string).getTime() : NaN;
1680
+ const live = !!session && String(session.userId) === userId && Number.isFinite(expiresAt) && expiresAt > Date.now();
1681
+ if (this.jwtSessionCacheTtlMs > 0) {
1682
+ const until = Math.min(now + this.jwtSessionCacheTtlMs, live ? expiresAt : Number.POSITIVE_INFINITY);
1683
+ rememberJwtSession(sessionId, userId, live, until);
1684
+ }
1685
+ return live;
1686
+ }
1687
+
1555
1688
  /**
1556
1689
  * Verifies an HS256 JWT token using the BetterAuth secret
1557
1690
  */
@@ -0,0 +1,27 @@
1
+ import { Controller, Get } from '@nestjs/common';
2
+
3
+ import { Roles } from '../../common/decorators/roles.decorator.js';
4
+ import { RoleEnum } from '../../common/enums/role.enum.js';
5
+ import { CoreHealthCheckService } from './core-health-check.service.js';
6
+
7
+ /**
8
+ * `GET /health-check/ready` (12.11.0): the readiness check beside the liveness check `GET /health-check`.
9
+ *
10
+ * Registered by `CoreHealthCheckModule.forRoot()` only with `healthCheck.readiness`, so without it the route does not
11
+ * exist (404). Public like the liveness check: a load balancer or a Kubernetes readiness probe sends no credential.
12
+ * 200 while every check is up, 503 when one is down or the application shuts down. A project replaces it with a
13
+ * subclass through `CoreModule.forRoot(env, { healthCheck: { readinessController } })` — a subclass that re-declares
14
+ * `readinessCheck()` re-declares its `@Get()` and `@Roles()` too.
15
+ */
16
+ @Controller()
17
+ @Roles(RoleEnum.ADMIN)
18
+ export class CoreHealthCheckReadinessController {
19
+ constructor(protected readonly healthCheckService: CoreHealthCheckService) {}
20
+
21
+ /** The readiness check: the checks `healthCheck.readiness.checks` lists and the project's readiness indicators */
22
+ @Get('health-check/ready')
23
+ @Roles(RoleEnum.S_EVERYONE)
24
+ async readinessCheck() {
25
+ return this.healthCheckService.readinessCheck();
26
+ }
27
+ }