@oxog/spark 1.1.1 → 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.
Files changed (64) hide show
  1. package/CHANGELOG.md +656 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +90 -89
  5. package/src/core/application.js +1068 -956
  6. package/src/core/context.js +1098 -830
  7. package/src/core/middleware.js +303 -217
  8. package/src/index.js +183 -280
  9. package/src/middleware/body-parser.js +482 -526
  10. package/src/middleware/cache.js +177 -170
  11. package/src/middleware/compression.js +177 -182
  12. package/src/middleware/cors.js +176 -95
  13. package/src/middleware/health.js +219 -218
  14. package/src/middleware/logger.js +195 -194
  15. package/src/middleware/metrics.js +339 -327
  16. package/src/middleware/rate-limit.js +367 -319
  17. package/src/middleware/security.js +442 -332
  18. package/src/middleware/session.js +647 -529
  19. package/src/middleware/static.js +404 -299
  20. package/src/router/layer.js +197 -117
  21. package/src/router/route.js +149 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +145 -147
  24. package/src/utils/context-pool.js +83 -82
  25. package/src/utils/regex-validator.js +187 -163
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +538 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -959
  31. package/dist/core/context.js +0 -833
  32. package/dist/core/middleware.js +0 -220
  33. package/dist/core/request.js +0 -335
  34. package/dist/core/response.js +0 -377
  35. package/dist/index.js +0 -280
  36. package/dist/middleware/body-parser.js +0 -528
  37. package/dist/middleware/cache.js +0 -173
  38. package/dist/middleware/compression.js +0 -185
  39. package/dist/middleware/cors.js +0 -97
  40. package/dist/middleware/health.js +0 -221
  41. package/dist/middleware/index.js +0 -23
  42. package/dist/middleware/logger.js +0 -197
  43. package/dist/middleware/metrics.js +0 -330
  44. package/dist/middleware/rate-limit.js +0 -322
  45. package/dist/middleware/security.js +0 -335
  46. package/dist/middleware/session.js +0 -532
  47. package/dist/middleware/static.js +0 -301
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -119
  50. package/dist/router/route.js +0 -125
  51. package/dist/router/router.js +0 -758
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -150
  54. package/dist/utils/cache.js +0 -443
  55. package/dist/utils/context-pool.js +0 -85
  56. package/dist/utils/error-types.js +0 -134
  57. package/dist/utils/http.js +0 -415
  58. package/dist/utils/regex-validator.js +0 -166
  59. package/src/core/request.js +0 -335
  60. package/src/core/response.js +0 -377
  61. package/src/middleware/index.js +0 -23
  62. package/src/utils/cache.js +0 -443
  63. package/src/utils/error-types.js +0 -134
  64. package/src/utils/http.js +0 -415
@@ -1,528 +1,484 @@
1
1
  'use strict';
2
2
 
3
- /**
4
- * @fileoverview Body parsing middleware for Spark Framework
5
- * @author Spark Framework Team
6
- * @since 1.0.0
7
- * @version 1.0.0
8
- */
9
-
10
- const querystring = require('querystring');
11
- const { Readable } = require('stream');
12
-
13
- /** @constant {number} Default size limit for request bodies (1MB) */
14
- const DEFAULT_LIMIT = 1024 * 1024; // 1MB
15
-
16
- /** @constant {boolean} Default extended parsing setting */
17
- const DEFAULT_EXTENDED = true;
18
-
19
- /**
20
- * Create a body parsing middleware
21
- *
22
- * Automatically parses request bodies based on Content-Type header.
23
- * Supports JSON, URL-encoded, multipart/form-data, text, and raw binary data.
24
- * Provides security features like size limits and content validation.
25
- *
26
- * @param {Object} [options={}] - Body parser configuration options
27
- * @param {number} [options.limit=1048576] - Maximum request body size in bytes (default: 1MB)
28
- * @param {boolean} [options.extended=true] - Use extended URL encoding parsing
29
- * @param {string} [options.type='auto'] - Force parsing type ('auto', 'json', 'urlencoded', 'multipart', 'text', 'raw')
30
- * @param {string} [options.encoding='utf8'] - Text encoding for parsing
31
- * @param {boolean} [options.inflate=true] - Enable gzip/deflate decompression
32
- * @param {boolean} [options.strict=true] - Enable strict parsing
33
- * @param {Function} [options.verify] - Custom verification function
34
- * @returns {Function} Express-style middleware function
35
- *
36
- * @since 1.0.0
37
- *
38
- * @example
39
- * // Auto-detect content type
40
- * app.use(bodyParser());
41
- *
42
- * @example
43
- * // JSON only with custom limit
44
- * app.use(bodyParser({
45
- * type: 'json',
46
- * limit: 1024 * 512 // 512KB
47
- * }));
48
- *
49
- * @example
50
- * // With verification
51
- * app.use(bodyParser({
52
- * verify: (req, res, body) => {
53
- * if (body.length > 1000) {
54
- * throw new Error('Body too large');
55
- * }
56
- * }
57
- * }));
58
- *
59
- * @example
60
- * // Multiple content types
61
- * app.use(bodyParser({ type: 'json' }));
62
- * app.use(bodyParser({ type: 'urlencoded' }));
63
- * app.use(bodyParser({ type: 'text' }));
64
- */
65
- function bodyParser(options = {}) {
66
- const opts = {
67
- limit: options.limit || DEFAULT_LIMIT,
68
- extended: options.extended !== false,
69
- type: options.type || 'auto',
70
- encoding: options.encoding || 'utf8',
71
- inflate: options.inflate !== false,
72
- strict: options.strict !== false,
73
- verify: options.verify,
74
- ...options
75
- };
76
-
77
- return async (ctx, next) => {
78
- if (ctx.body !== null || ctx.method === 'GET' || ctx.method === 'HEAD') {
79
- return next();
80
- }
81
-
82
- const contentType = ctx.get('content-type') || '';
83
- const contentLength = parseInt(ctx.get('content-length')) || 0;
84
-
85
- if (contentLength > opts.limit) {
86
- ctx.status(413).json({ error: 'Request entity too large' });
87
- return;
88
- }
89
-
90
- try {
91
- if (shouldParseJson(contentType, opts.type)) {
92
- await parseJson(ctx, opts);
93
- } else if (shouldParseUrlencoded(contentType, opts.type)) {
94
- await parseUrlencoded(ctx, opts);
95
- } else if (shouldParseMultipart(contentType, opts.type)) {
96
- await parseMultipart(ctx, opts);
97
- } else if (shouldParseText(contentType, opts.type)) {
98
- await parseText(ctx, opts);
99
- } else if (shouldParseRaw(contentType, opts.type)) {
100
- await parseRaw(ctx, opts);
101
- }
102
-
103
- if (opts.verify) {
104
- await Promise.resolve(opts.verify(ctx.req, ctx.res, ctx.body));
105
- }
106
-
107
- await next();
108
- } catch (error) {
109
- ctx.status(400).json({
110
- error: 'Bad Request',
111
- message: error.message,
112
- type: error.name
113
- });
114
- }
115
- };
116
- }
117
-
118
- /**
119
- * Check if content should be parsed as JSON
120
- *
121
- * @param {string} contentType - Request Content-Type header
122
- * @param {string} type - Parser type setting
123
- * @returns {boolean} Whether to parse as JSON
124
- *
125
- * @private
126
- * @since 1.0.0
127
- */
128
- function shouldParseJson(contentType, type) {
129
- if (type === 'json') return true;
130
- if (type === 'auto') return contentType.includes('application/json');
131
- return false;
132
- }
133
-
134
- /**
135
- * Check if content should be parsed as URL-encoded
136
- *
137
- * @param {string} contentType - Request Content-Type header
138
- * @param {string} type - Parser type setting
139
- * @returns {boolean} Whether to parse as URL-encoded
140
- *
141
- * @private
142
- * @since 1.0.0
143
- */
144
- function shouldParseUrlencoded(contentType, type) {
145
- if (type === 'urlencoded') return true;
146
- if (type === 'auto') return contentType.includes('application/x-www-form-urlencoded');
147
- return false;
148
- }
149
-
150
- /**
151
- * Check if content should be parsed as multipart
152
- *
153
- * @param {string} contentType - Request Content-Type header
154
- * @param {string} type - Parser type setting
155
- * @returns {boolean} Whether to parse as multipart
156
- *
157
- * @private
158
- * @since 1.0.0
159
- */
160
- function shouldParseMultipart(contentType, type) {
161
- if (type === 'multipart') return true;
162
- if (type === 'auto') return contentType.includes('multipart/form-data');
163
- return false;
164
- }
165
-
166
- /**
167
- * Check if content should be parsed as text
168
- *
169
- * @param {string} contentType - Request Content-Type header
170
- * @param {string} type - Parser type setting
171
- * @returns {boolean} Whether to parse as text
172
- *
173
- * @private
174
- * @since 1.0.0
175
- */
176
- function shouldParseText(contentType, type) {
177
- if (type === 'text') return true;
178
- if (type === 'auto') return contentType.includes('text/');
179
- return false;
180
- }
181
-
182
- /**
183
- * Check if content should be parsed as raw binary
184
- *
185
- * @param {string} contentType - Request Content-Type header
186
- * @param {string} type - Parser type setting
187
- * @returns {boolean} Whether to parse as raw binary
188
- *
189
- * @private
190
- * @since 1.0.0
191
- */
192
- function shouldParseRaw(contentType, type) {
193
- return type === 'raw';
194
- }
195
-
196
- /**
197
- * Parse request body as JSON
198
- *
199
- * @param {Context} ctx - Request context
200
- * @param {Object} opts - Parser options
201
- * @returns {Promise<void>}
202
- *
203
- * @throws {Error} When JSON parsing fails
204
- *
205
- * @private
206
- * @since 1.0.0
207
- */
208
- async function parseJson(ctx, opts) {
209
- const body = await readBody(ctx.req, opts);
210
-
211
- try {
212
- ctx.body = JSON.parse(body);
213
- } catch (error) {
214
- throw new Error(`Invalid JSON: ${error.message}`);
215
- }
216
- }
217
-
218
- /**
219
- * Parse request body as URL-encoded form data
220
- *
221
- * @param {Context} ctx - Request context
222
- * @param {Object} opts - Parser options
223
- * @returns {Promise<void>}
224
- *
225
- * @private
226
- * @since 1.0.0
227
- */
228
- async function parseUrlencoded(ctx, opts) {
229
- const body = await readBody(ctx.req, opts);
230
- ctx.body = querystring.parse(body);
231
- }
232
-
233
- async function parseMultipart(ctx, opts) {
234
- const contentType = ctx.get('content-type');
235
- const boundary = getBoundary(contentType);
236
-
237
- if (!boundary) {
238
- throw new Error('Invalid multipart/form-data: missing boundary');
239
- }
240
-
241
- const chunks = [];
242
- let size = 0;
243
-
244
- await new Promise((resolve, reject) => {
245
- const onData = (chunk) => {
246
- size += chunk.length;
247
- if (size > opts.limit) {
248
- ctx.req.removeListener('data', onData);
249
- ctx.req.removeListener('end', onEnd);
250
- ctx.req.removeListener('error', onError);
251
- return reject(new Error('Request entity too large'));
252
- }
253
- chunks.push(chunk);
254
- };
255
-
256
- const onEnd = () => {
257
- ctx.req.removeListener('data', onData);
258
- ctx.req.removeListener('error', onError);
259
- resolve();
260
- };
261
-
262
- const onError = (error) => {
263
- ctx.req.removeListener('data', onData);
264
- ctx.req.removeListener('end', onEnd);
265
- reject(error);
266
- };
267
-
268
- ctx.req.on('data', onData);
269
- ctx.req.on('end', onEnd);
270
- ctx.req.on('error', onError);
271
- });
272
-
273
- const body = Buffer.concat(chunks).toString('binary');
274
- const parsed = parseMultipartData(body, boundary);
275
-
276
- ctx.body = parsed.fields;
277
- ctx.files = parsed.files;
278
- }
279
-
280
- /**
281
- * Parse request body as plain text
282
- *
283
- * @param {Context} ctx - Request context
284
- * @param {Object} opts - Parser options
285
- * @returns {Promise<void>}
286
- *
287
- * @private
288
- * @since 1.0.0
289
- */
290
- async function parseText(ctx, opts) {
291
- ctx.body = await readBody(ctx.req, opts);
292
- }
293
-
294
- /**
295
- * Parse request body as raw binary data
296
- *
297
- * @param {Context} ctx - Request context
298
- * @param {Object} opts - Parser options
299
- * @returns {Promise<void>}
300
- *
301
- * @throws {Error} When request is too large
302
- *
303
- * @private
304
- * @since 1.0.0
305
- */
306
- async function parseRaw(ctx, opts) {
307
- const chunks = [];
308
-
309
- return new Promise((resolve, reject) => {
310
- let size = 0;
311
-
312
- const onData = (chunk) => {
313
- size += chunk.length;
314
- if (size > opts.limit) {
315
- ctx.req.removeListener('data', onData);
316
- ctx.req.removeListener('end', onEnd);
317
- ctx.req.removeListener('error', onError);
318
- return reject(new Error('Request entity too large'));
319
- }
320
- chunks.push(chunk);
321
- };
322
-
323
- const onEnd = () => {
324
- ctx.req.removeListener('data', onData);
325
- ctx.req.removeListener('error', onError);
326
- ctx.body = Buffer.concat(chunks);
327
- resolve();
328
- };
329
-
330
- const onError = (error) => {
331
- ctx.req.removeListener('data', onData);
332
- ctx.req.removeListener('end', onEnd);
333
- reject(error);
334
- };
335
-
336
- ctx.req.on('data', onData);
337
- ctx.req.on('end', onEnd);
338
- ctx.req.on('error', onError);
339
- });
340
- }
341
-
342
- /**
343
- * Read and decode request body as text
344
- *
345
- * @param {http.IncomingMessage} req - HTTP request object
346
- * @param {Object} opts - Parser options with encoding and limit
347
- * @returns {Promise<string>} Promise resolving to decoded body text
348
- *
349
- * @throws {Error} When request is too large
350
- *
351
- * @private
352
- * @since 1.0.0
353
- */
354
- function readBody(req, opts) {
355
- return new Promise((resolve, reject) => {
356
- const chunks = [];
357
- let size = 0;
358
-
359
- const onData = (chunk) => {
360
- size += chunk.length;
361
- if (size > opts.limit) {
362
- req.removeListener('data', onData);
363
- req.removeListener('end', onEnd);
364
- req.removeListener('error', onError);
365
- return reject(new Error('Request entity too large'));
366
- }
367
- chunks.push(chunk);
368
- };
369
-
370
- const onEnd = () => {
371
- req.removeListener('data', onData);
372
- req.removeListener('error', onError);
373
- const body = Buffer.concat(chunks).toString(opts.encoding || 'utf8');
374
- resolve(body);
375
- };
376
-
377
- const onError = (error) => {
378
- req.removeListener('data', onData);
379
- req.removeListener('end', onEnd);
380
- reject(error);
381
- };
382
-
383
- req.on('data', onData);
384
- req.on('end', onEnd);
385
- req.on('error', onError);
386
- });
387
- }
388
-
389
- /**
390
- * Extract boundary from multipart Content-Type header
391
- *
392
- * @param {string} contentType - Content-Type header value
393
- * @returns {string|null} Boundary string or null if not found
394
- *
395
- * @private
396
- * @since 1.0.0
397
- */
398
- function getBoundary(contentType) {
399
- const match = contentType.match(/boundary=([^;]+)/);
400
- if (!match || !match[1]) return null;
401
-
402
- // Remove quotes if present
403
- return match[1].replace(/^["']|["']$/g, '');
404
- }
405
-
406
- /**
407
- * Parse multipart/form-data body content
408
- *
409
- * @param {string} body - Raw multipart body as binary string
410
- * @param {string} boundary - Multipart boundary string
411
- * @returns {Object} Object with fields and files properties
412
- * @returns {Object} returns.fields - Parsed form fields
413
- * @returns {Object} returns.files - Parsed file uploads with metadata
414
- *
415
- * @private
416
- * @since 1.0.0
417
- */
418
- function parseMultipartData(body, boundary) {
419
- const fields = {};
420
- const files = {};
421
-
422
- const parts = body.split(`--${boundary}`);
423
-
424
- for (let i = 1; i < parts.length - 1; i++) {
425
- const part = parts[i];
426
- const [headers, content] = part.split('\r\n\r\n');
427
-
428
- if (!headers || content === undefined) continue;
429
-
430
- const headerLines = headers.split('\r\n');
431
- const contentDisposition = headerLines.find(line =>
432
- line.startsWith('Content-Disposition:')
433
- );
434
-
435
- if (!contentDisposition) continue;
436
-
437
- const nameMatch = contentDisposition.match(/name="([^"]+)"/);
438
- const filenameMatch = contentDisposition.match(/filename="([^"]+)"/);
439
-
440
- if (!nameMatch) continue;
441
-
442
- const name = nameMatch[1];
443
- const filename = filenameMatch ? filenameMatch[1] : null;
444
-
445
- if (filename) {
446
- const contentType = headerLines.find(line =>
447
- line.startsWith('Content-Type:')
448
- );
449
-
450
- files[name] = {
451
- filename,
452
- contentType: contentType ? contentType.split(': ')[1] : 'application/octet-stream',
453
- size: Buffer.byteLength(content.slice(0, -2)),
454
- data: Buffer.from(content.slice(0, -2))
455
- };
456
- } else {
457
- fields[name] = content.slice(0, -2);
458
- }
459
- }
460
-
461
- return { fields, files };
462
- }
463
-
464
- /**
465
- * Create a JSON body parser middleware
466
- *
467
- * @param {Object} [options] - Parser options (merged with type: 'json')
468
- * @returns {Function} Middleware function for parsing JSON bodies
469
- *
470
- * @since 1.0.0
471
- *
472
- * @example
473
- * app.use(json({ limit: '10mb' }));
474
- */
475
- function json(options) {
476
- return bodyParser({ ...options, type: 'json' });
477
- }
478
-
479
- /**
480
- * Create a URL-encoded body parser middleware
481
- *
482
- * @param {Object} [options] - Parser options (merged with type: 'urlencoded')
483
- * @returns {Function} Middleware function for parsing URL-encoded bodies
484
- *
485
- * @since 1.0.0
486
- *
487
- * @example
488
- * app.use(urlencoded({ extended: true }));
489
- */
490
- function urlencoded(options) {
491
- return bodyParser({ ...options, type: 'urlencoded' });
492
- }
493
-
494
- /**
495
- * Create a text body parser middleware
496
- *
497
- * @param {Object} [options] - Parser options (merged with type: 'text')
498
- * @returns {Function} Middleware function for parsing text bodies
499
- *
500
- * @since 1.0.0
501
- *
502
- * @example
503
- * app.use(text({ encoding: 'utf16' }));
504
- */
505
- function text(options) {
506
- return bodyParser({ ...options, type: 'text' });
507
- }
508
-
509
- /**
510
- * Create a raw binary body parser middleware
511
- *
512
- * @param {Object} [options] - Parser options (merged with type: 'raw')
513
- * @returns {Function} Middleware function for parsing raw binary bodies
514
- *
515
- * @since 1.0.0
516
- *
517
- * @example
518
- * app.use(raw({ limit: '5mb' }));
519
- */
520
- function raw(options) {
521
- return bodyParser({ ...options, type: 'raw' });
522
- }
523
-
524
- module.exports = bodyParser;
525
- module.exports.json = json;
526
- module.exports.urlencoded = urlencoded;
527
- module.exports.text = text;
528
- module.exports.raw = raw;
3
+ /**
4
+ * @fileoverview Body parsing middleware for Spark Framework
5
+ * @author Spark Framework Team
6
+ * @since 1.0.0
7
+ * @version 1.0.0
8
+ */
9
+
10
+ const querystring = require('querystring');
11
+ const zlib = require('zlib');
12
+ const { safeJSONParse } = require('../utils/safe-json');
13
+
14
+ /** @constant {number} Default size limit for request bodies (1MB) */
15
+ const DEFAULT_LIMIT = 1024 * 1024; // 1MB
16
+
17
+ const SIZE_UNITS = { b: 1, kb: 1024, mb: 1024 * 1024, gb: 1024 * 1024 * 1024 };
18
+
19
+ /**
20
+ * Create a body parsing middleware
21
+ *
22
+ * Automatically parses request bodies based on Content-Type header.
23
+ * Supports JSON, URL-encoded, multipart/form-data, text, and raw binary data.
24
+ * Provides security features like size limits and content validation.
25
+ *
26
+ * Bodies larger than `limit` (after decompression) are rejected with 413,
27
+ * malformed bodies with 400, unsupported Content-Encoding with 415. Errors
28
+ * thrown by later middleware or handlers are not caught here; they reach the
29
+ * application error handler. JSON `__proto__` keys are dropped.
30
+ *
31
+ * @param {Object} [options={}] - Body parser configuration options
32
+ * @param {number|string} [options.limit=1048576] - Maximum body size: bytes, or a string such as '100kb' or '5mb'
33
+ * @param {string} [options.type='auto'] - Body type to parse ('auto', 'json', 'urlencoded', 'multipart', 'text', 'raw');
34
+ * a fixed type parses only requests whose Content-Type matches it (or that send no Content-Type)
35
+ * @param {string} [options.encoding='utf8'] - Text encoding for parsing
36
+ * @param {boolean} [options.inflate=true] - Decompress gzip/deflate/br request bodies
37
+ * @param {Function} [options.verify] - Called as verify(req, res, body) after parsing; throwing rejects the request with 400
38
+ * @returns {Function} Express-style middleware function
39
+ *
40
+ * @since 1.0.0
41
+ *
42
+ * @example
43
+ * // Auto-detect content type
44
+ * app.use(bodyParser());
45
+ *
46
+ * @example
47
+ * // JSON only with custom limit
48
+ * app.use(bodyParser({
49
+ * type: 'json',
50
+ * limit: 1024 * 512 // 512KB
51
+ * }));
52
+ *
53
+ * @example
54
+ * // With verification
55
+ * app.use(bodyParser({
56
+ * verify: (req, res, body) => {
57
+ * if (body.length > 1000) {
58
+ * throw new Error('Body too large');
59
+ * }
60
+ * }
61
+ * }));
62
+ *
63
+ * @example
64
+ * // Multiple content types
65
+ * app.use(bodyParser({ type: 'json' }));
66
+ * app.use(bodyParser({ type: 'urlencoded' }));
67
+ * app.use(bodyParser({ type: 'text' }));
68
+ */
69
+ function bodyParser(options = {}) {
70
+ const opts = {
71
+ ...options,
72
+ limit: parseLimit(options.limit),
73
+ type: options.type || 'auto',
74
+ encoding: options.encoding || 'utf8',
75
+ inflate: options.inflate !== false,
76
+ verify: options.verify
77
+ };
78
+
79
+ return async (ctx, next) => {
80
+ if (ctx.body !== null || ctx.method === 'GET' || ctx.method === 'HEAD' || !hasBody(ctx.req)) {
81
+ return next();
82
+ }
83
+
84
+ const contentType = String(ctx.get('content-type') || '').toLowerCase();
85
+ const kind = detectKind(contentType, opts.type);
86
+ if (!kind) {
87
+ return next();
88
+ }
89
+
90
+ const contentLength = Number(ctx.get('content-length'));
91
+ const encoding = String(ctx.get('content-encoding') || 'identity').toLowerCase();
92
+ if (encoding === 'identity' && Number.isFinite(contentLength) && contentLength > opts.limit) {
93
+ ctx.set('Connection', 'close');
94
+ ctx.status(413).json({ error: 'Request entity too large' });
95
+ return undefined;
96
+ }
97
+
98
+ try {
99
+ const buffer = await readBody(ctx.req, opts, encoding);
100
+
101
+ switch (kind) {
102
+ case 'json':
103
+ ctx.body = parseJson(buffer.toString(opts.encoding), opts);
104
+ break;
105
+ case 'urlencoded':
106
+ ctx.body = querystring.parse(buffer.toString(opts.encoding));
107
+ break;
108
+ case 'multipart': {
109
+ const boundary = getBoundary(ctx.get('content-type'));
110
+ if (!boundary) {
111
+ throw clientError(400, 'Invalid multipart/form-data: missing boundary');
112
+ }
113
+ const parsed = parseMultipartData(buffer, boundary);
114
+ ctx.body = parsed.fields;
115
+ ctx.files = parsed.files;
116
+ break;
117
+ }
118
+ case 'text':
119
+ ctx.body = buffer.toString(opts.encoding);
120
+ break;
121
+ default:
122
+ ctx.body = buffer;
123
+ }
124
+
125
+ if (opts.verify) {
126
+ await opts.verify(ctx.req, ctx.res, ctx.body);
127
+ }
128
+ } catch (error) {
129
+ const status = Number.isInteger(error.status) ? error.status : 400;
130
+ if (status === 413) {
131
+ // The rest of the upload is not read; close the connection after replying.
132
+ ctx.set('Connection', 'close');
133
+ ctx.status(413).json({ error: 'Request entity too large' });
134
+ } else {
135
+ ctx.status(status).json({
136
+ error: status === 415 ? 'Unsupported Media Type' : 'Bad Request',
137
+ message: error.message,
138
+ type: error.name
139
+ });
140
+ }
141
+ return undefined;
142
+ }
143
+
144
+ return next();
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Parse a body size limit ('1mb', '100kb', 2048).
150
+ *
151
+ * @param {number|string} [limit] - Limit
152
+ * @returns {number} Limit in bytes
153
+ * @private
154
+ */
155
+ function parseLimit(limit) {
156
+ if (limit === undefined || limit === null || limit === '') {
157
+ return DEFAULT_LIMIT;
158
+ }
159
+ if (typeof limit === 'number' && Number.isFinite(limit) && limit >= 0) {
160
+ return limit;
161
+ }
162
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?\s*$/i.exec(String(limit));
163
+ if (!match) {
164
+ throw new TypeError(`Invalid body size limit: ${limit}`);
165
+ }
166
+ return Math.floor(parseFloat(match[1]) * SIZE_UNITS[(match[2] || 'b').toLowerCase()]);
167
+ }
168
+
169
+ /**
170
+ * Whether the request carries a body.
171
+ *
172
+ * @param {http.IncomingMessage} req - Request
173
+ * @returns {boolean}
174
+ * @private
175
+ */
176
+ function hasBody(req) {
177
+ if (!req || !req.headers) {
178
+ return false;
179
+ }
180
+ if (req.headers['transfer-encoding'] !== undefined) {
181
+ return true;
182
+ }
183
+ const length = Number(req.headers['content-length']);
184
+ return Number.isFinite(length) && length > 0;
185
+ }
186
+
187
+ /**
188
+ * Decide how to parse a request.
189
+ *
190
+ * @param {string} contentType - Lower-cased Content-Type header
191
+ * @param {string} type - Configured type
192
+ * @returns {string|null} Parser kind, or null to skip
193
+ * @private
194
+ */
195
+ function detectKind(contentType, type) {
196
+ const isJson = /^application\/(?:[\w.+-]+\+)?json\b/.test(contentType);
197
+ const isUrlencoded = contentType.startsWith('application/x-www-form-urlencoded');
198
+ const isMultipart = contentType.startsWith('multipart/form-data');
199
+ const isText = contentType.startsWith('text/');
200
+
201
+ if (type === 'auto') {
202
+ if (isJson) return 'json';
203
+ if (isUrlencoded) return 'urlencoded';
204
+ if (isMultipart) return 'multipart';
205
+ if (isText) return 'text';
206
+ return null;
207
+ }
208
+
209
+ if (type === 'raw') {
210
+ return 'raw';
211
+ }
212
+
213
+ const matches = { json: isJson, urlencoded: isUrlencoded, multipart: isMultipart, text: isText };
214
+ if (!(type in matches)) {
215
+ return null;
216
+ }
217
+ return matches[type] || contentType === '' ? type : null;
218
+ }
219
+
220
+ /**
221
+ * Create an error carrying an HTTP status.
222
+ *
223
+ * @param {number} status - HTTP status
224
+ * @param {string} message - Message
225
+ * @returns {Error}
226
+ * @private
227
+ */
228
+ function clientError(status, message) {
229
+ const error = new Error(message);
230
+ error.status = status;
231
+ return error;
232
+ }
233
+
234
+ /**
235
+ * Parse JSON with depth/size limits, dropping `__proto__` keys.
236
+ *
237
+ * @param {string} text - JSON text
238
+ * @param {Object} opts - Parser options
239
+ * @returns {*} Parsed value
240
+ * @private
241
+ */
242
+ function parseJson(text, opts) {
243
+ if (text.trim() === '') {
244
+ return {};
245
+ }
246
+ try {
247
+ return safeJSONParse(text, { maxDepth: 20, maxSize: opts.limit, reviver: dropProtoKeys });
248
+ } catch (error) {
249
+ throw clientError(400, error.message.startsWith('Invalid JSON') ? error.message : `Invalid JSON: ${error.message}`);
250
+ }
251
+ }
252
+
253
+ function dropProtoKeys(key, value) {
254
+ return key === '__proto__' ? undefined : value;
255
+ }
256
+
257
+ /**
258
+ * Read the request body into a Buffer, enforcing the size limit on the
259
+ * decoded bytes and decompressing gzip/deflate/br bodies when allowed.
260
+ *
261
+ * @param {http.IncomingMessage} req - Request
262
+ * @param {Object} opts - Parser options
263
+ * @param {string} encoding - Content-Encoding (lower case)
264
+ * @returns {Promise<Buffer>}
265
+ * @private
266
+ */
267
+ function readBody(req, opts, encoding) {
268
+ return new Promise((resolve, reject) => {
269
+ if (req.readableEnded) {
270
+ resolve(Buffer.alloc(0));
271
+ return;
272
+ }
273
+
274
+ let stream = req;
275
+ if (encoding !== 'identity') {
276
+ if (!opts.inflate) {
277
+ reject(clientError(415, `Content-Encoding "${encoding}" is not accepted`));
278
+ return;
279
+ }
280
+ const decoders = {
281
+ gzip: () => zlib.createGunzip(),
282
+ 'x-gzip': () => zlib.createGunzip(),
283
+ deflate: () => zlib.createInflate(),
284
+ br: () => zlib.createBrotliDecompress()
285
+ };
286
+ if (!decoders[encoding]) {
287
+ reject(clientError(415, `Unsupported Content-Encoding "${encoding}"`));
288
+ return;
289
+ }
290
+ stream = decoders[encoding]();
291
+ req.pipe(stream);
292
+ }
293
+
294
+ const chunks = [];
295
+ let size = 0;
296
+ let settled = false;
297
+
298
+ const cleanup = () => {
299
+ stream.removeListener('data', onData);
300
+ stream.removeListener('end', onEnd);
301
+ stream.removeListener('error', onError);
302
+ req.removeListener('aborted', onAborted);
303
+ req.removeListener('error', onError);
304
+ };
305
+ const fail = (error) => {
306
+ if (settled) return;
307
+ settled = true;
308
+ cleanup();
309
+ if (stream !== req) {
310
+ req.unpipe(stream);
311
+ stream.destroy();
312
+ }
313
+ // Stop reading the upload; the connection is closed after the reply.
314
+ req.pause();
315
+ reject(error);
316
+ };
317
+ const onData = (chunk) => {
318
+ size += chunk.length;
319
+ if (size > opts.limit) {
320
+ fail(clientError(413, 'Request entity too large'));
321
+ return;
322
+ }
323
+ chunks.push(chunk);
324
+ };
325
+ const onEnd = () => {
326
+ if (settled) return;
327
+ settled = true;
328
+ cleanup();
329
+ resolve(Buffer.concat(chunks, size));
330
+ };
331
+ const onError = (error) => {
332
+ const err = error instanceof Error ? error : new Error(String(error));
333
+ if (!err.status) {
334
+ err.status = 400;
335
+ }
336
+ fail(err);
337
+ };
338
+ const onAborted = () => fail(clientError(400, 'Request aborted'));
339
+
340
+ stream.on('data', onData);
341
+ stream.on('end', onEnd);
342
+ stream.on('error', onError);
343
+ req.on('aborted', onAborted);
344
+ if (stream !== req) {
345
+ req.on('error', onError);
346
+ }
347
+ });
348
+ }
349
+
350
+ /**
351
+ * Extract the multipart boundary from a Content-Type header.
352
+ *
353
+ * @param {string} contentType - Content-Type header
354
+ * @returns {string|null} Boundary
355
+ * @private
356
+ */
357
+ function getBoundary(contentType) {
358
+ const match = /boundary=(?:"([^"]+)"|'([^']+)'|([^;\s]+))/i.exec(contentType || '');
359
+ if (!match) return null;
360
+ const boundary = match[1] || match[2] || match[3];
361
+ if (!boundary || boundary.length > 70) {
362
+ return null;
363
+ }
364
+ return boundary;
365
+ }
366
+
367
+ /**
368
+ * Parse multipart/form-data. Works on raw bytes so binary file contents are
369
+ * preserved; text fields are decoded as UTF-8.
370
+ *
371
+ * @param {Buffer} buffer - Raw body
372
+ * @param {string} boundary - Multipart boundary
373
+ * @returns {{fields: Object, files: Object}} Parsed fields and files (null-prototype objects)
374
+ * @private
375
+ */
376
+ function parseMultipartData(buffer, boundary) {
377
+ const fields = Object.create(null);
378
+ const files = Object.create(null);
379
+ const dangerousKeys = ['__proto__', 'constructor', 'prototype'];
380
+
381
+ // latin1 maps every byte to one code unit, so string offsets equal byte offsets
382
+ const body = buffer.toString('latin1');
383
+ const parts = body.split(`--${boundary}`);
384
+
385
+ for (let i = 1; i < parts.length - 1; i++) {
386
+ const part = parts[i];
387
+ if (!part) continue;
388
+
389
+ const headerEndIndex = part.indexOf('\r\n\r\n');
390
+ if (headerEndIndex === -1) continue;
391
+
392
+ const headerLines = part.substring(0, headerEndIndex).split('\r\n').filter(Boolean);
393
+ // Content ends with the CRLF that precedes the next boundary
394
+ let content = part.substring(headerEndIndex + 4);
395
+ if (content.endsWith('\r\n')) {
396
+ content = content.slice(0, -2);
397
+ }
398
+
399
+ const header = (name) => {
400
+ const line = headerLines.find(l => l.toLowerCase().startsWith(`${name}:`));
401
+ return line ? line.slice(name.length + 1).trim() : null;
402
+ };
403
+
404
+ const contentDisposition = header('content-disposition');
405
+ if (!contentDisposition) continue;
406
+
407
+ const nameMatch = contentDisposition.match(/\bname="([^"]*)"/i);
408
+ if (!nameMatch) continue;
409
+ const name = Buffer.from(nameMatch[1], 'latin1').toString('utf8');
410
+
411
+ if (!name || dangerousKeys.includes(name) || name.includes('__proto__')) {
412
+ continue;
413
+ }
414
+
415
+ const filenameMatch = contentDisposition.match(/\bfilename="([^"]*)"/i);
416
+ if (filenameMatch) {
417
+ const filename = Buffer.from(filenameMatch[1], 'latin1').toString('utf8');
418
+ const sanitizedFilename = filename
419
+ .replace(/[/\\]/g, '') // Remove path separators
420
+ .replace(/\.\./g, '') // Remove parent directory references
421
+ .replace(/\0/g, '') // Remove null bytes
422
+ .substring(0, 255);
423
+ const data = Buffer.from(content, 'latin1');
424
+
425
+ files[name] = {
426
+ filename: sanitizedFilename,
427
+ contentType: header('content-type') || 'application/octet-stream',
428
+ size: data.length,
429
+ data
430
+ };
431
+ } else {
432
+ fields[name] = Buffer.from(content, 'latin1').toString('utf8');
433
+ }
434
+ }
435
+
436
+ return { fields, files };
437
+ }
438
+
439
+ /**
440
+ * JSON body parser (parses application/json and +json bodies)
441
+ *
442
+ * @param {Object} [options] - Body parser options
443
+ * @returns {Function} Middleware
444
+ */
445
+ function json(options) {
446
+ return bodyParser({ ...options, type: 'json' });
447
+ }
448
+
449
+ /**
450
+ * URL-encoded form body parser
451
+ *
452
+ * @param {Object} [options] - Body parser options
453
+ * @returns {Function} Middleware
454
+ */
455
+ function urlencoded(options) {
456
+ return bodyParser({ ...options, type: 'urlencoded' });
457
+ }
458
+
459
+ /**
460
+ * Text body parser (text/* bodies)
461
+ *
462
+ * @param {Object} [options] - Body parser options
463
+ * @returns {Function} Middleware
464
+ */
465
+ function text(options) {
466
+ return bodyParser({ ...options, type: 'text' });
467
+ }
468
+
469
+ /**
470
+ * Raw body parser (any request body, as a Buffer)
471
+ *
472
+ * @param {Object} [options] - Body parser options
473
+ * @returns {Function} Middleware
474
+ */
475
+ function raw(options) {
476
+ return bodyParser({ ...options, type: 'raw' });
477
+ }
478
+
479
+ module.exports = bodyParser;
480
+ module.exports.json = json;
481
+ module.exports.urlencoded = urlencoded;
482
+ module.exports.text = text;
483
+ module.exports.raw = raw;
484
+ module.exports.parseLimit = parseLimit;