Spaces:
Paused
Paused
refactor: update default allowed domains, unify domain filtering logic, and remove UptimeRobot setup UI from health server
Browse filesFiles changed (7)
- .env.example+6-6
- README.md+5-10
- cloudflare-proxy-setup.py+31-4
- cloudflare-proxy.js+25-5
- health-server.js+61-453
- setup-uptimerobot.sh+9-2
- start.sh+5-1
178 unmodified lines17918018118218318418518617 unmodified lines204205206207208209210211212213178 unmodified lines# CLOUDFLARE_PROXY_URL=https://your-proxy.workers.dev# CLOUDFLARE_PROXY_SECRET=your_proxy_secret_here# Domains to proxy (default: *)# CLOUDFLARE_PROXY_DOMAINS=*# ββ OPTIONAL: Workspace Backup to HF Dataset ββHF_USERNAME=your_hf_username17 unmodified lines# Webhooks: Standard POST notifications for lifecycle events# WEBHOOK_URL=https://your-webhook-endpoint.com/log# Optional: external keep-alive via UptimeRobot# Use the Main API key from UptimeRobot -> Integrations.# Do not use the Read-only API key or a Monitor-specific API key.# Run setup-uptimerobot.sh once from your own terminal to create the monitor.# UPTIMEROBOT_API_KEY=ur_your_api_key_here# Trusted proxies (comma-separated IPs)178 unmodified lines17918018118218318418518618718817 unmodified lines206207208209210211212213178 unmodified lines# CLOUDFLARE_PROXY_URL=https://your-proxy.workers.dev# CLOUDFLARE_PROXY_SECRET=your_proxy_secret_here# Extra domains to proxy, merged with built-in defaults (Telegram, Discord, WhatsApp,# Facebook, Google). Comma-separated. Set to "*" to proxy ALL external traffic.# Leave unset to proxy only the built-in default domains.# CLOUDFLARE_PROXY_DOMAINS=api.sendgrid.com,slack.com# ββ OPTIONAL: Workspace Backup to HF Dataset ββHF_USERNAME=your_hf_username17 unmodified lines# Webhooks: Standard POST notifications for lifecycle events# WEBHOOK_URL=https://your-webhook-endpoint.com/log# UptimeRobot keep-alive: add your Main API key (NOT Read-only or Monitor-specific).# Monitor is created automatically at boot. Status shown on the dashboard.# UPTIMEROBOT_API_KEY=ur_your_api_key_here# Trusted proxies (comma-separated IPs)
15 unmodified lines16171819202132 unmodified lines54555657585960105 unmodified lines166167168169170171172173174175176177178179133 unmodified lines31331431531631731831915 unmodified linesdescription: "Strong token to secure your OpenClaw Control UI (generate: openssl rand -hex 32)."- name: CLOUDFLARE_WORKERS_TOKENdescription: "Cloudflare API token β auto-creates a Worker proxy for Telegram, WhatsApp, and Google APIs."---<!-- Badges -->32 unmodified lines- π³ **Fast Builds:** Uses a pre-built OpenClaw Docker image to deploy in minutes.- π **Cloudflare Outbound Proxy:** HuggingClaw can automatically provision a Cloudflare Worker proxy for blocked outbound traffic such as Telegram API requests.- πΎ **Workspace Backup:** Chats, settings, and WhatsApp session state sync to a private HF Dataset via the `huggingface_hub`, preserving data automatically without storing your HF token in a git remote.- β° **External Keep-Alive:** Set up a one-time UptimeRobot monitor from the dashboard to help keep free HF Spaces awake.- π₯ **Multi-User Messaging:** Support for Telegram (multi-user) and WhatsApp (pairing).- π **Visual Dashboard:** Beautiful Web UI to monitor uptime, sync status, and active models.- π **Webhooks:** Get notified on restarts or backup failures via standard webhooks.105 unmodified lines## π Staying Alive *(Recommended on Free HF Spaces)*To help keep your Space awake, set up an external [UptimeRobot](https://uptimerobot.com/) monitor directly from the dashboard UI.1. Open your Space's dashboard (`/`).2. Find the **Keep Space Awake** section.3. Paste your UptimeRobot **Main API key**.4. Click **Create Monitor**.HuggingClaw will automatically create a monitor for your Space's `/health` endpoint.## π Webhooks *(Optional)*133 unmodified lines- **Missing secrets:** Ensure `LLM_API_KEY`, `LLM_MODEL`, and `GATEWAY_TOKEN` are set in your Space **Settings β Secrets**.- **Telegram bot issues:** Verify your `TELEGRAM_BOT_TOKEN`. Check Space logs for lines like `π± Enabling Telegram`.- **Backup restore failing:** Make sure `HF_TOKEN` is valid and has write access to your HF account dataset. Set `HF_USERNAME` only if auto-detection is not available in your environment.- **Space keeps sleeping:** Open `/` and use `Keep Space Awake` to create the external monitor.- **Auth errors / proxy:** If you see reverse-proxy auth errors, add the logged IPs under `TRUSTED_PROXIES` (from logs `remote=x.x.x.x`).- **Control UI says too many failed authentication attempts:** Wait for the retry window to expire, then open the Space in an incognito window or clear site storage for your Space before logging in again with `GATEWAY_TOKEN`.- **WhatsApp lost its session after restart:** Make sure `HF_TOKEN` is configured so the hidden session backup can be restored on boot.15 unmodified lines161718192021222332 unmodified lines56575859606162105 unmodified lines168169170171172173174133 unmodified lines30830931031131231331415 unmodified linesdescription: "Strong token to secure your OpenClaw Control UI (generate: openssl rand -hex 32)."- name: CLOUDFLARE_WORKERS_TOKENdescription: "Cloudflare API token β auto-creates a Worker proxy for Telegram, WhatsApp, and Google APIs."- name: UPTIMEROBOT_API_KEYdescription: UptimeRobot API key for automatic monitor setup.---<!-- Badges -->32 unmodified lines- π³ **Fast Builds:** Uses a pre-built OpenClaw Docker image to deploy in minutes.- π **Cloudflare Outbound Proxy:** HuggingClaw can automatically provision a Cloudflare Worker proxy for blocked outbound traffic such as Telegram API requests.- πΎ **Workspace Backup:** Chats, settings, and WhatsApp session state sync to a private HF Dataset via the `huggingface_hub`, preserving data automatically without storing your HF token in a git remote.- β° **External Keep-Alive:** Add `UPTIMEROBOT_API_KEY` as a Space secret and the monitor is created automatically at boot β no manual setup.- π₯ **Multi-User Messaging:** Support for Telegram (multi-user) and WhatsApp (pairing).- π **Visual Dashboard:** Beautiful Web UI to monitor uptime, sync status, and active models.- π **Webhooks:** Get notified on restarts or backup failures via standard webhooks.105 unmodified lines## π Staying Alive *(Recommended on Free HF Spaces)*Add your [UptimeRobot](https://uptimerobot.com/) **Main API key** as a Space secret named `UPTIMEROBOT_API_KEY`. HuggingClaw will automatically create a monitor for your Space's `/health` endpoint at boot. The dashboard shows the current status (configured, setting up, or failed).## π Webhooks *(Optional)*133 unmodified lines- **Missing secrets:** Ensure `LLM_API_KEY`, `LLM_MODEL`, and `GATEWAY_TOKEN` are set in your Space **Settings β Secrets**.- **Telegram bot issues:** Verify your `TELEGRAM_BOT_TOKEN`. Check Space logs for lines like `π± Enabling Telegram`.- **Backup restore failing:** Make sure `HF_TOKEN` is valid and has write access to your HF account dataset. Set `HF_USERNAME` only if auto-detection is not available in your environment.- **Space keeps sleeping:** Add `UPTIMEROBOT_API_KEY` as a Space secret to enable automatic keep-awake monitoring.- **Auth errors / proxy:** If you see reverse-proxy auth errors, add the logged IPs under `TRUSTED_PROXIES` (from logs `remote=x.x.x.x`).- **Control UI says too many failed authentication attempts:** Wait for the retry window to expire, then open the Space in an incognito window or clear site storage for your Space before logging in again with `GATEWAY_TOKEN`.- **WhatsApp lost its session after restart:** Make sure `HF_TOKEN` is configured so the hidden session backup can be restored on boot.
11 unmodified lines12131415161718192021222324182 unmodified lines20720820921021121221321421521611 unmodified linesAPI_BASE = "https://api.cloudflare.com/client/v4"ENV_FILE = Path("/tmp/huggingclaw-cloudflare-proxy.env")DEFAULT_ALLOWED = ["api.telegram.org","discord.com","discordapp.com","gateway.discord.gg","status.discord.com","web.whatsapp.com","graph.facebook.com","googleapis.com","google.com","googleusercontent.com",182 unmodified linesworker_name = derive_worker_name()allowed_raw = os.environ.get("CLOUDFLARE_PROXY_DOMAINS", "").strip()allow_proxy_all = not allowed_raw or allowed_raw == "*"allowed_targets = DEFAULT_ALLOWED if not allowed_raw or allow_proxy_all else [value.strip() for value in allowed_raw.split(",") if value.strip()]proxy_secret = existing_secret or secrets.token_urlsafe(24)worker_source = render_worker(proxy_secret, allowed_targets, allow_proxy_all)11 unmodified lines121314151617181920212223242526272829303132333435363738394041424344182 unmodified lines22722822923023123223323423523623723823924024124224311 unmodified linesAPI_BASE = "https://api.cloudflare.com/client/v4"ENV_FILE = Path("/tmp/huggingclaw-cloudflare-proxy.env")DEFAULT_ALLOWED = [# Messaging"api.telegram.org","discord.com","discordapp.com","gateway.discord.gg","status.discord.com","web.whatsapp.com",# Social β confirmed/likely blocked by HF firewall"graph.facebook.com","graph.instagram.com","api.twitter.com","api.x.com","upload.twitter.com","api.linkedin.com","www.linkedin.com","open.tiktokapis.com","oauth.reddit.com",# Video"youtube.com","www.youtube.com",# AI APIs"api.openai.com",# Email HTTP APIs (SMTP ports are blocked; use these instead)"api.resend.com","api.sendgrid.com","api.mailgun.net","googleapis.com","google.com","googleusercontent.com",182 unmodified linesworker_name = derive_worker_name()allowed_raw = os.environ.get("CLOUDFLARE_PROXY_DOMAINS", "").strip()allow_proxy_all = allowed_raw == "*"if allow_proxy_all:allowed_targets = DEFAULT_ALLOWEDelse:extra = [v.strip() for v in allowed_raw.split(",") if v.strip()]seen = set(DEFAULT_ALLOWED)allowed_targets = list(DEFAULT_ALLOWED)for domain in extra:if domain not in seen:allowed_targets.append(domain)seen.add(domain)proxy_secret = existing_secret or secrets.token_urlsafe(24)worker_source = render_worker(proxy_secret, allowed_targets, allow_proxy_all)
22 unmodified lines232425262728293031323322 unmodified linesconst DEBUG = process.env.CLOUDFLARE_PROXY_DEBUG === "true";const PROXY_SHARED_SECRET = (process.env.CLOUDFLARE_PROXY_SECRET || "").trim();const PROXY_DOMAINS = process.env.CLOUDFLARE_PROXY_DOMAINS || "*";const BLOCKED_DOMAINS = PROXY_DOMAINS.split(",").map((domain) => domain.trim()).filter(Boolean);const PROXY_ALL = PROXY_DOMAINS === "*";if (PROXY_URL) {try {22 unmodified lines2324252627282930313233343536373839404142434445464748495051525322 unmodified linesconst DEBUG = process.env.CLOUDFLARE_PROXY_DEBUG === "true";const PROXY_SHARED_SECRET = (process.env.CLOUDFLARE_PROXY_SECRET || "").trim();const DEFAULT_PROXY_DOMAINS = ["api.telegram.org", "discord.com", "discordapp.com","gateway.discord.gg", "status.discord.com", "web.whatsapp.com","graph.facebook.com", "graph.instagram.com","api.twitter.com", "api.x.com", "upload.twitter.com","api.linkedin.com", "www.linkedin.com","open.tiktokapis.com", "oauth.reddit.com","youtube.com", "www.youtube.com","api.openai.com","api.resend.com", "api.sendgrid.com", "api.mailgun.net","googleapis.com", "google.com", "googleusercontent.com", "gstatic.com",];const PROXY_DOMAINS_RAW = (process.env.CLOUDFLARE_PROXY_DOMAINS || "").trim();const PROXY_ALL = PROXY_DOMAINS_RAW === "*";let BLOCKED_DOMAINS;if (PROXY_ALL) {BLOCKED_DOMAINS = [];} else {const extra = PROXY_DOMAINS_RAW.split(",").map((d) => d.trim()).filter(Boolean);const seen = new Set(DEFAULT_PROXY_DOMAINS);BLOCKED_DOMAINS = [...DEFAULT_PROXY_DOMAINS];for (const d of extra) {if (!seen.has(d)) { BLOCKED_DOMAINS.push(d); seen.add(d); }}}if (PROXY_URL) {try {
12345610 unmodified lines1718192021222324252627282930313233343526 unmodified lines6263646566676869707153 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116233 unmodified lines19619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027123 unmodified lines295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342284 unmodified lines62762862963063163263363463563663763863964064164264364464564664764864965065165265365465565687 unmodified lines74474574674774874975056 unmodified lines80780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016151 unmodified lines11681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253// Single public entrypoint for HF Spaces: local dashboard + reverse proxy to OpenClaw.const http = require("http");const https = require("https");const fs = require("fs");const net = require("net");10 unmodified linesconst DASHBOARD_BASE = "/dashboard";const DASHBOARD_STATUS_PATH = `${DASHBOARD_BASE}/status`;const DASHBOARD_HEALTH_PATH = `${DASHBOARD_BASE}/health`;const DASHBOARD_UPTIMEROBOT_PATH = `${DASHBOARD_BASE}/uptimerobot/setup`;const DASHBOARD_APP_BASE = `${DASHBOARD_BASE}/app`;const APP_BASE = "/app";const UPTIMEROBOT_SETUP_ENABLED =String(process.env.UPTIMEROBOT_SETUP_ENABLED || "true").toLowerCase() ==="true";const UPTIMEROBOT_RATE_WINDOW_MS = 60 * 1000;const UPTIMEROBOT_RATE_MAX = Number(process.env.UPTIMEROBOT_RATE_LIMIT_PER_MINUTE || 5,);const SPACE_VISIBILITY_TTL_MS = 10 * 60 * 1000;const spaceVisibilityCache = new Map();const uptimerobotRateMap = new Map();function parseRequestUrl(url) {try {26 unmodified linesreturn (pathname === "/health" ||pathname === "/status" ||pathname === "/uptimerobot/setup" ||pathname === DASHBOARD_HEALTH_PATH ||pathname === DASHBOARD_STATUS_PATH ||pathname === DASHBOARD_UPTIMEROBOT_PATH);}53 unmodified lines);}function isRateLimited(req) {const now = Date.now();const ip = getRequesterIp(req);const bucket = uptimerobotRateMap.get(ip) || [];const recent = bucket.filter((ts) => now - ts < UPTIMEROBOT_RATE_WINDOW_MS);recent.push(now);uptimerobotRateMap.set(ip, recent);return recent.length > UPTIMEROBOT_RATE_MAX;}// Prune stale rate-limit buckets every 5 minutes to prevent unbounded growth.setInterval(() => {const cutoff = Date.now() - UPTIMEROBOT_RATE_WINDOW_MS;for (const [ip, timestamps] of uptimerobotRateMap) {if (timestamps.every((ts) => ts < cutoff)) uptimerobotRateMap.delete(ip);}}, 5 * 60 * 1000).unref();function isAllowedUptimeSetupOrigin(req) {const host = String(req.headers.host || "").toLowerCase();const origin = String(req.headers.origin || "").toLowerCase();const referer = String(req.headers.referer || "").toLowerCase();if (!host) return false;if (origin && !origin.includes(host)) return false;if (referer && !referer.includes(host)) return false;return true;}function isValidUptimeApiKey(key) {return /^[A-Za-z0-9_-]{20,128}$/.test(String(key || ""));}function readSyncStatus() {try {if (fs.existsSync("/tmp/sync-status.json")) {33 unmodified linesreturn { configured: true, connected: false, pairing: false };}function decodeJwtPayload(token) {try {const parts = String(token || "").split(".");if (parts.length < 2) return null;const normalized = parts[1].replace(/-/g, "+").replace(/_/g, "/");const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);return JSON.parse(Buffer.from(padded, "base64").toString("utf8"));} catch {return null;}}function getSpaceRef(parsedUrl) {const signedToken = parsedUrl.searchParams.get("__sign");if (!signedToken) return null;const payload = decodeJwtPayload(signedToken);const subject = payload && payload.sub;const match =typeof subject === "string"? subject.match(/^\/spaces\/([^/]+)\/([^/]+)$/): null;if (!match) return null;return { owner: match[1], repo: match[2] };}function fetchStatusCode(url) {return new Promise((resolve, reject) => {const req = https.get(url,{headers: {"user-agent": "HuggingClaw/1.0",accept: "application/json",},},(res) => {res.resume();resolve(res.statusCode || 0);},);req.on("error", reject);req.setTimeout(5000, () => {req.destroy(new Error("Request timed out"));});});}async function resolveSpaceIsPrivate(parsedUrl) {const ref = getSpaceRef(parsedUrl);if (!ref) return false;const cacheKey = `${ref.owner}/${ref.repo}`;const cached = spaceVisibilityCache.get(cacheKey);if (cached && Date.now() - cached.timestamp < SPACE_VISIBILITY_TTL_MS) {return cached.isPrivate;}try {const statusCode = await fetchStatusCode(`https://huggingface.co/api/spaces/${ref.owner}/${ref.repo}`,);const isPrivate = statusCode === 401 || statusCode === 403 || statusCode === 404;spaceVisibilityCache.set(cacheKey, { isPrivate, timestamp: Date.now() });return isPrivate;} catch {if (cached) return cached.isPrivate;return false;}}function renderChannelBadge(channel, configuredLabel) {23 unmodified linesfunction renderDashboard(initialData) {const controlUiHref = `${APP_BASE}/`;const keepAwakeHtml = !UPTIMEROBOT_SETUP_ENABLED? `<div id="uptimerobot-private-note" class="helper-summary">UptimeRobot setup is disabled for this Space.</div>`: initialData.spacePrivate? `<div id="uptimerobot-private-note" class="helper-summary"><strong>This Space is private.</strong> External monitors cannot reliably access private HF health URLs, so keep-awake setup is only available on public Spaces.</div>`: `<div id="uptimerobot-public-flow"><div id="uptimerobot-summary" class="helper-summary">One-time setup for public Spaces. Paste your UptimeRobot <strong>Main API key</strong> to create the monitor.</div><button id="uptimerobot-toggle" class="helper-toggle" type="button">Set Up Monitor</button><div id="uptimerobot-shell" class="helper-shell hidden"><div class="helper-copy">Do <strong>not</strong> use the Read-only API key or a Monitor-specific API key.</div><div class="helper-row"><inputid="uptimerobot-key"class="helper-input"type="password"placeholder="Paste your UptimeRobot Main API key"autocomplete="off"/><button id="uptimerobot-btn" class="helper-button" type="button">Create Monitor</button></div><div class="helper-note">One-time setup. Your key is only used to create the monitor for this Space.</div></div></div>`;return `<!DOCTYPE html><html lang="en">284 unmodified linescolor: var(--text-dim);font-size: 0.9rem;line-height: 1.5;}.helper-summary strong {color: var(--text);}.helper-summary.success {background: rgba(16, 185, 129, 0.08);}.helper-toggle {margin-top: 14px;display: inline-flex;align-items: center;justify-content: center;background: rgba(255, 255, 255, 0.04);color: var(--text);border: 1px solid rgba(255, 255, 255, 0.08);border-radius: 12px;padding: 12px 16px;font: inherit;font-weight: 600;cursor: pointer;}@media (max-width: 700px) {body {87 unmodified lines<div class="stat-card helper-card"><span class="stat-label">Keep Space Awake</span>${keepAwakeHtml}<div id="uptimerobot-result" class="helper-result"></div></div><div class="footer">56 unmodified lines}}const monitorStateKey = 'huggingclaw_uptimerobot_setup_v1';const KEEP_AWAKE_PRIVATE = ${initialData.spacePrivate ? "true" : "false"};const KEEP_AWAKE_SETUP_ENABLED = ${UPTIMEROBOT_SETUP_ENABLED ? "true" : "false"};function setMonitorUiState(isConfigured) {const summary = document.getElementById('uptimerobot-summary');const shell = document.getElementById('uptimerobot-shell');const toggle = document.getElementById('uptimerobot-toggle');if (!summary || !shell || !toggle) {return;}if (isConfigured) {summary.classList.add('success');summary.innerHTML = '<strong>Already set up.</strong> Your UptimeRobot monitor should keep this public Space awake.';shell.classList.add('hidden');toggle.textContent = 'Set Up Again';} else {summary.classList.remove('success');summary.innerHTML = 'One-time setup for public Spaces. Paste your UptimeRobot <strong>Main API key</strong> to create the monitor.';toggle.textContent = 'Set Up Monitor';}}function restoreMonitorUiState() {try {const value = window.localStorage.getItem(monitorStateKey);setMonitorUiState(value === 'done');} catch {setMonitorUiState(false);}}function toggleMonitorSetup() {const shell = document.getElementById('uptimerobot-shell');shell.classList.toggle('hidden');}async function setupUptimeRobot() {const input = document.getElementById('uptimerobot-key');const button = document.getElementById('uptimerobot-btn');const result = document.getElementById('uptimerobot-result');const apiKey = input.value.trim();if (!apiKey) {result.className = 'helper-result error';result.textContent = 'Paste your UptimeRobot Main API key first.';return;}button.disabled = true;button.textContent = 'Creating...';result.className = 'helper-result';result.textContent = '';try {const res = await fetch(getDashboardBase() + '/uptimerobot/setup' + getCurrentSearch(), {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ apiKey })});const data = await res.json();if (!res.ok) {throw new Error(data.message || 'Failed to create monitor.');}result.className = 'helper-result ok';result.textContent = data.message || 'UptimeRobot monitor is ready.';input.value = '';try {window.localStorage.setItem(monitorStateKey, 'done');} catch {}setMonitorUiState(true);document.getElementById('uptimerobot-shell').classList.add('hidden');} catch (error) {result.className = 'helper-result error';result.textContent = error.message || 'Failed to create monitor.';} finally {button.disabled = false;button.textContent = 'Create Monitor';}}updateStats();setInterval(updateStats, 10000);document.getElementById('control-ui-link').setAttribute('href', getDashboardBase() + '/app/' + getCurrentSearch());if (KEEP_AWAKE_SETUP_ENABLED && !KEEP_AWAKE_PRIVATE) {restoreMonitorUiState();document.getElementById('uptimerobot-btn').addEventListener('click', setupUptimeRobot);document.getElementById('uptimerobot-toggle').addEventListener('click', toggleMonitorSetup);}</script></body></html>`;}function readRequestBody(req) {return new Promise((resolve, reject) => {let body = "";req.on("data", (chunk) => {body += chunk;if (body.length > 1024 * 64) {reject(new Error("Request too large"));req.destroy();}});req.on("end", () => resolve(body));req.on("error", reject);});}function postUptimeRobot(path, form) {const body = new URLSearchParams(form).toString();return new Promise((resolve, reject) => {const request = https.request({hostname: "api.uptimerobot.com",port: 443,method: "POST",path,headers: {"Content-Type": "application/x-www-form-urlencoded","Content-Length": Buffer.byteLength(body),},},(response) => {let raw = "";response.setEncoding("utf8");response.on("data", (chunk) => {raw += chunk;});response.on("end", () => {try {resolve(JSON.parse(raw));} catch {reject(new Error("Unexpected response from UptimeRobot"));}});},);request.on("error", reject);request.write(body);request.end();});}async function createUptimeRobotMonitor(apiKey, host) {const cleanHost = String(host || "").replace(/^https?:\/\//, "").replace(/\/.*$/, "");if (!cleanHost) {throw new Error("Missing Space host.");}const monitorUrl = `https://${cleanHost}/health`;const existing = await postUptimeRobot("/v2/getMonitors", {api_key: apiKey,format: "json",logs: "0",response_times: "0",response_times_limit: "1",});const existingMonitor = Array.isArray(existing.monitors)? existing.monitors.find((monitor) => monitor.url === monitorUrl): null;if (existingMonitor) {return {created: false,message: `Monitor already exists for ${monitorUrl}`,};}const created = await postUptimeRobot("/v2/newMonitor", {api_key: apiKey,format: "json",type: "1",friendly_name: `HuggingClaw ${cleanHost}`,url: monitorUrl,interval: "300",});if (created.stat !== "ok") {const message =created?.error?.message ||created?.message ||"Failed to create UptimeRobot monitor.";throw new Error(message);}return {created: true,message: `Monitor created for ${monitorUrl}`,};}function proxyHttp(req, res, proxyPath = req.url, proxyPort = GATEWAY_PORT) {const clientIp = getForwardedClientIp(req);151 unmodified linesreturn;}if (pathname === "/uptimerobot/setup" ||pathname === DASHBOARD_UPTIMEROBOT_PATH) {if (req.method !== "POST") {res.writeHead(405, { "Content-Type": "application/json" });res.end(JSON.stringify({ message: "Method not allowed" }));return;}void (async () => {try {if (!UPTIMEROBOT_SETUP_ENABLED) {res.writeHead(403, { "Content-Type": "application/json" });res.end(JSON.stringify({ message: "Uptime setup is disabled." }));return;}if (isRateLimited(req)) {res.writeHead(429, { "Content-Type": "application/json" });res.end(JSON.stringify({ message: "Too many requests." }));return;}if (!isAllowedUptimeSetupOrigin(req)) {res.writeHead(403, { "Content-Type": "application/json" });res.end(JSON.stringify({ message: "Invalid request origin." }));return;}const body = await readRequestBody(req);const parsed = JSON.parse(body || "{}");const apiKey = String(parsed.apiKey || "").trim();if (!isValidUptimeApiKey(apiKey)) {res.writeHead(400, { "Content-Type": "application/json" });res.end(JSON.stringify({message: "A valid API key is required.",}),);return;}const result = await createUptimeRobotMonitor(apiKey, req.headers.host);res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify(result));} catch (error) {res.writeHead(400, { "Content-Type": "application/json" });res.end(JSON.stringify({message:error && error.message? error.message: "Failed to create UptimeRobot monitor.",}),);}})();return;}if (isDashboardRoute(pathname)) {void (async () => {const guardianStatus = readGuardianStatus();const initialData = {model: LLM_MODEL,whatsapp: {configured: guardianStatus.configured,connected: guardianStatus.connected,pairing: guardianStatus.pairing,},telegram: normalizeChannelStatus(null, TELEGRAM_ENABLED),sync: readSyncStatus(),uptime: uptimeHuman,spacePrivate: await resolveSpaceIsPrivate(parsedUrl),};res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });res.end(renderDashboard(initialData));})();return;}1234510 unmodified lines1617181920212223242526 unmodified lines525354555657585953 unmodified lines11311411511611711833 unmodified lines15215315415515615715815916016116216316423 unmodified lines188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219284 unmodified lines50450550650750850951051151251351451551651751851952052152252352487 unmodified lines61261361461561661756 unmodified lines674675676677678679680681682683684685686687688151 unmodified lines840841842843844845846847848849850851852853854855856857858859860861// Single public entrypoint for HF Spaces: local dashboard + reverse proxy to OpenClaw.const http = require("http");const fs = require("fs");const net = require("net");10 unmodified linesconst DASHBOARD_BASE = "/dashboard";const DASHBOARD_STATUS_PATH = `${DASHBOARD_BASE}/status`;const DASHBOARD_HEALTH_PATH = `${DASHBOARD_BASE}/health`;const DASHBOARD_APP_BASE = `${DASHBOARD_BASE}/app`;const APP_BASE = "/app";const UPTIMEROBOT_STATUS_FILE = "/tmp/huggingclaw-uptimerobot-status.json";const UPTIMEROBOT_API_KEY_SET = !!process.env.UPTIMEROBOT_API_KEY;function parseRequestUrl(url) {try {26 unmodified linesreturn (pathname === "/health" ||pathname === "/status" ||pathname === DASHBOARD_HEALTH_PATH ||pathname === DASHBOARD_STATUS_PATH);}53 unmodified lines);}function readSyncStatus() {try {if (fs.existsSync("/tmp/sync-status.json")) {33 unmodified linesreturn { configured: true, connected: false, pairing: false };}function getUptimeRobotStatus() {try {if (fs.existsSync(UPTIMEROBOT_STATUS_FILE)) {return JSON.parse(fs.readFileSync(UPTIMEROBOT_STATUS_FILE, "utf8"));}} catch {}return null;}function renderChannelBadge(channel, configuredLabel) {23 unmodified linesfunction renderDashboard(initialData) {const controlUiHref = `${APP_BASE}/`;const urStatus = initialData.uptimerobotStatus;let keepAwakeHtml;if (urStatus?.configured) {keepAwakeHtml = `<div class="helper-summary success"><div class="status-badge status-online"><div class="pulse"></div>CONFIGURED</div><span>UptimeRobot monitor active for <code>${urStatus.url || "your /health endpoint"}</code>.</span></div>`;} else if (urStatus?.configured === false) {keepAwakeHtml = `<div class="helper-summary" style="background:rgba(239,68,68,0.08);"><div class="status-badge status-offline">FAILED</div><span>Monitor setup failed. Check Space logs for details.</span></div>`;} else if (UPTIMEROBOT_API_KEY_SET) {keepAwakeHtml = `<div class="helper-summary"><div class="status-badge status-syncing">SETTING UP…</div><span>UptimeRobot monitor is being configured.</span></div>`;} else {keepAwakeHtml = `<div class="helper-summary"><strong>Not configured.</strong> Add <code>UPTIMEROBOT_API_KEY</code> to Space secrets to enable keep-awake monitoring.</div>`;}return `<!DOCTYPE html><html lang="en">284 unmodified linescolor: var(--text-dim);font-size: 0.9rem;line-height: 1.5;display: flex;align-items: center;gap: 10px;flex-wrap: wrap;}.helper-summary strong { color: var(--text); }.helper-summary code {background: rgba(255,255,255,0.06);padding: 2px 6px;border-radius: 6px;font-size: 0.82rem;color: var(--text);}.helper-summary.success { background: rgba(16, 185, 129, 0.08); }@media (max-width: 700px) {body {87 unmodified lines<div class="stat-card helper-card"><span class="stat-label">Keep Space Awake</span>${keepAwakeHtml}</div><div class="footer">56 unmodified lines}}updateStats();setInterval(updateStats, 10000);document.getElementById('control-ui-link').setAttribute('href', getDashboardBase() + '/app/' + getCurrentSearch());</script></body></html>`;}function proxyHttp(req, res, proxyPath = req.url, proxyPort = GATEWAY_PORT) {const clientIp = getForwardedClientIp(req);151 unmodified linesreturn;}if (isDashboardRoute(pathname)) {const guardianStatus = readGuardianStatus();const initialData = {model: LLM_MODEL,whatsapp: {configured: guardianStatus.configured,connected: guardianStatus.connected,pairing: guardianStatus.pairing,},telegram: normalizeChannelStatus(null, TELEGRAM_ENABLED),sync: readSyncStatus(),uptime: uptimeHuman,uptimerobotStatus: getUptimeRobotStatus(),};res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });res.end(renderDashboard(initialData));return;}
9 unmodified lines101112131415161718192014 unmodified lines353637383940418 unmodified lines50515253545519 unmodified lines757677787980818283849 unmodified lines# Optional:# - UPTIMEROBOT_MONITOR_NAME: friendly name for the monitor# - UPTIMEROBOT_ALERT_CONTACTS: dash-separated alert contact IDs, e.g. "123456-789012"# - UPTIMEROBOT_INTERVAL: monitoring interval in minutes (subject to account limits)API_URL="https://api.uptimerobot.com/v2"API_KEY="${UPTIMEROBOT_API_KEY:-}"SPACE_HOST_INPUT="${1:-${SPACE_HOST:-}}"if [ -z "$API_KEY" ]; thenecho "Missing UPTIMEROBOT_API_KEY."14 unmodified linesMONITOR_URL="https://${SPACE_HOST_CLEAN}/health"MONITOR_NAME="${UPTIMEROBOT_MONITOR_NAME:-HuggingClaw ${SPACE_HOST_CLEAN}}"INTERVAL="${UPTIMEROBOT_INTERVAL:-5}"echo "Checking existing UptimeRobot monitors for ${MONITOR_URL}..."MONITORS_RESPONSE=$(curl -sS -X POST "${API_URL}/getMonitors" \8 unmodified lines')if [ -n "$MONITOR_ID" ]; thenecho "Monitor already exists (id=${MONITOR_ID}) for ${MONITOR_URL}"exit 0fi19 unmodified linesCREATE_STATUS=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.stat // "fail"')if [ "$CREATE_STATUS" != "ok" ]; thenecho "Failed to create monitor."printf '%s\n' "$CREATE_RESPONSE"exit 1fiNEW_ID=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.monitor.id // empty')echo "Created UptimeRobot monitor ${NEW_ID:-"(id unavailable)"} for ${MONITOR_URL}"9 unmodified lines10111213141516171819202114 unmodified lines363738394041428 unmodified lines515253545556575819 unmodified lines78798081828384858687888990919 unmodified lines# Optional:# - UPTIMEROBOT_MONITOR_NAME: friendly name for the monitor# - UPTIMEROBOT_ALERT_CONTACTS: dash-separated alert contact IDs, e.g. "123456-789012"# - UPTIMEROBOT_INTERVAL: monitoring interval in seconds (default: 300 = 5 min; min: 30)API_URL="https://api.uptimerobot.com/v2"API_KEY="${UPTIMEROBOT_API_KEY:-}"SPACE_HOST_INPUT="${1:-${SPACE_HOST:-}}"STATUS_FILE="/tmp/huggingclaw-uptimerobot-status.json"if [ -z "$API_KEY" ]; thenecho "Missing UPTIMEROBOT_API_KEY."14 unmodified linesMONITOR_URL="https://${SPACE_HOST_CLEAN}/health"MONITOR_NAME="${UPTIMEROBOT_MONITOR_NAME:-HuggingClaw ${SPACE_HOST_CLEAN}}"INTERVAL="${UPTIMEROBOT_INTERVAL:-300}"echo "Checking existing UptimeRobot monitors for ${MONITOR_URL}..."MONITORS_RESPONSE=$(curl -sS -X POST "${API_URL}/getMonitors" \8 unmodified lines')if [ -n "$MONITOR_ID" ]; thenprintf '{"configured":true,"monitorId":"%s","url":"%s","alreadyExisted":true,"timestamp":"%s"}\n' \"$MONITOR_ID" "$MONITOR_URL" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATUS_FILE"echo "Monitor already exists (id=${MONITOR_ID}) for ${MONITOR_URL}"exit 0fi19 unmodified linesCREATE_STATUS=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.stat // "fail"')if [ "$CREATE_STATUS" != "ok" ]; thenprintf '{"configured":false,"error":"creation failed","timestamp":"%s"}\n' \"$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATUS_FILE"echo "Failed to create monitor."printf '%s\n' "$CREATE_RESPONSE"exit 1fiNEW_ID=$(printf '%s' "$CREATE_RESPONSE" | jq -r '.monitor.id // empty')printf '{"configured":true,"monitorId":"%s","url":"%s","timestamp":"%s"}\n' \"${NEW_ID:-}" "$MONITOR_URL" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$STATUS_FILE"echo "Created UptimeRobot monitor ${NEW_ID:-"(id unavailable)"} for ${MONITOR_URL}"
144 unmodified lines145146147148149150151346 unmodified lines498499500501502503144 unmodified linesexport CLOUDFLARE_WORKERS_TOKENCF_PROXY_ENV_FILE="/tmp/huggingclaw-cloudflare-proxy.env"if [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ] || [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; thenexport CLOUDFLARE_PROXY_DOMAINS="${CLOUDFLARE_PROXY_DOMAINS:-api.telegram.org,web.whatsapp.com,googleapis.com}"# Default debug off for production. Set CLOUDFLARE_PROXY_DEBUG=true in HF# Space secrets to surface per-request "Redirecting" + error-cause logs.export CLOUDFLARE_PROXY_DEBUG="${CLOUDFLARE_PROXY_DEBUG:-false}"346 unmodified linesnode /home/node/app/health-server.js &HEALTH_PID=$!# ββ Launch gateway ββecho "Launching OpenClaw gateway on port 7860..."144 unmodified lines145146147148149150346 unmodified lines497498499500501502503504505506507144 unmodified linesexport CLOUDFLARE_WORKERS_TOKENCF_PROXY_ENV_FILE="/tmp/huggingclaw-cloudflare-proxy.env"if [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ] || [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; then# Default debug off for production. Set CLOUDFLARE_PROXY_DEBUG=true in HF# Space secrets to surface per-request "Redirecting" + error-cause logs.export CLOUDFLARE_PROXY_DEBUG="${CLOUDFLARE_PROXY_DEBUG:-false}"346 unmodified linesnode /home/node/app/health-server.js &HEALTH_PID=$!if [ -n "${UPTIMEROBOT_API_KEY:-}" ] && [ -n "${SPACE_HOST:-}" ]; thenecho "Setting up UptimeRobot monitor..."bash /home/node/app/setup-uptimerobot.sh "${SPACE_HOST}" || truefi# ββ Launch gateway ββecho "Launching OpenClaw gateway on port 7860..."
.env.example+6-6
README.md+5-10
cloudflare-proxy-setup.py+31-4
cloudflare-proxy.js+25-5
health-server.js+61-453
setup-uptimerobot.sh+9-2
start.sh+5-1