-
Notifications
You must be signed in to change notification settings - Fork 194
/
ecstatic.js
492 lines (422 loc) · 13.9 KB
/
ecstatic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#! /usr/bin/env node
'use strict';
const path = require('path');
const fs = require('fs');
const url = require('url');
const mime = require('./ecstatic/mime');
const urlJoin = require('url-join');
const showDir = require('./ecstatic/show-dir');
const version = require('../package.json').version;
const status = require('./ecstatic/status-handlers');
const generateEtag = require('./ecstatic/etag');
const optsParser = require('./ecstatic/opts');
const onFinished = require('on-finished');
let ecstatic = null;
// See: https://github.com/jesusabdullah/node-ecstatic/issues/109
function decodePathname(pathname) {
const pieces = pathname.replace(/\\/g, '/').split('/');
return path.normalize(pieces.map((rawPiece) => {
const piece = decodeURIComponent(rawPiece);
if (process.platform === 'win32' && /\\/.test(piece)) {
throw new Error('Invalid forward slash character');
}
return piece;
}).join('/'));
}
// eslint-disable-next-line no-control-regex
const nonUrlSafeCharsRgx = /[\x00-\x1F\x7F-\uFFFF]+/g;
function ensureUriEncoded(text) {
return String(text).replace(nonUrlSafeCharsRgx, encodeURIComponent);
}
// Check to see if we should try to compress a file with gzip.
function shouldCompressGzip(req) {
const headers = req.headers;
return headers && headers['accept-encoding'] &&
headers['accept-encoding']
.split(',')
.some(el => ['*', 'compress', 'gzip', 'deflate'].indexOf(el.trim()) !== -1)
;
}
function shouldCompressBrotli(req) {
const headers = req.headers;
return headers && headers['accept-encoding'] &&
headers['accept-encoding']
.split(',')
.some(el => ['*', 'br'].indexOf(el.trim()) !== -1)
;
}
function hasGzipId12(gzipped, cb) {
const stream = fs.createReadStream(gzipped, { start: 0, end: 1 });
let buffer = Buffer.from('');
let hasBeenCalled = false;
stream.on('data', (chunk) => {
buffer = Buffer.concat([buffer, chunk], 2);
});
stream.on('error', (err) => {
if (hasBeenCalled) {
throw err;
}
hasBeenCalled = true;
cb(err);
});
stream.on('close', () => {
if (hasBeenCalled) {
return;
}
hasBeenCalled = true;
cb(null, buffer[0] === 31 && buffer[1] === 139);
});
}
module.exports = function createMiddleware(_dir, _options) {
let dir;
let options;
if (typeof _dir === 'string') {
dir = _dir;
options = _options;
} else {
options = _dir;
dir = options.root;
}
const root = path.join(path.resolve(dir), '/');
const opts = optsParser(options);
const cache = opts.cache;
const autoIndex = opts.autoIndex;
const baseDir = opts.baseDir;
let defaultExt = opts.defaultExt;
const handleError = opts.handleError;
const headers = opts.headers;
const serverHeader = opts.serverHeader;
const weakEtags = opts.weakEtags;
const handleOptionsMethod = opts.handleOptionsMethod;
opts.root = dir;
if (defaultExt && /^\./.test(defaultExt)) {
defaultExt = defaultExt.replace(/^\./, '');
}
if (opts.mimeTypes) {
try {
// You can pass a JSON blob here---useful for CLI use
opts.mimeTypes = JSON.parse(opts.mimeTypes);
} catch (e) {
// swallow parse errors, treat this as a string mimetype input
}
if (typeof opts.mimeTypes === 'object') {
mime.define(opts.mimeTypes);
}
if (typeof opts.mimeTypes === 'function') {
mime.setCustomGetType(opts.mimeTypes);
}
}
function shouldReturn304(req, serverLastModified, serverEtag) {
if (!req || !req.headers) {
return false;
}
const clientModifiedSince = req.headers['if-modified-since'];
const clientEtag = req.headers['if-none-match'];
let clientModifiedDate;
if (!clientModifiedSince && !clientEtag) {
// Client did not provide any conditional caching headers
return false;
}
if (clientModifiedSince) {
// Catch "illegal access" dates that will crash v8
// https://github.com/jfhbrook/node-ecstatic/pull/179
try {
clientModifiedDate = new Date(Date.parse(clientModifiedSince));
} catch (err) {
return false;
}
if (clientModifiedDate.toString() === 'Invalid Date') {
return false;
}
// If the client's copy is older than the server's, don't return 304
if (clientModifiedDate < new Date(serverLastModified)) {
return false;
}
}
if (clientEtag) {
// Do a strong or weak etag comparison based on setting
// https://www.ietf.org/rfc/rfc2616.txt Section 13.3.3
if (opts.weakCompare && clientEtag !== serverEtag
&& clientEtag !== `W/${serverEtag}` && `W/${clientEtag}` !== serverEtag) {
return false;
}
if (!opts.weakCompare && (clientEtag !== serverEtag || clientEtag.indexOf('W/') === 0)) {
return false;
}
}
return true;
}
return function middleware(req, res, next) {
// Figure out the path for the file from the given url
const parsed = url.parse(req.url);
let pathname = null;
let file = null;
let gzippedFile = null;
let brotliFile = null;
// Strip any null bytes from the url
// This was at one point necessary because of an old bug in url.parse
//
// See: https://github.com/jfhbrook/node-ecstatic/issues/16#issuecomment-3039914
// See: https://github.com/jfhbrook/node-ecstatic/commit/43f7e72a31524f88f47e367c3cc3af710e67c9f4
//
// But this opens up a regex dos attack vector! D:
//
// Based on some research (ie asking #node-dev if this is still an issue),
// it's *probably* not an issue. :)
/*
while (req.url.indexOf('%00') !== -1) {
req.url = req.url.replace(/\%00/g, '');
}
*/
try {
decodeURIComponent(req.url); // check validity of url
pathname = decodePathname(parsed.pathname);
} catch (err) {
status[400](res, next, { error: err });
return;
}
file = path.normalize(
path.join(
root,
path.relative(path.join('/', baseDir), pathname)
)
);
// determine compressed forms if they were to exist
gzippedFile = `${file}.gz`;
brotliFile = `${file}.br`;
if (serverHeader !== false) {
// Set common headers.
res.setHeader('server', `ecstatic-${version}`);
}
Object.keys(headers).forEach((key) => {
res.setHeader(key, headers[key]);
});
if (req.method === 'OPTIONS' && handleOptionsMethod) {
res.end();
return;
}
// TODO: This check is broken, which causes the 403 on the
// expected 404.
if (file.slice(0, root.length) !== root) {
status[403](res, next);
return;
}
if (req.method && (req.method !== 'GET' && req.method !== 'HEAD')) {
status[405](res, next);
return;
}
function serve(stat) {
if (onFinished.isFinished(res)) {
return;
}
// Do a MIME lookup, fall back to octet-stream and handle gzip
// and brotli special case.
const defaultType = opts.contentType || 'application/octet-stream';
let contentType = mime.getType(file, defaultType);
let charSet;
const range = (req.headers && req.headers.range);
const lastModified = (new Date(stat.mtime)).toUTCString();
const etag = generateEtag(stat, weakEtags);
let cacheControl = cache;
if (contentType) {
charSet = mime.lookupCharset(contentType);
if (charSet) {
contentType += `; charset=${charSet}`;
}
}
if (file === gzippedFile) { // is .gz picked up
res.setHeader('Content-Encoding', 'gzip');
// strip gz ending and lookup mime type
contentType = mime.getType(path.basename(file, '.gz'), defaultType);
} else if (file === brotliFile) { // is .br picked up
res.setHeader('Content-Encoding', 'br');
// strip br ending and lookup mime type
contentType = mime.getType(path.basename(file, '.br'), defaultType);
}
if (typeof cacheControl === 'function') {
cacheControl = cache(pathname);
}
if (typeof cacheControl === 'number') {
cacheControl = `max-age=${cacheControl}`;
}
if (range) {
const total = stat.size;
const parts = range.trim().replace(/bytes=/, '').split('-');
const partialstart = parts[0];
const partialend = parts[1];
const start = parseInt(partialstart, 10);
const end = Math.min(
total - 1,
partialend ? parseInt(partialend, 10) : total - 1
);
const chunksize = (end - start) + 1;
if (start > end || isNaN(start) || isNaN(end)) {
status['416'](res, next);
return;
}
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${total}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': contentType,
'cache-control': cacheControl,
'last-modified': lastModified,
etag,
});
const stream = fs
.createReadStream(file, { start, end })
.on('error', (err) => {
status['500'](res, next, { error: err });
})
.pipe(res);
onFinished(res, () => {
stream.destroy();
});
return;
}
// TODO: Helper for this, with default headers.
res.setHeader('cache-control', cacheControl);
res.setHeader('last-modified', lastModified);
res.setHeader('etag', etag);
// Return a 304 if necessary
if (shouldReturn304(req, lastModified, etag)) {
status[304](res, next);
return;
}
res.setHeader('content-length', stat.size);
res.setHeader('content-type', contentType);
// set the response statusCode if we have a request statusCode.
// This only can happen if we have a 404 with some kind of 404.html
// In all other cases where we have a file we serve the 200
res.statusCode = req.statusCode || 200;
if (req.method === 'HEAD') {
res.end();
return;
}
const stream = fs
.createReadStream(file)
.on('error', (err) => {
status['500'](res, next, { error: err });
})
.pipe(res);
onFinished(res, () => {
stream.destroy();
});
res.on('close', () => {
stream.destroy();
});
}
function statFile() {
fs.stat(file, (err, stat) => {
if (err && (err.code === 'ENOENT' || err.code === 'ENOTDIR')) {
if (req.statusCode === 404) {
// This means we're already trying ./404.html and can not find it.
// So send plain text response with 404 status code
status[404](res, next);
} else if (!path.extname(parsed.pathname).length && defaultExt) {
// If there is no file extension in the path and we have a default
// extension try filename and default extension combination before rendering 404.html.
middleware({
url: `${parsed.pathname}.${defaultExt}${(parsed.search) ? parsed.search : ''}`,
headers: req.headers,
}, res, next);
} else {
// Try to serve default ./404.html
const rawUrl = (handleError ? `/${path.join(baseDir, `404.${defaultExt}`)}` : req.url);
const encodedUrl = ensureUriEncoded(rawUrl);
middleware({
url: encodedUrl,
headers: req.headers,
statusCode: 404,
}, res, next);
}
} else if (err) {
status[500](res, next, { error: err });
} else if (stat.isDirectory()) {
if (!autoIndex && !opts.showDir) {
status[404](res, next);
return;
}
// 302 to / if necessary
if (!pathname.match(/\/$/)) {
res.statusCode = 302;
const q = parsed.query ? `?${parsed.query}` : '';
const d = `${parsed.pathname}/${q}`;
res.setHeader('location', ensureUriEncoded(d));
res.end();
return;
}
if (autoIndex) {
middleware({
url: urlJoin(
encodeURIComponent(pathname),
`/index.${defaultExt}`
),
headers: req.headers,
}, res, (autoIndexError) => {
if (autoIndexError) {
status[500](res, next, { error: autoIndexError });
return;
}
if (opts.showDir) {
showDir(opts, stat)(req, res);
return;
}
status[403](res, next);
});
return;
}
if (opts.showDir) {
showDir(opts, stat)(req, res);
}
} else {
serve(stat);
}
});
}
// serve gzip file if exists and is valid
function tryServeWithGzip() {
fs.stat(gzippedFile, (err, stat) => {
if (!err && stat.isFile()) {
hasGzipId12(gzippedFile, (gzipErr, isGzip) => {
if (!gzipErr && isGzip) {
file = gzippedFile;
serve(stat);
} else {
statFile();
}
});
} else {
statFile();
}
});
}
// serve brotli file if exists, otherwise try gzip
function tryServeWithBrotli(shouldTryGzip) {
fs.stat(brotliFile, (err, stat) => {
if (!err && stat.isFile()) {
file = brotliFile;
serve(stat);
} else if (shouldTryGzip) {
tryServeWithGzip();
} else {
statFile();
}
});
}
const shouldTryBrotli = opts.brotli && shouldCompressBrotli(req);
const shouldTryGzip = opts.gzip && shouldCompressGzip(req);
// always try brotli first, next try gzip, finally serve without compression
if (shouldTryBrotli) {
tryServeWithBrotli(shouldTryGzip);
} else if (shouldTryGzip) {
tryServeWithGzip();
} else {
statFile();
}
};
};
ecstatic = module.exports;
ecstatic.version = version;
ecstatic.showDir = showDir;
ecstatic.mime = mime;