Spaces:
Paused
Paused
Use token-only login for app route
Browse filesFiles changed (2)
- README.md+3-3
- health-server.js+200-21
57 unmodified lines58596061626364656657 unmodified linesThen:- Opening `/app/` asks for browser Basic Auth.- Use any username.- Use `GATEWAY_TOKEN` as the password.- API routes under `/v1/*` accept `Authorization: Bearer <GATEWAY_TOKEN>`.## LLM Providers57 unmodified lines58596061626364656657 unmodified linesThen:- Opening `/app/` shows a HuggingMess login page with one field.- Paste `GATEWAY_TOKEN` into that field.- HuggingMess stores an HTTP-only session cookie for the dashboard routes.- API routes under `/v1/*` accept `Authorization: Bearer <GATEWAY_TOKEN>`.## LLM Providers
2 unmodified lines3456783 unmodified lines1213141516171820 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374757677142 unmodified lines22022122222322422567 unmodified lines2932942952962972982992 unmodified linesconst http = require("http");const fs = require("fs");const net = require("net");const PORT = Number(process.env.PORT || 7861);const GATEWAY_PORT = Number(process.env.API_SERVER_PORT || 8642);3 unmodified linesconst startTime = Date.now();const API_SERVER_KEY = process.env.API_SERVER_KEY || "";const APP_BASE = "/app";const AUTH_REALM = "HuggingMess";const SYNC_STATUS_FILE = "/tmp/huggingmess-sync-status.json";const UPTIMEROBOT_STATUS_FILE = "/tmp/huggingmess-uptimerobot-status.json";20 unmodified linesreturn fallback;}function getBearerToken(req) {const value = req.headers.authorization || "";const match = /^Bearer\s+(.+)$/i.exec(value);return match ? match[1] : "";}function getBasicPassword(req) {const value = req.headers.authorization || "";const match = /^Basic\s+(.+)$/i.exec(value);if (!match) return "";try {const decoded = Buffer.from(match[1], "base64").toString("utf8");const separator = decoded.indexOf(":");return separator >= 0 ? decoded.slice(separator + 1) : "";} catch {return "";}}function isAuthorized(req) {if (!API_SERVER_KEY) return true;return getBearerToken(req) === API_SERVER_KEY || getBasicPassword(req) === API_SERVER_KEY;}function requireAuth(req, res) {if (isAuthorized(req)) return true;res.writeHead(401, {"content-type": "text/plain; charset=utf-8","www-authenticate": `Basic realm="${AUTH_REALM}", charset="UTF-8"`,"cache-control": "no-store",});res.end("Authentication required. Use any username and your GATEWAY_TOKEN as the password.");return false;}function proxyRequest(req, res, targetPort, rewritePath = (path) => path) {142 unmodified linesconst parsed = new URL(req.url, "http://localhost");const path = parsed.pathname;if (path === "/health" || path === `${APP_BASE}/health`) {const data = await statusPayload();res.writeHead(data.ok ? 200 : 503, { "content-type": "application/json" });67 unmodified linesif (!isAuthorized(req)) {res.writeHead(401, {"content-type": "application/json","www-authenticate": `Bearer realm="${AUTH_REALM}"`,"cache-control": "no-store",});res.end(JSON.stringify({ error: "unauthorized", message: "Use Authorization: Bearer <GATEWAY_TOKEN>." }));2 unmodified lines34567893 unmodified lines13141516171819202120 unmodified lines42434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247142 unmodified lines39039139239339439539639739839940040140240340440567 unmodified lines4734744754764774782 unmodified linesconst http = require("http");const fs = require("fs");const net = require("net");const crypto = require("crypto");const PORT = Number(process.env.PORT || 7861);const GATEWAY_PORT = Number(process.env.API_SERVER_PORT || 8642);3 unmodified linesconst startTime = Date.now();const API_SERVER_KEY = process.env.API_SERVER_KEY || "";const APP_BASE = "/app";const LOGIN_PATH = "/login";const LOGOUT_PATH = "/logout";const SESSION_COOKIE = "huggingmess_session";const SYNC_STATUS_FILE = "/tmp/huggingmess-sync-status.json";const UPTIMEROBOT_STATUS_FILE = "/tmp/huggingmess-uptimerobot-status.json";20 unmodified linesreturn fallback;}function timingSafeEqualString(left, right) {if (!left || !right) return false;const leftBuffer = Buffer.from(left);const rightBuffer = Buffer.from(right);if (leftBuffer.length !== rightBuffer.length) return false;return crypto.timingSafeEqual(leftBuffer, rightBuffer);}function expectedSessionValue() {if (!API_SERVER_KEY) return "";return crypto.createHmac("sha256", API_SERVER_KEY).update("huggingmess-session-v1").digest("hex");}function parseCookies(req) {const header = req.headers.cookie || "";const cookies = {};for (const item of header.split(";")) {const separator = item.indexOf("=");if (separator < 0) continue;const name = item.slice(0, separator).trim();const value = item.slice(separator + 1).trim();if (!name) continue;try {cookies[name] = decodeURIComponent(value);} catch {cookies[name] = value;}}return cookies;}function isHttpsRequest(req) {return req.headers["x-forwarded-proto"] === "https";}function buildSessionCookie(req) {const secure = isHttpsRequest(req) ? "; Secure" : "";return `${SESSION_COOKIE}=${encodeURIComponent(expectedSessionValue())}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${secure}`;}function buildClearSessionCookie(req) {const secure = isHttpsRequest(req) ? "; Secure" : "";return `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure}`;}function getBearerToken(req) {const value = req.headers.authorization || "";const match = /^Bearer\s+(.+)$/i.exec(value);return match ? match[1] : "";}function isAuthorized(req) {if (!API_SERVER_KEY) return true;return (timingSafeEqualString(getBearerToken(req), API_SERVER_KEY) ||timingSafeEqualString(parseCookies(req)[SESSION_COOKIE], expectedSessionValue()));}function sanitizeNext(value) {if (!value || typeof value !== "string") return `${APP_BASE}/`;if (!value.startsWith("/") || value.startsWith("//")) return `${APP_BASE}/`;return value;}function loginUrl(nextPath) {return `${LOGIN_PATH}?next=${encodeURIComponent(sanitizeNext(nextPath))}`;}function renderLoginPage(nextPath, errorMessage = "") {const safeNext = sanitizeNext(nextPath);const errorHtml = errorMessage ? `<div class="error">${escapeHtml(errorMessage)}</div>` : "";return `<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>HuggingMess Login</title><style>:root { color-scheme: dark; --bg:#10141f; --panel:#171d2b; --line:#293246; --text:#f4f7fb; --muted:#9aa7bd; --bad:#ef4444; --accent:#38bdf8; }* { box-sizing:border-box; }body { margin:0; min-height:100vh; display:grid; place-items:center; font-family:Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background:var(--bg); color:var(--text); padding:20px; }main { width:min(440px, 100%); border:1px solid var(--line); background:var(--panel); border-radius:8px; padding:28px; }h1 { margin:0 0 8px; font-size:1.55rem; letter-spacing:0; }p { margin:0 0 22px; color:var(--muted); line-height:1.5; }label { display:block; color:var(--muted); font-size:.82rem; margin-bottom:8px; }input { width:100%; min-height:46px; border:1px solid var(--line); border-radius:7px; background:#0b0f18; color:var(--text); padding:0 12px; font:inherit; }button { width:100%; min-height:44px; margin-top:16px; border:0; border-radius:7px; color:#07111f; background:var(--accent); font:inherit; font-weight:750; cursor:pointer; }.error { border:1px solid rgba(239,68,68,.4); background:rgba(239,68,68,.1); color:#fecaca; border-radius:7px; padding:10px 12px; margin-bottom:16px; }</style></head><body><main><h1>Open HuggingMess</h1><p>Enter the <code>GATEWAY_TOKEN</code> from your Space secrets.</p>${errorHtml}<form method="post" action="${LOGIN_PATH}"><input type="hidden" name="next" value="${escapeHtml(safeNext)}" /><label for="token">GATEWAY_TOKEN</label><input id="token" name="token" type="password" autocomplete="current-password" autofocus required /><button type="submit">Continue</button></form></main></body></html>`;}function escapeHtml(value) {return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);}function readRequestBody(req, limit = 64 * 1024) {return new Promise((resolve, reject) => {let body = "";req.on("data", (chunk) => {body += chunk;if (body.length > limit) {reject(new Error("Request body is too large."));req.destroy();}});req.on("end", () => resolve(body));req.on("error", reject);});}function requireAuth(req, res) {if (isAuthorized(req)) return true;const parsed = new URL(req.url, "http://localhost");redirect(res, loginUrl(`${parsed.pathname}${parsed.search}`));return false;}async function handleLogin(req, res, parsed) {const nextPath = sanitizeNext(parsed.searchParams.get("next") || `${APP_BASE}/`);if (!API_SERVER_KEY) {redirect(res, nextPath);return;}if (req.method === "GET") {res.writeHead(200, {"content-type": "text/html; charset=utf-8","cache-control": "no-store",});res.end(renderLoginPage(nextPath));return;}if (req.method !== "POST") {res.writeHead(405, { allow: "GET, POST" });res.end("Method not allowed");return;}try {const body = await readRequestBody(req);const params = new URLSearchParams(body);const submittedToken = params.get("token") || "";const submittedNext = sanitizeNext(params.get("next") || nextPath);if (!timingSafeEqualString(submittedToken, API_SERVER_KEY)) {res.writeHead(401, {"content-type": "text/html; charset=utf-8","cache-control": "no-store",});res.end(renderLoginPage(submittedNext, "That token did not match GATEWAY_TOKEN."));return;}res.writeHead(302, {location: submittedNext,"set-cookie": buildSessionCookie(req),"cache-control": "no-store",});res.end();} catch (error) {res.writeHead(400, {"content-type": "text/plain; charset=utf-8","cache-control": "no-store",});res.end(error.message || "Invalid login request.");}}function handleLogout(req, res) {res.writeHead(302, {location: LOGIN_PATH,"set-cookie": buildClearSessionCookie(req),"cache-control": "no-store",});res.end();}function proxyRequest(req, res, targetPort, rewritePath = (path) => path) {142 unmodified linesconst parsed = new URL(req.url, "http://localhost");const path = parsed.pathname;if (path === LOGIN_PATH) {await handleLogin(req, res, parsed);return;}if (path === LOGOUT_PATH) {handleLogout(req, res);return;}if (path === "/health" || path === `${APP_BASE}/health`) {const data = await statusPayload();res.writeHead(data.ok ? 200 : 503, { "content-type": "application/json" });67 unmodified linesif (!isAuthorized(req)) {res.writeHead(401, {"content-type": "application/json","cache-control": "no-store",});res.end(JSON.stringify({ error: "unauthorized", message: "Use Authorization: Bearer <GATEWAY_TOKEN>." }));
README.md+3-3
health-server.js+200-21