feat(cli): attach terminal clients to the selected Desktop [skip ci]

NAN-104 requires terminal chat and browser attachment without granting a client ownership of Desktop's gateway. Resolve bounded short-lived credentials over authenticated current-user IPC, pin both Desktop and gateway identities, and reject replacement instances or incompatible clients before any mutation.

Reuse the existing TUI artifact resolver behind a narrow Desktop-only entrypoint, keep credentials out of argv/environment/files, and preserve Python-mode reconnect and gateway leases. Add protocol, real-gateway, and anonymous IPC regression coverage; matching native-host and Windows acceptance remain release gates.
This commit is contained in:
Xubin Ren committed 2026-09-08 10:04:15 +08:00
1 parent b373a95f5c
commit 48e7c4f697
20 files changed
+797 -52

No files matched your search

+3
View File
@@ -809,6 +809,9 @@ class WebSocketChannel(BaseChannel):
"event": "ready",
"chat_id": default_chat_id,
"client_id": client_id,
**({"terminal": {
"protocolVersion": 1, "gatewayId": self.gateway.tokens.instance_id,
}} if _query_first(query, "terminal_protocol") == "1" else {}),
},
ensure_ascii=False,
)
+13 -15
View File
@@ -34,6 +34,7 @@ class DesktopReply:
state: str
capabilities: frozenset[str]
webui_url: str | None = None
tui: dict[str, object] | None = None
@dataclass(frozen=True)
@@ -44,7 +45,7 @@ class DesktopTarget:
transport: Literal["unix", "namedPipe"]
address: str
def request(self, operation: Literal["status", "webui"]) -> DesktopReply:
def request(self, operation: Literal["status", "webui", "tui"]) -> DesktopReply:
"""Perform one bounded, side-effect-free Desktop rendezvous request."""
payload = json.dumps(
{
@@ -120,9 +121,6 @@ def dispatch_bare_desktop_target(args: list[str]) -> int | None:
_print_python_target()
return None
if not args:
print("Desktop terminal chat attachment is not supported by this Python client yet.")
if _choose_target(status) == "python":
_print_python_target()
return None
@@ -130,19 +128,13 @@ def dispatch_bare_desktop_target(args: list[str]) -> int | None:
# Revalidate after selection. A status probe is never treated as authority
# to reuse stale bootstrap data or silently choose another backend.
if not args:
from nanobot.cli.desktop_tui import launch_desktop_tui
try:
current = target.request("status")
return launch_desktop_tui(target)
except DesktopTargetError:
_print_desktop_error("Nanobot Desktop disconnected after it was selected.")
_print_desktop_error("Desktop terminal attachment is unavailable or incompatible. Update Desktop and nanobot, then try again.")
return 3
if current.state != "ready":
_print_desktop_error(f"Nanobot Desktop is not ready ({current.state}).")
return 3
_print_desktop_error(
"This Python client does not yet provide attach-only terminal chat. "
"Run `nanobot agent` to use this Python environment."
)
return 4
try:
reply = target.request("webui")
@@ -348,7 +340,13 @@ def _parse_reply(raw: bytes, *, expected_instance_id: str) -> DesktopReply:
if any(not isinstance(item, str) for item in capability_values):
raise DesktopTargetError("Desktop reply is incompatible")
capabilities = frozenset(cast(list[str], capability_values))
return DesktopReply(state=state_value, capabilities=capabilities, webui_url=webui_url)
tui = fields.get("tui")
if tui is not None and not isinstance(tui, dict):
raise DesktopTargetError("Desktop terminal connection is incompatible")
return DesktopReply(
state=state_value, capabilities=capabilities, webui_url=webui_url,
tui=cast(dict[str, object] | None, tui),
)
def _desktop_webui_url(reply: DesktopReply) -> str:
+187
View File
@@ -0,0 +1,187 @@
"""Strict Desktop client entrypoint and pipe-only, current-user credential resolver.
Unlike the normal TUI launcher, this module never loads a Config or acquires a
gateway lease. The resolver is also executable with ``python -I -S <this file>``.
"""
from __future__ import annotations
import json
import os
import socket
import stat
import subprocess
import sys
import uuid
from pathlib import Path
from typing import cast
from urllib.parse import urlsplit
if __name__ == "__main__":
# Only the package beside this trusted script, not cwd/user-site/PYTHONPATH.
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from nanobot.cli.desktop_target import (
DesktopTarget,
DesktopTargetError,
discover_desktop_target,
)
PROTOCOL_VERSION = 1
_MAX_BYTES = 8192
def _connection(target: DesktopTarget, gateway_id: str | None = None) -> dict[str, object]:
reply = target.request("tui")
value = reply.tui
if reply.state != "ready" or "tui" not in reply.capabilities or value is None:
raise DesktopTargetError("Desktop does not support terminal attachment")
identity = value.get("gatewayId")
if type(value.get("protocolVersion")) is not int or value["protocolVersion"] != 1:
raise DesktopTargetError("Unsupported terminal protocol")
if not isinstance(identity, str) or (gateway_id is not None and identity != gateway_id):
raise DesktopTargetError("Desktop gateway identity changed")
try:
uuid.UUID(identity)
except ValueError as exc:
raise DesktopTargetError("Invalid gateway identity") from exc
api = _endpoint(value.get("apiUrl"), websocket=False)
ws = _endpoint(value.get("wsUrl"), websocket=True)
if (api.hostname, api.port or 80) != (ws.hostname, ws.port or 80) or api.path not in {"", "/"}:
raise DesktopTargetError("Terminal endpoints must share the same loopback listener")
for key in ("wsToken", "apiToken"):
token = value.get(key)
if not isinstance(token, str) or not 1 <= len(token) <= 2048 or any(
ord(char) < 33 or ord(char) > 126 for char in token
):
raise DesktopTargetError("Invalid terminal credentials")
# Do not forward unknown fields or untrusted executable/config paths.
return {key: value[key] for key in (
"protocolVersion", "gatewayId", "apiUrl", "wsUrl", "wsToken", "apiToken",
)}
def _endpoint(value: object, *, websocket: bool):
if not isinstance(value, str) or "\\" in value or any(
ord(char) < 33 or ord(char) == 127 for char in value
):
raise DesktopTargetError("Invalid terminal endpoint")
try:
parsed = urlsplit(value)
port = parsed.port
except ValueError as exc:
raise DesktopTargetError("Invalid terminal endpoint") from exc
if (
parsed.scheme != ("ws" if websocket else "http")
or parsed.hostname not in {"127.0.0.1", "::1"}
or port == 0
or parsed.username is not None or parsed.password is not None
or parsed.query or parsed.fragment
):
raise DesktopTargetError("Terminal endpoint is not a literal loopback address")
return parsed
def resolve_request(raw: bytes) -> dict[str, object]:
"""Re-discover the selected Desktop; never substitute a newly started instance."""
if len(raw) > _MAX_BYTES:
raise DesktopTargetError("Invalid resolver request")
value: object = json.loads(raw)
if not isinstance(value, dict):
raise DesktopTargetError("Invalid resolver request")
fields = cast(dict[str, object], value)
identity, gateway_id = fields.get("instanceId"), fields.get("gatewayId")
if not isinstance(identity, str) or not isinstance(gateway_id, str):
raise DesktopTargetError("Invalid resolver identity")
target = discover_desktop_target()
if target is None or target.instance_id != identity:
raise DesktopTargetError("Selected Desktop disconnected")
return _connection(target, gateway_id)
def launch_desktop_tui(target: DesktopTarget) -> int:
from nanobot.cli.tui_launcher import TuiUnavailableError, resolve_tui_command
process: subprocess.Popen[bytes] | None = None
try:
current = _connection(target)
# Resolve/install only the matching terminal client, never a backend.
cache = os.environ.get("NANOBOT_DESKTOP_CLIENT_CACHE")
if cache is not None and not Path(cache).is_absolute():
raise DesktopTargetError("Desktop client cache must be absolute")
command = resolve_tui_command(data_dir=Path(cache)) if cache else resolve_tui_command()
probe = subprocess.run(
[*command, "--desktop-protocol"], capture_output=True, timeout=15, check=False,
)
if probe.returncode != 0 or probe.stdout.strip() != b"1":
raise DesktopTargetError("The terminal client does not support Desktop attachment")
env = {key: value for key, value in os.environ.items() if not key.startswith("NANOBOT_TUI_")}
env["NANOBOT_TUI_DESKTOP_RESOLVER"] = json.dumps([
sys.executable, "-I", "-S", str(Path(__file__).resolve()), "--resolve",
])
env["NANOBOT_TUI_DESKTOP_TARGET"] = json.dumps({
"instanceId": target.instance_id, "gatewayId": current["gatewayId"],
})
process = subprocess.Popen(command, env=env)
code = process.wait()
return 0 if code == 90 else code
except (OSError, ValueError, subprocess.SubprocessError, TuiUnavailableError) as exc:
raise DesktopTargetError("Desktop terminal attachment failed") from exc
finally:
if process is not None and process.poll() is None:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
def main() -> None:
args = sys.argv[1:]
if args == ["--resolve"]:
try:
# Secret output is permitted only through a pipe captured by our TUI.
if not _anonymous_output(sys.stdout.fileno()):
raise DesktopTargetError("Resolver requires a pipe")
raw = sys.stdin.buffer.readline(_MAX_BYTES + 1)
if not raw.endswith(b"\n"):
raise DesktopTargetError("Incomplete resolver request")
payload = json.dumps(resolve_request(raw), separators=(",", ":")).encode()
if len(payload) > _MAX_BYTES:
raise DesktopTargetError("Resolver response is too large")
sys.stdout.buffer.write(payload + b"\n")
return
except Exception:
raise SystemExit(3) from None # Never print credential-bearing exceptions.
if args == ["--protocol"]:
print(PROTOCOL_VERSION)
return
if args or os.environ.get("_NANOBOT_COMPLETE") or not sys.stdin.isatty() or not sys.stdout.isatty():
raise SystemExit(2)
try:
target = discover_desktop_target()
if target is None:
raise DesktopTargetError("Desktop is absent")
expected = os.environ.get("NANOBOT_DESKTOP_EXPECTED_INSTANCE")
if expected is not None and target.instance_id != expected:
raise DesktopTargetError("Selected Desktop changed")
raise SystemExit(launch_desktop_tui(target))
except DesktopTargetError:
print("Desktop terminal connection unavailable. Start or update Desktop; no backend was started.", file=sys.stderr)
raise SystemExit(3) from None
def _anonymous_output(fd: int) -> bool:
"""Bun uses an unnamed Unix socket pair for its captured subprocess stdout."""
mode = os.fstat(fd).st_mode
if stat.S_ISFIFO(mode):
return True
if os.name == "posix" and stat.S_ISSOCK(mode):
with socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) as stream:
return stream.getsockname() == "" and stream.getpeername() == ""
return False
if __name__ == "__main__":
main()
+12 -8
View File
@@ -86,7 +86,7 @@ def launch_tui(
"""Run the native TUI against the shared local gateway."""
chat_id = _initial_tui_chat_id(session_id)
tui_workspace = _initial_tui_workspace(workspace_override)
command = _resolve_tui_command()
command = resolve_tui_command()
base_url, bootstrap_secret = _tui_gateway_connection(config)
gateway: _GatewayHandle | None = None
process: subprocess.Popen[Any] | None = None
@@ -94,6 +94,8 @@ def launch_tui(
env = os.environ.copy()
env.pop("NANOBOT_TUI_WS_URL", None)
env.pop("NANOBOT_TUI_API_TOKEN", None)
env.pop("NANOBOT_TUI_DESKTOP_RESOLVER", None)
env.pop("NANOBOT_TUI_DESKTOP_TARGET", None)
env.update(
{
"NANOBOT_TUI_BOOTSTRAP_URL": f"{base_url}/webui/bootstrap",
@@ -160,7 +162,7 @@ def launch_tui(
lease.release(wait_for_stop=False)
def _resolve_tui_command() -> list[str]:
def resolve_tui_command(*, data_dir: Path | None = None) -> list[str]:
override = os.environ.get("NANOBOT_TUI_BIN", "").strip()
if override:
executable = Path(override).expanduser().resolve(strict=False)
@@ -191,13 +193,13 @@ def _resolve_tui_command() -> list[str]:
"this source checkout requires Bun to run its matching TUI; "
"install Bun, then run `nanobot agent` again"
)
return _resolve_source_tui_command(source_dir, bun)
return _resolve_source_tui_command(source_dir, bun, data_dir=data_dir)
packaged = Path(__file__).resolve().parents[1] / "tui" / "bin" / asset
if packaged.is_file():
return [str(packaged)]
downloaded = _download_release_tui(asset)
downloaded = _download_release_tui(asset, data_dir=data_dir)
if downloaded is not None:
return [str(downloaded)]
@@ -222,7 +224,9 @@ def _tui_source_dir(project_root: Path) -> Path | None:
return None
def _resolve_source_tui_command(source_dir: Path, bun: str) -> list[str]:
def _resolve_source_tui_command(
source_dir: Path, bun: str, *, data_dir: Path | None = None,
) -> list[str]:
dependency = source_dir / "node_modules" / "@opentui" / "core"
try:
install = subprocess.run(
@@ -241,12 +245,12 @@ def _resolve_source_tui_command(source_dir: Path, bun: str) -> list[str]:
executable = named_executable(
bun,
name="nanobot-tui",
directory=get_data_dir() / "run" / "executables",
directory=(data_dir if data_dir is not None else get_data_dir()) / "run" / "executables",
)
return [executable, str(source_dir / "src" / "index.ts")]
def _download_release_tui(asset: str) -> Path | None:
def _download_release_tui(asset: str, *, data_dir: Path | None = None) -> Path | None:
"""Install the complete, version-matched TUI release bundle."""
if os.environ.get("NANOBOT_TUI_NO_DOWNLOAD") == "1":
return None
@@ -254,7 +258,7 @@ def _download_release_tui(asset: str) -> Path | None:
if not version or version.endswith((".dev0", "+dev")):
return None
target_dir = get_data_dir() / "bin" / "tui" / version
target_dir = (data_dir if data_dir is not None else get_data_dir()) / "bin" / "tui" / version
cached = _cached_release_tui(target_dir, asset)
if cached is not None:
return cached
+6
View File
@@ -60,6 +60,12 @@ class WebUIGatewayEndpoint:
got, query = parse_request_path(request.path)
expected_ws = normalize_config_path(self._config.path)
if got == expected_ws and is_websocket_upgrade(request):
terminal_version = query_first(query, "terminal_protocol")
if terminal_version is not None and (
terminal_version != "1"
or query_first(query, "terminal_instance") != self._tokens.instance_id
):
return connection.respond(409, "Terminal instance or protocol changed")
client_id = query_first(query, "client_id") or ""
if len(client_id) > 128:
client_id = client_id[:128]
+2
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import secrets
import time
import uuid
from dataclasses import dataclass, field
from typing import Any, Literal
@@ -19,6 +20,7 @@ class GatewayTokenStore:
"""Own short-lived WebSocket and WebUI API tokens for one gateway process."""
max_tokens: int = 10_000
instance_id: str = field(default_factory=lambda: str(uuid.uuid4()), init=False)
issued_tokens: dict[str, float] = field(default_factory=dict)
issued_token_audiences: dict[str, IssuedTokenAudience] = field(default_factory=dict)
api_tokens: dict[str, float] = field(default_factory=dict)
+11 -1
View File
@@ -511,6 +511,8 @@ class GatewayHTTPHandler:
# Bootstrap
if got == "/webui/bootstrap":
return self._handle_bootstrap(connection, request)
if got == "/webui/terminal":
return self._handle_bootstrap(connection, request, terminal_probe=True)
# Settings routes (delegated)
response = await self.settings_routes.dispatch(connection, request, got)
@@ -601,7 +603,9 @@ class GatewayHTTPHandler:
# -- Bootstrap ----------------------------------------------------------
def _handle_bootstrap(self, connection: Any, request: Any) -> Response:
def _handle_bootstrap(
self, connection: Any, request: Any, *, terminal_probe: bool = False,
) -> Response:
secret = self.config.token_issue_secret.strip() or self.config.token.strip()
is_local_browser = _is_local_browser_request(connection, request.headers)
is_proxy_authenticated = _is_trusted_proxy_authenticated_request(
@@ -616,6 +620,11 @@ class GatewayHTTPHandler:
elif not is_local_browser:
return _http_error(403, "bootstrap is localhost-only")
terminal = {"protocolVersion": 1, "gatewayId": self.tokens.instance_id}
if terminal_probe:
# Capability probing does not allocate credentials or acquire client leases.
return _http_json_response(terminal, extra_headers=_NO_STORE_HEADERS)
if is_proxy_authenticated:
payload = {
"ws_path": _normalize_config_path(self.config.path),
@@ -651,6 +660,7 @@ class GatewayHTTPHandler:
expected_path = _normalize_config_path(self.config.path)
payload = {
"token": token,
"terminal": terminal,
"ws_path": expected_path,
"ws_url": ws_url,
"expires_in": self.config.token_ttl_s,