@lenne.tech/nest-server 11.46.11 → 11.46.12

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.
@@ -147,7 +147,7 @@ if (config.dbObject && config.checkRights && this.checkRights) {
147
147
 
148
148
  - `CrudService.update()` (Zeile 552): Setzt `dbObject` bereits als lean-Objekt (`findById().lean()`) → konsistent.
149
149
  - Kein Projekt uebergibt ein Mongoose-Document als dbObject → kein Konflikt.
150
- - Services die `process()` direkt aufrufen mit `dbObject` als String (z.B. swaktiv/OfferService): Profitieren von der Optimierung.
150
+ - Services die `process()` direkt aufrufen mit `dbObject` als String (z.B. der eigene Offer-Service eines Projekts): Profitieren von der Optimierung.
151
151
 
152
152
  ---
153
153
 
@@ -0,0 +1,62 @@
1
+ # Migration Guide: 11.46.11 → 11.46.12
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | A rejected Better-Auth JWT produces a throttled warning with the facts needed to find its source (§1) |
9
+ | **Bugfixes** | None |
10
+ | **Migration Effort** | None |
11
+
12
+ ## Quick Migration
13
+
14
+ ```bash
15
+ pnpm add @lenne.tech/nest-server@11.46.12
16
+ pnpm run build
17
+ pnpm test
18
+ ```
19
+
20
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` with `--target 11.46.12` as usual.
21
+
22
+ ## 1. Warning for rejected JWTs
23
+
24
+ `CoreBetterAuthService` logged every rejected Bearer JWT at debug level only. In production, where debug output is
25
+ off, a client that kept sending tokens of another issuer (an old base URL, another stage, a wrong audience) stayed
26
+ invisible: its requests were simply anonymous.
27
+
28
+ Since 11.46.12 three kinds of rejection log a **warning**:
29
+
30
+ | Kind | When |
31
+ |---|---|
32
+ | `issuer or audience mismatch` | the token is signed by one of our keys, but `iss` / `aud` is not this API's base URL |
33
+ | `invalid signature` | the token names one of our keys, but that key did not sign it |
34
+ | `unknown signing key` | the token's `kid` is not in the JWKS store |
35
+
36
+ The line names the expected and the received issuer and audience, when the token was issued and when it expires
37
+ (mismatch), or the key id (signature, unknown key), and the request: method, path without query string, origin and
38
+ a shortened user agent. It **never** contains the token, the subject or any other claim. Every value that comes from
39
+ the client (claims, key id, headers) is length-capped, and control characters (C0, C1, line separators, bidi
40
+ controls) are replaced with `?`, so a crafted header cannot steer the terminal that shows the log. Example:
41
+
42
+ ```
43
+ JWT rejected (issuer or audience mismatch); expected "https://api.example.com", got iss "https://api.old.example.com", aud "https://api.old.example.com"; issued 2026-10-14T08:40:00.000Z, expires 2026-10-14T08:55:00.000Z (expired); POST /iam/sign-out; origin https://app.example.com; ua "Mozilla/5.0 …"
44
+ ```
45
+
46
+ Each kind is throttled to **one warning per hour** and issuer (mismatch) or stored key id (signature). Unknown key ids
47
+ share one warning per hour, because the caller invents them and could otherwise write one warning per request. The next
48
+ warning names how many were held back (`(12 more since the last warning)`). An expired token with the expected issuer
49
+ is routine and stays at debug level.
50
+
51
+ `verifyJwtToken(token, context?)` takes the request facts as an optional second parameter
52
+ (`JwtVerificationContext`, built with `jwtVerificationContextFromRequest(req)`); `verifyJwtFromRequest()` passes them
53
+ on. Existing calls with one argument keep working. A subclass changes the wording or the target of the warning by
54
+ overriding the protected `reportRejectedJwt()`.
55
+
56
+ **Check:** nothing to change. If the warning shows up, the named issuer tells you which client or stage still holds
57
+ tokens for another base URL.
58
+
59
+ ## Module Documentation
60
+
61
+ - `src/core/modules/better-auth/core-better-auth-jwt-rejection.helper.ts`
62
+ - `src/core/modules/better-auth/README.md`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.46.11",
3
+ "version": "11.46.12",
4
4
  "description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
5
5
  "keywords": [
6
6
  "node",
@@ -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 11.46.12 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 (11.46.12).
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
+ }
@@ -16,7 +16,7 @@ import {
16
16
  } from 'better-auth/api';
17
17
  import { Request } from 'express';
18
18
  import type { Response as ExpressResponse } from 'express';
19
- import { importJWK, jwtVerify } from 'jose';
19
+ import { errors as joseErrors, importJWK, jwtVerify } from 'jose';
20
20
  import { Connection } from 'mongoose';
21
21
 
22
22
  import {
@@ -32,6 +32,13 @@ import { ErrorCode } from '../error-code/error-codes';
32
32
  import { resolveBetterAuthCookiePrefix } from './better-auth-cookie-prefix.helper';
33
33
  import { BetterAuthInstance } from './better-auth.config';
34
34
  import { legacyCredentialAccountIssuer, usesLegacyAccountIssuer } from './core-better-auth-account-issuer.helper';
35
+ import {
36
+ describeRejectedJwt,
37
+ type JwtRejectionKind,
38
+ JwtRejectionThrottle,
39
+ type JwtVerificationContext,
40
+ jwtVerificationContextFromRequest,
41
+ } from './core-better-auth-jwt-rejection.helper';
35
42
  import {
36
43
  BUILT_IN_BETTER_AUTH_PLUGIN_IDS,
37
44
  HANDLER_SESSION_PATHS,
@@ -125,6 +132,8 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
125
132
  // this cache a test or fork that mutates `process.env.COOKIE_PREFIX` after
126
133
  // boot would push the service and the Better-Auth instance out of lockstep.
127
134
  private cachedCookiePrefix: null | string = null;
135
+ // Rejected JWTs are warned about at most once per hour and issuer or stored key (11.46.12)
136
+ protected readonly jwtRejectionThrottle = new JwtRejectionThrottle();
128
137
 
129
138
  constructor(
130
139
  @Optional() @Inject(BETTER_AUTH_INSTANCE) private readonly authInstance: BetterAuthInstance | null,
@@ -1433,6 +1442,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
1433
1442
  * This enables stateless JWT verification without requiring a session cookie.
1434
1443
  *
1435
1444
  * @param token - The JWT token to verify (from Authorization header)
1445
+ * @param context - Optional facts about the request, named in the warning when the token is rejected (11.46.12)
1436
1446
  * @returns The JWT payload with user info, or null if verification fails
1437
1447
  *
1438
1448
  * @example
@@ -1446,7 +1456,10 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
1446
1456
  * }
1447
1457
  * ```
1448
1458
  */
1449
- async verifyJwtToken(token: string): Promise<null | {
1459
+ async verifyJwtToken(
1460
+ token: string,
1461
+ context?: JwtVerificationContext,
1462
+ ): Promise<null | {
1450
1463
  [key: string]: any;
1451
1464
  email?: string;
1452
1465
  sub: string;
@@ -1476,7 +1489,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
1476
1489
 
1477
1490
  // For asymmetric algorithms (EdDSA, RS256, ES256), use JWKS
1478
1491
  if (kid && this.connection) {
1479
- return this.verifyJwksToken(token, kid, alg);
1492
+ return this.verifyJwksToken(token, kid, alg, context);
1480
1493
  }
1481
1494
 
1482
1495
  this.logger.debug(`JWT verification: unsupported algorithm=${alg} or missing kid`);
@@ -1528,6 +1541,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
1528
1541
  token: string,
1529
1542
  kid: string,
1530
1543
  alg: string,
1544
+ context?: JwtVerificationContext,
1531
1545
  ): Promise<null | {
1532
1546
  [key: string]: any;
1533
1547
  email?: string;
@@ -1548,7 +1562,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
1548
1562
  const allKeys = await jwksCollection.find({}).toArray();
1549
1563
  const matchingKey = allKeys.find((k) => k.id === kid || k._id?.toString() === kid);
1550
1564
  if (!matchingKey) {
1551
- this.logger.debug(`No JWKS key found for kid: ${kid}`);
1565
+ this.reportRejectedJwt('unknown signing key', token, context, kid);
1552
1566
  return null;
1553
1567
  }
1554
1568
  keyRecord = matchingKey;
@@ -1578,11 +1592,41 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
1578
1592
 
1579
1593
  return payload as { [key: string]: any; email?: string; sub: string };
1580
1594
  } catch (error) {
1595
+ // A token signed by our own key but issued for another address, a forged signature, or a token from an unknown
1596
+ // key points at a misconfiguration or an attack, so it is a warning. An expired token is routine (11.46.12).
1597
+ if (error instanceof joseErrors.JWTClaimValidationFailed && (error.claim === 'iss' || error.claim === 'aud')) {
1598
+ this.reportRejectedJwt('issuer or audience mismatch', token, context);
1599
+ return null;
1600
+ }
1601
+ if (error instanceof joseErrors.JWSSignatureVerificationFailed) {
1602
+ this.reportRejectedJwt('invalid signature', token, context, kid);
1603
+ return null;
1604
+ }
1581
1605
  this.logger.debug(`JWKS verification error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1582
1606
  return null;
1583
1607
  }
1584
1608
  }
1585
1609
 
1610
+ /**
1611
+ * Warns about a rejected JWT with the facts needed to find its source (11.46.12): never the token, the subject or any
1612
+ * other claim beyond issuer, audience and times. Throttled to one warning per hour and issuer or stored key, and one
1613
+ * per hour in all for unknown key ids (the caller chooses those); the next warning names how many were held back. Before 11.46.12 every rejection was logged at debug level only, so a client
1614
+ * holding tokens of another issuer stayed invisible in production.
1615
+ */
1616
+ protected reportRejectedJwt(
1617
+ kind: JwtRejectionKind,
1618
+ token: string,
1619
+ context?: JwtVerificationContext,
1620
+ kid?: string,
1621
+ ): void {
1622
+ const { key, message } = describeRejectedJwt(kind, token, this.getBaseUrl(), context, kid);
1623
+ const suppressed = this.jwtRejectionThrottle.take(key);
1624
+ if (suppressed === null) {
1625
+ return;
1626
+ }
1627
+ this.logger.warn(suppressed > 0 ? `${message} (${suppressed} more since the last warning)` : message);
1628
+ }
1629
+
1586
1630
  /**
1587
1631
  * Extracts and verifies a JWT token from a request's Authorization header,
1588
1632
  * or verifies a directly provided token.
@@ -1607,6 +1651,6 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
1607
1651
  token = authHeader.substring(7);
1608
1652
  }
1609
1653
 
1610
- return this.verifyJwtToken(token);
1654
+ return this.verifyJwtToken(token, jwtVerificationContextFromRequest(req));
1611
1655
  }
1612
1656
  }
@@ -32,6 +32,7 @@ export * from './core-better-auth-auth.model';
32
32
  export * from './core-better-auth-cookie.helper';
33
33
  export * from './core-better-auth-email-verification.service';
34
34
  export * from './core-better-auth-error-codes.helper';
35
+ export * from './core-better-auth-jwt-rejection.helper';
35
36
  export * from './core-better-auth-migration-status.model';
36
37
  export * from './core-better-auth-models';
37
38
  export * from './core-better-auth-path-guard.middleware';