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 += `
| key | time |
|---|