import { createServer } from "node:http"; import { readFile } from "node:fs/promises"; import { extname, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; const trustlabRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); const host = "127.0.0.1"; const port = Number.parseInt(process.env.TRUSTLAB_PORT ?? "4173", 10); const contentTypes = { ".css": "text/css; charset=utf-8", ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", }; const server = createServer(async (request, response) => { try { const url = new URL(request.url ?? "/", `http://${host}:${port}`); const relativePath = url.pathname === "/" ? "ui/index.html" : url.pathname.slice(1); const requestedPath = resolve(trustlabRoot, relativePath); if (!requestedPath.startsWith(`${trustlabRoot}${sep}`)) { respond(response, 403, "Forbidden"); return; } const body = await readFile(requestedPath); response.writeHead(200, { "Content-Type": contentTypes[extname(requestedPath)] ?? "application/octet-stream", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'self'; style-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'", }); response.end(body); } catch (error) { if (error?.code === "ENOENT" || error?.code === "EISDIR") { respond(response, 404, "Not found"); return; } respond(response, 500, "Internal server error"); } }); server.listen(port, host, () => { console.log(`TrustLab UI: http://${host}:${port}`); }); function respond(response, status, message) { response.writeHead(status, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store", }); response.end(message); }