@lenne.tech/nest-server 12.10.0 → 12.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/rules/better-auth.md +19 -0
- package/.claude/rules/configurable-features.md +12 -10
- package/.claude/rules/package-management.md +10 -8
- package/.claude/rules/role-system.md +4 -1
- package/.claude/rules/testing.md +4 -4
- package/CLAUDE.md +5 -0
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/decorators/unified-field.decorator.js +5 -2
- package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
- package/dist/core/common/helpers/config.helper.js +31 -9
- package/dist/core/common/helpers/config.helper.js.map +1 -1
- package/dist/core/common/helpers/graceful-shutdown.helper.js +3 -1
- package/dist/core/common/helpers/graceful-shutdown.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +2 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +31 -0
- package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-ws-connection.helper.d.ts +8 -3
- package/dist/core/common/helpers/graphql-ws-connection.helper.js +44 -0
- package/dist/core/common/helpers/graphql-ws-connection.helper.js.map +1 -1
- package/dist/core/common/helpers/http-stream-auth.helper.d.ts +13 -0
- package/dist/core/common/helpers/http-stream-auth.helper.js +90 -0
- package/dist/core/common/helpers/http-stream-auth.helper.js.map +1 -0
- package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
- package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
- package/dist/core/common/helpers/shutdown-state.helper.d.ts +3 -0
- package/dist/core/common/helpers/shutdown-state.helper.js +11 -0
- package/dist/core/common/helpers/shutdown-state.helper.js.map +1 -0
- package/dist/core/common/interfaces/cron-job-config-with-utc-offset.interface.d.ts +1 -1
- package/dist/core/common/interfaces/cron-job-config.interface.d.ts +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +14 -0
- package/dist/core/common/plugins/complexity.plugin.js +73 -9
- package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
- package/dist/core/common/services/core-cron-jobs.service.d.ts +13 -0
- package/dist/core/common/services/core-cron-jobs.service.js +129 -4
- package/dist/core/common/services/core-cron-jobs.service.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js +48 -4
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.d.ts +8 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js +47 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-models.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-models.js +7 -0
- package/dist/core/modules/better-auth/core-better-auth-models.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.d.ts +11 -0
- package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js +62 -0
- package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +28 -1
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.controller.js +2 -1
- package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.middleware.js +2 -2
- package/dist/core/modules/better-auth/core-better-auth.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -0
- package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +10 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js +105 -19
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/core/modules/health-check/core-health-check-readiness.controller.d.ts +6 -0
- package/dist/core/modules/health-check/core-health-check-readiness.controller.js +36 -0
- package/dist/core/modules/health-check/core-health-check-readiness.controller.js.map +1 -0
- package/dist/core/modules/health-check/core-health-check.helpers.d.ts +10 -0
- package/dist/core/modules/health-check/core-health-check.helpers.js +31 -0
- package/dist/core/modules/health-check/core-health-check.helpers.js.map +1 -0
- package/dist/core/modules/health-check/core-health-check.module.d.ts +9 -0
- package/dist/core/modules/health-check/core-health-check.module.js +13 -2
- package/dist/core/modules/health-check/core-health-check.module.js.map +1 -1
- package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -1
- package/dist/core/modules/health-check/core-health-check.service.js +66 -29
- package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
- package/dist/core/modules/sync/core-sync.service.d.ts +2 -0
- package/dist/core/modules/sync/core-sync.service.js +11 -1
- package/dist/core/modules/sync/core-sync.service.js.map +1 -1
- package/dist/core.module.js +5 -1
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +18 -6
- package/docs/offline-sync-protocol.md +5 -3
- package/migration-guides/12.10.0-to-12.10.1.md +182 -0
- package/migration-guides/12.10.x-to-12.11.x.md +295 -0
- package/package.json +17 -17
- package/src/core/common/decorators/unified-field.decorator.ts +14 -4
- package/src/core/common/helpers/config.helper.ts +55 -8
- package/src/core/common/helpers/graceful-shutdown.helper.ts +10 -3
- package/src/core/common/helpers/graphql-upload.helper.ts +93 -0
- package/src/core/common/helpers/graphql-ws-connection.helper.ts +99 -4
- package/src/core/common/helpers/http-stream-auth.helper.ts +197 -0
- package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
- package/src/core/common/helpers/shutdown-state.helper.ts +28 -0
- package/src/core/common/interfaces/cron-job-config-with-utc-offset.interface.ts +1 -1
- package/src/core/common/interfaces/cron-job-config.interface.ts +1 -1
- package/src/core/common/interfaces/server-options.interface.ts +113 -1
- package/src/core/common/plugins/complexity.plugin.ts +150 -9
- package/src/core/common/services/core-cron-jobs.service.ts +241 -14
- package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +26 -10
- package/src/core/modules/better-auth/README.md +37 -8
- package/src/core/modules/better-auth/better-auth.config.ts +83 -12
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +1 -1
- package/src/core/modules/better-auth/core-better-auth-jwt-session.cache.ts +104 -0
- package/src/core/modules/better-auth/core-better-auth-models.ts +5 -0
- package/src/core/modules/better-auth/core-better-auth-sign-in-factors.helper.ts +105 -0
- package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +37 -1
- package/src/core/modules/better-auth/core-better-auth.controller.ts +6 -3
- package/src/core/modules/better-auth/core-better-auth.middleware.ts +4 -3
- package/src/core/modules/better-auth/core-better-auth.module.ts +1 -1
- package/src/core/modules/better-auth/core-better-auth.resolver.ts +1 -0
- package/src/core/modules/better-auth/core-better-auth.service.ts +160 -27
- package/src/core/modules/health-check/core-health-check-readiness.controller.ts +27 -0
- package/src/core/modules/health-check/core-health-check.helpers.ts +65 -0
- package/src/core/modules/health-check/core-health-check.module.ts +37 -2
- package/src/core/modules/health-check/core-health-check.service.ts +154 -59
- package/src/core/modules/sync/README.md +18 -6
- package/src/core/modules/sync/core-sync.service.ts +35 -6
- package/src/core.module.ts +9 -1
- package/src/index.ts +4 -0
- package/src/main.ts +2 -1
|
@@ -19,6 +19,23 @@
|
|
|
19
19
|
* when the response closed — temporary files and file descriptors leaked per request (with `maxFiles` > 1; the
|
|
20
20
|
* default is unlimited).
|
|
21
21
|
*
|
|
22
|
+
* One addition of the framework's own, not in graphql-upload (18.0.2 has the same flaws): the `map` is bounded, and
|
|
23
|
+
* with it everything the parser builds from it. A path may have at most {@link GRAPHQL_UPLOAD_MAX_PATH_KEYS} keys. The
|
|
24
|
+
* whole `map` may name at most {@link GRAPHQL_UPLOAD_MAX_MAP_KEYS} units: one per entry, one per path key and one per
|
|
25
|
+
* array element a numeric path key creates, holes included. The entry or path that goes over a bound is refused with
|
|
26
|
+
* 400 before the parser builds anything for it. Measured on Node 24, one anonymous request each, before the bounds:
|
|
27
|
+
*
|
|
28
|
+
* - object-path's `set()` recurses once per key and copies the remaining keys each time, so a path of n keys costs
|
|
29
|
+
* O(n²): an 80 KB path (40,000 keys) exhausted a 1 GB heap and ended the process, 16 KB (8,000 keys) took 300 MB and
|
|
30
|
+
* blocked the event loop for half a second; 1 MB of paths under the per-path bound blocked it for up to 640 ms.
|
|
31
|
+
* - Every entry becomes an `Upload` that is rejected with an error of its own when its file never arrives: 1 MB of
|
|
32
|
+
* entries without a path (83,000) took 230 MB and blocked the event loop for 410 ms.
|
|
33
|
+
* - object-path reads a key like `4294967294` as a number and sets that index of an array it creates, so the 258-byte
|
|
34
|
+
* request `{"1":["variables.f.4294967294"]}` handed GraphQL an array of 4,294,967,295 elements. Coercing its holes in
|
|
35
|
+
* the complexity plugin exhausted a 1 GB heap within seconds.
|
|
36
|
+
*
|
|
37
|
+
* With the bounds such requests are refused within about 30 ms, most of it spent parsing the field's JSON.
|
|
38
|
+
*
|
|
22
39
|
* `CoreModule` passes this function to `graphqlUploadExpress({ processRequest })`. A project that registers
|
|
23
40
|
* `graphqlUploadExpress()` itself must pass it too — graphql-upload's own default is the unpatched function.
|
|
24
41
|
*
|
|
@@ -58,6 +75,26 @@ import type { Readable } from 'node:stream';
|
|
|
58
75
|
/** graphql-upload's `GRAPHQL_MULTIPART_REQUEST_SPEC_URL`, used in the error messages exactly as upstream does. */
|
|
59
76
|
const GRAPHQL_MULTIPART_REQUEST_SPEC_URL = 'https://github.com/jaydenseric/graphql-multipart-request-spec';
|
|
60
77
|
|
|
78
|
+
/**
|
|
79
|
+
* Most keys one `map` path may have (`variables.input.files.3` has 4). A longer path is refused with 400 "Invalid
|
|
80
|
+
* object path" before anything walks it: object-path's `set()` costs O(n²) in the number of keys. No request a client
|
|
81
|
+
* library builds comes near it — batched operations add one key (`0.variables.file`).
|
|
82
|
+
*/
|
|
83
|
+
export const GRAPHQL_UPLOAD_MAX_PATH_KEYS = 64;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Most units one `map` may name: one per entry, one per key of its paths, and one per element a numeric path key adds
|
|
87
|
+
* to an array, holes included — object-path sets index i, so the array becomes i + 1 long.
|
|
88
|
+
* `{"1":["variables.files.0"]}` counts 5 when `variables.files` does not exist yet and 4 when the operations already
|
|
89
|
+
* hold the slot; 2,000 files at `variables.files.N` count at most 10,000. The entry that goes over it is refused before
|
|
90
|
+
* its `Upload` exists, with 400 "Invalid ‘map’ multipart field entry key …"; the path that goes over it with 400
|
|
91
|
+
* "Invalid object path". It bounds the work of many paths (1 MB of 64-key paths blocked the event loop for up to
|
|
92
|
+
* 640 ms), of many entries (83,000 path-less entries in 1 MB took 230 MB and 410 ms) and of sparse arrays
|
|
93
|
+
* (`variables.f.4294967294` became an array of 2^32 − 1 elements, and GraphQL's list coercion walked them until the
|
|
94
|
+
* heap ran out).
|
|
95
|
+
*/
|
|
96
|
+
export const GRAPHQL_UPLOAD_MAX_MAP_KEYS = 10_000;
|
|
97
|
+
|
|
61
98
|
/**
|
|
62
99
|
* Options of {@link processGraphQlUploadRequest} — the same as graphql-upload's `ProcessRequestOptions`, so
|
|
63
100
|
* `graphqlUploadExpress({ processRequest, ...options })` forwards them unchanged.
|
|
@@ -98,6 +135,25 @@ function ignoreStream(stream: Readable): void {
|
|
|
98
135
|
stream.resume();
|
|
99
136
|
}
|
|
100
137
|
|
|
138
|
+
/**
|
|
139
|
+
* How many elements setting `key` in `container` adds to an array, the way object-path's `set()` sees it. object-path
|
|
140
|
+
* reads a key that `parseInt()` turns back into the same string as a NUMBER, and creates an array — not an object —
|
|
141
|
+
* for a missing container whose key is a number. Setting index i makes an array of length n i + 1 long when i ≥ n,
|
|
142
|
+
* every element in between a hole, and GraphQL's list coercion walks each of them. 0 for an object container, a
|
|
143
|
+
* string key, or a number that is not a non-negative integer (`NaN`, `-1`: a property, not an element).
|
|
144
|
+
*/
|
|
145
|
+
function arrayGrowth(container: unknown, key: string): number {
|
|
146
|
+
// object-path's getKey() calls parseInt() without a radix; for a key that round-trips the result is the same.
|
|
147
|
+
const index = Number.parseInt(key, 10);
|
|
148
|
+
if (index.toString() !== key || !Number.isInteger(index) || index < 0) {
|
|
149
|
+
return 0;
|
|
150
|
+
}
|
|
151
|
+
if (container === undefined) {
|
|
152
|
+
return index + 1;
|
|
153
|
+
}
|
|
154
|
+
return Array.isArray(container) ? Math.max(0, index + 1 - container.length) : 0;
|
|
155
|
+
}
|
|
156
|
+
|
|
101
157
|
/**
|
|
102
158
|
* Processes an incoming GraphQL multipart request
|
|
103
159
|
* (https://github.com/jaydenseric/graphql-multipart-request-spec): parses the `operations` and `map` fields, places
|
|
@@ -237,6 +293,8 @@ export function processGraphQlUploadRequest(
|
|
|
237
293
|
}
|
|
238
294
|
|
|
239
295
|
map = new Map();
|
|
296
|
+
// Map entries and path keys so far, against GRAPHQL_UPLOAD_MAX_MAP_KEYS.
|
|
297
|
+
let mapKeyCount = 0;
|
|
240
298
|
for (const [mapFieldName, paths] of mapEntries) {
|
|
241
299
|
if (!Array.isArray(paths)) {
|
|
242
300
|
return exit(
|
|
@@ -247,6 +305,18 @@ export function processGraphQlUploadRequest(
|
|
|
247
305
|
);
|
|
248
306
|
}
|
|
249
307
|
|
|
308
|
+
// Every entry counts one against GRAPHQL_UPLOAD_MAX_MAP_KEYS, before its Upload exists: an Upload whose
|
|
309
|
+
// file never arrives is rejected with an error of its own at the end of the request.
|
|
310
|
+
mapKeyCount += 1;
|
|
311
|
+
if (mapKeyCount > GRAPHQL_UPLOAD_MAX_MAP_KEYS) {
|
|
312
|
+
return exit(
|
|
313
|
+
createError(
|
|
314
|
+
400,
|
|
315
|
+
`Invalid ‘map’ multipart field entry key ‘${mapFieldName}’: the map has more than ${GRAPHQL_UPLOAD_MAX_MAP_KEYS} entries and object path keys together (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
|
|
316
|
+
),
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
|
|
250
320
|
map.set(mapFieldName, new Upload());
|
|
251
321
|
|
|
252
322
|
for (const [index, path] of paths.entries()) {
|
|
@@ -264,6 +334,18 @@ export function processGraphQlUploadRequest(
|
|
|
264
334
|
// safe before setting it.
|
|
265
335
|
const keys = path.split('.');
|
|
266
336
|
|
|
337
|
+
// Bound the path, and the whole map, before anything walks it: object-path's `set()` recurses once per
|
|
338
|
+
// key with a copy of the remaining keys — O(n²) for a path of n keys (see the file header).
|
|
339
|
+
if (keys.length > GRAPHQL_UPLOAD_MAX_PATH_KEYS) {
|
|
340
|
+
throw new RangeError(`Object path has more than ${GRAPHQL_UPLOAD_MAX_PATH_KEYS} keys.`);
|
|
341
|
+
}
|
|
342
|
+
mapKeyCount += keys.length;
|
|
343
|
+
if (mapKeyCount > GRAPHQL_UPLOAD_MAX_MAP_KEYS) {
|
|
344
|
+
throw new RangeError(
|
|
345
|
+
`The map has more than ${GRAPHQL_UPLOAD_MAX_MAP_KEYS} entries and object path keys.`,
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
|
|
267
349
|
let pathValue: unknown = operations;
|
|
268
350
|
|
|
269
351
|
for (const [keyIndex, key] of keys.entries()) {
|
|
@@ -273,6 +355,17 @@ export function processGraphQlUploadRequest(
|
|
|
273
355
|
throw new TypeError('Object path has a `__proto__` key.');
|
|
274
356
|
}
|
|
275
357
|
|
|
358
|
+
// `pathValue` is this key's container. A key object-path reads as a number extends an array — a new
|
|
359
|
+
// one when the container does not exist yet — up to that index: every element it adds counts against
|
|
360
|
+
// GRAPHQL_UPLOAD_MAX_MAP_KEYS, holes included (`variables.f.4294967294` adds 4,294,967,295).
|
|
361
|
+
const growth = arrayGrowth(pathValue, key);
|
|
362
|
+
if (growth > 0) {
|
|
363
|
+
mapKeyCount += growth;
|
|
364
|
+
if (mapKeyCount > GRAPHQL_UPLOAD_MAX_MAP_KEYS) {
|
|
365
|
+
throw new RangeError(`The map's arrays have more than ${GRAPHQL_UPLOAD_MAX_MAP_KEYS} elements.`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
276
369
|
// Forbid setting an upload within an already set upload, but allow a total replacement. Resolved
|
|
277
370
|
// with object-path's own `get`, so it sees what `set` will reach, inherited array elements included.
|
|
278
371
|
if (keyIndex < keys.length - 1) {
|
|
@@ -33,6 +33,12 @@ import { getTenantContextResolver, ResolvedTenantContext } from '../services/cor
|
|
|
33
33
|
* WHAT IT DOES NOT DO: an event is checked AFTER graphql-js executed it and BEFORE it is sent. Reads
|
|
34
34
|
* made while computing a dropped event still happened — under the old context — but nothing of them
|
|
35
35
|
* reaches the client. Subscription resolvers that WRITE are outside what this can take back.
|
|
36
|
+
*
|
|
37
|
+
* HTTP STREAMS (Server-Sent Events) are registered the same way, with `endsOnRecheck`: they end on
|
|
38
|
+
* every re-check and the client's reconnect passes the guards again. Since 12.11.0
|
|
39
|
+
* `recheckHttpStreamInPlace()` gives a stream whose credential can be re-run the WebSocket semantics
|
|
40
|
+
* instead — re-checked in place, closed only when the rights changed (`registerHttpStream()` in
|
|
41
|
+
* `http-stream-auth.helper.ts` registers a stream that way in one call).
|
|
36
42
|
*/
|
|
37
43
|
|
|
38
44
|
/**
|
|
@@ -90,6 +96,10 @@ export interface IWsConnectionRegistration {
|
|
|
90
96
|
* it, and the client's reconnect passes the guards again. The end the re-check interval brings is planned and logged
|
|
91
97
|
* at debug; one an invalidation brings (sign-out, role or tenant change) is logged like every withdrawn
|
|
92
98
|
* authorization. `reauthenticate` is not called.
|
|
99
|
+
*
|
|
100
|
+
* Since 12.11.0 `recheckHttpStreamInPlace()` switches such a stream to the WebSocket semantics once its credential
|
|
101
|
+
* can be re-run (a Better-Auth session cookie or bearer token: `createHttpStreamReauthenticator()`): it then stays
|
|
102
|
+
* open while the rights are unchanged and is closed only when they changed. `registerHttpStream()` does both steps.
|
|
93
103
|
*/
|
|
94
104
|
endsOnRecheck?: boolean;
|
|
95
105
|
|
|
@@ -118,14 +128,19 @@ export interface IWsConnectionIdentity {
|
|
|
118
128
|
export interface WsConnection {
|
|
119
129
|
readonly channel: string;
|
|
120
130
|
readonly email?: string;
|
|
121
|
-
|
|
131
|
+
/** Writable only for `recheckHttpStreamInPlace()`, which switches an HTTP stream to the in-place re-check. */
|
|
132
|
+
endsOnRecheck: boolean;
|
|
122
133
|
readonly iamId?: string;
|
|
123
|
-
|
|
134
|
+
/** Writable only for `recheckHttpStreamInPlace()`. */
|
|
135
|
+
reauthenticate?: () => any;
|
|
124
136
|
readonly socket?: IWsConnectionSocket;
|
|
125
137
|
/** The tenant scope the connection's operations resolved, once one has. */
|
|
126
138
|
tenant?: ResolvedTenantContext;
|
|
127
|
-
/**
|
|
128
|
-
|
|
139
|
+
/**
|
|
140
|
+
* The tenant header the client sent — constant for the life of the connection. Writable only for
|
|
141
|
+
* `recheckHttpStreamInPlace()`, which takes it from the HTTP request rather than from the carrier.
|
|
142
|
+
*/
|
|
143
|
+
tenantHeader?: string;
|
|
129
144
|
terminated: boolean;
|
|
130
145
|
readonly user: any;
|
|
131
146
|
readonly userFingerprint: string;
|
|
@@ -375,6 +390,86 @@ export function noteWsConnectionTenant(connection: WsConnection, tenant: Resolve
|
|
|
375
390
|
return true;
|
|
376
391
|
}
|
|
377
392
|
|
|
393
|
+
/** Options of {@link recheckHttpStreamInPlace}. */
|
|
394
|
+
export interface IHttpStreamRecheckOptions {
|
|
395
|
+
/**
|
|
396
|
+
* Re-run the credential the stream was opened with — the same authentication the request passed. Resolves to the
|
|
397
|
+
* user the credential authenticates as NOW, or to a falsy value when it no longer does; a rejection counts as falsy.
|
|
398
|
+
* `createHttpStreamReauthenticator()` builds one for a Better-Auth session cookie or bearer token.
|
|
399
|
+
*/
|
|
400
|
+
reauthenticate: () => any;
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* The tenant header the HTTP request carried (`readWsTenantHeader(request)`). It is validated against an active
|
|
404
|
+
* membership again on every re-check. Default: what the carrier held at registration.
|
|
405
|
+
*/
|
|
406
|
+
tenantHeader?: string;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Let an HTTP stream registered with `endsOnRecheck` (Server-Sent Events) be re-checked IN PLACE, the way a GraphQL
|
|
411
|
+
* WebSocket is (12.11.0).
|
|
412
|
+
*
|
|
413
|
+
* Until then such a stream ended on the first event after `graphQl.subscriptionRevalidationMs` and on every
|
|
414
|
+
* invalidation, and the client got that event only after its reconnect (an EventSource waits its `retry`, ~3 s).
|
|
415
|
+
* Switched, the re-check re-runs the credential (`reauthenticate`) and the tenant resolution and compares user id,
|
|
416
|
+
* roles, verification and tenant scope with what the stream was authorized with: unchanged, the stream stays open and
|
|
417
|
+
* the event is delivered; changed — in either direction — the stream is closed and the client reconnects with the
|
|
418
|
+
* rights it holds now.
|
|
419
|
+
*
|
|
420
|
+
* The switch is made only when the credential, run once NOW, answers the user the guards authorized the stream for
|
|
421
|
+
* with the same rights and — when the stream recorded its tenant scope (`noteWsConnectionTenant()`, record it BEFORE
|
|
422
|
+
* calling this) — the same tenant scope. Otherwise nothing can tell a later difference from a different shape of the
|
|
423
|
+
* same user, and the stream keeps ending on every re-check (logged at debug). Answers whether the stream is re-checked
|
|
424
|
+
* in place now.
|
|
425
|
+
*/
|
|
426
|
+
export async function recheckHttpStreamInPlace(
|
|
427
|
+
connection: undefined | WsConnection,
|
|
428
|
+
options: IHttpStreamRecheckOptions,
|
|
429
|
+
): Promise<boolean> {
|
|
430
|
+
if (!connection?.endsOnRecheck || connection.terminated || typeof options?.reauthenticate !== 'function') {
|
|
431
|
+
return false;
|
|
432
|
+
}
|
|
433
|
+
const keepsEnding = (reason: string): false => {
|
|
434
|
+
logger.debug(`${connection.channel} of user ${connection.userId ?? '(unknown)'} ends on every re-check: ${reason}`);
|
|
435
|
+
return false;
|
|
436
|
+
};
|
|
437
|
+
const tenantHeader = options.tenantHeader ?? connection.tenantHeader;
|
|
438
|
+
let user: any;
|
|
439
|
+
try {
|
|
440
|
+
user = await options.reauthenticate();
|
|
441
|
+
} catch {
|
|
442
|
+
user = undefined;
|
|
443
|
+
}
|
|
444
|
+
if (!user) {
|
|
445
|
+
return keepsEnding('its credential cannot be re-run');
|
|
446
|
+
}
|
|
447
|
+
if (fingerprintUser(user) !== connection.userFingerprint) {
|
|
448
|
+
return keepsEnding('the re-run credential does not answer the authorized user with the same rights');
|
|
449
|
+
}
|
|
450
|
+
if (connection.tenantFingerprint !== undefined) {
|
|
451
|
+
let tenant: ResolvedTenantContext;
|
|
452
|
+
try {
|
|
453
|
+
const resolver = getTenantContextResolver();
|
|
454
|
+
tenant = resolver ? await resolver.resolve(user, tenantHeader) : {};
|
|
455
|
+
} catch {
|
|
456
|
+
return keepsEnding('its tenant scope cannot be resolved again');
|
|
457
|
+
}
|
|
458
|
+
if (fingerprintTenant(tenant) !== connection.tenantFingerprint) {
|
|
459
|
+
return keepsEnding('its tenant scope resolves differently');
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
// An invalidation while the credential ran has ended the stream (it still ended on every re-check): nothing to switch
|
|
463
|
+
if (connection.terminated || connection.stale) {
|
|
464
|
+
return false;
|
|
465
|
+
}
|
|
466
|
+
connection.reauthenticate = options.reauthenticate;
|
|
467
|
+
connection.tenantHeader = tenantHeader;
|
|
468
|
+
connection.validatedAt = Date.now();
|
|
469
|
+
connection.endsOnRecheck = false;
|
|
470
|
+
return true;
|
|
471
|
+
}
|
|
472
|
+
|
|
378
473
|
/** Mark a connection for an immediate re-check and start it. */
|
|
379
474
|
function markStale(connection: WsConnection): void {
|
|
380
475
|
connection.stale = true;
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { hasApiTokenCredential } from '../../modules/api-token/core-api-token.helpers.js';
|
|
2
|
+
import { isLegacyJwt } from '../../modules/better-auth/core-better-auth-token.helper.js';
|
|
3
|
+
import { extractSessionToken, parseCookieHeader } from '../../modules/better-auth/core-better-auth-web.helper.js';
|
|
4
|
+
import { getBetterAuthTokenService } from '../../modules/better-auth/core-better-auth.registry.js';
|
|
5
|
+
import { ConfigService } from '../services/config.service.js';
|
|
6
|
+
import {
|
|
7
|
+
getWsConnection,
|
|
8
|
+
type IWsConnectionSocket,
|
|
9
|
+
noteWsConnectionTenant,
|
|
10
|
+
readWsTenantHeader,
|
|
11
|
+
recheckHttpStreamInPlace,
|
|
12
|
+
registerWsConnection,
|
|
13
|
+
type WsConnection,
|
|
14
|
+
} from './graphql-ws-connection.helper.js';
|
|
15
|
+
|
|
16
|
+
import type { ResolvedTenantContext } from '../services/core-tenant-context.registry.js';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Re-checking an OPEN HTTP stream (Server-Sent Events) against the credential it was opened with (12.11.0).
|
|
20
|
+
*
|
|
21
|
+
* An HTTP stream is authorized once, by the guards of the request that opened it. `registerWsConnection()` with
|
|
22
|
+
* `endsOnRecheck` keeps it inside the user's rights by ending it on every re-check, so the client's reconnect passes
|
|
23
|
+
* the guards again — at the price of a reconnect (an EventSource waits its `retry`, ~3 s) before the event that
|
|
24
|
+
* triggered the re-check reaches it. This file re-runs the request's own credential instead, so the stream can be
|
|
25
|
+
* re-checked in place like a GraphQL WebSocket (`recheckHttpStreamInPlace()`).
|
|
26
|
+
*
|
|
27
|
+
* WHICH CREDENTIALS: the ones `CoreBetterAuthMiddleware` resolves, in its order — the bearer token of the
|
|
28
|
+
* `Authorization` header (a Better-Auth JWT or session token), the `lt-jwt-token` cookie when no header was sent, then
|
|
29
|
+
* the Better-Auth session cookie (`<prefix>.session_token`, signed or not) — each verified and loaded through
|
|
30
|
+
* Better-Auth's token service, the one the IAM role guard uses. A legacy JWT is Passport's and an API token has checks
|
|
31
|
+
* of its own: neither can be re-run here, and such a stream keeps ending on every re-check.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/** The cookie a JWT-mode frontend keeps the Better-Auth JWT in — the one `CoreBetterAuthMiddleware` reads. */
|
|
35
|
+
const JWT_COOKIE_NAME = 'lt-jwt-token';
|
|
36
|
+
|
|
37
|
+
/** What a request carried to authenticate, as it was when the stream was opened. */
|
|
38
|
+
interface HttpStreamCredential {
|
|
39
|
+
authorization?: string;
|
|
40
|
+
cookieHeader?: string;
|
|
41
|
+
cookies?: Record<string, unknown>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function firstHeaderValue(value: unknown): string | undefined {
|
|
45
|
+
const first = Array.isArray(value) ? value[0] : value;
|
|
46
|
+
return typeof first === 'string' && first ? first : undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The Better-Auth base path the session cookie name derives from */
|
|
50
|
+
function betterAuthBasePath(): string {
|
|
51
|
+
const betterAuth = ConfigService.configFastButReadOnly?.betterAuth;
|
|
52
|
+
const basePath = betterAuth && typeof betterAuth === 'object' ? betterAuth.basePath : undefined;
|
|
53
|
+
return typeof basePath === 'string' && basePath ? basePath : '/iam';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The tokens to try, in the order `CoreBetterAuthMiddleware` tries them. Only non-empty strings: a cookie parsed from
|
|
58
|
+
* `j:` JSON is an object and is never handed to a lookup (DEV-4138).
|
|
59
|
+
*/
|
|
60
|
+
function credentialTokens(credential: HttpStreamCredential): string[] {
|
|
61
|
+
const tokens: string[] = [];
|
|
62
|
+
const add = (token: unknown) => {
|
|
63
|
+
if (typeof token === 'string' && token && !tokens.includes(token)) {
|
|
64
|
+
tokens.push(token);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
const isLegacy = (token: string) => token.split('.').length === 3 && isLegacyJwt(token);
|
|
68
|
+
const cookies = credential.cookies ?? parseCookieHeader(credential.cookieHeader);
|
|
69
|
+
if (credential.authorization) {
|
|
70
|
+
const token = credential.authorization.replace(/^bearer\s+/i, '');
|
|
71
|
+
// A legacy JWT is Passport's; the middleware leaves it alone as well
|
|
72
|
+
if (!isLegacy(token)) {
|
|
73
|
+
add(token);
|
|
74
|
+
}
|
|
75
|
+
} else {
|
|
76
|
+
const jwt = cookies?.[JWT_COOKIE_NAME];
|
|
77
|
+
if (typeof jwt === 'string' && jwt.split('.').length === 3 && !isLegacy(jwt)) {
|
|
78
|
+
add(jwt);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
add(
|
|
82
|
+
extractSessionToken(
|
|
83
|
+
{ cookies, headers: { authorization: credential.authorization, cookie: credential.cookieHeader } } as any,
|
|
84
|
+
betterAuthBasePath(),
|
|
85
|
+
{ skipAuthHeader: !!credential.authorization },
|
|
86
|
+
),
|
|
87
|
+
);
|
|
88
|
+
return tokens;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Build the re-authentication of an HTTP stream from the request that opened it: a function that re-runs the
|
|
93
|
+
* request's Better-Auth credential (bearer token, `lt-jwt-token` cookie, session cookie — see the file comment) and
|
|
94
|
+
* resolves to the user it authenticates as NOW, or to `null` when it no longer does (a signed-out or expired session,
|
|
95
|
+
* an expired JWT).
|
|
96
|
+
*
|
|
97
|
+
* The credential is read from the request once, here; the function verifies it again on every call. Answers
|
|
98
|
+
* `undefined` when there is nothing it could re-run: Better-Auth is not active, the request carries an API token, or
|
|
99
|
+
* its only credential is a legacy JWT. Pass the result as `reauthenticate` to `recheckHttpStreamInPlace()`.
|
|
100
|
+
*/
|
|
101
|
+
export function createHttpStreamReauthenticator(request: any): (() => Promise<any>) | undefined {
|
|
102
|
+
if (!request || typeof request !== 'object' || !getBetterAuthTokenService() || hasApiTokenCredential(request)) {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
const credential: HttpStreamCredential = {
|
|
106
|
+
authorization: firstHeaderValue(request.headers?.authorization),
|
|
107
|
+
cookieHeader: firstHeaderValue(request.headers?.cookie),
|
|
108
|
+
cookies: request.cookies && typeof request.cookies === 'object' ? { ...request.cookies } : undefined,
|
|
109
|
+
};
|
|
110
|
+
if (!credentialTokens(credential).length) {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
return async () => {
|
|
114
|
+
// Read at call time: a test module rebuilt in between registers a token service of its own
|
|
115
|
+
const tokenService = getBetterAuthTokenService();
|
|
116
|
+
if (!tokenService) {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
for (const token of credentialTokens(credential)) {
|
|
120
|
+
try {
|
|
121
|
+
const user = await tokenService.verifyAndLoadUser(token);
|
|
122
|
+
if (user) {
|
|
123
|
+
return user;
|
|
124
|
+
}
|
|
125
|
+
} catch {
|
|
126
|
+
// An expired JWT: the middleware goes on to the session cookie, and so does this
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return null;
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** What {@link registerHttpStream} needs to know about a stream. */
|
|
134
|
+
export interface IHttpStreamRegistration {
|
|
135
|
+
/** The object the stream is identified by (`getWsConnection(carrier)`). Default: a new object. */
|
|
136
|
+
carrier?: object;
|
|
137
|
+
|
|
138
|
+
/** How the log names the stream when it is closed, e.g. `SSE hint stream`. Default `HTTP stream`. */
|
|
139
|
+
channel?: string;
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Re-run the credential the stream was opened with. Default: {@link createHttpStreamReauthenticator} of `request`.
|
|
143
|
+
* `false` keeps the stream ending on every re-check (the behaviour before 12.11.0).
|
|
144
|
+
*/
|
|
145
|
+
reauthenticate?: (() => any) | false;
|
|
146
|
+
|
|
147
|
+
/** The HTTP request the stream was opened with: its credential and its tenant header are re-checked. */
|
|
148
|
+
request: any;
|
|
149
|
+
|
|
150
|
+
/** Closes the stream (with the close code as first argument, which a stream ignores) and reports its end. */
|
|
151
|
+
socket: IWsConnectionSocket;
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* The tenant scope the stream's reads are scoped by — what the guards resolved for the request (`RequestContext`:
|
|
155
|
+
* `tenantId`, `tenantIds`, `tenantRole`, `isAdminBypass`). A re-check closes the stream when it resolves
|
|
156
|
+
* differently. Without it the tenant scope is not re-checked.
|
|
157
|
+
*/
|
|
158
|
+
tenant?: ResolvedTenantContext;
|
|
159
|
+
|
|
160
|
+
/** The user the guards authenticated for the request (`@CurrentUser()`). */
|
|
161
|
+
user: any;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Register an HTTP stream (Server-Sent Events) for the authorization lifecycle of `graphql-ws-connection.helper.ts`
|
|
166
|
+
* and let it be re-checked in place when its credential can be re-run (12.11.0).
|
|
167
|
+
*
|
|
168
|
+
* Re-checked in place, the stream stays open while the rights are unchanged — an event after
|
|
169
|
+
* `graphQl.subscriptionRevalidationMs` or after an invalidation is delivered without a reconnect — and is closed when
|
|
170
|
+
* user id, roles, verification or tenant scope changed. A stream whose credential cannot be re-run (see
|
|
171
|
+
* {@link createHttpStreamReauthenticator}) ends on every re-check as before, and the client's reconnect passes the
|
|
172
|
+
* guards again.
|
|
173
|
+
*
|
|
174
|
+
* Call `ensureWsConnectionCurrent(connection)` before every event and send the event only when it answers `true`.
|
|
175
|
+
* Register the stream before anything may end it, and end it through `socket.close()`; report its end through the
|
|
176
|
+
* `close` listener of `socket.once()`.
|
|
177
|
+
*/
|
|
178
|
+
export async function registerHttpStream(registration: IHttpStreamRegistration): Promise<undefined | WsConnection> {
|
|
179
|
+
const { channel, request, socket, tenant, user } = registration;
|
|
180
|
+
const carrier = registration.carrier ?? {};
|
|
181
|
+
registerWsConnection({ carrier, channel: channel || 'HTTP stream', endsOnRecheck: true, socket, user });
|
|
182
|
+
const connection = getWsConnection(carrier);
|
|
183
|
+
if (!connection) {
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
if (tenant) {
|
|
187
|
+
noteWsConnectionTenant(connection, tenant);
|
|
188
|
+
}
|
|
189
|
+
const reauthenticate =
|
|
190
|
+
registration.reauthenticate === false
|
|
191
|
+
? undefined
|
|
192
|
+
: (registration.reauthenticate ?? createHttpStreamReauthenticator(request));
|
|
193
|
+
if (reauthenticate) {
|
|
194
|
+
await recheckHttpStreamInPlace(connection, { reauthenticate, tenantHeader: readWsTenantHeader(request) });
|
|
195
|
+
}
|
|
196
|
+
return connection;
|
|
197
|
+
}
|
|
@@ -29,7 +29,20 @@
|
|
|
29
29
|
* and booleans below such a key stay visible.
|
|
30
30
|
*/
|
|
31
31
|
const SECRET_KEY_PATTERN =
|
|
32
|
-
/secret|passwd|password|passphrase|credential|api[-_]?key|access[-_]?key|private[-_]?key|encryption|token|\bpass\b|pass$|dsn|salt|key$|(^|[^a-z])key([^a-z]|$)/i;
|
|
32
|
+
/secret|passwd|password|passphrase|credential|api[-_]?key|access[-_]?key|private[-_]?key|encryption|token|\bpass\b|pass$|dsn|salt|key$|(^|[^a-z])key([^a-z]|$)|pfx|pkcs12/i;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Value-shape heuristic: a PEM block holding a private key — `-----BEGIN PRIVATE KEY-----` and its `RSA`, `EC`,
|
|
36
|
+
* `ENCRYPTED`, `OPENSSH` variants, and PGP's `-----BEGIN PGP PRIVATE KEY BLOCK-----`. Checked in every string and
|
|
37
|
+
* `Buffer`, whatever its key is called (12.10.1): a certificate login keeps certificate and key in ONE PEM, usually
|
|
38
|
+
* under a name such as `certificate` that no key heuristic may call secret — a certificate alone is public, and an
|
|
39
|
+
* operator needs to see which one is configured. Until 12.10.1 such a key reached `GET /config` and the `warn: true`
|
|
40
|
+
* debug output in clear text. The whole value is masked; the certificate beside the key goes with it.
|
|
41
|
+
*
|
|
42
|
+
* A PKCS#12 container carries no text marker, so it is caught by its NAME (`pfx`, `pkcs12` in
|
|
43
|
+
* {@link SECRET_KEY_PATTERN}).
|
|
44
|
+
*/
|
|
45
|
+
const PRIVATE_KEY_PEM_PATTERN = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY[A-Z ]*-----/i;
|
|
33
46
|
|
|
34
47
|
/**
|
|
35
48
|
* Keys whose value is an address that can carry a secret in its PATH (a Slack or Teams webhook,
|
|
@@ -95,6 +108,7 @@ export const FRAMEWORK_SECRET_FIELDS: readonly string[] = [
|
|
|
95
108
|
* keep flags such as `emailAndPassword.disableSignUp` readable.
|
|
96
109
|
* - A string shaped like a connection URI has the password of its user info masked, and every secret-named query
|
|
97
110
|
* parameter, whatever its key is called.
|
|
111
|
+
* - A string or `Buffer` holding a PEM private key is masked as a whole, whatever its key is called.
|
|
98
112
|
* - `null` and `undefined` pass through; a `Date` or `Buffer` is kept as it is (masked under a secret key).
|
|
99
113
|
*
|
|
100
114
|
* @param value - the object or value to mask (never mutated)
|
|
@@ -154,13 +168,18 @@ function redactValue(value: unknown, underSecretKey: boolean, extra: Set<string>
|
|
|
154
168
|
if (typeof value !== 'string') {
|
|
155
169
|
return value;
|
|
156
170
|
}
|
|
171
|
+
if (PRIVATE_KEY_PEM_PATTERN.test(value)) {
|
|
172
|
+
return REDACTED_VALUE;
|
|
173
|
+
}
|
|
157
174
|
return URL_KEY_PATTERN.test(key) ? redactUrl(value) : redactString(value);
|
|
158
175
|
}
|
|
159
176
|
|
|
160
177
|
// Non-plain objects (Date, Buffer) are kept as they are — cloning would lose their type, and they carry no framework
|
|
161
|
-
// secret — unless they sit below a secret key
|
|
178
|
+
// secret — unless they sit below a secret key or the Buffer holds a PEM private key (`readFileSync('key.pem')`
|
|
179
|
+
// without an encoding, which JSON would print byte by byte)
|
|
162
180
|
if (value instanceof Date || Buffer.isBuffer(value)) {
|
|
163
|
-
|
|
181
|
+
const holdsPrivateKey = Buffer.isBuffer(value) && PRIVATE_KEY_PEM_PATTERN.test(value.toString('latin1'));
|
|
182
|
+
return underSecretKey || holdsPrivateKey ? REDACTED_VALUE : value;
|
|
164
183
|
}
|
|
165
184
|
|
|
166
185
|
if (Array.isArray(value)) {
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether the application has started to shut down (12.11.0) — an import-free leaf, so `installGracefulShutdown()` and
|
|
3
|
+
* the health check's readiness endpoint reach the same state without importing each other.
|
|
4
|
+
*
|
|
5
|
+
* `installGracefulShutdown()` marks it on the first SIGTERM / SIGINT, BEFORE the `shutdownDelayMs` wait. From then on
|
|
6
|
+
* `GET /health-check/ready` answers 503 (`shutting_down`) while the liveness check stays healthy: a load balancer that
|
|
7
|
+
* polls readiness takes the replica out of rotation during the wait, and the process is not restarted. Terminus' own
|
|
8
|
+
* shutdown state comes only inside `app.close()`, right before the HTTP server closes — too late for any poll.
|
|
9
|
+
*
|
|
10
|
+
* Process-wide, like the signals it follows.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
let draining = false;
|
|
14
|
+
|
|
15
|
+
/** Marks the start of the shutdown. */
|
|
16
|
+
export function markShutdownDraining(): void {
|
|
17
|
+
draining = true;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Whether the shutdown has started. */
|
|
21
|
+
export function isShutdownDraining(): boolean {
|
|
22
|
+
return draining;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Resets the state — for tests. */
|
|
26
|
+
export function resetShutdownDraining(): void {
|
|
27
|
+
draining = false;
|
|
28
|
+
}
|
|
@@ -23,5 +23,5 @@ export interface CronJobConfigWithUtcOffset<
|
|
|
23
23
|
* This allows you to specify the offset of the timezone rather than using the `timeZone` parameter.
|
|
24
24
|
* Probably don't use both `timeZone` and `utcOffset` together or weird things may happen.
|
|
25
25
|
*/
|
|
26
|
-
utcOffset?: CronJobParams<OC, C>['
|
|
26
|
+
utcOffset?: CronJobParams<OC, C>['utcOffset'];
|
|
27
27
|
}
|
|
@@ -87,5 +87,5 @@ export interface CronJobConfig<OC extends CronOnCompleteCommand | null = null, C
|
|
|
87
87
|
* This allows you to specify the offset of the timezone rather than using the `timeZone` parameter.
|
|
88
88
|
* Probably don't use both `timeZone` and `utcOffset` together or weird things may happen.
|
|
89
89
|
*/
|
|
90
|
-
utcOffset?:
|
|
90
|
+
utcOffset?: number | null;
|
|
91
91
|
}
|