Spaces:
Paused
Paused
feat: implement wa-guardian for automated WhatsApp pairing and add Control UI shortcut to dashboard
Browse filesFiles changed (5)
- .env.example+2-6
- README.md+3-12
- health-server.js+66-29
- start.sh+11-10
- wa-guardian.jsAdded+126
141 unmodified lines14214314414514614714814915013 unmodified lines164165166167168169170171172141 unmodified lines# Multiple user IDs (comma-separated for team access)# TELEGRAM_USER_IDS=123456789,987654321,555555555# WhatsApp integration (pairing mode via CLI)# WHATSAPP_ENABLED=true# ββ OPTIONAL: Workspace Backup to HF Dataset ββHF_USERNAME=your_hf_usernameHF_TOKEN=hf_your_token_here13 unmodified lines# Workspace auto-sync interval (seconds). Default: 600.SYNC_INTERVAL=600# ββ OPTIONAL: Webhooks ββ# URL to send HTTP POST requests on startup and backup errors# WEBHOOK_URL=https://your-webhook-endpoint.com/webhook# ββ OPTIONAL: Advanced ββ# Pin OpenClaw version. Default: latest141 unmodified lines14214314414514614713 unmodified lines161162163164165166167168141 unmodified lines# Multiple user IDs (comma-separated for team access)# TELEGRAM_USER_IDS=123456789,987654321,555555555# ββ OPTIONAL: Workspace Backup to HF Dataset ββHF_USERNAME=your_hf_usernameHF_TOKEN=hf_your_token_here13 unmodified lines# Workspace auto-sync interval (seconds). Default: 600.SYNC_INTERVAL=600# Webhooks: Standard POST notifications for lifecycle events# WEBHOOK_URL=https://your-webhook-endpoint.com/log# ββ OPTIONAL: Advanced ββ# Pin OpenClaw version. Default: latest
94 unmodified lines959697989910010110210310410510610710810911011111294 unmodified linesTo use WhatsApp:1. Add the secret `WHATSAPP_ENABLED` and set it to `true`.2. Once the Space restarts, use the OpenClaw CLI to link your account:```bashnpm install -g openclaw@latestopenclaw channels login --gateway https://YOUR_SPACE_URL.hf.space --channel whatsapp```3. Scan the QR code with your phone (WhatsApp β Linked Devices).> [!NOTE]> HuggingClaw uses dynamic DNS-over-HTTPS probing to ensure reliability on HuggingFace Spaces.## πΎ Workspace Backup *(Optional)*94 unmodified lines959697989910010110210394 unmodified linesTo use WhatsApp:1. Visit your Space's Dashboard (Port 7861) and click **π Open Control UI**.2. In the Control UI, go to **Channels** β **WhatsApp** β **Login**.3. Scan the QR code with your phone. π±## πΎ Workspace Backup *(Optional)*
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950102 unmodified lines15315415515615715867 unmodified lines22622722822923023165 unmodified lines297298299300301302// Lightweight health server and dashboard on port 7861const http = require('http');const fs = require('fs');const path = require('path');const PORT = process.env.HEALTH_PORT || 7861;const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || 'Not Set';const WHATSAPP_ENABLED = process.env.WHATSAPP_ENABLED === 'true' || process.env.WHATSAPP_ENABLED === '1';const TELEGRAM_ENABLED = !!process.env.TELEGRAM_BOT_TOKEN;const server = http.createServer((req, res) => {const uptime = Math.floor((Date.now() - startTime) / 1000);const uptimeHuman = `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`;if (req.url === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({status: 'ok',uptime: uptime,uptimeHuman: uptimeHuman,timestamp: new Date().toISOString()}));return;}if (req.url === '/status') {let syncStatus = { status: 'unknown', message: 'No sync data yet' };try {if (fs.existsSync('/tmp/sync-status.json')) {syncStatus = JSON.parse(fs.readFileSync('/tmp/sync-status.json', 'utf8'));}} catch (e) {}res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({model: LLM_MODEL,whatsapp: WHATSAPP_ENABLED,telegram: TELEGRAM_ENABLED,sync: syncStatus,uptime: uptimeHuman}));return;}if (req.url === '/') {res.writeHead(200, { 'Content-Type': 'text/html' });res.end(`<!DOCTYPE html><html lang="en">102 unmodified linesword-break: break-all;}.status-badge {display: inline-flex;align-items: center;67 unmodified lines<span class="stat-label">Telegram</span><span id="tg-status">Loading...</span></div></div><div class="stat-card" style="width: 100%;">65 unmodified linesres.end();});server.listen(PORT, '0.0.0.0', () => {console.log(`π₯ Health server & Dashboard listening on port ${PORT}`);});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667102 unmodified lines17017117217317417517617717817918018118218318418518618718818919019119219319467 unmodified lines26226326426526626726865 unmodified lines334335336337338339// Lightweight health server and dashboard on port 7861const http = require("http");const fs = require("fs");const PORT = process.env.HEALTH_PORT || 7861;const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || "Not Set";const GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || "huggingclaw";const SPACE_HOST = process.env.SPACE_HOST || "localhost:7860";const TELEGRAM_ENABLED = !!process.env.TELEGRAM_BOT_TOKEN;const server = http.createServer((req, res) => {const uptime = Math.floor((Date.now() - startTime) / 1000);const uptimeHuman = `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`;if (req.url === "/health") {res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "ok",uptime: uptime,uptimeHuman: uptimeHuman,timestamp: new Date().toISOString(),}),);return;}if (req.url === "/status") {let syncStatus = { status: "unknown", message: "No sync data yet" };try {if (fs.existsSync("/tmp/sync-status.json")) {syncStatus = JSON.parse(fs.readFileSync("/tmp/sync-status.json", "utf8"),);}} catch (e) {}res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({model: LLM_MODEL,whatsapp: true,telegram: TELEGRAM_ENABLED,sync: syncStatus,uptime: uptimeHuman,token: GATEWAY_TOKEN,}),);return;}// Auto-login redirect to OpenClaw Control UIif (req.url === "/login") {const protocol = req.headers["x-forwarded-proto"] || "http";const host = req.headers["host"] || SPACE_HOST;const target = `${protocol}://${host}/?token=${GATEWAY_TOKEN}`;res.writeHead(302, { Location: target });res.end();return;}if (req.url === "/") {res.writeHead(200, { "Content-Type": "text/html" });res.end(`<!DOCTYPE html><html lang="en">102 unmodified linesword-break: break-all;}.stat-btn {grid-column: span 2;background: var(--accent);color: #fff;padding: 16px;border-radius: 16px;text-align: center;text-decoration: none;font-weight: 600;margin-top: 10px;transition: transform 0.3s ease, box-shadow 0.3s ease;box-shadow: 0 10px 20px -5px rgba(59, 130, 246, 0.4);}.stat-btn:hover {transform: scale(1.02);box-shadow: 0 15px 30px -5px rgba(59, 130, 246, 0.6);}.status-badge {display: inline-flex;align-items: center;67 unmodified lines<span class="stat-label">Telegram</span><span id="tg-status">Loading...</span></div><a href="/login" class="stat-btn">π Open Control UI</a></div><div class="stat-card" style="width: 100%;">65 unmodified linesres.end();});server.listen(PORT, "0.0.0.0", () => {console.log(`π₯ Health server & Dashboard listening on port ${PORT}`);});
234 unmodified lines23523623723823924024124224324410 unmodified lines25525625725825926026126226326426557 unmodified lines323324325326327328329330331332234 unmodified linesfiif [ "$WHATSAPP_ENABLED" = "true" ] || [ "$WHATSAPP_ENABLED" = "1" ]; thenCONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.plugins.entries.whatsapp = {"enabled": true}')CONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.channels.whatsapp = {"dmPolicy": "pairing"}')fi# Write configecho "$CONFIG_JSON" > "/home/node/.openclaw/openclaw.json"10 unmodified lineselseprintf " β %-40s β\n" "Telegram: β not configured"fiif [ "$WHATSAPP_ENABLED" = "true" ] || [ "$WHATSAPP_ENABLED" = "1" ]; thenprintf " β %-40s β\n" "WhatsApp: β enabled"elseprintf " β %-40s β\n" "WhatsApp: β not configured"fiif [ -n "$HF_USERNAME" ] && [ -n "$HF_TOKEN" ]; thenprintf " β %-40s β\n" "Backup: β ${HF_USERNAME}/${BACKUP_DATASET:-huggingclaw-backup}"else57 unmodified lines# ββ Start background services ββexport LLM_MODEL="$LLM_MODEL"node /home/node/app/health-server.js &/home/node/app/keep-alive.sh &python3 /home/node/app/workspace-sync.py &# ββ Launch gateway ββecho "π Launching OpenClaw gateway on port 7860..."234 unmodified lines23523623723823924024124210 unmodified lines25325425525625725825957 unmodified lines317318319320321322323324325326327328329330331332333234 unmodified linesfiCONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.plugins.entries.whatsapp = {"enabled": true}')CONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.channels.whatsapp = {"dmPolicy": "pairing"}')# Write configecho "$CONFIG_JSON" > "/home/node/.openclaw/openclaw.json"10 unmodified lineselseprintf " β %-40s β\n" "Telegram: β not configured"fiprintf " β %-40s β\n" "WhatsApp: β enabled"if [ -n "$HF_USERNAME" ] && [ -n "$HF_TOKEN" ]; thenprintf " β %-40s β\n" "Backup: β ${HF_USERNAME}/${BACKUP_DATASET:-huggingclaw-backup}"else57 unmodified lines# ββ Start background services ββexport LLM_MODEL="$LLM_MODEL"# 10. Start Health Server & Dashboardnode /home/node/app/health-server.js &HEALTH_PID=$!# 11. Start WhatsApp Guardian (Automates pairing)node /home/node/app/wa-guardian.js &GUARDIAN_PID=$!echo "π‘οΈ WhatsApp Guardian started (PID: $GUARDIAN_PID)"# 12. Start Workspace Syncpython3 -u /home/node/app/workspace-sync.py &# ββ Launch gateway ββecho "π Launching OpenClaw gateway on port 7860..."
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126/** * HuggingClaw WhatsApp Guardian * * Automates the WhatsApp pairing process on HuggingFace Spaces. * Handles the "515 Restart" by monitoring the channel status and * re-applying the configuration after a successful scan. */"use strict";
const { WebSocket } = require('/home/node/.openclaw/openclaw-app/node_modules/ws');const { randomUUID } = require('node:crypto');
const GATEWAY_URL = "ws://127.0.0.1:7860";const GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || "huggingclaw";const CHECK_INTERVAL = 5000;const WAIT_TIMEOUT = 120000;
let isWaiting = false;let hasShownWaitMessage = false;
async function createConnection() { return new Promise((resolve, reject) => { const ws = new WebSocket(GATEWAY_URL); let resolved = false;
ws.on("message", (data) => { const msg = JSON.parse(data.toString());
if (msg.type === "event" && msg.event === "connect.challenge") { ws.send(JSON.stringify({ type: "req", id: randomUUID(), method: "connect", params: { auth: { token: GATEWAY_TOKEN }, client: { id: "wa-guardian", platform: "linux", mode: "backend", version: "1.0.0" }, scopes: ["operator.admin", "operator.pairing", "operator.read", "operator.write"] } })); return; }
if (!resolved && msg.type === "res" && msg.ok) { resolved = true; resolve(ws); } });
ws.on("error", (e) => { if (!resolved) reject(e); }); setTimeout(() => { if (!resolved) { ws.close(); reject(new Error("Timeout")); } }, 10000); });}
async function callRpc(ws, method, params) { return new Promise((resolve, reject) => { const id = randomUUID(); const handler = (data) => { const msg = JSON.parse(data.toString()); if (msg.id === id) { ws.removeListener("message", handler); resolve(msg); } }; ws.on("message", handler); ws.send(JSON.stringify({ type: "req", id, method, params })); setTimeout(() => { ws.removeListener("message", handler); reject(new Error("RPC Timeout")); }, WAIT_TIMEOUT + 5000); });}
async function checkStatus() { if (isWaiting) return;
let ws; try { ws = await createConnection();
// Check if WhatsApp channel exists and its status const statusRes = await callRpc(ws, "channels.status", {}); const channels = (statusRes.payload || statusRes.result)?.channels || {}; const wa = channels.whatsapp;
if (!wa) { ws.close(); return; }
// If connected, we are good if (wa.connected) { ws.close(); return; }
// If "Ready to pair", we wait for the scan isWaiting = true; if (!hasShownWaitMessage) { console.log("\n[guardian] π± WhatsApp pairing in progress. Please scan the QR code in the Control UI."); hasShownWaitMessage = true; }
console.log("[guardian] Waiting for pairing completion..."); const waitRes = await callRpc(ws, "web.login.wait", { timeoutMs: WAIT_TIMEOUT }); const result = waitRes.payload || waitRes.result;
if (result && (result.connected || (result.message && result.message.includes("515")))) { console.log("[guardian] β
Pairing completed! Saving session and restarting gateway..."); hasShownWaitMessage = false; // Auto-reapply config to finalize pairing const getRes = await callRpc(ws, "config.get", {}); if (getRes.ok) { await callRpc(ws, "config.apply", { raw: getRes.payload.raw, baseHash: getRes.payload.hash }); console.log("[guardian] Configuration re-applied."); } }
} catch (e) { // Normal timeout or gateway starting up } finally { isWaiting = false; if (ws) ws.close(); }}
console.log("[guardian] βοΈ WhatsApp Guardian active. Monitoring pairing status...");setInterval(checkStatus, CHECK_INTERVAL);setTimeout(checkStatus, 10000);.env.example+2-6
README.md+3-12
health-server.js+66-29
start.sh+11-10
wa-guardian.jsAdded+126