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