@astratra/core 1.2.0 → 1.3.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/src/upload.js ADDED
@@ -0,0 +1,469 @@
1
+ /*
2
+ * Le téléversement de fichiers (multipart/form-data, RFC 7578), lu au fil du flux et gardé en mémoire, sans multer ni
3
+ * busboy. Les mêmes usages que multer en mémoire : .single(nom), .array(nom, max), .fields([...]), .none(), .any() ;
4
+ * req.file / req.files { fieldname, originalname, encoding, mimetype, size, buffer } et req.body ; fileFilter ; les
5
+ * mêmes codes d'erreur (LIMIT_FILE_SIZE, LIMIT_FILE_COUNT, LIMIT_UNEXPECTED_FILE…).
6
+ *
7
+ * Différences voulues :
8
+ * - des limites par défaut (multer n'en avait aucune) : 10 Mio par fichier, 10 fichiers, 100 champs, 1 Mio par champ,
9
+ * 200 parties, 50 Mio au total ;
10
+ * - un nom de champ « __proto__ », « constructor » ou « prototype » est refusé (pollution de prototype) ;
11
+ * - le nom du fichier est lu en UTF-8 (filename*= compris), sans caractères de contrôle ; `safeName` en donne une
12
+ * forme sans chemin, utilisable sur un disque ;
13
+ * - un corps interrompu, une frontière absente ou des en-têtes trop longs sont des erreurs 400, jamais une attente sans fin.
14
+ * Le type annoncé par le client (`mimetype`) n'est pas une preuve : `detectFileType(buffer)` lit les premiers octets.
15
+ */
16
+
17
+ const CRLF = Buffer.from('\r\n');
18
+ const HEADER_END = Buffer.from('\r\n\r\n');
19
+ const FORBIDDEN_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
20
+
21
+ const DEFAULT_LIMITS = {
22
+ fileSize: 10 * 1024 * 1024,
23
+ files: 10,
24
+ fields: 100,
25
+ fieldSize: 1024 * 1024,
26
+ fieldNameSize: 200,
27
+ parts: 200,
28
+ headerSize: 8 * 1024,
29
+ headerPairs: 20,
30
+ totalSize: 50 * 1024 * 1024,
31
+ };
32
+
33
+ const MESSAGES = {
34
+ LIMIT_PART_COUNT: 'Too many parts',
35
+ LIMIT_FILE_SIZE: 'File too large',
36
+ LIMIT_FILE_COUNT: 'Too many files',
37
+ LIMIT_FIELD_KEY: 'Field name too long',
38
+ LIMIT_FIELD_VALUE: 'Field value too long',
39
+ LIMIT_FIELD_COUNT: 'Too many fields',
40
+ LIMIT_UNEXPECTED_FILE: 'Unexpected field',
41
+ LIMIT_TOTAL_SIZE: 'Request body too large',
42
+ MISSING_FIELD_NAME: 'Field name missing',
43
+ FIELD_NAME_FORBIDDEN: 'Field name not allowed',
44
+ MALFORMED: 'Malformed multipart body',
45
+ UNEXPECTED_END: 'Unexpected end of form',
46
+ HEADER_TOO_LARGE: 'Part headers too large',
47
+ };
48
+
49
+ class UploadError extends Error {
50
+ constructor(code, field) {
51
+ super(MESSAGES[code] || code);
52
+ this.name = 'UploadError';
53
+ this.code = code;
54
+ this.field = field;
55
+ this.status = code === 'LIMIT_FILE_SIZE' || code === 'LIMIT_TOTAL_SIZE' ? 413 : 400;
56
+ this.statusCode = this.status;
57
+ }
58
+ }
59
+
60
+ /** La frontière d'un Content-Type multipart/form-data (RFC 2046 : 1 à 70 caractères), ou null. */
61
+ function boundaryOf(contentType) {
62
+ if (typeof contentType !== 'string' || !/^multipart\/form-data\s*(;|$)/i.test(contentType)) return null;
63
+ for (const part of contentType.split(';').slice(1)) {
64
+ const eq = part.indexOf('=');
65
+ if (eq < 0) continue;
66
+ if (part.slice(0, eq).trim().toLowerCase() !== 'boundary') continue;
67
+ let value = part.slice(eq + 1).trim();
68
+ if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) value = value.slice(1, -1);
69
+ if (value.length >= 1 && value.length <= 70 && /^[0-9A-Za-z'()+_,\-./:=? ]*[0-9A-Za-z'()+_,\-./:=?]$/.test(value)) return value;
70
+ return '';
71
+ }
72
+ return '';
73
+ }
74
+
75
+ /** Les paramètres d'un en-tête (« form-data; name="a"; filename*=UTF-8''%C3%A9.txt »), lus sans expression ambiguë. */
76
+ function parseParameters(value) {
77
+ const params = Object.create(null);
78
+ let i = value.indexOf(';');
79
+ const type = (i < 0 ? value : value.slice(0, i)).trim().toLowerCase();
80
+ while (i >= 0 && i < value.length) {
81
+ i += 1;
82
+ while (value[i] === ' ' || value[i] === '\t') i += 1;
83
+ const eq = value.indexOf('=', i);
84
+ if (eq < 0) break;
85
+ const key = value.slice(i, eq).trim().toLowerCase();
86
+ let j = eq + 1;
87
+ let text = '';
88
+ if (value[j] === '"') {
89
+ j += 1;
90
+ // Comme les navigateurs et busboy : la barre oblique inverse est un caractère comme un autre (un nom de fichier
91
+ // Windows « C:\dossier\a.txt »), sauf devant un guillemet.
92
+ while (j < value.length && value[j] !== '"') {
93
+ if (value[j] === '\\' && value[j + 1] === '"') j += 1;
94
+ text += value[j];
95
+ j += 1;
96
+ }
97
+ j += 1;
98
+ // Après une valeur entre guillemets : seulement des espaces, puis « ; » ou la fin.
99
+ while (value[j] === ' ' || value[j] === '\t') j += 1;
100
+ if (j < value.length && value[j] !== ';') throw new UploadError('MALFORMED');
101
+ } else {
102
+ const end = value.indexOf(';', j);
103
+ text = (end < 0 ? value.slice(j) : value.slice(j, end)).trim();
104
+ j = end < 0 ? value.length : end;
105
+ }
106
+ if (key && !(key in params)) params[key] = text;
107
+ i = value.indexOf(';', j);
108
+ }
109
+ return { type, params };
110
+ }
111
+
112
+ /** filename*=UTF-8''… (RFC 5987), sinon filename="…", lu en UTF-8 ; sans caractères de contrôle. */
113
+ function fileNameOf(params) {
114
+ let name;
115
+ const extended = params['filename*'];
116
+ if (extended !== undefined) {
117
+ const match = /^([\w!#$%&+^`{}~-]+)'[\w-]*'(.*)$/.exec(extended);
118
+ if (match) {
119
+ try {
120
+ name = match[1].toLowerCase() === 'utf-8' ? decodeURIComponent(match[2]) : Buffer.from(unescape(match[2]), 'latin1').toString('latin1');
121
+ } catch {
122
+ name = undefined;
123
+ }
124
+ }
125
+ }
126
+ if (name === undefined && params.filename !== undefined) name = Buffer.from(params.filename, 'latin1').toString('utf8');
127
+ if (name === undefined) return undefined;
128
+ // eslint-disable-next-line no-control-regex
129
+ return name.replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 1024);
130
+ }
131
+
132
+ /** Un nom de fichier sans chemin ni caractère réservé, utilisable sur un disque (« ../../a.php » → « a.php »). */
133
+ function safeFileName(name) {
134
+ const base = String(name || '').split(/[\\/]/).pop().normalize('NFC');
135
+ const cleaned = base
136
+ // eslint-disable-next-line no-control-regex
137
+ .replace(/[<>:"|?*\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069]/g, '')
138
+ .replace(/^[.\s]+|[.\s]+$/g, '')
139
+ .slice(0, 200);
140
+ return /^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i.test(cleaned) || !cleaned ? `fichier${cleaned ? `-${cleaned}` : ''}` : cleaned;
141
+ }
142
+
143
+ /**
144
+ * Lit un corps multipart depuis le flux `req`. `accept(file)` dit si un fichier est attendu (sinon
145
+ * LIMIT_UNEXPECTED_FILE) ; `filter(file)` (promesse) applique le fileFilter du projet.
146
+ */
147
+ function parseMultipart(req, { boundary, limits, accept, filter }) {
148
+ return new Promise((resolve, reject) => {
149
+ const delimiter = Buffer.from(`\r\n--${boundary}`);
150
+ const first = Buffer.from(`--${boundary}`);
151
+ const body = {};
152
+ const files = [];
153
+ let carry = Buffer.alloc(0);
154
+ let state = 'preamble';
155
+ let part = null;
156
+ let parts = 0;
157
+ let fieldCount = 0;
158
+ let fileCount = 0;
159
+ let total = 0;
160
+ let settled = false;
161
+ let pending = Promise.resolve();
162
+
163
+ const cleanup = () => {
164
+ req.removeListener('data', onData);
165
+ req.removeListener('end', onEnd);
166
+ req.removeListener('error', onError);
167
+ req.removeListener('aborted', onAborted);
168
+ req.removeListener('close', onClose);
169
+ };
170
+ const fail = (error) => {
171
+ if (settled) return;
172
+ settled = true;
173
+ cleanup();
174
+ // Le reste du corps est lu sans être gardé, jusqu'à la limite totale, pour que la réponse puisse partir ;
175
+ // au-delà, la connexion est coupée.
176
+ let drained = 0;
177
+ req.on('data', (chunk) => {
178
+ drained += chunk.length;
179
+ if (drained > limits.totalSize) req.destroy();
180
+ });
181
+ req.on('error', () => {});
182
+ req.resume();
183
+ reject(error);
184
+ };
185
+ const succeed = () => {
186
+ if (settled) return;
187
+ settled = true;
188
+ cleanup();
189
+ resolve({ body, files });
190
+ };
191
+
192
+ const addField = (name, value) => {
193
+ if (Object.prototype.hasOwnProperty.call(body, name)) body[name] = Array.isArray(body[name]) ? [...body[name], value] : [body[name], value];
194
+ else body[name] = value;
195
+ };
196
+
197
+ const startPart = (headerText) => {
198
+ parts += 1;
199
+ if (parts > limits.parts) throw new UploadError('LIMIT_PART_COUNT');
200
+ const lines = headerText.split('\r\n').filter(Boolean);
201
+ if (lines.length > limits.headerPairs) throw new UploadError('HEADER_TOO_LARGE');
202
+ const headers = Object.create(null);
203
+ for (const line of lines) {
204
+ const colon = line.indexOf(':');
205
+ if (colon <= 0) throw new UploadError('MALFORMED');
206
+ // Un nom d'en-tête est un mot permis (RFC 9110, « token ») : pas d'espace, pas d'octet invisible.
207
+ const headerName = line.slice(0, colon);
208
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(headerName)) throw new UploadError('MALFORMED');
209
+ // Un en-tête répété (deux Content-Disposition) laisserait deux lectures possibles de la même partie : refusé.
210
+ if (headerName.toLowerCase() in headers) throw new UploadError('MALFORMED');
211
+ headers[headerName.toLowerCase()] = line.slice(colon + 1).trim();
212
+ }
213
+ const disposition = parseParameters(headers['content-disposition'] || '');
214
+ if (disposition.type !== 'form-data') throw new UploadError('MALFORMED');
215
+ const name = disposition.params.name !== undefined ? Buffer.from(disposition.params.name, 'latin1').toString('utf8') : undefined;
216
+ if (!name) throw new UploadError('MISSING_FIELD_NAME');
217
+ if (Buffer.byteLength(name) > limits.fieldNameSize) throw new UploadError('LIMIT_FIELD_KEY', name);
218
+ if (FORBIDDEN_NAMES.has(name)) throw new UploadError('FIELD_NAME_FORBIDDEN', name);
219
+ const filename = fileNameOf(disposition.params);
220
+ if (filename === undefined) {
221
+ fieldCount += 1;
222
+ if (fieldCount > limits.fields) throw new UploadError('LIMIT_FIELD_COUNT', name);
223
+ return { kind: 'field', name, chunks: [], size: 0 };
224
+ }
225
+ // Un nom de fichier vide (un champ de fichier laissé vide par le navigateur) : la partie est ignorée, comme multer.
226
+ if (filename === '') return { kind: 'skip', size: 0 };
227
+ fileCount += 1;
228
+ if (fileCount > limits.files) throw new UploadError('LIMIT_FILE_COUNT', name);
229
+ // Comme multer : le nom sans son chemin (« ../../etc/passwd » → « passwd »), et le type text/plain quand la partie
230
+ // n'en annonce pas de lisible (RFC 7578).
231
+ const baseName = filename.split(/[\\/]/).pop();
232
+ const announced = parseParameters(headers['content-type'] || '').type;
233
+ const file = {
234
+ fieldname: name,
235
+ originalname: baseName,
236
+ safeName: safeFileName(baseName),
237
+ encoding: (headers['content-transfer-encoding'] || '7bit').toLowerCase(),
238
+ mimetype: /^[!#$%&'*+\-.^_`|~0-9a-z]{1,127}\/[!#$%&'*+\-.^_`|~0-9a-z]{1,127}$/.test(announced) ? announced : 'text/plain',
239
+ };
240
+ if (!accept(file)) throw new UploadError('LIMIT_UNEXPECTED_FILE', name);
241
+ return { kind: 'file', file, chunks: [], size: 0, accepted: null };
242
+ };
243
+
244
+ const appendData = (data) => {
245
+ if (!data.length || part.kind === 'skip') return;
246
+ part.size += data.length;
247
+ if (part.kind === 'field') {
248
+ if (part.size > limits.fieldSize) throw new UploadError('LIMIT_FIELD_VALUE', part.name);
249
+ } else if (part.size > limits.fileSize) {
250
+ throw new UploadError('LIMIT_FILE_SIZE', part.file.fieldname);
251
+ }
252
+ part.chunks.push(data);
253
+ };
254
+
255
+ const endPart = () => {
256
+ if (part.kind === 'skip') {
257
+ part = null;
258
+ return;
259
+ }
260
+ if (part.kind === 'field') {
261
+ addField(part.name, Buffer.concat(part.chunks).toString('utf8'));
262
+ } else {
263
+ const done = part;
264
+ done.file.buffer = Buffer.concat(done.chunks);
265
+ done.file.size = done.file.buffer.length;
266
+ // Le filtre du projet (fileFilter) décide une fois le fichier lu ; un refus sans erreur le laisse de côté.
267
+ pending = pending.then(async () => {
268
+ const keep = await filter(done.file);
269
+ if (keep) files.push(done.file);
270
+ });
271
+ }
272
+ part = null;
273
+ };
274
+
275
+ const consume = () => {
276
+ for (;;) {
277
+ if (state === 'preamble') {
278
+ const at = carry.indexOf(first);
279
+ if (at < 0) {
280
+ if (carry.length > limits.headerSize + first.length) throw new UploadError('MALFORMED');
281
+ return;
282
+ }
283
+ carry = carry.subarray(at + first.length);
284
+ state = 'afterBoundary';
285
+ } else if (state === 'afterBoundary') {
286
+ if (carry.length < 2) return;
287
+ if (carry[0] === 0x2d && carry[1] === 0x2d) {
288
+ state = 'done';
289
+ carry = Buffer.alloc(0);
290
+ return;
291
+ }
292
+ // Espaces permis avant la fin de ligne (RFC 2046, « transport padding »).
293
+ const eol = carry.indexOf(CRLF);
294
+ if (eol < 0) {
295
+ if (carry.length > 1024) throw new UploadError('MALFORMED');
296
+ return;
297
+ }
298
+ if (carry.subarray(0, eol).toString('latin1').trim() !== '') throw new UploadError('MALFORMED');
299
+ carry = carry.subarray(eol + 2);
300
+ state = 'headers';
301
+ } else if (state === 'headers') {
302
+ const end = carry.indexOf(HEADER_END);
303
+ const blank = carry.length >= 2 && carry[0] === 0x0d && carry[1] === 0x0a;
304
+ if (blank) {
305
+ part = startPart('');
306
+ carry = carry.subarray(2);
307
+ state = 'body';
308
+ continue;
309
+ }
310
+ if (end < 0) {
311
+ if (carry.length > limits.headerSize) throw new UploadError('HEADER_TOO_LARGE');
312
+ return;
313
+ }
314
+ if (end > limits.headerSize) throw new UploadError('HEADER_TOO_LARGE');
315
+ part = startPart(carry.subarray(0, end).toString('latin1'));
316
+ carry = carry.subarray(end + 4);
317
+ state = 'body';
318
+ } else if (state === 'body') {
319
+ const at = carry.indexOf(delimiter);
320
+ if (at < 0) {
321
+ // Les derniers octets peuvent être le début de la frontière : ils attendent le morceau suivant.
322
+ const keep = Math.min(carry.length, delimiter.length - 1);
323
+ appendData(carry.subarray(0, carry.length - keep));
324
+ carry = Buffer.from(carry.subarray(carry.length - keep));
325
+ return;
326
+ }
327
+ appendData(carry.subarray(0, at));
328
+ endPart();
329
+ carry = carry.subarray(at + delimiter.length);
330
+ state = 'afterBoundary';
331
+ } else {
332
+ // Après la dernière frontière : l'épilogue n'est pas gardé.
333
+ carry = Buffer.alloc(0);
334
+ return;
335
+ }
336
+ }
337
+ };
338
+
339
+ function onData(chunk) {
340
+ if (settled) return;
341
+ total += chunk.length;
342
+ if (total > limits.totalSize) return fail(new UploadError('LIMIT_TOTAL_SIZE'));
343
+ carry = carry.length ? Buffer.concat([carry, chunk]) : chunk;
344
+ try {
345
+ consume();
346
+ } catch (error) {
347
+ fail(error instanceof UploadError ? error : new UploadError('MALFORMED'));
348
+ }
349
+ }
350
+ function onEnd() {
351
+ if (settled) return;
352
+ if (state !== 'done') return fail(new UploadError(state === 'preamble' && total === 0 ? 'MALFORMED' : 'UNEXPECTED_END'));
353
+ cleanup();
354
+ pending.then(succeed, (error) => fail(error));
355
+ }
356
+ function onError() {
357
+ fail(new UploadError('UNEXPECTED_END'));
358
+ }
359
+ function onAborted() {
360
+ fail(new UploadError('UNEXPECTED_END'));
361
+ }
362
+ function onClose() {
363
+ if (!settled && state !== 'done') fail(new UploadError('UNEXPECTED_END'));
364
+ }
365
+ req.on('data', onData);
366
+ req.on('end', onEnd);
367
+ req.on('error', onError);
368
+ req.on('aborted', onAborted);
369
+ req.on('close', onClose);
370
+ });
371
+ }
372
+
373
+ /**
374
+ * @param {object} [options]
375
+ * @param {object} [options.limits] fileSize, files, fields, fieldSize, fieldNameSize, parts, headerSize, headerPairs, totalSize.
376
+ * @param {Function} [options.fileFilter] (req, file, cb) comme multer, ou (req, file) => booléen / promesse.
377
+ */
378
+ function createUpload({ limits: userLimits = {}, fileFilter } = {}) {
379
+ const limits = { ...DEFAULT_LIMITS, ...userLimits };
380
+ for (const [key, value] of Object.entries(limits)) {
381
+ if (!Number.isFinite(value) || value < 0) throw new TypeError(`createUpload: limits.${key} must be a number of zero or more.`);
382
+ }
383
+
384
+ const runFilter = (req, file) =>
385
+ new Promise((resolve, reject) => {
386
+ if (!fileFilter) return resolve(true);
387
+ let done = false;
388
+ const cb = (error, keep) => {
389
+ if (done) return;
390
+ done = true;
391
+ if (error) reject(error);
392
+ else resolve(Boolean(keep));
393
+ };
394
+ try {
395
+ const out = fileFilter(req, file, cb);
396
+ if (fileFilter.length < 3) Promise.resolve(out).then((keep) => cb(null, keep), cb);
397
+ } catch (error) {
398
+ cb(error);
399
+ }
400
+ });
401
+
402
+ const middleware = (mode, expected) => async (req, res, next) => {
403
+ const boundary = boundaryOf(req.headers && req.headers['content-type']);
404
+ // Pas du multipart : la requête passe telle quelle (comme multer).
405
+ if (boundary === null) return next();
406
+ if (!boundary) return next(new UploadError('MALFORMED'));
407
+ const counts = new Map();
408
+ const accept = (file) => {
409
+ if (mode === 'none') return false;
410
+ if (mode === 'any') return true;
411
+ const max = expected.get(file.fieldname);
412
+ if (max === undefined) return false;
413
+ const seen = (counts.get(file.fieldname) || 0) + 1;
414
+ counts.set(file.fieldname, seen);
415
+ return seen <= max;
416
+ };
417
+ try {
418
+ const { body, files } = await parseMultipart(req, { boundary, limits, accept, filter: (file) => runFilter(req, file) });
419
+ req.body = body;
420
+ if (mode === 'single') req.file = files[0];
421
+ else if (mode === 'fields') {
422
+ req.files = {};
423
+ for (const file of files) (req.files[file.fieldname] ||= []).push(file);
424
+ } else if (mode !== 'none') req.files = files;
425
+ return next();
426
+ } catch (error) {
427
+ return next(error);
428
+ }
429
+ };
430
+
431
+ return {
432
+ single: (name) => middleware('single', new Map([[name, 1]])),
433
+ array: (name, maxCount = Infinity) => middleware('array', new Map([[name, maxCount]])),
434
+ fields: (list) => middleware('fields', new Map(list.map(({ name, maxCount = Infinity }) => [name, maxCount]))),
435
+ none: () => middleware('none', new Map()),
436
+ any: () => middleware('any', new Map()),
437
+ };
438
+ }
439
+
440
+ /**
441
+ * Le vrai type d'un fichier, d'après ses premiers octets (le type annoncé par le client n'est pas une preuve). Rend
442
+ * { ext, mime } ou null.
443
+ */
444
+ function detectFileType(buffer) {
445
+ if (!Buffer.isBuffer(buffer) || buffer.length < 4) return null;
446
+ const b = buffer;
447
+ const ascii = (start, end) => b.subarray(start, end).toString('latin1');
448
+ if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' };
449
+ if (b.length >= 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' };
450
+ if (ascii(0, 6) === 'GIF87a' || ascii(0, 6) === 'GIF89a') return { ext: 'gif', mime: 'image/gif' };
451
+ if (b.length >= 12 && ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' };
452
+ if (b.length >= 12 && ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WAVE') return { ext: 'wav', mime: 'audio/wav' };
453
+ if (ascii(0, 5) === '%PDF-') return { ext: 'pdf', mime: 'application/pdf' };
454
+ if (b.length >= 12 && ascii(4, 8) === 'ftyp') {
455
+ const brand = ascii(8, 12);
456
+ if (brand === 'avif' || brand === 'avis') return { ext: 'avif', mime: 'image/avif' };
457
+ if (['heic', 'heix', 'hevc', 'hevx', 'mif1', 'msf1', 'heim', 'heis'].includes(brand)) return { ext: 'heic', mime: 'image/heic' };
458
+ if (brand === 'qt ') return { ext: 'mov', mime: 'video/quicktime' };
459
+ if (brand.startsWith('M4A')) return { ext: 'm4a', mime: 'audio/mp4' };
460
+ return { ext: 'mp4', mime: 'video/mp4' };
461
+ }
462
+ if (b.readUInt32BE(0) === 0x1a45dfa3) return { ext: 'webm', mime: 'video/webm' };
463
+ if (ascii(0, 4) === 'OggS') return { ext: 'ogg', mime: 'audio/ogg' };
464
+ if (ascii(0, 3) === 'ID3' || (b[0] === 0xff && (b[1] & 0xe0) === 0xe0)) return { ext: 'mp3', mime: 'audio/mpeg' };
465
+ if (b[0] === 0x50 && b[1] === 0x4b && (b[2] === 0x03 || b[2] === 0x05) && (b[3] === 0x04 || b[3] === 0x06)) return { ext: 'zip', mime: 'application/zip' };
466
+ return null;
467
+ }
468
+
469
+ module.exports = { createUpload, detectFileType, safeFileName, UploadError, UPLOAD_DEFAULT_LIMITS: DEFAULT_LIMITS };
@@ -1,4 +1,4 @@
1
- const { validationResult } = require('express-validator');
1
+ const { validationResult } = require('./validation');
2
2
  const apiResponse = require('./apiResponse');
3
3
 
4
4
  function validateMiddleware(validations = []) {