Spaces:
Paused
Paused
feat: replace DNS fix with automated Cloudflare outbound proxy provisioning for blocked network requests
Browse filesFiles changed (8)
- CHANGELOG.md+3-1
- Dockerfile+5-3
- README.md+45-3
- cloudflare-proxy-setup.pyAdded+202
- cloudflare-proxy.jsAdded+140
- cloudflare-worker.jsAdded+89
- dns-fix.jsDeleted-108
- start.sh+13-10
6 unmodified lines7891011121 unmodified line14151617181976 unmodified lines969798996 unmodified lines### Added- **Custom OpenAI-compatible provider registration** β HuggingClaw can now register a custom provider at startup with `CUSTOM_PROVIDER_NAME`, `CUSTOM_BASE_URL`, and `CUSTOM_MODEL_ID`, so you can point `LLM_MODEL` at your own OpenAI-compatible endpoint without modifying the OpenClaw CLI### Changed1 unmodified line- **HF username no longer required in most cases** β backup namespace resolution now works from `HF_USERNAME`, `SPACE_AUTHOR_NAME`, or the authenticated HF token, so `HF_TOKEN` is usually enough on its own- **Startup restore path modernized** β startup now restores workspace and hidden state through `workspace-sync.py restore` instead of configuring a token-bearing git remote- **README refreshed for the new backup model** β documentation now describes token-only backup setup, the removed git sync assumptions, and the hardened dashboard helper behavior### Fixed76 unmodified lines- `start.sh` β config generator + validation + orchestrator- `workspace-sync.sh` β periodic workspace backup- `health-server.js` β lightweight health endpoint- `dns-fix.js` β DNS override for HF network restrictions6 unmodified lines789101112131 unmodified line151617181920212276 unmodified lines991001016 unmodified lines### Added- **Custom OpenAI-compatible provider registration** β HuggingClaw can now register a custom provider at startup with `CUSTOM_PROVIDER_NAME`, `CUSTOM_BASE_URL`, and `CUSTOM_MODEL_ID`, so you can point `LLM_MODEL` at your own OpenAI-compatible endpoint without modifying the OpenClaw CLI- **Automatic Cloudflare outbound proxy setup** β HuggingClaw can now provision and use a Cloudflare Worker proxy for blocked outbound traffic from a `CLOUDFLARE_API_TOKEN`, with the same transparent proxy model used in Hugging8n### Changed1 unmodified line- **HF username no longer required in most cases** β backup namespace resolution now works from `HF_USERNAME`, `SPACE_AUTHOR_NAME`, or the authenticated HF token, so `HF_TOKEN` is usually enough on its own- **Startup restore path modernized** β startup now restores workspace and hidden state through `workspace-sync.py restore` instead of configuring a token-bearing git remote- **README refreshed for the new backup model** β documentation now describes token-only backup setup, the removed git sync assumptions, and the hardened dashboard helper behavior- **Telegram networking simplified** β removed the channel-specific Telegram transport tweaks in favor of the generic Cloudflare outbound proxy path- **DNS monkey-patch removed** β HuggingClaw now relies on the Cloudflare outbound proxy path instead of the old `dns-fix.js` preload### Fixed76 unmodified lines- `start.sh` β config generator + validation + orchestrator- `workspace-sync.sh` β periodic workspace backup- `health-server.js` β lightweight health endpoint
62 unmodified lines636465666768697071727374751 unmodified line7778798081828362 unmodified linesnpm install -g openclaw@${OPENCLAW_VERSION}# Copy HuggingClaw filesCOPY --chown=1000:1000 dns-fix.js /opt/dns-fix.jsCOPY --chown=1000:1000 health-server.js /home/node/app/health-server.jsCOPY --chown=1000:1000 iframe-fix.cjs /home/node/app/iframe-fix.cjsCOPY --chown=1000:1000 start.sh /home/node/app/start.shCOPY --chown=1000:1000 wa-guardian.js /home/node/app/wa-guardian.jsCOPY --chown=1000:1000 workspace-sync.py /home/node/app/workspace-sync.pyRUN chmod +x /home/node/app/start.shUSER node1 unmodified lineOPENCLAW_VERSION=${OPENCLAW_VERSION} \PATH=/home/node/.local/bin:/usr/local/bin:$PATH \NODE_PATH=/home/node/browser-deps/node_modules \NODE_OPTIONS="--require /opt/dns-fix.js"WORKDIR /home/node/app62 unmodified lines6364656667686970717273747576771 unmodified line7980818283848562 unmodified linesnpm install -g openclaw@${OPENCLAW_VERSION}# Copy HuggingClaw filesCOPY --chown=1000:1000 cloudflare-proxy.js /opt/cloudflare-proxy.jsCOPY --chown=1000:1000 cloudflare-proxy-setup.py /home/node/app/cloudflare-proxy-setup.pyCOPY --chown=1000:1000 cloudflare-worker.js /home/node/app/cloudflare-worker.jsCOPY --chown=1000:1000 health-server.js /home/node/app/health-server.jsCOPY --chown=1000:1000 iframe-fix.cjs /home/node/app/iframe-fix.cjsCOPY --chown=1000:1000 start.sh /home/node/app/start.shCOPY --chown=1000:1000 wa-guardian.js /home/node/app/wa-guardian.jsCOPY --chown=1000:1000 workspace-sync.py /home/node/app/workspace-sync.pyRUN chmod +x /home/node/app/start.sh /home/node/app/cloudflare-proxy-setup.pyUSER node1 unmodified lineOPENCLAW_VERSION=${OPENCLAW_VERSION} \PATH=/home/node/.local/bin:/usr/local/bin:$PATH \NODE_PATH=/home/node/browser-deps/node_modules \NODE_OPTIONS="--require /opt/cloudflare-proxy.js"WORKDIR /home/node/app
13 unmodified lines14151617181910 unmodified lines30313233343513 unmodified lines4950515253545546 unmodified lines1021031041051061071081 unmodified line110111112113114115177 unmodified lines29329429529629729829913 unmodified linesdescription: The model ID to use, e.g. openai/gpt-4o or google/gemini-2.5-flash.- name: GATEWAY_TOKENdescription: A strong password or token to secure your OpenClaw Control UI.---<!-- Badges -->10 unmodified lines- [π₯ Video Tutorial](#-video-tutorial)- [π Quick Start](#-quick-start)- [π± Telegram Setup *(Optional)*](#-telegram-setup-optional)- [π¬ WhatsApp Setup *(Optional)*](#-whatsapp-setup-optional)- [πΎ Workspace Backup *(Optional)*](#-workspace-backup-optional)- [π Webhooks *(Optional)*](#-webhooks-optional)13 unmodified lines- π **Any LLM:** Use Claude, OpenAI GPT, Google Gemini, Grok, DeepSeek, Qwen, and 40+ providers (set `LLM_API_KEY` and `LLM_MODEL` accordingly).- β‘ **Zero Config:** Duplicate this Space and set **just three** secrets (LLM_API_KEY, LLM_MODEL, GATEWAY_TOKEN) β no other setup needed.- π³ **Fast Builds:** Uses a pre-built OpenClaw Docker image to deploy in minutes.- π **Built-In Browser:** Headless Chromium is included in the Space, so browser actions work from the start.- πΎ **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).46 unmodified lines1. Create a bot via [@BotFather](https://t.me/BotFather): send `/newbot`, follow prompts, and copy the bot token.2. Find your Telegram user ID with [@userinfobot](https://t.me/userinfobot).3. Add these secrets in Settings β Secrets. After restarting, the bot should appear online on Telegram.| Variable | Default | Description || :--- | :--- | :--- |1 unmodified line| `TELEGRAM_USER_ID` | β | Single Telegram user ID allowlist || `TELEGRAM_USER_IDS` | β | Comma-separated Telegram user IDs for team access |## π¬ WhatsApp Setup *(Optional)*To use WhatsApp, enable the channel and scan the QR code from the Control UI (**Channels** β **WhatsApp** β **Login**):177 unmodified linesβββ start.sh # Config generator, validator, and orchestratorβββ workspace-sync.py # Syncs workspace/state to HF Datasets via huggingface_hubβββ health-server.js # /health endpoint for uptime checksβββ dns-fix.js # DNS-over-HTTPS fallback (for blocked domains)βββ .env.example # Environment variable referenceβββ README.md # (this file)13 unmodified lines141516171819202110 unmodified lines3233343536373813 unmodified lines5253545556575846 unmodified lines1051061071081091101111121 unmodified line114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157177 unmodified lines33533633733833934034113 unmodified linesdescription: The model ID to use, e.g. openai/gpt-4o or google/gemini-2.5-flash.- name: GATEWAY_TOKENdescription: A strong password or token to secure your OpenClaw Control UI.- name: CLOUDFLARE_API_TOKENdescription: Optional Cloudflare API token for automatic outbound proxy setup.---<!-- Badges -->10 unmodified lines- [π₯ Video Tutorial](#-video-tutorial)- [π Quick Start](#-quick-start)- [π± Telegram Setup *(Optional)*](#-telegram-setup-optional)- [π Cloudflare Proxy *(Optional)*](#-cloudflare-proxy-optional)- [π¬ WhatsApp Setup *(Optional)*](#-whatsapp-setup-optional)- [πΎ Workspace Backup *(Optional)*](#-workspace-backup-optional)- [π Webhooks *(Optional)*](#-webhooks-optional)13 unmodified lines- π **Any LLM:** Use Claude, OpenAI GPT, Google Gemini, Grok, DeepSeek, Qwen, and 40+ providers (set `LLM_API_KEY` and `LLM_MODEL` accordingly).- β‘ **Zero Config:** Duplicate this Space and set **just three** secrets (LLM_API_KEY, LLM_MODEL, GATEWAY_TOKEN) β no other setup needed.- π³ **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).46 unmodified lines1. Create a bot via [@BotFather](https://t.me/BotFather): send `/newbot`, follow prompts, and copy the bot token.2. Find your Telegram user ID with [@userinfobot](https://t.me/userinfobot).3. Add `CLOUDFLARE_API_TOKEN` in Space secrets to let HuggingClaw auto-provision the outbound proxy, or set `CLOUDFLARE_PROXY_URL` manually if you already have a Worker.4. Add these secrets in Settings β Secrets. After restarting, the bot should appear online on Telegram.| Variable | Default | Description || :--- | :--- | :--- |1 unmodified line| `TELEGRAM_USER_ID` | β | Single Telegram user ID allowlist || `TELEGRAM_USER_IDS` | β | Comma-separated Telegram user IDs for team access |## π Cloudflare Proxy *(Optional)*Hugging Face Spaces sometimes blocks outgoing connections to Telegram, WhatsApp-related APIs, Google integrations, and other external services. HuggingClaw includes the same transparent Cloudflare proxy approach used in Hugging8n.Automatic setup:1. Create a Cloudflare API token with Workers edit permissions.2. Add `CLOUDFLARE_API_TOKEN` as a Space secret.3. Restart the Space.HuggingClaw will:- create or update a Worker named from your Space host- generate a private shared secret automatically- export `CLOUDFLARE_PROXY_URL` and `CLOUDFLARE_PROXY_SECRET` before OpenClaw starts- transparently proxy outbound external requests through Cloudflare by defaultDefault behavior:- `CLOUDFLARE_PROXY_DOMAINS=*`- all external traffic is proxied- Hugging Face internal hosts stay direct automaticallyThat wider default is intentional so Telegram, WhatsApp-related APIs, Google integrations, and other external providers work without extra domain tuning.Optional variables:| Variable | Default | Description || :--- | :--- | :--- || `CLOUDFLARE_API_TOKEN` | β | Cloudflare API token for automatic Worker setup || `CLOUDFLARE_ACCOUNT_ID` | auto | Optional Cloudflare account override || `CLOUDFLARE_WORKER_NAME` | derived from Space host | Optional Worker script name || `CLOUDFLARE_PROXY_URL` | auto | Use an existing Worker URL instead of auto-provisioning || `CLOUDFLARE_PROXY_SECRET` | auto | Optional shared secret override || `CLOUDFLARE_PROXY_DOMAINS` | `*` | Comma-separated proxied domains or `*` for all external traffic |Manual setup is also available with [cloudflare-worker.js](/Users/somrat/Development/hf-space/HuggingClaw/cloudflare-worker.js) if you prefer to deploy the Worker yourself.## π¬ WhatsApp Setup *(Optional)*To use WhatsApp, enable the channel and scan the QR code from the Control UI (**Channels** β **WhatsApp** β **Login**):177 unmodified linesβββ start.sh # Config generator, validator, and orchestratorβββ workspace-sync.py # Syncs workspace/state to HF Datasets via huggingface_hubβββ health-server.js # /health endpoint for uptime checksβββ cloudflare-proxy.js # Transparent outbound proxy for blocked domainsβββ .env.example # Environment variable referenceβββ README.md # (this file)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202#!/usr/bin/env python3
import jsonimport osimport reimport secretsimport sysimport urllib.errorimport urllib.requestfrom pathlib import Path
API_BASE = "https://api.cloudflare.com/client/v4"ENV_FILE = Path("/tmp/huggingclaw-cloudflare-proxy.env")DEFAULT_ALLOWED = [ "api.telegram.org", "web.whatsapp.com",]
def cf_request(method: str, path: str, token: str, body: bytes | None = None, content_type: str = "application/json"): req = urllib.request.Request( f"{API_BASE}{path}", data=body, method=method, headers={ "Authorization": f"Bearer {token}", "Content-Type": content_type, }, ) with urllib.request.urlopen(req, timeout=30) as response: payload = json.loads(response.read().decode("utf-8")) if not payload.get("success"): errors = payload.get("errors") or [{"message": "Unknown Cloudflare API error"}] raise RuntimeError(errors[0].get("message", "Unknown Cloudflare API error")) return payload["result"]
def slugify(value: str) -> str: cleaned = re.sub(r"[^a-z0-9-]+", "-", value.lower()).strip("-") cleaned = re.sub(r"-{2,}", "-", cleaned) if not cleaned: cleaned = "huggingclaw-proxy" return cleaned[:63].rstrip("-")
def derive_worker_name() -> str: explicit = os.environ.get("CLOUDFLARE_WORKER_NAME", "").strip() if explicit: return slugify(explicit) space_host = os.environ.get("SPACE_HOST", "").strip() if space_host: base = space_host.replace(".hf.space", "") return slugify(f"{base}-proxy") return "huggingclaw-proxy"
def render_worker(secret_value: str, allowed_targets: list[str], allow_proxy_all: bool) -> str: allowed_json = json.dumps(allowed_targets) allow_all_js = "true" if allow_proxy_all else "false" secret_json = json.dumps(secret_value) return f"""addEventListener("fetch", (event) => {{ event.respondWith(handleRequest(event.request));}});
const PROXY_SHARED_SECRET = {secret_json};const ALLOW_PROXY_ALL = {allow_all_js};const ALLOWED_TARGETS = {allowed_json};
function isAllowedHost(hostname) {{ const normalized = String(hostname || "").trim().toLowerCase(); if (!normalized) return false; if (ALLOW_PROXY_ALL) return true; return ALLOWED_TARGETS.some( (domain) => normalized === domain || normalized.endsWith(`.${{domain}}`), );}}
async function handleRequest(request) {{ const url = new URL(request.url); const targetHost = request.headers.get("x-target-host");
if (PROXY_SHARED_SECRET) {{ const providedSecret = request.headers.get("x-proxy-key") || ""; if (providedSecret !== PROXY_SHARED_SECRET) {{ return new Response("Unauthorized", {{ status: 401 }}); }} }}
let targetBase = ""; if (targetHost) {{ if (!isAllowedHost(targetHost)) {{ return new Response("Target host is not allowed.", {{ status: 403 }}); }} targetBase = `https://${{targetHost}}`; }} else if (url.pathname.startsWith("/bot")) {{ targetBase = "https://api.telegram.org"; }} else {{ return new Response("Invalid request.", {{ status: 400 }}); }}
const targetUrl = targetBase + url.pathname + url.search; const headers = new Headers(request.headers); headers.delete("cf-connecting-ip"); headers.delete("cf-ray"); headers.delete("cf-visitor"); headers.delete("x-real-ip"); headers.delete("x-target-host");
const proxiedRequest = new Request(targetUrl, {{ method: request.method, headers, body: request.body, redirect: "follow", }});
try {{ return await fetch(proxiedRequest); }} catch (error) {{ return new Response(`Proxy Error: ${{error.message}}`, {{ status: 502 }}); }}}}"""
def write_env(proxy_url: str, proxy_secret: str) -> None: ENV_FILE.write_text( "\n".join( [ f'export CLOUDFLARE_PROXY_URL="{proxy_url}"', f'export CLOUDFLARE_PROXY_SECRET="{proxy_secret}"', ] ) + "\n", encoding="utf-8", )
def main() -> int: existing_url = os.environ.get("CLOUDFLARE_PROXY_URL", "").strip() existing_secret = os.environ.get("CLOUDFLARE_PROXY_SECRET", "").strip() api_token = os.environ.get("CLOUDFLARE_API_TOKEN", "").strip()
if existing_url: if existing_secret: write_env(existing_url, existing_secret) print(f"βοΈ Using configured Cloudflare proxy: {existing_url}") return 0
if not api_token: return 0
account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip() try: if not account_id: accounts = cf_request("GET", "/accounts", api_token) if not accounts: raise RuntimeError("No Cloudflare account available for this token.") account_id = accounts[0]["id"]
subdomain_info = cf_request( "GET", f"/accounts/{account_id}/workers/subdomain", api_token, ) subdomain = (subdomain_info or {}).get("subdomain", "").strip() if not subdomain: raise RuntimeError( "Cloudflare Workers subdomain is not configured. Enable workers.dev in your Cloudflare account first." )
worker_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)
cf_request( "PUT", f"/accounts/{account_id}/workers/scripts/{worker_name}", api_token, body=worker_source.encode("utf-8"), content_type="application/javascript", )
proxy_url = f"https://{worker_name}.{subdomain}.workers.dev" write_env(proxy_url, proxy_secret) print(f"βοΈ Cloudflare proxy ready: {proxy_url}") return 0 except urllib.error.HTTPError as error: detail = error.read().decode("utf-8", errors="replace") print(f"βοΈ Cloudflare proxy setup failed: HTTP {error.code} {detail}") return 1 except Exception as error: print(f"βοΈ Cloudflare proxy setup failed: {error}") return 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140/** * Cloudflare Proxy: Transparent Fix for Blocked Domains * * Patches https.request/http.request to redirect traffic for blocked hosts * through a Cloudflare Worker proxy. */"use strict";
const https = require("https");const http = require("http");
let PROXY_URL = process.env.CLOUDFLARE_PROXY_URL;if ( PROXY_URL && !PROXY_URL.startsWith("http://") && !PROXY_URL.startsWith("https://")) { PROXY_URL = `https://${PROXY_URL}`;}
const DEBUG = process.env.CLOUDFLARE_PROXY_DEBUG === "true";const PROXY_SHARED_SECRET = (process.env.CLOUDFLARE_PROXY_SECRET || "").trim();// Default to wildcard mode so Google, WhatsApp, Telegram, Discord, and other// outbound integrations all work unless they are HF-internal hosts.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 { const proxy = new URL(PROXY_URL); const originalHttpsRequest = https.request; const originalHttpRequest = http.request;
const patch = (original, originalModuleName) => { return function patchedRequest(options, callback) { let hostname = ""; let path = ""; let headers = {};
if (typeof options === "string") { const parsed = new URL(options); hostname = parsed.hostname; path = parsed.pathname + parsed.search; } else if (options instanceof URL) { hostname = options.hostname; path = options.pathname + options.search; headers = options.headers || {}; } else { hostname = options.hostname || (options.host ? String(options.host).split(":")[0] : ""); path = options.path || "/"; headers = options.headers || {}; }
const isInternal = hostname === "localhost" || hostname === "127.0.0.1" || hostname.endsWith(".hf.space") || hostname.endsWith(".huggingface.co") || hostname === "huggingface.co";
let shouldProxy = false; if (PROXY_ALL) { shouldProxy = !isInternal; } else { shouldProxy = BLOCKED_DOMAINS.some( (domain) => hostname === domain || hostname.endsWith(`.${domain}`), ); }
const alreadyProxied = options && typeof options === "object" && options._proxied; const hasTargetHeader = headers && (headers["x-target-host"] || headers["X-Target-Host"]);
if (shouldProxy && !alreadyProxied && !hasTargetHeader) { if (DEBUG) { console.log( `[cloudflare-proxy] Redirecting ${originalModuleName}://${hostname}${path} -> ${proxy.hostname}`, ); }
const newOptions = typeof options === "string" || options instanceof URL ? { protocol: "https:", path } : { ...options };
newOptions._proxied = true; newOptions.protocol = "https:"; newOptions.hostname = proxy.hostname; newOptions.port = proxy.port || 443; newOptions.servername = proxy.hostname; delete newOptions.host; delete newOptions.agent;
newOptions.headers = { ...(newOptions.headers || {}), host: proxy.host, "x-target-host": hostname, };
if (PROXY_SHARED_SECRET) { newOptions.headers["x-proxy-key"] = PROXY_SHARED_SECRET; }
return originalHttpsRequest.call(https, newOptions, callback); }
return original.call(this, options, callback); }; };
https.request = patch(originalHttpsRequest, "https"); http.request = patch(originalHttpRequest, "http");
if (DEBUG) { if (PROXY_ALL) { console.log( "[cloudflare-proxy] Transparent proxy active in wildcard mode", ); } else { console.log( `[cloudflare-proxy] Transparent proxy active for: ${BLOCKED_DOMAINS.join(", ")}`, ); } console.log(`[cloudflare-proxy] Target proxy: ${proxy.hostname}`); } } catch (error) { if (DEBUG) { console.error( `[cloudflare-proxy] Failed to initialize: ${error.message}`, ); } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889/** * Cloudflare Worker: Universal Outbound Proxy * * Manual setup: * 1. Create a Cloudflare Worker. * 2. Paste this file and deploy it. * 3. Use the worker URL as CLOUDFLARE_PROXY_URL. * * Optional worker vars: * - PROXY_SHARED_SECRET * - ALLOWED_TARGETS * - ALLOW_PROXY_ALL */
function normalizeList(raw) { return String(raw || "") .split(",") .map((value) => value.trim().toLowerCase()) .filter(Boolean);}
export default { async fetch(request, env) { const url = new URL(request.url); const targetHost = request.headers.get("x-target-host"); const proxySecret = ( env.PROXY_SHARED_SECRET || env.CLOUDFLARE_PROXY_SECRET || "" ).trim();
if (proxySecret) { const providedSecret = request.headers.get("x-proxy-key") || ""; if (providedSecret !== proxySecret) { return new Response("Unauthorized", { status: 401 }); } }
const allowProxyAll = String(env.ALLOW_PROXY_ALL || "true").toLowerCase() === "true"; const allowedTargets = normalizeList( env.ALLOWED_TARGETS || "api.telegram.org,web.whatsapp.com", );
const isAllowedHost = (hostname) => { const normalized = String(hostname || "") .trim() .toLowerCase(); if (!normalized) return false; if (allowProxyAll) return true; return allowedTargets.some( (domain) => normalized === domain || normalized.endsWith(`.${domain}`), ); };
let targetBase = ""; if (targetHost) { if (!isAllowedHost(targetHost)) { return new Response("Target host is not allowed.", { status: 403 }); } targetBase = `https://${targetHost}`; } else if (url.pathname.startsWith("/bot")) { targetBase = "https://api.telegram.org"; } else { return new Response("Invalid request.", { status: 400 }); }
const targetUrl = targetBase + url.pathname + url.search; const headers = new Headers(request.headers); headers.delete("cf-connecting-ip"); headers.delete("cf-ray"); headers.delete("cf-visitor"); headers.delete("x-real-ip"); headers.delete("x-target-host");
const proxiedRequest = new Request(targetUrl, { method: request.method, headers, body: request.body, redirect: "follow", });
try { return await fetch(proxiedRequest); } catch (error) { return new Response(`Proxy Error: ${error.message}`, { status: 502 }); } },};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108/** * DNS fix preload script for HF Spaces. * * Patches Node.js dns.lookup to: * 1. Try system DNS first * 2. Fall back to DNS-over-HTTPS (Cloudflare) if system DNS fails * (This is needed because HF Spaces intercepts/blocks some domains like * WhatsApp web or Telegram API via standard UDP DNS). * * Loaded via: NODE_OPTIONS="--require /opt/dns-fix.js" */"use strict";
const dns = require("dns");const https = require("https");
// In-memory cache for runtime DoH resolutionsconst runtimeCache = new Map(); // hostname -> { ip, expiry }
// DNS-over-HTTPS resolverfunction dohResolve(hostname, callback) { // Check runtime cache const cached = runtimeCache.get(hostname); if (cached && cached.expiry > Date.now()) { return callback(null, cached.ip); }
const url = `https://1.1.1.1/dns-query?name=${encodeURIComponent(hostname)}&type=A`; const req = https.get( url, { headers: { Accept: "application/dns-json" }, timeout: 15000 }, (res) => { let body = ""; res.on("data", (c) => (body += c)); res.on("end", () => { try { const data = JSON.parse(body); const aRecords = (data.Answer || []).filter((a) => a.type === 1); if (aRecords.length === 0) { return callback(new Error(`DoH: no A record for ${hostname}`)); } const ip = aRecords[0].data; const ttl = Math.max((aRecords[0].TTL || 300) * 1000, 60000); runtimeCache.set(hostname, { ip, expiry: Date.now() + ttl }); callback(null, ip); } catch (e) { callback(new Error(`DoH parse error: ${e.message}`)); } }); } ); req.on("error", (e) => callback(new Error(`DoH request failed: ${e.message}`))); req.on("timeout", () => { req.destroy(); callback(new Error("DoH request timed out")); });}
// Monkey-patch dns.lookupconst origLookup = dns.lookup;
dns.lookup = function patchedLookup(hostname, options, callback) { // Normalize arguments (options is optional, can be number or object) if (typeof options === "function") { callback = options; options = {}; } if (typeof options === "number") { options = { family: options }; } options = options || {};
// Skip patching for localhost, IPs, and internal domains if ( !hostname || hostname === "localhost" || hostname === "0.0.0.0" || hostname === "127.0.0.1" || hostname === "::1" || /^\d+\.\d+\.\d+\.\d+$/.test(hostname) || /^::/.test(hostname) ) { return origLookup.call(dns, hostname, options, callback); }
// 1) Try system DNS first origLookup.call(dns, hostname, options, (err, address, family) => { if (!err && address) { return callback(null, address, family); }
// 2) System DNS failed with ENOTFOUND or EAI_AGAIN β fall back to DoH if (err && (err.code === "ENOTFOUND" || err.code === "EAI_AGAIN")) { dohResolve(hostname, (dohErr, ip) => { if (dohErr || !ip) { return callback(err); // Return original error } if (options.all) { return callback(null, [{ address: ip, family: 4 }]); } callback(null, ip, 4); }); } else { // Other DNS errors β pass through callback(err, address, family); } });};17 unmodified lines18192021222324251 unmodified line2728293031323334120 unmodified lines155156157158159160171 unmodified lines33233333433533633733833934034134234348 unmodified lines39239339439539639717 unmodified linesOPENCLAW_CONSOLE_LOG_LEVEL="${OPENCLAW_CONSOLE_LOG_LEVEL:-warn}"OPENCLAW_FILE_LOG_LEVEL="${OPENCLAW_FILE_LOG_LEVEL:-info}"OPENCLAW_CONSOLE_LOG_STYLE="${OPENCLAW_CONSOLE_LOG_STYLE:-compact}"TELEGRAM_NATIVE_COMMANDS="${TELEGRAM_NATIVE_COMMANDS:-}"TELEGRAM_AUTO_SELECT_FAMILY="${TELEGRAM_AUTO_SELECT_FAMILY:-false}"BROWSER_PLUGIN_MODE="${BROWSER_PLUGIN_MODE:-disabled}"# HF Spaces does not benefit from Bonjour discovery, and the retries add noise.export OPENCLAW_DISABLE_BONJOUR="${OPENCLAW_DISABLE_BONJOUR:-1}"1 unmodified lineOPENCLAW_CONSOLE_LOG_LEVEL="${OPENCLAW_CONSOLE_LOG_LEVEL:-info}"OPENCLAW_FILE_LOG_LEVEL="${OPENCLAW_FILE_LOG_LEVEL:-info}"OPENCLAW_CONSOLE_LOG_STYLE="${OPENCLAW_CONSOLE_LOG_STYLE:-pretty}"TELEGRAM_NATIVE_COMMANDS="${TELEGRAM_NATIVE_COMMANDS:-auto}"TELEGRAM_AUTO_SELECT_FAMILY="${TELEGRAM_AUTO_SELECT_FAMILY:-true}"BROWSER_PLUGIN_MODE="${BROWSER_PLUGIN_MODE:-auto}"fiecho ""120 unmodified linesecho "HF_TOKEN is not set. Running without dataset persistence."fi# ββ Build config ββCONFIG_JSON=$(cat <<'CONFIGEOF'{171 unmodified linesif [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenCONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.plugins.entries.telegram = {"enabled": true}')export TELEGRAM_BOT_TOKEN="$TELEGRAM_BOT_TOKEN"CONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".channels.telegram.enabled = true")CONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".channels.telegram.botToken = \"$TELEGRAM_BOT_TOKEN\"")CONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".channels.telegram.commands.native = \"$TELEGRAM_NATIVE_COMMANDS\"")CONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.channels.telegram.timeoutSeconds = 60')CONFIG_JSON=$(echo "$CONFIG_JSON" | jq ".channels.telegram.network.autoSelectFamily = ${TELEGRAM_AUTO_SELECT_FAMILY}")CONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.channels.telegram.retry = {"attempts": 5, "minDelayMs": 800, "maxDelayMs": 30000, "jitter": 0.2}')if [ -n "${TELEGRAM_USER_IDS:-}" ]; then# Convert comma-separated IDs to JSON array48 unmodified lineselseprintf " β %-40s β\n" "Backup: β not configured"fiif [ -n "${OPENCLAW_PASSWORD:-}" ]; thenprintf " β %-40s β\n" "Auth: π password"else17 unmodified lines1819202122231 unmodified line252627282930120 unmodified lines151152153154155156157158159160161162163164165171 unmodified lines33733833934034134234348 unmodified lines39239339439539639739839940017 unmodified linesOPENCLAW_CONSOLE_LOG_LEVEL="${OPENCLAW_CONSOLE_LOG_LEVEL:-warn}"OPENCLAW_FILE_LOG_LEVEL="${OPENCLAW_FILE_LOG_LEVEL:-info}"OPENCLAW_CONSOLE_LOG_STYLE="${OPENCLAW_CONSOLE_LOG_STYLE:-compact}"BROWSER_PLUGIN_MODE="${BROWSER_PLUGIN_MODE:-disabled}"# HF Spaces does not benefit from Bonjour discovery, and the retries add noise.export OPENCLAW_DISABLE_BONJOUR="${OPENCLAW_DISABLE_BONJOUR:-1}"1 unmodified lineOPENCLAW_CONSOLE_LOG_LEVEL="${OPENCLAW_CONSOLE_LOG_LEVEL:-info}"OPENCLAW_FILE_LOG_LEVEL="${OPENCLAW_FILE_LOG_LEVEL:-info}"OPENCLAW_CONSOLE_LOG_STYLE="${OPENCLAW_CONSOLE_LOG_STYLE:-pretty}"BROWSER_PLUGIN_MODE="${BROWSER_PLUGIN_MODE:-auto}"fiecho ""120 unmodified linesecho "HF_TOKEN is not set. Running without dataset persistence."fiCF_PROXY_ENV_FILE="/tmp/huggingclaw-cloudflare-proxy.env"if [ -n "${CLOUDFLARE_API_TOKEN:-}" ] || [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; thenecho "βοΈ Preparing Cloudflare outbound proxy..."python3 /home/node/app/cloudflare-proxy-setup.py || trueif [ -f "$CF_PROXY_ENV_FILE" ]; then. "$CF_PROXY_ENV_FILE"fifi# ββ Build config ββCONFIG_JSON=$(cat <<'CONFIGEOF'{171 unmodified linesif [ -n "${TELEGRAM_BOT_TOKEN:-}" ]; thenCONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.plugins.entries.telegram = {"enabled": true}')export TELEGRAM_BOT_TOKEN="$TELEGRAM_BOT_TOKEN"CONFIG_JSON=$(echo "$CONFIG_JSON" | jq '.channels.telegram.enabled = true')if [ -n "${TELEGRAM_USER_IDS:-}" ]; then# Convert comma-separated IDs to JSON array48 unmodified lineselseprintf " β %-40s β\n" "Backup: β not configured"fiif [ -n "${CLOUDFLARE_PROXY_URL:-}" ]; thenprintf " β %-40s β\n" "Proxy: βοΈ ${CLOUDFLARE_PROXY_URL}"fiif [ -n "${OPENCLAW_PASSWORD:-}" ]; thenprintf " β %-40s β\n" "Auth: π password"else
CHANGELOG.md+3-1
Dockerfile+5-3
README.md+45-3
cloudflare-proxy-setup.pyAdded+202
cloudflare-proxy.jsAdded+140
cloudflare-worker.jsAdded+89
dns-fix.jsDeleted-108
start.sh+13-10