-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
53 lines (46 loc) · 1.58 KB
/
server.js
File metadata and controls
53 lines (46 loc) · 1.58 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 8888;
const MIMES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.json': 'application/json'
};
http.createServer((req, res) => {
// SECURITY: Prevent Path Traversal
const safeRoot = path.normalize(__dirname);
// Decode URI component to handle spaces/special chars in URL
const sanitizedUrl = path.normalize(decodeURIComponent(req.url === '/' ? 'index.html' : req.url)).replace(/^(\.\.[\/\\])+/, '');
let filePath = path.join(safeRoot, sanitizedUrl);
// SECURITY: Ensure resolved path is within the safeRoot
if (!filePath.startsWith(safeRoot)) {
res.writeHead(403);
res.end('403 Forbidden');
return;
}
const ext = path.extname(filePath);
const contentType = MIMES[ext] || 'application/octet-stream';
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
res.writeHead(404);
res.end('404 Not Found');
} else {
res.writeHead(500);
res.end(`Server Error: ${err.code}`);
}
} else {
// SECURITY: Basic headers
res.writeHead(200, {
'Content-Type': contentType,
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY'
});
res.end(content, 'utf-8');
}
});
}).listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});