ultimate-express 1.2.14 → 1.2.16

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.
@@ -1,316 +1,316 @@
1
- /*
2
- Copyright 2024 dimden.dev
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- const fs = require('fs');
18
- const path = require('path');
19
- const bytes = require('bytes');
20
- const zlib = require('fast-zlib');
21
- const typeis = require('type-is');
22
- const querystring = require('fast-querystring');
23
- const { fastQueryParse } = require('./utils.js');
24
-
25
- function static(root, options) {
26
- if(!options) options = {};
27
- if(typeof options.index === 'undefined') options.index = 'index.html';
28
- if(typeof options.redirect === 'undefined') options.redirect = true;
29
- if(typeof options.fallthrough === 'undefined') options.fallthrough = true;
30
- if(typeof options.dotfiles === 'undefined') options.dotfiles = 'ignore_files';
31
- if(options.extensions) {
32
- if(typeof options.extensions !== 'string' && !Array.isArray(options.extensions)) {
33
- throw new Error('extensions must be a string or an array');
34
- }
35
- if(!Array.isArray(options.extensions)) {
36
- options.extensions = [options.extensions];
37
- }
38
- options.extensions = options.extensions.map(ext => ext.startsWith('.') ? ext.slice(1) : ext);
39
- }
40
- options.root = root;
41
- options.skipEncodePath = true;
42
-
43
- return (req, res, next) => {
44
- const iq = req.url.indexOf('?');
45
- let url = decodeURIComponent(iq !== -1 ? req.url.substring(0, iq) : req.url);
46
- let _path = url;
47
- let fullpath = path.resolve(path.join(options.root, url));
48
- if(options.root && !fullpath.startsWith(path.resolve(options.root))) {
49
- if(!options.fallthrough) {
50
- res.status(403);
51
- return next(new Error('Forbidden'));
52
- } else return next();
53
- }
54
-
55
- let stat;
56
- try {
57
- stat = fs.statSync(fullpath);
58
- } catch(err) {
59
- const ext = path.extname(fullpath);
60
- let i = 0;
61
- if(ext === '' && options.extensions) {
62
- while(i < options.extensions.length) {
63
- try {
64
- stat = fs.statSync(fullpath + '.' + options.extensions[i]);
65
- _path = url + '.' + options.extensions[i];
66
- break;
67
- } catch(err) {
68
- i++;
69
- }
70
- }
71
- }
72
- if(!stat) {
73
- if(!options.fallthrough) {
74
- res.status(404);
75
- return next(err.message);
76
- } else return next();
77
- }
78
- }
79
-
80
- if(stat.isDirectory()) {
81
- if(!req.endsWithSlash) {
82
- if(options.redirect) return res.redirect(301, req.path + '/');
83
- else {
84
- if(!options.fallthrough) {
85
- res.status(404);
86
- return next(new Error('Not found'));
87
- } else return next();
88
- }
89
- }
90
- if(options.index) {
91
- try {
92
- stat = fs.statSync(path.join(fullpath, options.index));
93
- _path = path.join(url, options.index);
94
- } catch(err) {
95
- if(!options.fallthrough) {
96
- res.status(404);
97
- return next(new Error('Not found'));
98
- } else return next();
99
- }
100
- } else {
101
-
102
- return next();
103
- }
104
- }
105
-
106
- options._stat = stat;
107
-
108
- return res.sendFile(_path, options, e => {
109
- if(e) {
110
- next(!options.fallthrough ? e : undefined);
111
- }
112
- });
113
- }
114
- }
115
-
116
- function createInflate(contentEncoding) {
117
- const encoding = (contentEncoding || 'identity').toLowerCase();
118
- switch(encoding) {
119
- case 'identity':
120
- return;
121
- case 'deflate':
122
- return new zlib.Inflate();
123
- case 'gzip':
124
- return new zlib.Gunzip();
125
- case 'br':
126
- return new zlib.BrotliDecompress();
127
- default:
128
- return false;
129
- }
130
- }
131
-
132
- function createBodyParser(defaultType, beforeReturn) {
133
- return function(options) {
134
- if(typeof options !== 'object') {
135
- options = {};
136
- }
137
- if(typeof options.limit === 'undefined') options.limit = bytes('100kb');
138
- else options.limit = bytes(options.limit);
139
-
140
- if(typeof options.type === 'undefined') options.type = defaultType;
141
- else if(typeof options.type !== 'string') {
142
- throw new Error('type must be a string');
143
- }
144
- if(typeof options.inflate === 'undefined') options.inflate = true;
145
- if(typeof options.type === 'string') {
146
- if(!options.type.includes("*")) {
147
- options.simpleType = options.type;
148
- }
149
- options.type = [options.type];
150
- } else if(typeof options.type !== 'function' && !Array.isArray(options.type)) {
151
- throw new Error('type must be a string, function or an array');
152
- }
153
- if(typeof options.defaultCharset === 'undefined') options.defaultCharset = 'utf-8';
154
-
155
- return (req, res, next) => {
156
- const type = req.headers['content-type'];
157
-
158
- // skip reading body for non-json content type
159
- if(!type) {
160
- return next();
161
- }
162
-
163
- // skip reading body twice
164
- if(req.body) {
165
- return next();
166
- }
167
-
168
- const length = req.headers['content-length'];
169
- // skip reading empty body
170
- if(length == '0') {
171
- return next();
172
- }
173
-
174
- // skip reading too large body
175
- if(length && +length > options.limit) {
176
- return next(new Error('Request entity too large'));
177
- }
178
-
179
- if(options.simpleType) {
180
- const semicolonIndex = type.indexOf(';');
181
- const clearType = semicolonIndex !== -1 ? type.substring(0, semicolonIndex) : type;
182
- if(clearType !== options.simpleType) {
183
- return next();
184
- }
185
- } else {
186
- if(typeof options.type === 'function') {
187
- if(!options.type(req)) {
188
- return next();
189
- }
190
- } else {
191
- if(!typeis(req, options.type)) {
192
- return next();
193
- }
194
- }
195
- }
196
-
197
- // skip reading body for non-POST requests
198
- // this makes it +10k req/sec faster
199
- const additionalMethods = req.app.get('body methods');
200
- if(
201
- req.method !== 'POST' &&
202
- req.method !== 'PUT' &&
203
- req.method !== 'PATCH' &&
204
- (!additionalMethods || !additionalMethods.includes(req.method))
205
- ) {
206
- return next();
207
- }
208
-
209
- const abs = [];
210
- let inflate;
211
- let totalSize = 0;
212
- if(options.inflate) {
213
- inflate = createInflate(req.headers['content-encoding']);
214
- if(inflate === false) {
215
- return next(new Error('Unsupported content encoding'));
216
- }
217
- }
218
-
219
- function onData(buf) {
220
- if(!Buffer.isBuffer(buf)) {
221
- buf = Buffer.from(buf);
222
- }
223
- if(inflate) {
224
- buf = inflate.process(buf);
225
- }
226
- abs.push(buf);
227
- totalSize += buf.length;
228
- if(totalSize > options.limit) {
229
- return next(new Error('Request entity too large'));
230
- }
231
- }
232
-
233
- function onEnd() {
234
- const buf = Buffer.concat(abs);
235
- if(options.verify) {
236
- try {
237
- options.verify(req, res, buf);
238
- } catch(e) {
239
- return next(e);
240
- }
241
- }
242
- beforeReturn(req, res, next, options, buf);
243
- }
244
-
245
- // reading data directly from uWS is faster than from a stream
246
- // if we are fast enough (not async), we can do it
247
- // otherwise we need to use a stream since it already started streaming it
248
- if(!req.receivedData) {
249
- req._res.onData((ab, isLast) => {
250
- onData(ab);
251
- if(isLast) {
252
- onEnd();
253
- }
254
- });
255
- } else {
256
- req.on('data', onData);
257
- req.on('end', onEnd);
258
- }
259
- }
260
- }
261
- }
262
-
263
- const json = createBodyParser('application/json', function(req, res, next, options, buf) {
264
- if(options.strict) {
265
- if(req.body && typeof req.body !== 'object') {
266
- return next(new Error('Invalid body'));
267
- }
268
- }
269
- req.body = JSON.parse(buf.toString(), options.reviver);
270
- next();
271
- });
272
-
273
- const raw = createBodyParser('application/octet-stream', function(req, res, next, options, buf) {
274
- req.body = buf;
275
- next();
276
- });
277
-
278
- const text = createBodyParser('text/plain', function(req, res, next, options, buf) {
279
- let contentType = req.headers['content-type'];
280
- let charsetIndex = contentType.indexOf('charset=');
281
- let encoding = options.defaultCharset;
282
- if(charsetIndex !== -1) {
283
- encoding = contentType.substring(charsetIndex + 8);
284
- const semicolonIndex = encoding.indexOf(';');
285
- if(semicolonIndex !== -1) {
286
- encoding = encoding.substring(0, semicolonIndex);
287
- }
288
- encoding = encoding.trim().toLowerCase();
289
- }
290
- if(encoding !== 'utf-8' && encoding !== 'utf-16le' && encoding !== 'latin1') {
291
- return next(new Error('Unsupported charset'));
292
- }
293
- req.body = buf.toString(encoding);
294
- next();
295
- });
296
-
297
- const urlencoded = createBodyParser('application/x-www-form-urlencoded', function(req, res, next, options, buf) {
298
- try {
299
- if(options.extended) {
300
- req.body = fastQueryParse(buf.toString(), options);
301
- } else {
302
- req.body = querystring.parse(buf.toString());
303
- }
304
- } catch(e) {
305
- return next(e);
306
- }
307
- next();
308
- });
309
-
310
- module.exports = {
311
- static,
312
- json,
313
- raw,
314
- text,
315
- urlencoded,
316
- };
1
+ /*
2
+ Copyright 2024 dimden.dev
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const bytes = require('bytes');
20
+ const zlib = require('fast-zlib');
21
+ const typeis = require('type-is');
22
+ const querystring = require('fast-querystring');
23
+ const { fastQueryParse } = require('./utils.js');
24
+
25
+ function static(root, options) {
26
+ if(!options) options = {};
27
+ if(typeof options.index === 'undefined') options.index = 'index.html';
28
+ if(typeof options.redirect === 'undefined') options.redirect = true;
29
+ if(typeof options.fallthrough === 'undefined') options.fallthrough = true;
30
+ if(typeof options.dotfiles === 'undefined') options.dotfiles = 'ignore_files';
31
+ if(options.extensions) {
32
+ if(typeof options.extensions !== 'string' && !Array.isArray(options.extensions)) {
33
+ throw new Error('extensions must be a string or an array');
34
+ }
35
+ if(!Array.isArray(options.extensions)) {
36
+ options.extensions = [options.extensions];
37
+ }
38
+ options.extensions = options.extensions.map(ext => ext.startsWith('.') ? ext.slice(1) : ext);
39
+ }
40
+ options.root = root;
41
+ options.skipEncodePath = true;
42
+
43
+ return (req, res, next) => {
44
+ const iq = req.url.indexOf('?');
45
+ let url = decodeURIComponent(iq !== -1 ? req.url.substring(0, iq) : req.url);
46
+ let _path = url;
47
+ let fullpath = path.resolve(path.join(options.root, url));
48
+ if(options.root && !fullpath.startsWith(path.resolve(options.root))) {
49
+ if(!options.fallthrough) {
50
+ res.status(403);
51
+ return next(new Error('Forbidden'));
52
+ } else return next();
53
+ }
54
+
55
+ let stat;
56
+ try {
57
+ stat = fs.statSync(fullpath);
58
+ } catch(err) {
59
+ const ext = path.extname(fullpath);
60
+ let i = 0;
61
+ if(ext === '' && options.extensions) {
62
+ while(i < options.extensions.length) {
63
+ try {
64
+ stat = fs.statSync(fullpath + '.' + options.extensions[i]);
65
+ _path = url + '.' + options.extensions[i];
66
+ break;
67
+ } catch(err) {
68
+ i++;
69
+ }
70
+ }
71
+ }
72
+ if(!stat) {
73
+ if(!options.fallthrough) {
74
+ res.status(404);
75
+ return next(err.message);
76
+ } else return next();
77
+ }
78
+ }
79
+
80
+ if(stat.isDirectory()) {
81
+ if(!req.endsWithSlash) {
82
+ if(options.redirect) return res.redirect(301, req.path + '/');
83
+ else {
84
+ if(!options.fallthrough) {
85
+ res.status(404);
86
+ return next(new Error('Not found'));
87
+ } else return next();
88
+ }
89
+ }
90
+ if(options.index) {
91
+ try {
92
+ stat = fs.statSync(path.join(fullpath, options.index));
93
+ _path = path.join(url, options.index);
94
+ } catch(err) {
95
+ if(!options.fallthrough) {
96
+ res.status(404);
97
+ return next(new Error('Not found'));
98
+ } else return next();
99
+ }
100
+ } else {
101
+
102
+ return next();
103
+ }
104
+ }
105
+
106
+ options._stat = stat;
107
+
108
+ return res.sendFile(_path, options, e => {
109
+ if(e) {
110
+ next(!options.fallthrough ? e : undefined);
111
+ }
112
+ });
113
+ }
114
+ }
115
+
116
+ function createInflate(contentEncoding) {
117
+ const encoding = (contentEncoding || 'identity').toLowerCase();
118
+ switch(encoding) {
119
+ case 'identity':
120
+ return;
121
+ case 'deflate':
122
+ return new zlib.Inflate();
123
+ case 'gzip':
124
+ return new zlib.Gunzip();
125
+ case 'br':
126
+ return new zlib.BrotliDecompress();
127
+ default:
128
+ return false;
129
+ }
130
+ }
131
+
132
+ function createBodyParser(defaultType, beforeReturn) {
133
+ return function(options) {
134
+ if(typeof options !== 'object') {
135
+ options = {};
136
+ }
137
+ if(typeof options.limit === 'undefined') options.limit = bytes('100kb');
138
+ else options.limit = bytes(options.limit);
139
+
140
+ if(typeof options.type === 'undefined') options.type = defaultType;
141
+ else if(typeof options.type !== 'string') {
142
+ throw new Error('type must be a string');
143
+ }
144
+ if(typeof options.inflate === 'undefined') options.inflate = true;
145
+ if(typeof options.type === 'string') {
146
+ if(!options.type.includes("*")) {
147
+ options.simpleType = options.type;
148
+ }
149
+ options.type = [options.type];
150
+ } else if(typeof options.type !== 'function' && !Array.isArray(options.type)) {
151
+ throw new Error('type must be a string, function or an array');
152
+ }
153
+ if(typeof options.defaultCharset === 'undefined') options.defaultCharset = 'utf-8';
154
+
155
+ return (req, res, next) => {
156
+ const type = req.headers['content-type'];
157
+
158
+ // skip reading body for non-json content type
159
+ if(!type) {
160
+ return next();
161
+ }
162
+
163
+ // skip reading body twice
164
+ if(req.body) {
165
+ return next();
166
+ }
167
+
168
+ const length = req.headers['content-length'];
169
+ // skip reading empty body
170
+ if(length == '0') {
171
+ return next();
172
+ }
173
+
174
+ // skip reading too large body
175
+ if(length && +length > options.limit) {
176
+ return next(new Error('Request entity too large'));
177
+ }
178
+
179
+ if(options.simpleType) {
180
+ const semicolonIndex = type.indexOf(';');
181
+ const clearType = semicolonIndex !== -1 ? type.substring(0, semicolonIndex) : type;
182
+ if(clearType !== options.simpleType) {
183
+ return next();
184
+ }
185
+ } else {
186
+ if(typeof options.type === 'function') {
187
+ if(!options.type(req)) {
188
+ return next();
189
+ }
190
+ } else {
191
+ if(!typeis(req, options.type)) {
192
+ return next();
193
+ }
194
+ }
195
+ }
196
+
197
+ // skip reading body for non-POST requests
198
+ // this makes it +10k req/sec faster
199
+ const additionalMethods = req.app.get('body methods');
200
+ if(
201
+ req.method !== 'POST' &&
202
+ req.method !== 'PUT' &&
203
+ req.method !== 'PATCH' &&
204
+ (!additionalMethods || !additionalMethods.includes(req.method))
205
+ ) {
206
+ return next();
207
+ }
208
+
209
+ const abs = [];
210
+ let inflate;
211
+ let totalSize = 0;
212
+ if(options.inflate) {
213
+ inflate = createInflate(req.headers['content-encoding']);
214
+ if(inflate === false) {
215
+ return next(new Error('Unsupported content encoding'));
216
+ }
217
+ }
218
+
219
+ function onData(buf) {
220
+ if(!Buffer.isBuffer(buf)) {
221
+ buf = Buffer.from(buf);
222
+ }
223
+ if(inflate) {
224
+ buf = inflate.process(buf);
225
+ }
226
+ abs.push(buf);
227
+ totalSize += buf.length;
228
+ if(totalSize > options.limit) {
229
+ return next(new Error('Request entity too large'));
230
+ }
231
+ }
232
+
233
+ function onEnd() {
234
+ const buf = Buffer.concat(abs);
235
+ if(options.verify) {
236
+ try {
237
+ options.verify(req, res, buf);
238
+ } catch(e) {
239
+ return next(e);
240
+ }
241
+ }
242
+ beforeReturn(req, res, next, options, buf);
243
+ }
244
+
245
+ // reading data directly from uWS is faster than from a stream
246
+ // if we are fast enough (not async), we can do it
247
+ // otherwise we need to use a stream since it already started streaming it
248
+ if(!req.receivedData) {
249
+ req._res.onData((ab, isLast) => {
250
+ onData(ab);
251
+ if(isLast) {
252
+ onEnd();
253
+ }
254
+ });
255
+ } else {
256
+ req.on('data', onData);
257
+ req.on('end', onEnd);
258
+ }
259
+ }
260
+ }
261
+ }
262
+
263
+ const json = createBodyParser('application/json', function(req, res, next, options, buf) {
264
+ if(options.strict) {
265
+ if(req.body && typeof req.body !== 'object') {
266
+ return next(new Error('Invalid body'));
267
+ }
268
+ }
269
+ req.body = JSON.parse(buf.toString(), options.reviver);
270
+ next();
271
+ });
272
+
273
+ const raw = createBodyParser('application/octet-stream', function(req, res, next, options, buf) {
274
+ req.body = buf;
275
+ next();
276
+ });
277
+
278
+ const text = createBodyParser('text/plain', function(req, res, next, options, buf) {
279
+ let contentType = req.headers['content-type'];
280
+ let charsetIndex = contentType.indexOf('charset=');
281
+ let encoding = options.defaultCharset;
282
+ if(charsetIndex !== -1) {
283
+ encoding = contentType.substring(charsetIndex + 8);
284
+ const semicolonIndex = encoding.indexOf(';');
285
+ if(semicolonIndex !== -1) {
286
+ encoding = encoding.substring(0, semicolonIndex);
287
+ }
288
+ encoding = encoding.trim().toLowerCase();
289
+ }
290
+ if(encoding !== 'utf-8' && encoding !== 'utf-16le' && encoding !== 'latin1') {
291
+ return next(new Error('Unsupported charset'));
292
+ }
293
+ req.body = buf.toString(encoding);
294
+ next();
295
+ });
296
+
297
+ const urlencoded = createBodyParser('application/x-www-form-urlencoded', function(req, res, next, options, buf) {
298
+ try {
299
+ if(options.extended) {
300
+ req.body = fastQueryParse(buf.toString(), options);
301
+ } else {
302
+ req.body = querystring.parse(buf.toString());
303
+ }
304
+ } catch(e) {
305
+ return next(e);
306
+ }
307
+ next();
308
+ });
309
+
310
+ module.exports = {
311
+ static,
312
+ json,
313
+ raw,
314
+ text,
315
+ urlencoded,
316
+ };