import { createReadStream, realpathSync, statSync } from "node:fs"; import { createServer } from "node:http"; import path from "node:path"; import { fileURLToPath } from "node:url"; const ROOT = realpathSync(path.dirname(fileURLToPath(import.meta.url))); const HOST = process.env.HOST || "127.0.0.1"; const PORT = Number.parseInt(process.env.PORT || "4173", 10); const 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"], [".mjs", "text/javascript; charset=utf-8"], [".svg", "image/svg+xml"], ]); const PUBLIC_PATHS = new Set([ "/index.html", "/styles.css", "/js/app.js", "/js/charts.js", "/js/data.js", "/public/data/age_risk_curve.json", "/public/data/cohort_scorecard.json", "/public/data/coverage_quality.json", "/public/data/data_manifest.json", "/public/data/filter_catalog.json", "/public/data/model_diagnostics.json", "/public/data/overview_period_county.json", "/public/data/sha256_manifest.json", ]); function safeFile(requestUrl) { let pathname; try { pathname = decodeURIComponent(new URL(requestUrl, "http://local").pathname); } catch { return { file: null, status: 400 }; } if (pathname === "/") pathname = "/index.html"; if (!PUBLIC_PATHS.has(pathname)) return { file: null, status: 404 }; try { const candidate = realpathSync(path.join(ROOT, pathname.slice(1))); if (!candidate.startsWith(`${ROOT}${path.sep}`) || !statSync(candidate).isFile()) { return { file: null, status: 404 }; } return { file: candidate, status: 200 }; } catch { return { file: null, status: 404 }; } } const server = createServer((request, response) => { if (!request.url || !["GET", "HEAD"].includes(request.method || "")) { response.writeHead(405, { Allow: "GET, HEAD" }); response.end("Method not allowed"); return; } const resolved = safeFile(request.url); if (!resolved.file) { response.writeHead(resolved.status, { "Content-Type": "text/plain; charset=utf-8" }); response.end(resolved.status === 400 ? "Bad request" : "Not found"); return; } const file = resolved.file; const extension = path.extname(file).toLowerCase(); response.writeHead(200, { "Content-Type": TYPES.get(extension) || "application/octet-stream", "Cache-Control": extension === ".json" ? "no-store" : "public, max-age=300", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", }); if (request.method === "HEAD") { response.end(); return; } createReadStream(file).on("error", () => response.destroy()).pipe(response); }); server.listen(PORT, HOST, () => { process.stdout.write(`Utah Vehicle Health dashboard: http://${HOST}:${PORT}\n`); });