expediate 0.0.3 → 1.0.1

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/static.js DELETED
@@ -1,416 +0,0 @@
1
- /* Copyright 2021 Fabien Bavent
2
- *
3
- * Permission is hereby granted, free of charge, to any person obtaining a
4
- * copy of this software and associated documentation files (the "Software"),
5
- * to deal in the Software without restriction, including without limitation
6
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
7
- * and/or sell copies of the Software, and to permit persons to whom the
8
- * Software is furnished to do so, subject to the following conditions:
9
- *
10
- * The above copyright notice and this permission notice shall be included
11
- * in all copies or substantial portions of the Software.
12
- *
13
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19
- * DEALINGS IN THE SOFTWARE.
20
- */
21
- 'use strict';
22
-
23
- const fs = require('fs'),
24
- path = require('path');
25
- const mime = require('mime');
26
-
27
- // Regular expression to match a path with a directory up component.
28
- const UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/
29
-
30
- const HTTP = {
31
- NOT_MODIFIED: res => httpSend(res, 304),
32
- FORBIDDEN: res => httpSend(res, 403, {
33
- 'Content-Security-Policy': "default-src 'none'",
34
- 'X-Content-Type-Options': 'nosniff'
35
- }, 'Forbidden'),
36
- NOT_FOUND: res => httpSend(res, 404, {
37
- // 'Content-Type': 'text/html; charset=UTF-8',
38
- 'Content-Security-Policy': "default-src 'none'",
39
- 'X-Content-Type-Options': 'nosniff'
40
- }, 'Not Found'),
41
- NOT_ALLOWED: res => httpSend(res, 405, { 'Allow': 'GET, HEAD' }),
42
- PRECONDITION_FAILS: res => httpSend(res, 412, {
43
- 'Content-Security-Policy': "default-src 'none'",
44
- 'X-Content-Type-Options': 'nosniff'
45
- }, 'Precondition Failed'),
46
- INTERNAL_ERROR: (res, err) => httpSend(res, 500, {
47
- 'Content-Security-Policy': "default-src 'none'",
48
- 'X-Content-Type-Options': 'nosniff'
49
- }, `Internal error: ${err}`),
50
- };
51
-
52
- // Destroy a read stream properly
53
- function destroyReadStream(stream) {
54
- stream.destroy()
55
- if (typeof stream.close === 'function') {
56
- // node.js core bug work-around
57
- stream.on('open', _ => {
58
- if (typeof stream.fd === 'number')
59
- stream.close()
60
- })
61
- }
62
- }
63
-
64
- function removeContentHeaders(res) {
65
- var keys = Object.keys(res.getHeaders() || {});
66
- for (let key of keys) {
67
- if (key.substr(0, 8) === 'content-' && key != 'content-location')
68
- res.removeHeader(key)
69
- }
70
- }
71
-
72
- // Create a simple ETag based on file metadata
73
- function createETag(stat) {
74
- var mtime = stat.mtime.getTime().toString(16)
75
- var size = stat.size.toString(16)
76
- return 'W/"' + size + '-' + mtime + '"'
77
- }
78
-
79
- // Basic utility for default answers
80
- function httpSend (res, code, headers, body) {
81
- headers = headers || {}
82
- body = body || ''
83
- res.statusCode = code;
84
- for (let k in headers)
85
- res.setHeader(k.toString(), headers[k].toString())
86
- res.setHeader('Content-Length', Buffer.byteLength(body))
87
- if (body)
88
- res.write(body);
89
- res.end();
90
- }
91
-
92
- // Parse a HTTP token list.
93
- function parseTokenList (str) {
94
- var end = 0
95
- var list = []
96
- var start = 0
97
-
98
- // gather tokens
99
- for (var i = 0, len = str.length; i < len; i++) {
100
- switch (str.charCodeAt(i)) {
101
- case 0x20: /* */
102
- if (start === end) {
103
- start = end = i + 1
104
- }
105
- break
106
- case 0x2c: /* , */
107
- list.push(str.substring(start, end))
108
- start = end = i + 1
109
- break
110
- default:
111
- end = i + 1
112
- break
113
- }
114
- }
115
-
116
- // final token
117
- list.push(str.substring(start, end))
118
-
119
- return list
120
- }
121
-
122
- // Parse an HTTP Date into a number.
123
- function parseHttpDate (date) {
124
- var timestamp = date && Date.parse(date)
125
-
126
- return typeof timestamp === 'number'
127
- ? timestamp
128
- : NaN
129
- }
130
-
131
- function hasCondition(req) {
132
- return req['if-match'] ||
133
- req['if-unmodified-since'] ||
134
- req['if-none-match'] ||
135
- req['if-modified-since']
136
- }
137
-
138
- function conditionMatch(req, res) {
139
-
140
- // if-match
141
- const match = req['if-match']
142
- if (match) {
143
- const etag = res['etag']
144
- if (match === etag || match === '*')
145
- return true;
146
- for (let tag of parseTokenList(match))
147
- if (match === tag || match === 'W/' + tag || 'W/' + match === tag)
148
- return true;
149
- }
150
-
151
- // if-unmodified-since
152
- const lastModified = parseHttpDate(res['last-modified'])
153
- const unmodifiedSince = parseHttpDate(req['if-modified-since'])
154
- if (!isNaN(unmodifiedSince) && !isNaN(lastModified))
155
- return lastModified <= unmodifiedSince
156
-
157
-
158
- return false
159
- }
160
-
161
- // Check freshness of the response using request and response headers.
162
- function isCacheFresh (req, res) {
163
- const CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/
164
- // fields
165
- var modifiedSince = req['if-modified-since']
166
- var noneMatch = req['if-none-match']
167
-
168
- // unconditional request
169
- if (!modifiedSince && !noneMatch) {
170
- return false
171
- }
172
-
173
- // Always return stale when Cache-Control: no-cache
174
- // to support end-to-end reload requests
175
- // https://tools.ietf.org/html/rfc2616#section-14.9.4
176
- var cacheControl = req['cache-control']
177
- if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) {
178
- return false
179
- }
180
-
181
- // if-none-match
182
- if (noneMatch && noneMatch !== '*') {
183
- var etag = res['etag']
184
-
185
- if (!etag) {
186
- return false
187
- }
188
-
189
- var etagStale = true
190
- var matches = parseTokenList(noneMatch)
191
- for (var i = 0; i < matches.length; i++) {
192
- var match = matches[i]
193
- if (match === etag || match === 'W/' + etag || 'W/' + match === etag) {
194
- etagStale = false
195
- break
196
- }
197
- }
198
-
199
- if (etagStale) {
200
- return false
201
- }
202
- }
203
-
204
- // if-modified-since
205
- if (modifiedSince) {
206
- var lastModified = res['last-modified']
207
- var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince))
208
-
209
- if (modifiedStale) {
210
- return false
211
- }
212
- }
213
-
214
- return true
215
- }
216
-
217
- function sendFile(req, res, pathname, stat, opts) {
218
- const len = stat.size
219
- const etag = createETag(stat)
220
-
221
- if (opts.setHeaders)
222
- opts.setHeaders(res);
223
-
224
- // set cache-control
225
- if (!res.getHeader('Cache-Control') && opts.maxage) {
226
- var cacheControl = 'public, max-age=' + Math.floor(opts.maxage / 1000)
227
- if (opts.immutable === true)
228
- cacheControl += ', immutable'
229
- res.setHeader('Cache-Control', cacheControl)
230
- }
231
-
232
- if (!res.getHeader('Last-Modified') && opts.lastModified !== false)
233
- res.setHeader('Last-Modified', stat.mtime.toUTCString())
234
-
235
- if (!res.getHeader('ETag') && opts.etag !== false)
236
- res.setHeader('ETag', etag)
237
-
238
- // set content-type
239
- if (!res.getHeader('Content-Type')) {
240
- if (opts.contentType) {
241
- res.setHeader('Content-Type', opts.contentType)
242
- } else {
243
- var type = mime.lookup(pathname)
244
- if (type) {
245
- var charset = mime.charsets.lookup(type)
246
- if (charset)
247
- res.setHeader('Content-Type', type + '; charset=' + charset)
248
- else
249
- res.setHeader('Content-Type', type)
250
- }
251
- }
252
- }
253
-
254
- // Conditionnal GET
255
- if (hasCondition(req.headers)) {
256
- if (conditionMatch(req.headers, res.getHeaders())) {
257
-
258
- if (isCacheFresh(req.headers, res.getHeaders())) {
259
- removeContentHeaders(res);
260
- return HTTP.NOT_MODIFIED(res);
261
- }
262
- }
263
- // return HTTP.PRECONDITION_FAILS(res)
264
- }
265
-
266
-
267
- // Send data
268
- res.setHeader('Content-Length', len)
269
- if (req.method === 'HEAD')
270
- return res.end()
271
-
272
- let finished = false
273
- const stream = fs.createReadStream(pathname);
274
- res.on('finish', _ => {
275
- finished = true;
276
- destroyReadStream(stream);
277
- });
278
- stream.on('error', err => {
279
- if (finished) return;
280
- console.warn('static error', pathname, err)
281
- HTTP.INTERNAL_ERROR(res, err.code);
282
- finished = true;
283
- destroyReadStream(stream);
284
- });
285
- stream.on('end', _ => {
286
- res.end();
287
- });
288
- stream.pipe(res);
289
- }
290
-
291
- function sendIndex(req, res, pathname, stat, opts) {
292
-
293
- var p = path.join(pathname, 'index.html')
294
- fs.stat(p, function (err, stat) {
295
- if (err) {
296
- if (err.code == 'ENOENT' || err.code == 'ENAMETOOLONG' || err.code == 'ENOTDIR') {
297
- if (opts.fallthrough)
298
- return next();
299
- return HTTP.NOT_FOUND(res)
300
- }
301
- return HTTP.INTERNAL_ERROR(res, err.code);
302
- }
303
-
304
- // index file support
305
- if (stat.isDirectory()) {
306
- return HTTP.NOT_FOUND(res);
307
- }
308
-
309
- sendFile(req, res, p, stat, opts)
310
- })
311
- }
312
-
313
- function serveOptions(root, options) {
314
-
315
- if (!root)
316
- throw new TypeError('root path required')
317
- else if (typeof root !== 'string')
318
- throw new TypeError('root path must be a string')
319
-
320
- // copy options
321
- var opts = options || {
322
- fallthrough: true,
323
- redirect: false,
324
- };
325
- opts.fallthrough = opts.fallthrough !== false
326
- opts.redirect = opts.redirect !== false
327
- opts.maxage = opts.maxage || opts.maxAge || 0
328
- opts.root = path.resolve(root)
329
- if (opts.setHeaders && typeof opts.setHeaders !== 'function')
330
- throw new TypeError('option setHeaders must be function')
331
-
332
- return opts;
333
- }
334
-
335
- function serveStatic (root, options) {
336
-
337
- var opts = serveOptions(root, options);
338
- return function (req, res, next) {
339
-
340
- if (req.method !== 'GET' && req.method !== 'HEAD') {
341
- if (opts.fallthrough)
342
- return next()
343
- return HTTP.NOT_ALLOWED(res);
344
- }
345
-
346
- var originalUrl = decodeURIComponent(/*req.originalUrl || */req.path || req.url)
347
- var pathname = originalUrl
348
-
349
- // make sure redirect occurs at mount
350
- if (pathname === '/' && originalUrl.substr(-1) !== '/') {
351
- pathname = ''
352
- }
353
-
354
- if (UP_PATH_REGEXP.test(pathname))
355
- return HTTP.FORBIDDEN(res);
356
-
357
- // resolve the path
358
- pathname = path.resolve(path.normalize(opts.root + '/' + pathname));
359
-
360
- // dotfile handling
361
- if (opts.dotfiles != 'allow' && pathname.indexOf('/.') >= 0) {
362
- if (opts.dotfiles == 'deny')
363
- return HTTP.FORBIDDEN(res);
364
- return HTTP.NOT_FOUND(res);
365
- }
366
-
367
- fs.stat(pathname, function onstat (err, stat) {
368
- if (err) {
369
- // console.log('DBG', pathname, err.code, req.originalUrl, req.url, req.path)
370
- if (err.code == 'ENOENT' || err.code == 'ENAMETOOLONG' || err.code == 'ENOTDIR') {
371
- if (opts.fallthrough)
372
- return next();
373
- console.warn('static error:', err)
374
- return HTTP.NOT_FOUND(res)
375
- }
376
- return HTTP.INTERNAL_ERROR(res, err.code);
377
- }
378
-
379
- // index file support
380
- if (stat.isDirectory()) {
381
- // if (!opts.redirect)
382
- // return HTTP.NOT_FOUND(res);
383
- return sendIndex(req, res, pathname, stat, opts)
384
- }
385
-
386
-
387
- sendFile(req, res, pathname, stat, opts)
388
- });
389
- }
390
- }
391
-
392
- function serveFile (root, options) {
393
-
394
- var opts = serveOptions(root, options);
395
- return function (req, res, next) {
396
-
397
- if (req.method !== 'GET' && req.method !== 'HEAD') {
398
- if (opts.fallthrough)
399
- return next()
400
- return HTTP.NOT_ALLOWED(res);
401
- }
402
-
403
- const pathname = opts.root;
404
- fs.stat(pathname, function onstat (err, stat) {
405
- if (err)
406
- return HTTP.INTERNAL_ERROR(res, err.code);
407
- if (stat.isDirectory())
408
- return HTTP.INTERNAL_ERROR(res, err.code);
409
-
410
- sendFile(req, res, pathname, stat, opts)
411
- });
412
- }
413
- }
414
-
415
-
416
- module.exports = { serveStatic, serveFile, sendFile, sendIndex };