graphql-upload-nextjs 2.0.11 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +6 -3
- package/README.md +83 -255
- package/SECURITY.md +3 -3
- package/core.d.ts +107 -0
- package/core.js +341 -0
- package/index.d.ts +7 -72
- package/index.js +36 -352
- package/package.json +28 -17
- package/streaming.d.ts +22 -0
- package/streaming.js +269 -0
package/streaming.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/** Executes multipart operations while file bytes arrive, with bounded parsing and private disk spooling. */
|
|
2
|
+
import busboy from 'busboy';
|
|
3
|
+
import { WriteStream } from 'fs-capacitor';
|
|
4
|
+
import { Readable, Transform } from 'node:stream';
|
|
5
|
+
import { finished, pipeline } from 'node:stream/promises';
|
|
6
|
+
import { UploadRequestError, checkUploadRequest, detectMimeType, executeOperations, prepareOperations, uploadErrorResponse, } from './core.js';
|
|
7
|
+
/** Opt-in Node.js API; success waits for reception, and all readers must finish within execution. */
|
|
8
|
+
export async function uploadProcessStreaming(request, contextValueInput, server, settings = {}) {
|
|
9
|
+
let dispose;
|
|
10
|
+
try {
|
|
11
|
+
checkUploadRequest(request.headers, settings);
|
|
12
|
+
const limits = {
|
|
13
|
+
maxFieldSize: settings.maxFieldSize === undefined ? 1024 * 1024 : settings.maxFieldSize,
|
|
14
|
+
maxFileSize: settings.maxFileSize === undefined ? 10 * 1024 * 1024 : settings.maxFileSize,
|
|
15
|
+
maxFiles: settings.maxFiles === undefined ? 10 : settings.maxFiles,
|
|
16
|
+
maxRequestSize: settings.maxRequestSize === undefined ? 100 * 1024 * 1024 : settings.maxRequestSize,
|
|
17
|
+
};
|
|
18
|
+
for (const key of ['maxFieldSize', 'maxFileSize', 'maxFiles', 'maxRequestSize']) {
|
|
19
|
+
if (!Number.isSafeInteger(limits[key]) || limits[key] < 0) {
|
|
20
|
+
throw new UploadRequestError(`Invalid ${key} setting: expected a non-negative safe integer.`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (!request.body || request.body.locked)
|
|
24
|
+
throw new UploadRequestError('An unread request body is required.');
|
|
25
|
+
const contentType = request.headers.get('content-type') || '';
|
|
26
|
+
if (!/^multipart\/form-data(?:;|$)/i.test(contentType)) {
|
|
27
|
+
throw new UploadRequestError('Expected a multipart/form-data request.');
|
|
28
|
+
}
|
|
29
|
+
let parser;
|
|
30
|
+
try {
|
|
31
|
+
parser = busboy({
|
|
32
|
+
headers: { 'content-type': contentType }, defParamCharset: 'utf8',
|
|
33
|
+
limits: {
|
|
34
|
+
fields: 2, files: limits.maxFiles,
|
|
35
|
+
// Busboy reports equality as truncation; the public limits are inclusive.
|
|
36
|
+
fieldSize: limits.maxFieldSize + 1, fileSize: limits.maxFileSize + 1,
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new UploadRequestError('Invalid multipart Content-Type or boundary.');
|
|
42
|
+
}
|
|
43
|
+
const ready = Promise.withResolvers();
|
|
44
|
+
const failure = Promise.withResolvers();
|
|
45
|
+
// Parser failures can precede the caller awaiting either promise.
|
|
46
|
+
void ready.promise.catch(() => { });
|
|
47
|
+
void failure.promise.catch(() => { });
|
|
48
|
+
let uploads;
|
|
49
|
+
let operationsRaw;
|
|
50
|
+
let fatal;
|
|
51
|
+
let released = false;
|
|
52
|
+
let requestSize = 0;
|
|
53
|
+
const seen = new Set();
|
|
54
|
+
const writes = [];
|
|
55
|
+
const validations = [];
|
|
56
|
+
const storage = [];
|
|
57
|
+
const readers = new Set();
|
|
58
|
+
const sniffers = new Set();
|
|
59
|
+
const sizes = new Set();
|
|
60
|
+
let cleanupError;
|
|
61
|
+
const source = Readable.fromWeb(request.body);
|
|
62
|
+
function fail(error) {
|
|
63
|
+
if (fatal || released)
|
|
64
|
+
return;
|
|
65
|
+
fatal = error;
|
|
66
|
+
ready.reject(error);
|
|
67
|
+
failure.reject(error);
|
|
68
|
+
for (const upload of uploads?.values() || [])
|
|
69
|
+
upload.reject(error);
|
|
70
|
+
for (const reject of sizes)
|
|
71
|
+
reject(error);
|
|
72
|
+
// Let parser callbacks and native Fetch EOF microtasks finish before cancellation.
|
|
73
|
+
setImmediate(() => {
|
|
74
|
+
source.destroy(error);
|
|
75
|
+
parser.destroy(error);
|
|
76
|
+
for (const sniffer of sniffers)
|
|
77
|
+
sniffer.destroy(error);
|
|
78
|
+
for (const { capacitor, ready } of storage) {
|
|
79
|
+
void ready.then(() => capacitor.destroy(error), () => { });
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
const onAbort = () => fail(new UploadRequestError('Request aborted during file upload.', 499));
|
|
84
|
+
request.signal?.addEventListener('abort', onAbort, { once: true });
|
|
85
|
+
dispose = async () => {
|
|
86
|
+
released = true;
|
|
87
|
+
request.signal?.removeEventListener('abort', onAbort);
|
|
88
|
+
const error = fatal || new Error('Upload execution has finished.');
|
|
89
|
+
for (const upload of uploads?.values() || [])
|
|
90
|
+
upload.reject(error);
|
|
91
|
+
for (const reject of sizes)
|
|
92
|
+
reject(error);
|
|
93
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
94
|
+
source.destroy();
|
|
95
|
+
parser.destroy();
|
|
96
|
+
for (const reader of readers)
|
|
97
|
+
reader.destroy(error);
|
|
98
|
+
for (const sniffer of sniffers)
|
|
99
|
+
sniffer.destroy();
|
|
100
|
+
await Promise.allSettled(storage.map(entry => entry.ready));
|
|
101
|
+
for (const { capacitor } of storage)
|
|
102
|
+
capacitor.destroy();
|
|
103
|
+
await Promise.all(storage.map(entry => entry.closed));
|
|
104
|
+
if (cleanupError)
|
|
105
|
+
throw cleanupError;
|
|
106
|
+
};
|
|
107
|
+
parser.on('field', (name, value, info) => {
|
|
108
|
+
if (fatal)
|
|
109
|
+
return;
|
|
110
|
+
try {
|
|
111
|
+
if (info.valueTruncated || Buffer.byteLength(value) > limits.maxFieldSize) {
|
|
112
|
+
throw new UploadRequestError('Multipart control field size limit exceeded.', 413);
|
|
113
|
+
}
|
|
114
|
+
if (name === 'operations' && operationsRaw === undefined && !uploads) {
|
|
115
|
+
operationsRaw = value;
|
|
116
|
+
}
|
|
117
|
+
else if (name === 'map' && operationsRaw !== undefined && !uploads) {
|
|
118
|
+
const prepared = prepareOperations(operationsRaw, value, limits.maxFiles);
|
|
119
|
+
uploads = prepared.uploads;
|
|
120
|
+
ready.resolve(prepared.operations);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
throw new UploadRequestError('Expected unique operations, then map, then file fields.');
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
fail(error);
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
parser.on('file', (name, file, info) => {
|
|
131
|
+
file.on('error', error => fail(error instanceof UploadRequestError ? error : new UploadRequestError('Incomplete multipart file.')));
|
|
132
|
+
file.on('limit', () => fail(new UploadRequestError('File size limit exceeded.', 413)));
|
|
133
|
+
if (fatal) {
|
|
134
|
+
file.resume();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (!uploads || seen.has(name) || name === 'operations' || name === 'map') {
|
|
138
|
+
file.resume();
|
|
139
|
+
fail(new UploadRequestError('Misordered or duplicate multipart file field.'));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
seen.add(name);
|
|
143
|
+
const upload = uploads.get(name);
|
|
144
|
+
if (!upload) {
|
|
145
|
+
file.resume();
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const filename = info.filename;
|
|
149
|
+
if (!filename) {
|
|
150
|
+
file.resume();
|
|
151
|
+
fail(new UploadRequestError('A non-empty file name is required.'));
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const capacitor = new WriteStream();
|
|
155
|
+
const storageReady = new Promise((resolve, reject) => {
|
|
156
|
+
capacitor.once('ready', resolve);
|
|
157
|
+
capacitor.once('error', reject);
|
|
158
|
+
});
|
|
159
|
+
void storageReady.catch(() => { });
|
|
160
|
+
storage.push({ capacitor, ready: storageReady, closed: new Promise(resolve => capacitor.once('close', resolve)) });
|
|
161
|
+
capacitor.on('error', error => {
|
|
162
|
+
if (released) {
|
|
163
|
+
if (error !== fatal)
|
|
164
|
+
cleanupError ||= error;
|
|
165
|
+
}
|
|
166
|
+
else
|
|
167
|
+
fail(error);
|
|
168
|
+
});
|
|
169
|
+
const size = Promise.withResolvers();
|
|
170
|
+
void size.promise.catch(() => { });
|
|
171
|
+
sizes.add(size.reject);
|
|
172
|
+
let bytes = 0;
|
|
173
|
+
let prefixBytes = 0;
|
|
174
|
+
const prefix = [];
|
|
175
|
+
let published = false;
|
|
176
|
+
const publish = () => {
|
|
177
|
+
if (published || fatal || released)
|
|
178
|
+
return;
|
|
179
|
+
published = true;
|
|
180
|
+
const validation = detectMimeType(Buffer.concat(prefix), settings.allowedTypes).then(mimetype => {
|
|
181
|
+
if (fatal || released)
|
|
182
|
+
return;
|
|
183
|
+
upload.resolve({
|
|
184
|
+
filename, encoding: info.encoding, mimetype, fileSize: size.promise,
|
|
185
|
+
abort: () => fail(new UploadRequestError('Multipart upload cancelled by a resolver.')),
|
|
186
|
+
createReadStream() {
|
|
187
|
+
if (fatal)
|
|
188
|
+
throw fatal;
|
|
189
|
+
if (released)
|
|
190
|
+
throw new Error('Upload streams are unavailable after execution finishes.');
|
|
191
|
+
const reader = capacitor.createReadStream();
|
|
192
|
+
// Cancellation must also be safe for a reader whose consumer never attached.
|
|
193
|
+
reader.on('error', () => { });
|
|
194
|
+
readers.add(reader);
|
|
195
|
+
reader.once('close', () => readers.delete(reader));
|
|
196
|
+
return reader;
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
}, error => fail(new UploadRequestError(`File type detection failed: ${error.message}`)));
|
|
200
|
+
validations.push(validation);
|
|
201
|
+
};
|
|
202
|
+
const sniffer = new Transform({
|
|
203
|
+
transform(chunk, _encoding, callback) {
|
|
204
|
+
bytes += chunk.length;
|
|
205
|
+
if (bytes > limits.maxFileSize) {
|
|
206
|
+
callback(new UploadRequestError('File size limit exceeded.', 413));
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (prefixBytes < 4100) {
|
|
210
|
+
const slice = chunk.subarray(0, 4100 - prefixBytes);
|
|
211
|
+
prefix.push(Buffer.from(slice));
|
|
212
|
+
prefixBytes += slice.length;
|
|
213
|
+
}
|
|
214
|
+
if (prefixBytes === 4100)
|
|
215
|
+
publish();
|
|
216
|
+
callback(null, chunk);
|
|
217
|
+
},
|
|
218
|
+
flush(callback) { publish(); callback(); },
|
|
219
|
+
});
|
|
220
|
+
sniffers.add(sniffer);
|
|
221
|
+
sniffer.on('error', fail);
|
|
222
|
+
const write = finished(capacitor, { cleanup: true }).then(() => { size.resolve(bytes); }, error => {
|
|
223
|
+
size.reject(error);
|
|
224
|
+
fail(error);
|
|
225
|
+
});
|
|
226
|
+
writes.push(write);
|
|
227
|
+
file.pipe(sniffer).pipe(capacitor);
|
|
228
|
+
});
|
|
229
|
+
parser.on('fieldsLimit', () => fail(new UploadRequestError('Only operations and map control fields are allowed.')));
|
|
230
|
+
parser.on('filesLimit', () => fail(new UploadRequestError('File count limit exceeded.', 413)));
|
|
231
|
+
parser.on('error', error => fail(error instanceof UploadRequestError ? error : new UploadRequestError('Malformed multipart request.')));
|
|
232
|
+
parser.once('finish', () => {
|
|
233
|
+
if (!uploads) {
|
|
234
|
+
fail(new UploadRequestError('Missing operations or map multipart field.'));
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
for (const [name, upload] of uploads) {
|
|
238
|
+
if (!seen.has(name))
|
|
239
|
+
upload.reject(new Error('File missing in the request.'));
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
const meter = new Transform({ transform(chunk, _encoding, callback) {
|
|
243
|
+
requestSize += chunk.length;
|
|
244
|
+
callback(requestSize > limits.maxRequestSize ? new UploadRequestError('Request size limit exceeded.', 413) : null, chunk);
|
|
245
|
+
} });
|
|
246
|
+
const received = pipeline(source, meter, parser).catch(error => {
|
|
247
|
+
fail(error instanceof UploadRequestError ? error : new UploadRequestError('Incomplete multipart request.'));
|
|
248
|
+
});
|
|
249
|
+
if (request.signal?.aborted)
|
|
250
|
+
onAbort();
|
|
251
|
+
const operations = await ready.promise;
|
|
252
|
+
if (fatal)
|
|
253
|
+
throw fatal;
|
|
254
|
+
const response = await Promise.race([executeOperations(operations, contextValueInput, server), failure.promise]);
|
|
255
|
+
await Promise.race([received.then(async () => {
|
|
256
|
+
await Promise.all(writes);
|
|
257
|
+
await Promise.all(validations);
|
|
258
|
+
}), failure.promise]);
|
|
259
|
+
if (fatal)
|
|
260
|
+
throw fatal;
|
|
261
|
+
return response;
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
return uploadErrorResponse(error);
|
|
265
|
+
}
|
|
266
|
+
finally {
|
|
267
|
+
await dispose?.();
|
|
268
|
+
}
|
|
269
|
+
}
|