37 lines
1.4 KiB
JavaScript
37 lines
1.4 KiB
JavaScript
import { createReadStream } from "node:fs";
|
|
import { stat } from "node:fs/promises";
|
|
import { createServer } from "node:http";
|
|
import { extname, join, normalize, relative, resolve } from "node:path";
|
|
|
|
const root = resolve("dist");
|
|
const port = Number(process.env.PORT ?? 4173);
|
|
const contentTypes = {
|
|
".html": "text/html; charset=utf-8",
|
|
".js": "text/javascript; charset=utf-8",
|
|
".json": "application/json; charset=utf-8",
|
|
".css": "text/css; charset=utf-8"
|
|
};
|
|
|
|
const server = createServer(async (request, response) => {
|
|
const requestPath = decodeURIComponent((request.url ?? "/").split("?", 1)[0]);
|
|
const candidate = resolve(join(root, requestPath === "/" ? "index.html" : requestPath));
|
|
const safeRelativePath = relative(root, candidate);
|
|
if (safeRelativePath.startsWith("..") || safeRelativePath.includes(`..${process.platform === "win32" ? "\\" : "/"}`)) {
|
|
response.writeHead(403).end("Forbidden");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const file = await stat(candidate);
|
|
if (!file.isFile()) throw new Error("not a file");
|
|
response.writeHead(200, { "content-type": contentTypes[extname(candidate)] ?? "application/octet-stream" });
|
|
createReadStream(candidate).pipe(response);
|
|
} catch {
|
|
response.writeHead(404).end("Not found");
|
|
}
|
|
});
|
|
|
|
server.listen(port, "127.0.0.1", () => {
|
|
console.log(`JPW7 M0 server listening on http://127.0.0.1:${port}`);
|
|
});
|