graphql-upload 12.0.0 → 15.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,427 @@
1
+ // @ts-check
2
+
3
+ "use strict";
4
+
5
+ const busboy = require("busboy");
6
+ const { WriteStream } = require("fs-capacitor");
7
+ const createError = require("http-errors");
8
+ const objectPath = require("object-path");
9
+ const GRAPHQL_MULTIPART_REQUEST_SPEC_URL = require("./GRAPHQL_MULTIPART_REQUEST_SPEC_URL.js");
10
+ const ignoreStream = require("./ignoreStream.js");
11
+ const Upload = require("./Upload.js");
12
+
13
+ /** @typedef {import("./GraphQLUpload.js")} GraphQLUpload */
14
+ /** @typedef {import("./graphqlUploadExpress.js")} graphqlUploadExpress */
15
+ /** @typedef {import("./graphqlUploadKoa.js")} graphqlUploadKoa */
16
+
17
+ /**
18
+ * Processes an incoming
19
+ * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
20
+ * It parses the `operations` and `map` fields to create an {@linkcode Upload}
21
+ * instance for each expected file upload, placing references wherever the file
22
+ * is expected in the GraphQL operation for the {@linkcode GraphQLUpload} scalar
23
+ * to derive it’s value. Errors are created with
24
+ * [`http-errors`](https://npm.im/http-errors) to assist in sending responses
25
+ * with appropriate HTTP status codes. Used to create custom middleware and is
26
+ * used by {@linkcode graphqlUploadExpress} and {@linkcode graphqlUploadKoa}.
27
+ * @type {ProcessRequestFunction}
28
+ */
29
+ function processRequest(
30
+ request,
31
+ response,
32
+ {
33
+ maxFieldSize = 1000000, // 1 MB
34
+ maxFileSize = Infinity,
35
+ maxFiles = Infinity,
36
+ } = {}
37
+ ) {
38
+ return new Promise((resolve, reject) => {
39
+ /** @type {boolean} */
40
+ let released;
41
+
42
+ /** @type {Error} */
43
+ let exitError;
44
+
45
+ /**
46
+ * @type {{ [key: string]: unknown } | Array<
47
+ * { [key: string]: unknown }
48
+ * >}
49
+ */
50
+ let operations;
51
+
52
+ /**
53
+ * @type {import("object-path").ObjectPathBound<
54
+ * { [key: string]: unknown } | Array<{ [key: string]: unknown }>
55
+ * >}
56
+ */
57
+ let operationsPath;
58
+
59
+ /** @type {Map<string, Upload>} */
60
+ let map;
61
+
62
+ const parser = busboy({
63
+ // @ts-ignore This is about to change with `busboy` v1 types.
64
+ headers: request.headers,
65
+ limits: {
66
+ fieldSize: maxFieldSize,
67
+ fields: 2, // Only operations and map.
68
+ fileSize: maxFileSize,
69
+ files: maxFiles,
70
+ },
71
+ });
72
+
73
+ /**
74
+ * Exits request processing with an error. Successive calls have no effect.
75
+ * @param {Error} error Error instance.
76
+ * @param {boolean} [isParserError] Is the error from the parser.
77
+ */
78
+ function exit(error, isParserError = false) {
79
+ if (exitError) return;
80
+
81
+ exitError = error;
82
+
83
+ if (map)
84
+ for (const upload of map.values())
85
+ if (!upload.file) upload.reject(exitError);
86
+
87
+ // If the error came from the parser, don’t cause it to be emitted again.
88
+ isParserError ? parser.destroy() : parser.destroy(exitError);
89
+
90
+ request.unpipe(parser);
91
+
92
+ // With a sufficiently large request body, subsequent events in the same
93
+ // event frame cause the stream to pause after the parser is destroyed. To
94
+ // ensure that the request resumes, the call to .resume() is scheduled for
95
+ // later in the event loop.
96
+ setImmediate(() => {
97
+ request.resume();
98
+ });
99
+
100
+ reject(exitError);
101
+ }
102
+
103
+ parser.on("field", (fieldName, value, { valueTruncated }) => {
104
+ if (valueTruncated)
105
+ return exit(
106
+ createError(
107
+ 413,
108
+ `The ‘${fieldName}’ multipart field value exceeds the ${maxFieldSize} byte size limit.`
109
+ )
110
+ );
111
+
112
+ switch (fieldName) {
113
+ case "operations":
114
+ try {
115
+ operations = JSON.parse(value);
116
+ } catch (error) {
117
+ return exit(
118
+ createError(
119
+ 400,
120
+ `Invalid JSON in the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
121
+ )
122
+ );
123
+ }
124
+
125
+ // `operations` should be an object or an array. Note that arrays
126
+ // and `null` have an `object` type.
127
+ if (typeof operations !== "object" || !operations)
128
+ return exit(
129
+ createError(
130
+ 400,
131
+ `Invalid type for the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
132
+ )
133
+ );
134
+
135
+ operationsPath = objectPath(operations);
136
+
137
+ break;
138
+ case "map": {
139
+ if (!operations)
140
+ return exit(
141
+ createError(
142
+ 400,
143
+ `Misordered multipart fields; ‘map’ should follow ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
144
+ )
145
+ );
146
+
147
+ let parsedMap;
148
+ try {
149
+ parsedMap = JSON.parse(value);
150
+ } catch (error) {
151
+ return exit(
152
+ createError(
153
+ 400,
154
+ `Invalid JSON in the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
155
+ )
156
+ );
157
+ }
158
+
159
+ // `map` should be an object.
160
+ if (
161
+ typeof parsedMap !== "object" ||
162
+ !parsedMap ||
163
+ Array.isArray(parsedMap)
164
+ )
165
+ return exit(
166
+ createError(
167
+ 400,
168
+ `Invalid type for the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
169
+ )
170
+ );
171
+
172
+ const mapEntries = Object.entries(parsedMap);
173
+
174
+ // Check max files is not exceeded, even though the number of files
175
+ // to parse might not match the map provided by the client.
176
+ if (mapEntries.length > maxFiles)
177
+ return exit(
178
+ createError(413, `${maxFiles} max file uploads exceeded.`)
179
+ );
180
+
181
+ map = new Map();
182
+ for (const [fieldName, paths] of mapEntries) {
183
+ if (!Array.isArray(paths))
184
+ return exit(
185
+ createError(
186
+ 400,
187
+ `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
188
+ )
189
+ );
190
+
191
+ map.set(fieldName, new Upload());
192
+
193
+ for (const [index, path] of paths.entries()) {
194
+ if (typeof path !== "string")
195
+ return exit(
196
+ createError(
197
+ 400,
198
+ `Invalid type for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
199
+ )
200
+ );
201
+
202
+ try {
203
+ operationsPath.set(path, map.get(fieldName));
204
+ } catch (error) {
205
+ return exit(
206
+ createError(
207
+ 400,
208
+ `Invalid object path for the ‘map’ multipart field entry key ‘${fieldName}’ array index ‘${index}’ value ‘${path}’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
209
+ )
210
+ );
211
+ }
212
+ }
213
+ }
214
+
215
+ resolve(operations);
216
+ }
217
+ }
218
+ });
219
+
220
+ parser.on(
221
+ "file",
222
+ (fieldName, stream, { filename, encoding, mimeType: mimetype }) => {
223
+ if (!map) {
224
+ ignoreStream(stream);
225
+ return exit(
226
+ createError(
227
+ 400,
228
+ `Misordered multipart fields; files should follow ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
229
+ )
230
+ );
231
+ }
232
+
233
+ const upload = map.get(fieldName);
234
+
235
+ if (!upload) {
236
+ // The file is extraneous. As the rest can still be processed, just
237
+ // ignore it and don’t exit with an error.
238
+ ignoreStream(stream);
239
+ return;
240
+ }
241
+
242
+ /** @type {Error} */
243
+ let fileError;
244
+
245
+ const capacitor = new WriteStream();
246
+
247
+ capacitor.on("error", () => {
248
+ stream.unpipe();
249
+ stream.resume();
250
+ });
251
+
252
+ stream.on("limit", () => {
253
+ fileError = createError(
254
+ 413,
255
+ `File truncated as it exceeds the ${maxFileSize} byte size limit.`
256
+ );
257
+ stream.unpipe();
258
+ capacitor.destroy(fileError);
259
+ });
260
+
261
+ stream.on("error", (error) => {
262
+ fileError = error;
263
+ stream.unpipe();
264
+ capacitor.destroy(fileError);
265
+ });
266
+
267
+ /** @type {FileUpload} */
268
+ const file = {
269
+ filename,
270
+ mimetype,
271
+ encoding,
272
+ createReadStream(options) {
273
+ const error = fileError || (released ? exitError : null);
274
+ if (error) throw error;
275
+ return capacitor.createReadStream(options);
276
+ },
277
+ capacitor,
278
+ };
279
+
280
+ Object.defineProperty(file, "capacitor", {
281
+ enumerable: false,
282
+ configurable: false,
283
+ writable: false,
284
+ });
285
+
286
+ stream.pipe(capacitor);
287
+ upload.resolve(file);
288
+ }
289
+ );
290
+
291
+ parser.once("filesLimit", () =>
292
+ exit(createError(413, `${maxFiles} max file uploads exceeded.`))
293
+ );
294
+
295
+ parser.once("finish", () => {
296
+ request.unpipe(parser);
297
+ request.resume();
298
+
299
+ if (!operations)
300
+ return exit(
301
+ createError(
302
+ 400,
303
+ `Missing multipart field ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
304
+ )
305
+ );
306
+
307
+ if (!map)
308
+ return exit(
309
+ createError(
310
+ 400,
311
+ `Missing multipart field ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`
312
+ )
313
+ );
314
+
315
+ for (const upload of map.values())
316
+ if (!upload.file)
317
+ upload.reject(createError(400, "File missing in the request."));
318
+ });
319
+
320
+ // Use the `on` method instead of `once` as in edge cases the same parser
321
+ // could have multiple `error` events and all must be handled to prevent the
322
+ // Node.js process exiting with an error. One edge case is if there is a
323
+ // malformed part header as well as an unexpected end of the form.
324
+ parser.on("error", (/** @type {Error} */ error) => {
325
+ exit(error, true);
326
+ });
327
+
328
+ response.once("close", () => {
329
+ released = true;
330
+
331
+ if (map)
332
+ for (const upload of map.values())
333
+ if (upload.file)
334
+ // Release resources and clean up temporary files.
335
+ upload.file.capacitor.release();
336
+ });
337
+
338
+ request.once("close", () => {
339
+ if (!request.readableEnded)
340
+ exit(
341
+ createError(
342
+ 499,
343
+ "Request disconnected during file upload stream parsing."
344
+ )
345
+ );
346
+ });
347
+
348
+ request.pipe(parser);
349
+ });
350
+ }
351
+
352
+ module.exports = processRequest;
353
+
354
+ /**
355
+ * File upload details that are only available after the file’s field in the
356
+ * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec)
357
+ * has begun streaming in.
358
+ * @typedef {object} FileUpload
359
+ * @prop {string} filename File name.
360
+ * @prop {string} mimetype File MIME type. Provided by the client and can’t be
361
+ * trusted.
362
+ * @prop {string} encoding File stream transfer encoding.
363
+ * @prop {import("fs-capacitor").WriteStream} capacitor A private implementation
364
+ * detail that shouldn’t be used outside
365
+ * [`graphql-upload`](https://npm.im/graphql-upload).
366
+ * @prop {FileUploadCreateReadStream} createReadStream Creates a
367
+ * [Node.js readable stream](https://nodejs.org/api/stream.html#readable-streams)
368
+ * of the file’s contents, for processing and storage.
369
+ */
370
+
371
+ /**
372
+ * Creates a
373
+ * [Node.js readable stream](https://nodejs.org/api/stream.html#readable-streams)
374
+ * of an {@link FileUpload uploading file’s} contents, for processing and
375
+ * storage. Multiple calls create independent streams. Throws if called after
376
+ * all resolvers have resolved, or after an error has interrupted the request.
377
+ * @callback FileUploadCreateReadStream
378
+ * @param {FileUploadCreateReadStreamOptions} [options] Options.
379
+ * @returns {import("stream").Readable}
380
+ * [Node.js readable stream](https://nodejs.org/api/stream.html#readable-streams)
381
+ * of the file’s contents.
382
+ * @see [Node.js `Readable` stream constructor docs](https://nodejs.org/api/stream.html#new-streamreadableoptions).
383
+ * @see [Node.js stream backpressure guide](https://nodejs.org/en/docs/guides/backpressuring-in-streams).
384
+ */
385
+
386
+ /**
387
+ * {@linkcode FileUploadCreateReadStream} options.
388
+ * @typedef {object} FileUploadCreateReadStreamOptions
389
+ * @prop {string} [options.encoding] Specify an encoding for the
390
+ * [`data`](https://nodejs.org/api/stream.html#event-data) chunks to be
391
+ * strings (without splitting multi-byte characters across chunks) instead of
392
+ * Node.js [`Buffer`](https://nodejs.org/api/buffer.html#buffer) instances.
393
+ * Supported values depend on the
394
+ * [`Buffer` implementation](https://github.com/nodejs/node/blob/v18.1.0/lib/buffer.js#L590-L680)
395
+ * and include `utf8`, `ucs2`, `utf16le`, `latin1`, `ascii`, `base64`,
396
+ * `base64url`, or `hex`. Defaults to `utf8`.
397
+ * @prop {number} [options.highWaterMark] Maximum number of bytes to store in
398
+ * the internal buffer before ceasing to read from the underlying resource.
399
+ * Defaults to `16384`.
400
+ */
401
+
402
+ /**
403
+ * Processes an incoming
404
+ * [GraphQL multipart request](https://github.com/jaydenseric/graphql-multipart-request-spec).
405
+ * @callback ProcessRequestFunction
406
+ * @param {import("http").IncomingMessage} request
407
+ * [Node.js HTTP server request instance](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
408
+ * @param {import("http").ServerResponse} response
409
+ * [Node.js HTTP server response instance](https://nodejs.org/api/http.html#http_class_http_serverresponse).
410
+ * @param {ProcessRequestOptions} [options] Options.
411
+ * @returns {Promise<
412
+ * { [key: string]: unknown } | Array<{ [key: string]: unknown }>
413
+ * >} GraphQL operation or batch of operations for a GraphQL server to consume
414
+ * (usually as the request body). A GraphQL operation typically has the
415
+ * properties `query` and `variables`.
416
+ */
417
+
418
+ /**
419
+ * {@linkcode ProcessRequestFunction} options.
420
+ * @typedef {object} ProcessRequestOptions
421
+ * @prop {number} [maxFieldSize] Maximum allowed non file multipart form field
422
+ * size in bytes; enough for your queries. Defaults to `1000000` (1 MB).
423
+ * @prop {number} [maxFileSize] Maximum allowed file size in bytes. Defaults to
424
+ * `Infinity`.
425
+ * @prop {number} [maxFiles] Maximum allowed number of files. Defaults to
426
+ * `Infinity`.
427
+ */