-
Notifications
You must be signed in to change notification settings - Fork 97
/
index.js
756 lines (601 loc) · 19.1 KB
/
index.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
// Native
const {promisify} = require('util');
const path = require('path');
const {createHash} = require('crypto');
const {realpath, lstat, createReadStream, readdir} = require('fs');
// Packages
const url = require('fast-url-parser');
const slasher = require('./glob-slash');
const minimatch = require('minimatch');
const pathToRegExp = require('path-to-regexp');
const mime = require('mime-types');
const bytes = require('bytes');
const contentDisposition = require('content-disposition');
const isPathInside = require('path-is-inside');
const parseRange = require('range-parser');
// Other
const directoryTemplate = require('./directory');
const errorTemplate = require('./error');
const etags = new Map();
const calculateSha = (handlers, absolutePath) =>
new Promise((resolve, reject) => {
const hash = createHash('sha1');
hash.update(path.extname(absolutePath));
hash.update('-');
const rs = handlers.createReadStream(absolutePath);
rs.on('error', reject);
rs.on('data', buf => hash.update(buf));
rs.on('end', () => {
const sha = hash.digest('hex');
resolve(sha);
});
});
const sourceMatches = (source, requestPath, allowSegments) => {
const keys = [];
const slashed = slasher(source);
const resolvedPath = path.posix.resolve(requestPath);
let results = null;
if (allowSegments) {
const normalized = slashed.replace('*', '(.*)');
const expression = pathToRegExp(normalized, keys);
results = expression.exec(resolvedPath);
if (!results) {
// clear keys so that they are not used
// later with empty results. this may
// happen if minimatch returns true
keys.length = 0;
}
}
if (results || minimatch(resolvedPath, slashed)) {
return {
keys,
results
};
}
return null;
};
const toTarget = (source, destination, previousPath) => {
const matches = sourceMatches(source, previousPath, true);
if (!matches) {
return null;
}
const {keys, results} = matches;
const props = {};
const {protocol} = url.parse(destination);
const normalizedDest = protocol ? destination : slasher(destination);
const toPath = pathToRegExp.compile(normalizedDest);
for (let index = 0; index < keys.length; index++) {
const {name} = keys[index];
props[name] = results[index + 1];
}
return toPath(props);
};
const applyRewrites = (requestPath, rewrites = [], repetitive) => {
// We need to copy the array, since we're going to modify it.
const rewritesCopy = rewrites.slice();
// If the method was called again, the path was already rewritten
// so we need to make sure to return it.
const fallback = repetitive ? requestPath : null;
if (rewritesCopy.length === 0) {
return fallback;
}
for (let index = 0; index < rewritesCopy.length; index++) {
const {source, destination} = rewrites[index];
const target = toTarget(source, destination, requestPath);
if (target) {
// Remove rules that were already applied
rewritesCopy.splice(index, 1);
// Check if there are remaining ones to be applied
return applyRewrites(slasher(target), rewritesCopy, true);
}
}
return fallback;
};
const ensureSlashStart = target => (target.startsWith('/') ? target : `/${target}`);
const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl) => {
const slashing = typeof trailingSlash === 'boolean';
const defaultType = 301;
const matchHTML = /(\.html|\/index)$/g;
if (redirects.length === 0 && !slashing && !cleanUrl) {
return null;
}
// By stripping the HTML parts from the decoded
// path *before* handling the trailing slash, we make
// sure that only *one* redirect occurs if both
// config options are used.
if (cleanUrl && matchHTML.test(decodedPath)) {
decodedPath = decodedPath.replace(matchHTML, '');
if (decodedPath.indexOf('//') > -1) {
decodedPath = decodedPath.replace(/\/+/g, '/');
}
return {
target: ensureSlashStart(decodedPath),
statusCode: defaultType
};
}
if (slashing) {
const {ext, name} = path.parse(decodedPath);
const isTrailed = decodedPath.endsWith('/');
const isDotfile = name.startsWith('.');
let target = null;
if (!trailingSlash && isTrailed) {
target = decodedPath.slice(0, -1);
} else if (trailingSlash && !isTrailed && !ext && !isDotfile) {
target = `${decodedPath}/`;
}
if (decodedPath.indexOf('//') > -1) {
target = decodedPath.replace(/\/+/g, '/');
}
if (target) {
return {
target: ensureSlashStart(target),
statusCode: defaultType
};
}
}
// This is currently the fastest way to
// iterate over an array
for (let index = 0; index < redirects.length; index++) {
const {source, destination, type} = redirects[index];
const target = toTarget(source, destination, decodedPath);
if (target) {
return {
target,
statusCode: type || defaultType
};
}
}
return null;
};
const appendHeaders = (target, source) => {
for (let index = 0; index < source.length; index++) {
const {key, value} = source[index];
target[key] = value;
}
};
const getHeaders = async (handlers, config, current, absolutePath, stats) => {
const {headers: customHeaders = [], etag = false} = config;
const related = {};
const {base} = path.parse(absolutePath);
const relativePath = path.relative(current, absolutePath);
if (customHeaders.length > 0) {
// By iterating over all headers and never stopping, developers
// can specify multiple header sources in the config that
// might match a single path.
for (let index = 0; index < customHeaders.length; index++) {
const {source, headers} = customHeaders[index];
if (sourceMatches(source, slasher(relativePath))) {
appendHeaders(related, headers);
}
}
}
let defaultHeaders = {};
if (stats) {
defaultHeaders = {
'Content-Length': stats.size,
// Default to "inline", which always tries to render in the browser,
// if that's not working, it will save the file. But to be clear: This
// only happens if it cannot find a appropiate value.
'Content-Disposition': contentDisposition(base, {
type: 'inline'
}),
'Accept-Ranges': 'bytes'
};
if (etag) {
let [mtime, sha] = etags.get(absolutePath) || [];
if (Number(mtime) !== Number(stats.mtime)) {
sha = await calculateSha(handlers, absolutePath);
etags.set(absolutePath, [stats.mtime, sha]);
}
defaultHeaders['ETag'] = `"${sha}"`;
} else {
defaultHeaders['Last-Modified'] = stats.mtime.toUTCString();
}
const contentType = mime.contentType(base);
if (contentType) {
defaultHeaders['Content-Type'] = contentType;
}
}
const headers = Object.assign(defaultHeaders, related);
for (const key in headers) {
if (headers.hasOwnProperty(key) && headers[key] === null) {
delete headers[key];
}
}
return headers;
};
const applicable = (decodedPath, configEntry) => {
if (typeof configEntry === 'boolean') {
return configEntry;
}
if (Array.isArray(configEntry)) {
for (let index = 0; index < configEntry.length; index++) {
const source = configEntry[index];
if (sourceMatches(source, decodedPath)) {
return true;
}
}
return false;
}
return true;
};
const getPossiblePaths = (relativePath, extension) => [
path.join(relativePath, `index${extension}`),
relativePath.endsWith('/') ? relativePath.replace(/\/$/g, extension) : (relativePath + extension)
].filter(item => path.basename(item) !== extension);
const findRelated = async (current, relativePath, rewrittenPath, originalStat) => {
const possible = rewrittenPath ? [rewrittenPath] : getPossiblePaths(relativePath, '.html');
let stats = null;
for (let index = 0; index < possible.length; index++) {
const related = possible[index];
const absolutePath = path.join(current, related);
try {
stats = await originalStat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
throw err;
}
}
if (stats) {
return {
stats,
absolutePath
};
}
}
return null;
};
const canBeListed = (excluded, file) => {
const slashed = slasher(file);
let whether = true;
for (let mark = 0; mark < excluded.length; mark++) {
const source = excluded[mark];
if (sourceMatches(source, slashed)) {
whether = false;
break;
}
}
return whether;
};
const renderDirectory = async (current, acceptsJSON, handlers, methods, config, paths) => {
const {directoryListing, trailingSlash, unlisted = [], renderSingle} = config;
const slashSuffix = typeof trailingSlash === 'boolean' ? (trailingSlash ? '/' : '') : '/';
const {relativePath, absolutePath} = paths;
const excluded = [
'.DS_Store',
'.git',
...unlisted
];
if (!applicable(relativePath, directoryListing) && !renderSingle) {
return {};
}
let files = await handlers.readdir(absolutePath);
const canRenderSingle = renderSingle && (files.length === 1);
for (let index = 0; index < files.length; index++) {
const file = files[index];
const filePath = path.resolve(absolutePath, file);
const details = path.parse(filePath);
// It's important to indicate that the `stat` call was
// spawned by the directory listing, as Now is
// simulating those calls and needs to special-case this.
let stats = null;
if (methods.lstat) {
stats = await handlers.lstat(filePath, true);
} else {
stats = await handlers.lstat(filePath);
}
details.relative = path.join(relativePath, details.base);
if (stats.isDirectory()) {
details.base += slashSuffix;
details.relative += slashSuffix;
details.type = 'folder';
} else {
if (canRenderSingle) {
return {
singleFile: true,
absolutePath: filePath,
stats
};
}
details.ext = details.ext.split('.')[1] || 'txt';
details.type = 'file';
details.size = bytes(stats.size, {
unitSeparator: ' ',
decimalPlaces: 0
});
}
details.title = details.base;
if (canBeListed(excluded, file)) {
files[index] = details;
} else {
delete files[index];
}
}
const toRoot = path.relative(current, absolutePath);
const directory = path.join(path.basename(current), toRoot, slashSuffix);
const pathParts = directory.split(path.sep).filter(Boolean);
// Sort to list directories first, then sort alphabetically
files = files.sort((a, b) => {
const aIsDir = a.type === 'directory';
const bIsDir = b.type === 'directory';
/* istanbul ignore next */
if (aIsDir && !bIsDir) {
return -1;
}
if ((bIsDir && !aIsDir) || (a.base > b.base)) {
return 1;
}
/* istanbul ignore next */
if (a.base < b.base) {
return -1;
}
/* istanbul ignore next */
return 0;
}).filter(Boolean);
// Add parent directory to the head of the sorted files array
if (toRoot.length > 0) {
const directoryPath = [...pathParts].slice(1);
const relative = path.join('/', ...directoryPath, '..', slashSuffix);
files.unshift({
type: 'directory',
base: '..',
relative,
title: relative,
ext: ''
});
}
const subPaths = [];
for (let index = 0; index < pathParts.length; index++) {
const parents = [];
const isLast = index === (pathParts.length - 1);
let before = 0;
while (before <= index) {
parents.push(pathParts[before]);
before++;
}
parents.shift();
subPaths.push({
name: pathParts[index] + (isLast ? slashSuffix : '/'),
url: index === 0 ? '' : parents.join('/') + slashSuffix
});
}
const spec = {
files,
directory,
paths: subPaths
};
const output = acceptsJSON ? JSON.stringify(spec) : directoryTemplate(spec);
return {directory: output};
};
const sendError = async (absolutePath, response, acceptsJSON, current, handlers, config, spec) => {
const {err: original, message, code, statusCode} = spec;
/* istanbul ignore next */
if (original && process.env.NODE_ENV !== 'test') {
console.error(original);
}
response.statusCode = statusCode;
if (acceptsJSON) {
response.setHeader('Content-Type', 'application/json; charset=utf-8');
response.end(JSON.stringify({
error: {
code,
message
}
}));
return;
}
let stats = null;
const errorPage = path.join(current, `${statusCode}.html`);
try {
stats = await handlers.lstat(errorPage);
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(err);
}
}
if (stats) {
let stream = null;
try {
stream = await handlers.createReadStream(errorPage);
const headers = await getHeaders(handlers, config, current, errorPage, stats);
response.writeHead(statusCode, headers);
stream.pipe(response);
return;
} catch (err) {
console.error(err);
}
}
const headers = await getHeaders(handlers, config, current, absolutePath, null);
headers['Content-Type'] = 'text/html; charset=utf-8';
response.writeHead(statusCode, headers);
response.end(errorTemplate({statusCode, message}));
};
const internalError = async (...args) => {
const lastIndex = args.length - 1;
const err = args[lastIndex];
args[lastIndex] = {
statusCode: 500,
code: 'internal_server_error',
message: 'A server error has occurred',
err
};
return sendError(...args);
};
const getHandlers = methods => Object.assign({
lstat: promisify(lstat),
realpath: promisify(realpath),
createReadStream,
readdir: promisify(readdir),
sendError
}, methods);
module.exports = async (request, response, config = {}, methods = {}) => {
const cwd = process.cwd();
const current = config.public ? path.resolve(cwd, config.public) : cwd;
const handlers = getHandlers(methods);
let relativePath = null;
let acceptsJSON = null;
if (request.headers.accept) {
acceptsJSON = request.headers.accept.includes('application/json');
}
try {
relativePath = decodeURIComponent(url.parse(request.url).pathname);
} catch (err) {
return sendError('/', response, acceptsJSON, current, handlers, config, {
statusCode: 400,
code: 'bad_request',
message: 'Bad Request'
});
}
let absolutePath = path.join(current, relativePath);
// Prevent path traversal vulnerabilities. We could do this
// by ourselves, but using the package covers all the edge cases.
if (!isPathInside(absolutePath, current)) {
return sendError(absolutePath, response, acceptsJSON, current, handlers, config, {
statusCode: 400,
code: 'bad_request',
message: 'Bad Request'
});
}
const cleanUrl = applicable(relativePath, config.cleanUrls);
const redirect = shouldRedirect(relativePath, config, cleanUrl);
if (redirect) {
response.writeHead(redirect.statusCode, {
Location: encodeURI(redirect.target)
});
response.end();
return;
}
let stats = null;
// It's extremely important that we're doing multiple stat calls. This one
// right here could technically be removed, but then the program
// would be slower. Because for directories, we always want to see if a related file
// exists and then (after that), fetch the directory itself if no
// related file was found. However (for files, of which most have extensions), we should
// always stat right away.
//
// When simulating a file system without directory indexes, calculating whether a
// directory exists requires loading all the file paths and then checking if
// one of them includes the path of the directory. As that's a very
// performance-expensive thing to do, we need to ensure it's not happening if not really necessary.
if (path.extname(relativePath) !== '') {
try {
stats = await handlers.lstat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
}
}
const rewrittenPath = applyRewrites(relativePath, config.rewrites);
if (!stats && (cleanUrl || rewrittenPath)) {
try {
const related = await findRelated(current, relativePath, rewrittenPath, handlers.lstat);
if (related) {
({stats, absolutePath} = related);
}
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
}
}
if (!stats) {
try {
stats = await handlers.lstat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
}
}
if (stats && stats.isDirectory()) {
let directory = null;
let singleFile = null;
try {
const related = await renderDirectory(current, acceptsJSON, handlers, methods, config, {
relativePath,
absolutePath
});
if (related.singleFile) {
({stats, absolutePath, singleFile} = related);
} else {
({directory} = related);
}
} catch (err) {
if (err.code !== 'ENOENT') {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
}
if (directory) {
const contentType = acceptsJSON ? 'application/json; charset=utf-8' : 'text/html; charset=utf-8';
response.statusCode = 200;
response.setHeader('Content-Type', contentType);
response.end(directory);
return;
}
if (!singleFile) {
// The directory listing is disabled, so we want to
// render a 404 error.
stats = null;
}
}
const isSymLink = stats && stats.isSymbolicLink();
// There are two scenarios in which we want to reply with
// a 404 error: Either the path does not exist, or it is a
// symlink while the `symlinks` option is disabled (which it is by default).
if (!stats || (!config.symlinks && isSymLink)) {
// allow for custom 404 handling
return handlers.sendError(absolutePath, response, acceptsJSON, current, handlers, config, {
statusCode: 404,
code: 'not_found',
message: 'The requested path could not be found'
});
}
// If we figured out that the target is a symlink, we need to
// resolve the symlink and run a new `stat` call just for the
// target of that symlink.
if (isSymLink) {
absolutePath = await handlers.realpath(absolutePath);
stats = await handlers.lstat(absolutePath);
}
const streamOpts = {};
// TODO ? if-range
if (request.headers.range && stats.size) {
const range = parseRange(stats.size, request.headers.range);
if (typeof range === 'object' && range.type === 'bytes') {
const {start, end} = range[0];
streamOpts.start = start;
streamOpts.end = end;
response.statusCode = 206;
} else {
response.statusCode = 416;
response.setHeader('Content-Range', `bytes */${stats.size}`);
}
}
// TODO ? multiple ranges
let stream = null;
try {
stream = await handlers.createReadStream(absolutePath, streamOpts);
} catch (err) {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
const headers = await getHeaders(handlers, config, current, absolutePath, stats);
// eslint-disable-next-line no-undefined
if (streamOpts.start !== undefined && streamOpts.end !== undefined) {
headers['Content-Range'] = `bytes ${streamOpts.start}-${streamOpts.end}/${stats.size}`;
headers['Content-Length'] = streamOpts.end - streamOpts.start + 1;
}
// We need to check for `headers.ETag` being truthy first, otherwise it will
// match `undefined` being equal to `undefined`, which is true.
//
// Checking for `undefined` and `null` is also important, because `Range` can be `0`.
//
// eslint-disable-next-line no-eq-null
if (request.headers.range == null && headers.ETag && headers.ETag === request.headers['if-none-match']) {
response.statusCode = 304;
response.end();
return;
}
response.writeHead(response.statusCode || 200, headers);
stream.pipe(response);
};