@oxog/spark 1.1.1 → 1.3.0
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/CHANGELOG.md +656 -315
- package/LICENSE +20 -20
- package/README.md +288 -241
- package/package.json +90 -89
- package/src/core/application.js +1068 -956
- package/src/core/context.js +1098 -830
- package/src/core/middleware.js +303 -217
- package/src/index.js +183 -280
- package/src/middleware/body-parser.js +482 -526
- package/src/middleware/cache.js +177 -170
- package/src/middleware/compression.js +177 -182
- package/src/middleware/cors.js +176 -95
- package/src/middleware/health.js +219 -218
- package/src/middleware/logger.js +195 -194
- package/src/middleware/metrics.js +339 -327
- package/src/middleware/rate-limit.js +367 -319
- package/src/middleware/security.js +442 -332
- package/src/middleware/session.js +647 -529
- package/src/middleware/static.js +404 -299
- package/src/router/layer.js +197 -117
- package/src/router/route.js +149 -123
- package/src/router/router.js +705 -755
- package/src/utils/async-handler.js +145 -147
- package/src/utils/context-pool.js +83 -82
- package/src/utils/regex-validator.js +187 -163
- package/src/utils/safe-json.js +110 -0
- package/types/index.d.ts +538 -291
- package/dist/LICENSE +0 -21
- package/dist/README.md +0 -242
- package/dist/core/application.js +0 -959
- package/dist/core/context.js +0 -833
- package/dist/core/middleware.js +0 -220
- package/dist/core/request.js +0 -335
- package/dist/core/response.js +0 -377
- package/dist/index.js +0 -280
- package/dist/middleware/body-parser.js +0 -528
- package/dist/middleware/cache.js +0 -173
- package/dist/middleware/compression.js +0 -185
- package/dist/middleware/cors.js +0 -97
- package/dist/middleware/health.js +0 -221
- package/dist/middleware/index.js +0 -23
- package/dist/middleware/logger.js +0 -197
- package/dist/middleware/metrics.js +0 -330
- package/dist/middleware/rate-limit.js +0 -322
- package/dist/middleware/security.js +0 -335
- package/dist/middleware/session.js +0 -532
- package/dist/middleware/static.js +0 -301
- package/dist/package.json +0 -62
- package/dist/router/layer.js +0 -119
- package/dist/router/route.js +0 -125
- package/dist/router/router.js +0 -758
- package/dist/types/index.d.ts +0 -291
- package/dist/utils/async-handler.js +0 -150
- package/dist/utils/cache.js +0 -443
- package/dist/utils/context-pool.js +0 -85
- package/dist/utils/error-types.js +0 -134
- package/dist/utils/http.js +0 -415
- package/dist/utils/regex-validator.js +0 -166
- package/src/core/request.js +0 -335
- package/src/core/response.js +0 -377
- package/src/middleware/index.js +0 -23
- package/src/utils/cache.js +0 -443
- package/src/utils/error-types.js +0 -134
- package/src/utils/http.js +0 -415
package/src/middleware/static.js
CHANGED
|
@@ -1,301 +1,406 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
return
|
|
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
|
-
return
|
|
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
|
-
const
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
const
|
|
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
|
-
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Static file serving middleware for Spark Framework
|
|
5
|
+
* @since 1.0.0
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const { promisify } = require('util');
|
|
11
|
+
const crypto = require('crypto');
|
|
12
|
+
|
|
13
|
+
const stat = promisify(fs.stat);
|
|
14
|
+
|
|
15
|
+
// SECURITY: File operation timeout to prevent hanging on slow/malicious filesystems
|
|
16
|
+
const FILE_OPERATION_TIMEOUT = 5000; // 5 seconds
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Reject a promise that does not settle in time.
|
|
20
|
+
*
|
|
21
|
+
* @param {Promise} promise - Promise to wrap
|
|
22
|
+
* @param {number} [timeout] - Timeout in milliseconds
|
|
23
|
+
* @returns {Promise}
|
|
24
|
+
* @private
|
|
25
|
+
*/
|
|
26
|
+
function withTimeout(promise, timeout = FILE_OPERATION_TIMEOUT) {
|
|
27
|
+
let timeoutId;
|
|
28
|
+
|
|
29
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
30
|
+
timeoutId = setTimeout(() => reject(new Error('File operation timeout')), timeout);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
return Promise.race([
|
|
34
|
+
promise.finally(() => clearTimeout(timeoutId)),
|
|
35
|
+
timeoutPromise
|
|
36
|
+
]);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const DEFAULT_MAX_AGE = 0;
|
|
40
|
+
const DEFAULT_INDEX = ['index.html'];
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Create a static file serving middleware.
|
|
44
|
+
*
|
|
45
|
+
* Files are streamed (with backpressure) rather than buffered in memory.
|
|
46
|
+
* Requests that try to leave `root` (`..`, encoded `%2e%2e%2f`, null bytes)
|
|
47
|
+
* never reach the filesystem. Any path segment starting with a dot (for
|
|
48
|
+
* example `/.git/config` or `/.env`) is treated according to `dotfiles`.
|
|
49
|
+
*
|
|
50
|
+
* @param {string} root - Directory to serve
|
|
51
|
+
* @param {Object} [options={}] - Options
|
|
52
|
+
* @param {number} [options.maxAge=0] - Cache-Control max-age in seconds
|
|
53
|
+
* @param {string|string[]} [options.index=['index.html']] - Directory index files (false to disable)
|
|
54
|
+
* @param {string} [options.dotfiles='ignore'] - 'ignore' (404), 'deny' (403) or 'allow'
|
|
55
|
+
* @param {boolean} [options.hidden=false] - Legacy alias for `dotfiles: 'allow'`
|
|
56
|
+
* @param {boolean} [options.etag=true] - Send ETag and honour If-None-Match
|
|
57
|
+
* @param {boolean} [options.lastModified=true] - Send Last-Modified and honour If-Modified-Since
|
|
58
|
+
* @param {string[]} [options.extensions=[]] - Extensions to try when the file is missing
|
|
59
|
+
* @param {boolean} [options.fallthrough=true] - Call next() instead of replying 404/403 for missing or rejected paths
|
|
60
|
+
* @param {boolean} [options.redirect=true] - Redirect directories to a trailing slash
|
|
61
|
+
* @param {Function} [options.setHeaders] - Called as setHeaders(ctx, fileName, stats)
|
|
62
|
+
* @returns {Function} Middleware
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* app.use(staticFiles('./public', { maxAge: 3600 }));
|
|
66
|
+
*/
|
|
67
|
+
function staticFiles(root, options = {}) {
|
|
68
|
+
const opts = {
|
|
69
|
+
...options,
|
|
70
|
+
root: path.resolve(root),
|
|
71
|
+
maxAge: options.maxAge || DEFAULT_MAX_AGE,
|
|
72
|
+
index: options.index === false ? [] : [].concat(options.index || DEFAULT_INDEX),
|
|
73
|
+
dotfiles: options.hidden ? 'allow' : (options.dotfiles || 'ignore'),
|
|
74
|
+
etag: options.etag !== false,
|
|
75
|
+
lastModified: options.lastModified !== false,
|
|
76
|
+
extensions: options.extensions || [],
|
|
77
|
+
fallthrough: options.fallthrough !== false,
|
|
78
|
+
redirect: options.redirect !== false,
|
|
79
|
+
setHeaders: options.setHeaders
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const rootWithSep = opts.root.endsWith(path.sep) ? opts.root : opts.root + path.sep;
|
|
83
|
+
|
|
84
|
+
const notFound = (ctx, next) => {
|
|
85
|
+
if (opts.fallthrough) {
|
|
86
|
+
return next();
|
|
87
|
+
}
|
|
88
|
+
return ctx.status(404).json({ error: 'Not Found' });
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const forbidden = (ctx, next) => {
|
|
92
|
+
if (opts.fallthrough) {
|
|
93
|
+
return next();
|
|
94
|
+
}
|
|
95
|
+
return ctx.status(403).json({ error: 'Forbidden' });
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
return async (ctx, next) => {
|
|
99
|
+
if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
|
|
100
|
+
return next();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
let pathname;
|
|
104
|
+
try {
|
|
105
|
+
pathname = decodeURIComponent(ctx.path);
|
|
106
|
+
} catch (e) {
|
|
107
|
+
return ctx.status(400).json({ error: 'Invalid URL encoding' });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// A second decoding pass only serves to detect double-encoded traversal
|
|
111
|
+
// (%252e%252e%252f); the file is looked up with the single-decoded path.
|
|
112
|
+
let doubleDecoded = pathname;
|
|
113
|
+
try {
|
|
114
|
+
doubleDecoded = decodeURIComponent(pathname);
|
|
115
|
+
} catch (e) {
|
|
116
|
+
// not double-encoded
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (isTraversal(pathname) || isTraversal(doubleDecoded)) {
|
|
120
|
+
return forbidden(ctx, next);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const relativePath = path.normalize(pathname).replace(/^[/\\]+/, '');
|
|
124
|
+
const filePath = path.join(opts.root, relativePath);
|
|
125
|
+
|
|
126
|
+
// Ensure the resolved path is within the root directory
|
|
127
|
+
if (filePath !== opts.root && !filePath.startsWith(rootWithSep)) {
|
|
128
|
+
return forbidden(ctx, next);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Dot segments anywhere in the path (/.git/config, /.env, /a/.ssh/key)
|
|
132
|
+
if (opts.dotfiles !== 'allow' && hasDotSegment(relativePath)) {
|
|
133
|
+
if (opts.dotfiles === 'deny') {
|
|
134
|
+
return ctx.status(403).json({ error: 'Forbidden' });
|
|
135
|
+
}
|
|
136
|
+
return notFound(ctx, next);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
let stats;
|
|
140
|
+
try {
|
|
141
|
+
stats = await withTimeout(stat(filePath));
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
|
|
144
|
+
return tryExtensions(ctx, filePath, opts, () => notFound(ctx, next));
|
|
145
|
+
}
|
|
146
|
+
if (opts.fallthrough) {
|
|
147
|
+
return next();
|
|
148
|
+
}
|
|
149
|
+
return ctx.status(500).json({ error: 'Internal Server Error' });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (stats.isDirectory()) {
|
|
153
|
+
return handleDirectory(ctx, filePath, opts, () => notFound(ctx, next));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (stats.isFile()) {
|
|
157
|
+
return sendFile(ctx, filePath, stats, opts);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return notFound(ctx, next);
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Whether a decoded path tries to escape the root.
|
|
166
|
+
*
|
|
167
|
+
* @param {string} pathname - Decoded request path
|
|
168
|
+
* @returns {boolean}
|
|
169
|
+
* @private
|
|
170
|
+
*/
|
|
171
|
+
function isTraversal(pathname) {
|
|
172
|
+
return pathname.includes('\0') ||
|
|
173
|
+
pathname.split(/[/\\]/).some(segment => segment === '..');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Whether any segment of a relative path starts with a dot.
|
|
178
|
+
*
|
|
179
|
+
* @param {string} relativePath - Path relative to the root
|
|
180
|
+
* @returns {boolean}
|
|
181
|
+
* @private
|
|
182
|
+
*/
|
|
183
|
+
function hasDotSegment(relativePath) {
|
|
184
|
+
return relativePath.split(/[/\\]/).some(segment => segment.length > 1 && segment.startsWith('.'));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function handleDirectory(ctx, dirPath, opts, notFound) {
|
|
188
|
+
if (opts.redirect && !ctx.path.endsWith('/')) {
|
|
189
|
+
const base = ctx.mountpath ? `${ctx.mountpath}${ctx.path}` : ctx.path;
|
|
190
|
+
return ctx.redirect(`${base}/`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
for (const indexFile of opts.index) {
|
|
194
|
+
const indexPath = path.join(dirPath, indexFile);
|
|
195
|
+
try {
|
|
196
|
+
const stats = await withTimeout(stat(indexPath));
|
|
197
|
+
if (stats.isFile()) {
|
|
198
|
+
return sendFile(ctx, indexPath, stats, opts);
|
|
199
|
+
}
|
|
200
|
+
} catch (error) {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
return notFound();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function tryExtensions(ctx, filePath, opts, notFound) {
|
|
209
|
+
for (const ext of opts.extensions) {
|
|
210
|
+
const extPath = filePath + (ext.startsWith('.') ? ext : `.${ext}`);
|
|
211
|
+
try {
|
|
212
|
+
const stats = await withTimeout(stat(extPath));
|
|
213
|
+
if (stats.isFile()) {
|
|
214
|
+
return sendFile(ctx, extPath, stats, opts);
|
|
215
|
+
}
|
|
216
|
+
} catch (error) {
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return notFound();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Whether the client's cached copy is still valid.
|
|
226
|
+
*
|
|
227
|
+
* @private
|
|
228
|
+
*/
|
|
229
|
+
function isNotModified(ctx, etag, stats, opts) {
|
|
230
|
+
const ifNoneMatch = ctx.get('if-none-match');
|
|
231
|
+
if (ifNoneMatch && opts.etag) {
|
|
232
|
+
const tags = ifNoneMatch.split(',').map(tag => tag.trim().replace(/^W\//, ''));
|
|
233
|
+
return tags.includes('*') || tags.includes(etag);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const ifModifiedSince = ctx.get('if-modified-since');
|
|
237
|
+
if (ifModifiedSince && opts.lastModified) {
|
|
238
|
+
const since = Date.parse(ifModifiedSince);
|
|
239
|
+
return !Number.isNaN(since) && Math.floor(stats.mtime.getTime() / 1000) * 1000 <= since;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function sendFile(ctx, filePath, stats, opts) {
|
|
246
|
+
const contentType = getContentType(filePath);
|
|
247
|
+
ctx.set('Content-Type', contentType);
|
|
248
|
+
ctx.set('Accept-Ranges', 'bytes');
|
|
249
|
+
|
|
250
|
+
if (opts.lastModified) {
|
|
251
|
+
ctx.set('Last-Modified', stats.mtime.toUTCString());
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const etag = generateETag(stats);
|
|
255
|
+
if (opts.etag) {
|
|
256
|
+
ctx.set('ETag', etag);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (opts.maxAge) {
|
|
260
|
+
ctx.set('Cache-Control', `public, max-age=${opts.maxAge}`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (opts.setHeaders) {
|
|
264
|
+
try {
|
|
265
|
+
opts.setHeaders(ctx, path.basename(filePath), stats);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
console.error('Error in setHeaders callback:', error.message);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (isNotModified(ctx, etag, stats, opts)) {
|
|
272
|
+
ctx.removeHeader('Content-Type');
|
|
273
|
+
return ctx.status(304).end();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
let start = 0;
|
|
277
|
+
let end = stats.size - 1;
|
|
278
|
+
|
|
279
|
+
const rangeHeader = ctx.get('range');
|
|
280
|
+
if (rangeHeader) {
|
|
281
|
+
const ranges = parseRange(stats.size, rangeHeader);
|
|
282
|
+
if (ranges === null) {
|
|
283
|
+
// Not a byte range we understand: send the whole file
|
|
284
|
+
} else if (ranges.length !== 1) {
|
|
285
|
+
ctx.set('Content-Range', `bytes */${stats.size}`);
|
|
286
|
+
return ctx.status(416).json({ error: 'Range Not Satisfiable' });
|
|
287
|
+
} else {
|
|
288
|
+
start = ranges[0].start;
|
|
289
|
+
end = ranges[0].end;
|
|
290
|
+
ctx.set('Content-Range', `bytes ${start}-${end}/${stats.size}`);
|
|
291
|
+
ctx.status(206);
|
|
292
|
+
}
|
|
293
|
+
} else {
|
|
294
|
+
ctx.status(200);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const length = stats.size === 0 ? 0 : end - start + 1;
|
|
298
|
+
ctx.set('Content-Length', length);
|
|
299
|
+
|
|
300
|
+
if (ctx.method === 'HEAD' || length === 0) {
|
|
301
|
+
return ctx.end();
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return ctx.stream(fs.createReadStream(filePath, { start, end }));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Parse a Range header.
|
|
309
|
+
*
|
|
310
|
+
* @param {number} size - File size
|
|
311
|
+
* @param {string} rangeHeader - Range header value
|
|
312
|
+
* @returns {Array<{start: number, end: number}>|null} Satisfiable ranges, or
|
|
313
|
+
* null when the header is not a byte range
|
|
314
|
+
* @private
|
|
315
|
+
*/
|
|
316
|
+
function parseRange(size, rangeHeader) {
|
|
317
|
+
if (!rangeHeader || !rangeHeader.startsWith('bytes=')) {
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const ranges = [];
|
|
322
|
+
const parts = rangeHeader.slice(6).split(',');
|
|
323
|
+
|
|
324
|
+
for (const part of parts) {
|
|
325
|
+
const match = /^\s*(\d*)\s*-\s*(\d*)\s*$/.exec(part);
|
|
326
|
+
if (!match || (match[1] === '' && match[2] === '')) {
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (match[1] === '') {
|
|
331
|
+
// Suffix range: last N bytes
|
|
332
|
+
const suffix = parseInt(match[2], 10);
|
|
333
|
+
if (suffix > 0 && size > 0) {
|
|
334
|
+
ranges.push({ start: Math.max(0, size - suffix), end: size - 1 });
|
|
335
|
+
}
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const start = parseInt(match[1], 10);
|
|
340
|
+
const end = match[2] === '' ? size - 1 : Math.min(parseInt(match[2], 10), size - 1);
|
|
341
|
+
if (start <= end && start < size) {
|
|
342
|
+
ranges.push({ start, end });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return ranges;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function getContentType(filePath) {
|
|
350
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
351
|
+
|
|
352
|
+
const mimeTypes = {
|
|
353
|
+
'.html': 'text/html; charset=utf-8',
|
|
354
|
+
'.htm': 'text/html; charset=utf-8',
|
|
355
|
+
'.js': 'application/javascript; charset=utf-8',
|
|
356
|
+
'.mjs': 'application/javascript; charset=utf-8',
|
|
357
|
+
'.css': 'text/css; charset=utf-8',
|
|
358
|
+
'.json': 'application/json; charset=utf-8',
|
|
359
|
+
'.png': 'image/png',
|
|
360
|
+
'.jpg': 'image/jpeg',
|
|
361
|
+
'.jpeg': 'image/jpeg',
|
|
362
|
+
'.gif': 'image/gif',
|
|
363
|
+
'.webp': 'image/webp',
|
|
364
|
+
'.svg': 'image/svg+xml',
|
|
365
|
+
'.ico': 'image/x-icon',
|
|
366
|
+
'.pdf': 'application/pdf',
|
|
367
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
368
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
369
|
+
'.xml': 'application/xml',
|
|
370
|
+
'.zip': 'application/zip',
|
|
371
|
+
'.tar': 'application/x-tar',
|
|
372
|
+
'.gz': 'application/gzip',
|
|
373
|
+
'.mp4': 'video/mp4',
|
|
374
|
+
'.webm': 'video/webm',
|
|
375
|
+
'.mp3': 'audio/mpeg',
|
|
376
|
+
'.wav': 'audio/wav',
|
|
377
|
+
'.woff': 'font/woff',
|
|
378
|
+
'.woff2': 'font/woff2',
|
|
379
|
+
'.ttf': 'font/ttf',
|
|
380
|
+
'.otf': 'font/otf',
|
|
381
|
+
'.wasm': 'application/wasm'
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
return mimeTypes[ext] || 'application/octet-stream';
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function generateETag(stats) {
|
|
388
|
+
const hash = crypto.createHash('sha256');
|
|
389
|
+
hash.update(stats.size.toString());
|
|
390
|
+
hash.update(stats.mtime.getTime().toString());
|
|
391
|
+
return `"${hash.digest('hex').substring(0, 32)}"`;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Alias of staticFiles
|
|
396
|
+
*
|
|
397
|
+
* @param {string} root - Directory to serve
|
|
398
|
+
* @param {Object} [options] - Options
|
|
399
|
+
* @returns {Function} Middleware
|
|
400
|
+
*/
|
|
401
|
+
function serveStatic(root, options) {
|
|
402
|
+
return staticFiles(root, options);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
module.exports = staticFiles;
|
|
406
|
+
module.exports.serveStatic = serveStatic;
|