Repository navigation
Expand file tree
/
Copy pathupload.js
More file actions
1594 lines (1442 loc) · 55.4 KB
/
Copy pathupload.js
File metadata and controls
1594 lines (1442 loc) · 55.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module upload
* @description Byte-bounded `multipart/form-data` parser, path-traversal/bidi/device-safe
* filename sanitizer, and magic-byte MIME verifier (`INV-LEGO-01`, `INV-LEGO-18`) for `@krusch/toolkit`.
* Zero third-party dependencies; linear O(N) `Buffer.indexOf` framing scan.
*/
import { okEnvelope, errorEnvelope } from './http.js';
const DEFAULT_FALLBACK_FILENAME = 'upload.bin';
const DEFAULT_MAX_FILENAME_LENGTH = 128;
const MIN_FILENAME_LENGTH = 1;
const MAX_PRESERVED_EXT_LENGTH = 16;
const DEFAULT_MAX_TOTAL_BYTES = 10_485_760; // 10 MiB
const DEFAULT_MAX_FILE_BYTES = 5_242_880; // 5 MiB
const DEFAULT_MAX_FILES = 5;
const DEFAULT_MAX_FIELDS = 32;
const DEFAULT_MAX_FIELD_BYTES = 65_536; // 64 KiB
const MAX_PART_HEADER_BYTES = 16_384; // 16 KiB
const CRLF_BYTES = Buffer.from('\r\n', 'ascii');
const DOUBLE_CRLF_BYTES = Buffer.from('\r\n\r\n', 'ascii');
const UNSAFE_FILENAME_CHARS_RE = /[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069\ufeff<>:"|?*]+/g;
const LEADING_UNSAFE_RE = /^[.\s-]+/;
const TRAILING_UNSAFE_RE = /[.\s]+$/;
const WINDOWS_RESERVED_STEM_RE = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
const VALID_BOUNDARY_CHARS_RE = /^[A-Za-z0-9'()+_,\-./:=?!#$%&*^`{|}~ ]+$/;
const FORBIDDEN_FIELD_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
const MIME_ALIASES = new Map([
['image/jpg', 'image/jpeg'],
['image/pjpeg', 'image/jpeg'],
['audio/wave', 'audio/wav'],
['audio/x-wav', 'audio/wav'],
['audio/vnd.wave', 'audio/wav'],
['audio/mp3', 'audio/mpeg'],
['audio/x-mp3', 'audio/mpeg'],
['audio/mpeg3', 'audio/mpeg'],
['audio/x-mpeg-3', 'audio/mpeg'],
['audio/x-ogg', 'audio/ogg'],
['application/ogg', 'audio/ogg'],
['application/x-zip-compressed', 'application/zip'],
['application/x-pdf', 'application/pdf'],
]);
const MAGIC_REQUIRED_MIMES = new Set([
'application/pdf',
'image/png',
'image/jpeg',
'image/gif',
'image/webp',
'audio/wav',
'audio/mpeg',
'audio/ogg',
'audio/webm',
'video/webm',
'application/zip',
]);
/**
* Convert a `Uint8Array`, `Buffer`, or `ArrayBuffer` into a `Uint8Array` view, or `null` otherwise.
*
* @param {unknown} bytes - Candidate binary input
* @returns {Uint8Array|null}
*/
function toByteView(bytes) {
if (bytes instanceof Uint8Array) {
return bytes;
}
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(bytes)) {
return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
}
if (
bytes instanceof ArrayBuffer ||
Object.prototype.toString.call(bytes) === '[object ArrayBuffer]'
) {
return new Uint8Array(bytes);
}
return null;
}
/**
* Normalize a raw MIME string by stripping parameters and mapping common aliases to canonical types.
*
* @param {unknown} rawMime - Declared or pattern MIME string
* @returns {string}
*/
function canonicalizeMime(rawMime) {
const base = String(rawMime ?? '')
.split(';')[0]
.trim()
.toLowerCase();
if (!base) return '';
return MIME_ALIASES.get(base) || base;
}
/**
* Determine whether a declared MIME type and magic-sniffed MIME type represent compatible formats.
*
* @param {string} declared - Lowercased base declared MIME
* @param {string} detected - Magic-sniffed canonical MIME
* @returns {boolean}
*/
function areMimesEquivalent(declared, detected) {
if (!declared || !detected) return false;
const canonDeclared = canonicalizeMime(declared);
const canonDetected = canonicalizeMime(detected);
if (canonDeclared === canonDetected) return true;
if (
(canonDeclared === 'audio/webm' && canonDetected === 'video/webm') ||
(canonDeclared === 'video/webm' && canonDetected === 'audio/webm')
) {
return true;
}
return false;
}
/**
* Determine whether a filename or stem resolves to a Windows reserved DOS device name
* (`CON`, `PRN`, `AUX`, `NUL`, `COM1..9`, `LPT1..9`), including multi-dot stems (`CON.a`)
* and trailing spaces/dots.
*
* @param {string} name - Candidate stem or filename
* @returns {boolean}
*/
function isWindowsReservedFilenameStem(name) {
if (!name) return false;
const trimmed = name.replace(TRAILING_UNSAFE_RE, '');
if (!trimmed) return false;
const firstDotSegment = trimmed.split('.')[0].replace(TRAILING_UNSAFE_RE, '');
return WINDOWS_RESERVED_STEM_RE.test(trimmed) || WINDOWS_RESERVED_STEM_RE.test(firstDotSegment);
}
/**
* Core single-pass filename sanitizer without fallback recursion.
*
* @param {string} candidate - Candidate raw filename
* @param {number} safeMaxLen - Clamped maximum length (`>= 8`)
* @returns {string} Sanitized filename or `''` if empty/invalid
*/
function sanitizeFilenameCore(candidate, safeMaxLen) {
if (typeof candidate !== 'string' || candidate.length === 0) return '';
const slashNormalized = candidate.replace(/\\/g, '/');
const lastSlash = slashNormalized.lastIndexOf('/');
const baseSegment = lastSlash >= 0 ? slashNormalized.slice(lastSlash + 1) : slashNormalized;
if (!baseSegment) return '';
let cleaned = baseSegment
.replace(UNSAFE_FILENAME_CHARS_RE, '')
.replace(LEADING_UNSAFE_RE, '')
.replace(TRAILING_UNSAFE_RE, '')
.replace(/\s+/g, '_')
.replace(LEADING_UNSAFE_RE, '')
.replace(TRAILING_UNSAFE_RE, '');
if (!cleaned) return '';
const lastDot = cleaned.lastIndexOf('.');
let stem = lastDot > 0 ? cleaned.slice(0, lastDot) : cleaned;
const ext = lastDot > 0 ? cleaned.slice(lastDot) : '';
if (!stem) return '';
if (isWindowsReservedFilenameStem(stem)) {
stem = `_${stem}`;
}
const reassembled = `${stem}${ext}`;
if (reassembled.length <= safeMaxLen) {
return reassembled;
}
if (
ext.length > 1 &&
ext.length <= MAX_PRESERVED_EXT_LENGTH &&
safeMaxLen - ext.length >= 1
) {
const stemBudget = safeMaxLen - ext.length;
let truncatedStem = stem.slice(0, stemBudget).replace(TRAILING_UNSAFE_RE, '');
if (!truncatedStem) return '';
if (isWindowsReservedFilenameStem(truncatedStem)) {
if (stemBudget <= 1) return '';
const shorterStem = stem.slice(0, stemBudget - 1).replace(TRAILING_UNSAFE_RE, '');
if (!shorterStem) return '';
truncatedStem = `_${shorterStem}`;
}
return `${truncatedStem}${ext}`;
}
let truncated = reassembled.slice(0, safeMaxLen).replace(TRAILING_UNSAFE_RE, '');
if (!truncated) return '';
if (isWindowsReservedFilenameStem(truncated)) {
if (safeMaxLen < 2) return '';
const shorter = reassembled.slice(0, safeMaxLen - 1).replace(TRAILING_UNSAFE_RE, '');
if (!shorter) return '';
truncated = `_${shorter}`;
}
return truncated;
}
const UNSAFE_FILENAME_CHAR_SINGLE_RE = /[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069\ufeff<>:"|?*]/;
/**
* Validate and normalize a caller-supplied fallback filename, returning `''` if empty or unsafe.
*
* @param {unknown} rawFallback - Caller fallback option
* @param {number} safeMaxLen - Clamped maximum length
* @returns {string}
*/
function resolveSafeFallback(rawFallback, safeMaxLen) {
if (typeof rawFallback !== 'string' || rawFallback.length === 0) return '';
if (/[\/\\]/.test(rawFallback)) return '';
if (UNSAFE_FILENAME_CHAR_SINGLE_RE.test(rawFallback)) return '';
if (LEADING_UNSAFE_RE.test(rawFallback)) return '';
const trimmed = rawFallback.replace(TRAILING_UNSAFE_RE, '');
if (!trimmed) return '';
if (isWindowsReservedFilenameStem(trimmed)) return '';
return sanitizeFilenameCore(rawFallback, safeMaxLen);
}
/**
* Sanitize an untrusted upload filename against directory traversal, NUL/control/bidi characters,
* dotfiles, Windows reserved device names, and excessive lengths (`INV-LEGO-18`).
*
* @param {string} [rawFilename=''] - Raw untrusted filename
* @param {object} [options={}] - Sanitizer options
* @param {string} [options.fallback='upload.bin'] - Fallback filename when input is empty or unsafe
* @param {number} [options.maxLength=128] - Maximum output length (`>= 1`)
* @returns {string}
*/
export function sanitizeUploadFilename(
rawFilename = '',
options = {}
) {
const opts = options && typeof options === 'object' ? options : {};
const safeMaxLen =
typeof opts.maxLength === 'number' &&
Number.isFinite(opts.maxLength) &&
Math.trunc(opts.maxLength) >= MIN_FILENAME_LENGTH
? Math.trunc(opts.maxLength)
: DEFAULT_MAX_FILENAME_LENGTH;
const rawFallback = opts.fallback === undefined ? DEFAULT_FALLBACK_FILENAME : opts.fallback;
const safeFallback =
resolveSafeFallback(rawFallback, safeMaxLen) ||
sanitizeFilenameCore(DEFAULT_FALLBACK_FILENAME, safeMaxLen) ||
'u'.slice(0, safeMaxLen);
const sanitized = sanitizeFilenameCore(rawFilename, safeMaxLen);
return sanitized || safeFallback;
}
/**
* Inspect leading magic bytes of a binary buffer to identify canonical file MIME types (`INV-LEGO-18`).
*
* @param {Uint8Array|Buffer|ArrayBuffer} bytes - Input byte buffer
* @returns {'application/pdf'|'image/png'|'image/jpeg'|'image/gif'|'image/webp'|'audio/wav'|'audio/mpeg'|'audio/ogg'|'video/webm'|'application/zip'|null}
*/
export function sniffMimeMagic(bytes) {
const b = toByteView(bytes);
if (!b || b.length < 2) return null;
const len = b.length;
// %PDF- (0x25 0x50 0x44 0x46 0x2d)
if (
len >= 5 &&
b[0] === 0x25 &&
b[1] === 0x50 &&
b[2] === 0x44 &&
b[3] === 0x46 &&
b[4] === 0x2d
) {
return 'application/pdf';
}
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (
len >= 8 &&
b[0] === 0x89 &&
b[1] === 0x50 &&
b[2] === 0x4e &&
b[3] === 0x47 &&
b[4] === 0x0d &&
b[5] === 0x0a &&
b[6] === 0x1a &&
b[7] === 0x0a
) {
return 'image/png';
}
// JPEG: FF D8 FF
if (len >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) {
return 'image/jpeg';
}
// GIF87a / GIF89a
if (
len >= 6 &&
b[0] === 0x47 &&
b[1] === 0x49 &&
b[2] === 0x46 &&
b[3] === 0x38 &&
(b[4] === 0x37 || b[4] === 0x39) &&
b[5] === 0x61
) {
return 'image/gif';
}
// RIFF....WEBP or RIFF....WAVE
if (
len >= 12 &&
b[0] === 0x52 &&
b[1] === 0x49 &&
b[2] === 0x46 &&
b[3] === 0x46
) {
if (b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) {
return 'image/webp';
}
if (b[8] === 0x57 && b[9] === 0x41 && b[10] === 0x56 && b[11] === 0x45) {
return 'audio/wav';
}
}
// MP3: ID3 tag (49 44 33) or valid MPEG audio frame sync
if (len >= 3 && b[0] === 0x49 && b[1] === 0x44 && b[2] === 0x33) {
return 'audio/mpeg';
}
if (
len >= 2 &&
b[0] === 0xff &&
(b[1] & 0xe0) === 0xe0 &&
(b[1] & 0x18) !== 0x08 &&
(b[1] & 0x06) !== 0x00
) {
return 'audio/mpeg';
}
// OggS (4F 67 67 53)
if (len >= 4 && b[0] === 0x4f && b[1] === 0x67 && b[2] === 0x67 && b[3] === 0x53) {
return 'audio/ogg';
}
// EBML / WebM / Matroska (1A 45 DF A3)
if (len >= 4 && b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3) {
return 'video/webm';
}
// ZIP: PK\x03\x04 (50 4B 03 04)
if (len >= 4 && b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04) {
return 'application/zip';
}
return null;
}
const UTF8_DECODER = new TextDecoder('utf-8', { fatal: false });
/**
* Check whether an allowlist pattern strictly requires magic-verifiable binary bytes.
*
* @param {string} rawPattern - Allowlist entry
* @returns {boolean}
*/
function patternRequiresMagic(rawPattern) {
const pat = canonicalizeMime(rawPattern);
if (!pat) return false;
if (MAGIC_REQUIRED_MIMES.has(pat)) return true;
return pat === 'image/*' || pat === 'audio/*' || pat === 'video/*';
}
/**
* Inspect leading 4 KiB of bytes for active SVG/script/HTML markup.
*
* @param {Uint8Array|Buffer|ArrayBuffer} bytes - Input bytes
* @returns {boolean}
*/
function containsActiveMarkup(bytes) {
const view = toByteView(bytes);
if (!view || view.length === 0) return false;
const headLen = Math.min(view.length, 4096);
const probe = UTF8_DECODER.decode(view.subarray(0, headLen)).trimStart().toLowerCase();
return (
probe.includes('<svg') ||
probe.includes('<script') ||
probe.startsWith('<!doctype html') ||
probe.startsWith('<html')
);
}
/**
* Check whether an effective MIME matches at least one pattern in `allowedMimeTypes`.
* Enforces that `'image/*'`, `'audio/*'`, and `'video/*'` with `requireMagicMatch: true`
* require magic-verified binary bytes so `<svg><script>` or spoofed text cannot bypass wildcards.
*
* @param {string} effectiveMime - Resolved canonical MIME type
* @param {string|null} detectedMime - Magic-sniffed MIME type or `null`
* @param {string[]} allowList - Normalized allowed MIME patterns
* @param {boolean} requireMagicMatch - Whether magic verification is active
* @returns {boolean}
*/
function matchesAllowedMimeList(effectiveMime, detectedMime, allowList, requireMagicMatch) {
for (const pattern of allowList) {
if (!pattern) continue;
if (pattern === '*/*' || pattern === '*') {
return true;
}
if (pattern.endsWith('/*')) {
const prefix = pattern.slice(0, -1); // e.g. 'image/', 'audio/', 'video/'
if (
requireMagicMatch &&
(prefix === 'image/' || prefix === 'audio/' || prefix === 'video/')
) {
if (!detectedMime) continue;
if (detectedMime.startsWith(prefix)) {
return true;
}
if (
prefix === 'audio/' &&
effectiveMime === 'audio/webm' &&
detectedMime === 'video/webm'
) {
return true;
}
continue;
}
if (effectiveMime.startsWith(prefix)) {
return true;
}
continue;
}
if (effectiveMime === pattern || canonicalizeMime(effectiveMime) === pattern) {
return true;
}
if (
detectedMime === 'video/webm' &&
((effectiveMime === 'video/webm' && pattern === 'audio/webm') ||
(effectiveMime === 'audio/webm' && pattern === 'video/webm'))
) {
return true;
}
}
return false;
}
/**
* Non-throwing MIME validator comparing declared `Content-Type` against `sniffMimeMagic(bytes)`
* and an optional `allowedMimeTypes` allowlist (`INV-LEGO-01`, `INV-LEGO-18`).
*
* @param {Uint8Array|Buffer|ArrayBuffer} bytes - Uploaded file bytes
* @param {string} [declaredMime=''] - Caller-declared `Content-Type`
* @param {object} [options={}] - Verification options
* @param {Iterable<string>|string[]|Set<string>|null} [options.allowedMimeTypes=null] - Permitted MIME types or wildcards
* @param {boolean} [options.requireMagicMatch=true] - Require magic signature consistency
* @param {string} [options.tool='upload.mime'] - Envelope tool identifier
* @returns {{ ok: true, tool: string, summary: string, data: { mimeType: string, declaredMime: string|null, detectedMime: string|null } } | { ok: false, tool: string, summary: string, error: { code: string, message: string, details?: unknown } }}
*/
export function verifyUploadMime(bytes, declaredMime = '', options = {}) {
const opts = options && typeof options === 'object' ? options : {};
const allowedMimeTypes = opts.allowedMimeTypes ?? null;
const requireMagicMatch = opts.requireMagicMatch !== false;
const tool = String(opts.tool || 'upload.mime');
const view = toByteView(bytes);
if (!view) {
return errorEnvelope(
'UPLOAD_INVALID_DATA',
'Upload data must be a Uint8Array, Buffer, or ArrayBuffer',
null,
tool
);
}
if (view.byteLength === 0) {
return errorEnvelope(
'UPLOAD_EMPTY',
'Upload data cannot be empty (0 bytes)',
{ size: 0 },
tool
);
}
const cleanDeclared =
typeof declaredMime === 'string'
? declaredMime.split(';')[0].trim().toLowerCase()
: '';
const canonDeclared = canonicalizeMime(cleanDeclared);
const detectedMime = sniffMimeMagic(view);
let allowList = null;
if (allowedMimeTypes !== null && allowedMimeTypes !== undefined) {
if (typeof allowedMimeTypes === 'string') {
const single = canonicalizeMime(allowedMimeTypes);
allowList = single ? [single] : [];
} else if (
Array.isArray(allowedMimeTypes) ||
allowedMimeTypes instanceof Set ||
typeof allowedMimeTypes?.[Symbol.iterator] === 'function'
) {
allowList = [];
for (const entry of allowedMimeTypes) {
if (typeof entry !== 'string') continue;
const norm = canonicalizeMime(entry);
if (norm) allowList.push(norm);
}
} else {
allowList = [];
}
if (allowList.length === 0) {
return errorEnvelope(
'UPLOAD_UNSUPPORTED_MIME',
'No MIME types are permitted by allowlist',
{ declaredMime: cleanDeclared || null, detectedMime },
tool
);
}
}
const effectiveMime =
canonDeclared === 'audio/webm' && detectedMime === 'video/webm'
? 'audio/webm'
: detectedMime || canonDeclared || 'application/octet-stream';
if (requireMagicMatch) {
const allowlistImageOnly =
allowList !== null &&
allowList.length > 0 &&
allowList.every((pat) => pat.startsWith('image/'));
if (
cleanDeclared === 'image/svg+xml' ||
canonDeclared === 'image/svg+xml' ||
((effectiveMime.startsWith('image/') || allowlistImageOnly) &&
containsActiveMarkup(bytes))
) {
return errorEnvelope(
'UPLOAD_MIME_MISMATCH',
'SVG or active script markup is blocked under magic-verified image uploads',
{ declaredMime: cleanDeclared || null, detectedMime },
tool
);
}
if (
detectedMime &&
cleanDeclared &&
cleanDeclared !== 'application/octet-stream' &&
!areMimesEquivalent(cleanDeclared, detectedMime)
) {
return errorEnvelope(
'UPLOAD_MIME_MISMATCH',
`Declared MIME "${cleanDeclared}" does not match detected magic "${detectedMime}"`,
{ declaredMime: cleanDeclared, detectedMime },
tool
);
}
if (!detectedMime) {
const declaredNeedsMagic =
Boolean(canonDeclared) &&
(MAGIC_REQUIRED_MIMES.has(canonDeclared) ||
canonDeclared.startsWith('image/') ||
canonDeclared.startsWith('audio/') ||
canonDeclared.startsWith('video/'));
const allowlistStrictlyBinary =
allowList !== null &&
allowList.length > 0 &&
allowList.every((pat) => patternRequiresMagic(pat));
if (
declaredNeedsMagic ||
(allowlistStrictlyBinary &&
(!canonDeclared || canonDeclared === 'application/octet-stream'))
) {
return errorEnvelope(
'UPLOAD_MIME_MISMATCH',
`Missing expected binary magic signature for "${cleanDeclared || 'binary allowlist'}"`,
{ declaredMime: cleanDeclared || null, detectedMime: null },
tool
);
}
}
}
if (allowList !== null) {
const permitted = matchesAllowedMimeList(
effectiveMime,
detectedMime,
allowList,
requireMagicMatch
);
if (!permitted) {
return errorEnvelope(
'UPLOAD_UNSUPPORTED_MIME',
`MIME type "${effectiveMime}" is not permitted`,
{ mimeType: effectiveMime, declaredMime: cleanDeclared, detectedMime },
tool
);
}
}
return okEnvelope(tool, 'Upload MIME verified', {
mimeType: effectiveMime,
declaredMime: cleanDeclared || null,
detectedMime,
});
}
/**
* Read a case-insensitive header value from a `Headers` instance or Node/plain header map.
*
* @param {unknown} headers - Header container
* @param {string} lowerName - Lowercase header name
* @returns {string}
*/
function readHeaderValue(headers, lowerName) {
if (!headers || typeof headers !== 'object') return '';
if (typeof headers.get === 'function') {
const val = headers.get(lowerName);
return typeof val === 'string' ? val : '';
}
if (Object.hasOwn(headers, lowerName)) {
const direct = headers[lowerName];
if (Array.isArray(direct)) return String(direct[0] ?? '');
if (direct !== undefined && direct !== null) return String(direct);
}
for (const [k, v] of Object.entries(headers)) {
if (k.toLowerCase() === lowerName && v !== undefined && v !== null) {
return Array.isArray(v) ? String(v[0] ?? '') : String(v);
}
}
return '';
}
/**
* Split semicolon-delimited HTTP header parameters without regex backtracking, preserving quoted semicolons.
*
* @param {string} raw - Parameter tail after initial `;`
* @returns {string[]}
*/
function splitHeaderParams(raw) {
const parts = [];
let start = 0;
let inQuotes = false;
let escaped = false;
for (let i = 0; i < raw.length; i += 1) {
const ch = raw[i];
if (escaped) {
escaped = false;
continue;
}
if (inQuotes && ch === '\\') {
escaped = true;
continue;
}
if (ch === '"') {
inQuotes = !inQuotes;
continue;
}
if (!inQuotes && ch === ';') {
parts.push(raw.slice(start, i));
start = i + 1;
}
}
if (inQuotes || escaped) {
return [];
}
parts.push(raw.slice(start));
return parts;
}
/**
* Extract and validate the RFC 2046 / RFC 7578 `boundary` parameter from `Content-Type`.
*
* @param {string} rawContentType - Incoming `Content-Type` header
* @returns {string|null}
*/
function parseMultipartBoundary(rawContentType) {
if (typeof rawContentType !== 'string' || /[\r\n\x00]/.test(rawContentType)) {
return null;
}
const semiIdx = rawContentType.indexOf(';');
if (semiIdx < 0) return null;
const mediaType = rawContentType.slice(0, semiIdx).trim().toLowerCase();
if (mediaType !== 'multipart/form-data') return null;
const params = splitHeaderParams(rawContentType.slice(semiIdx + 1));
if (params.length === 0) return null;
for (const rawParam of params) {
const eqIdx = rawParam.indexOf('=');
if (eqIdx <= 0) continue;
const name = rawParam.slice(0, eqIdx).trim().toLowerCase();
if (name !== 'boundary') continue;
const rawVal = rawParam.slice(eqIdx + 1).trim();
if (!rawVal) return null;
let boundary = '';
if (rawVal.startsWith('"')) {
if (rawVal.length < 2 || !rawVal.endsWith('"')) return null;
const inner = rawVal.slice(1, -1);
if (inner.includes('"') || inner.includes('\\')) return null;
boundary = inner;
} else {
if (/\s/.test(rawVal) || rawVal.includes('"')) return null;
boundary = rawVal;
}
if (
boundary.length < 1 ||
boundary.length > 70 ||
boundary.endsWith(' ') ||
!VALID_BOUNDARY_CHARS_RE.test(boundary)
) {
return null;
}
return boundary;
}
return null;
}
const MAX_POST_REJECTION_DRAIN_BYTES = 1_048_576; // 1 MiB post-rejection drain cap
/**
* Drain a rejected Node `Readable` / `IncomingMessage` up to `maxDrainBytes` while keeping a
* self-cleaning `'error'` guard attached until `'close'` so asynchronous stream resets never throw
* `ERR_UNHANDLED_ERROR` (`INV-LEGO-03`, `INV-LEGO-18`).
*
* @param {import('node:stream').Readable & { aborted?: boolean }} stream - Node readable stream
* @param {number} [maxDrainBytes=MAX_POST_REJECTION_DRAIN_BYTES] - Maximum post-rejection bytes to drain
*/
function drainNodeStreamSafely(stream, maxDrainBytes = MAX_POST_REJECTION_DRAIN_BYTES) {
if (!stream || typeof stream.on !== 'function' || stream.destroyed) return;
const remove = (event, fn) => {
if (typeof stream.off === 'function') {
stream.off(event, fn);
} else if (typeof stream.removeListener === 'function') {
stream.removeListener(event, fn);
}
};
let drainedBytes = 0;
const detachDataListeners = () => {
remove('data', onDrainData);
remove('end', onDrainEnd);
};
const detachAllListeners = () => {
detachDataListeners();
remove('error', onDrainError);
remove('close', onDrainClose);
};
const onDrainError = () => {
detachDataListeners();
};
const onDrainEnd = () => {
detachDataListeners();
};
const onDrainClose = () => {
detachAllListeners();
};
const onDrainData = (chunk) => {
const len = Buffer.isBuffer(chunk)
? chunk.byteLength
: chunk instanceof Uint8Array
? chunk.byteLength
: Buffer.byteLength(String(chunk), 'utf8');
drainedBytes += len;
if (drainedBytes > maxDrainBytes) {
detachDataListeners();
stream.pause?.();
}
};
stream.on('error', onDrainError);
stream.on('close', onDrainClose);
if (!stream.readableEnded) {
stream.on('data', onDrainData);
stream.on('end', onDrainEnd);
stream.resume?.();
}
}
/**
* Cancel or drain an unread request body safely so rejected uploads neither leak listeners nor trigger `ECONNRESET`.
*
* @param {unknown} input - Request, Node stream, or buffer container
*/
async function drainRejectedInput(input) {
if (!input || typeof input !== 'object') return;
if (typeof input.body?.cancel === 'function') {
try {
await input.body.cancel();
} catch {
// Ignore Web ReadableStream cancel errors on rejected input
}
return;
}
if (typeof input.on === 'function' && !input.destroyed) {
drainNodeStreamSafely(input);
}
}
/**
* Read a Node `IncomingMessage` / `Readable` into a single `Buffer` up to `safeMaxTotal` bytes,
* detaching active accumulation listeners and draining safely on overflow (`INV-LEGO-03`, `INV-LEGO-18`).
*
* @param {import('node:stream').Readable & { aborted?: boolean }} stream - Node readable stream
* @param {number} safeMaxTotal - Byte limit
* @param {string} tool - Envelope tool identifier
* @returns {Promise<{ ok: true, buffer: Buffer } | { ok: false, envelope: object }>}
*/
function readBoundedNodeStream(stream, safeMaxTotal, tool) {
if (stream.aborted || stream.destroyed) {
return Promise.resolve({
ok: false,
envelope: errorEnvelope('UPLOAD_STREAM_ABORTED', 'Upload stream was aborted', null, tool),
});
}
if (stream.readableEnded) {
return Promise.resolve({ ok: true, buffer: Buffer.alloc(0) });
}
return new Promise((resolve) => {
let totalBytes = 0;
let settled = false;
const chunks = [];
const remove = (event, fn) => {
if (typeof stream.off === 'function') {
stream.off(event, fn);
} else if (typeof stream.removeListener === 'function') {
stream.removeListener(event, fn);
}
};
const cleanup = () => {
remove('data', onData);
remove('end', onEnd);
remove('error', onError);
remove('aborted', onAborted);
remove('close', onClose);
};
const onData = (chunk) => {
if (settled) return;
const buf = Buffer.isBuffer(chunk)
? chunk
: chunk instanceof Uint8Array
? Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
: Buffer.from(String(chunk), 'utf8');
totalBytes += buf.byteLength;
if (totalBytes > safeMaxTotal) {
settled = true;
chunks.length = 0;
cleanup();
drainNodeStreamSafely(stream, Math.max(safeMaxTotal, MAX_POST_REJECTION_DRAIN_BYTES));
resolve({
ok: false,
envelope: errorEnvelope(
'UPLOAD_TOO_LARGE',
`Multipart body exceeds ${safeMaxTotal} bytes`,
{ maxTotalBytes: safeMaxTotal, receivedBytes: totalBytes },
tool
),
});
return;
}
chunks.push(buf);
};
const onEnd = () => {
if (settled) return;
settled = true;
cleanup();
const combined = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, totalBytes);
chunks.length = 0;
resolve({ ok: true, buffer: combined });
};
const onAborted = () => {
if (settled) return;
settled = true;
chunks.length = 0;
cleanup();
resolve({
ok: false,
envelope: errorEnvelope('UPLOAD_STREAM_ABORTED', 'Upload stream was aborted', null, tool),
});
};
const onClose = () => {
if (settled) return;
settled = true;
chunks.length = 0;
cleanup();
resolve({
ok: false,
envelope: errorEnvelope('UPLOAD_STREAM_ABORTED', 'Upload stream closed prematurely', null, tool),
});
};
const onError = (err) => {
if (settled) return;
settled = true;
chunks.length = 0;
cleanup();
resolve({
ok: false,
envelope: errorEnvelope(
'UPLOAD_STREAM_ERROR',
err?.message || 'Upload stream error',
null,
tool
),
});
};
stream.on('data', onData);
stream.on('end', onEnd);
stream.on('error', onError);
stream.on('aborted', onAborted);
stream.on('close', onClose);
});
}
/**
* Read a Web `Request` body `ReadableStream` up to `safeMaxTotal` bytes, canceling immediately on overflow.
*
* @param {Request} request - Web `Request`
* @param {number} safeMaxTotal - Byte limit
* @param {string} tool - Envelope tool identifier
* @returns {Promise<{ ok: true, buffer: Buffer } | { ok: false, envelope: object }>}
*/
async function readBoundedWebRequest(request, safeMaxTotal, tool) {
if (!request.body || typeof request.body.getReader !== 'function') {
if (typeof request.arrayBuffer === 'function') {
try {
const ab = await request.arrayBuffer();
if (ab.byteLength > safeMaxTotal) {
return {
ok: false,
envelope: errorEnvelope(
'UPLOAD_TOO_LARGE',
`Multipart body exceeds ${safeMaxTotal} bytes`,
{ maxTotalBytes: safeMaxTotal, receivedBytes: ab.byteLength },
tool
),
};
}
return { ok: true, buffer: Buffer.from(ab) };
} catch (err) {
return {
ok: false,
envelope: errorEnvelope(
'UPLOAD_STREAM_ERROR',
err?.message || 'Unable to read request body',
null,
tool
),
};
}
}
return { ok: true, buffer: Buffer.alloc(0) };
}
let reader;
try {
reader = request.body.getReader();
} catch (err) {
return {
ok: false,
envelope: errorEnvelope(
'UPLOAD_STREAM_ERROR',
err?.message || 'Unable to acquire request body reader',
null,
tool
),
};