@lenne.tech/nest-server 11.46.10 → 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.
- package/.claude/rules/testing.md +3 -3
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.d.ts +21 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.js +112 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +4 -1
- package/dist/core/modules/better-auth/core-better-auth.service.js +23 -5
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/core/modules/better-auth/index.d.ts +1 -0
- package/dist/core/modules/better-auth/index.js +1 -0
- package/dist/core/modules/better-auth/index.js.map +1 -1
- package/dist/core/modules/health-check/core-health-check.service.d.ts +12 -0
- package/dist/core/modules/health-check/core-health-check.service.js +40 -2
- package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/docs/process-performance-optimization.md +1 -1
- package/migration-guides/11.46.10-to-11.46.11.md +57 -0
- package/migration-guides/11.46.11-to-11.46.12.md +62 -0
- package/package.json +1 -1
- package/src/core/modules/better-auth/README.md +4 -1
- package/src/core/modules/better-auth/core-better-auth-jwt-rejection.helper.ts +164 -0
- package/src/core/modules/better-auth/core-better-auth.service.ts +49 -5
- package/src/core/modules/better-auth/index.ts +1 -0
- package/src/core/modules/health-check/core-health-check.service.ts +74 -3
|
@@ -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.
|
|
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,57 @@
|
|
|
1
|
+
# Migration Guide: 11.46.10 → 11.46.11
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
| Category | Details |
|
|
6
|
+
|---|---|
|
|
7
|
+
| **Breaking Changes** | None. Changed defaults: the MongoDB health check pings instead of reading `readyState`, and waits up to 2000 ms (§1) |
|
|
8
|
+
| **New Features** | None |
|
|
9
|
+
| **Bugfixes** | The health check reported a reachable MongoDB replica set as down whenever the driver briefly saw no primary (§1) |
|
|
10
|
+
| **Migration Effort** | None |
|
|
11
|
+
|
|
12
|
+
## Quick Migration
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @lenne.tech/nest-server@11.46.11
|
|
16
|
+
pnpm run build
|
|
17
|
+
pnpm test
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
**Vendor mode**: run `/lt-dev:backend:update-nest-server-core` with `--target 11.46.11` as usual.
|
|
21
|
+
|
|
22
|
+
## 1. Health check: the MongoDB check pings, and waits up to 2000 ms
|
|
23
|
+
|
|
24
|
+
Terminus 11's `MongooseHealthIndicator` does not ping the database: it reports up when the Mongoose connection's
|
|
25
|
+
`readyState` is 1 and down otherwise. Mongoose sets `disconnected` as soon as the driver's topology briefly sees no
|
|
26
|
+
primary: a replica set without `ReplicaSetWithPrimary`, a single server turning `Unknown`. One lost heartbeat is
|
|
27
|
+
enough, while the database answers in milliseconds and the application's own queries simply wait for the driver's
|
|
28
|
+
server selection. On a cluster with managed MongoDB replica sets this caused far more than 95 % of all "database
|
|
29
|
+
down" alarms, and three in a row took the pod out of the readiness rotation.
|
|
30
|
+
|
|
31
|
+
The core now sends a real `ping` (`CoreHealthCheckService.mongoPingCheck()` / `pingMongoDb()`). It waits for the
|
|
32
|
+
driver's server selection like any query, so the check reports down only when the database does not answer within
|
|
33
|
+
the timeout (message `timeout of <n>ms exceeded`), when the ping fails (the driver's message), or when the initial
|
|
34
|
+
connect has not finished yet (`Not connected to database`).
|
|
35
|
+
|
|
36
|
+
The timeout is now **2000 ms** (`DEFAULT_DATABASE_PING_TIMEOUT_MS`), unless
|
|
37
|
+
`healthCheck.configs.database.options.timeout` sets another value. Before, it was 300 ms without configured options
|
|
38
|
+
and 1000 ms with options but no `timeout`.
|
|
39
|
+
|
|
40
|
+
**Check:** nothing to change. Keep your probe timeout above 2 s. A subclass of `CoreHealthCheckService` keeps the new
|
|
41
|
+
check; one that builds its own MongoDB indicator with `this.db.pingCheck()` keeps Terminus' `readyState` check. To keep
|
|
42
|
+
the old timeout, set `healthCheck.configs.database.options.timeout: 300`.
|
|
43
|
+
|
|
44
|
+
## 2. Audit: minimatch 11.0.10, glob residual
|
|
45
|
+
|
|
46
|
+
Two advisories reached GitHub's global database on 2026-12-04, so `pnpm audit` fails without action:
|
|
47
|
+
|
|
48
|
+
- GHSA-3924-r96c-gp9w (low, minimatch 11.0.6 to 11.0.9): nest-server overrides it to 11.0.10. The override does not
|
|
49
|
+
reach your project; where `pnpm audit` reports it, add `'minimatch@>=11.0.0 <11.0.10': '11.0.10'` to `overrides` in
|
|
50
|
+
your `pnpm-workspace.yaml`.
|
|
51
|
+
- GHSA-c6wh-w8c3-cv3g (moderate, glob up to 14.0.5): fixed only in glob 14.0.6, while `@nestjs/cli` 11.0.24 (the newest
|
|
52
|
+
11.x) pins glob 13.0.6 exactly. Dev tooling only (the CLI's glob matches your own build patterns). nest-server
|
|
53
|
+
declares it like GHSA-qxr8-q827-836c: `ignoreGhsas` plus `unusableFixConsumers: { GHSA-c6wh-w8c3-cv3g: '@nestjs/cli@11.0.24 cannot use 14.0.6' }`. Do the same in your project if `pnpm audit` reports it.
|
|
54
|
+
|
|
55
|
+
## Module Documentation
|
|
56
|
+
|
|
57
|
+
- `src/core/modules/health-check/core-health-check.service.ts`: `mongoPingCheck()`, `pingMongoDb()`
|
|
@@ -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.
|
|
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(
|
|
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.
|
|
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';
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { Injectable } from '@nestjs/common';
|
|
1
|
+
import { Injectable, Optional } from '@nestjs/common';
|
|
2
|
+
import { InjectConnection } from '@nestjs/mongoose';
|
|
2
3
|
import {
|
|
3
4
|
DiskHealthIndicator,
|
|
4
5
|
HealthCheckResult,
|
|
5
6
|
HealthCheckService,
|
|
7
|
+
HealthIndicatorService,
|
|
6
8
|
MemoryHealthIndicator,
|
|
7
9
|
MongooseHealthIndicator,
|
|
8
10
|
} from '@nestjs/terminus';
|
|
@@ -12,6 +14,20 @@ import type { DiskHealthIndicatorOptions } from '@nestjs/terminus/dist/health-in
|
|
|
12
14
|
import { getBuildInfo } from '../../common/helpers/meta.helper';
|
|
13
15
|
import { ConfigService } from '../../common/services/config.service';
|
|
14
16
|
|
|
17
|
+
/**
|
|
18
|
+
* How long the MongoDB ping may take before the health check reports the database as down, unless
|
|
19
|
+
* `healthCheck.configs.database.options.timeout` sets another value (11.46.11; before: 300 ms without options, 1000 ms
|
|
20
|
+
* with options but no `timeout`). The ping waits for the driver's server selection (see
|
|
21
|
+
* {@link CoreHealthCheckService.pingMongoDb}), which rides out a replica set that briefly sees no primary; 2 s still
|
|
22
|
+
* fails a database that does not answer and stays below the readiness probe timeout of the lt charts (3 s).
|
|
23
|
+
*/
|
|
24
|
+
export const DEFAULT_DATABASE_PING_TIMEOUT_MS = 2000;
|
|
25
|
+
|
|
26
|
+
/** The part of a Mongoose connection the health check's MongoDB ping uses */
|
|
27
|
+
export interface IHealthCheckMongoConnection {
|
|
28
|
+
db?: { command(command: Record<string, unknown>): Promise<unknown> } | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
15
31
|
/**
|
|
16
32
|
* Core health check service
|
|
17
33
|
* Inspired by https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2
|
|
@@ -26,13 +42,21 @@ export class CoreHealthCheckService {
|
|
|
26
42
|
protected memory: MemoryHealthIndicator,
|
|
27
43
|
) {}
|
|
28
44
|
|
|
45
|
+
/**
|
|
46
|
+
* The application's Mongoose connection for the MongoDB ping (11.46.11). Injected as a property, so a project
|
|
47
|
+
* subclass with its own constructor receives it too.
|
|
48
|
+
*/
|
|
49
|
+
@Optional()
|
|
50
|
+
@InjectConnection()
|
|
51
|
+
protected mongoConnection?: IHealthCheckMongoConnection | null;
|
|
52
|
+
|
|
29
53
|
healthCheck(): Promise<HealthCheckResult> {
|
|
30
54
|
const healthIndicatorFunctions = [];
|
|
31
55
|
if (this.config.get<boolean>('healthCheck.configs.database.enabled')) {
|
|
32
56
|
healthIndicatorFunctions.push(() =>
|
|
33
|
-
this.
|
|
57
|
+
this.mongoPingCheck(
|
|
34
58
|
this.config.get<string>('healthCheck.configs.database.key') ?? 'database',
|
|
35
|
-
this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options') ?? {
|
|
59
|
+
this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options') ?? {},
|
|
36
60
|
),
|
|
37
61
|
);
|
|
38
62
|
}
|
|
@@ -79,4 +103,51 @@ export class CoreHealthCheckService {
|
|
|
79
103
|
|
|
80
104
|
return this.health.check(healthIndicatorFunctions);
|
|
81
105
|
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The MongoDB indicator (11.46.11): up when the database answers a real `ping` within the timeout.
|
|
109
|
+
*
|
|
110
|
+
* Replaces Terminus' `MongooseHealthIndicator.pingCheck()`, which in Terminus 11 does not ping at all: it reports
|
|
111
|
+
* up when the connection's `readyState` is 1 and down otherwise. Mongoose sets `disconnected` as soon as the
|
|
112
|
+
* driver's topology briefly sees no primary (a replica set without `ReplicaSetWithPrimary`, a single server turning
|
|
113
|
+
* `Unknown`): one lost heartbeat is enough, while the database answers in milliseconds and the application's own
|
|
114
|
+
* queries just wait for the driver's server selection. On a cluster with managed MongoDB replica sets that produced
|
|
115
|
+
* far more than 95 % of all "database down" alarms. Falls back to Terminus' check when no connection is available.
|
|
116
|
+
*/
|
|
117
|
+
protected async mongoPingCheck(key: string, options: MongoosePingCheckSettings) {
|
|
118
|
+
const connection: IHealthCheckMongoConnection | null | undefined = options.connection ?? this.mongoConnection;
|
|
119
|
+
if (!connection) {
|
|
120
|
+
return this.db.pingCheck(key, { timeout: DEFAULT_DATABASE_PING_TIMEOUT_MS, ...options });
|
|
121
|
+
}
|
|
122
|
+
const timeout = options.timeout || DEFAULT_DATABASE_PING_TIMEOUT_MS;
|
|
123
|
+
const check = new HealthIndicatorService().check(key);
|
|
124
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
125
|
+
try {
|
|
126
|
+
await Promise.race([
|
|
127
|
+
this.pingMongoDb(connection),
|
|
128
|
+
new Promise<never>((_, reject) => {
|
|
129
|
+
timer = setTimeout(() => reject(new Error(`timeout of ${timeout}ms exceeded`)), timeout);
|
|
130
|
+
}),
|
|
131
|
+
]);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
return check.down({ message: (error as Error)?.message ?? String(error) });
|
|
134
|
+
} finally {
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
}
|
|
137
|
+
return check.up();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Pings the MongoDB the application uses: a real `ping` command that waits for the driver's server selection like
|
|
142
|
+
* any query — deliberately without a `readyState` check (see {@link mongoPingCheck}).
|
|
143
|
+
*
|
|
144
|
+
* @param connection The Mongoose connection (`healthCheck.configs.database.options.connection` or the injected one)
|
|
145
|
+
*/
|
|
146
|
+
protected async pingMongoDb(connection: IHealthCheckMongoConnection): Promise<void> {
|
|
147
|
+
if (!connection.db) {
|
|
148
|
+
// Not connected yet (the initial connect is still running) or never connected
|
|
149
|
+
throw new Error('Not connected to database');
|
|
150
|
+
}
|
|
151
|
+
await connection.db.command({ ping: 1 });
|
|
152
|
+
}
|
|
82
153
|
}
|