Spaces:
Paused
Paused
Merge branch 'main' into main
Browse filesFiles changed (5)
- Dockerfile+3-1
- env-builder.js+5-5
- health-server.js+93-6
- login.html+12-22
- start.sh+11-17
14 unmodified lines1516171819202114 unmodified linesFROM node:22-slimARG OPENCLAW_VERSION=latestARG DEV_MODE=falseENV DEV_MODE=${DEV_MODE}# Install system dependencies (+ optional JupyterLab deps in DEV_MODE)RUN apt-get update && apt-get install -y \14 unmodified lines15161718192021222314 unmodified linesFROM node:22-slimARG OPENCLAW_VERSION=latestARG DEV_MODE=false# DEV_MODE intentionally not baked into runtime ENV β defaults to unset so# start.sh can auto-enable terminal when GATEWAY_TOKEN is present. Users can# override by setting DEV_MODE=false as an HF Space Variable to opt out.# Install system dependencies (+ optional JupyterLab deps in DEV_MODE)RUN apt-get update && apt-get install -y \
852 unmodified lines853854855856857858859860861862863101 unmodified lines965966967968969970971852 unmodified lines"k": "JUPYTER_TOKEN","lbl": "Jupyter access token (Must NOT be 'huggingface'. Run: openssl rand -hex 32)","type": "password","ph": "change_this_to_a_strong_token","common": 1,"tag": "credential"},{"g": "Core","icon": "β‘","k": "OPENCLAW_DISABLE_BONJOUR",101 unmodified lines"ph": "/home/node","tag": "advanced"},{"g": "Provider Keys","icon": "π","k": "ANTHROPIC_API_KEY",852 unmodified lines853854855856857858859860861862863101 unmodified lines965966967968969970971852 unmodified lines"k": "JUPYTER_TOKEN","lbl": "Jupyter access token (Must NOT be 'huggingface'. Run: openssl rand -hex 32)","type": "password","secret": 1,"ph": "huggingface","common": 1},{"g": "Core","icon": "β‘","k": "OPENCLAW_DISABLE_BONJOUR",101 unmodified lines"ph": "/home/node","tag": "advanced"},{"g": "Provider Keys","icon": "π","k": "ANTHROPIC_API_KEY",
21 unmodified lines2223242526272829303132207 unmodified lines240241242243244245353 unmodified lines59960060160260360460560660760860961061161261361422 unmodified lines63763863964064164264321 unmodified linesconst JUPYTER_BASE = normalizeBase(process.env.JUPYTER_BASE, "/terminal");const GATEWAY_TOKEN = (process.env.GATEWAY_TOKEN || "").trim();const DEV_MODE_ENABLED = isTrue(process.env.DEV_MODE);// Auto-enable Jupyter when DEV_MODE=true, HUGGINGCLAW_JUPYTER_ENABLED=true, or GATEWAY_TOKEN is set.// GATEWAY_TOKEN doubles as JUPYTER_TOKEN in start.sh β no extra secret needed.const JUPYTER_ENABLED = /^(true|1|yes|on)$/i.test(process.env.HUGGINGCLAW_JUPYTER_ENABLED || (DEV_MODE_ENABLED ? "true" : GATEWAY_TOKEN ? "true" : "false"));const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || "Not Set";const TELEGRAM_ENABLED = !!process.env.TELEGRAM_BOT_TOKEN;207 unmodified linesreturn String(v).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");}function badge(label, tone = "neutral") {return `<span class="badge ${tone}">${escapeHtml(label)}</span>`;}353 unmodified lines!isSameOriginNav &&!isFromHFApp;if (pathname === "/env-builder" || pathname === "/env-builder/") {if (isDirectHfSpaceRequest) {res.writeHead(200, { "Content-Type": "text/html" });return res.end(renderPrivateRedirect(HF_SPACE_URL));}res.writeHead(200, { "Content-Type": "text/html" });return res.end(renderEnvBuilder());}if (pathname === "/env-builder.js") {try {const js = fs.readFileSync(require("path").join(__dirname, "env-builder.js"), "utf8");res.writeHead(200, { "Content-Type": "application/javascript" });22 unmodified linesif (pathname === JUPYTER_BASE || pathname.startsWith(JUPYTER_BASE + "/")) {if (!JUPYTER_ENABLED) {res.writeHead(404, { "Content-Type": "application/json" });return res.end(JSON.stringify({ status: "disabled", message: "JupyterLab terminal is disabled. Set GATEWAY_TOKEN or DEV_MODE=true to enable /terminal/ (or set HUGGINGCLAW_JUPYTER_ENABLED=true)." }));}if (isDirectHfSpaceRequest) {res.writeHead(200, { "Content-Type": "text/html" });21 unmodified lines22232425262728293031207 unmodified lines239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303353 unmodified lines65765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070122 unmodified lines72472572672772872973021 unmodified linesconst JUPYTER_BASE = normalizeBase(process.env.JUPYTER_BASE, "/terminal");const GATEWAY_TOKEN = (process.env.GATEWAY_TOKEN || "").trim();const DEV_MODE_ENABLED = isTrue(process.env.DEV_MODE);// Default true. Only false when DEV_MODE=false or HUGGINGCLAW_JUPYTER_ENABLED=false is explicitly set.const JUPYTER_ENABLED =!/^(false|0|no|off)$/i.test(String(process.env.DEV_MODE || "").trim()) &&!/^(false|0|no|off)$/i.test(String(process.env.HUGGINGCLAW_JUPYTER_ENABLED || "").trim());const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || "Not Set";const TELEGRAM_ENABLED = !!process.env.TELEGRAM_BOT_TOKEN;207 unmodified linesreturn String(v).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");}function parseCookies(req) {const h = req.headers.cookie || "";return Object.fromEntries(h.split(";").map(c => c.trim().split("=")).filter(p => p.length >= 2).map(([k, ...v]) => [k.trim(), decodeURIComponent(v.join("=").trim())]));}// Constant-time comparison β prevent timing attacks on token checkfunction safeEqual(a, b) {if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;let d = 0;for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);return d === 0;}function isEnvBuilderAuthed(req) {if (!GATEWAY_TOKEN) return true; // unprotected when no token setreturn safeEqual(parseCookies(req).hc_env_auth || "", GATEWAY_TOKEN);}function readBody(req) {return new Promise((resolve) => {let body = "";req.on("data", chunk => { body += chunk; if (body.length > 4096) { body = ""; req.destroy(); } });req.on("end", () => resolve(body));req.on("error", () => resolve(""));});}function renderEnvBuilderLogin(error = false) {return `<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>HuggingClaw β Env Builder</title><style>:root{color-scheme:dark;--bg:#08080f;--panel:#12111b;--line:#26243a;--text:#f6f4ff;--muted:#7f7a9e;--bad:#fb7185}*{box-sizing:border-box}body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;font-family:Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;background:var(--bg);color:var(--text);padding:24px}.card{border:1px solid var(--line);background:var(--panel);border-radius:14px;padding:36px 32px;max-width:400px;width:100%;text-align:center}h1{margin:0 0 8px;font-size:1.4rem}.sub{color:var(--muted);font-size:.82rem;margin:0 0 24px}.row{display:flex;gap:8px;margin-top:16px}input{flex:1;background:#0d0c18;border:1px solid var(--line);border-radius:7px;padding:10px 12px;color:var(--text);font-size:.95rem;outline:none}input:focus{border-color:#6366f1}button{background:#fff;color:#000;border:none;border-radius:7px;padding:10px 20px;font-weight:700;font-size:.95rem;cursor:pointer;transition:opacity .15s}button:hover{opacity:.85}.err{color:var(--bad);font-size:.82rem;margin-top:10px}code{background:#232234;border:1px solid #34324c;border-radius:5px;padding:2px 6px;font-size:.88em}</style></head><body><div class="card"><h1>βοΈ Env Builder</h1><p class="sub">Enter your <code>GATEWAY_TOKEN</code> to continue</p><form method="post" action="/env-builder/login"><div class="row"><input type="password" name="token" placeholder="GATEWAY_TOKEN" autofocus autocomplete="current-password"><button type="submit">Unlock</button></div>${error ? '<p class="err">Invalid token β try again</p>' : ""}</form></div></body></html>`;}function badge(label, tone = "neutral") {return `<span class="badge ${tone}">${escapeHtml(label)}</span>`;}353 unmodified lines!isSameOriginNav &&!isFromHFApp;if (pathname === "/env-builder/login") {if (req.method === "POST") {const body = await readBody(req);const token = decodeURIComponent((body.match(/(?:^|&)token=([^&]*)/) || [])[1] || "").replace(/\+/g, " ");if (safeEqual(token, GATEWAY_TOKEN)) {const cookie = `hc_env_auth=${encodeURIComponent(GATEWAY_TOKEN)}; Path=/env-builder; HttpOnly; SameSite=Strict; Max-Age=86400`;res.writeHead(302, { Location: "/env-builder", "Set-Cookie": cookie, "Cache-Control": "no-store" });return res.end();}res.writeHead(200, { "Content-Type": "text/html" });return res.end(renderEnvBuilderLogin(true));}res.writeHead(302, { Location: "/env-builder", "Cache-Control": "no-store" });return res.end();}if (pathname === "/env-builder/logout") {res.writeHead(302, { Location: "/env-builder", "Set-Cookie": "hc_env_auth=; Path=/env-builder; HttpOnly; Max-Age=0", "Cache-Control": "no-store" });return res.end();}if (pathname === "/env-builder" || pathname === "/env-builder/") {if (isDirectHfSpaceRequest) {res.writeHead(200, { "Content-Type": "text/html" });return res.end(renderPrivateRedirect(HF_SPACE_URL));}if (!isEnvBuilderAuthed(req)) {res.writeHead(200, { "Content-Type": "text/html" });return res.end(renderEnvBuilderLogin(false));}res.writeHead(200, { "Content-Type": "text/html" });return res.end(renderEnvBuilder());}if (pathname === "/env-builder.js") {if (!isEnvBuilderAuthed(req)) {res.writeHead(401, { "Content-Type": "text/plain" });return res.end("Unauthorized");}try {const js = fs.readFileSync(require("path").join(__dirname, "env-builder.js"), "utf8");res.writeHead(200, { "Content-Type": "application/javascript" });22 unmodified linesif (pathname === JUPYTER_BASE || pathname.startsWith(JUPYTER_BASE + "/")) {if (!JUPYTER_ENABLED) {res.writeHead(404, { "Content-Type": "application/json" });return res.end(JSON.stringify({ status: "disabled", message: "JupyterLab terminal is disabled. Remove DEV_MODE=false to re-enable." }));}if (isDirectHfSpaceRequest) {res.writeHead(200, { "Content-Type": "text/html" });
7 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142437 unmodified lines<img src="https://huggingface.co/front/assets/huggingface_logo-noborder.svg" alt="Hugging Face Logo" style="max-width: 120px; margin-bottom: 24px;"><h3>HuggingClaw Terminal</h3><h4>Welcome to JupyterLab</h4><p style="color:#666;">Enter the <strong>JUPYTER_TOKEN</strong> you set in your Space secrets to access the terminal.</p><p style="color:#666;">This terminal is mounted at <code>/terminal/</code> inside the same Hugging Face Space as the OpenClaw UI.</p>{% if login_available %}<div class="row" style="display:flex; justify-content:center; margin-top:24px;"><div class="navbar col-sm-8"><div class="navbar-inner"><div class="container"><div class="center-nav"><form action="{{base_url}}login?next={{next}}" method="post" class="navbar-form pull-left">{{ xsrf_form_html() | safe }}{% if token_available %}<label for="password_input"><strong>{% trans %}Jupyter token <span title="This is the secret you set up when deploying your JupyterLab terminal">β</span> {% endtrans %}</strong></label>{% else %}<label for="password_input"><strong>{% trans %}Jupyter password:{% endtrans %}</strong></label>{% endif %}<input type="password" name="password" id="password_input" class="form-control"><button type="submit" class="btn btn-default" id="login_submit">{% trans %}Log in{% endtrans %}</button></form></div></div></div></div></div>{% else %}<p>{% trans %}No login available, you shouldn't be seeing this page.{% endtrans %}</p>{% endif %}<h5 style="margin-top:28px;"><a href="/dashboard">Back to HuggingClaw dashboard</a></h5><p>This login page is based on the Hugging Face JupyterLab Space template.</p>{% if message %}<div class="row">7 unmodified lines891011121314151617181920212223242526272829303132337 unmodified lines<img src="https://huggingface.co/front/assets/huggingface_logo-noborder.svg" alt="Hugging Face Logo" style="max-width: 120px; margin-bottom: 24px;"><h3>HuggingClaw Terminal</h3><h4>Welcome to JupyterLab</h4><p style="color:#666;">Token defaults to your <code>GATEWAY_TOKEN</code>. Set <code>JUPYTER_TOKEN</code> to override.</p>{% if login_available %}<div style="display:flex; justify-content:center; margin-top:24px;"><form action="{{base_url}}login?next={{next}}" method="post" style="display:flex; align-items:center; gap:8px;">{{ xsrf_form_html() | safe }}{% if token_available %}<label for="password_input"><strong>{% trans %}Jupyter token <span title="Your GATEWAY_TOKEN (or JUPYTER_TOKEN if set)">β</span>{% endtrans %}</strong></label>{% else %}<label for="password_input"><strong>{% trans %}Jupyter password:{% endtrans %}</strong></label>{% endif %}<input type="password" name="password" id="password_input" class="form-control"><button type="submit" class="btn btn-default" id="login_submit">{% trans %}Log in{% endtrans %}</button></form></div>{% else %}<p>{% trans %}No login available, you shouldn't be seeing this page.{% endtrans %}</p>{% endif %}<h5 style="margin-top:28px;"><a href="/dashboard">Back to HuggingClaw dashboard</a></h5>{% if message %}<div class="row">
96 unmodified lines979899100101102103771 unmodified lines8758768778788798808818828838848858869 unmodified lines89689789889990090190281 unmodified lines98498598698798898999026 unmodified lines101710181019102010211022102319 unmodified lines10431044104510461047104810496 unmodified lines1056105710581059106010611062106310641 unmodified line1066106710681069107010711072107310741 unmodified line1076107710781079108010811082108396 unmodified lines# GATEWAY_TOKEN doubles as JUPYTER_TOKEN (see start_jupyter_once) β no extra secret required.if [ "$DEV_MODE_ENABLED" != "true" ] && [ -z "${DEV_MODE:-}" ] && [ -n "${GATEWAY_TOKEN:-}" ]; thenDEV_MODE_ENABLED=trueecho "GATEWAY_TOKEN set and DEV_MODE not explicitly configured β auto-enabling terminal (set DEV_MODE=false to opt out)"fiSYNC_INTERVAL="$(trim_var "${SYNC_INTERVAL:-180}")"DEVDATA_DATASET_NAME="$(trim_var "${DEVDATA_DATASET_NAME:-huggingclaw-devdata}")"771 unmodified lines# Runtime install fallback: only attempt if DEV_MODE is enabled but install failed during buildif [ "$DEV_MODE_ENABLED" = "true" ] && ! python3 -c "import jupyterlab" >/dev/null 2>&1; thenecho "DEV_MODE enabled but jupyter-lab is missing; attempting runtime install..."if python3 -m pip install --user --no-cache-dir --break-system-packages "jupyterlab>=4.2,<5" "tornado>=6.3" "ipywidgets>=8.1"; thenecho "Runtime Jupyter install complete."python3 -c "from pathlib import Path; import shutil, jupyter_server; d=Path(jupyter_server.__file__).parent/'templates'; d.mkdir(parents=True,exist_ok=True); shutil.copyfile('/home/node/app/login.html', d/'login.html')" || trueelseecho "WARNING: Runtime Jupyter install failed; disabling terminal for this boot."RUNTIME_JUPYTER_ENABLED=falsefifi9 unmodified lineselseecho "Routes : /app/ (Control UI)"fiecho "Private : open the Hugging Face App tab first; raw https://${SPACE_HOST}/... links can show HF 404 without the embedded Space session."fiecho ""81 unmodified lines# reuse GATEWAY_TOKEN. Both protect the same Space, so the credential is equivalent.if { [ -z "${JUPYTER_TOKEN:-}" ] || [ "${JUPYTER_TOKEN}" = "huggingface" ]; } && [ -n "${GATEWAY_TOKEN:-}" ]; thenJUPYTER_TOKEN="$GATEWAY_TOKEN"echo "JUPYTER_TOKEN not set β using GATEWAY_TOKEN as terminal auth token"fi# Security guard: refuse to start JupyterLab with the insecure default token.26 unmodified lines# Pre-create runtime directorymkdir -p "$JUPYTER_ROOT_DIR/.jupyter"echo "DEV_MODE enabled (${DEV_MODE_RAW}) β starting JupyterLab terminal on internal port 8888 (path: /terminal/) with root: $JUPYTER_ROOT_DIR"JUPYTER_LOG_FILE="/tmp/jupyterlab.log"# Use explicit Python to avoid PATH issues; set memory-friendly limits19 unmodified lines>> "$JUPYTER_LOG_FILE" 2>&1 &JUPYTER_PID=$!export JUPYTER_PIDecho "JupyterLab started (PID: $JUPYTER_PID)"}# BUG FIX #3: DevData restore must happen BEFORE JupyterLab starts.6 unmodified lines[ -n "${HF_TOKEN:-}" ] && \[ -f "/home/node/app/jupyter-devdata-sync.py" ] && \[ "${DEVDATA_DATASET_NAME:-huggingclaw-devdata}" != "${BACKUP_DATASET_NAME:-huggingclaw-backup}" ]; thenecho "DevData : restoring workspace from ${DEVDATA_DATASET_NAME:-huggingclaw-devdata} (before JupyterLab starts)..."python3 /home/node/app/jupyter-devdata-sync.py --restore || \echo "DevData : restore warning (non-fatal); continuing startup."fi# Fix: reinstall jsonschema AFTER devdata restore β restore can overwrite a broken1 unmodified line# JupyterLab to crash with a circular import error on every boot.if [ "$DEV_MODE_ENABLED" = "true" ]; thenif ! python3 -c "import jsonschema" >/dev/null 2>&1; thenecho "DevData : jsonschema broken after restore β reinstalling (circular import fix)..."python3 -m pip install --force-reinstall --no-cache-dir --break-system-packages "jsonschema>=4.0" >/dev/null 2>&1 || trueecho "DevData : jsonschema reinstall done."fifi1 unmodified line# Accessible via /terminal/ path through the health-server proxyif [ "$RUNTIME_JUPYTER_ENABLED" = "true" ]; thenstart_jupyter_onceelseecho "Jupyter terminal disabled for this boot (DEV_MODE=${DEV_MODE_RAW})."fiif [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ]; then96 unmodified lines979899100101102103771 unmodified lines8758768778788798808818828838848858869 unmodified lines89689789889990090181 unmodified lines98398498598698798826 unmodified lines101510161017101810191020102119 unmodified lines10411042104310441045104610476 unmodified lines1054105510561057105810591060106110621 unmodified line10641065106610671068106910701 unmodified line10721073107410751076107796 unmodified lines# GATEWAY_TOKEN doubles as JUPYTER_TOKEN (see start_jupyter_once) β no extra secret required.if [ "$DEV_MODE_ENABLED" != "true" ] && [ -z "${DEV_MODE:-}" ] && [ -n "${GATEWAY_TOKEN:-}" ]; thenDEV_MODE_ENABLED=true: # auto-enable is silent; set DEV_MODE=false to opt outfiSYNC_INTERVAL="$(trim_var "${SYNC_INTERVAL:-180}")"DEVDATA_DATASET_NAME="$(trim_var "${DEVDATA_DATASET_NAME:-huggingclaw-devdata}")"771 unmodified lines# Runtime install fallback: only attempt if DEV_MODE is enabled but install failed during buildif [ "$DEV_MODE_ENABLED" = "true" ] && ! python3 -c "import jupyterlab" >/dev/null 2>&1; thenecho "Terminal : installing JupyterLab..."if python3 -m pip install -q --user --no-cache-dir --break-system-packages "jupyterlab>=4.2,<5" "tornado>=6.3" "ipywidgets>=8.1" >/dev/null 2>&1; thenecho "Terminal : installed"python3 -c "from pathlib import Path; import shutil, jupyter_server; d=Path(jupyter_server.__file__).parent/'templates'; d.mkdir(parents=True,exist_ok=True); shutil.copyfile('/home/node/app/login.html', d/'login.html')" || trueelseecho "Terminal : install failed β disabling for this boot"RUNTIME_JUPYTER_ENABLED=falsefifi9 unmodified lineselseecho "Routes : /app/ (Control UI)"fifiecho ""81 unmodified lines# reuse GATEWAY_TOKEN. Both protect the same Space, so the credential is equivalent.if { [ -z "${JUPYTER_TOKEN:-}" ] || [ "${JUPYTER_TOKEN}" = "huggingface" ]; } && [ -n "${GATEWAY_TOKEN:-}" ]; thenJUPYTER_TOKEN="$GATEWAY_TOKEN"fi# Security guard: refuse to start JupyterLab with the insecure default token.26 unmodified lines# Pre-create runtime directorymkdir -p "$JUPYTER_ROOT_DIR/.jupyter"echo "Terminal : starting (root: $JUPYTER_ROOT_DIR)"JUPYTER_LOG_FILE="/tmp/jupyterlab.log"# Use explicit Python to avoid PATH issues; set memory-friendly limits19 unmodified lines>> "$JUPYTER_LOG_FILE" 2>&1 &JUPYTER_PID=$!export JUPYTER_PIDecho "Terminal : started (PID: $JUPYTER_PID)"}# BUG FIX #3: DevData restore must happen BEFORE JupyterLab starts.6 unmodified lines[ -n "${HF_TOKEN:-}" ] && \[ -f "/home/node/app/jupyter-devdata-sync.py" ] && \[ "${DEVDATA_DATASET_NAME:-huggingclaw-devdata}" != "${BACKUP_DATASET_NAME:-huggingclaw-backup}" ]; thenecho "DevData : restoring workspace..."python3 /home/node/app/jupyter-devdata-sync.py --restore 2>/dev/null || \echo "DevData : restore warning (non-fatal); continuing startup."fi# Fix: reinstall jsonschema AFTER devdata restore β restore can overwrite a broken1 unmodified line# JupyterLab to crash with a circular import error on every boot.if [ "$DEV_MODE_ENABLED" = "true" ]; thenif ! python3 -c "import jsonschema" >/dev/null 2>&1; thenpython3 -m pip install -q --force-reinstall --no-cache-dir --break-system-packages "jsonschema>=4.0" >/dev/null 2>&1 || truefifi1 unmodified line# Accessible via /terminal/ path through the health-server proxyif [ "$RUNTIME_JUPYTER_ENABLED" = "true" ]; thenstart_jupyter_oncefiif [ -n "${CLOUDFLARE_WORKERS_TOKEN:-}" ]; then
Dockerfile+3-1
env-builder.js+5-5
health-server.js+93-6
login.html+12-22
start.sh+11-17