const http = require("http"); const os = require("os"); const fs = require("fs"); const path = require("path"); const { read } = require("./lib/state"); const TOKEN = process.env.STATUS_TOKEN || ""; const PORT = Number(process.env.PORT || process.env.STATUS_PORT || 0); function okAuth(req) { if (!TOKEN) return false; const h = req.headers["authorization"] || ""; const bearer = h.startsWith("Bearer ") ? h.slice(7) : ""; const url = new URL(req.url, "http://x"); const q = url.searchParams.get("token") || ""; return bearer === TOKEN || q === TOKEN; } function fmt(ts) { if (!ts) return "never"; const d = new Date(ts); return d.toLocaleString(); } const server = http.createServer((req, res) => { if (req.method === "GET" && req.url === "/health") { res.writeHead(200, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ ok: true })); } if (!okAuth(req)) { res.writeHead(401, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ error: "unauthorized" })); } if (req.method === "GET" && (req.url.startsWith("/api/status"))) { const s = read(); res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*" }); return res.end(JSON.stringify({ host: os.hostname(), uptimeSec: Math.floor(process.uptime()), data: s })); } if (req.method === "GET" && (req.url === "/status" || req.url === "/")) { const s = read(); const keys = Object.keys(s).sort(); let rows = ""; for (const k of keys) rows += `${k}${fmt(s[k])}`; const html = ` skynet status

skynet status

host ${os.hostname()} uptime ${Math.floor(process.uptime())}s ${rows}
keytime
`; res.writeHead(200, { "Content-Type": "text/html", "Cache-Control": "no-store" }); return res.end(html); } res.writeHead(404); res.end("not found"); }); server.listen(PORT, "0.0.0.0", () => { const addr = server.address(); const port = typeof addr === "object" && addr ? addr.port : 0; console.log("status up on port", port); try { fs.writeFileSync(path.join(os.homedir(), ".skynet_status_port"), String(port)); } catch {} });