/** Shared static host + Chrome discovery for browser runners and the MCP session. */ import fs from "node:fs"; import http from "node:http"; import path from "node:path"; export const CHROME_CANDIDATES = ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/opt/google/chrome/google-chrome"]; export function findChrome() { const override = process.env.FREECAD_CHROME; if (override) return fs.existsSync(override) ? override : null; return CHROME_CANDIDATES.find((candidate) => fs.existsSync(candidate)) ?? null; } export const ISOLATION_HEADERS = { "cross-origin-opener-policy": "same-origin", "cross-origin-embedder-policy": "require-corp", }; const CONTENT_TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css", ".json": "application/json", ".wasm": "application/wasm", ".png": "image/png" }; /** * Serve a built dist directory on an ephemeral loopback port with COOP/COEP. * Returns { server, origin, close }. */ export async function startStaticHost(distRoot, defaultDocument = "index.html") { if (!fs.existsSync(path.join(distRoot, defaultDocument))) throw new Error(`web/dist/${defaultDocument} is missing; run npm run build first`); const server = http.createServer((request, response) => { const requestPath = decodeURIComponent(new URL(request.url ?? "/", "http://127.0.0.1").pathname); if (requestPath === "/favicon.ico") { response.writeHead(204, ISOLATION_HEADERS); response.end(); return; } const relative = requestPath === "/" ? defaultDocument : requestPath.replace(/^\/+/, ""); const filePath = path.resolve(distRoot, relative); if (filePath !== distRoot && !filePath.startsWith(`${distRoot}${path.sep}`)) { response.writeHead(403); response.end("forbidden"); return; } if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) { response.writeHead(404); response.end("not found"); return; } response.writeHead(200, { "content-type": CONTENT_TYPES[path.extname(filePath)] ?? "application/octet-stream", "cache-control": "no-store", ...ISOLATION_HEADERS }); fs.createReadStream(filePath).pipe(response); }); await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); return { server, origin: `http://127.0.0.1:${server.address().port}`, close: () => server.close() }; }