@lenne.tech/nest-server 12.6.11 → 12.6.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/.claude/rules/package-management.md +7 -7
  2. package/.claude/rules/role-system.md +10 -0
  3. package/.claude/rules/testing.md +4 -4
  4. package/FRAMEWORK-API.md +1 -1
  5. package/dist/core/common/decorators/rest-user.decorator.js +4 -0
  6. package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
  7. package/dist/core/common/filters/http-exception-log.filter.js +4 -0
  8. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  9. package/dist/core/common/helpers/byte-range.helper.d.ts +8 -0
  10. package/dist/core/common/helpers/byte-range.helper.js +71 -0
  11. package/dist/core/common/helpers/byte-range.helper.js.map +1 -0
  12. package/dist/core/common/helpers/context.helper.js +9 -0
  13. package/dist/core/common/helpers/context.helper.js.map +1 -1
  14. package/dist/core/common/helpers/decorator.helper.js +4 -0
  15. package/dist/core/common/helpers/decorator.helper.js.map +1 -1
  16. package/dist/core/common/helpers/execution-context-request.helper.d.ts +9 -1
  17. package/dist/core/common/helpers/execution-context-request.helper.js +29 -0
  18. package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
  19. package/dist/core/common/helpers/graphql-upload.helper.d.ts +10 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js +220 -0
  21. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  22. package/dist/core/common/helpers/gridfs.helper.d.ts +7 -2
  23. package/dist/core/common/helpers/gridfs.helper.js +7 -4
  24. package/dist/core/common/helpers/gridfs.helper.js.map +1 -1
  25. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  26. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  27. package/dist/core/common/services/core-s3.service.d.ts +3 -0
  28. package/dist/core/common/services/core-s3.service.js +8 -1
  29. package/dist/core/common/services/core-s3.service.js.map +1 -1
  30. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  31. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  32. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  33. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  34. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  35. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  36. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  37. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  38. package/dist/core/modules/error-code/error-codes.d.ts +9 -0
  39. package/dist/core/modules/error-code/error-codes.js +8 -0
  40. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  41. package/dist/core/modules/file/core-file.controller.d.ts +5 -0
  42. package/dist/core/modules/file/core-file.controller.js +66 -4
  43. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  44. package/dist/core/modules/file/core-file.service.d.ts +2 -0
  45. package/dist/core/modules/file/core-file.service.js +17 -6
  46. package/dist/core/modules/file/core-file.service.js.map +1 -1
  47. package/dist/core/modules/file/filesystem-file.helper.d.ts +2 -1
  48. package/dist/core/modules/file/filesystem-file.helper.js +2 -2
  49. package/dist/core/modules/file/filesystem-file.helper.js.map +1 -1
  50. package/dist/core/modules/file/interfaces/file-service-options.interface.d.ts +2 -0
  51. package/dist/core/modules/file/s3-file.helper.d.ts +2 -0
  52. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  53. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  54. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  55. package/dist/core.module.js +2 -1
  56. package/dist/core.module.js.map +1 -1
  57. package/dist/index.d.ts +2 -0
  58. package/dist/index.js +2 -0
  59. package/dist/index.js.map +1 -1
  60. package/dist/server/modules/error-code/error-codes.d.ts +1 -0
  61. package/dist/test/test.helper.d.ts +1 -0
  62. package/dist/test/test.helper.js +6 -0
  63. package/dist/test/test.helper.js.map +1 -1
  64. package/dist/types/graphql-upload.d.ts +34 -2
  65. package/docs/REQUEST-LIFECYCLE.md +31 -9
  66. package/docs/error-codes.md +14 -0
  67. package/docs/security-overrides.md +34 -6
  68. package/migration-guides/12.6.11-to-12.6.12.md +180 -0
  69. package/migration-guides/12.6.12-to-12.6.13.md +162 -0
  70. package/package.json +15 -8
  71. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  72. package/src/core/common/filters/http-exception-log.filter.ts +9 -0
  73. package/src/core/common/helpers/byte-range.helper.ts +144 -0
  74. package/src/core/common/helpers/context.helper.ts +14 -0
  75. package/src/core/common/helpers/decorator.helper.ts +5 -0
  76. package/src/core/common/helpers/execution-context-request.helper.ts +78 -1
  77. package/src/core/common/helpers/graphql-upload.helper.ts +482 -0
  78. package/src/core/common/helpers/gridfs.helper.ts +20 -6
  79. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  80. package/src/core/common/services/core-s3.service.ts +16 -2
  81. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  82. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  83. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  84. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  85. package/src/core/modules/error-code/error-codes.ts +13 -0
  86. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +1 -0
  87. package/src/core/modules/file/README.md +74 -1
  88. package/src/core/modules/file/core-file.controller.ts +139 -3
  89. package/src/core/modules/file/core-file.service.ts +33 -13
  90. package/src/core/modules/file/filesystem-file.helper.ts +8 -3
  91. package/src/core/modules/file/interfaces/file-service-options.interface.ts +13 -0
  92. package/src/core/modules/file/s3-file.helper.ts +3 -2
  93. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  94. package/src/core.module.ts +5 -1
  95. package/src/index.ts +2 -0
  96. package/src/test/README.md +8 -4
  97. package/src/test/test.helper.ts +12 -0
  98. package/src/types/graphql-upload.d.ts +34 -2
@@ -0,0 +1,482 @@
1
+ /**
2
+ * GraphQL multipart request processing for `graphqlUploadExpress()`: graphql-upload's `processRequest` with the
3
+ * fixes for GHSA-5vm7-vc2x-p3w2 (high) and GHSA-qwwm-252j-9whw (medium) applied.
4
+ *
5
+ * Source: package `graphql-upload` 17.1.0, file `processRequest.mjs`
6
+ * (https://github.com/jaydenseric/graphql-upload), ported to TypeScript. Upstream fixed both advisories in
7
+ * graphql-upload 18.0.2, which requires graphql 17 — this framework runs graphql 16 (Apollo Server 5,
8
+ * @nestjs/graphql 14), so the fix is carried here instead. Both hunks of the upstream fix are applied unchanged:
9
+ *
10
+ * 1. GHSA-5vm7-vc2x-p3w2: a `map` path with a `__proto__` key, or one that goes through an already placed
11
+ * `Upload`, is refused with the existing 400 "Invalid object path". Without it one anonymous request crashed the
12
+ * process: `{"1":["variables.file"],"2":["variables.file.reject"]}` without file fields replaces the first
13
+ * upload's `reject`, and the parser's `finish` handler throws `TypeError: upload.reject is not a function` outside
14
+ * any request — an uncaught exception, which `installProcessDiagnostics()` (and Node itself) answers with exit 1.
15
+ * `variables.file.__proto__` gave a client-supplied object an `Upload` prototype, so it passed the scalar's
16
+ * `instanceof Upload` check.
17
+ * 2. GHSA-qwwm-252j-9whw: a second file field with the name of an already resolved upload is ignored. Before, each
18
+ * duplicate created a new temporary file whose reference replaced the previous one, so only the last was released
19
+ * when the response closed — temporary files and file descriptors leaked per request (with `maxFiles` > 1; the
20
+ * default is unlimited).
21
+ *
22
+ * One addition of the framework's own, not in graphql-upload (18.0.2 has the same flaw): the `map` is bounded. A path
23
+ * may have at most {@link GRAPHQL_UPLOAD_MAX_PATH_KEYS} keys, and the whole `map` at most
24
+ * {@link GRAPHQL_UPLOAD_MAX_MAP_KEYS} entries and path keys together; over either bound the request is refused with
25
+ * 400. object-path's `set()` recurses once per key and copies the remaining keys each time, so a path of n keys costs
26
+ * O(n²) time and memory, all of it in one synchronous call: measured on Node 24, a single anonymous request with an
27
+ * 80 KB path (40,000 keys) exhausted a 1 GB heap and ended the process; 16 KB (8,000 keys) took 300 MB and blocked the
28
+ * event loop for half a second. Below the per-path bound, 1 MB of paths near it (the default `maxFieldSize`) still
29
+ * blocked the event loop for 150 to 640 ms, and 1 MB of entries without any path (83,000 `Upload`s, each rejected with
30
+ * an error of its own when its file never arrives) for 410 ms with 230 MB. With the map bound such requests are
31
+ * refused within about 30 ms, most of it spent parsing the field's JSON.
32
+ *
33
+ * `CoreModule` passes this function to `graphqlUploadExpress({ processRequest })`. A project that registers
34
+ * `graphqlUploadExpress()` itself must pass it too — graphql-upload's own default is the unpatched function.
35
+ *
36
+ * `Upload` comes from graphql-upload's own `Upload.mjs`, the class the `GraphQLUpload` scalar checks with
37
+ * `instanceof`: an `Upload` of any other class would be refused as an invalid upload. `ignoreStream` is not exported
38
+ * by graphql-upload and is re-implemented below.
39
+ *
40
+ * ---------------------------------------------------------------------------------------------------------------
41
+ * MIT License
42
+ *
43
+ * Copyright Jayden Seric
44
+ *
45
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
46
+ * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
47
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
48
+ * permit persons to whom the Software is furnished to do so, subject to the following conditions:
49
+ *
50
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of
51
+ * the Software.
52
+ *
53
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
54
+ * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
56
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
57
+ * SOFTWARE.
58
+ * ---------------------------------------------------------------------------------------------------------------
59
+ */
60
+ import busboy from 'busboy';
61
+ import { WriteStream } from 'fs-capacitor';
62
+ import Upload from 'graphql-upload/Upload.mjs';
63
+ import createError from 'http-errors';
64
+ import objectPath from 'object-path';
65
+
66
+ import type { IncomingMessage, ServerResponse } from 'node:http';
67
+ import type { Readable } from 'node:stream';
68
+
69
+ /** graphql-upload's `GRAPHQL_MULTIPART_REQUEST_SPEC_URL`, used in the error messages exactly as upstream does. */
70
+ const GRAPHQL_MULTIPART_REQUEST_SPEC_URL = 'https://github.com/jaydenseric/graphql-multipart-request-spec';
71
+
72
+ /**
73
+ * Most keys one `map` path may have (`variables.input.files.3` has 4). A longer path is refused with 400 "Invalid
74
+ * object path" before anything walks it: object-path's `set()` costs O(n²) in the number of keys. No request a client
75
+ * library builds comes near it — batched operations add one key (`0.variables.file`).
76
+ */
77
+ export const GRAPHQL_UPLOAD_MAX_PATH_KEYS = 64;
78
+
79
+ /**
80
+ * Most entries and path keys one `map` may name together: every entry counts one, every key of its paths one more, so
81
+ * `{"1":["variables.file"]}` counts 3, and 2,000 files at `variables.input.files.N` count 10,000. An entry over it is
82
+ * refused before its `Upload` exists, with 400 "Invalid ‘map’ multipart field entry key …"; a path over it with 400
83
+ * "Invalid object path". It bounds the work of a `map` of many paths that each stay under
84
+ * {@link GRAPHQL_UPLOAD_MAX_PATH_KEYS} (1 MB of them blocked the event loop for up to 640 ms) and of a `map` of many
85
+ * entries, each of which becomes an `Upload` that the parser rejects with an error of its own when its file never
86
+ * arrives (1 MB of entries without a path, 83,000 of them, took 230 MB and blocked the event loop for 410 ms).
87
+ */
88
+ export const GRAPHQL_UPLOAD_MAX_MAP_KEYS = 10_000;
89
+
90
+ /**
91
+ * Options of {@link processGraphQlUploadRequest} — the same as graphql-upload's `ProcessRequestOptions`, so
92
+ * `graphqlUploadExpress({ processRequest, ...options })` forwards them unchanged.
93
+ */
94
+ export interface GraphQlUploadProcessRequestOptions {
95
+ /** Maximum size of a non-file multipart field (`operations`, `map`) in bytes. Defaults to `1000000` (1 MB). */
96
+ maxFieldSize?: number;
97
+ /** Maximum size of one file in bytes. Defaults to `Infinity`. */
98
+ maxFileSize?: number;
99
+ /** Maximum number of files. Defaults to `Infinity`. */
100
+ maxFiles?: number;
101
+ }
102
+
103
+ /** The GraphQL operation (or batch of operations) a multipart request resolves to, with `Upload` instances placed. */
104
+ export type GraphQlUploadOperations = Array<Record<string, unknown>> | Record<string, unknown>;
105
+
106
+ /** File details an `Upload` resolves with (graphql-upload's `FileUpload`). */
107
+ interface ProcessedFileUpload {
108
+ capacitor: WriteStream;
109
+ createReadStream: (options?: { encoding?: BufferEncoding; highWaterMark?: number }) => Readable;
110
+ encoding: string;
111
+ filename: string;
112
+ mimetype: string;
113
+ }
114
+
115
+ /** An error created with `http-errors` (or any other error the parser reports). */
116
+ type ProcessRequestError = Error & { expose?: boolean; status?: number };
117
+
118
+ /**
119
+ * Safely ignores a readable stream (graphql-upload's `ignoreStream`, which the package does not export): an error
120
+ * on it must not crash the process, and its data is drained so the parser can go on.
121
+ */
122
+ function ignoreStream(stream: Readable): void {
123
+ // Prevent an unhandled error from crashing the process.
124
+ stream.on('error', () => {});
125
+
126
+ // Waste the stream.
127
+ stream.resume();
128
+ }
129
+
130
+ /**
131
+ * Processes an incoming GraphQL multipart request
132
+ * (https://github.com/jaydenseric/graphql-multipart-request-spec): parses the `operations` and `map` fields, places
133
+ * an `Upload` wherever the `map` names one and resolves each with its file once that file streams in.
134
+ *
135
+ * graphql-upload 17.1.0's `processRequest` with the fixes of graphql-upload 18.0.2 (see the file header). Pass it to
136
+ * `graphqlUploadExpress({ processRequest: processGraphQlUploadRequest })`; `CoreModule` does so for `/graphql`.
137
+ *
138
+ * @returns The operation(s), with an `Upload` at every mapped path — resolved once the `map` is parsed. Rejects with
139
+ * an `http-errors` error (400 for a malformed request, 413 above a limit, 499 on a disconnect).
140
+ */
141
+ export function processGraphQlUploadRequest(
142
+ request: IncomingMessage,
143
+ response: ServerResponse,
144
+ { maxFieldSize = 1000000, maxFileSize = Infinity, maxFiles = Infinity }: GraphQlUploadProcessRequestOptions = {},
145
+ ): Promise<GraphQlUploadOperations> {
146
+ return new Promise((resolve, reject) => {
147
+ let released: boolean;
148
+ let exitError: ProcessRequestError;
149
+ let operations: GraphQlUploadOperations;
150
+ let operationsPath: ReturnType<typeof objectPath>;
151
+ let map: Map<string, Upload>;
152
+
153
+ const parser = busboy({
154
+ headers: request.headers,
155
+ defParamCharset: 'utf8',
156
+ limits: {
157
+ fieldSize: maxFieldSize,
158
+ fields: 2, // Only operations and map.
159
+ fileSize: maxFileSize,
160
+ files: maxFiles,
161
+ },
162
+ });
163
+
164
+ /**
165
+ * Exits request processing with an error. Successive calls have no effect.
166
+ */
167
+ function exit(error: ProcessRequestError, isParserError = false): void {
168
+ if (exitError) {
169
+ return;
170
+ }
171
+
172
+ exitError = error;
173
+
174
+ if (map) {
175
+ for (const upload of map.values()) {
176
+ if (!upload.file) {
177
+ upload.reject(exitError);
178
+ }
179
+ }
180
+ }
181
+
182
+ // If the error came from the parser, don't cause it to be emitted again.
183
+ if (isParserError) {
184
+ parser.destroy();
185
+ } else {
186
+ parser.destroy(exitError);
187
+ }
188
+
189
+ request.unpipe(parser);
190
+
191
+ // With a sufficiently large request body, subsequent events in the same event frame cause the stream to pause
192
+ // after the parser is destroyed. To ensure that the request resumes, the call to .resume() is scheduled for
193
+ // later in the event loop.
194
+ setImmediate(() => {
195
+ request.resume();
196
+ });
197
+
198
+ reject(exitError);
199
+ }
200
+
201
+ parser.on('field', (fieldName: string, value: string, { valueTruncated }: { valueTruncated: boolean }) => {
202
+ if (valueTruncated) {
203
+ return exit(
204
+ createError(413, `The ‘${fieldName}’ multipart field value exceeds the ${maxFieldSize} byte size limit.`),
205
+ );
206
+ }
207
+
208
+ switch (fieldName) {
209
+ case 'operations':
210
+ try {
211
+ operations = JSON.parse(value);
212
+ } catch {
213
+ return exit(
214
+ createError(
215
+ 400,
216
+ `Invalid JSON in the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
217
+ ),
218
+ );
219
+ }
220
+
221
+ // `operations` should be an object or an array. Note that arrays and `null` have an `object` type.
222
+ if (typeof operations !== 'object' || !operations) {
223
+ return exit(
224
+ createError(
225
+ 400,
226
+ `Invalid type for the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
227
+ ),
228
+ );
229
+ }
230
+
231
+ operationsPath = objectPath(operations);
232
+
233
+ break;
234
+ case 'map': {
235
+ if (!operations) {
236
+ return exit(
237
+ createError(
238
+ 400,
239
+ `Misordered multipart fields; ‘map’ should follow ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
240
+ ),
241
+ );
242
+ }
243
+
244
+ let parsedMap: unknown;
245
+ try {
246
+ parsedMap = JSON.parse(value);
247
+ } catch {
248
+ return exit(
249
+ createError(400, `Invalid JSON in the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`),
250
+ );
251
+ }
252
+
253
+ // `map` should be an object.
254
+ if (typeof parsedMap !== 'object' || !parsedMap || Array.isArray(parsedMap)) {
255
+ return exit(
256
+ createError(400, `Invalid type for the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`),
257
+ );
258
+ }
259
+
260
+ const mapEntries = Object.entries(parsedMap);
261
+
262
+ // Check max files is not exceeded, even though the number of files to parse might not match the map
263
+ // provided by the client.
264
+ if (mapEntries.length > maxFiles) {
265
+ return exit(createError(413, `${maxFiles} max file uploads exceeded.`));
266
+ }
267
+
268
+ map = new Map();
269
+ // Map entries and path keys so far, against GRAPHQL_UPLOAD_MAX_MAP_KEYS.
270
+ let mapKeyCount = 0;
271
+ for (const [mapFieldName, paths] of mapEntries) {
272
+ if (!Array.isArray(paths)) {
273
+ return exit(
274
+ createError(
275
+ 400,
276
+ `Invalid type for the ‘map’ multipart field entry key ‘${mapFieldName}’ array (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
277
+ ),
278
+ );
279
+ }
280
+
281
+ // Every entry counts one against GRAPHQL_UPLOAD_MAX_MAP_KEYS, before its Upload exists: an Upload whose
282
+ // file never arrives is rejected with an error of its own at the end of the request.
283
+ mapKeyCount += 1;
284
+ if (mapKeyCount > GRAPHQL_UPLOAD_MAX_MAP_KEYS) {
285
+ return exit(
286
+ createError(
287
+ 400,
288
+ `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}).`,
289
+ ),
290
+ );
291
+ }
292
+
293
+ map.set(mapFieldName, new Upload());
294
+
295
+ for (const [index, path] of paths.entries()) {
296
+ if (typeof path !== 'string') {
297
+ return exit(
298
+ createError(
299
+ 400,
300
+ `Invalid type for the ‘map’ multipart field entry key ‘${mapFieldName}’ array index ‘${index}’ value (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
301
+ ),
302
+ );
303
+ }
304
+
305
+ try {
306
+ // GHSA-5vm7-vc2x-p3w2 (graphql-upload 18.0.2): check the upload's mapped path in the operations is
307
+ // safe before setting it.
308
+ const keys = path.split('.');
309
+
310
+ // Bound the path, and the whole map, before anything walks it: object-path's `set()` recurses once per
311
+ // key with a copy of the remaining keys — O(n²) for a path of n keys (see the file header).
312
+ if (keys.length > GRAPHQL_UPLOAD_MAX_PATH_KEYS) {
313
+ throw new RangeError(`Object path has more than ${GRAPHQL_UPLOAD_MAX_PATH_KEYS} keys.`);
314
+ }
315
+ mapKeyCount += keys.length;
316
+ if (mapKeyCount > GRAPHQL_UPLOAD_MAX_MAP_KEYS) {
317
+ throw new RangeError(
318
+ `The map has more than ${GRAPHQL_UPLOAD_MAX_MAP_KEYS} entries and object path keys.`,
319
+ );
320
+ }
321
+
322
+ let pathValue: unknown = operations;
323
+
324
+ for (const [keyIndex, key] of keys.entries()) {
325
+ // Forbid `__proto__` keys to prevent prototype manipulation that could make client-supplied
326
+ // objects pass `instanceof Upload` checks.
327
+ if (key === '__proto__') {
328
+ throw new TypeError('Object path has a `__proto__` key.');
329
+ }
330
+
331
+ // Forbid setting an upload within an already set upload, but allow a total replacement. Resolved
332
+ // with object-path's own `get`, so it sees what `set` will reach, inherited array elements included.
333
+ if (keyIndex < keys.length - 1) {
334
+ pathValue = objectPath.get(pathValue as object, [key]);
335
+
336
+ if (pathValue instanceof Upload) {
337
+ throw new TypeError('Object path traverses an upload.');
338
+ }
339
+ }
340
+ }
341
+
342
+ operationsPath.set(path, map.get(mapFieldName));
343
+ } catch {
344
+ return exit(
345
+ createError(
346
+ 400,
347
+ `Invalid object path for the ‘map’ multipart field entry key ‘${mapFieldName}’ array index ‘${index}’ value ‘${path}’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
348
+ ),
349
+ );
350
+ }
351
+ }
352
+ }
353
+
354
+ resolve(operations);
355
+ }
356
+ }
357
+ });
358
+
359
+ parser.on(
360
+ 'file',
361
+ (
362
+ fieldName: string,
363
+ stream: Readable,
364
+ { encoding, filename, mimeType: mimetype }: { encoding: string; filename: string; mimeType: string },
365
+ ) => {
366
+ if (!map) {
367
+ ignoreStream(stream);
368
+ return exit(
369
+ createError(
370
+ 400,
371
+ `Misordered multipart fields; files should follow ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
372
+ ),
373
+ );
374
+ }
375
+
376
+ const upload = map.get(fieldName);
377
+
378
+ // GHSA-qwwm-252j-9whw (graphql-upload 18.0.2): `|| upload.file` — a duplicate file field would create a new
379
+ // capacitor and replace the reference to the first one, which then never gets released.
380
+ if (!upload || upload.file) {
381
+ // The file is extraneous or a duplicate. As the rest can still be processed, just ignore it and don't
382
+ // exit with an error.
383
+ ignoreStream(stream);
384
+ return;
385
+ }
386
+
387
+ let fileError: ProcessRequestError;
388
+
389
+ const capacitor = new WriteStream();
390
+
391
+ capacitor.on('error', () => {
392
+ stream.unpipe();
393
+ stream.resume();
394
+ });
395
+
396
+ stream.on('limit', () => {
397
+ fileError = createError(413, `File truncated as it exceeds the ${maxFileSize} byte size limit.`);
398
+ stream.unpipe();
399
+ capacitor.destroy(fileError);
400
+ });
401
+
402
+ stream.on('error', (error: Error) => {
403
+ fileError = error;
404
+ stream.unpipe();
405
+ capacitor.destroy(fileError);
406
+ });
407
+
408
+ const file: ProcessedFileUpload = {
409
+ filename,
410
+ mimetype,
411
+ encoding,
412
+ createReadStream(options) {
413
+ const error = fileError || (released ? exitError : null);
414
+ if (error) {
415
+ throw error;
416
+ }
417
+ return capacitor.createReadStream(options);
418
+ },
419
+ capacitor,
420
+ };
421
+
422
+ Object.defineProperty(file, 'capacitor', {
423
+ enumerable: false,
424
+ configurable: false,
425
+ writable: false,
426
+ });
427
+
428
+ stream.pipe(capacitor);
429
+ upload.resolve(file);
430
+ },
431
+ );
432
+
433
+ parser.once('filesLimit', () => exit(createError(413, `${maxFiles} max file uploads exceeded.`)));
434
+
435
+ parser.once('finish', () => {
436
+ request.unpipe(parser);
437
+ request.resume();
438
+
439
+ if (!operations) {
440
+ return exit(createError(400, `Missing multipart field ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`));
441
+ }
442
+
443
+ if (!map) {
444
+ return exit(createError(400, `Missing multipart field ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`));
445
+ }
446
+
447
+ for (const upload of map.values()) {
448
+ if (!upload.file) {
449
+ upload.reject(createError(400, 'File missing in the request.'));
450
+ }
451
+ }
452
+ });
453
+
454
+ // Use the `on` method instead of `once` as in edge cases the same parser could have multiple `error` events and
455
+ // all must be handled to prevent the Node.js process exiting with an error. One edge case is if there is a
456
+ // malformed part header as well as an unexpected end of the form.
457
+ parser.on('error', (error: Error) => {
458
+ exit(error, true);
459
+ });
460
+
461
+ response.once('close', () => {
462
+ released = true;
463
+
464
+ if (map) {
465
+ for (const upload of map.values()) {
466
+ if (upload.file) {
467
+ // Release resources and clean up temporary files.
468
+ (upload.file as ProcessedFileUpload).capacitor.release();
469
+ }
470
+ }
471
+ }
472
+ });
473
+
474
+ request.once('close', () => {
475
+ if (!request.readableEnded) {
476
+ exit(createError(499, 'Request disconnected during file upload stream parsing.'));
477
+ }
478
+ });
479
+
480
+ request.pipe(parser);
481
+ });
482
+ }
@@ -1,6 +1,7 @@
1
1
  import type { mongo, Types } from 'mongoose';
2
2
  import { Readable } from 'stream';
3
3
  import { newObjectId } from '../persistence/mongo/mongoose-compat.js';
4
+ import type { ByteRange } from './byte-range.helper.js';
4
5
 
5
6
  // Use Mongoose's MongoDB types to avoid BSON version conflicts
6
7
 
@@ -298,18 +299,31 @@ export class GridFSHelper {
298
299
  }
299
300
 
300
301
  /**
301
- * Open download stream by ID
302
+ * Open download stream by ID — with `range`, only those bytes (both inclusive). The range must lie inside the
303
+ * file: GridFS refuses a start or end past its length with an error on the stream.
302
304
  */
303
- static openDownloadStream(bucket: GridFSBucket, id: string | Types.ObjectId): GridFSBucketReadStream {
305
+ static openDownloadStream(
306
+ bucket: GridFSBucket,
307
+ id: string | Types.ObjectId,
308
+ range?: ByteRange,
309
+ ): GridFSBucketReadStream {
304
310
  const objectId = typeof id === 'string' ? newObjectId(id) : id;
305
- return bucket.openDownloadStream(objectId);
311
+ return bucket.openDownloadStream(objectId, GridFSHelper.streamRange(range));
312
+ }
313
+
314
+ /**
315
+ * Open download stream by name — with `range`, only those bytes (both inclusive)
316
+ */
317
+ static openDownloadStreamByName(bucket: GridFSBucket, filename: string, range?: ByteRange): GridFSBucketReadStream {
318
+ return bucket.openDownloadStreamByName(filename, GridFSHelper.streamRange(range));
306
319
  }
307
320
 
308
321
  /**
309
- * Open download stream by name
322
+ * The GridFS stream options of a range. GridFS counts `end` EXCLUSIVE (the byte after the last one), HTTP and
323
+ * `ByteRange` count it inclusive — hence the `+ 1`.
310
324
  */
311
- static openDownloadStreamByName(bucket: GridFSBucket, filename: string): GridFSBucketReadStream {
312
- return bucket.openDownloadStreamByName(filename);
325
+ static streamRange(range?: ByteRange): undefined | { end: number; start: number } {
326
+ return range ? { end: range.end + 1, start: range.start } : undefined;
313
327
  }
314
328
 
315
329
  /**
@@ -4,6 +4,7 @@ import { Observable } from 'rxjs';
4
4
  import { map } from 'rxjs/operators';
5
5
 
6
6
  import { applyTranslationsRecursively } from '../helpers/service.helper.js';
7
+ import { isAgentCallContext } from '../helpers/execution-context-request.helper.js';
7
8
 
8
9
  /**
9
10
  * Interceptor that automatically applies translations from _translations
@@ -82,6 +83,13 @@ export class TranslateResponseInterceptor implements NestInterceptor {
82
83
  }
83
84
 
84
85
  private getLanguage(context: ExecutionContext): string | null {
86
+ // An agent function / MCP call (nestjs-ai plan §1): this interceptor shapes HTTP and GraphQL responses for a
87
+ // reader's language; a model reads the result as it is. Without this the HTTP fallback below read
88
+ // `accept-language` from the call's ARGUMENTS.
89
+ if (isAgentCallContext(context)) {
90
+ return null;
91
+ }
92
+
85
93
  // GraphQL context
86
94
  try {
87
95
  if (context.getType<GqlContextType>() === 'graphql') {
@@ -4,6 +4,7 @@ import { Agent as HttpsAgent } from 'https';
4
4
  import { PassThrough } from 'stream';
5
5
 
6
6
  import { buildContentDisposition } from '../helpers/content-disposition.helper.js';
7
+ import { assertByteRange, type ByteRange } from '../helpers/byte-range.helper.js';
7
8
  import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, guardIdleStream, MAX_TIMER_DELAY_MS } from '../helpers/idle-stream.helper.js';
8
9
  import { ConfigService } from './config.service.js';
9
10
 
@@ -701,6 +702,11 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
701
702
  /**
702
703
  * Get an object stream (plus metadata) from the main bucket.
703
704
  * Throws the SDK's NoSuchKey error when the object does not exist.
705
+ *
706
+ * With `range`, only those bytes are read (`Range: bytes=<start>-<end>`, end inclusive): `contentLength` is then
707
+ * the length of the range and `contentRange` S3's `bytes <start>-<end>/<total>`. The range must lie inside the
708
+ * object — a range starting past its end is refused by S3 with `InvalidRange`; `resolveDownloadRange()` produces a
709
+ * valid one from a request's `Range` header. A malformed range throws a `RangeError` before S3 is asked.
704
710
  */
705
711
  async getObject(
706
712
  key: string,
@@ -712,14 +718,21 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
712
718
  * its turn comes) AND is certain to read it to the end or destroy it; such a body holds its socket until then.
713
719
  */
714
720
  idleTimeoutMs?: false | number;
721
+ /** Read only these bytes (both inclusive). Since 12.6.12. */
722
+ range?: ByteRange;
715
723
  },
716
- ): Promise<{ body: Readable; contentLength?: number; contentType?: string }> {
724
+ ): Promise<{ body: Readable; contentLength?: number; contentRange?: string; contentType?: string }> {
717
725
  const { client, config, sdk } = this.requireInit();
726
+ const range = assertByteRange(options?.range);
718
727
  // `abortSignal`: a caller whose client has gone aborts the request, also while it still waits for a socket —
719
728
  // otherwise it stays queued and takes a socket and a body later, for nobody (see `IS3Config.maxSockets`)
720
729
  const idleMs = options?.idleTimeoutMs;
721
730
  const result = await client.send(
722
- new sdk.GetObjectCommand({ Bucket: config.bucket, Key: key }),
731
+ new sdk.GetObjectCommand({
732
+ Bucket: config.bucket,
733
+ Key: key,
734
+ ...(range ? { Range: `bytes=${range.start}-${range.end}` } : {}),
735
+ }),
723
736
  options?.abortSignal ? { abortSignal: options.abortSignal } : undefined,
724
737
  );
725
738
  return {
@@ -734,6 +747,7 @@ export class CoreS3Service implements OnApplicationShutdown, OnModuleInit {
734
747
  },
735
748
  }),
736
749
  contentLength: result.ContentLength,
750
+ ...(result.ContentRange ? { contentRange: result.ContentRange } : {}),
737
751
  contentType: result.ContentType,
738
752
  };
739
753
  }
@@ -1,13 +1,18 @@
1
- import { CanActivate, ExecutionContext, Logger, mixin, Optional } from '@nestjs/common';
1
+ import { CanActivate, ExecutionContext, Logger, mixin, Optional, UnauthorizedException } from '@nestjs/common';
2
2
  import { ModuleRef } from '@nestjs/core';
3
3
  import { GqlExecutionContext } from '@nestjs/graphql';
4
4
  import { AuthModuleOptions, Type } from '@nestjs/passport';
5
5
  import passport from 'passport';
6
6
 
7
+ import {
8
+ isAgentCallContext,
9
+ resolveAgentCallRequest,
10
+ } from '../../../common/helpers/execution-context-request.helper.js';
7
11
  import { enforceApiTokenRoute, getApiTokenContext } from '../../api-token/core-api-token.helpers.js';
8
12
  import { BetterAuthTokenService } from '../../better-auth/better-auth-token.service.js';
9
13
  import { BetterAuthenticatedUser } from '../../better-auth/better-auth.types.js';
10
14
  import { CoreBetterAuthService } from '../../better-auth/core-better-auth.service.js';
15
+ import { ErrorCode } from '../../error-code/index.js';
11
16
  import { AuthGuardStrategy } from '../auth-guard-strategy.enum.js';
12
17
  import { ExpiredRefreshTokenException } from '../exceptions/expired-refresh-token.exception.js';
13
18
  import { ExpiredTokenException } from '../exceptions/expired-token.exception.js';
@@ -165,6 +170,11 @@ function createAuthGuard(type?: AuthGuardStrategy | string | string[]): Type<IAu
165
170
 
166
171
  const options = { ...defaultOptions, ...this.options };
167
172
  const request = this.getRequest(context);
173
+ // An agent function / MCP call without a request is anonymous (nestjs-ai plan §1): this guard authenticates, so
174
+ // it refuses — Passport would otherwise be handed nothing, or the call's arguments.
175
+ if (!request && isAgentCallContext(context)) {
176
+ throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
177
+ }
168
178
  const existingUser = request?.[options.property || defaultOptions.property];
169
179
 
170
180
  // An API token was already authenticated by CoreApiTokenMiddleware. Neither Passport nor
@@ -195,7 +205,9 @@ function createAuthGuard(type?: AuthGuardStrategy | string | string[]): Type<IAu
195
205
  }
196
206
 
197
207
  // Proceed with Passport authentication for other strategies
198
- const response = context?.switchToHttp()?.getResponse();
208
+ // On an agent / MCP call the second argument is the call, not a response: Passport gets the request's own
209
+ // response object (Express sets `req.res`).
210
+ const response = isAgentCallContext(context) ? request?.res : context?.switchToHttp()?.getResponse();
199
211
  const passportFn = createPassportContext(request, response);
200
212
  const user = await passportFn(
201
213
  type || this.options?.defaultStrategy,
@@ -270,6 +282,11 @@ function createAuthGuard(type?: AuthGuardStrategy | string | string[]): Type<IAu
270
282
  * Prepare request
271
283
  */
272
284
  getRequest<T = any>(context: ExecutionContext): T {
285
+ // An agent function / MCP call: the request it runs in, never its arguments (nestjs-ai plan §1)
286
+ if (isAgentCallContext(context)) {
287
+ return (resolveAgentCallRequest(context) ?? null) as T;
288
+ }
289
+
273
290
  // Try to get request GraphQL context
274
291
  try {
275
292
  const ctx = GqlExecutionContext.create(context)?.getContext();
@@ -2,6 +2,10 @@ import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable }
2
2
  import { GqlExecutionContext } from '@nestjs/graphql';
3
3
 
4
4
  import { LegacyAuthRateLimiter } from '../services/legacy-auth-rate-limiter.service.js';
5
+ import {
6
+ isAgentCallContext,
7
+ resolveAgentCallRequest,
8
+ } from '../../../common/helpers/execution-context-request.helper.js';
5
9
 
6
10
  /**
7
11
  * Guard for rate limiting Legacy Auth endpoints
@@ -72,8 +76,11 @@ export class LegacyAuthRateLimitGuard implements CanActivate {
72
76
  return { endpoint, ip };
73
77
  }
74
78
 
75
- // HTTP context
76
- const request = context.switchToHttp().getRequest();
79
+ // HTTP context — or an agent function / MCP call, whose request is the one it runs in, never its arguments
80
+ // (nestjs-ai plan §1)
81
+ const request = isAgentCallContext(context)
82
+ ? resolveAgentCallRequest(context)
83
+ : context.switchToHttp().getRequest();
77
84
  const ip = this.getClientIp(request);
78
85
 
79
86
  // The handler, never the URL: the URL carries the query string and the client's spelling of the path