50 lines
1.7 KiB
TypeScript
50 lines
1.7 KiB
TypeScript
import { createReadStream } from "node:fs";
|
|
import { stat } from "node:fs/promises";
|
|
import { createServer } from "node:http";
|
|
import path from "node:path";
|
|
|
|
const port = Number(process.argv[2] ?? "4175");
|
|
const root = path.resolve("tests/fixtures/memento-visual-baseline/legacy");
|
|
const publicRoot = path.resolve("public");
|
|
|
|
const MIME = Object.freeze({
|
|
".css": "text/css; charset=utf-8",
|
|
".html": "text/html; charset=utf-8",
|
|
".js": "text/javascript; charset=utf-8",
|
|
".jpg": "image/jpeg",
|
|
".json": "application/json; charset=utf-8",
|
|
".png": "image/png",
|
|
".svg": "image/svg+xml",
|
|
});
|
|
|
|
function candidatePath(urlPath: string): string {
|
|
const clean = decodeURIComponent(urlPath.split("?")[0] ?? "/");
|
|
const relative = clean === "/" ? "index.html" : clean.replace(/^\/+/, "");
|
|
const base = relative.startsWith("assets/") ? publicRoot : root;
|
|
const resolved = path.resolve(base, relative);
|
|
if (!resolved.startsWith(base + path.sep) && resolved !== base) {
|
|
throw new Error("path traversal");
|
|
}
|
|
return resolved;
|
|
}
|
|
|
|
const server = createServer(async (request, response) => {
|
|
try {
|
|
const file = candidatePath(request.url ?? "/");
|
|
const metadata = await stat(file);
|
|
if (!metadata.isFile()) throw new Error("not a file");
|
|
const extension = path.extname(file) as keyof typeof MIME;
|
|
response.statusCode = 200;
|
|
response.setHeader("Content-Type", MIME[extension] ?? "application/octet-stream");
|
|
response.setHeader("Cache-Control", "no-store");
|
|
createReadStream(file).pipe(response);
|
|
} catch {
|
|
response.statusCode = 404;
|
|
response.end("Not found");
|
|
}
|
|
});
|
|
|
|
server.listen(port, "127.0.0.1", () => {
|
|
process.stdout.write(`Memento legacy visual fixture: http://127.0.0.1:${port}\n`);
|
|
});
|