ultimate-express 1.3.11 → 1.3.13

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