@zero-server/body 0.9.1 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/index.js +6 -6
- package/lib/body/index.js +14 -0
- package/lib/body/json.js +109 -0
- package/lib/body/multipart.js +440 -0
- package/lib/body/raw.js +71 -0
- package/lib/body/rawBuffer.js +161 -0
- package/lib/body/sendError.js +25 -0
- package/lib/body/text.js +75 -0
- package/lib/body/typeMatch.js +42 -0
- package/lib/body/urlencoded.js +235 -0
- package/package.json +9 -3
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 Tony Wiedman
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tony Wiedman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// AUTO-GENERATED by .tools/generate-package-stubs.js — edit .tools/scope-manifest.js and re-run `npm run packages:generate`.
|
|
2
2
|
'use strict';
|
|
3
|
-
const
|
|
3
|
+
const lib = require("./lib/body");
|
|
4
4
|
|
|
5
5
|
module.exports = {
|
|
6
|
-
json:
|
|
7
|
-
urlencoded:
|
|
8
|
-
text:
|
|
9
|
-
raw:
|
|
10
|
-
multipart:
|
|
6
|
+
json: lib.json,
|
|
7
|
+
urlencoded: lib.urlencoded,
|
|
8
|
+
text: lib.text,
|
|
9
|
+
raw: lib.raw,
|
|
10
|
+
multipart: lib.multipart,
|
|
11
11
|
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module body
|
|
3
|
+
* @description Barrel export for all body-parsing utilities and middleware.
|
|
4
|
+
*/
|
|
5
|
+
const rawBuffer = require('./rawBuffer');
|
|
6
|
+
const isTypeMatch = require('./typeMatch');
|
|
7
|
+
const sendError = require('./sendError');
|
|
8
|
+
const json = require('./json');
|
|
9
|
+
const urlencoded = require('./urlencoded');
|
|
10
|
+
const text = require('./text');
|
|
11
|
+
const raw = require('./raw');
|
|
12
|
+
const multipart = require('./multipart');
|
|
13
|
+
|
|
14
|
+
module.exports = { rawBuffer, isTypeMatch, sendError, json, urlencoded, text, raw, multipart };
|
package/lib/body/json.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module body/json
|
|
3
|
+
* @description JSON body-parsing middleware.
|
|
4
|
+
* Reads the request body, parses it as JSON, and sets `req.body`.
|
|
5
|
+
* Stores the raw buffer on `req.rawBody` for signature verification.
|
|
6
|
+
*/
|
|
7
|
+
const rawBuffer = require('./rawBuffer');
|
|
8
|
+
const { charsetFromContentType } = require('./rawBuffer');
|
|
9
|
+
const isTypeMatch = require('./typeMatch');
|
|
10
|
+
const sendError = require('./sendError');
|
|
11
|
+
|
|
12
|
+
/** @private Recursively remove __proto__, constructor, and prototype keys to prevent prototype pollution. */
|
|
13
|
+
function _sanitize(obj)
|
|
14
|
+
{
|
|
15
|
+
if (!obj || typeof obj !== 'object') return;
|
|
16
|
+
const keys = Object.keys(obj);
|
|
17
|
+
for (let i = 0; i < keys.length; i++)
|
|
18
|
+
{
|
|
19
|
+
const k = keys[i];
|
|
20
|
+
if (k === '__proto__' || k === 'constructor' || k === 'prototype')
|
|
21
|
+
{
|
|
22
|
+
delete obj[k];
|
|
23
|
+
}
|
|
24
|
+
else if (typeof obj[k] === 'object' && obj[k] !== null)
|
|
25
|
+
{
|
|
26
|
+
_sanitize(obj[k]);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Create a JSON body-parsing middleware.
|
|
33
|
+
*
|
|
34
|
+
* @param {object} [options] - Configuration options.
|
|
35
|
+
* @param {string|number} [options.limit] - Max body size (e.g. `'10kb'`). Default `'1mb'`.
|
|
36
|
+
* @param {Function} [options.reviver] - `JSON.parse` reviver function.
|
|
37
|
+
* @param {boolean} [options.strict=true] - When true, reject non-object/array roots.
|
|
38
|
+
* @param {string|string[]|Function} [options.type='application/json'] - Content-Type(s) to match.
|
|
39
|
+
* @param {boolean} [options.requireSecure=false] - When true, reject non-HTTPS requests with 403.
|
|
40
|
+
* @param {Function} [options.verify] - `verify(req, res, buf, encoding)` — called before parsing. Throw to reject with 403.
|
|
41
|
+
* @param {boolean} [options.inflate=true] - Decompress gzip/deflate/br bodies. When false, compressed bodies return 415.
|
|
42
|
+
* @returns {Function} Async middleware `(req, res, next) => void`.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* const { json } = require('@zero-server/sdk');
|
|
46
|
+
*
|
|
47
|
+
* app.use(json({ limit: '500kb', strict: true }));
|
|
48
|
+
*
|
|
49
|
+
* app.post('/api/data', (req, res) => {
|
|
50
|
+
* console.log(req.body); // parsed JSON object
|
|
51
|
+
* res.json({ ok: true });
|
|
52
|
+
* });
|
|
53
|
+
*/
|
|
54
|
+
function json(options = {})
|
|
55
|
+
{
|
|
56
|
+
const opts = options || {};
|
|
57
|
+
const limit = opts.limit !== undefined ? opts.limit : '1mb';
|
|
58
|
+
const reviver = opts.reviver;
|
|
59
|
+
const strict = (opts.hasOwnProperty('strict')) ? !!opts.strict : true;
|
|
60
|
+
const typeOpt = opts.type || 'application/json';
|
|
61
|
+
const requireSecure = !!opts.requireSecure;
|
|
62
|
+
const verify = opts.verify;
|
|
63
|
+
const inflate = opts.inflate !== undefined ? opts.inflate : true;
|
|
64
|
+
|
|
65
|
+
return async (req, res, next) =>
|
|
66
|
+
{
|
|
67
|
+
if (requireSecure && !req.secure) return sendError(res, 403, 'HTTPS required');
|
|
68
|
+
const ct = (req.headers['content-type'] || '');
|
|
69
|
+
if (!isTypeMatch(ct, typeOpt)) return next();
|
|
70
|
+
try
|
|
71
|
+
{
|
|
72
|
+
const buf = await rawBuffer(req, { limit, inflate });
|
|
73
|
+
const encoding = charsetFromContentType(ct) || 'utf8';
|
|
74
|
+
|
|
75
|
+
// Store raw body for webhook signature verification (Stripe, GitHub, etc.)
|
|
76
|
+
req.rawBody = buf;
|
|
77
|
+
|
|
78
|
+
// Optional verification callback (e.g. HMAC signature check)
|
|
79
|
+
if (verify)
|
|
80
|
+
{
|
|
81
|
+
try { verify(req, res, buf, encoding); }
|
|
82
|
+
catch (e) { return sendError(res, 403, e.message || 'verification failed'); }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const txt = buf.toString(encoding);
|
|
86
|
+
if (!txt) { req.body = null; return next(); }
|
|
87
|
+
let parsed;
|
|
88
|
+
try { parsed = JSON.parse(txt, reviver); } catch (e) { return sendError(res, 400, 'invalid JSON'); }
|
|
89
|
+
if (strict && (typeof parsed !== 'object' || parsed === null))
|
|
90
|
+
{
|
|
91
|
+
return sendError(res, 400, 'invalid JSON: root must be object or array');
|
|
92
|
+
}
|
|
93
|
+
// Prevent prototype pollution
|
|
94
|
+
if (parsed && typeof parsed === 'object')
|
|
95
|
+
{
|
|
96
|
+
_sanitize(parsed);
|
|
97
|
+
}
|
|
98
|
+
req.body = parsed;
|
|
99
|
+
} catch (err)
|
|
100
|
+
{
|
|
101
|
+
if (err && err.status === 413) return sendError(res, 413, 'payload too large');
|
|
102
|
+
if (err && err.status === 415) return sendError(res, 415, err.message || 'unsupported encoding');
|
|
103
|
+
req.body = null;
|
|
104
|
+
}
|
|
105
|
+
next();
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
module.exports = json;
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module body/multipart
|
|
3
|
+
* @description Streaming multipart/form-data parser.
|
|
4
|
+
* Writes uploaded files to a temp directory and collects
|
|
5
|
+
* form fields. Sets `req.body = { fields, files }`.
|
|
6
|
+
*/
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const os = require('os');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const sendError = require('./sendError');
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Generate a unique filename with an optional prefix.
|
|
14
|
+
*
|
|
15
|
+
* @private
|
|
16
|
+
* @param {string} [prefix='miniex'] - Filename prefix.
|
|
17
|
+
* @returns {string} Formatted string.
|
|
18
|
+
*/
|
|
19
|
+
function uniqueName(prefix = 'miniex')
|
|
20
|
+
{
|
|
21
|
+
return `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e9)}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Recursively create a directory if it doesn't exist.
|
|
26
|
+
*
|
|
27
|
+
* @private
|
|
28
|
+
* @param {string} dir - Directory path.
|
|
29
|
+
*/
|
|
30
|
+
function ensureDir(dir)
|
|
31
|
+
{
|
|
32
|
+
try { fs.mkdirSync(dir, { recursive: true }); } catch (e) { }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Parse raw MIME header text (CRLF-separated) into a plain object.
|
|
37
|
+
*
|
|
38
|
+
* @private
|
|
39
|
+
* @param {string} headerText - Raw header block.
|
|
40
|
+
* @returns {Object<string, string>} Lower-cased header key/value map.
|
|
41
|
+
*/
|
|
42
|
+
function parseHeaders(headerText)
|
|
43
|
+
{
|
|
44
|
+
const lines = headerText.split('\r\n');
|
|
45
|
+
const obj = {};
|
|
46
|
+
for (const l of lines)
|
|
47
|
+
{
|
|
48
|
+
const idx = l.indexOf(':');
|
|
49
|
+
if (idx === -1) continue;
|
|
50
|
+
const k = l.slice(0, idx).trim().toLowerCase();
|
|
51
|
+
const v = l.slice(idx + 1).trim();
|
|
52
|
+
obj[k] = v;
|
|
53
|
+
}
|
|
54
|
+
return obj;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Sanitize a filename by stripping path traversal characters and
|
|
59
|
+
* null bytes. Keeps only the basename.
|
|
60
|
+
*
|
|
61
|
+
* @private
|
|
62
|
+
* @param {string} filename - Raw filename from the upload.
|
|
63
|
+
* @returns {string} Sanitized filename.
|
|
64
|
+
*/
|
|
65
|
+
function sanitizeFilename(filename)
|
|
66
|
+
{
|
|
67
|
+
if (!filename) return '';
|
|
68
|
+
// Strip null bytes
|
|
69
|
+
let safe = filename.replace(/\0/g, '');
|
|
70
|
+
// Take only the basename (strip directory traversal)
|
|
71
|
+
safe = safe.replace(/^.*[/\\]/, '');
|
|
72
|
+
// Remove leading dots (prevent dotfile creation)
|
|
73
|
+
safe = safe.replace(/^\.+/, '');
|
|
74
|
+
// Replace potentially dangerous characters
|
|
75
|
+
safe = safe.replace(/[<>:"|?*]/g, '_');
|
|
76
|
+
return safe || 'unnamed';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Extract `name` and `filename` fields from a `Content-Disposition` header.
|
|
81
|
+
*
|
|
82
|
+
* @private
|
|
83
|
+
* @param {string} cd - Content-Disposition value.
|
|
84
|
+
* @returns {Object<string, string>} Parsed disposition parameters.
|
|
85
|
+
*/
|
|
86
|
+
function parseContentDisposition(cd)
|
|
87
|
+
{
|
|
88
|
+
const m = /form-data;(.*)/i.exec(cd);
|
|
89
|
+
if (!m) return {};
|
|
90
|
+
const parts = m[1].split(';').map(s => s.trim());
|
|
91
|
+
const out = {};
|
|
92
|
+
for (const p of parts)
|
|
93
|
+
{
|
|
94
|
+
const mm = /([^=]+)="?([^"]+)"?/.exec(p);
|
|
95
|
+
if (mm)
|
|
96
|
+
{
|
|
97
|
+
const key = mm[1].trim();
|
|
98
|
+
let val = mm[2];
|
|
99
|
+
// Sanitize filename values
|
|
100
|
+
if (key === 'filename') val = sanitizeFilename(val);
|
|
101
|
+
out[key] = val;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Create a streaming multipart/form-data parsing middleware.
|
|
109
|
+
*
|
|
110
|
+
* @param {object} [opts] - Configuration options.
|
|
111
|
+
* @param {string} [opts.dir] - Upload directory (default: OS temp dir).
|
|
112
|
+
* @param {number} [opts.maxFileSize] - Maximum size per file in bytes.
|
|
113
|
+
* @param {boolean} [opts.requireSecure=false] - When true, reject non-HTTPS requests with 403.
|
|
114
|
+
* @param {number} [opts.maxFields=1000] - Maximum number of non-file fields. Prevents DoS via field flooding.
|
|
115
|
+
* @param {number} [opts.maxFiles=10] - Maximum number of uploaded files.
|
|
116
|
+
* @param {number} [opts.maxFieldSize] - Maximum size of a single field value in bytes. Default 1 MB.
|
|
117
|
+
* @param {string[]} [opts.allowedMimeTypes] - Whitelist of MIME types for uploaded files (e.g. `['image/png', 'image/jpeg']`).
|
|
118
|
+
* @param {number} [opts.maxTotalSize] - Maximum combined size of all uploaded files in bytes.
|
|
119
|
+
* @returns {Function} Async middleware `(req, res, next) => void`.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* const { multipart } = require('@zero-server/sdk');
|
|
123
|
+
*
|
|
124
|
+
* app.use(multipart({
|
|
125
|
+
* dir: './uploads',
|
|
126
|
+
* maxFileSize: 10 * 1024 * 1024, // 10 MB
|
|
127
|
+
* maxFiles: 5,
|
|
128
|
+
* allowedMimeTypes: ['image/png', 'image/jpeg'],
|
|
129
|
+
* }));
|
|
130
|
+
*
|
|
131
|
+
* app.post('/upload', (req, res) => {
|
|
132
|
+
* const { fields, files } = req.body;
|
|
133
|
+
* res.json({ fields, uploaded: Object.keys(files) });
|
|
134
|
+
* });
|
|
135
|
+
*/
|
|
136
|
+
function multipart(opts = {})
|
|
137
|
+
{
|
|
138
|
+
return async (req, res, next) =>
|
|
139
|
+
{
|
|
140
|
+
if (opts.requireSecure && !req.secure) return sendError(res, 403, 'HTTPS required');
|
|
141
|
+
const ct = req.headers['content-type'] || '';
|
|
142
|
+
const m = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(ct);
|
|
143
|
+
if (!m) return next();
|
|
144
|
+
const boundary = (m[1] || m[2] || '').replace(/^"|"$/g, '');
|
|
145
|
+
const dashBoundary = `--${boundary}`;
|
|
146
|
+
const dashBoundaryBuf = Buffer.from('\r\n' + dashBoundary);
|
|
147
|
+
const startBoundaryBuf = Buffer.from(dashBoundary);
|
|
148
|
+
|
|
149
|
+
let tmpDir;
|
|
150
|
+
if (opts.dir)
|
|
151
|
+
{
|
|
152
|
+
tmpDir = path.isAbsolute(opts.dir) ? opts.dir : path.join(process.cwd(), opts.dir);
|
|
153
|
+
} else
|
|
154
|
+
{
|
|
155
|
+
tmpDir = path.join(os.tmpdir(), 'zero-server-uploads');
|
|
156
|
+
}
|
|
157
|
+
const maxFileSize = opts.maxFileSize || null; // bytes
|
|
158
|
+
const maxFields = opts.maxFields !== undefined ? opts.maxFields : 1000;
|
|
159
|
+
const maxFiles = opts.maxFiles !== undefined ? opts.maxFiles : 10;
|
|
160
|
+
const maxFieldSize = opts.maxFieldSize !== undefined ? opts.maxFieldSize : (1024 * 1024); // 1 MB
|
|
161
|
+
const allowedMimeTypes = opts.allowedMimeTypes || null;
|
|
162
|
+
const maxTotalSize = opts.maxTotalSize || null;
|
|
163
|
+
ensureDir(tmpDir);
|
|
164
|
+
|
|
165
|
+
const fields = {};
|
|
166
|
+
const files = {};
|
|
167
|
+
let fieldCount = 0;
|
|
168
|
+
let fileCount = 0;
|
|
169
|
+
let totalFileSize = 0;
|
|
170
|
+
|
|
171
|
+
let buffer = Buffer.alloc(0);
|
|
172
|
+
let state = 'start'; // start, headers, body
|
|
173
|
+
let current = null; // { headers, name, filename, contentType, writeStream, collectedSize }
|
|
174
|
+
|
|
175
|
+
const pendingWrites = [];
|
|
176
|
+
|
|
177
|
+
function abortFileTooLarge()
|
|
178
|
+
{
|
|
179
|
+
if (current.writeStream) { current.writeStream.on('error', () => {}); try { current.writeStream.destroy(); } catch (e) { } }
|
|
180
|
+
try { fs.unlinkSync(current.filePath); } catch (e) { }
|
|
181
|
+
if (!req._multipartErrorHandled)
|
|
182
|
+
{
|
|
183
|
+
req._multipartErrorHandled = true;
|
|
184
|
+
sendError(res, 413, 'file too large');
|
|
185
|
+
req.raw.pause && req.raw.pause();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function closeCurrent()
|
|
190
|
+
{
|
|
191
|
+
if (!current) return;
|
|
192
|
+
if (current.writeStream)
|
|
193
|
+
{
|
|
194
|
+
// end the stream and record file after it's flushed to disk
|
|
195
|
+
// capture values so we don't rely on `current` later
|
|
196
|
+
const info = { name: current.name, filename: current.filename, filePath: current.filePath, contentType: current.contentType, size: current.collectedSize };
|
|
197
|
+
const p = new Promise((resolve) =>
|
|
198
|
+
{
|
|
199
|
+
current.writeStream.on('finish', () =>
|
|
200
|
+
{
|
|
201
|
+
files[info.name] = { originalFilename: info.filename, storedName: path.basename(info.filePath), path: info.filePath, contentType: info.contentType, size: info.size };
|
|
202
|
+
resolve();
|
|
203
|
+
});
|
|
204
|
+
current.writeStream.on('error', () =>
|
|
205
|
+
{
|
|
206
|
+
resolve();
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
pendingWrites.push(p);
|
|
210
|
+
current.writeStream.end();
|
|
211
|
+
} else
|
|
212
|
+
{
|
|
213
|
+
fields[current.name] = current.value || '';
|
|
214
|
+
}
|
|
215
|
+
current = null;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
req.raw.on('data', (chunk) =>
|
|
219
|
+
{
|
|
220
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
221
|
+
|
|
222
|
+
while (true)
|
|
223
|
+
{
|
|
224
|
+
if (state === 'start')
|
|
225
|
+
{
|
|
226
|
+
// look for starting boundary
|
|
227
|
+
const idx = buffer.indexOf(startBoundaryBuf);
|
|
228
|
+
if (idx === -1)
|
|
229
|
+
{
|
|
230
|
+
// boundary not yet found
|
|
231
|
+
if (buffer.length > startBoundaryBuf.length) buffer = buffer.slice(buffer.length - startBoundaryBuf.length);
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
// consume up to after boundary and CRLF
|
|
235
|
+
const after = idx + startBoundaryBuf.length;
|
|
236
|
+
if (buffer.length < after + 2) break; // wait for CRLF
|
|
237
|
+
buffer = buffer.slice(after);
|
|
238
|
+
if (buffer.slice(0, 2).toString() === '\r\n') buffer = buffer.slice(2);
|
|
239
|
+
state = 'headers';
|
|
240
|
+
} else if (state === 'headers')
|
|
241
|
+
{
|
|
242
|
+
const idx = buffer.indexOf('\r\n\r\n');
|
|
243
|
+
if (idx === -1)
|
|
244
|
+
{
|
|
245
|
+
// wait for more
|
|
246
|
+
if (buffer.length > 1024 * 1024)
|
|
247
|
+
{
|
|
248
|
+
// keep buffer bounded
|
|
249
|
+
buffer = buffer.slice(buffer.length - 1024 * 16);
|
|
250
|
+
}
|
|
251
|
+
break;
|
|
252
|
+
}
|
|
253
|
+
const headerText = buffer.slice(0, idx).toString('utf8');
|
|
254
|
+
buffer = buffer.slice(idx + 4);
|
|
255
|
+
const hdrs = parseHeaders(headerText);
|
|
256
|
+
const disp = hdrs['content-disposition'] || '';
|
|
257
|
+
const cd = parseContentDisposition(disp);
|
|
258
|
+
const name = cd.name;
|
|
259
|
+
const filename = cd.filename;
|
|
260
|
+
const contentType = hdrs['content-type'] || null;
|
|
261
|
+
current = { headers: hdrs, name, filename, contentType, collectedSize: 0 };
|
|
262
|
+
if (filename)
|
|
263
|
+
{
|
|
264
|
+
// Enforce file count limit
|
|
265
|
+
fileCount++;
|
|
266
|
+
if (maxFiles && fileCount > maxFiles)
|
|
267
|
+
{
|
|
268
|
+
if (!req._multipartErrorHandled)
|
|
269
|
+
{
|
|
270
|
+
req._multipartErrorHandled = true;
|
|
271
|
+
sendError(res, 413, 'too many files');
|
|
272
|
+
req.raw.pause && req.raw.pause();
|
|
273
|
+
}
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
// Enforce MIME type whitelist
|
|
277
|
+
if (allowedMimeTypes && contentType && !allowedMimeTypes.includes(contentType))
|
|
278
|
+
{
|
|
279
|
+
if (!req._multipartErrorHandled)
|
|
280
|
+
{
|
|
281
|
+
req._multipartErrorHandled = true;
|
|
282
|
+
sendError(res, 415, 'file type not allowed: ' + contentType);
|
|
283
|
+
req.raw.pause && req.raw.pause();
|
|
284
|
+
}
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
// create temp file; preserve the original extension when possible
|
|
288
|
+
const ext = path.extname(filename) || '';
|
|
289
|
+
const safeExt = ext.replace(/[^a-z0-9.]/gi, '');
|
|
290
|
+
let fname = uniqueName('upload');
|
|
291
|
+
if (safeExt) fname = fname + (safeExt.startsWith('.') ? safeExt : ('.' + safeExt));
|
|
292
|
+
const filePath = path.join(tmpDir, fname);
|
|
293
|
+
current.filePath = filePath;
|
|
294
|
+
current.writeStream = fs.createWriteStream(filePath);
|
|
295
|
+
} else
|
|
296
|
+
{
|
|
297
|
+
// Enforce field count limit
|
|
298
|
+
fieldCount++;
|
|
299
|
+
if (maxFields && fieldCount > maxFields)
|
|
300
|
+
{
|
|
301
|
+
if (!req._multipartErrorHandled)
|
|
302
|
+
{
|
|
303
|
+
req._multipartErrorHandled = true;
|
|
304
|
+
sendError(res, 413, 'too many fields');
|
|
305
|
+
req.raw.pause && req.raw.pause();
|
|
306
|
+
}
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
current.value = '';
|
|
310
|
+
}
|
|
311
|
+
state = 'body';
|
|
312
|
+
} else if (state === 'body')
|
|
313
|
+
{
|
|
314
|
+
// look for boundary preceded by CRLF
|
|
315
|
+
const idx = buffer.indexOf(dashBoundaryBuf);
|
|
316
|
+
if (idx === -1)
|
|
317
|
+
{
|
|
318
|
+
// keep tail in buffer to match partial boundary
|
|
319
|
+
const keep = Math.max(dashBoundaryBuf.length, 1024);
|
|
320
|
+
const writeLen = buffer.length - keep;
|
|
321
|
+
if (writeLen > 0)
|
|
322
|
+
{
|
|
323
|
+
const toWrite = buffer.slice(0, writeLen);
|
|
324
|
+
if (current.writeStream)
|
|
325
|
+
{
|
|
326
|
+
current.collectedSize += toWrite.length;
|
|
327
|
+
totalFileSize += toWrite.length;
|
|
328
|
+
if (maxFileSize && current.collectedSize > maxFileSize)
|
|
329
|
+
{
|
|
330
|
+
abortFileTooLarge();
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (maxTotalSize && totalFileSize > maxTotalSize)
|
|
334
|
+
{
|
|
335
|
+
abortFileTooLarge();
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
current.writeStream.write(toWrite);
|
|
339
|
+
} else
|
|
340
|
+
{
|
|
341
|
+
if (maxFieldSize && current.value.length + toWrite.length > maxFieldSize)
|
|
342
|
+
{
|
|
343
|
+
if (!req._multipartErrorHandled)
|
|
344
|
+
{
|
|
345
|
+
req._multipartErrorHandled = true;
|
|
346
|
+
sendError(res, 413, 'field value too large');
|
|
347
|
+
req.raw.pause && req.raw.pause();
|
|
348
|
+
}
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
current.value += toWrite.toString('utf8');
|
|
352
|
+
}
|
|
353
|
+
buffer = buffer.slice(writeLen);
|
|
354
|
+
}
|
|
355
|
+
break;
|
|
356
|
+
}
|
|
357
|
+
// boundary found at idx; data before idx is body chunk (without the leading CRLF)
|
|
358
|
+
const bodyChunk = buffer.slice(0, idx);
|
|
359
|
+
// if bodyChunk starts with CRLF, strip it
|
|
360
|
+
const toWrite = (bodyChunk.slice(0, 2).toString() === '\r\n') ? bodyChunk.slice(2) : bodyChunk;
|
|
361
|
+
if (toWrite.length)
|
|
362
|
+
{
|
|
363
|
+
if (current.writeStream)
|
|
364
|
+
{
|
|
365
|
+
current.collectedSize += toWrite.length;
|
|
366
|
+
totalFileSize += toWrite.length;
|
|
367
|
+
if (maxFileSize && current.collectedSize > maxFileSize)
|
|
368
|
+
{
|
|
369
|
+
abortFileTooLarge();
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if (maxTotalSize && totalFileSize > maxTotalSize)
|
|
373
|
+
{
|
|
374
|
+
abortFileTooLarge();
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
current.writeStream.write(toWrite);
|
|
378
|
+
} else
|
|
379
|
+
{
|
|
380
|
+
if (maxFieldSize && current.value.length + toWrite.length > maxFieldSize)
|
|
381
|
+
{
|
|
382
|
+
if (!req._multipartErrorHandled)
|
|
383
|
+
{
|
|
384
|
+
req._multipartErrorHandled = true;
|
|
385
|
+
sendError(res, 413, 'field value too large');
|
|
386
|
+
req.raw.pause && req.raw.pause();
|
|
387
|
+
}
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
current.value += toWrite.toString('utf8');
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
// consume boundary marker
|
|
394
|
+
buffer = buffer.slice(idx + dashBoundaryBuf.length);
|
|
395
|
+
// check for final boundary '--'
|
|
396
|
+
if (buffer.slice(0, 2).toString() === '--')
|
|
397
|
+
{
|
|
398
|
+
// final
|
|
399
|
+
closeCurrent();
|
|
400
|
+
// wait for any pending file flushes then continue
|
|
401
|
+
req.raw.pause && req.raw.pause();
|
|
402
|
+
Promise.all(pendingWrites).then(() =>
|
|
403
|
+
{
|
|
404
|
+
req.body = { fields, files };
|
|
405
|
+
req._multipart = true;
|
|
406
|
+
return next();
|
|
407
|
+
}).catch(() =>
|
|
408
|
+
{
|
|
409
|
+
req.body = { fields, files };
|
|
410
|
+
req._multipart = true;
|
|
411
|
+
return next();
|
|
412
|
+
});
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
// trim leading CRLF if present
|
|
416
|
+
if (buffer.slice(0, 2).toString() === '\r\n') buffer = buffer.slice(2);
|
|
417
|
+
// close current and continue to next headers
|
|
418
|
+
closeCurrent();
|
|
419
|
+
state = 'headers';
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
req.raw.on('end', () =>
|
|
425
|
+
{
|
|
426
|
+
// finish any current
|
|
427
|
+
if (current) closeCurrent();
|
|
428
|
+
req.body = { fields, files };
|
|
429
|
+
req._multipart = true;
|
|
430
|
+
next();
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
req.raw.on('error', (err) =>
|
|
434
|
+
{
|
|
435
|
+
next();
|
|
436
|
+
});
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
module.exports = multipart;
|
package/lib/body/raw.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module body/raw
|
|
3
|
+
* @description Raw-buffer body-parsing middleware.
|
|
4
|
+
* Stores the full request body as a Buffer on `req.body`.
|
|
5
|
+
* Also sets `req.rawBody` for signature verification workflows.
|
|
6
|
+
*/
|
|
7
|
+
const rawBuffer = require('./rawBuffer');
|
|
8
|
+
const isTypeMatch = require('./typeMatch');
|
|
9
|
+
const sendError = require('./sendError');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Create a raw-buffer body-parsing middleware.
|
|
13
|
+
*
|
|
14
|
+
* @param {object} [options] - Configuration options.
|
|
15
|
+
* @param {string|number} [options.limit] - Max body size. Default `'1mb'`.
|
|
16
|
+
* @param {string|string[]|Function} [options.type='application/octet-stream'] - Content-Type(s) to match.
|
|
17
|
+
* @param {boolean} [options.requireSecure=false] - When true, reject non-HTTPS requests with 403.
|
|
18
|
+
* @param {Function} [options.verify] - `verify(req, res, buf)` — called before setting body. Throw to reject with 403.
|
|
19
|
+
* @param {boolean} [options.inflate=true] - Decompress gzip/deflate/br bodies. When false, compressed bodies return 415.
|
|
20
|
+
* @returns {Function} Async middleware `(req, res, next) => void`.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* const { raw } = require('@zero-server/sdk');
|
|
24
|
+
*
|
|
25
|
+
* app.use(raw({ type: 'application/octet-stream', limit: '5mb' }));
|
|
26
|
+
*
|
|
27
|
+
* app.post('/upload', (req, res) => {
|
|
28
|
+
* console.log(req.body); // Buffer
|
|
29
|
+
* res.send('received ' + req.body.length + ' bytes');
|
|
30
|
+
* });
|
|
31
|
+
*/
|
|
32
|
+
function raw(options = {})
|
|
33
|
+
{
|
|
34
|
+
const opts = options || {};
|
|
35
|
+
const limit = opts.limit !== undefined ? opts.limit : '1mb';
|
|
36
|
+
const typeOpt = opts.type || 'application/octet-stream';
|
|
37
|
+
const requireSecure = !!opts.requireSecure;
|
|
38
|
+
const verify = opts.verify;
|
|
39
|
+
const inflate = opts.inflate !== undefined ? opts.inflate : true;
|
|
40
|
+
|
|
41
|
+
return async (req, res, next) =>
|
|
42
|
+
{
|
|
43
|
+
if (requireSecure && !req.secure) return sendError(res, 403, 'HTTPS required');
|
|
44
|
+
const ct = (req.headers['content-type'] || '');
|
|
45
|
+
if (!isTypeMatch(ct, typeOpt)) return next();
|
|
46
|
+
try
|
|
47
|
+
{
|
|
48
|
+
const buf = await rawBuffer(req, { limit, inflate });
|
|
49
|
+
|
|
50
|
+
// Store raw body for signature verification
|
|
51
|
+
req.rawBody = buf;
|
|
52
|
+
|
|
53
|
+
// Optional verification callback
|
|
54
|
+
if (verify)
|
|
55
|
+
{
|
|
56
|
+
try { verify(req, res, buf); }
|
|
57
|
+
catch (e) { return sendError(res, 403, e.message || 'verification failed'); }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
req.body = buf;
|
|
61
|
+
} catch (err)
|
|
62
|
+
{
|
|
63
|
+
if (err && err.status === 413) return sendError(res, 413, 'payload too large');
|
|
64
|
+
if (err && err.status === 415) return sendError(res, 415, err.message || 'unsupported encoding');
|
|
65
|
+
req.body = Buffer.alloc(0);
|
|
66
|
+
}
|
|
67
|
+
next();
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
module.exports = raw;
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module body/rawBuffer
|
|
3
|
+
* @description Low-level helper that collects the raw request body into a
|
|
4
|
+
* single Buffer, enforcing an optional byte-size limit.
|
|
5
|
+
* Supports Content-Encoding decompression (gzip, deflate, br)
|
|
6
|
+
* and Content-Length pre-checking for early rejection.
|
|
7
|
+
*/
|
|
8
|
+
const zlib = require('zlib');
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Parse a human-readable size string (e.g. `'10kb'`, `'2mb'`) into bytes.
|
|
12
|
+
*
|
|
13
|
+
* @private
|
|
14
|
+
* @param {string|number|null} limit - Size limit value.
|
|
15
|
+
* @returns {number|null} Byte limit, or `null` for unlimited.
|
|
16
|
+
*/
|
|
17
|
+
function parseLimit(limit)
|
|
18
|
+
{
|
|
19
|
+
if (!limit && limit !== 0) return null;
|
|
20
|
+
if (typeof limit === 'number') return limit;
|
|
21
|
+
if (typeof limit === 'string')
|
|
22
|
+
{
|
|
23
|
+
const v = limit.trim().toLowerCase();
|
|
24
|
+
const num = Number(v.replace(/[^0-9.]/g, ''));
|
|
25
|
+
if (v.endsWith('kb')) return Math.floor(num * 1024);
|
|
26
|
+
if (v.endsWith('mb')) return Math.floor(num * 1024 * 1024);
|
|
27
|
+
if (v.endsWith('gb')) return Math.floor(num * 1024 * 1024 * 1024);
|
|
28
|
+
return Math.floor(num);
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Extract and normalise the charset from a Content-Type header value
|
|
35
|
+
* into a Node.js-compatible `BufferEncoding` name.
|
|
36
|
+
*
|
|
37
|
+
* @param {string} contentType - Full Content-Type header value.
|
|
38
|
+
* @returns {string|null} Normalised encoding or `null` when not specified.
|
|
39
|
+
*/
|
|
40
|
+
function charsetFromContentType(contentType)
|
|
41
|
+
{
|
|
42
|
+
if (!contentType) return null;
|
|
43
|
+
const m = contentType.match(/charset=["']?([^\s;"']+)/i);
|
|
44
|
+
if (!m) return null;
|
|
45
|
+
const raw = m[1].toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
46
|
+
if (raw === 'utf8') return 'utf8';
|
|
47
|
+
if (raw === 'utf16le' || raw === 'utf16' || raw === 'ucs2') return 'utf16le';
|
|
48
|
+
if (raw === 'latin1' || raw === 'iso88591') return 'latin1';
|
|
49
|
+
if (raw === 'ascii' || raw === 'usascii') return 'ascii';
|
|
50
|
+
return 'utf8'; // safe fallback for unknown charsets
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Collect the raw request body into a Buffer.
|
|
55
|
+
*
|
|
56
|
+
* - Rejects with `{ status: 413 }` when `opts.limit` is exceeded.
|
|
57
|
+
* - Rejects with `{ status: 415 }` for unsupported Content-Encoding or
|
|
58
|
+
* when `opts.inflate` is `false` and the body is compressed.
|
|
59
|
+
* - Automatically decompresses gzip / deflate / br when `opts.inflate`
|
|
60
|
+
* is `true` (the default).
|
|
61
|
+
*
|
|
62
|
+
* @param {import('../http/request')} req - Wrapped request (`.raw` stream, `.headers`).
|
|
63
|
+
* @param {object} [opts] - Configuration options.
|
|
64
|
+
* @param {string|number|null} [opts.limit] - Max body size (post-decompression).
|
|
65
|
+
* @param {boolean} [opts.inflate=true] - Decompress gzip/deflate/br bodies.
|
|
66
|
+
* @returns {Promise<Buffer>} Resolved with the full body buffer.
|
|
67
|
+
*/
|
|
68
|
+
function rawBuffer(req, opts = {})
|
|
69
|
+
{
|
|
70
|
+
const limit = parseLimit(opts.limit);
|
|
71
|
+
const inflate = opts.inflate !== false;
|
|
72
|
+
|
|
73
|
+
return new Promise((resolve, reject) =>
|
|
74
|
+
{
|
|
75
|
+
const headers = req.headers || (req.raw && req.raw.headers) || {};
|
|
76
|
+
|
|
77
|
+
// Content-Encoding handling
|
|
78
|
+
const encoding = (headers['content-encoding'] || '').toLowerCase().trim();
|
|
79
|
+
const isCompressed = encoding && encoding !== 'identity';
|
|
80
|
+
|
|
81
|
+
// Content-Length pre-check (skip for compressed bodies — CL is the compressed size)
|
|
82
|
+
if (!isCompressed)
|
|
83
|
+
{
|
|
84
|
+
const cl = parseInt(headers['content-length'], 10);
|
|
85
|
+
if (limit && cl && cl > limit)
|
|
86
|
+
{
|
|
87
|
+
const err = new Error('payload too large');
|
|
88
|
+
err.status = 413;
|
|
89
|
+
return reject(err);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Select stream source (possibly a decompression transform)
|
|
94
|
+
let stream = req.raw;
|
|
95
|
+
if (isCompressed)
|
|
96
|
+
{
|
|
97
|
+
if (!inflate)
|
|
98
|
+
{
|
|
99
|
+
const err = new Error('compressed bodies not accepted');
|
|
100
|
+
err.status = 415;
|
|
101
|
+
return reject(err);
|
|
102
|
+
}
|
|
103
|
+
if (encoding === 'gzip' || encoding === 'x-gzip')
|
|
104
|
+
{
|
|
105
|
+
stream = req.raw.pipe(zlib.createGunzip());
|
|
106
|
+
}
|
|
107
|
+
else if (encoding === 'deflate')
|
|
108
|
+
{
|
|
109
|
+
stream = req.raw.pipe(zlib.createInflate());
|
|
110
|
+
}
|
|
111
|
+
else if (encoding === 'br')
|
|
112
|
+
{
|
|
113
|
+
stream = req.raw.pipe(zlib.createBrotliDecompress());
|
|
114
|
+
}
|
|
115
|
+
else
|
|
116
|
+
{
|
|
117
|
+
const err = new Error('unsupported Content-Encoding: ' + encoding);
|
|
118
|
+
err.status = 415;
|
|
119
|
+
return reject(err);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const chunks = [];
|
|
124
|
+
let total = 0;
|
|
125
|
+
|
|
126
|
+
function cleanup()
|
|
127
|
+
{
|
|
128
|
+
stream.removeListener('data', onData);
|
|
129
|
+
stream.removeListener('end', onEnd);
|
|
130
|
+
stream.removeListener('error', onError);
|
|
131
|
+
}
|
|
132
|
+
function onData(c)
|
|
133
|
+
{
|
|
134
|
+
total += c.length;
|
|
135
|
+
if (limit && total > limit)
|
|
136
|
+
{
|
|
137
|
+
cleanup();
|
|
138
|
+
const err = new Error('payload too large');
|
|
139
|
+
err.status = 413;
|
|
140
|
+
return reject(err);
|
|
141
|
+
}
|
|
142
|
+
chunks.push(c);
|
|
143
|
+
}
|
|
144
|
+
function onEnd()
|
|
145
|
+
{
|
|
146
|
+
cleanup();
|
|
147
|
+
resolve(Buffer.concat(chunks));
|
|
148
|
+
}
|
|
149
|
+
function onError(e)
|
|
150
|
+
{
|
|
151
|
+
cleanup();
|
|
152
|
+
reject(e);
|
|
153
|
+
}
|
|
154
|
+
stream.on('data', onData);
|
|
155
|
+
stream.on('end', onEnd);
|
|
156
|
+
stream.on('error', onError);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
module.exports = rawBuffer;
|
|
161
|
+
module.exports.charsetFromContentType = charsetFromContentType;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module body/sendError
|
|
3
|
+
* @private
|
|
4
|
+
* @description Shared helper for sending HTTP error responses from body parsers.
|
|
5
|
+
* Centralizes the pattern used across all parsers so changes only happen in one place.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Send an HTTP error response.
|
|
10
|
+
*
|
|
11
|
+
* @private
|
|
12
|
+
* @param {object} res - The response wrapper (or raw response).
|
|
13
|
+
* @param {number} status - HTTP status code.
|
|
14
|
+
* @param {string} message - Error message string for the JSON body.
|
|
15
|
+
*/
|
|
16
|
+
function sendError(res, status, message)
|
|
17
|
+
{
|
|
18
|
+
const raw = res.raw || res;
|
|
19
|
+
if (raw.headersSent) return;
|
|
20
|
+
raw.statusCode = status;
|
|
21
|
+
raw.setHeader('Content-Type', 'application/json');
|
|
22
|
+
raw.end(JSON.stringify({ error: message }));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
module.exports = sendError;
|
package/lib/body/text.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module body/text
|
|
3
|
+
* @description Plain-text body-parsing middleware.
|
|
4
|
+
* Reads the request body as a string and sets `req.body`.
|
|
5
|
+
* Stores the raw buffer on `req.rawBody` for signature verification.
|
|
6
|
+
*/
|
|
7
|
+
const rawBuffer = require('./rawBuffer');
|
|
8
|
+
const { charsetFromContentType } = require('./rawBuffer');
|
|
9
|
+
const isTypeMatch = require('./typeMatch');
|
|
10
|
+
const sendError = require('./sendError');
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Create a plain-text body-parsing middleware.
|
|
14
|
+
*
|
|
15
|
+
* @param {object} [options] - Configuration options.
|
|
16
|
+
* @param {string|number} [options.limit] - Max body size. Default `'1mb'`.
|
|
17
|
+
* @param {string} [options.encoding='utf8'] - Fallback character encoding when Content-Type has no charset.
|
|
18
|
+
* @param {string|string[]|Function} [options.type='text/*'] - Content-Type(s) to match.
|
|
19
|
+
* @param {boolean} [options.requireSecure=false] - When true, reject non-HTTPS requests with 403.
|
|
20
|
+
* @param {Function} [options.verify] - `verify(req, res, buf, encoding)` — called before decoding. Throw to reject with 403.
|
|
21
|
+
* @param {boolean} [options.inflate=true] - Decompress gzip/deflate/br bodies. When false, compressed bodies return 415.
|
|
22
|
+
* @returns {Function} Async middleware `(req, res, next) => void`.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* const { text } = require('@zero-server/sdk');
|
|
26
|
+
*
|
|
27
|
+
* app.use(text({ type: 'text/plain', limit: '256kb' }));
|
|
28
|
+
*
|
|
29
|
+
* app.post('/log', (req, res) => {
|
|
30
|
+
* console.log(req.body); // raw string
|
|
31
|
+
* res.send('ok');
|
|
32
|
+
* });
|
|
33
|
+
*/
|
|
34
|
+
function text(options = {})
|
|
35
|
+
{
|
|
36
|
+
const opts = options || {};
|
|
37
|
+
const limit = opts.limit !== undefined ? opts.limit : '1mb';
|
|
38
|
+
const defaultEncoding = opts.encoding || 'utf8';
|
|
39
|
+
const typeOpt = opts.type || 'text/*';
|
|
40
|
+
const requireSecure = !!opts.requireSecure;
|
|
41
|
+
const verify = opts.verify;
|
|
42
|
+
const inflate = opts.inflate !== undefined ? opts.inflate : true;
|
|
43
|
+
|
|
44
|
+
return async (req, res, next) =>
|
|
45
|
+
{
|
|
46
|
+
if (requireSecure && !req.secure) return sendError(res, 403, 'HTTPS required');
|
|
47
|
+
const ct = (req.headers['content-type'] || '');
|
|
48
|
+
if (!isTypeMatch(ct, typeOpt)) return next();
|
|
49
|
+
try
|
|
50
|
+
{
|
|
51
|
+
const buf = await rawBuffer(req, { limit, inflate });
|
|
52
|
+
const encoding = charsetFromContentType(ct) || defaultEncoding;
|
|
53
|
+
|
|
54
|
+
// Store raw body for signature verification
|
|
55
|
+
req.rawBody = buf;
|
|
56
|
+
|
|
57
|
+
// Optional verification callback
|
|
58
|
+
if (verify)
|
|
59
|
+
{
|
|
60
|
+
try { verify(req, res, buf, encoding); }
|
|
61
|
+
catch (e) { return sendError(res, 403, e.message || 'verification failed'); }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
req.body = buf.toString(encoding);
|
|
65
|
+
} catch (err)
|
|
66
|
+
{
|
|
67
|
+
if (err && err.status === 413) return sendError(res, 413, 'payload too large');
|
|
68
|
+
if (err && err.status === 415) return sendError(res, 415, err.message || 'unsupported encoding');
|
|
69
|
+
req.body = '';
|
|
70
|
+
}
|
|
71
|
+
next();
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = text;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module body/typeMatch
|
|
3
|
+
* @private
|
|
4
|
+
* @description Shared Content-Type matching utility for body parsers.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Check whether a Content-Type header matches the configured type filter.
|
|
9
|
+
*
|
|
10
|
+
* @private
|
|
11
|
+
* @param {string} contentType - The request Content-Type header value.
|
|
12
|
+
* @param {string|string[]|function} typeOpt - MIME pattern to match against (e.g. 'application/json', 'text/*', '*\/*'),
|
|
13
|
+
* an array of patterns, or a custom predicate `(ct) => boolean`.
|
|
14
|
+
* @returns {boolean} Boolean result.
|
|
15
|
+
*/
|
|
16
|
+
function isTypeMatch(contentType, typeOpt)
|
|
17
|
+
{
|
|
18
|
+
if (!typeOpt) return true;
|
|
19
|
+
if (typeof typeOpt === 'function') return !!typeOpt(contentType);
|
|
20
|
+
if (Array.isArray(typeOpt)) return typeOpt.some(t => isTypeMatch(contentType, t));
|
|
21
|
+
if (!contentType) return false;
|
|
22
|
+
if (typeOpt === '*/*') return true;
|
|
23
|
+
// Strip charset/parameters from content-type for proper matching
|
|
24
|
+
const semiIdx = contentType.indexOf(';');
|
|
25
|
+
const baseType = semiIdx !== -1 ? contentType.substring(0, semiIdx).trim() : contentType;
|
|
26
|
+
if (typeOpt.endsWith('/*'))
|
|
27
|
+
{
|
|
28
|
+
return baseType.startsWith(typeOpt.slice(0, -1));
|
|
29
|
+
}
|
|
30
|
+
// Suffix pattern: application/*+json matches application/vnd.api+json
|
|
31
|
+
const starIdx = typeOpt.indexOf('/*+');
|
|
32
|
+
if (starIdx !== -1)
|
|
33
|
+
{
|
|
34
|
+
const prefix = typeOpt.slice(0, starIdx + 1); // 'application/'
|
|
35
|
+
const suffix = typeOpt.slice(starIdx + 2); // '+json'
|
|
36
|
+
return baseType.startsWith(prefix) && baseType.endsWith(suffix);
|
|
37
|
+
}
|
|
38
|
+
// Exact or substring match against the base type only
|
|
39
|
+
return baseType.indexOf(typeOpt) !== -1;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = isTypeMatch;
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module body/urlencoded
|
|
3
|
+
* @description URL-encoded body-parsing middleware.
|
|
4
|
+
* Supports both flat (`URLSearchParams`) and extended
|
|
5
|
+
* (nested bracket syntax) parsing modes.
|
|
6
|
+
* Stores the raw buffer on `req.rawBody` for signature verification.
|
|
7
|
+
*/
|
|
8
|
+
const rawBuffer = require('./rawBuffer');
|
|
9
|
+
const isTypeMatch = require('./typeMatch');
|
|
10
|
+
const sendError = require('./sendError');
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Append a value to an existing key, converting to an array when needed.
|
|
14
|
+
*
|
|
15
|
+
* @private
|
|
16
|
+
* @param {*} prev - Previous value for the key (or `undefined`).
|
|
17
|
+
* @param {string} val - New value to append.
|
|
18
|
+
* @returns {string|string[]} Merged value.
|
|
19
|
+
*/
|
|
20
|
+
function appendValue(prev, val)
|
|
21
|
+
{
|
|
22
|
+
if (prev === undefined) return val;
|
|
23
|
+
if (Array.isArray(prev)) { prev.push(val); return prev; }
|
|
24
|
+
// convert existing scalar or object into array to hold multiple values
|
|
25
|
+
return [prev, val];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Create a URL-encoded body-parsing middleware.
|
|
30
|
+
*
|
|
31
|
+
* @param {object} [options] - Configuration options.
|
|
32
|
+
* @param {string|number} [options.limit] - Max body size (e.g. `'10kb'`). Default `'1mb'`.
|
|
33
|
+
* @param {string|string[]|Function} [options.type='application/x-www-form-urlencoded'] - Content-Type(s) to match.
|
|
34
|
+
* @param {boolean} [options.extended=false] - Use nested bracket parsing (e.g. `a[b][c]=1`).
|
|
35
|
+
* @param {boolean} [options.requireSecure=false] - When true, reject non-HTTPS requests with 403.
|
|
36
|
+
* @param {number} [options.parameterLimit=1000] - Max number of parameters. Prevents DoS via huge payloads.
|
|
37
|
+
* @param {number} [options.depth=32] - Max nesting depth for bracket syntax. Prevents deep-nesting DoS.
|
|
38
|
+
* @param {Function} [options.verify] - `verify(req, res, buf, encoding)` — called before parsing. Throw to reject with 403.
|
|
39
|
+
* @param {boolean} [options.inflate=true] - Decompress gzip/deflate/br bodies.
|
|
40
|
+
* @returns {Function} Async middleware `(req, res, next) => void`.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* const { urlencoded } = require('@zero-server/sdk');
|
|
44
|
+
*
|
|
45
|
+
* // Flat parsing (default)
|
|
46
|
+
* app.use(urlencoded({ limit: '100kb' }));
|
|
47
|
+
*
|
|
48
|
+
* // Nested bracket syntax
|
|
49
|
+
* app.use(urlencoded({ extended: true }));
|
|
50
|
+
*
|
|
51
|
+
* app.post('/form', (req, res) => {
|
|
52
|
+
* console.log(req.body); // { name: 'Tony', age: '30' }
|
|
53
|
+
* res.json(req.body);
|
|
54
|
+
* });
|
|
55
|
+
*/
|
|
56
|
+
function urlencoded(options = {})
|
|
57
|
+
{
|
|
58
|
+
const opts = options || {};
|
|
59
|
+
const limit = opts.limit !== undefined ? opts.limit : '1mb';
|
|
60
|
+
const typeOpt = opts.type || 'application/x-www-form-urlencoded';
|
|
61
|
+
const extended = !!opts.extended;
|
|
62
|
+
const requireSecure = !!opts.requireSecure;
|
|
63
|
+
const parameterLimit = opts.parameterLimit !== undefined ? opts.parameterLimit : 1000;
|
|
64
|
+
const maxDepth = opts.depth !== undefined ? opts.depth : 32;
|
|
65
|
+
const verify = opts.verify;
|
|
66
|
+
const inflate = opts.inflate !== undefined ? opts.inflate : true;
|
|
67
|
+
|
|
68
|
+
return async (req, res, next) =>
|
|
69
|
+
{
|
|
70
|
+
if (requireSecure && !req.secure) return sendError(res, 403, 'HTTPS required');
|
|
71
|
+
const ct = (req.headers['content-type'] || '');
|
|
72
|
+
if (!isTypeMatch(ct, typeOpt)) return next();
|
|
73
|
+
try
|
|
74
|
+
{
|
|
75
|
+
const buf = await rawBuffer(req, { limit, inflate });
|
|
76
|
+
|
|
77
|
+
// Store raw body for signature verification
|
|
78
|
+
req.rawBody = buf;
|
|
79
|
+
|
|
80
|
+
// Optional verification callback
|
|
81
|
+
if (verify)
|
|
82
|
+
{
|
|
83
|
+
try { verify(req, res, buf, 'utf8'); }
|
|
84
|
+
catch (e) { return sendError(res, 403, e.message || 'verification failed'); }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const txt = buf.toString('utf8');
|
|
88
|
+
if (!extended)
|
|
89
|
+
{
|
|
90
|
+
const params = new URLSearchParams(txt);
|
|
91
|
+
// Enforce parameter limit
|
|
92
|
+
if (parameterLimit)
|
|
93
|
+
{
|
|
94
|
+
let count = 0;
|
|
95
|
+
for (const _ of params) { if (++count > parameterLimit) return sendError(res, 413, 'too many parameters'); }
|
|
96
|
+
}
|
|
97
|
+
req.body = Object.fromEntries(params);
|
|
98
|
+
}
|
|
99
|
+
else
|
|
100
|
+
{
|
|
101
|
+
// extended parsing: support nested bracket syntax like a[b][c]=1 and arrays a[]=1
|
|
102
|
+
const out = {};
|
|
103
|
+
if (txt.trim() === '') { req.body = out; return next(); }
|
|
104
|
+
const pairs = txt.split('&');
|
|
105
|
+
// Enforce parameter limit
|
|
106
|
+
if (parameterLimit && pairs.length > parameterLimit)
|
|
107
|
+
{
|
|
108
|
+
return sendError(res, 413, 'too many parameters');
|
|
109
|
+
}
|
|
110
|
+
for (const p of pairs)
|
|
111
|
+
{
|
|
112
|
+
if (!p) continue;
|
|
113
|
+
const eq = p.indexOf('=');
|
|
114
|
+
let k, v;
|
|
115
|
+
if (eq === -1) { k = decodeURIComponent(p.replace(/\+/g, ' ')); v = ''; }
|
|
116
|
+
else { k = decodeURIComponent(p.slice(0, eq).replace(/\+/g, ' ')); v = decodeURIComponent(p.slice(eq + 1).replace(/\+/g, ' ')); }
|
|
117
|
+
// parse key into parts
|
|
118
|
+
const parts = [];
|
|
119
|
+
const re = /([^\[\]]+)|\[(.*?)\]/g;
|
|
120
|
+
let m;
|
|
121
|
+
while ((m = re.exec(k)) !== null)
|
|
122
|
+
{
|
|
123
|
+
const part = m[1] || m[2];
|
|
124
|
+
// Prevent prototype pollution
|
|
125
|
+
if (part === '__proto__' || part === 'constructor' || part === 'prototype') continue;
|
|
126
|
+
parts.push(part);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Enforce depth limit
|
|
130
|
+
if (maxDepth && parts.length > maxDepth)
|
|
131
|
+
{
|
|
132
|
+
return sendError(res, 400, 'nesting depth exceeded');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// set value into out following parts
|
|
136
|
+
// _parent/_parentKey track the container holding `cur` so we can
|
|
137
|
+
// convert it from object → array when the `[]` push syntax is used.
|
|
138
|
+
let cur = out;
|
|
139
|
+
let _parent = null;
|
|
140
|
+
let _parentKey = null;
|
|
141
|
+
for (let i = 0; i < parts.length; i++)
|
|
142
|
+
{
|
|
143
|
+
const part = parts[i];
|
|
144
|
+
const isLast = (i === parts.length - 1);
|
|
145
|
+
|
|
146
|
+
if (part === '')
|
|
147
|
+
{
|
|
148
|
+
// Empty-bracket array-push syntax: a[]=val / a[][key]=val
|
|
149
|
+
if (isLast)
|
|
150
|
+
{
|
|
151
|
+
// Ensure cur is an array before pushing, converting parent ref if needed
|
|
152
|
+
if (!Array.isArray(cur))
|
|
153
|
+
{
|
|
154
|
+
const arr = [];
|
|
155
|
+
if (_parent !== null) _parent[_parentKey] = arr;
|
|
156
|
+
cur = arr;
|
|
157
|
+
}
|
|
158
|
+
cur.push(v);
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
// Intermediate empty bracket — navigate into next element of the array
|
|
162
|
+
if (!Array.isArray(cur))
|
|
163
|
+
{
|
|
164
|
+
const arr = [];
|
|
165
|
+
if (_parent !== null) _parent[_parentKey] = arr;
|
|
166
|
+
cur = arr;
|
|
167
|
+
}
|
|
168
|
+
if (cur.length === 0 || typeof cur[cur.length - 1] !== 'object') cur.push({});
|
|
169
|
+
_parent = cur;
|
|
170
|
+
_parentKey = cur.length - 1;
|
|
171
|
+
cur = cur[cur.length - 1];
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// normal key
|
|
176
|
+
if (isLast)
|
|
177
|
+
{
|
|
178
|
+
if (Array.isArray(cur))
|
|
179
|
+
{
|
|
180
|
+
// numeric key may indicate index
|
|
181
|
+
const idx = Number(part);
|
|
182
|
+
if (!Number.isNaN(idx)) cur[idx] = appendValue(cur[idx], v);
|
|
183
|
+
else cur[part] = appendValue(cur[part], v);
|
|
184
|
+
}
|
|
185
|
+
else
|
|
186
|
+
{
|
|
187
|
+
cur[part] = appendValue(cur[part], v);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
else
|
|
191
|
+
{
|
|
192
|
+
if (Array.isArray(cur))
|
|
193
|
+
{
|
|
194
|
+
const idx = Number(part);
|
|
195
|
+
if (!Number.isNaN(idx))
|
|
196
|
+
{
|
|
197
|
+
if (!cur[idx]) cur[idx] = {};
|
|
198
|
+
_parent = cur;
|
|
199
|
+
_parentKey = idx;
|
|
200
|
+
cur = cur[idx];
|
|
201
|
+
} else
|
|
202
|
+
{
|
|
203
|
+
// Non-numeric key on array — navigate into last pushed object
|
|
204
|
+
if (cur.length === 0) cur.push({});
|
|
205
|
+
if (typeof cur[cur.length - 1] !== 'object') cur.push({});
|
|
206
|
+
const obj = cur[cur.length - 1];
|
|
207
|
+
if (!obj[part]) obj[part] = {};
|
|
208
|
+
_parent = obj;
|
|
209
|
+
_parentKey = part;
|
|
210
|
+
cur = obj[part];
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
else
|
|
214
|
+
{
|
|
215
|
+
if (!cur[part]) cur[part] = {};
|
|
216
|
+
_parent = cur;
|
|
217
|
+
_parentKey = part;
|
|
218
|
+
cur = cur[part];
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
req.body = out;
|
|
224
|
+
}
|
|
225
|
+
} catch (err)
|
|
226
|
+
{
|
|
227
|
+
if (err && err.status === 413) return sendError(res, 413, 'payload too large');
|
|
228
|
+
if (err && err.status === 415) return sendError(res, 415, err.message || 'unsupported encoding');
|
|
229
|
+
req.body = {};
|
|
230
|
+
}
|
|
231
|
+
next();
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
module.exports = urlencoded;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zero-server/body",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.2",
|
|
4
4
|
"description": "json, urlencoded, text, raw, multipart parsers.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"zero-server",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"./package.json": "./package.json"
|
|
21
21
|
},
|
|
22
22
|
"files": [
|
|
23
|
+
"lib",
|
|
23
24
|
"index.js",
|
|
24
25
|
"index.d.ts",
|
|
25
26
|
"README.md",
|
|
@@ -42,7 +43,12 @@
|
|
|
42
43
|
"access": "public"
|
|
43
44
|
},
|
|
44
45
|
"sideEffects": false,
|
|
45
|
-
"
|
|
46
|
-
"@zero-server/sdk": "0.9.
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@zero-server/sdk": ">=0.9.2"
|
|
48
|
+
},
|
|
49
|
+
"peerDependenciesMeta": {
|
|
50
|
+
"@zero-server/sdk": {
|
|
51
|
+
"optional": true
|
|
52
|
+
}
|
|
47
53
|
}
|
|
48
54
|
}
|