-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (61 loc) · 2.21 KB
/
Copy pathserver.js
File metadata and controls
72 lines (61 loc) · 2.21 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.manifest': 'text/cache-manifest; charset=utf-8',
'.webmanifest': 'application/manifest+json; charset=utf-8'
};
const server = http.createServer((req, res) => {
let reqPath = req.url.split('?')[0];
// 1. Safe URI decoding to prevent traversal bypass via URL encoded dots/slashes
let decodedPath;
try {
decodedPath = decodeURIComponent(reqPath);
} catch (e) {
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('400 Bad Request');
return;
}
// 2. Normalize and check if file path stays within root directory to prevent directory traversal
const rootPath = path.resolve(__dirname);
const filePath = path.normalize(path.join(rootPath, decodedPath === '/' ? 'index.html' : decodedPath));
if (!filePath.startsWith(rootPath + path.sep) && filePath !== rootPath) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('403 Forbidden');
return;
}
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('404 Not Found');
return;
}
fs.readFile(filePath, (error, content) => {
if (error) {
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('500 Internal Server Error: ' + error.code);
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': 'no-store, no-cache, must-revalidate, private'
});
res.end(content, 'utf-8');
});
});
});
server.listen(PORT, () => {
console.log(`[Server] ethos.init v2.4.0 is running at http://localhost:${PORT}`);
});