Repository navigation
fix: auto-disable device auth for non-loopback URLs (#2341) #2449
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 19 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
3a1729d
spec-simplify: merge Phase 3 (docs) into Phases 1 and 2
jyaunches f22aa69
Add test specification for brev-launchable-pairing-fix
jyaunches 9447a99
Add validation plan for brev-launchable-pairing-fix
jyaunches 420f6b6
validation: add Docker build+inspect scenario for Brev Launchable
jyaunches 6a03d36
Approve validation plan for brev-launchable-pairing-fix
jyaunches 56bef9c
spec-review-design: no changes needed
jyaunches b0d8efe
spec-review-implementation: fix config path gateway.auth → gateway.co…
jyaunches cbc3c2d
test: add failing tests for Phase 1 — generate-openclaw-config.py
jyaunches ca46f47
feat: extract inline Python config to scripts/generate-openclaw-confi…
jyaunches 563b57d
Mark Phase 1 as completed [ca46f470]
jyaunches e84a548
test: add failing tests for Phase 2 — non-loopback auto-disable devic…
jyaunches 054f1d7
feat: auto-disable device auth for non-loopback URLs (#2341)
jyaunches 1dbfc56
Mark Phase 2 as completed [054f1d73]
jyaunches 8ec43d8
validation: 9/10 scenarios validated, 1 skipped (Docker not running)
jyaunches 581dd8b
chore: remove specs/ directory from tracked files
jyaunches bdd663e
Merge remote-tracking branch 'origin/main' into issue-2341-brev-launc…
jyaunches 2d928c3
fix: update nemoclaw-start.test.ts for extracted config script
jyaunches 68aed03
Merge remote-tracking branch 'origin/main' into issue-2341-brev-launc…
jyaunches 50d29bf
fix: address CodeRabbit review — defaults and schemeless URL parsing
jyaunches 4dc3faf
fix: make --clear-token idempotent when config absent
jyaunches 9f5d517
fix: address remaining CodeRabbit review feedback
ericksoa 5c88191
Merge branch 'main' into issue-2341-brev-launchable-pairing-required
ericksoa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,252 @@ | ||
| #!/usr/bin/env python3 | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| """Generate openclaw.json from environment variables. | ||
|
|
||
| Called at Docker image build time (RUN layer) after ARG→ENV promotion. | ||
| Reads all configuration from os.environ — never from string interpolation | ||
| in Dockerfile source. See: C-2 security model. | ||
|
|
||
| Usage: | ||
| python3 scripts/generate-openclaw-config.py # Generate config | ||
| python3 scripts/generate-openclaw-config.py --clear-token # Clear auth token | ||
|
|
||
| Environment variables: | ||
| CHAT_UI_URL Dashboard URL (default: http://127.0.0.1:18789) | ||
| NEMOCLAW_MODEL Model identifier | ||
| NEMOCLAW_PROVIDER_KEY Provider key for model config | ||
| NEMOCLAW_PRIMARY_MODEL_REF Primary model reference | ||
| NEMOCLAW_INFERENCE_BASE_URL Inference endpoint | ||
| NEMOCLAW_INFERENCE_API Inference API type | ||
| NEMOCLAW_CONTEXT_WINDOW Context window size (default: 131072) | ||
| NEMOCLAW_MAX_TOKENS Max tokens (default: 4096) | ||
| NEMOCLAW_REASONING Enable reasoning (default: false) | ||
| NEMOCLAW_AGENT_TIMEOUT Per-request timeout seconds (default: 600) | ||
| NEMOCLAW_INFERENCE_COMPAT_B64 Base64-encoded inference compat JSON | ||
| NEMOCLAW_MESSAGING_CHANNELS_B64 Base64-encoded channel list | ||
| NEMOCLAW_MESSAGING_ALLOWED_IDS_B64 Base64-encoded allowed IDs map | ||
| NEMOCLAW_DISCORD_GUILDS_B64 Base64-encoded Discord guild config | ||
| NEMOCLAW_DISABLE_DEVICE_AUTH Set to "1" to force-disable device auth | ||
| NEMOCLAW_PROXY_HOST Egress proxy host (default: 10.200.0.1) | ||
| NEMOCLAW_PROXY_PORT Egress proxy port (default: 3128) | ||
| NEMOCLAW_WEB_SEARCH_ENABLED Set to "1" to enable web search tools | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import base64 | ||
| import json | ||
| import os | ||
| import re | ||
| import sys | ||
| from typing import Optional | ||
| from urllib.parse import urlparse | ||
|
|
||
|
|
||
| def is_loopback(hostname: str) -> bool: | ||
| """Check if a hostname is a loopback address. | ||
|
|
||
| Mirrors isLoopbackHostname() from src/lib/url-utils.ts. | ||
| Returns True for localhost, ::1, and 127.x.x.x addresses. | ||
| """ | ||
| normalized = (hostname or "").strip().lower().strip("[]") | ||
| if normalized == "localhost" or normalized == "::1": | ||
| return True | ||
| return bool(re.match(r"^127(?:\.\d{1,3}){3}$", normalized)) | ||
|
|
||
|
|
||
| def build_config(env: dict | None = None) -> dict: | ||
| """Build the complete openclaw config dict from environment variables. | ||
|
|
||
| Args: | ||
| env: Dict of environment variables. Defaults to os.environ. | ||
|
|
||
| Returns: | ||
| Complete config dict ready to be written as JSON. | ||
| """ | ||
| if env is None: | ||
| env = dict(os.environ) | ||
|
|
||
| proxy_host = env.get("NEMOCLAW_PROXY_HOST", "10.200.0.1") | ||
| proxy_port = env.get("NEMOCLAW_PROXY_PORT", "3128") | ||
| proxy_url = f"http://{proxy_host}:{proxy_port}" | ||
| model = env["NEMOCLAW_MODEL"] | ||
| chat_ui_url = env.get("CHAT_UI_URL", "http://127.0.0.1:18789") | ||
| provider_key = env["NEMOCLAW_PROVIDER_KEY"] | ||
| primary_model_ref = env["NEMOCLAW_PRIMARY_MODEL_REF"] | ||
| inference_base_url = env["NEMOCLAW_INFERENCE_BASE_URL"] | ||
| inference_api = env["NEMOCLAW_INFERENCE_API"] | ||
| context_window = int(env.get("NEMOCLAW_CONTEXT_WINDOW", "131072")) | ||
| max_tokens = int(env.get("NEMOCLAW_MAX_TOKENS", "4096")) | ||
| reasoning = env.get("NEMOCLAW_REASONING", "false") == "true" | ||
|
|
||
| _raw_agent_timeout = env.get("NEMOCLAW_AGENT_TIMEOUT", "600") | ||
| if not _raw_agent_timeout.isdigit() or int(_raw_agent_timeout) <= 0: | ||
| raise ValueError("NEMOCLAW_AGENT_TIMEOUT must be a positive integer") | ||
| agent_timeout = int(_raw_agent_timeout) | ||
|
|
||
| inference_compat = json.loads( | ||
| base64.b64decode(env["NEMOCLAW_INFERENCE_COMPAT_B64"]).decode("utf-8") | ||
| ) | ||
|
|
||
| msg_channels = json.loads( | ||
| base64.b64decode( | ||
| env.get("NEMOCLAW_MESSAGING_CHANNELS_B64", "W10=") or "W10=" | ||
| ).decode("utf-8") | ||
| ) | ||
| _allowed_ids = json.loads( | ||
| base64.b64decode( | ||
| env.get("NEMOCLAW_MESSAGING_ALLOWED_IDS_B64", "e30=") or "e30=" | ||
| ).decode("utf-8") | ||
| ) | ||
| _discord_guilds = json.loads( | ||
| base64.b64decode( | ||
| env.get("NEMOCLAW_DISCORD_GUILDS_B64", "e30=") or "e30=" | ||
| ).decode("utf-8") | ||
| ) | ||
|
|
||
| _token_keys = {"discord": "token", "telegram": "botToken", "slack": "botToken"} | ||
| _env_keys = { | ||
| "discord": "DISCORD_BOT_TOKEN", | ||
| "telegram": "TELEGRAM_BOT_TOKEN", | ||
| "slack": "SLACK_BOT_TOKEN", | ||
| } | ||
|
|
||
| _ch_cfg = {} | ||
| for ch in msg_channels: | ||
| if ch not in _token_keys: | ||
| continue | ||
| account = { | ||
| _token_keys[ch]: f"openshell:resolve:env:{_env_keys[ch]}", | ||
| "enabled": True, | ||
| } | ||
| if ch == "slack": | ||
| account["appToken"] = "openshell:resolve:env:SLACK_APP_TOKEN" | ||
| if ch in ("telegram", "discord"): | ||
| account["proxy"] = proxy_url | ||
| if ch == "telegram": | ||
| account["groupPolicy"] = "open" | ||
| if ch in _allowed_ids and _allowed_ids[ch]: | ||
| account["dmPolicy"] = "allowlist" | ||
| account["allowFrom"] = _allowed_ids[ch] | ||
| _ch_cfg[ch] = {"accounts": {"default": account}} | ||
|
|
||
| if "discord" in _ch_cfg and _discord_guilds: | ||
| _ch_cfg["discord"].update( | ||
| {"groupPolicy": "allowlist", "guilds": _discord_guilds} | ||
| ) | ||
|
|
||
| # Normalize schemeless URLs before parsing — urlparse("remote-host:18789") | ||
| # misclassifies hostname as scheme. Mirrors ensureScheme() in dashboard-contract.ts. | ||
| _normalized_url = chat_ui_url | ||
| if chat_ui_url and not re.match(r"^[a-z][a-z0-9+.-]*://", chat_ui_url, re.IGNORECASE): | ||
| _normalized_url = f"http://{chat_ui_url}" | ||
|
|
||
| parsed = urlparse(_normalized_url) | ||
| chat_origin = ( | ||
| f"{parsed.scheme}://{parsed.netloc}" | ||
| if parsed.scheme and parsed.netloc | ||
| else "http://127.0.0.1:18789" | ||
| ) | ||
| origins = list(dict.fromkeys(["http://127.0.0.1:18789", chat_origin])) | ||
|
|
||
| # Auto-disable device auth when CHAT_UI_URL is non-loopback — terminal-based | ||
| # pairing is impossible when the user only has web access (Brev Launchable, | ||
| # remote deployments). The explicit env var override still works but cannot | ||
| # re-enable device auth for non-loopback URLs (security default). | ||
| _is_remote = not is_loopback(parsed.hostname or "") | ||
| disable_device_auth = ( | ||
| env.get("NEMOCLAW_DISABLE_DEVICE_AUTH", "") == "1" | ||
| or _is_remote | ||
| ) | ||
| allow_insecure = parsed.scheme == "http" | ||
|
|
||
| providers = { | ||
| provider_key: { | ||
| "baseUrl": inference_base_url, | ||
| "apiKey": "unused", | ||
| "api": inference_api, | ||
| "models": [ | ||
| { | ||
| **({"compat": inference_compat} if inference_compat else {}), | ||
| "id": model, | ||
| "name": primary_model_ref, | ||
| "reasoning": reasoning, | ||
| "input": ["text"], | ||
| "cost": { | ||
| "input": 0, | ||
| "output": 0, | ||
| "cacheRead": 0, | ||
| "cacheWrite": 0, | ||
| }, | ||
| "contextWindow": context_window, | ||
| "maxTokens": max_tokens, | ||
| } | ||
| ], | ||
| } | ||
| } | ||
|
|
||
| config = { | ||
| "agents": { | ||
| "defaults": { | ||
| "model": {"primary": primary_model_ref}, | ||
| "timeoutSeconds": agent_timeout, | ||
| } | ||
| }, | ||
| "models": {"mode": "merge", "providers": providers}, | ||
| "channels": {"defaults": {}, **_ch_cfg}, | ||
| "update": {"checkOnStart": False}, | ||
| "gateway": { | ||
| "mode": "local", | ||
| "controlUi": { | ||
| "allowInsecureAuth": allow_insecure, | ||
| "dangerouslyDisableDeviceAuth": disable_device_auth, | ||
| "allowedOrigins": origins, | ||
| }, | ||
| "trustedProxies": ["127.0.0.1", "::1"], | ||
| "auth": {"token": ""}, | ||
| }, | ||
| } | ||
|
|
||
| if env.get("NEMOCLAW_WEB_SEARCH_ENABLED", "") == "1": | ||
| config["tools"] = { | ||
| "web": { | ||
| "search": { | ||
| "enabled": True, | ||
| "provider": "brave", | ||
| "apiKey": "openshell:resolve:env:BRAVE_API_KEY", | ||
| }, | ||
| "fetch": {"enabled": True}, | ||
| } | ||
| } | ||
|
|
||
| return config | ||
|
|
||
|
|
||
| def clear_token() -> None: | ||
| """Read existing openclaw.json and clear the gateway auth token.""" | ||
| path = os.path.expanduser("~/.openclaw/openclaw.json") | ||
| with open(path) as f: | ||
| cfg = json.load(f) | ||
| cfg.setdefault("gateway", {}).setdefault("auth", {})["token"] = "" | ||
| with open(path, "w") as f: | ||
| json.dump(cfg, f, indent=2) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| os.chmod(path, 0o600) | ||
|
|
||
|
|
||
| def main() -> None: | ||
| """Generate openclaw.json or clear token based on CLI args.""" | ||
| if "--clear-token" in sys.argv: | ||
| clear_token() | ||
| return | ||
|
|
||
| config = build_config() | ||
| path = os.path.expanduser("~/.openclaw/openclaw.json") | ||
| os.makedirs(os.path.dirname(path), exist_ok=True) | ||
| with open(path, "w") as f: | ||
| json.dump(config, f, indent=2) | ||
| os.chmod(path, 0o600) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.