@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
@@ -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
  /**
@@ -824,13 +828,21 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
824
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.
825
829
  * See `presentSessionTokens()` (`core-better-auth-session-token.helper.ts`) for the rules.
826
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
+ *
827
835
  * Override to present tokens differently; keep the cookie-mode rule, it is what keeps the session out of scripts.
828
836
  */
829
- async presentSessionTokens(response: globalThis.Response): Promise<globalThis.Response> {
837
+ async presentSessionTokens(
838
+ response: globalThis.Response,
839
+ options?: { requestSessionToken?: null | string },
840
+ ): Promise<globalThis.Response> {
830
841
  const cookiesConfig = ConfigService.configFastButReadOnly?.cookies as boolean | ICookiesConfig | undefined;
831
842
  return presentSessionTokens(response, {
832
843
  cookieName: await this.sessionCookieNameOfInstance(),
833
844
  isSessionToken: async (token) => !!(await this.getSessionByToken(token))?.session,
845
+ requestSessionToken: options?.requestSessionToken,
834
846
  resolveJwt: (sessionToken) => this.resolveJwtToken(sessionToken),
835
847
  tokenInBody: !isCookiesEnabled(cookiesConfig) || isExposeTokenInBodyEnabled(cookiesConfig),
836
848
  });
@@ -857,10 +869,15 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
857
869
  /**
858
870
  * Sends a response of Better-Auth's handler to the client, through {@link presentSessionTokens}. Every place that
859
871
  * forwards to the handler (the API middleware, the controller's catch-all) sends through here, so a forwarded route
860
- * 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).
861
874
  */
862
- async sendBetterAuthResponse(res: ExpressResponse, response: globalThis.Response): Promise<void> {
863
- 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));
864
881
  }
865
882
 
866
883
  /**
@@ -1534,24 +1551,153 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1534
1551
  const alg = header.alg;
1535
1552
  const kid = header.kid;
1536
1553
 
1537
- // For HS256 (symmetric), verify with the BetterAuth secret
1554
+ let payload: null | { [key: string]: any; email?: string; sub: string } = null;
1538
1555
  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);
1556
+ // For HS256 (symmetric), verify with the BetterAuth secret
1557
+ payload = await this.verifyHs256Token(token);
1558
+ } else if (kid) {
1559
+ // For asymmetric algorithms (EdDSA, RS256, ES256), use JWKS — from MongoDB or the SQL source, whichever holds them
1560
+ payload = await this.verifyJwksToken(token, kid, alg);
1561
+ } else {
1562
+ this.logger.debug(`JWT verification: unsupported algorithm=${alg} or missing kid`);
1563
+ return null;
1545
1564
  }
1546
1565
 
1547
- this.logger.debug(`JWT verification: unsupported algorithm=${alg} or missing kid`);
1548
- return null;
1566
+ // A signature and an expiry are not enough (12.11.0): the session the JWT was issued from must still live
1567
+ return payload && (await this.isJwtSessionLive(payload)) ? payload : null;
1549
1568
  } catch (error) {
1550
1569
  this.logger.debug(`JWT verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
1551
1570
  return null;
1552
1571
  }
1553
1572
  }
1554
1573
 
1574
+ /**
1575
+ * The session a Better-Auth JWT was issued from, with its user (12.11.0) — what the middleware hands Better-Auth's
1576
+ * plugin routes (`req.betterAuthSession`) for a JWT request.
1577
+ *
1578
+ * Before 12.11.0 the middleware took the user's NEWEST active session instead (`getActiveSessionForUser()`), whatever
1579
+ * session the JWT came from: `POST /iam/sign-out` with the JWT of one device signed out the device that signed in
1580
+ * last, and the first device's JWT kept working. Asked through Better-Auth's own adapter by the JWT's `sid`, and
1581
+ * cached with the liveness answer of {@link isJwtSessionLive} for {@link jwtSessionCacheTtlMs}.
1582
+ *
1583
+ * @returns the session and its user, or nulls for a JWT without `sid`, a session that is gone, expired or belongs to
1584
+ * another user, and a failed lookup
1585
+ */
1586
+ async getJwtSession(payload: { [key: string]: any; sub: string } | null | undefined): Promise<SessionResult> {
1587
+ const none: SessionResult = { session: null, user: null };
1588
+ const sessionId: unknown = payload?.sid;
1589
+ const userId = payload?.sub ? String(payload.sub) : '';
1590
+ if (!this.isEnabled() || typeof sessionId !== 'string' || !sessionId || !userId) {
1591
+ return none;
1592
+ }
1593
+ const now = Date.now();
1594
+ if (this.jwtSessionCacheTtlMs > 0) {
1595
+ const cached = cachedJwtSessionRecord(sessionId, userId, now) as SessionResult | undefined;
1596
+ if (cached) {
1597
+ return cached;
1598
+ }
1599
+ }
1600
+ try {
1601
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
1602
+ const session = await context?.adapter?.findOne?.({
1603
+ model: 'session',
1604
+ where: [{ field: 'id', value: sessionId }],
1605
+ });
1606
+ const expiresAt = session?.expiresAt ? new Date(session.expiresAt).getTime() : NaN;
1607
+ if (!session || String(session.userId) !== userId || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
1608
+ return none;
1609
+ }
1610
+ const user = await context.internalAdapter?.findUserById?.(userId);
1611
+ if (!user) {
1612
+ return none;
1613
+ }
1614
+ const result: SessionResult = {
1615
+ session: {
1616
+ expiresAt: new Date(expiresAt),
1617
+ id: String(session.id),
1618
+ token: session.token,
1619
+ userId,
1620
+ },
1621
+ user: { email: user.email, emailVerified: user.emailVerified, id: String(user.id), name: user.name },
1622
+ };
1623
+ if (this.jwtSessionCacheTtlMs > 0) {
1624
+ rememberJwtSession(sessionId, userId, true, Math.min(now + this.jwtSessionCacheTtlMs, expiresAt), result);
1625
+ }
1626
+ return result;
1627
+ } catch (error) {
1628
+ this.logger.debug(`getJwtSession error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1629
+ return none;
1630
+ }
1631
+ }
1632
+
1633
+ /**
1634
+ * How long the answer "this JWT's session lives" is kept before the session is asked again, in milliseconds
1635
+ * (12.11.0). A deleted session is forgotten at once, so this bounds only what no deletion hook reports — a session
1636
+ * removed directly in the database, a broadcast lost while Redis was down. A subclass may set another value; `0`
1637
+ * asks for every request.
1638
+ */
1639
+ protected jwtSessionCacheTtlMs = 10_000;
1640
+
1641
+ /**
1642
+ * Whether the session a Better-Auth JWT was issued from still lives (12.11.0): it exists, belongs to the token's
1643
+ * subject and has not expired.
1644
+ *
1645
+ * Before 12.11.0 the JWT carried no reference to its session and was accepted on its signature and expiry alone:
1646
+ * after `POST /iam/sign-out`, a revoked session or a deleted user it kept reading and writing for the rest of its
1647
+ * lifetime (15 minutes by default), and so did a copy of it. A JWT without `sid` — issued before 12.11.0 — is refused;
1648
+ * a client fetches a new one with its session (`GET /iam/token`), which the frontend libraries do on the 401.
1649
+ *
1650
+ * Asked through Better-Auth's own adapter by the session id, so it reads wherever Better-Auth keeps its sessions;
1651
+ * with sessions held only in `secondaryStorage` through the user's session list. The answer is cached for
1652
+ * {@link jwtSessionCacheTtlMs} in `core-better-auth-jwt-session.cache.ts`, and a deleted session is forgotten at once
1653
+ * there (on every replica with `redis`). A failed lookup refuses the JWT and is not cached.
1654
+ */
1655
+ protected async isJwtSessionLive(payload: { [key: string]: any; sub: string }): Promise<boolean> {
1656
+ const sessionId: unknown = payload.sid;
1657
+ const userId = String(payload.sub);
1658
+ if (typeof sessionId !== 'string' || !sessionId) {
1659
+ this.logger.debug('JWT without a session reference refused (issued before 12.11.0)');
1660
+ return false;
1661
+ }
1662
+ const now = Date.now();
1663
+ const cached = this.jwtSessionCacheTtlMs > 0 ? cachedJwtSession(sessionId, userId, now) : undefined;
1664
+ if (cached !== undefined) {
1665
+ return cached;
1666
+ }
1667
+
1668
+ let session: undefined | { expiresAt?: unknown; id?: unknown; userId?: unknown };
1669
+ try {
1670
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
1671
+ if (!context) {
1672
+ return false;
1673
+ }
1674
+ const options = context.options ?? {};
1675
+ if (options.secondaryStorage && !options.session?.storeSessionInDatabase) {
1676
+ const sessions: unknown = await context.internalAdapter?.listSessions?.(userId, { onlyActiveSessions: true });
1677
+ session = (Array.isArray(sessions) ? sessions : []).find(
1678
+ (candidate: { id?: unknown }) => String(candidate?.id) === sessionId,
1679
+ );
1680
+ } else {
1681
+ session =
1682
+ (await context.adapter?.findOne?.({ model: 'session', where: [{ field: 'id', value: sessionId }] })) ??
1683
+ undefined;
1684
+ }
1685
+ } catch (error) {
1686
+ this.logger.warn(
1687
+ `JWT refused: its session could not be looked up (${error instanceof Error ? error.message : 'Unknown error'})`,
1688
+ );
1689
+ return false;
1690
+ }
1691
+
1692
+ const expiresAt = session?.expiresAt ? new Date(session.expiresAt as Date | number | string).getTime() : NaN;
1693
+ const live = !!session && String(session.userId) === userId && Number.isFinite(expiresAt) && expiresAt > Date.now();
1694
+ if (this.jwtSessionCacheTtlMs > 0) {
1695
+ const until = Math.min(now + this.jwtSessionCacheTtlMs, live ? expiresAt : Number.POSITIVE_INFINITY);
1696
+ rememberJwtSession(sessionId, userId, live, until);
1697
+ }
1698
+ return live;
1699
+ }
1700
+
1555
1701
  /**
1556
1702
  * Verifies an HS256 JWT token using the BetterAuth secret
1557
1703
  */
@@ -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
+ }
@@ -0,0 +1,65 @@
1
+ import { Logger } from '@nestjs/common';
2
+
3
+ import type { IServerOptions } from '../../common/interfaces/server-options.interface.js';
4
+
5
+ /** The checks `healthCheck.configs` configures, in the order they report */
6
+ export const CORE_HEALTH_CHECK_NAMES = ['database', 'memoryHeap', 'memoryRss', 'storage', 'build'] as const;
7
+
8
+ /** A check `healthCheck.configs` configures */
9
+ export type CoreHealthCheckName = (typeof CORE_HEALTH_CHECK_NAMES)[number];
10
+
11
+ /** Which endpoint a health check answers for: `GET /health-check` (liveness) or `GET /health-check/ready` (readiness) */
12
+ export type CoreHealthCheckKind = 'liveness' | 'readiness';
13
+
14
+ /** The checks the readiness endpoint runs without `healthCheck.readiness.checks` */
15
+ export const DEFAULT_READINESS_CHECKS: readonly CoreHealthCheckName[] = ['database', 'build'];
16
+
17
+ /** The readiness endpoint as the configuration describes it */
18
+ export interface IResolvedHealthCheckReadiness {
19
+ /** The configured checks the readiness endpoint runs, in report order */
20
+ checks: CoreHealthCheckName[];
21
+ /** Whether `GET /health-check/ready` is registered */
22
+ enabled: boolean;
23
+ }
24
+
25
+ const logger = new Logger('CoreHealthCheck');
26
+ const warnedUnknownChecks = new Set<string>();
27
+
28
+ /**
29
+ * Resolve `healthCheck.readiness` (12.11.0): boolean shorthand and "presence implies enabled".
30
+ *
31
+ * - absent (or `false`, `{ enabled: false }`): no readiness endpoint — the health check is what it was
32
+ * - `true` / `{}`: `GET /health-check/ready` with the default checks (`database`, `build`)
33
+ * - `{ checks: [...] }`: the listed checks of `healthCheck.configs` — a list (or a comma-separated string, which is
34
+ * what an `NSC__HEALTH_CHECK__READINESS__CHECKS` variable gives) of `database`, `memoryHeap`, `memoryRss`, `storage`,
35
+ * `build`. Unknown names are ignored with one warning each; `[]` runs only the project's own readiness indicators.
36
+ *
37
+ * A listed check runs in the readiness check whatever `configs.<check>.enabled` says: that flag decides for
38
+ * `GET /health-check`. Key, thresholds and options come from `configs.<check>`.
39
+ */
40
+ export function resolveHealthCheckReadiness(healthCheck: IServerOptions['healthCheck']): IResolvedHealthCheckReadiness {
41
+ const readiness = healthCheck?.readiness;
42
+ const enabled = readiness === true || (!!readiness && typeof readiness === 'object' && readiness.enabled !== false);
43
+ if (!enabled || typeof readiness !== 'object' || readiness.checks === undefined || readiness.checks === null) {
44
+ return { checks: enabled ? [...DEFAULT_READINESS_CHECKS] : [], enabled };
45
+ }
46
+ const listed = typeof readiness.checks === 'string' ? readiness.checks.split(',') : readiness.checks;
47
+ if (!Array.isArray(listed)) {
48
+ warnOnce(`healthCheck.readiness.checks is neither a list nor a string — the default checks run`);
49
+ return { checks: [...DEFAULT_READINESS_CHECKS], enabled };
50
+ }
51
+ const names = listed.map((name) => (typeof name === 'string' ? name.trim() : name)).filter((name) => name !== '');
52
+ for (const name of names) {
53
+ if (!(CORE_HEALTH_CHECK_NAMES as readonly unknown[]).includes(name)) {
54
+ warnOnce(`healthCheck.readiness.checks names an unknown check "${String(name)}" — it is ignored`);
55
+ }
56
+ }
57
+ return { checks: CORE_HEALTH_CHECK_NAMES.filter((name) => names.includes(name)), enabled };
58
+ }
59
+
60
+ function warnOnce(message: string): void {
61
+ if (!warnedUnknownChecks.has(message)) {
62
+ warnedUnknownChecks.add(message);
63
+ logger.warn(message);
64
+ }
65
+ }
@@ -1,16 +1,35 @@
1
- import { Module } from '@nestjs/common';
1
+ import { type DynamicModule, Module, type Type } from '@nestjs/common';
2
2
  import { ModuleRef } from '@nestjs/core';
3
3
  import { HealthIndicatorService, MongooseHealthIndicator, TerminusModule } from '@nestjs/terminus';
4
4
 
5
+ import type { IServerOptions } from '../../common/interfaces/server-options.interface.js';
5
6
  import { getConnectionToken } from '../../common/persistence/mongo/mongoose-compat.js';
6
7
 
8
+ import { CoreHealthCheckReadinessController } from './core-health-check-readiness.controller.js';
7
9
  import { CoreHealthCheckController } from './core-health-check.controller.js';
10
+ import { resolveHealthCheckReadiness } from './core-health-check.helpers.js';
8
11
  import { CoreHealthCheckResolver } from './core-health-check.resolver.js';
9
12
  import { CoreHealthCheckService } from './core-health-check.service.js';
10
13
 
14
+ /** Options of {@link CoreHealthCheckModule.forRoot} — what `CoreModule.forRoot()` passes on */
15
+ export interface ICoreHealthCheckModuleOptions {
16
+ /** `healthCheck.readiness`: registers `GET /health-check/ready` when set (boolean shorthand) */
17
+ readiness?: NonNullable<IServerOptions['healthCheck']>['readiness'];
18
+
19
+ /** Replaces `CoreHealthCheckReadinessController`; must extend it */
20
+ readinessController?: Type<any>;
21
+
22
+ /** Replaces `CoreHealthCheckService`; must extend it — the way to add checks (`additionalHealthIndicators()`) */
23
+ service?: Type<CoreHealthCheckService>;
24
+ }
25
+
11
26
  /**
12
27
  * This is a module that imports the TerminusModule and includes a HealthController.
13
28
  * Inspired by https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2
29
+ *
30
+ * Imported as it is, the module registers the liveness check (`GET /health-check`, the `healthCheck` query) exactly as
31
+ * before 12.11.0. `forRoot()` adds what the configuration and the overrides ask for: the readiness endpoint and a
32
+ * project's subclass of `CoreHealthCheckService`.
14
33
  */
15
34
  @Module({
16
35
  controllers: [CoreHealthCheckController],
@@ -28,4 +47,20 @@ import { CoreHealthCheckService } from './core-health-check.service.js';
28
47
  },
29
48
  ],
30
49
  })
31
- export class CoreHealthCheckModule {}
50
+ export class CoreHealthCheckModule {
51
+ /**
52
+ * The module with the readiness endpoint and the service override (12.11.0). A dynamic module EXTENDS the static
53
+ * metadata above, so only what is not there is added: the readiness controller (only with `readiness`), and a project
54
+ * service registered under its own class and — replacing the core one — under `CoreHealthCheckService`, which the
55
+ * controllers and the resolver inject.
56
+ */
57
+ static forRoot(options: ICoreHealthCheckModuleOptions = {}): DynamicModule {
58
+ const readiness = resolveHealthCheckReadiness({ readiness: options.readiness });
59
+ const controllers = readiness.enabled ? [options.readinessController || CoreHealthCheckReadinessController] : [];
60
+ const providers =
61
+ options.service && options.service !== CoreHealthCheckService
62
+ ? [options.service, { provide: CoreHealthCheckService, useExisting: options.service }]
63
+ : [];
64
+ return { controllers, module: CoreHealthCheckModule, providers };
65
+ }
66
+ }