@lenne.tech/nest-server 12.13.0 → 12.14.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 (29) hide show
  1. package/.claude/rules/configurable-features.md +1 -1
  2. package/.claude/rules/package-management.md +1 -1
  3. package/.claude/rules/testing.md +3 -3
  4. package/FRAMEWORK-API.md +1 -1
  5. package/dist/core/common/helpers/meta.helper.d.ts +5 -0
  6. package/dist/core/common/helpers/meta.helper.js +16 -1
  7. package/dist/core/common/helpers/meta.helper.js.map +1 -1
  8. package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.d.ts +21 -0
  9. package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.js +106 -0
  10. package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.js.map +1 -0
  11. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +4 -1
  12. package/dist/core/modules/better-auth/core-better-auth.service.js +25 -7
  13. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  14. package/dist/core/modules/better-auth/index.d.ts +1 -0
  15. package/dist/core/modules/better-auth/index.js +1 -0
  16. package/dist/core/modules/better-auth/index.js.map +1 -1
  17. package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -0
  18. package/dist/core/modules/health-check/core-health-check.service.js +28 -4
  19. package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
  20. package/migration-guides/12.13.x-to-12.14.x.md +132 -0
  21. package/migration-guides/12.14.0-to-12.14.1.md +63 -0
  22. package/package.json +7 -7
  23. package/src/core/common/helpers/meta.helper.ts +62 -3
  24. package/src/core/common/interfaces/server-options.interface.ts +6 -1
  25. package/src/core/modules/better-auth/README.md +4 -1
  26. package/src/core/modules/better-auth/core-better-auth-jwt-rejection.helper.ts +164 -0
  27. package/src/core/modules/better-auth/core-better-auth.service.ts +50 -6
  28. package/src/core/modules/better-auth/index.ts +1 -0
  29. package/src/core/modules/health-check/core-health-check.service.ts +69 -12
@@ -11,7 +11,17 @@
11
11
  * deployed together bake the SAME commit, but each reads its own at runtime — so
12
12
  * comparing them detects a drifted / stale container after a partial rollout.
13
13
  *
14
+ * For people there is a second value: the build number (default env
15
+ * `APP_VERSION_BUILD`, fed from the CI pipeline counter, which the deploy pipeline
16
+ * passes as a Docker build arg). It always increases and travels with the image
17
+ * through a promotion. With it, the version shown to people becomes
18
+ * `<Major>.<Minor>.<Build>`: Major.Minor from package.json / config (raised by
19
+ * hand), the build number in the patch position. Without it the version stays
20
+ * as configured. The commit remains the identity machines compare.
21
+ *
14
22
  * @see getCommit
23
+ * @see getBuild
24
+ * @see composeVersion
15
25
  * @see getBuildInfo
16
26
  */
17
27
 
@@ -21,6 +31,9 @@ import { join } from 'path';
21
31
  /** Default environment variable the build commit SHA is baked into. */
22
32
  export const DEFAULT_COMMIT_ENV = 'APP_VERSION_COMMIT';
23
33
 
34
+ /** Default environment variable the build number (CI pipeline counter) is baked into. */
35
+ export const DEFAULT_BUILD_ENV = 'APP_VERSION_BUILD';
36
+
24
37
  /** Defined value returned when no commit could be resolved. */
25
38
  export const UNKNOWN_COMMIT = 'unknown';
26
39
 
@@ -31,13 +44,19 @@ let cachedVersion: null | string | undefined;
31
44
  * Build identity of the running process.
32
45
  */
33
46
  export interface BuildInfo {
47
+ /** Build number (CI pipeline counter) the image was built in, if known. */
48
+ build?: string;
49
+
34
50
  /** Git commit SHA the build was produced from, or `'unknown'`. */
35
51
  commit: string;
36
52
 
37
53
  /** Environment the process runs in (e.g. `'production'`), if provided. */
38
54
  env?: string;
39
55
 
40
- /** Semantic version of the build, or `'unknown'`. */
56
+ /**
57
+ * Version of the build for people: `<Major>.<Minor>.<Build>` when a build number is known,
58
+ * otherwise the configured / package.json version, or `'unknown'`.
59
+ */
41
60
  version?: string;
42
61
  }
43
62
 
@@ -55,6 +74,39 @@ export function getCommit(envName: string = DEFAULT_COMMIT_ENV): string {
55
74
  return process.env[envName] || UNKNOWN_COMMIT;
56
75
  }
57
76
 
77
+ /**
78
+ * Resolve the build number (CI pipeline counter) the running build was produced in.
79
+ *
80
+ * Reads `process.env[envName]` (default `APP_VERSION_BUILD`). Returns `undefined` when the
81
+ * variable is unset or not a plain number — local builds and builds outside the lt pipelines
82
+ * have none, and the version then stays as configured.
83
+ *
84
+ * @param envName Name of the environment variable holding the build number.
85
+ */
86
+ export function getBuild(envName: string = DEFAULT_BUILD_ENV): string | undefined {
87
+ const build = (process.env[envName] || '').trim();
88
+ return /^\d+$/.test(build) ? build : undefined;
89
+ }
90
+
91
+ /**
92
+ * Compose the version shown to people: `<Major>.<Minor>.<Build>`.
93
+ *
94
+ * Major.Minor come from `version` (package.json or config, raised by hand); the build number
95
+ * takes the patch position. Returns `version` unchanged when the build number is missing or not
96
+ * numeric, and when `version` itself is not a `<major>.<minor>…` version (e.g. `'unknown'`).
97
+ *
98
+ * @param version Configured / package.json version, e.g. `'1.32.0'`.
99
+ * @param build Build number, e.g. `'1875'`.
100
+ */
101
+ export function composeVersion(version: string, build?: null | string): string {
102
+ const buildNumber = (build ?? '').trim();
103
+ const match = /^(\d+)\.(\d+)/.exec(version);
104
+ if (!match || !/^\d+$/.test(buildNumber)) {
105
+ return version;
106
+ }
107
+ return `${match[1]}.${match[2]}.${buildNumber}`;
108
+ }
109
+
58
110
  /**
59
111
  * Assemble the build identity of the running process.
60
112
  *
@@ -62,15 +114,22 @@ export function getCommit(envName: string = DEFAULT_COMMIT_ENV): string {
62
114
  * `version` and `env`. Designed to be surfaced via a public meta / info endpoint
63
115
  * and the health check so deployments can be compared at a glance.
64
116
  *
117
+ * The `version` is composed with the build number (see {@link composeVersion}) when one is set.
118
+ *
119
+ * @param options.buildEnvName Override the env var the build number is read from.
65
120
  * @param options.commitEnvName Override the env var the commit SHA is read from.
66
121
  * @param options.env Environment label to include (e.g. from the config).
67
122
  * @param options.version Semantic version to include (e.g. from package.json).
68
123
  */
69
- export function getBuildInfo(options: { commitEnvName?: string; env?: string; version?: string } = {}): BuildInfo {
124
+ export function getBuildInfo(
125
+ options: { buildEnvName?: string; commitEnvName?: string; env?: string; version?: string } = {},
126
+ ): BuildInfo {
127
+ const build = getBuild(options.buildEnvName);
70
128
  return {
129
+ ...(build ? { build } : {}),
71
130
  commit: getCommit(options.commitEnvName),
72
131
  env: options.env,
73
- version: options.version || getVersion(),
132
+ version: composeVersion(options.version || getVersion(), build),
74
133
  };
75
134
  }
76
135
 
@@ -3046,6 +3046,8 @@ export interface IServerOptions {
3046
3046
  * Surfaced via the build-identity health indicator alongside the commit SHA.
3047
3047
  * Unlike the commit (which uniquely pins the exact build), the version is a
3048
3048
  * rarely-bumped semver and may legitimately differ between API and frontend.
3049
+ * When the image carries a build number (`APP_VERSION_BUILD`, since 12.14.0), its
3050
+ * Major.Minor are combined with it to `<Major>.<Minor>.<Build>`.
3049
3051
  *
3050
3052
  * @since 11.27.0
3051
3053
  */
@@ -3179,6 +3181,8 @@ export interface IServerOptions {
3179
3181
  * drifted / stale container can be detected after a partial rollout. The
3180
3182
  * commit is read from `process.env.APP_VERSION_COMMIT` (baked at build
3181
3183
  * time from the CI commit SHA); `version` comes from {@link IServerOptions.version}.
3184
+ * With `process.env.APP_VERSION_BUILD` (the CI pipeline counter, since 12.14.0) the
3185
+ * indicator also reports `build`, and `version` becomes `<Major>.<Minor>.<Build>`.
3182
3186
  *
3183
3187
  * @since 11.27.0
3184
3188
  */
@@ -3204,7 +3208,8 @@ export interface IServerOptions {
3204
3208
  key?: string;
3205
3209
 
3206
3210
  /**
3207
- * Database health check options
3211
+ * Database health check options. `timeout` (ms) applies to the MongoDB ping and to every SQL source;
3212
+ * default: 2000 (`DEFAULT_DATABASE_PING_TIMEOUT_MS`)
3208
3213
  */
3209
3214
  options?: MongoosePingCheckSettings;
3210
3215
  };
@@ -221,8 +221,11 @@ Read the security section below for production deployments.
221
221
  https://your-domain.com/iam/callback/google
222
222
  ```
223
223
  - **CORS Origin Validation**: If no `trustedOrigins` are set, `baseUrl` is used as the trusted origin
224
+ - **JWT issuer and audience**: Bearer JWTs are accepted only with this origin as `iss` and `aud`. A token issued for
225
+ another base URL (an old domain, another stage) is rejected; since 12.14.1 the rejection logs a warning naming the
226
+ expected and the received issuer, at most once per hour and issuer (`core-better-auth-jwt-rejection.helper.ts`)
224
227
 
225
- **Impact of incorrect value:** Email links point to wrong server, OAuth callbacks fail.
228
+ **Impact of incorrect value:** Email links point to wrong server, OAuth callbacks fail, Bearer JWTs are rejected.
226
229
 
227
230
  ### Base Path (`basePath`)
228
231
 
@@ -0,0 +1,164 @@
1
+ import type { Request } from 'express';
2
+ import { decodeJwt } from 'jose';
3
+
4
+ /**
5
+ * Facts about the request that carried a JWT, used to find the source of a rejected token. Never the token itself and
6
+ * never the user it names.
7
+ */
8
+ export interface JwtVerificationContext {
9
+ method?: string;
10
+ origin?: string;
11
+ path?: string;
12
+ userAgent?: string;
13
+ }
14
+
15
+ /** Why a JWT was rejected, for the cases worth a warning (an expired token is routine and stays at debug level). */
16
+ export type JwtRejectionKind = 'invalid signature' | 'issuer or audience mismatch' | 'unknown signing key';
17
+
18
+ const USER_AGENT_MAX_LENGTH = 120;
19
+ const CLAIM_MAX_LENGTH = 200;
20
+ const KID_MAX_LENGTH = 40;
21
+
22
+ /**
23
+ * Whether a character can steer a terminal or a log viewer: C0 controls and DEL, the C1 controls (U+0080–U+009F, an
24
+ * 8-bit CSI/OSC moves the cursor, erases lines or injects a hyperlink in xterm-like terminals), the line and paragraph
25
+ * separators and the bidi controls (they reorder what an operator reads). Node hands header bytes 0x80–0x9F through as
26
+ * these characters, and a JSON `\u009b` in a token header decodes to one.
27
+ */
28
+ function isUnsafeLogCharacter(code: number): boolean {
29
+ return (
30
+ code < 0x20 ||
31
+ (code >= 0x7f && code <= 0x9f) ||
32
+ code === 0x2028 ||
33
+ code === 0x2029 ||
34
+ (code >= 0x202a && code <= 0x202e) ||
35
+ (code >= 0x2066 && code <= 0x2069)
36
+ );
37
+ }
38
+
39
+ /** Token claims and request headers are client-controlled: no control characters (log injection), bounded length. */
40
+ function clean(value: unknown, maxLength: number): string {
41
+ let result = '';
42
+ for (const char of String(value)) {
43
+ if (result.length >= maxLength) {
44
+ break;
45
+ }
46
+ const code = char.codePointAt(0) ?? 0;
47
+ result += isUnsafeLogCharacter(code) ? '?' : char;
48
+ }
49
+ return result.slice(0, maxLength);
50
+ }
51
+
52
+ function header(req: Request, name: string): string | undefined {
53
+ const value = req.headers?.[name];
54
+ return Array.isArray(value) ? value[0] : value;
55
+ }
56
+
57
+ /** The context of a request: method, path without query string, origin and a shortened user agent. */
58
+ export function jwtVerificationContextFromRequest(req: Request | undefined): JwtVerificationContext | undefined {
59
+ if (!req) {
60
+ return undefined;
61
+ }
62
+ const url = req.originalUrl || req.url || '';
63
+ return {
64
+ method: req.method,
65
+ origin: header(req, 'origin'),
66
+ path: url.split('?')[0] || undefined,
67
+ userAgent: header(req, 'user-agent')?.slice(0, USER_AGENT_MAX_LENGTH),
68
+ };
69
+ }
70
+
71
+ function isoFromEpoch(seconds: unknown): string {
72
+ return typeof seconds === 'number' ? new Date(seconds * 1000).toISOString() : '-';
73
+ }
74
+
75
+ /**
76
+ * The warning line for a rejected JWT and the key it is throttled under (12.14.1).
77
+ *
78
+ * For an issuer or audience mismatch it names the expected and the received issuer and audience, when the token was
79
+ * issued and when it expires, because those tell where a foreign token comes from. For a signature or key failure it
80
+ * names the key id. It never contains the token, the subject or any other claim.
81
+ *
82
+ * The key never holds a value the caller can choose freely, or rotating it would write one warning per request: the
83
+ * issuer is reported only for a token one of our keys signed, the key id of a signature failure is one of our stored
84
+ * keys, and an unknown key id is the caller's invention, so that kind is throttled as a whole.
85
+ */
86
+ export function describeRejectedJwt(
87
+ kind: JwtRejectionKind,
88
+ token: string,
89
+ expected: string,
90
+ context?: JwtVerificationContext,
91
+ kid?: string,
92
+ ): { key: string; message: string } {
93
+ const parts = [`JWT rejected (${kind})`];
94
+ let key: string;
95
+ if (kind === 'issuer or audience mismatch') {
96
+ let claims: Record<string, unknown> = {};
97
+ try {
98
+ claims = decodeJwt(token);
99
+ } catch {
100
+ // Undecodable payload: report what is known
101
+ }
102
+ const iss = claims.iss === undefined ? '-' : clean(claims.iss, CLAIM_MAX_LENGTH);
103
+ const aud = Array.isArray(claims.aud) ? claims.aud.join(',') : (claims.aud ?? '-');
104
+ const expired = typeof claims.exp === 'number' && claims.exp * 1000 < Date.now();
105
+ parts.push(`expected "${expected}", got iss "${iss}", aud "${clean(aud, CLAIM_MAX_LENGTH)}"`);
106
+ parts.push(`issued ${isoFromEpoch(claims.iat)}, expires ${isoFromEpoch(claims.exp)}${expired ? ' (expired)' : ''}`);
107
+ key = `${kind}|${iss}`;
108
+ } else {
109
+ const safeKid = kid === undefined ? '-' : clean(kid, KID_MAX_LENGTH);
110
+ parts.push(`kid "${safeKid}"`);
111
+ key = kind === 'unknown signing key' ? kind : `${kind}|${safeKid}`;
112
+ }
113
+ if (context?.method || context?.path) {
114
+ parts.push(`${clean(context.method ?? '?', 10)} ${clean(context.path ?? '?', CLAIM_MAX_LENGTH)}`);
115
+ }
116
+ if (context?.origin) {
117
+ parts.push(`origin ${clean(context.origin, CLAIM_MAX_LENGTH)}`);
118
+ }
119
+ if (context?.userAgent) {
120
+ parts.push(`ua "${clean(context.userAgent, USER_AGENT_MAX_LENGTH)}"`);
121
+ }
122
+ return { key, message: parts.join('; ') };
123
+ }
124
+
125
+ /**
126
+ * Lets one warning per key through per window and counts the ones it holds back, so a client that sends the same bad
127
+ * token with every request cannot flood the log. The map is capped: when it is full, entries whose window has passed
128
+ * are dropped, and a key that still finds no room shares one overflow entry. A full map never resets the keys it holds,
129
+ * so nobody can reopen the warning of a real issuer by filling the map with others.
130
+ */
131
+ export class JwtRejectionThrottle {
132
+ private static readonly OVERFLOW_KEY = '*';
133
+ private readonly seen = new Map<string, { lastAt: number; suppressed: number }>();
134
+
135
+ constructor(
136
+ private readonly windowMs = 60 * 60 * 1000,
137
+ private readonly maxKeys = 500,
138
+ ) {}
139
+
140
+ /**
141
+ * @returns the number of occurrences held back since the last warning for this key, or `null` when this one is
142
+ * held back as well
143
+ */
144
+ take(key: string): null | number {
145
+ const now = Date.now();
146
+ if (!this.seen.has(key) && this.seen.size >= this.maxKeys) {
147
+ for (const [seenKey, seenEntry] of this.seen) {
148
+ if (now - seenEntry.lastAt >= this.windowMs) {
149
+ this.seen.delete(seenKey);
150
+ }
151
+ }
152
+ if (this.seen.size >= this.maxKeys) {
153
+ key = JwtRejectionThrottle.OVERFLOW_KEY;
154
+ }
155
+ }
156
+ const entry = this.seen.get(key);
157
+ if (entry && now - entry.lastAt < this.windowMs) {
158
+ entry.suppressed += 1;
159
+ return null;
160
+ }
161
+ this.seen.set(key, { lastAt: now, suppressed: 0 });
162
+ return entry?.suppressed ?? 0;
163
+ }
164
+ }
@@ -17,7 +17,7 @@ import {
17
17
  } from 'better-auth/api';
18
18
  import { Request } from 'express';
19
19
  import type { Response as ExpressResponse } from 'express';
20
- import { importJWK, jwtVerify } from 'jose';
20
+ import { errors as joseErrors, importJWK, jwtVerify } from 'jose';
21
21
  import type { Connection } from 'mongoose';
22
22
 
23
23
  import {
@@ -48,6 +48,13 @@ import {
48
48
  isPasskeyConfigured,
49
49
  isTwoFactorConfigured,
50
50
  } from './core-better-auth-sign-in-factors.helper.js';
51
+ import {
52
+ describeRejectedJwt,
53
+ type JwtRejectionKind,
54
+ JwtRejectionThrottle,
55
+ type JwtVerificationContext,
56
+ jwtVerificationContextFromRequest,
57
+ } from './core-better-auth-jwt-rejection.helper.js';
51
58
  import { isJwtShaped } from './core-better-auth-token.helper.js';
52
59
  import { BetterAuthSessionUser } from './core-better-auth-user.mapper.js';
53
60
  import { presentSessionTokens } from './core-better-auth-session-token.helper.js';
@@ -135,6 +142,8 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
135
142
  // this cache a test or fork that mutates `process.env.COOKIE_PREFIX` after
136
143
  // boot would push the service and the Better-Auth instance out of lockstep.
137
144
  private cachedCookiePrefix: null | string = null;
145
+ // Rejected JWTs are warned about at most once per hour and issuer or stored key (12.14.1)
146
+ protected readonly jwtRejectionThrottle = new JwtRejectionThrottle();
138
147
 
139
148
  constructor(
140
149
  @Optional() @Inject(BETTER_AUTH_INSTANCE) private readonly authInstance: BetterAuthInstance | null,
@@ -1515,6 +1524,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1515
1524
  * This enables stateless JWT verification without requiring a session cookie.
1516
1525
  *
1517
1526
  * @param token - The JWT token to verify (from Authorization header)
1527
+ * @param context - Optional facts about the request, named in the warning when the token is rejected (12.14.1)
1518
1528
  * @returns The JWT payload with user info, or null if verification fails
1519
1529
  *
1520
1530
  * @example
@@ -1528,7 +1538,10 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1528
1538
  * }
1529
1539
  * ```
1530
1540
  */
1531
- async verifyJwtToken(token: string): Promise<null | {
1541
+ async verifyJwtToken(
1542
+ token: string,
1543
+ context?: JwtVerificationContext,
1544
+ ): Promise<null | {
1532
1545
  [key: string]: any;
1533
1546
  email?: string;
1534
1547
  sub: string;
@@ -1557,7 +1570,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1557
1570
  payload = await this.verifyHs256Token(token);
1558
1571
  } else if (kid) {
1559
1572
  // 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);
1573
+ payload = await this.verifyJwksToken(token, kid, alg, context);
1561
1574
  } else {
1562
1575
  this.logger.debug(`JWT verification: unsupported algorithm=${alg} or missing kid`);
1563
1576
  return null;
@@ -1739,6 +1752,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1739
1752
  token: string,
1740
1753
  kid: string,
1741
1754
  alg: string,
1755
+ context?: JwtVerificationContext,
1742
1756
  ): Promise<null | {
1743
1757
  [key: string]: any;
1744
1758
  email?: string;
@@ -1756,7 +1770,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1756
1770
  let keyRecord = sql ? await sql.findJwk(kid) : await jwksCollection?.findOne({ id: kid });
1757
1771
 
1758
1772
  if (!keyRecord && sql) {
1759
- this.logger.debug(`No JWKS key found for kid: ${kid}`);
1773
+ this.reportRejectedJwt('unknown signing key', token, context, kid);
1760
1774
  return null;
1761
1775
  }
1762
1776
  if (!keyRecord && jwksCollection) {
@@ -1764,7 +1778,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1764
1778
  const allKeys = await jwksCollection.find({}).toArray();
1765
1779
  const matchingKey = allKeys.find((k) => k.id === kid || k._id?.toString() === kid);
1766
1780
  if (!matchingKey) {
1767
- this.logger.debug(`No JWKS key found for kid: ${kid}`);
1781
+ this.reportRejectedJwt('unknown signing key', token, context, kid);
1768
1782
  return null;
1769
1783
  }
1770
1784
  keyRecord = matchingKey;
@@ -1794,11 +1808,41 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1794
1808
 
1795
1809
  return payload as { [key: string]: any; email?: string; sub: string };
1796
1810
  } catch (error) {
1811
+ // A token signed by our own key but issued for another address, a forged signature, or a token from an unknown
1812
+ // key points at a misconfiguration or an attack, so it is a warning. An expired token is routine (12.14.1).
1813
+ if (error instanceof joseErrors.JWTClaimValidationFailed && (error.claim === 'iss' || error.claim === 'aud')) {
1814
+ this.reportRejectedJwt('issuer or audience mismatch', token, context);
1815
+ return null;
1816
+ }
1817
+ if (error instanceof joseErrors.JWSSignatureVerificationFailed) {
1818
+ this.reportRejectedJwt('invalid signature', token, context, kid);
1819
+ return null;
1820
+ }
1797
1821
  this.logger.debug(`JWKS verification error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1798
1822
  return null;
1799
1823
  }
1800
1824
  }
1801
1825
 
1826
+ /**
1827
+ * Warns about a rejected JWT with the facts needed to find its source (12.14.1): never the token, the subject or any
1828
+ * other claim beyond issuer, audience and times. Throttled to one warning per hour and issuer or stored key, and one
1829
+ * per hour in all for unknown key ids (the caller chooses those); the next warning names how many were held back. Before 12.14.1 every rejection was logged at debug level only, so a client
1830
+ * holding tokens of another issuer stayed invisible in production.
1831
+ */
1832
+ protected reportRejectedJwt(
1833
+ kind: JwtRejectionKind,
1834
+ token: string,
1835
+ context?: JwtVerificationContext,
1836
+ kid?: string,
1837
+ ): void {
1838
+ const { key, message } = describeRejectedJwt(kind, token, this.getBaseUrl(), context, kid);
1839
+ const suppressed = this.jwtRejectionThrottle.take(key);
1840
+ if (suppressed === null) {
1841
+ return;
1842
+ }
1843
+ this.logger.warn(suppressed > 0 ? `${message} (${suppressed} more since the last warning)` : message);
1844
+ }
1845
+
1802
1846
  /**
1803
1847
  * Extracts and verifies a JWT token from a request's Authorization header,
1804
1848
  * or verifies a directly provided token.
@@ -1823,6 +1867,6 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1823
1867
  token = authHeader.substring(7);
1824
1868
  }
1825
1869
 
1826
- return this.verifyJwtToken(token);
1870
+ return this.verifyJwtToken(token, jwtVerificationContextFromRequest(req));
1827
1871
  }
1828
1872
  }
@@ -32,6 +32,7 @@ export * from './core-better-auth-auth.model.js';
32
32
  export * from './core-better-auth-cookie.helper.js';
33
33
  export * from './core-better-auth-email-verification.service.js';
34
34
  export * from './core-better-auth-error-codes.helper.js';
35
+ export * from './core-better-auth-jwt-rejection.helper.js';
35
36
  export * from './core-better-auth-migration-status.model.js';
36
37
  export * from './core-better-auth-models.js';
37
38
  export * from './core-better-auth-path-guard.middleware.js';
@@ -13,6 +13,7 @@ import {
13
13
 
14
14
  import { getBuildInfo } from '../../common/helpers/meta.helper.js';
15
15
  import { isShutdownDraining } from '../../common/helpers/shutdown-state.helper.js';
16
+ import { InjectConnection } from '../../common/persistence/mongo/mongoose-compat.js';
16
17
  import { getPersistenceRuntime } from '../../common/persistence/persistence-runtime.registry.js';
17
18
  import { ConfigService } from '../../common/services/config.service.js';
18
19
  import {
@@ -22,6 +23,22 @@ import {
22
23
  resolveHealthCheckReadiness,
23
24
  } from './core-health-check.helpers.js';
24
25
 
26
+ /**
27
+ * How long a database ping (MongoDB and every SQL source) may take before the health check reports the database as
28
+ * down, unless `healthCheck.configs.database.options.timeout` sets another value.
29
+ *
30
+ * 2 s, not the former 300 ms (MongoDB) / 1000 ms (SQL): the MongoDB ping waits for the driver's server selection
31
+ * (see {@link CoreHealthCheckService.pingMongoDb}), which rides out a replica set that briefly sees no primary; a
32
+ * single slow round trip to a managed database outside the cluster must not report it down either. 2 s still fails a
33
+ * database that does not answer and stays below the readiness probe timeout of the lt charts (3 s).
34
+ */
35
+ export const DEFAULT_DATABASE_PING_TIMEOUT_MS = 2000;
36
+
37
+ /** The part of a Mongoose connection the health check's MongoDB ping uses */
38
+ export interface IHealthCheckMongoConnection {
39
+ db?: { command(command: Record<string, unknown>): Promise<unknown> } | null;
40
+ }
41
+
25
42
  /**
26
43
  * Core health check service
27
44
  * Inspired by https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2
@@ -44,6 +61,14 @@ export class CoreHealthCheckService {
44
61
  @Optional() protected indicators?: HealthIndicatorService,
45
62
  ) {}
46
63
 
64
+ /**
65
+ * The application's Mongoose connection for the MongoDB ping (12.14.0); `null` where no MongoDB is configured.
66
+ * Injected as a property, so a project subclass with its own constructor receives it too.
67
+ */
68
+ @Optional()
69
+ @InjectConnection()
70
+ protected mongoConnection?: IHealthCheckMongoConnection | null;
71
+
47
72
  /**
48
73
  * The liveness check (`GET /health-check`, the `healthCheck` query): every check `healthCheck.configs` enables, then
49
74
  * the project's own (`additionalHealthIndicators('liveness')`). Answers the Terminus result; rejects with 503 when a
@@ -161,26 +186,36 @@ export class CoreHealthCheckService {
161
186
  const healthIndicatorFunctions: HealthIndicatorFunction[] = [];
162
187
  // The MongoDB ping where MongoDB is configured — a project on PostgreSQL alone has no MongoDB to ping
163
188
  if (this.db) {
189
+ const db = this.db;
164
190
  healthIndicatorFunctions.push(() => {
165
191
  // `timeout` stays part of the config contract, but @nestjs/terminus 12 deprecated it on the
166
192
  // indicator in favour of `.withTimeout()` on the returned attempt — translate it here, so the
167
193
  // configuration keeps working once the option is gone from the indicator.
168
- // Same effective timeouts as before: 300 ms without configured options, otherwise the
169
- // configured `timeout`, otherwise Terminus' own default (1000 ms).
170
- const { timeout, ...options } = this.config.get<MongoosePingCheckSettings>(
171
- 'healthCheck.configs.database.options',
172
- ) ?? { timeout: 300 };
173
- const attempt = this.db.pingCheck(
174
- this.config.get<string>('healthCheck.configs.database.key') ?? 'database',
175
- options,
176
- );
177
- return timeout === undefined ? attempt : attempt.withTimeout(timeout);
194
+ const {
195
+ connection,
196
+ timeout = DEFAULT_DATABASE_PING_TIMEOUT_MS,
197
+ ...options
198
+ } = this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options') ?? {};
199
+ const key = this.config.get<string>('healthCheck.configs.database.key') ?? 'database';
200
+ const target: IHealthCheckMongoConnection | null | undefined = connection ?? this.mongoConnection;
201
+ if (!this.indicators || !target) {
202
+ // A subclass constructed without the HealthIndicatorService, or without the injected connection: Terminus'
203
+ // own check, with its readyState gate (see pingMongoDb)
204
+ return db.pingCheck(key, { connection, ...options }).withTimeout(timeout);
205
+ }
206
+ return this.indicators
207
+ .check(key)
208
+ .attempt(() => this.pingMongoDb(target))
209
+ .withFailureData((error: unknown) => ({ code: (error as { code?: unknown })?.code }))
210
+ .withTimeout(timeout);
178
211
  });
179
212
  }
180
213
  // Every SQL source answers on its own key, next to the MongoDB ping: `<key>:<source>` (`database:default`). A
181
214
  // database the application cannot reach is down, whichever one it is
182
215
  const key = this.config.get<string>('healthCheck.configs.database.key') ?? 'database';
183
- const timeout = this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options')?.timeout ?? 1000;
216
+ const timeout =
217
+ this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options')?.timeout ??
218
+ DEFAULT_DATABASE_PING_TIMEOUT_MS;
184
219
  if (this.indicators) {
185
220
  for (const source of getPersistenceRuntime()?.sqlSources() ?? []) {
186
221
  healthIndicatorFunctions.push(() =>
@@ -194,11 +229,33 @@ export class CoreHealthCheckService {
194
229
  return healthIndicatorFunctions;
195
230
  }
196
231
 
232
+ /**
233
+ * Pings the MongoDB the application uses (12.14.0): a real `ping` command, bounded by the check's timeout.
234
+ *
235
+ * Deliberately WITHOUT the `readyState` gate of Terminus' `MongooseHealthIndicator`, which reports "down" before it
236
+ * pings whenever the connection's `readyState` is not 1. Mongoose sets `disconnected` as soon as the driver's
237
+ * topology briefly sees no primary (a replica set without `ReplicaSetWithPrimary`, a single server turning
238
+ * `Unknown`): one lost heartbeat is enough, while the database answers in milliseconds and the application's own
239
+ * queries just wait for the driver's server selection. On a cluster with managed MongoDB replica sets that gate
240
+ * produced far more than 95 % of all "database down" alarms. Here the ping waits for server selection the same way,
241
+ * so the check reports down only when the database does not answer within the timeout.
242
+ *
243
+ * @param connection The Mongoose connection (`healthCheck.configs.database.options.connection` or the injected one)
244
+ */
245
+ protected async pingMongoDb(connection: IHealthCheckMongoConnection): Promise<void> {
246
+ if (!connection.db) {
247
+ // Not connected yet (the initial connect is still running) or never connected
248
+ throw new Error('Not connected to database');
249
+ }
250
+ await connection.db.command({ ping: 1 });
251
+ }
252
+
197
253
  /**
198
254
  * Build identity (commit / version / env) — always reported as "up", so it surfaces under `info`/`details` without
199
255
  * ever affecting the overall health status. Lets ops/monitoring detect a drifted or stale container after a partial
200
256
  * rollout (the same commit-SHA signal the admin UI compares). The commit is baked into the image at build time
201
- * (APP_VERSION_COMMIT, fed from the CI commit SHA); `version`/`env` come from the config. Opt out with
257
+ * (APP_VERSION_COMMIT, fed from the CI commit SHA); `version`/`env` come from the config, and with a build number
258
+ * (APP_VERSION_BUILD, the CI pipeline counter) `build` is reported and `version` becomes <Major>.<Minor>.<Build>. Opt out with
202
259
  * `healthCheck.configs.build.enabled: false`.
203
260
  */
204
261
  protected buildHealthIndicators(): HealthIndicatorFunction[] {