-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
97 lines (85 loc) · 2.65 KB
/
Copy pathserver.js
File metadata and controls
97 lines (85 loc) · 2.65 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
/**
* Static server with COOP/COEP (cross-origin isolation for ffmpeg.wasm).
* Usage: node server.js
*/
const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = Number(process.env.PORT) || 5173;
const ROOT = path.resolve(__dirname);
const TYPES = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".json": "application/json",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
".gif": "image/gif",
".wasm": "application/wasm",
".ico": "image/x-icon",
".map": "application/json",
};
function isInsideRoot(filePath) {
const resolved = path.resolve(filePath);
const root = ROOT.toLowerCase();
const candidate = resolved.toLowerCase();
return candidate === root || candidate.startsWith(root + path.sep.toLowerCase()) || candidate.startsWith(root + "\\") || candidate.startsWith(root + "/");
}
const server = http.createServer((req, res) => {
try {
const rawUrl = (req.url || "/").split("?")[0];
let urlPath = decodeURIComponent(rawUrl);
// Normalize and strip leading slashes so path.resolve stays under ROOT (Windows-safe).
urlPath = urlPath.replace(/\\/g, "/");
if (urlPath === "/" || urlPath === "") {
urlPath = "index.html";
} else {
urlPath = urlPath.replace(/^\/+/, "");
}
// Block path traversal
if (urlPath.split("/").some((p) => p === "..")) {
res.writeHead(403);
res.end("Forbidden");
return;
}
const filePath = path.resolve(ROOT, ...urlPath.split("/"));
if (!isInsideRoot(filePath)) {
res.writeHead(403);
res.end("Forbidden");
return;
}
fs.stat(filePath, (statErr, stat) => {
if (statErr || !stat.isFile()) {
res.writeHead(404);
res.end("Not found");
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(500);
res.end("Server error");
return;
}
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, {
"Content-Type": TYPES[ext] || "application/octet-stream",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp",
"Cross-Origin-Resource-Policy": "same-origin",
"Cache-Control": "no-cache",
});
res.end(data);
});
});
} catch (e) {
res.writeHead(500);
res.end("Server error");
}
});
server.listen(PORT, () => {
console.log(`ClipForge: http://localhost:${PORT}`);
});