@lenne.tech/nest-server 12.6.12 → 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.
- package/.claude/rules/package-management.md +7 -7
- package/.claude/rules/role-system.md +10 -0
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/decorators/rest-user.decorator.js +4 -0
- package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
- package/dist/core/common/filters/http-exception-log.filter.js +4 -0
- package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
- package/dist/core/common/helpers/context.helper.js +9 -0
- package/dist/core/common/helpers/context.helper.js.map +1 -1
- package/dist/core/common/helpers/decorator.helper.js +4 -0
- package/dist/core/common/helpers/decorator.helper.js.map +1 -1
- package/dist/core/common/helpers/execution-context-request.helper.d.ts +9 -1
- package/dist/core/common/helpers/execution-context-request.helper.js +29 -0
- package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +10 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +220 -0
- package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
- package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
- package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
- package/dist/core/modules/auth/guards/auth.guard.js +10 -2
- package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/roles.guard.js +11 -1
- package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
- package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
- package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
- package/dist/core.module.js +2 -1
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/types/graphql-upload.d.ts +34 -2
- package/docs/REQUEST-LIFECYCLE.md +30 -8
- package/docs/security-overrides.md +3 -2
- package/migration-guides/12.6.12-to-12.6.13.md +162 -0
- package/package.json +10 -3
- package/src/core/common/decorators/rest-user.decorator.ts +6 -0
- package/src/core/common/filters/http-exception-log.filter.ts +9 -0
- package/src/core/common/helpers/context.helper.ts +14 -0
- package/src/core/common/helpers/decorator.helper.ts +5 -0
- package/src/core/common/helpers/execution-context-request.helper.ts +78 -1
- package/src/core/common/helpers/graphql-upload.helper.ts +482 -0
- package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
- package/src/core/modules/auth/guards/auth.guard.ts +19 -2
- package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
- package/src/core/modules/auth/guards/roles.guard.ts +23 -1
- package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
- package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
- package/src/core.module.ts +5 -1
- package/src/index.ts +1 -0
- 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
|
+
}
|
|
@@ -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') {
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
@@ -10,7 +10,11 @@ import {
|
|
|
10
10
|
import { ModuleRef, Reflector } from '@nestjs/core';
|
|
11
11
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
12
12
|
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
isAgentCallContext,
|
|
15
|
+
resolveAgentCallRequest,
|
|
16
|
+
resolveGuardRequest,
|
|
17
|
+
} from '../../../common/helpers/execution-context-request.helper.js';
|
|
14
18
|
import { firstValueFrom, isObservable } from 'rxjs';
|
|
15
19
|
|
|
16
20
|
import { RoleEnum } from '../../../common/enums/role.enum.js';
|
|
@@ -147,6 +151,19 @@ export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
|
|
|
147
151
|
throw new ForbiddenException(ErrorCode.ACCESS_DENIED);
|
|
148
152
|
}
|
|
149
153
|
|
|
154
|
+
// An agent function / MCP tool call without a request (`@nestjs/ai`'s `caller: { user }`, a durable run, MCP over
|
|
155
|
+
// stdio) is ANONYMOUS: nothing authenticated `caller.user`, and the call's arguments are the model's. Open only
|
|
156
|
+
// where the route is public. Kept in sync with BetterAuthRolesGuard (nestjs-ai plan §1).
|
|
157
|
+
if (isAgentCallContext(context) && !this.getRequest(context)) {
|
|
158
|
+
// The method's own roles win over the class's, as CoreTenantGuard decides system roles: a class-level
|
|
159
|
+
// S_EVERYONE does not open a method that asks for S_USER
|
|
160
|
+
const effective = reflectorRoles?.[0]?.some((value) => !!value) ? reflectorRoles[0] : roles;
|
|
161
|
+
if (!effective || !effective.some((value) => !!value) || effective.includes(RoleEnum.S_EVERYONE)) {
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
165
|
+
}
|
|
166
|
+
|
|
150
167
|
// API tokens are decided BEFORE the public-route shortcut below: a token is denied on every route
|
|
151
168
|
// that does not declare @ApiTokenScopes(), public ones included (see core-api-token.helpers).
|
|
152
169
|
// A tenant token is fully decided there. A user token was authenticated by CoreApiTokenMiddleware,
|
|
@@ -289,6 +306,11 @@ export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
|
|
|
289
306
|
cookies?: Record<string, string>;
|
|
290
307
|
headers?: Record<string, string | string[] | undefined>;
|
|
291
308
|
} {
|
|
309
|
+
// An agent function / MCP call: the request it runs in, never its arguments (nestjs-ai plan §1)
|
|
310
|
+
if (isAgentCallContext(context)) {
|
|
311
|
+
return resolveAgentCallRequest(context) ?? null;
|
|
312
|
+
}
|
|
313
|
+
|
|
292
314
|
// Try GraphQL context first
|
|
293
315
|
try {
|
|
294
316
|
const gqlContext = GqlExecutionContext.create(context);
|
|
@@ -8,7 +8,11 @@ import {
|
|
|
8
8
|
} from '@nestjs/common';
|
|
9
9
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
10
10
|
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
agentCallOf,
|
|
13
|
+
isAgentCallContext,
|
|
14
|
+
resolveGuardRequest,
|
|
15
|
+
} from '../../common/helpers/execution-context-request.helper.js';
|
|
12
16
|
|
|
13
17
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
14
18
|
import { ApiTokenKind } from '../api-token/core-api-token.constants.js';
|
|
@@ -103,6 +107,20 @@ export class BetterAuthRolesGuard implements CanActivate {
|
|
|
103
107
|
// that does not declare @ApiTokenScopes(), public ones included. A tenant token is fully decided
|
|
104
108
|
// there; a user token continues through the ordinary checks as its user (see core-api-token.helpers).
|
|
105
109
|
const request = this.getRequest(context);
|
|
110
|
+
|
|
111
|
+
// An agent function / MCP tool call without a request (`@nestjs/ai`'s `caller: { user }`, a durable run, MCP over
|
|
112
|
+
// stdio) is ANONYMOUS: nothing authenticated `caller.user`, and the call's arguments are the model's. Open only
|
|
113
|
+
// where the route is public. Kept in sync with RolesGuard (nestjs-ai plan §1).
|
|
114
|
+
if (isAgentCallContext(context) && !request) {
|
|
115
|
+
// The method's own roles win over the class's, as CoreTenantGuard decides system roles: a class-level
|
|
116
|
+
// S_EVERYONE does not open a method that asks for S_USER. Kept in sync with RolesGuard.
|
|
117
|
+
const effective = handlerRoles?.some((value) => !!value) ? handlerRoles : roles;
|
|
118
|
+
if (!effective || !effective.some((value) => !!value) || effective.includes(RoleEnum.S_EVERYONE)) {
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
122
|
+
}
|
|
123
|
+
|
|
106
124
|
const apiTokenKind = enforceApiTokenRoute({
|
|
107
125
|
controllerClass: context.getClass(),
|
|
108
126
|
handler: context.getHandler(),
|
|
@@ -205,6 +223,16 @@ export class BetterAuthRolesGuard implements CanActivate {
|
|
|
205
223
|
* Get target ID from context for S_SELF checks
|
|
206
224
|
*/
|
|
207
225
|
private getTargetId(context: ExecutionContext): null | string {
|
|
226
|
+
// An agent function / MCP call: its arguments are the target, as a resolver's args are on GraphQL. Never the HTTP
|
|
227
|
+
// fallback below, which would read the same arguments as if they were a request with `params`.
|
|
228
|
+
if (isAgentCallContext(context)) {
|
|
229
|
+
if (!agentCallOf(context)) {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
const input = context.getArgByIndex(0);
|
|
233
|
+
return typeof input?.id === 'string' ? input.id : null;
|
|
234
|
+
}
|
|
235
|
+
|
|
208
236
|
// Try GraphQL args
|
|
209
237
|
try {
|
|
210
238
|
const gqlContext = GqlExecutionContext.create(context);
|