53 lines
2.1 KiB
JavaScript
53 lines
2.1 KiB
JavaScript
import { createServer } from "node:http";
|
|
import { readFile, stat } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
const root = path.resolve(
|
|
path.dirname(fileURLToPath(import.meta.url)),
|
|
"..",
|
|
"dist",
|
|
),
|
|
prefix = "/deep/nested/query/",
|
|
types = new Map([
|
|
[".css", "text/css; charset=utf-8"],
|
|
[".html", "text/html; charset=utf-8"],
|
|
[".js", "text/javascript; charset=utf-8"],
|
|
[".json", "application/json; charset=utf-8"],
|
|
[".webmanifest", "application/manifest+json; charset=utf-8"],
|
|
[".wasm", "application/wasm"],
|
|
[".svg", "image/svg+xml"],
|
|
[".md", "text/markdown; charset=utf-8"],
|
|
[".txt", "text/plain; charset=utf-8"],
|
|
]),
|
|
headers = {
|
|
"Content-Security-Policy":
|
|
"default-src 'self';base-uri 'self';object-src 'none';frame-ancestors 'none';form-action 'self';script-src 'self' 'wasm-unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;connect-src 'self';worker-src 'self' blob:;manifest-src 'self'",
|
|
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
|
|
"Referrer-Policy": "no-referrer",
|
|
"X-Content-Type-Options": "nosniff",
|
|
};
|
|
createServer(async (q, s) => {
|
|
try {
|
|
const u = new URL(q.url ?? "/", "http://127.0.0.1"),
|
|
d = decodeURIComponent(u.pathname),
|
|
r = d.startsWith(prefix) ? d.slice(prefix.length) : d.replace(/^\/+/, ""),
|
|
n = path.posix.normalize(r || "index.html");
|
|
if (n === ".." || n.startsWith("../") || path.isAbsolute(n))
|
|
return void s.writeHead(400).end();
|
|
let f = path.join(root, n);
|
|
if ((await stat(f).catch(() => null))?.isDirectory())
|
|
f = path.join(f, "index.html");
|
|
const c = await readFile(f);
|
|
s.writeHead(200, {
|
|
"Content-Type": types.get(path.extname(f)) ?? "application/octet-stream",
|
|
"Cache-Control": n.startsWith("assets/")
|
|
? "public,max-age=31536000,immutable"
|
|
: "no-cache",
|
|
...headers,
|
|
});
|
|
s.end(c);
|
|
} catch {
|
|
s.writeHead(404).end("Not found");
|
|
}
|
|
}).listen(4220, "127.0.0.1", () => console.log("ready"));
|