-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathserver.mjs
More file actions
132 lines (114 loc) · 4 KB
/
server.mjs
File metadata and controls
132 lines (114 loc) · 4 KB
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
/*
* Copyright (c) 2026, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0
*/
import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises';
import { join, extname, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const PORT = process.env.PORT || 8080;
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.mjs': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.wasm': 'application/wasm',
'.map': 'application/json',
};
// Single merged directory: UI dist + docs copied into dist/docs/
const STATIC_ROOT = resolve(__dirname, 'apps', 'ui', 'dist');
// Boundary check used to mitigate CWE-22 path traversal.
// The WHATWG URL parser does not normalize `..` segments when the slash is
// percent-encoded (e.g. `..%2f..%2f` or `%2e%2e%2f`), so once we run the
// pathname through decodeURIComponent the `..` segments can survive. We
// must therefore re-resolve the joined path and confirm it is still
// confined to STATIC_ROOT before touching the filesystem.
function isInsideStaticRoot(absPath) {
return absPath === STATIC_ROOT || absPath.startsWith(STATIC_ROOT + sep);
}
async function serveFile(res, filePath) {
try {
const data = await readFile(filePath);
const ext = extname(filePath);
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
const isHashed = /\.[a-f0-9]{8,}\.\w+$/.test(filePath);
const cacheControl = isHashed
? 'public, max-age=31536000, immutable'
: 'public, max-age=60';
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': cacheControl,
});
res.end(data);
return true;
} catch {
return false;
}
}
async function exists(filePath) {
try {
const s = await stat(filePath);
return s.isFile();
} catch {
return false;
}
}
const server = createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const pathname = decodeURIComponent(url.pathname);
// Defense in depth: refuse decoded paths containing NUL bytes or
// backslashes. These never appear in legitimate static asset URLs and
// are common ingredients in path-confusion attacks.
if (pathname.includes('\0') || pathname.includes('\\')) {
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Bad Request');
return;
}
// Resolve to an absolute, normalized path and confine to STATIC_ROOT.
const filePath = resolve(STATIC_ROOT, '.' + pathname);
if (!isInsideStaticRoot(filePath)) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Forbidden');
return;
}
// Try exact file
if (await exists(filePath)) {
await serveFile(res, filePath);
return;
}
// Try directory/index.html (Docusaurus pages under /docs/)
const indexPath = join(filePath, 'index.html');
if (await exists(indexPath)) {
await serveFile(res, indexPath);
return;
}
// For /docs/* paths, serve the docs 404 page
if (pathname.startsWith('/docs')) {
const docs404 = join(STATIC_ROOT, 'docs', '404.html');
if (await exists(docs404)) {
const data = await readFile(docs404, 'utf-8');
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(data);
return;
}
}
// SPA fallback for UI routes
await serveFile(res, join(STATIC_ROOT, 'index.html'));
});
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
console.log(` http://localhost:${PORT}/`);
});