Spaces:
Paused
Paused
refactor: reconfigure n8n for root path hosting and overhaul dashboard UI components
Browse filesFiles changed (2)
- health-server.js+238-136
- start.sh+4-4
31 unmodified lines3233343536373810 unmodified lines4950515253545556575859604 unmodified lines656667686970717273747576777879808182838485868788899091929394959697982 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671 unmodified line1691701711721731741751 unmodified line17717817918018118218318418518618718814 unmodified lines2032042052062072082092102112122133 unmodified lines21721821922022122222362 unmodified lines2862872882892902912927 unmodified lines3003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653669 unmodified lines37637737837938031 unmodified lines}function renderDashboard(data) {const syncBadge = (status) => {let cls = "status-offline";if (status === "success" ||10 unmodified lines? `<div class="helper-summary"><strong>Private Space detected.</strong> External monitors cannot access private health URLs.</div>`: `<div id="uptimerobot-flow"><div class="helper-summary" id="uptimerobot-summary">Setup a free monitor to prevent this Space from sleeping.</div><button id="uptimerobot-toggle" class="helper-toggle">Set Up Monitor</button><div id="uptimerobot-shell" class="hidden" style="margin-top:12px"><input id="uptimerobot-key" class="helper-input" type="password" placeholder="UptimeRobot Main API Key"><button id="uptimerobot-btn" class="helper-button">Create Monitor</button></div></div>`;4 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Hugging8n Dashboard</title><link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap" rel="stylesheet"><style>:root { --bg: #0f172a; --card: rgba(30, 41, 59, 0.7); --accent: linear-gradient(135deg, #3b82f6, #8b5cf6); --text: #f8fafc; --text-dim: #94a3b8; --success: #10b981; --error: #ef4444; }* { box-sizing: border-box; margin: 0; padding: 0; }body { font-family: 'Outfit', sans-serif; background: var(--bg); color: var(--text); display: flex; justify-content: center; min-height: 100vh; padding: 40px 20px; background-image: radial-gradient(at 0% 0%, rgba(59, 130, 246, 0.15) 0px, transparent 50%), radial-gradient(at 100% 0%, rgba(139, 92, 246, 0.15) 0px, transparent 50%); }.dashboard { width: 100%; max-width: 600px; background: var(--card); backdrop-filter: blur(12px); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 24px; padding: 40px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5); }h1 { font-size: 2.2rem; margin-bottom: 8px; background: var(--accent); -webkit-background-clip: text; -webkit-text-fill-color: transparent; text-align: center; }.subtitle { color: var(--text-dim); text-align: center; font-size: 0.9rem; margin-bottom: 40px; text-transform: uppercase; letter-spacing: 1px; }.stats { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px; }.card { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.05); padding: 20px; border-radius: 16px; }.label { color: var(--text-dim); font-size: 0.75rem; text-transform: uppercase; margin-bottom: 8px; display: block; }.value { font-size: 1.1rem; font-weight: 600; }.btn { display: block; background: var(--accent); color: #fff; padding: 16px; border-radius: 16px; text-align: center; text-decoration: none; font-weight: 600; margin-top: 8px; transition: transform 0.2s; box-shadow: 0 10px 20px -5px rgba(59, 130, 246, 0.4); }.btn:hover { transform: scale(1.02); }.status-badge { display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; }.status-online { background: rgba(16, 185, 129, 0.1); color: var(--success); }.status-syncing { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }.status-offline { background: rgba(239, 68, 68, 0.1); color: var(--error); }.pulse { width: 8px; height: 8px; border-radius: 50%; background: currentColor; animation: pulse 2s infinite; }@keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); } 70% { box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); } 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); } }.helper-input { width: 100%; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #fff; padding: 12px; border-radius: 12px; margin-bottom: 12px; }.helper-button { background: var(--accent); color: #fff; border: 0; padding: 12px; border-radius: 12px; cursor: pointer; width: 100%; font-weight: 600; }.helper-toggle { background: rgba(255,255,255,0.05); color: #fff; border: 1px solid rgba(255,255,255,0.1); padding: 8px 16px; border-radius: 12px; cursor: pointer; font-size: 0.85rem; }.hidden { display: none; }.helper-summary { background: rgba(255,255,255,0.03); padding: 12px; border-radius: 12px; font-size: 0.85rem; color: var(--text-dim); margin-bottom: 12px; }.helper-result { margin-top: 12px; font-size: 0.85rem; padding: 10px; border-radius: 8px; display: none; }.helper-result.ok { display: block; background: rgba(16, 185, 129, 0.1); color: var(--success); }.helper-result.error { display: block; background: rgba(239, 68, 68, 0.1); color: var(--error); }</style></head><body>2 unmodified lines<p class="subtitle">Workflow Automation Space</p><div class="stats"><div class="card"><span class="label">Uptime</span><span class="value" id="uptime">${data.uptimeHuman}</span></div><div class="card"><span class="label">n8n Port</span><span class="value">${TARGET_PORT}</span></div></div><div class="card" style="margin-bottom:16px"><div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px"><span class="label" style="margin-bottom:0">Sync Status</span><div id="sync-badge">${syncBadge(data.sync.status)}</div></div><div style="font-size:0.85rem; color:var(--text-dim)">Last Activity: <span id="sync-time" style="color:var(--text)">${data.sync.timestamp}</span><div id="sync-msg" style="margin-top:4px">${data.sync.message}</div></div></div><a href="/app/" class="btn" target="_blank" rel="noopener noreferrer">Open n8n Editor</a><div class="card" style="margin-top:24px"><span class="label">Keep Alive</span>${keepAwakeHtml}<div id="uptimerobot-result" class="helper-result"></div></div></div><script>async function refresh() {try {const res = await fetch('/status' + window.location.search);const d = await res.json();document.getElementById('uptime').textContent = d.uptime;document.getElementById('sync-time').textContent = d.sync.timestamp;document.getElementById('sync-msg').textContent = d.sync.message;const s = d.sync.status;let cls = "status-offline";if (s === "success" || s === "configured" || s === "restored") cls = "status-online";if (s === "syncing" || s === "restoring") cls = "status-syncing";document.getElementById('sync-badge').innerHTML = '<div class="status-badge ' + cls + '">' + (cls === 'status-online' ? '<div class="pulse"></div>' : '') + s.toUpperCase() + '</div>';} catch (e) {}}setInterval(refresh, 5000);const toggle = document.getElementById('uptimerobot-toggle');if (toggle) {toggle.onclick = () => document.getElementById('uptimerobot-shell').classList.toggle('hidden');document.getElementById('uptimerobot-btn').onclick = async () => {const key = document.getElementById('uptimerobot-key').value;const res = document.getElementById('uptimerobot-result');if (!key) return;res.className = 'helper-result'; res.textContent = 'Creating...'; res.style.display = 'block';try {const r = await fetch('/uptimerobot/setup' + window.location.search, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ apiKey: key })});const data = await r.json();res.className = 'helper-result ' + (r.ok ? 'ok' : 'error');res.textContent = data.message;} catch (e) { res.className = 'helper-result error'; res.textContent = 'Connection failed'; }};}</script></body>1 unmodified line}async function resolveSpaceIsPrivate(req) {const params = new URLSearchParams(parseRequestUrl(req.url).search);const token = params.get("__sign");if (!token) return false;try {1 unmodified lineBuffer.from(token.split(".")[1], "base64").toString(),);const sub = payload.sub || "";const match = sub.match(/^\/spaces\/([^/]+)\/([^/]+)$/);if (!match) return false;return new Promise((resolve) => {https.get(`https://huggingface.co/api/spaces/${match[1]}/${match[2]}`,{ headers: { "User-Agent": "Hugging8n" } },(res) => {resolve(14 unmodified linesconst url = parseRequestUrl(req.url);const pathname = url.pathname;if (pathname === "/health") {res.writeHead(200, { "Content-Type": "application/json" });return res.end(JSON.stringify({ status: "ok", ...getStatus() }));}if (pathname === "/status") {const uptime = Math.floor((Date.now() - startTime) / 1000);return res.end(3 unmodified lines}),);}if (pathname === "/uptimerobot/setup" && req.method === "POST") {let body = "";req.on("data", (c) => (body += c));62 unmodified lines});return;}if (pathname === "/" || pathname === "/dashboard") {const uptime = Math.floor((Date.now() - startTime) / 1000);const isPrivate = await resolveSpaceIsPrivate(req);7 unmodified lines);}// 1. Redirect root /app to /app/ (trailing slash)if (pathname === APP_BASE) {res.writeHead(301, { Location: APP_BASE + "/" });return res.end();}// 2. Confine n8n to /app subpath// If it's not a dashboard path and doesn't start with /app, redirect to /app/if (!pathname.startsWith(APP_BASE + "/")) {res.writeHead(302, { Location: APP_BASE + "/" });return res.end();}// 3. Proxy to n8n (Pass full path as n8n is natively configured for /app/)const proxyPath = pathname;// Handle n8n's common 404 on root /app/ by redirecting to workflowsif (proxyPath === APP_BASE + "/" && req.method === "GET") {res.writeHead(302, { Location: APP_BASE + "/home/workflows" });return res.end();}const proxyHeaders = {...req.headers,host: `127.0.0.1:${TARGET_PORT}`,"x-forwarded-for": req.socket.remoteAddress,"x-forwarded-host": req.headers.host,"x-forwarded-proto": "https",};const proxyReq = http.request({hostname: TARGET_HOST,port: TARGET_PORT,path: proxyPath + url.search,method: req.method,headers: proxyHeaders,},(proxyRes) => {res.writeHead(proxyRes.statusCode, proxyRes.headers);proxyRes.pipe(res);},);proxyReq.on("error", () => {res.writeHead(503, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "starting",message: "n8n is initializing, please wait...",}),);});req.pipe(proxyReq);});server.on("upgrade", (req, socket, head) => {const url = parseRequestUrl(req.url);const proxyPath = url.pathname;const proxySocket = net.connect(TARGET_PORT, TARGET_HOST, () => {proxySocket.write(`${req.method} ${proxyPath}${url.search} HTTP/${req.httpVersion}\r\n`,9 unmodified lines});server.listen(PORT, "0.0.0.0", () =>console.log(`Dashboard/Proxy on ${PORT} -> n8n on ${TARGET_PORT}`),);31 unmodified lines323334353637383910 unmodified lines5051525354555657585960614 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042 unmodified lines2072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632641 unmodified line2662672682692702712722732742752762772781 unmodified line28028128228328428528628728828929029114 unmodified lines3063073083093103113123133143153163 unmodified lines32032132232332432562 unmodified lines3883893903913923937 unmodified lines4014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674689 unmodified lines47847948048148231 unmodified lines}function renderDashboard(data) {const { status } = data.sync;const getBadge = (status) => {let cls = "status-offline";if (status === "success" ||10 unmodified lines? `<div class="helper-summary"><strong>Private Space detected.</strong> External monitors cannot access private health URLs.</div>`: `<div id="uptimerobot-flow"><p class="helper-text">Setup a free monitor to prevent this Space from sleeping.</p><div class="input-group"><input type="password" id="ur-key" placeholder="UptimeRobot Main API Key"><button id="ur-btn" onclick="setupMonitor()">Set Up Monitor</button></div><p id="ur-status"></p></div>`;4 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Hugging8n Dashboard</title><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap" rel="stylesheet"><style>:root {--bg: #0f172a;--card: #1e293b;--accent: #6366f1;--text: #f8fafc;--text-muted: #94a3b8;--success: #22c55e;--warning: #f59e0b;--error: #ef4444;}* { box-sizing: border-box; margin: 0; padding: 0; }body {font-family: 'Outfit', sans-serif;background: var(--bg);color: var(--text);display: flex;align-items: center;justify-content: center;min-height: 100vh;padding: 20px;}.dashboard {background: var(--card);width: 100%;max-width: 500px;padding: 40px;border-radius: 24px;box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);text-align: center;border: 1px solid rgba(255,255,255,0.05);}h1 { font-size: 2.5rem; margin-bottom: 8px; letter-spacing: -1px; }.subtitle { color: var(--text-muted); margin-bottom: 32px; font-weight: 300; }.stats {display: grid;grid-template-columns: 1fr 1fr;gap: 16px;margin-bottom: 24px;}.stat-card {background: rgba(255,255,255,0.03);padding: 20px;border-radius: 16px;text-align: left;}.stat-label { font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; margin-bottom: 4px; }.stat-value { font-size: 1.25rem; font-weight: 600; }.sync-box {background: rgba(255,255,255,0.03);padding: 24px;border-radius: 16px;margin-bottom: 32px;text-align: left;position: relative;}.sync-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }.status-badge {padding: 4px 10px;border-radius: 20px;font-size: 0.7rem;font-weight: 600;display: flex;align-items: center;gap: 6px;}.status-online { background: rgba(34, 197, 94, 0.2); color: var(--success); }.status-syncing { background: rgba(245, 158, 11, 0.2); color: var(--warning); }.status-offline { background: rgba(239, 68, 68, 0.2); color: var(--error); }.pulse {width: 8px;height: 8px;background: currentColor;border-radius: 50%;animation: pulse 2s infinite;}@keyframes pulse {0% { transform: scale(0.95); opacity: 0.7; }70% { transform: scale(1.5); opacity: 0; }100% { transform: scale(0.95); opacity: 0; }}.btn-primary {display: block;width: 100%;padding: 18px;background: var(--accent);color: white;text-decoration: none;border-radius: 16px;font-weight: 600;font-size: 1.1rem;transition: all 0.2s;box-shadow: 0 10px 15px -3px rgba(99, 102, 241, 0.4);margin-bottom: 32px;}.btn-primary:hover { transform: translateY(-2px); box-shadow: 0 20px 25px -5px rgba(99, 102, 241, 0.4); }.keep-alive {border-top: 1px solid rgba(255,255,255,0.05);padding-top: 24px;text-align: left;}.keep-alive h3 { font-size: 0.85rem; color: var(--text-muted); margin-bottom: 12px; }.helper-text { font-size: 0.85rem; color: var(--text-muted); margin-bottom: 16px; }.input-group { display: flex; gap: 8px; }input {flex: 1;background: #0f172a;border: 1px solid rgba(255,255,255,0.1);padding: 12px;border-radius: 12px;color: white;font-family: inherit;}button#ur-btn {background: rgba(255,255,255,0.05);border: none;color: white;padding: 0 16px;border-radius: 12px;cursor: pointer;font-weight: 600;font-size: 0.85rem;}button#ur-btn:hover { background: rgba(255,255,255,0.1); }#ur-status { font-size: 0.8rem; margin-top: 8px; }</style></head><body>2 unmodified lines<p class="subtitle">Workflow Automation Space</p><div class="stats"><div class="stat-card"><div class="stat-label">Uptime</div><div class="stat-value">${data.uptimeHuman}</div></div><div class="stat-card"><div class="stat-label">n8n Port</div><div class="stat-value">${TARGET_PORT}</div></div></div><div class="sync-box"><div class="sync-header"><div class="stat-label">Sync Status</div>${getBadge(data.sync.status)}</div><div class="stat-value" style="font-size: 1rem; margin-bottom: 4px;">Last Activity: ${data.sync.timestamp.split('.')[0]}Z</div><div class="stat-label" style="text-transform: none;">${data.sync.message}</div></div><a href="/app/" target="_blank" class="btn-primary">Open n8n Editor</a><div class="keep-alive"><h3>Keep Alive</h3>${keepAwakeHtml}</div></div><script>async function setupMonitor() {const key = document.getElementById('ur-key').value;const btn = document.getElementById('ur-btn');const status = document.getElementById('ur-status');if (!key) return alert('Please enter an API key');btn.disabled = true;btn.innerText = 'Setting up...';try {const res = await fetch('/uptimerobot/setup', {method: 'POST',body: JSON.stringify({ apiKey: key })});const data = await res.json();status.innerText = data.message;status.style.color = res.ok ? '#22c55e' : '#ef4444';} catch (e) {status.innerText = 'Connection error.';status.style.color = '#ef4444';} finally {btn.disabled = false;btn.innerText = 'Set Up Monitor';}}</script></body>1 unmodified line}async function resolveSpaceIsPrivate(req) {const host = req.headers.host || "";const match = host.match(/^([^.]+)-([^.]+)\.hf\.space$/);if (!match) return false;const user = match[1];const space = match[2];const params = new URLSearchParams(req.url.split("?")[1] || "");const token = params.get("__sign");if (!token) return false;try {1 unmodified lineBuffer.from(token.split(".")[1], "base64").toString(),);const sub = payload.sub || "";const match_sub = sub.match(/^\/spaces\/([^/]+)\/([^/]+)$/);if (!match_sub) return false;return new Promise((resolve) => {https.get(`https://huggingface.co/api/spaces/${match_sub[1]}/${match_sub[2]}`,{ headers: { "User-Agent": "Hugging8n" } },(res) => {resolve(14 unmodified linesconst url = parseRequestUrl(req.url);const pathname = url.pathname;// 1. Dashboard Routesif (pathname === "/health") {res.writeHead(200, { "Content-Type": "application/json" });return res.end(JSON.stringify({ status: "ok", ...getStatus() }));}if (pathname === "/status") {const uptime = Math.floor((Date.now() - startTime) / 1000);return res.end(3 unmodified lines}),);}if (pathname === "/uptimerobot/setup" && req.method === "POST") {let body = "";req.on("data", (c) => (body += c));62 unmodified lines});return;}if (pathname === "/" || pathname === "/dashboard") {const uptime = Math.floor((Date.now() - startTime) / 1000);const isPrivate = await resolveSpaceIsPrivate(req);7 unmodified lines);}// 2. n8n Routing Logic (Namespace-based Proxy)// These are the prefixes n8n uses. If it matches, we proxy to n8n at ROOT.const isN8nPath =pathname.startsWith("/static/") ||pathname.startsWith("/assets/") ||pathname.startsWith("/rest/") ||pathname.startsWith("/api/") ||pathname.startsWith("/webhook/") ||pathname.startsWith("/home/") ||pathname.startsWith("/auth/") ||pathname.startsWith("/login") ||pathname.startsWith("/signup") ||pathname.startsWith("/logout") ||pathname.startsWith("/nodes/") ||pathname.startsWith("/healthz");// Special case: /app/ redirects to /home/workflowsif (pathname === "/app" || pathname === "/app/") {res.writeHead(302, { Location: "/home/workflows" });return res.end();}if (isN8nPath) {const proxyHeaders = {...req.headers,host: `127.0.0.1:${TARGET_PORT}`,"x-forwarded-for": req.socket.remoteAddress,"x-forwarded-host": req.headers.host,"x-forwarded-proto": "https",};const proxyReq = http.request({hostname: TARGET_HOST,port: TARGET_PORT,path: pathname + url.search,method: req.method,headers: proxyHeaders,},(proxyRes) => {res.writeHead(proxyRes.statusCode, proxyRes.headers);proxyRes.pipe(res);},);proxyReq.on("error", () => {res.writeHead(503, { "Content-Type": "application/json" });res.end(JSON.stringify({ status: "starting", message: "n8n is initializing..." }));});req.pipe(proxyReq);return;}// 3. Fallback: Redirect anything else to Dashboardres.writeHead(302, { Location: "/" });res.end();});server.on("upgrade", (req, socket, head) => {const url = parseRequestUrl(req.url);const proxyPath = url.pathname;const proxySocket = net.connect(TARGET_PORT, TARGET_HOST, () => {proxySocket.write(`${req.method} ${proxyPath}${url.search} HTTP/${req.httpVersion}\r\n`,9 unmodified lines});server.listen(PORT, "0.0.0.0", () =>console.log(`Namespace Proxy on ${PORT} -> n8n on ${TARGET_PORT}`),);
14 unmodified lines15161718192021222324252614 unmodified linesSPACE_HOST_DETECTED="${SPACE_HOST_OVERRIDE:-${SPACE_HOST:-}}"if [ -n "$SPACE_HOST_DETECTED" ]; thenexport N8N_HOST="${N8N_HOST:-$SPACE_HOST_DETECTED}"# Strict Native Subpath Configurationexport N8N_PATH="/app/"export N8N_PROTOCOL="https"export N8N_HOST="${SPACE_HOST_DETECTED}"export WEBHOOK_URL="https://${SPACE_HOST_DETECTED}/app/"export N8N_EDITOR_BASE_URL="https://${SPACE_HOST_DETECTED}/app/"fiexport N8N_PORT14 unmodified lines15161718192021222324252614 unmodified linesSPACE_HOST_DETECTED="${SPACE_HOST_OVERRIDE:-${SPACE_HOST:-}}"if [ -n "$SPACE_HOST_DETECTED" ]; thenexport N8N_HOST="${N8N_HOST:-$SPACE_HOST_DETECTED}"# Namespace-based Proxy Configuration (n8n at root internally)export N8N_PATH="/"export N8N_PROTOCOL="https"export N8N_HOST="${SPACE_HOST_DETECTED}"export WEBHOOK_URL="https://${SPACE_HOST_DETECTED}/"export N8N_EDITOR_BASE_URL="https://${SPACE_HOST_DETECTED}/"fiexport N8N_PORT
health-server.js+238-136
start.sh+4-4