Spaces:
Paused
Paused
feat: enhance Cloudflare proxy with shared secret support, add uptime monitoring features, and improve startup timeout handling
Browse filesFiles changed (8)
- .env.example+11
- README.md+14
- SECURITY.md+3-1
- cloudflare-proxy.js+5
- cloudflare-worker.js+37
- health-server.js+97-4
- n8n-sync.py+42-7
- start.sh+26-1
40 unmodified lines4142434445464748495051525354555657585940 unmodified lines# -----------------------------------------------------------------------------# Your Cloudflare Worker URL (e.g. h8n-proxy.somrat.workers.dev)CLOUDFLARE_PROXY_URL=# Optional shared secret that should match Worker CLOUDFLARE_PROXY_SECRET# If unset, proxy still works but without app-to-worker auth# Generate with: openssl rand -hex 24CLOUDFLARE_PROXY_SECRET=# Comma-separated list of domains to proxy. Use "*" to proxy everything.CLOUDFLARE_PROXY_DOMAINS=api.telegram.org,discord.com,discordapp.com
# Dashboard helper hardeningUPTIMEROBOT_SETUP_ENABLED=trueUPTIMEROBOT_RATE_LIMIT_PER_MINUTE=5
# Max seconds to wait for n8n readiness at startupN8N_STARTUP_TIMEOUT=180# BUILD-TIME VARIABLE (HF Spaces: add as Variable, not Secret)# -----------------------------------------------------------------------------
58 unmodified lines5960616263646522 unmodified lines88899091929394959697989910010110227 unmodified lines13013113213313413513613713813914058 unmodified lines
- `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).- `CLOUDFLARE_PROXY_SECRET` – *(Optional, Security Recommended)* Shared secret used between Space and Worker to prevent proxy abuse.
### Step 3: Deploy & Initialize
22 unmodified lines5. 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.8. (Optional, Recommended) In Cloudflare Worker settings, add a secret binding named `CLOUDFLARE_PROXY_SECRET`.9. (Optional, Recommended) Add the same value in your Space secrets as `CLOUDFLARE_PROXY_SECRET`.
If you skip steps 8-9, proxying still works. The secret simply adds request authentication between your app and worker.
Optional Worker vars for tighter control:
- `ALLOWED_TARGETS` (comma-separated, defaults to Telegram/Discord hosts)- `ALLOW_PROXY_ALL` (`false` by default; set `true` only if you fully trust your setup)
## 💾 Persistent Backup
27 unmodified lines| `GENERIC_TIMEZONE` | `UTC` | Timezone for your n8n instance || `N8N_LOG_LEVEL` | `error` | Set to `info` or `debug` for more details || `CLOUDFLARE_PROXY_DOMAINS` | (default list) | Comma-separated domains to proxy (or `*` for all) || `CLOUDFLARE_PROXY_SECRET` | — | Optional shared secret for app-to-worker proxy authentication || `SPACE_HOST_OVERRIDE` | — | Override detected host for custom domains || `N8N_STARTUP_TIMEOUT` | `180` | Max seconds to wait for n8n readiness before fail-fast || `UPTIMEROBOT_SETUP_ENABLED` | `true` | Enable/disable dashboard helper endpoint || `UPTIMEROBOT_RATE_LIMIT_PER_MINUTE` | `5` | Per-IP rate limit for helper endpoint |
## 💻 Local Development
14 unmodified lines1516171818192021222324252614 unmodified linesWhen deploying Hugging8n:
- **Enable basic auth** — set `N8N_BASIC_AUTH_USER` and `N8N_BASIC_AUTH_PASSWORD` to protect your n8n instance from unauthorized access- **Use a strong password** — generate with `openssl rand -base64 24`- **Create a strong n8n owner password** during first-run setup- **Set your Space to Private** — prevents unauthorized access to your n8n instance from the web- **Keep your HF token scoped** — use fine-grained tokens with minimum permissions (read/write to your backup dataset only)- **Set a strong `N8N_ENCRYPTION_KEY`** — protects your stored credentials; if lost, credentials cannot be recovered- **Optionally set `CLOUDFLARE_PROXY_SECRET` in both Space and Worker** — recommended to prevent Worker URL abuse as an open proxy- **Keep secure cookies enabled on HTTPS** — default is secure in this project; only disable for local non-HTTPS testing- **Don't commit `.env` files** — the `.gitignore` already excludes them- **Review n8n credentials** — periodically audit credentials stored in n8n
18 unmodified lines1920212223242584 unmodified lines11011111211311411511611711811918 unmodified lines}
const DEBUG = process.env.CLOUDFLARE_PROXY_DEBUG === "true";const PROXY_SHARED_SECRET = (process.env.CLOUDFLARE_PROXY_SECRET || "").trim();
// Allow user to define what to proxy. Use "*" to proxy everything except internal HF traffic.const PROXY_DOMAINS =84 unmodified lines "x-target-host": hostname, };
if (PROXY_SHARED_SECRET) { newOptions.headers["x-proxy-key"] = PROXY_SHARED_SECRET; }
// Always use HTTPS for the proxy connection return originalHttpsRequest.call(https, newOptions, callback); }12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596012 unmodified lines async fetch(request, env, ctx) { const url = new URL(request.url); const targetHost = request.headers.get("x-target-host"); const proxySecret = ( env.CLOUDFLARE_PROXY_SECRET || env.PROXY_SHARED_SECRET || "" ).trim();
// Secret check is optional: when unset, requests are allowed without x-proxy-key. if (proxySecret) { const providedSecret = request.headers.get("x-proxy-key") || ""; if (providedSecret !== proxySecret) { return new Response("Unauthorized", { status: 401 }); } }
const allowedTargetsRaw = ( env.ALLOWED_TARGETS || "api.telegram.org,discord.com,discordapp.com,gateway.discord.gg,status.discord.com" ).trim(); const allowProxyAll = String(env.ALLOW_PROXY_ALL || "false").toLowerCase() === "true"; const allowedTargets = allowedTargetsRaw .split(",") .map((value) => value.trim().toLowerCase()) .filter(Boolean);
const isAllowedHost = (hostname) => { if (!hostname) return false; 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) { // Use the host provided in the header (preferred) if (!isAllowedHost(targetHost)) { return new Response("Target host is not allowed.", { status: 403 }); } targetBase = `https://${targetHost}`; } else { // Fallback: Guess based on path (legacy support)7 unmodified lines8910111213141516171819202116 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697487 unmodified lines58558658758858959059159259332 unmodified lines6266276285645656296306316326336346356366376386396406416426436446456466476481 unmodified line6506516526536546556566576586596606616626636646656666676686696706715816726735836746756766776786797 unmodified linesconst TARGET_HOST = "127.0.0.1";const SYNC_STATUS_FILE = "/tmp/hugging8n-sync-status.json";const startTime = Date.now();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 uptimerobotRateMap = new Map();
function parseRequestUrl(url) { try {16 unmodified lines };}
function probeN8nHealth(timeoutMs = 1500) { return new Promise((resolve) => { const request = http.get( { hostname: TARGET_HOST, port: TARGET_PORT, path: "/healthz", timeout: timeoutMs, }, (response) => { response.resume(); resolve(response.statusCode >= 200 && response.statusCode < 400); }, ); request.on("timeout", () => { request.destroy(); resolve(false); }); request.on("error", () => resolve(false)); });}
function getRequesterIp(req) { return ( req.headers["x-forwarded-for"]?.split(",")[0]?.trim() || req.socket.remoteAddress || "unknown" );}
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;}
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 renderDashboard(data) { const { status } = data.sync; const getBadge = (status) => {487 unmodified lines const cleanHost = String(host || "") .replace(/^https?:\/\//, "") .replace(/\/.*$/, ""); if (!cleanHost.endsWith(".hf.space")) { throw new Error("Uptime setup is only supported on .hf.space hosts."); } if (!cleanHost) throw new Error("Missing Space host."); const monitorUrl = `https://${cleanHost}/health`; const existing = await postUptimeRobot("/v2/getMonitors", {32 unmodified lines
// 1. Dashboard Routes if (pathname === "/health") { res.writeHead(200, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ status: "ok", ...getStatus() })); const n8nReady = await probeN8nHealth(); res.writeHead(n8nReady ? 200 : 503, { "Content-Type": "application/json" }); return res.end( JSON.stringify({ status: n8nReady ? "ok" : "degraded", n8nReady, ...getStatus(), }), ); } if (pathname === "/status") { const uptime = Math.floor((Date.now() - startTime) / 1000); const n8nReady = await probeN8nHealth(); return res.end( JSON.stringify({ uptime: `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`, n8nReady, sync: getStatus(), }), );1 unmodified line if (pathname === "/uptimerobot/setup" && req.method === "POST") { void (async () => { try { if (!UPTIMEROBOT_SETUP_ENABLED) { res.writeHead(403, { "Content-Type": "application/json" }); return res.end( JSON.stringify({ message: "Uptime setup is disabled." }), ); } if (isRateLimited(req)) { res.writeHead(429, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ message: "Too many requests." })); } if (!isAllowedUptimeSetupOrigin(req)) { res.writeHead(403, { "Content-Type": "application/json" }); return res.end( JSON.stringify({ message: "Invalid request origin." }), ); }
const body = await readRequestBody(req); const { apiKey } = JSON.parse(body || "{}"); if (!apiKey) { if (!isValidUptimeApiKey(apiKey)) { res.writeHead(400, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ message: "API key is required." })); return res.end( JSON.stringify({ message: "A valid API key is required." }), ); } const result = await createUptimeRobotMonitor(apiKey, req.headers.host); res.writeHead(200, { "Content-Type": "application/json" });35 unmodified lines363738393940414243444546474849505152535455565758596061626364656667116 unmodified lines1841851861621871881891901911921651931941951961971981992002012022032041712052062072089 unmodified lines2182192201872212222232245 unmodified lines23023123223323423523623720323823924024113 unmodified lines25525625722325825926026135 unmodified lines "message": message, "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), } tmp_path = STATUS_FILE.with_suffix(".tmp") STATUS_FILE.write_text(json.dumps(payload), encoding="utf-8") tmp_path.write_text(json.dumps(payload), encoding="utf-8") tmp_path.replace(STATUS_FILE)
def metadata_marker(root: Path) -> tuple[int, int, int]: if not root.exists(): return (0, 0, 0)
file_count = 0 total_size = 0 newest_mtime = 0 for path in root.rglob("*"): if not path.is_file(): continue rel = path.relative_to(root).as_posix() if rel.startswith(".cache/"): continue try: stat = path.stat() except OSError: continue file_count += 1 total_size += int(stat.st_size) newest_mtime = max(newest_mtime, int(stat.st_mtime_ns)) return (file_count, total_size, newest_mtime)
def dataset_repo_id() -> str:116 unmodified lines return False
def sync_once(last_fingerprint: str | None = None) -> str:def sync_once( last_fingerprint: str | None = None, last_marker: tuple[int, int, int] | None = None,) -> tuple[str, tuple[int, int, int]]: if not HF_TOKEN: write_status("disabled", "HF_TOKEN is not configured.") return last_fingerprint or "" return (last_fingerprint or "", last_marker or (0, 0, 0))
repo_id = ensure_repo_exists()
current_marker = metadata_marker(N8N_HOME) if last_marker is not None and current_marker == last_marker: write_status("synced", "No state changes detected.") return (last_fingerprint or "", current_marker)
current_fingerprint = fingerprint_dir(N8N_HOME) if last_fingerprint is not None and current_fingerprint == last_fingerprint: write_status("synced", "No state changes detected.") return last_fingerprint return (last_fingerprint, current_marker)
write_status("syncing", f"Uploading state to {repo_id}") snapshot_dir = create_snapshot_dir(N8N_HOME)9 unmodified lines finally: shutil.rmtree(snapshot_dir, ignore_errors=True) write_status("success", f"Uploaded state to {repo_id}") return current_fingerprint return (current_fingerprint, current_marker)
def handle_signal(_sig, _frame) -> None:5 unmodified lines signal.signal(signal.SIGINT, handle_signal)
last_fingerprint = fingerprint_dir(N8N_HOME) last_marker = metadata_marker(N8N_HOME) write_status("configured", f"Backup loop active with {INTERVAL}s interval.")
while not STOP_EVENT.is_set(): try: last_fingerprint = sync_once(last_fingerprint) last_fingerprint, last_marker = sync_once(last_fingerprint, last_marker) except Exception as exc: write_status("error", f"Sync failed: {exc}") print(f"Sync failed: {exc}", file=sys.stderr)13 unmodified lines if command == "restore": return 0 if restore() else 1 if command == "sync-once": sync_once(None) sync_once(None, None) return 0 if command == "loop": return loop()8 unmodified lines910111213141512 unmodified lines2829303031323334353637383940414221 unmodified lines6465666768697039 unmodified lines1101111121131141151161171181191201211221231241251261271281291301318 unmodified linesN8N_PORT="${N8N_PORT:-5678}"PUBLIC_PORT="${PUBLIC_PORT:-7861}"SYNC_INTERVAL="${SYNC_INTERVAL:-180}"N8N_STARTUP_TIMEOUT="${N8N_STARTUP_TIMEOUT:-180}"
mkdir -p "$N8N_HOME"
12 unmodified linesexport N8N_PROTOCOL="${N8N_PROTOCOL:-https}"export N8N_PROXY_HOPS="${N8N_PROXY_HOPS:-1}"export N8N_LISTEN_ADDRESS="${N8N_LISTEN_ADDRESS:-0.0.0.0}"export N8N_SECURE_COOKIE="${N8N_SECURE_COOKIE:-false}"if [ -z "${N8N_SECURE_COOKIE:-}" ]; then if [ "${N8N_PROTOCOL}" = "https" ]; then export N8N_SECURE_COOKIE="true" else export N8N_SECURE_COOKIE="false" fielse export N8N_SECURE_COOKIEfiexport N8N_DIAGNOSTICS_ENABLED="${N8N_DIAGNOSTICS_ENABLED:-false}"export N8N_PERSONALIZATION_ENABLED="${N8N_PERSONALIZATION_ENABLED:-false}"export N8N_USER_FOLDER="$N8N_HOME"21 unmodified linesecho "Public port : ${PUBLIC_PORT}"echo "Timezone : ${GENERIC_TIMEZONE}"echo "Sync every : ${SYNC_INTERVAL}s"echo "Startup wait: ${N8N_STARTUP_TIMEOUT}s"
if [ -n "${HF_TOKEN:-}" ]; then echo "Restoring persisted n8n state from HF Dataset..."39 unmodified lines
# Readiness probeecho "Waiting for n8n to be ready on port ${N8N_PORT}..."start_ts="$(date +%s)"until curl -sf "http://127.0.0.1:${N8N_PORT}/healthz" > /dev/null 2>&1; do now_ts="$(date +%s)" elapsed="$((now_ts - start_ts))" if [ "$elapsed" -ge "$N8N_STARTUP_TIMEOUT" ]; then echo "n8n did not become ready within ${N8N_STARTUP_TIMEOUT}s. Exiting." kill -TERM "$N8N_PID" 2>/dev/null || true wait "$N8N_PID" 2>/dev/null || true exit 1 fi
if ! kill -0 "$N8N_PID" 2>/dev/null; then echo "n8n process exited before readiness check passed. Exiting." exit 1 fi
sleep 1doneecho "n8n is ready!".env.example+11
README.md+14
SECURITY.md+3-1
cloudflare-proxy.js+5
cloudflare-worker.js+37
health-server.js+97-4
n8n-sync.py+42-7
start.sh+26-1