Spaces:
Paused
Paused
refactor: standardize Cloudflare proxy implementation, clean up configuration, and update documentation
Browse filesFiles changed (8)
- .env.example+1-1
- CHANGELOG.md+21-17
- CLOUDFLARE_PROXY_GUIDE.mdDeleted-44
- CODE_OF_CONDUCT.md+2
- README.md+11-8
- cloudflare-proxy.js+48-26
- cloudflare-worker.js+14-8
- dns-fix.js+6-2
41 unmodified lines4243444546474841 unmodified lines# Your Cloudflare Worker URL (e.g. h8n-proxy.somrat.workers.dev)CLOUDFLARE_PROXY_URL=# Comma-separated list of domains to proxy. Use "*" to proxy everything.OUTBOUND_PROXY_DOMAINS=api.telegram.org,discord.com,discordapp.com# BUILD-TIME VARIABLE (HF Spaces: add as Variable, not Secret)# -----------------------------------------------------------------------------41 unmodified lines4243444546474841 unmodified lines# Your Cloudflare Worker URL (e.g. h8n-proxy.somrat.workers.dev)CLOUDFLARE_PROXY_URL=# Comma-separated list of domains to proxy. Use "*" to proxy everything.CLOUDFLARE_PROXY_DOMAINS=api.telegram.org,discord.com,discordapp.com# BUILD-TIME VARIABLE (HF Spaces: add as Variable, not Secret)# -----------------------------------------------------------------------------
1 unmodified line2345678910111213141516171819202122232425262728291 unmodified lineAll notable changes to this project will be documented in this file.## [1.0.0] - 2026-04-22### 🎉 Initial Release#### Features- **Self-hosted n8n** — runs the latest n8n on HuggingFace Spaces Docker with zero external database requirements (uses SQLite)- **Persistent backup** — automatically backs up `/home/node/.n8n` (workflows, credentials, SQLite DB, encryption key) to a private HF Dataset via `huggingface_hub`- **Safe SQLite backup** — uses `sqlite3 .backup` for a consistent hot-copy of the live database- **Auto-restore on startup** — restores the full n8n state from the dataset before starting n8n- **Graceful shutdown** — runs a final backup pass on `SIGTERM` / `SIGINT` before exiting- **Health endpoint** — `/health` on port 7861 returns sync status and service info- **Proxy server** — lightweight Node.js reverse proxy forwards HTTP and WebSocket traffic from port 7861 to n8n on port 5678- **UptimeRobot integration** — `setup-uptimerobot.sh` creates an external keep-alive monitor for the `/health` endpoint- **Basic auth** — n8n basic auth enabled by default; set `N8N_BASIC_AUTH_USER` and `N8N_BASIC_AUTH_PASSWORD` to secure your instance- **Timezone support** — set `GENERIC_TIMEZONE` for schedule trigger accuracy- **Optional n8n version pinning** — pass `N8N_VERSION` as a HF Space Variable to pin a specific n8n release#### Architecture- `Dockerfile` — builds on `node:22-slim`, installs n8n and Python sync dependencies- `start.sh` — validates config, restores backup, starts sync loop, proxy, and n8n- `n8n-sync.py` — manages backup/restore using `huggingface_hub`- `health-server.js` — lightweight HTTP + WebSocket reverse proxy with `/health` and `/status` endpoints- `setup-uptimerobot.sh` — optional one-shot script to create an UptimeRobot monitor1 unmodified line234567891011121314151617181920212223242526272829303132331 unmodified lineAll notable changes to this project will be documented in this file.## [1.0.0] - 2026-04-24### 🎉 Initial Release#### Features- **Self-hosted n8n** — Runs the latest n8n on HuggingFace Spaces Docker using SQLite (no external DB required).- **Persistent Backup** — Automatically syncs the entire n8n workspace (workflows, credentials, database) to a private HF Dataset.- **Cloudflare Transparent Proxy** — Built-in fix to bypass platform network blocks for services like Telegram and Discord.- **DNS-over-HTTPS (DoH)** — Automatic fallback resolution for domains blocked at the DNS level (e.g., WhatsApp, Telegram).- **Premium Dashboard** — Beautiful web interface at `/` for real-time uptime monitoring and sync health tracking.- **Built-in Keep-Alive** — Integrated UptimeRobot setup tool directly from the dashboard to prevent free HF Spaces from sleeping.- **Native Security** — Optimized for n8n v2 native user management with hardened file permissions (`umask 0077`).- **Safe Persistence** — Uses atomic SQLite backups to ensure data integrity during periodic syncs.- **Auto-Restore** — Seamlessly pulls the latest state from your HF Dataset on every startup.- **Graceful Shutdown** — Ensures a final backup pass is completed on `SIGTERM` / `SIGINT` before the container exits.#### Architecture- `Dockerfile` — Optimized build on `node:22-slim` including all n8n and sync dependencies.- `start.sh` — Orchestrates startup, validates environment, and manages service lifecycle.- `health-server.js` — High-performance namespace proxy and dashboard server.- `cloudflare-proxy.js` — Transparently intercepts and routes blocked traffic via Cloudflare Workers.- `dns-fix.js` — Monkey-patches Node.js DNS for reliable DoH fallback.- `n8n-sync.py` — Robust background sync engine using the `huggingface_hub` API.- `start.sh` — Configures environment, restores backup, and launches background sync loop.---*Made with ❤️ by [@somratpro](https://github.com/somratpro)*
1234567891011121314151617181920212223242526272829303132333435363738394041424344# 🌐 Cloudflare Proxy Guide
Hugging Face Spaces officially blocks outgoing connections to specific services like **Telegram**, **WhatsApp**, and **Discord** on the free tier.
Hugging8n includes a built-in **Transparent Cloudflare Proxy** that allows you to bypass these restrictions using a single Cloudflare Worker.
---
## 🚀 Setup in 2 Minutes
### Step 1: Deploy your Cloudflare Worker
1. Log in to [dash.cloudflare.com](https://dash.cloudflare.com/).2. Go to **Workers & Pages** -> **Create Worker**.3. Name it (e.g., `h8n-proxy`).4. Paste the code from [cloudflare-worker.js](./cloudflare-worker.js) into the editor.5. Click **Deploy**.6. Copy your Worker URL (e.g., `h8n-proxy.yourname.workers.dev`).
### Step 2: Configure Hugging8n
Go to your Space **Settings** -> **Variables** (or Secrets) and add:
1. **`CLOUDFLARE_PROXY_URL`** (Required): - Value: `h8n-proxy.yourname.workers.dev` (You can omit the `https://`).
2. **`CLOUDFLARE_PROXY_DOMAINS`** (Optional): - **Default**: Proxies Telegram and Discord only. - **Wildcard Mode**: Set this to `*` to proxy **every single request** n8n makes to the outside world.
### Step 3: Restart Space
Hugging8n will now automatically intercept all requests to the blocked domains and route them through your worker. **You do not need to change any URLs inside your n8n workflows.**
---
## 🛠️ How it Works
1. **DNS Fix**: Hugging8n uses a built-in DNS-over-HTTPS (DoH) resolver to get the real IPs of blocked domains, bypassing HF's sinkholed DNS.2. **SNI Bypass**: The transparent proxy changes the "label" (SNI) of your traffic to match your Cloudflare domain. Hugging Face sees you connecting to Cloudflare (allowed) instead of Telegram/Discord (blocked).3. **Universal Routing**: Using the `x-target-host` header, one single worker can handle multiple different services dynamically.
---*If you upgrade to a paid Space, these firewalls are removed and you no longer need this proxy.*6 unmodified lines7891011121314151617186 unmodified lines## Our Standards**Positive behavior includes:**- Using welcoming and inclusive language- Being respectful of differing viewpoints- Gracefully accepting constructive criticism- Focusing on what is best for the community**Unacceptable behavior includes:**- Trolling, insulting, or derogatory comments- Public or private harassment- Publishing others' private information without permission6 unmodified lines78910111213141516171819206 unmodified lines## Our Standards**Positive behavior includes:**- Using welcoming and inclusive language- Being respectful of differing viewpoints- Gracefully accepting constructive criticism- Focusing on what is best for the community**Unacceptable behavior includes:**- Trolling, insulting, or derogatory comments- Public or private harassment- Publishing others' private information without permission
57 unmodified lines58596061626364656667681 unmodified line7071727374753 unmodified lines7980818283848586878889909192939435 unmodified lines13013113213313413557 unmodified linesNavigate to your new Space's **Settings**, scroll down to **Variables and secrets**, and add:- `HF_TOKEN` – Your HuggingFace token with **Write** access (to enable automatic backup).- `CLOUDFLARE_PROXY_URL` – *(Optional but Recommended)* Your Cloudflare Worker URL to bypass platform blocks.### Step 3: Deploy & InitializeThe Space will build and start automatically. Once ready:1. Visit the Space URL.2. Click **Open n8n Editor**.3. Create your **Owner account** (this is your primary login).1 unmodified line### Step 4: Monitor & ManageUse the built-in dashboard at the root URL (`/`) to track:- **Uptime:** Real-time uptime monitoring.- **Sync Status:** Visual indicators for your workflow backups.- **Keep-Alive:** Setup tool for external monitors.3 unmodified linesHugging Face Free Tier blocks outgoing connections to some services (Telegram, Discord, etc.). Hugging8n includes a transparent proxy system to bypass this.1. Go to [Cloudflare Workers](https://dash.cloudflare.com/?to=/:account/workers-and-pages).2. Create a new Worker and paste the code from [cloudflare-worker.js](./cloudflare-worker.js).3. Deploy and copy the Worker URL.4. Add this URL as the `CLOUDFLARE_PROXY_URL` secret in your Space settings.> [!TIP]> Check the [Cloudflare Proxy Guide](./CLOUDFLARE_PROXY_GUIDE.md) for detailed step-by-step instructions.## 💾 Persistent BackupHugging8n automatically creates a private dataset named `hugging8n-backup` in your Hugging Face account.- **Restore:** On startup, it pulls the latest state from your dataset.- **Sync:** Periodically (every 3 minutes by default), it pushes updates to the dataset.35 unmodified lines```**With Docker:**```bashdocker build -t hugging8n .docker run -p 7861:7861 --env-file .env hugging8n57 unmodified lines5859606162636465666768691 unmodified line717273747576773 unmodified lines8182838485868788899091929394959635 unmodified lines13213313413513613713857 unmodified linesNavigate to your new Space's **Settings**, scroll down to **Variables and secrets**, and add:- `HF_TOKEN` – Your HuggingFace token with **Write** access (to enable automatic backup).- `CLOUDFLARE_PROXY_URL` – *(Optional but Recommended)* Your Cloudflare Worker URL to bypass platform blocks. check [Setup Guide](#-cloudflare-proxy-setup).### Step 3: Deploy & InitializeThe Space will build and start automatically. Once ready:1. Visit the Space URL.2. Click **Open n8n Editor**.3. Create your **Owner account** (this is your primary login).1 unmodified line### Step 4: Monitor & ManageUse the built-in dashboard at the root URL (`/`) to track:- **Uptime:** Real-time uptime monitoring.- **Sync Status:** Visual indicators for your workflow backups.- **Keep-Alive:** Setup tool for external monitors.3 unmodified linesHugging Face Free Tier blocks outgoing connections to some services (Telegram, Discord, etc.). Hugging8n includes a transparent proxy system to bypass this.1. Go to [Cloudflare Workers](https://dash.cloudflare.com/?to=/:account/workers-and-pages).2. Create a new Worker using "Start with Hello World!" template3. choose worker name (e.g. h8n-proxy) and deploy.4. Click on "Edit Code" button, paste the code from [cloudflare-worker.js](./cloudflare-worker.js).5. Click on "Deploy" button.6. Copy the Worker URL (e.g., `https://h8n-proxy.yourname.workers.dev`).7. Add this URL as the `CLOUDFLARE_PROXY_URL` secret in your Hugging8n Space settings.## 💾 Persistent BackupHugging8n automatically creates a private dataset named `hugging8n-backup` in your Hugging Face account.- **Restore:** On startup, it pulls the latest state from your dataset.- **Sync:** Periodically (every 3 minutes by default), it pushes updates to the dataset.35 unmodified lines```**With Docker:**```bashdocker build -t hugging8n .docker run -p 7861:7861 --env-file .env hugging8n
1234562 unmodified lines910111213141516171819202122232418 unmodified lines43444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959 unmodified lines105106107108109110111112113114115116117/*** Cloudflare Proxy: Transparent Fix for Blocked Domains** Patches https.request to redirect traffic for Telegram/Discord* through a Cloudflare Worker proxy.*/2 unmodified linesconst https = require("https");const http = require("http");let PROXY_URL = process.env.CLOUDFLARE_PROXY_URL || process.env.OUTBOUND_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" || process.env.OUTBOUND_PROXY_DEBUG === "true";// Allow user to define what to proxy. Use "*" to proxy everything except internal HF traffic.const PROXY_DOMAINS = process.env.CLOUDFLARE_PROXY_DOMAINS || process.env.OUTBOUND_PROXY_DOMAINS || "api.telegram.org,discord.com,discordapp.com,gateway.discord.gg,status.discord.com";const BLOCKED_DOMAINS = PROXY_DOMAINS.split(",").map(d => d.trim());const PROXY_ALL = PROXY_DOMAINS === "*";if (PROXY_URL) {18 unmodified linespath = options.pathname + options.search;headers = options.headers || {};} else {hostname = options.hostname || (options.host ? options.host.split(":")[0] : "");path = options.path || "/";headers = options.headers || {};}// 2. Check if we should intercept (and prevent recursion)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._proxied || (headers && headers["x-target-host"]);if (shouldProxy && !alreadyProxied) {if (DEBUG) console.log(`[cloudflare-proxy] Redirecting ${hostname}${path} -> ${proxy.hostname}`);// 3. Create fresh options for the proxied requestconst newOptions = (typeof options === "string" || options instanceof URL)? { protocol: "https:", path: path }: { ...options };// Ensure it's an object we can modifyif (typeof newOptions !== "object") return original.apply(this, arguments);newOptions._proxied = true;newOptions.protocol = "https:";newOptions.hostname = proxy.hostname;newOptions.port = proxy.port || 443;// CRITICAL: Force fresh TLS handshake for the new domainnewOptions.servername = proxy.hostname;delete newOptions.host; // Prefer hostnamedelete newOptions.agent; // Force a new agent to prevent connection reuse issues// Merge and update headersnewOptions.headers = {...(newOptions.headers || {}),"host": proxy.host,"x-target-host": hostname};// Always use HTTPS for the proxy connection9 unmodified linesif (DEBUG) {if (PROXY_ALL) {console.log(`[cloudflare-proxy] Transparent proxy active in WILDCARD mode (Proxying ALL except HF internal)`);} else {console.log(`[cloudflare-proxy] Transparent proxy active for: ${BLOCKED_DOMAINS.join(", ")}`);}console.log(`[cloudflare-proxy] Target proxy: ${proxy.hostname}`);}} catch (e) {if (DEBUG) console.error(`[cloudflare-proxy] Failed to initialize: ${e.message}`);}}1234562 unmodified lines910111213141516171819202122232425262728293018 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111129 unmodified lines122123124125126127128129130131132133134135136137138139/*** Cloudflare Proxy: Transparent Fix for Blocked Domains** Patches https.request to redirect traffic for Telegram/Discord* through a Cloudflare Worker proxy.*/2 unmodified linesconst 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";// Allow user to define what to proxy. Use "*" to proxy everything except internal HF traffic.const PROXY_DOMAINS =process.env.CLOUDFLARE_PROXY_DOMAINS ||"api.telegram.org,discord.com,discordapp.com,gateway.discord.gg,status.discord.com";const BLOCKED_DOMAINS = PROXY_DOMAINS.split(",").map((d) => d.trim());const PROXY_ALL = PROXY_DOMAINS === "*";if (PROXY_URL) {18 unmodified linespath = options.pathname + options.search;headers = options.headers || {};} else {hostname =options.hostname ||(options.host ? options.host.split(":")[0] : "");path = options.path || "/";headers = options.headers || {};}// 2. Check if we should intercept (and prevent recursion)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._proxied || (headers && headers["x-target-host"]);if (shouldProxy && !alreadyProxied) {if (DEBUG)console.log(`[cloudflare-proxy] Redirecting ${hostname}${path} -> ${proxy.hostname}`,);// 3. Create fresh options for the proxied requestconst newOptions =typeof options === "string" || options instanceof URL? { protocol: "https:", path: path }: { ...options };// Ensure it's an object we can modifyif (typeof newOptions !== "object")return original.apply(this, arguments);newOptions._proxied = true;newOptions.protocol = "https:";newOptions.hostname = proxy.hostname;newOptions.port = proxy.port || 443;// CRITICAL: Force fresh TLS handshake for the new domainnewOptions.servername = proxy.hostname;delete newOptions.host; // Prefer hostnamedelete newOptions.agent; // Force a new agent to prevent connection reuse issues// Merge and update headersnewOptions.headers = {...(newOptions.headers || {}),host: proxy.host,"x-target-host": hostname,};// Always use HTTPS for the proxy connection9 unmodified linesif (DEBUG) {if (PROXY_ALL) {console.log(`[cloudflare-proxy] Transparent proxy active in WILDCARD mode (Proxying ALL except HF internal)`,);} else {console.log(`[cloudflare-proxy] Transparent proxy active for: ${BLOCKED_DOMAINS.join(", ")}`,);}console.log(`[cloudflare-proxy] Target proxy: ${proxy.hostname}`);}} catch (e) {if (DEBUG)console.error(`[cloudflare-proxy] Failed to initialize: ${e.message}`);}}
12345678910111 unmodified line131415161718193 unmodified lines23242526272829303132333435363711 unmodified lines49505152535455565758/*** Cloudflare Worker: Universal Outbound Proxy** Deployment:* 1. Go to dash.cloudflare.com -> Workers & Pages -> Create Worker.* 2. Paste this code and deploy.* 3. Use your worker URL (e.g., https://my-proxy.workers.dev) as CLOUDFLARE_PROXY_URL.** This worker reads the 'x-target-host' header to determine where to forward the request.*/1 unmodified lineasync fetch(request, env, ctx) {const url = new URL(request.url);const targetHost = request.headers.get("x-target-host");let targetBase = "";if (targetHost) {3 unmodified lines// Fallback: Guess based on path (legacy support)if (url.pathname.startsWith("/bot")) {targetBase = "https://api.telegram.org";} else if (url.pathname.startsWith("/api/webhooks") || url.pathname.startsWith("/api/v")) {targetBase = "https://discord.com";} else {return new Response("Invalid request. 'x-target-host' header missing and target not recognized via path.", { status: 400 });}}const targetUrl = targetBase + url.pathname + url.search;// Copy headers and remove internal/Cloudflare-specific onesconst headers = new Headers(request.headers);headers.delete("cf-connecting-ip");11 unmodified linestry {const response = await fetch(modifiedRequest);// Special handling for Discord/Telegram which might return 403 on some CF IPs// If needed, you can add retry logic here.return response;} catch (e) {return new Response(`Proxy Error: ${e.message}`, { status: 502 });12345678910111 unmodified line131415161718193 unmodified lines23242526272829303132333435363738394041424311 unmodified lines55565758596061626364/*** Cloudflare Worker: Universal Outbound Proxy** Deployment:* 1. Go to dash.cloudflare.com -> Workers & Pages -> Create Worker.* 2. Paste this code and deploy.* 3. Use your worker URL (e.g., https://my-proxy.workers.dev) as CLOUDFLARE_PROXY_URL.** This worker reads the 'x-target-host' header to determine where to forward the request.*/1 unmodified lineasync fetch(request, env, ctx) {const url = new URL(request.url);const targetHost = request.headers.get("x-target-host");let targetBase = "";if (targetHost) {3 unmodified lines// Fallback: Guess based on path (legacy support)if (url.pathname.startsWith("/bot")) {targetBase = "https://api.telegram.org";} else if (url.pathname.startsWith("/api/webhooks") ||url.pathname.startsWith("/api/v")) {targetBase = "https://discord.com";} else {return new Response("Invalid request. 'x-target-host' header missing and target not recognized via path.",{ status: 400 },);}}const targetUrl = targetBase + url.pathname + url.search;// Copy headers and remove internal/Cloudflare-specific onesconst headers = new Headers(request.headers);headers.delete("cf-connecting-ip");11 unmodified linestry {const response = await fetch(modifiedRequest);// Special handling for Discord/Telegram which might return 403 on some CF IPs// If needed, you can add retry logic here.return response;} catch (e) {return new Response(`Proxy Error: ${e.message}`, { status: 502 });
41 unmodified lines424344454647489 unmodified lines5859606162636441 unmodified linesres.on("end", () => {try {if (res.statusCode !== 200) {return callback(new Error(`DoH: server returned status ${res.statusCode}`));}const data = JSON.parse(body);const aRecords = (data.Answer || []).filter((a) => a.type === 1);9 unmodified lines}});});req.on("error", (e) => callback(new Error(`DoH request failed: ${e.message}`)));req.on("timeout", () => {req.destroy();callback(new Error("DoH request timed out"));41 unmodified lines4243444546474849509 unmodified lines60616263646566676841 unmodified linesres.on("end", () => {try {if (res.statusCode !== 200) {return callback(new Error(`DoH: server returned status ${res.statusCode}`),);}const data = JSON.parse(body);const aRecords = (data.Answer || []).filter((a) => a.type === 1);9 unmodified lines}});});req.on("error", (e) =>callback(new Error(`DoH request failed: ${e.message}`)),);req.on("timeout", () => {req.destroy();callback(new Error("DoH request timed out"));
.env.example+1-1
CHANGELOG.md+21-17
CLOUDFLARE_PROXY_GUIDE.mdDeleted-44
CODE_OF_CONDUCT.md+2
README.md+11-8
cloudflare-proxy.js+48-26
cloudflare-worker.js+14-8
dns-fix.js+6-2