@lenne.tech/nest-server 12.9.4 → 12.10.1

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 (152) hide show
  1. package/.claude/rules/configurable-features.md +5 -1
  2. package/.claude/rules/package-management.md +38 -12
  3. package/.claude/rules/role-system.md +12 -0
  4. package/.claude/rules/testing.md +4 -4
  5. package/CLAUDE.md +10 -1
  6. package/FRAMEWORK-API.md +2 -1
  7. package/dist/core/common/decorators/rest-user.decorator.js +4 -0
  8. package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
  9. package/dist/core/common/filters/http-exception-log.filter.js +3 -0
  10. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  11. package/dist/core/common/helpers/context.helper.js +9 -0
  12. package/dist/core/common/helpers/context.helper.js.map +1 -1
  13. package/dist/core/common/helpers/decorator.helper.js +4 -0
  14. package/dist/core/common/helpers/decorator.helper.js.map +1 -1
  15. package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
  16. package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
  17. package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
  18. package/dist/core/common/helpers/graphql-upload.helper.d.ts +10 -0
  19. package/dist/core/common/helpers/graphql-upload.helper.js +237 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  21. package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
  22. package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
  23. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  24. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  25. package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
  26. package/dist/core/common/middleware/request-context.middleware.js +3 -0
  27. package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
  28. package/dist/core/common/plugins/complexity.plugin.js +73 -9
  29. package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
  30. package/dist/core/common/services/request-context.service.d.ts +2 -0
  31. package/dist/core/common/services/request-context.service.js +3 -0
  32. package/dist/core/common/services/request-context.service.js.map +1 -1
  33. package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
  34. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  35. package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
  36. package/dist/core/modules/ai/core-ai.constants.js +1 -0
  37. package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
  38. package/dist/core/modules/ai/core-ai.module.js +2 -0
  39. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  40. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
  41. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
  42. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
  43. package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
  44. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
  45. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
  46. package/dist/core/modules/ai/index.d.ts +8 -0
  47. package/dist/core/modules/ai/index.js +8 -0
  48. package/dist/core/modules/ai/index.js.map +1 -1
  49. package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
  50. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
  51. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
  52. package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
  53. package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
  54. package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
  55. package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
  56. package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
  57. package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
  58. package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
  59. package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
  60. package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
  61. package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
  62. package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
  63. package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
  64. package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
  65. package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
  66. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
  67. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
  68. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
  69. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
  70. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
  71. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  72. package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
  73. package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
  74. package/dist/core/modules/ai/services/core-ai.service.js +2 -7
  75. package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
  76. package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
  77. package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
  78. package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
  79. package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
  80. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
  81. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
  82. package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
  83. package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
  84. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  85. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  86. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  87. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  88. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  89. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  90. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  91. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  92. package/dist/core/modules/better-auth/better-auth.config.js +78 -0
  93. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  94. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  95. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  96. package/dist/core.module.js +2 -1
  97. package/dist/core.module.js.map +1 -1
  98. package/dist/index.d.ts +1 -0
  99. package/dist/index.js +1 -0
  100. package/dist/index.js.map +1 -1
  101. package/dist/types/graphql-upload.d.ts +34 -2
  102. package/docs/REQUEST-LIFECYCLE.md +59 -10
  103. package/migration-guides/12.10.0-to-12.10.1.md +182 -0
  104. package/migration-guides/12.9.3-to-12.9.4.md +3 -1
  105. package/migration-guides/12.9.x-to-12.10.x.md +271 -0
  106. package/package.json +46 -21
  107. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  108. package/src/core/common/filters/http-exception-log.filter.ts +8 -0
  109. package/src/core/common/helpers/context.helper.ts +14 -0
  110. package/src/core/common/helpers/decorator.helper.ts +5 -0
  111. package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
  112. package/src/core/common/helpers/graphql-upload.helper.ts +520 -0
  113. package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
  114. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  115. package/src/core/common/interfaces/server-options.interface.ts +98 -0
  116. package/src/core/common/middleware/request-context.middleware.ts +3 -0
  117. package/src/core/common/plugins/complexity.plugin.ts +150 -9
  118. package/src/core/common/services/request-context.service.ts +11 -0
  119. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
  120. package/src/core/modules/ai/README.md +101 -0
  121. package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
  122. package/src/core/modules/ai/core-ai.constants.ts +4 -0
  123. package/src/core/modules/ai/core-ai.module.ts +3 -0
  124. package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
  125. package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
  126. package/src/core/modules/ai/index.ts +8 -0
  127. package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
  128. package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
  129. package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
  130. package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
  131. package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
  132. package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
  133. package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
  134. package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
  135. package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
  136. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
  137. package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
  138. package/src/core/modules/ai/services/core-ai.service.ts +5 -7
  139. package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
  140. package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
  141. package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
  142. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  143. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  144. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  145. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
  146. package/src/core/modules/better-auth/README.md +204 -0
  147. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  148. package/src/core/modules/better-auth/better-auth.config.ts +138 -1
  149. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  150. package/src/core.module.ts +5 -1
  151. package/src/index.ts +1 -0
  152. package/src/types/graphql-upload.d.ts +34 -2
@@ -0,0 +1,520 @@
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 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
+ *
39
+ * `CoreModule` passes this function to `graphqlUploadExpress({ processRequest })`. A project that registers
40
+ * `graphqlUploadExpress()` itself must pass it too — graphql-upload's own default is the unpatched function.
41
+ *
42
+ * `Upload` comes from graphql-upload's own `Upload.mjs`, the class the `GraphQLUpload` scalar checks with
43
+ * `instanceof`: an `Upload` of any other class would be refused as an invalid upload. `ignoreStream` is not exported
44
+ * by graphql-upload and is re-implemented below.
45
+ *
46
+ * ---------------------------------------------------------------------------------------------------------------
47
+ * MIT License
48
+ *
49
+ * Copyright Jayden Seric
50
+ *
51
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
52
+ * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
53
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
54
+ * permit persons to whom the Software is furnished to do so, subject to the following conditions:
55
+ *
56
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of
57
+ * the Software.
58
+ *
59
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
60
+ * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
61
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
62
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
63
+ * SOFTWARE.
64
+ * ---------------------------------------------------------------------------------------------------------------
65
+ */
66
+ import busboy from 'busboy';
67
+ import { WriteStream } from 'fs-capacitor';
68
+ import Upload from 'graphql-upload/Upload.mjs';
69
+ import createError from 'http-errors';
70
+ import objectPath from 'object-path';
71
+
72
+ import type { IncomingMessage, ServerResponse } from 'node:http';
73
+ import type { Readable } from 'node:stream';
74
+
75
+ /** graphql-upload's `GRAPHQL_MULTIPART_REQUEST_SPEC_URL`, used in the error messages exactly as upstream does. */
76
+ const GRAPHQL_MULTIPART_REQUEST_SPEC_URL = 'https://github.com/jaydenseric/graphql-multipart-request-spec';
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
+
98
+ /**
99
+ * Options of {@link processGraphQlUploadRequest} — the same as graphql-upload's `ProcessRequestOptions`, so
100
+ * `graphqlUploadExpress({ processRequest, ...options })` forwards them unchanged.
101
+ */
102
+ export interface GraphQlUploadProcessRequestOptions {
103
+ /** Maximum size of a non-file multipart field (`operations`, `map`) in bytes. Defaults to `1000000` (1 MB). */
104
+ maxFieldSize?: number;
105
+ /** Maximum size of one file in bytes. Defaults to `Infinity`. */
106
+ maxFileSize?: number;
107
+ /** Maximum number of files. Defaults to `Infinity`. */
108
+ maxFiles?: number;
109
+ }
110
+
111
+ /** The GraphQL operation (or batch of operations) a multipart request resolves to, with `Upload` instances placed. */
112
+ export type GraphQlUploadOperations = Array<Record<string, unknown>> | Record<string, unknown>;
113
+
114
+ /** File details an `Upload` resolves with (graphql-upload's `FileUpload`). */
115
+ interface ProcessedFileUpload {
116
+ capacitor: WriteStream;
117
+ createReadStream: (options?: { encoding?: BufferEncoding; highWaterMark?: number }) => Readable;
118
+ encoding: string;
119
+ filename: string;
120
+ mimetype: string;
121
+ }
122
+
123
+ /** An error created with `http-errors` (or any other error the parser reports). */
124
+ type ProcessRequestError = Error & { expose?: boolean; status?: number };
125
+
126
+ /**
127
+ * Safely ignores a readable stream (graphql-upload's `ignoreStream`, which the package does not export): an error
128
+ * on it must not crash the process, and its data is drained so the parser can go on.
129
+ */
130
+ function ignoreStream(stream: Readable): void {
131
+ // Prevent an unhandled error from crashing the process.
132
+ stream.on('error', () => {});
133
+
134
+ // Waste the stream.
135
+ stream.resume();
136
+ }
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
+
157
+ /**
158
+ * Processes an incoming GraphQL multipart request
159
+ * (https://github.com/jaydenseric/graphql-multipart-request-spec): parses the `operations` and `map` fields, places
160
+ * an `Upload` wherever the `map` names one and resolves each with its file once that file streams in.
161
+ *
162
+ * graphql-upload 17.1.0's `processRequest` with the fixes of graphql-upload 18.0.2 (see the file header). Pass it to
163
+ * `graphqlUploadExpress({ processRequest: processGraphQlUploadRequest })`; `CoreModule` does so for `/graphql`.
164
+ *
165
+ * @returns The operation(s), with an `Upload` at every mapped path — resolved once the `map` is parsed. Rejects with
166
+ * an `http-errors` error (400 for a malformed request, 413 above a limit, 499 on a disconnect).
167
+ */
168
+ export function processGraphQlUploadRequest(
169
+ request: IncomingMessage,
170
+ response: ServerResponse,
171
+ { maxFieldSize = 1000000, maxFileSize = Infinity, maxFiles = Infinity }: GraphQlUploadProcessRequestOptions = {},
172
+ ): Promise<GraphQlUploadOperations> {
173
+ return new Promise((resolve, reject) => {
174
+ let released: boolean;
175
+ let exitError: ProcessRequestError;
176
+ let operations: GraphQlUploadOperations;
177
+ let operationsPath: ReturnType<typeof objectPath>;
178
+ let map: Map<string, Upload>;
179
+
180
+ const parser = busboy({
181
+ headers: request.headers,
182
+ defParamCharset: 'utf8',
183
+ limits: {
184
+ fieldSize: maxFieldSize,
185
+ fields: 2, // Only operations and map.
186
+ fileSize: maxFileSize,
187
+ files: maxFiles,
188
+ },
189
+ });
190
+
191
+ /**
192
+ * Exits request processing with an error. Successive calls have no effect.
193
+ */
194
+ function exit(error: ProcessRequestError, isParserError = false): void {
195
+ if (exitError) {
196
+ return;
197
+ }
198
+
199
+ exitError = error;
200
+
201
+ if (map) {
202
+ for (const upload of map.values()) {
203
+ if (!upload.file) {
204
+ upload.reject(exitError);
205
+ }
206
+ }
207
+ }
208
+
209
+ // If the error came from the parser, don't cause it to be emitted again.
210
+ if (isParserError) {
211
+ parser.destroy();
212
+ } else {
213
+ parser.destroy(exitError);
214
+ }
215
+
216
+ request.unpipe(parser);
217
+
218
+ // With a sufficiently large request body, subsequent events in the same event frame cause the stream to pause
219
+ // after the parser is destroyed. To ensure that the request resumes, the call to .resume() is scheduled for
220
+ // later in the event loop.
221
+ setImmediate(() => {
222
+ request.resume();
223
+ });
224
+
225
+ reject(exitError);
226
+ }
227
+
228
+ parser.on('field', (fieldName: string, value: string, { valueTruncated }: { valueTruncated: boolean }) => {
229
+ if (valueTruncated) {
230
+ return exit(
231
+ createError(413, `The ‘${fieldName}’ multipart field value exceeds the ${maxFieldSize} byte size limit.`),
232
+ );
233
+ }
234
+
235
+ switch (fieldName) {
236
+ case 'operations':
237
+ try {
238
+ operations = JSON.parse(value);
239
+ } catch {
240
+ return exit(
241
+ createError(
242
+ 400,
243
+ `Invalid JSON in the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
244
+ ),
245
+ );
246
+ }
247
+
248
+ // `operations` should be an object or an array. Note that arrays and `null` have an `object` type.
249
+ if (typeof operations !== 'object' || !operations) {
250
+ return exit(
251
+ createError(
252
+ 400,
253
+ `Invalid type for the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
254
+ ),
255
+ );
256
+ }
257
+
258
+ operationsPath = objectPath(operations);
259
+
260
+ break;
261
+ case 'map': {
262
+ if (!operations) {
263
+ return exit(
264
+ createError(
265
+ 400,
266
+ `Misordered multipart fields; ‘map’ should follow ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
267
+ ),
268
+ );
269
+ }
270
+
271
+ let parsedMap: unknown;
272
+ try {
273
+ parsedMap = JSON.parse(value);
274
+ } catch {
275
+ return exit(
276
+ createError(400, `Invalid JSON in the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`),
277
+ );
278
+ }
279
+
280
+ // `map` should be an object.
281
+ if (typeof parsedMap !== 'object' || !parsedMap || Array.isArray(parsedMap)) {
282
+ return exit(
283
+ createError(400, `Invalid type for the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`),
284
+ );
285
+ }
286
+
287
+ const mapEntries = Object.entries(parsedMap);
288
+
289
+ // Check max files is not exceeded, even though the number of files to parse might not match the map
290
+ // provided by the client.
291
+ if (mapEntries.length > maxFiles) {
292
+ return exit(createError(413, `${maxFiles} max file uploads exceeded.`));
293
+ }
294
+
295
+ map = new Map();
296
+ // Map entries and path keys so far, against GRAPHQL_UPLOAD_MAX_MAP_KEYS.
297
+ let mapKeyCount = 0;
298
+ for (const [mapFieldName, paths] of mapEntries) {
299
+ if (!Array.isArray(paths)) {
300
+ return exit(
301
+ createError(
302
+ 400,
303
+ `Invalid type for the ‘map’ multipart field entry key ‘${mapFieldName}’ array (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
304
+ ),
305
+ );
306
+ }
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
+
320
+ map.set(mapFieldName, new Upload());
321
+
322
+ for (const [index, path] of paths.entries()) {
323
+ if (typeof path !== 'string') {
324
+ return exit(
325
+ createError(
326
+ 400,
327
+ `Invalid type for the ‘map’ multipart field entry key ‘${mapFieldName}’ array index ‘${index}’ value (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
328
+ ),
329
+ );
330
+ }
331
+
332
+ try {
333
+ // GHSA-5vm7-vc2x-p3w2 (graphql-upload 18.0.2): check the upload's mapped path in the operations is
334
+ // safe before setting it.
335
+ const keys = path.split('.');
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
+
349
+ let pathValue: unknown = operations;
350
+
351
+ for (const [keyIndex, key] of keys.entries()) {
352
+ // Forbid `__proto__` keys to prevent prototype manipulation that could make client-supplied
353
+ // objects pass `instanceof Upload` checks.
354
+ if (key === '__proto__') {
355
+ throw new TypeError('Object path has a `__proto__` key.');
356
+ }
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
+
369
+ // Forbid setting an upload within an already set upload, but allow a total replacement. Resolved
370
+ // with object-path's own `get`, so it sees what `set` will reach, inherited array elements included.
371
+ if (keyIndex < keys.length - 1) {
372
+ pathValue = objectPath.get(pathValue as object, [key]);
373
+
374
+ if (pathValue instanceof Upload) {
375
+ throw new TypeError('Object path traverses an upload.');
376
+ }
377
+ }
378
+ }
379
+
380
+ operationsPath.set(path, map.get(mapFieldName));
381
+ } catch {
382
+ return exit(
383
+ createError(
384
+ 400,
385
+ `Invalid object path for the ‘map’ multipart field entry key ‘${mapFieldName}’ array index ‘${index}’ value ‘${path}’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
386
+ ),
387
+ );
388
+ }
389
+ }
390
+ }
391
+
392
+ resolve(operations);
393
+ }
394
+ }
395
+ });
396
+
397
+ parser.on(
398
+ 'file',
399
+ (
400
+ fieldName: string,
401
+ stream: Readable,
402
+ { encoding, filename, mimeType: mimetype }: { encoding: string; filename: string; mimeType: string },
403
+ ) => {
404
+ if (!map) {
405
+ ignoreStream(stream);
406
+ return exit(
407
+ createError(
408
+ 400,
409
+ `Misordered multipart fields; files should follow ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
410
+ ),
411
+ );
412
+ }
413
+
414
+ const upload = map.get(fieldName);
415
+
416
+ // GHSA-qwwm-252j-9whw (graphql-upload 18.0.2): `|| upload.file` — a duplicate file field would create a new
417
+ // capacitor and replace the reference to the first one, which then never gets released.
418
+ if (!upload || upload.file) {
419
+ // The file is extraneous or a duplicate. As the rest can still be processed, just ignore it and don't
420
+ // exit with an error.
421
+ ignoreStream(stream);
422
+ return;
423
+ }
424
+
425
+ let fileError: ProcessRequestError;
426
+
427
+ const capacitor = new WriteStream();
428
+
429
+ capacitor.on('error', () => {
430
+ stream.unpipe();
431
+ stream.resume();
432
+ });
433
+
434
+ stream.on('limit', () => {
435
+ fileError = createError(413, `File truncated as it exceeds the ${maxFileSize} byte size limit.`);
436
+ stream.unpipe();
437
+ capacitor.destroy(fileError);
438
+ });
439
+
440
+ stream.on('error', (error: Error) => {
441
+ fileError = error;
442
+ stream.unpipe();
443
+ capacitor.destroy(fileError);
444
+ });
445
+
446
+ const file: ProcessedFileUpload = {
447
+ filename,
448
+ mimetype,
449
+ encoding,
450
+ createReadStream(options) {
451
+ const error = fileError || (released ? exitError : null);
452
+ if (error) {
453
+ throw error;
454
+ }
455
+ return capacitor.createReadStream(options);
456
+ },
457
+ capacitor,
458
+ };
459
+
460
+ Object.defineProperty(file, 'capacitor', {
461
+ enumerable: false,
462
+ configurable: false,
463
+ writable: false,
464
+ });
465
+
466
+ stream.pipe(capacitor);
467
+ upload.resolve(file);
468
+ },
469
+ );
470
+
471
+ parser.once('filesLimit', () => exit(createError(413, `${maxFiles} max file uploads exceeded.`)));
472
+
473
+ parser.once('finish', () => {
474
+ request.unpipe(parser);
475
+ request.resume();
476
+
477
+ if (!operations) {
478
+ return exit(createError(400, `Missing multipart field ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`));
479
+ }
480
+
481
+ if (!map) {
482
+ return exit(createError(400, `Missing multipart field ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`));
483
+ }
484
+
485
+ for (const upload of map.values()) {
486
+ if (!upload.file) {
487
+ upload.reject(createError(400, 'File missing in the request.'));
488
+ }
489
+ }
490
+ });
491
+
492
+ // Use the `on` method instead of `once` as in edge cases the same parser could have multiple `error` events and
493
+ // all must be handled to prevent the Node.js process exiting with an error. One edge case is if there is a
494
+ // malformed part header as well as an unexpected end of the form.
495
+ parser.on('error', (error: Error) => {
496
+ exit(error, true);
497
+ });
498
+
499
+ response.once('close', () => {
500
+ released = true;
501
+
502
+ if (map) {
503
+ for (const upload of map.values()) {
504
+ if (upload.file) {
505
+ // Release resources and clean up temporary files.
506
+ (upload.file as ProcessedFileUpload).capacitor.release();
507
+ }
508
+ }
509
+ }
510
+ });
511
+
512
+ request.once('close', () => {
513
+ if (!request.readableEnded) {
514
+ exit(createError(499, 'Request disconnected during file upload stream parsing.'));
515
+ }
516
+ });
517
+
518
+ request.pipe(parser);
519
+ });
520
+ }
@@ -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
- return underSecretKey ? REDACTED_VALUE : value;
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)) {
@@ -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') {