From 11889c018e89e75a6725ba6fdb5bb37204cb09ca Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sun, 27 Sep 2026 20:51:49 +0800 Subject: [PATCH] feat(webui): connect to existing remote nanobot instances (NAN-157) --- docs/guides/remote-instances.md | 151 ++++++ nanobot/channels/websocket/runtime.py | 2 + .../tests/test_websocket_runtime_lifecycle.py | 1 + nanobot/webui/remote_instances.py | 251 ++++++++++ nanobot/webui/remote_ssh.py | 262 ++++++++++ nanobot/webui/ssh_config.py | 126 +++++ nanobot/webui/ws_http.py | 48 ++ tests/webui/test_remote_instances.py | 286 +++++++++++ tests/webui/test_ssh_config.py | 137 ++++++ webui/src/App.tsx | 43 +- webui/src/components/Sidebar.tsx | 20 +- webui/src/components/remote/HostSwitcher.tsx | 106 ++++ .../remote/RemoteConnectionsPage.tsx | 245 ++++++++++ .../src/components/remote/RemoteInstances.tsx | 119 +++++ webui/src/components/remote/SSHHostPicker.tsx | 97 ++++ webui/src/components/remote/host-bridge.ts | 36 ++ .../src/components/remote/useHostSessions.ts | 186 +++++++ .../components/remote/useSidebarHostBridge.ts | 88 ++++ .../components/settings/SettingsSidebar.tsx | 7 +- webui/src/i18n/locales/en/common.json | 102 ++++ webui/src/i18n/locales/es/common.json | 102 ++++ webui/src/i18n/locales/fr/common.json | 102 ++++ webui/src/i18n/locales/id/common.json | 102 ++++ webui/src/i18n/locales/ja/common.json | 102 ++++ webui/src/i18n/locales/ko/common.json | 102 ++++ webui/src/i18n/locales/pt-BR/common.json | 102 ++++ webui/src/i18n/locales/vi/common.json | 102 ++++ webui/src/i18n/locales/zh-CN/common.json | 102 ++++ webui/src/i18n/locales/zh-TW/common.json | 102 ++++ webui/src/lib/remote-instances.ts | 81 ++++ webui/src/tests/app-layout.test.tsx | 44 ++ webui/src/tests/host-bridge.test.tsx | 110 +++++ webui/src/tests/host-sessions.test.tsx | 168 +++++++ webui/src/tests/remote-instances.test.tsx | 454 ++++++++++++++++++ 34 files changed, 4074 insertions(+), 14 deletions(-) create mode 100644 docs/guides/remote-instances.md create mode 100644 nanobot/webui/remote_instances.py create mode 100644 nanobot/webui/remote_ssh.py create mode 100644 nanobot/webui/ssh_config.py create mode 100644 tests/webui/test_remote_instances.py create mode 100644 tests/webui/test_ssh_config.py create mode 100644 webui/src/components/remote/HostSwitcher.tsx create mode 100644 webui/src/components/remote/RemoteConnectionsPage.tsx create mode 100644 webui/src/components/remote/RemoteInstances.tsx create mode 100644 webui/src/components/remote/SSHHostPicker.tsx create mode 100644 webui/src/components/remote/host-bridge.ts create mode 100644 webui/src/components/remote/useHostSessions.ts create mode 100644 webui/src/components/remote/useSidebarHostBridge.ts create mode 100644 webui/src/lib/remote-instances.ts create mode 100644 webui/src/tests/host-bridge.test.tsx create mode 100644 webui/src/tests/host-sessions.test.tsx create mode 100644 webui/src/tests/remote-instances.test.tsx diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.md new file mode 100644 index 000000000..9c4b8d6a3 --- /dev/null +++ b/docs/guides/remote-instances.md @@ -0,0 +1,151 @@ +# Connect to an existing remote nanobot + +Open your local **nanobot WebUI** and choose **Remote connections** in the sidebar +(below Channels). Setup opens in the main content area, with the sidebar still +available. Choose a host from **From your SSH config**, or enter an SSH address +such as `ubuntu@your-server` using **Connect to remote nanobot…**. +Give it a recognizable name, then choose **Save & connect**. Next time, select +the saved server. No port-forwarding command or `.command` launcher is needed. + +To add another server, choose **Connect to remote nanobot…** below your saved +connections. Use a server's menu to edit or forget it. The page supports browser +back/forward and the `#/remote` route. Leaving setup while SSH is connecting won't +switch you away from the page you chose when that connection finishes. + +This connects to the nanobot **already running on the server**. It does not +install a worker, clone a workspace, move conversations, or start a second bot. +It is separate from remote execution/worker deployment. + +## Find a server you already use + +nanobot lists named hosts from `~/.ssh/config` and the system SSH config, including +ordinary `Include` files. Search by alias, then select a host to review its setup. +If your configuration lives elsewhere, expand **Use another SSH config file** +and enter its local path. Returning from setup keeps the previous list and search. + +Discovery is passive: it reads host names and source paths, not private keys, +and does not contact servers or execute SSH hooks. Wildcard and negated patterns +aren't destinations. Conditional includes may suggest hosts; only connecting +checks reachability. Large or dynamic configurations show a partial-list notice; +you can still enter an alias manually. Discovery is capped at 200 hosts, 64 files, +256 KiB per file, and approximately 1 MiB in total. + +At connection time, the system SSH client resolves your existing `User`, `Port`, +`IdentityFile`, jump hosts and other connection settings. An empty port field +inherits SSH configuration instead of overriding it with 22. Listing a host +does not mean nanobot is installed there. Enter an alias or address, not a full +shell command. + +## Prerequisites + +- Run the local WebUI on a loopback address, using the system OpenSSH client. +- Your SSH key must already have access to the server. Encrypted keys should + be unlocked in the system SSH agent. Interactive SSH passwords are not + collected by this UI. +- The remote server needs `python3` and an already running nanobot WebUI with + a configured `tokenIssueSecret` (or `token`) in its configuration file. +- The remote gateway must support the authenticated `/webui/terminal` + identity probe, protocol version 1, and have the WebUI bundle installed. + The initial transport supports HTTP on the server's loopback address; SSH + encrypts the connection. A configured public WebSocket URL is not supported. + +If this machine has never connected to the server, nanobot displays its SSH +fingerprint. Compare it with the server console or your administrator before +confirming. The public key is pinned for this connection, without changing +your system `known_hosts`. A **changed** host key is blocked, not automatically +accepted. Jump-host-only or non-Ed25519 hosts can use a previously verified +system SSH configuration instead of the in-app first-contact verifier. + +## Advanced options + +Most setups only need the SSH address. Expand **Advanced** when necessary: + +| Option | Meaning | +| --- | --- | +| SSH port | Optional override; empty inherits SSH config (normally 22) | +| SSH config file | Existing local config, including aliases or jump hosts | +| Private key path | Path to an existing local key; key contents aren't uploaded | +| nanobot config path | Server-side config, default `~/.nanobot/config.json` | +| nanobot service account | Optional account owning the remote config; requires existing passwordless `sudo -u` permission | + +For a service installation, the SSH login and nanobot owner may differ. For +example, you might sign in as `ubuntu`, with nanobot running as `nanobot` and +its config in `/var/lib/nanobot/.nanobot/config.json`. Enter those last two +values in Advanced. The connection does not grant new sudo privileges. + +## Using the remote instance + +The remote instance's **own complete WebUI** fills the main window. Its UI +version follows the server, independently of the local +installation. Model settings, channels, tools and conversations belong to that +server. The isolated remote view cannot navigate the local application's +top-level window. The first version has been exercised in macOS Chrome; native +desktop-host packaging and other platforms still need their own acceptance. + +The host switcher lives beside **Settings at the bottom of the sidebar**, showing +**Local** or your saved server name. It is also available in Settings. Its menu +opens upward and shows the computer name, recent hosts, and **Manage connections…**. +With the sidebar collapsed, the icon still opens the same menu. Recent, loaded +hosts show **Ready**. Remote +connection setup is hidden inside the embedded remote view, and connecting back +to the same gateway is rejected rather than creating a nested local session. + +Updated remote WebUIs put the switcher in the same sidebar location. A narrowly +scoped, origin- and frame-checked bridge sends only the current host's display +identity and allows its button to open the local shell's menu. The remote page +does not receive your host directory, SSH configuration, or connection commands. +Older remote WebUIs retain a compact bottom-strip switcher so you can always +return local without covering their controls. + +Refreshing restores the selected remote instance. A failed connection stays +on a remote error screen; it never silently redirects work to your local agent. +The selected server ID is stored per browser tab, without credentials. + +- **Switching hosts**, including returning local, keeps both pages mounted and + keeps SSH connected. Each host retains its own chat, unsent draft, scroll + position and UI state; nothing is copied between hosts. Up to three remote + views are kept per tab. At the limit, explicitly disconnect one rather than + silently discarding its work. Reloading the browser still follows each + instance's normal draft persistence; unfinished uploads aren't guaranteed. +- A first connection prepares a hidden server page while the current page stays + usable. It switches after the page loads; **Cancel switch** keeps you where + you are. The most recent choice wins even if an earlier SSH request finishes + later. Cancelling navigation does not stop an in-flight server connection. + Older server WebUIs can still show their own sign-in/startup indicator after + the initial page load; returning to an already loaded view avoids that startup. +- **Disconnect** in a server's menu confirms before closing its view and shared + SSH tunnel. Unsaved view-only work can be lost; the remote bot keeps running. + Idle views do not automatically close a tunnel another tab might be using. +- **Forget server** removes its local connection metadata and pinned public key. + It does not delete remote conversations, keys, files, or the installation. +- Closing the local gateway cleans up its SSH processes. The independently + running remote gateway, Linear integration, and scheduled tasks keep running. +- Connections to the same saved server share one tunnel; explicitly disconnecting + it also disconnects other local tabs using that tunnel. Reloading a tab reuses + a healthy connection. Up to four servers can be connected concurrently. + +## Security and troubleshooting + +The local connection directory is stored beside the local config under +`webui/remote-instances.json`. It contains connection metadata, not private-key +contents or model/channel credentials. A stable loopback port per saved server +keeps browser preferences scoped to that server. Port conflicts fail explicitly; +nanobot does not attach to an unrelated listener. + +SSH authenticates the server. A read-only, fixed Python probe retrieves only +WebUI login information from its config. The gateway's protocol and runtime ID +are verified before navigation. The WebUI credential is held by the live +connection and passed in the remote view's URL fragment, not an HTTP query or +local model configuration. The remote WebUI uses its existing browser login +storage. Nothing opens a public administration port or forwards your SSH agent. + +Remote-connection actions require an authenticated local WebUI connection, a +loopback-bound gateway, and local request origin. They are unavailable from a +public/reverse-proxied administration page. Connecting requires server admin +access; permission to mention nanobot in Linear is **not** that permission. + +Common errors explain whether SSH authentication, a missing config, a service +account, WebUI authentication, protocol compatibility or networking failed. +Configurations whose WebUI secret is supplied only by a service environment, +interactive SSH passwords, and remote WebUIs with a public WebSocket URL need +additional setup; this flow does not silently weaken their authentication. diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py index 05df43843..927e7986a 100644 --- a/nanobot/channels/websocket/runtime.py +++ b/nanobot/channels/websocket/runtime.py @@ -676,6 +676,7 @@ class WebSocketChannel(BaseChannel): ) async def start(self) -> None: + self.gateway.http.remote_instances.resume() from nanobot.utils.logging_bridge import redirect_lib_logging redirect_lib_logging("websockets", level="WARNING") @@ -880,6 +881,7 @@ class WebSocketChannel(BaseChannel): # -- Outbound WebSocket events ----------------------------------------- async def stop(self) -> None: + await self.gateway.http.remote_instances.close() server_task = self._server_task if ( not self._running diff --git a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py index feee6e51f..64f719538 100644 --- a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py +++ b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py @@ -45,6 +45,7 @@ def _channel() -> WebSocketChannel: gateway = MagicMock() gateway.session_manager = None gateway.http.settings_routes.close = AsyncMock() + gateway.http.remote_instances.close = AsyncMock() return WebSocketChannel( {"enabled": True, "allowFrom": ["*"]}, MessageBus(), diff --git a/nanobot/webui/remote_instances.py b/nanobot/webui/remote_instances.py new file mode 100644 index 000000000..35aeea115 --- /dev/null +++ b/nanobot/webui/remote_instances.py @@ -0,0 +1,251 @@ +"""Local connection directory. Owns SSH tunnels, never remote gateway lifetimes.""" + +from __future__ import annotations + +import asyncio +import json +import secrets +import socket +import time +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Any, cast +from urllib.parse import quote + +import httpx +from pydantic import Field + +from nanobot.utils.helpers import _write_text_atomic # pyright: ignore[reportPrivateUsage] +from nanobot.webui import remote_ssh +from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, Tunnel + + +class _SavedProfile(RemoteProfile): + # Retain an origin per server so browser preferences/caches cannot drift + # between servers on every reconnect. Not an editable API field. + local_port: int = Field(default=0, ge=0, le=65535) + + +@dataclass +class Connection: + tunnel: Tunnel + secret: str + hostname: str + config_path: str + gateway_id: str + error: str = "" + + +class RemoteInstances: + """List/save/connect/disconnect with credentials confined to live connections.""" + + def __init__(self, directory: Path, *, local_gateway_id: str = "") -> None: + self.path = directory / "remote-instances.json" + self.local_gateway_id = local_gateway_id + self.connections: dict[str, Connection] = {} + self._lock = asyncio.Lock() + self._unverified: dict[str, tuple[str, str, float]] = {} + self._unknown_hosts: set[str] = set() + self._closed = False + + def _known_hosts(self, key: str) -> Path: + return self.path.parent / "remote-hosts" / key + + def resume(self) -> None: + """Allow a reused local channel to start again after its stop completed.""" + self._closed = False + + def _read(self) -> dict[str, _SavedProfile]: + if not self.path.exists(): + return {} + try: + raw = json.loads(self.path.read_text(encoding="utf-8")) + if not isinstance(raw, dict): + raise ValueError + return {str(uuid.UUID(key)): _SavedProfile.model_validate(value) + for key, value in cast(dict[str, Any], raw).items()} + except (ValueError, TypeError, OSError): + raise RemoteError("profile_store_invalid") from None + + def _write(self, profiles: dict[str, _SavedProfile]) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + _write_text_atomic(self.path, json.dumps( + {key: profile.model_dump() for key, profile in profiles.items()}, ensure_ascii=False, + )) + self.path.chmod(0o600) + + def snapshot(self) -> dict[str, Any]: + return {"available": True, "machine_name": socket.gethostname(), "profiles": [ + {"id": key, **profile.model_dump(exclude={"local_port"}), + "connected": key in self.connections + and self.connections[key].tunnel.process.returncode is None + and not self.connections[key].error} + for key, profile in self._read().items() + ]} + + async def health(self) -> dict[str, Any]: + async def check(connection: Connection) -> None: + if connection.tunnel.process.returncode is not None: + connection.error = "ssh_unreachable" + return + try: + async with httpx.AsyncClient(timeout=8, trust_env=False) as client: + response = await client.get( + f"http://127.0.0.1:{connection.tunnel.port}/webui/terminal", + headers={"X-Nanobot-Auth": connection.secret}, + ) + if response.status_code != 200: + connection.error = "remote_unreachable" + elif response.json().get("gatewayId") != connection.gateway_id: + connection.error = "instance_changed" + else: + connection.error = "" + except (httpx.HTTPError, ValueError, AttributeError): + connection.error = "remote_unreachable" + + await asyncio.gather(*(check(item) for item in tuple(self.connections.values()))) + return self.snapshot() + + async def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]: + if action == "discover": + from nanobot.webui.ssh_config import discover_hosts + + config_file = payload.get("ssh_config", "") + if not isinstance(config_file, str): + raise RemoteError("invalid_profile") + discovery = await asyncio.to_thread(discover_hosts, config_file) + return dict(discovery) + async with self._lock: + if self._closed: + raise RemoteError("local_io_error") + profiles = self._read() + key = str(payload.get("id", "")) + if action == "save": + profile = RemoteProfile.model_validate(payload.get("profile")) + if key and key not in profiles: + raise RemoteError("profile_not_found") + if not key and len(profiles) >= 20: + raise RemoteError("profile_limit") + key = key or str(uuid.uuid4()) + if key in self.connections: + raise RemoteError("disconnect_before_edit") + target_changed = key in profiles and any( + getattr(profiles[key], field) != getattr(profile, field) + for field in ("host", "port", "ssh_config") + ) + if target_changed: + self._known_hosts(key).unlink(missing_ok=True) + self._unverified.pop(key, None) + self._unknown_hosts.discard(key) + local_port = profiles[key].local_port if key in profiles and not target_changed else 0 + profiles[key] = _SavedProfile(**profile.model_dump(), local_port=local_port) + self._write(profiles) + return {"id": key, **self.snapshot()} + if key not in profiles: + raise RemoteError("profile_not_found") + if action == "connect": + try: + return await self._connect(key, profiles[key]) + except RemoteError as exc: + if str(exc) == "host_key_unknown": + self._unknown_hosts.add(key) + else: + self._unknown_hosts.discard(key) + raise + if action == "fingerprint": + if key not in self._unknown_hosts or self._known_hosts(key).exists(): + raise RemoteError("host_key_changed") + known_host, fingerprint = await remote_ssh.scan_host_key(profiles[key]) + challenge = secrets.token_urlsafe(24) + self._unverified[key] = (challenge, known_host, time.monotonic() + 300) + return {"fingerprint": fingerprint, "challenge": challenge} + if action == "trust": + pending = self._unverified.pop(key, None) + if (not pending or pending[2] < time.monotonic() + or not secrets.compare_digest(pending[0], str(payload.get("challenge", ""))) + or key not in self._unknown_hosts or self._known_hosts(key).exists()): + raise RemoteError("host_key_changed") + path = self._known_hosts(key) + path.parent.mkdir(parents=True, exist_ok=True) + _write_text_atomic(path, pending[1]) + path.chmod(0o600) + self._unknown_hosts.discard(key) + return {"trusted": True} + if action in {"disconnect", "remove"}: + connection = self.connections.pop(key, None) + if connection: + await connection.tunnel.close() + if action == "remove": + del profiles[key] + self._write(profiles) + self._known_hosts(key).unlink(missing_ok=True) + self._unknown_hosts.discard(key) + self._unverified.pop(key, None) + return self.snapshot() + raise RemoteError("unknown_action") + + def _launch(self, key: str, profile: RemoteProfile, connection: Connection) -> dict[str, Any]: + return {"id": key, "name": profile.name, "host": profile.host, + "hostname": connection.hostname, "config_path": connection.config_path, + "url": f"http://127.0.0.1:{connection.tunnel.port}/#/?bootstrapSecret={quote(connection.secret, safe='')}", + "gateway_id": connection.gateway_id} + + async def _connect(self, key: str, profile: _SavedProfile) -> dict[str, Any]: + existing = self.connections.get(key) + if existing: + await self.health() + if not existing.error: + return self._launch(key, profile, existing) + await existing.tunnel.close() + del self.connections[key] + if len(self.connections) >= 4: + raise RemoteError("connection_limit") + known_hosts = self._known_hosts(key) + data = await remote_ssh.probe(profile, known_hosts) + tunnel = await remote_ssh.open_tunnel(profile, data["port"], known_hosts, profile.local_port) + base = f"http://127.0.0.1:{tunnel.port}" + try: + async with httpx.AsyncClient(timeout=8, trust_env=False, follow_redirects=False) as client: + response = await client.get( + f"{base}/webui/terminal", headers={"X-Nanobot-Auth": data["secret"]}, + ) + if response.status_code in {401, 403}: + raise RemoteError("remote_auth_failed") + if response.status_code != 200: + raise RemoteError("incompatible_gateway") + raw_identity = response.json() + if not isinstance(raw_identity, dict): + raise RemoteError("incompatible_gateway") + identity = cast(dict[str, Any], raw_identity) + if (identity.get("protocolVersion") != 1 + or not isinstance(identity.get("gatewayId"), str)): + raise RemoteError("incompatible_gateway") + if identity["gatewayId"] == self.local_gateway_id: + raise RemoteError("same_instance") + # Require the installed WebUI too, not just a port answering HTTP. + page = await client.get(base + "/") + if page.status_code != 200 or "text/html" not in page.headers.get("content-type", ""): + raise RemoteError("webui_unavailable") + connection = Connection( + tunnel, data["secret"], str(data.get("hostname", profile.host)), + str(data.get("config_path", profile.config_path)), identity["gatewayId"], + ) + profiles = self._read() + profiles[key].local_port = tunnel.port + self._write(profiles) + self.connections[key] = connection + return self._launch(key, profile, connection) + except BaseException as exc: + await tunnel.close() + if isinstance(exc, httpx.HTTPError): + raise RemoteError("remote_unreachable") from None + if isinstance(exc, ValueError): + raise RemoteError("incompatible_gateway") from None + raise + + async def close(self) -> None: + self._closed = True + async with self._lock: + connections, self.connections = self.connections, {} + await asyncio.gather(*(item.tunnel.close() for item in connections.values())) diff --git a/nanobot/webui/remote_ssh.py b/nanobot/webui/remote_ssh.py new file mode 100644 index 000000000..7f7817308 --- /dev/null +++ b/nanobot/webui/remote_ssh.py @@ -0,0 +1,262 @@ +"""SSH-only access to an existing nanobot. Never installs or starts a remote process. + +The system SSH client owns key/agent authentication and host verification. Probe +output is private: only the WebUI credential is read, never provider credentials. +""" + +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json +import shlex +import shutil +import socket +from dataclasses import dataclass +from pathlib import Path +from typing import Any, cast + +from pydantic import BaseModel, ConfigDict, Field, field_validator + + +class RemoteError(Exception): + """A stable, non-secret error code for the connection UI.""" + + +class RemoteProfile(BaseModel): + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + + name: str = Field(min_length=1, max_length=64) + host: str = Field(min_length=1, max_length=253, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9._:@-]*$") + port: int | None = Field(default=None, ge=1, le=65535) + ssh_config: str = Field(default="", max_length=2048) + identity_file: str = Field(default="", max_length=2048) + config_path: str = Field(default="~/.nanobot/config.json", min_length=1, max_length=2048) + runtime_user: str = Field(default="", max_length=64, pattern=r"^([a-zA-Z_][a-zA-Z0-9_-]*)?$") + + @field_validator("ssh_config", "identity_file", "config_path") + @classmethod + def safe_path(cls, value: str) -> str: + if any(ord(char) < 32 for char in value): + raise ValueError("control characters are not allowed") + return value + + +# Fixed program, quoted as one shell argument. No user-supplied shell commands. +_PROBE = r''' +import json, os, pathlib, socket, sys +try: + path = pathlib.Path(sys.argv[1]).expanduser() + data = json.loads(path.read_text()) + ws = data.get("channels", {}).get("websocket", {}) + secret = ws.get("tokenIssueSecret") or ws.get("token_issue_secret") or ws.get("token") + if not ws.get("enabled"): + raise ValueError("webui_disabled") + if not isinstance(secret, str) or not secret.strip() or "${" in secret: + raise ValueError("webui_auth_required") + if ws.get("publicWsUrl") or ws.get("public_ws_url"): + raise ValueError("public_ws_unsupported") + print(json.dumps({"port": ws.get("port", 8765), "secret": secret, + "hostname": socket.gethostname(), "config_path": str(path)})) +except FileNotFoundError: + print(json.dumps({"error": "config_not_found"})) +except PermissionError: + print(json.dumps({"error": "config_permission"})) +except ValueError as e: + code = str(e) + print(json.dumps({"error": code if code in {"webui_disabled", "webui_auth_required", "public_ws_unsupported"} else "config_invalid"})) +''' + + +def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> list[str]: + executable = shutil.which("ssh") + if not executable: + raise RemoteError("ssh_unavailable") + args = [executable] + for flag, value in [("-F", profile.ssh_config), ("-i", profile.identity_file)]: + if value: + path = Path(value).expanduser() + if not path.is_file(): + raise RemoteError("local_file_not_found") + args.extend([flag, str(path)]) + # CLI options override config. Never forward the agent or reuse an unrelated + # multiplexed session (whose identity/forwarding policy could be different). + args.extend([ + "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", + "-o", "ForwardAgent=no", "-o", "ForwardX11=no", "-o", "PermitLocalCommand=no", + "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=10", + "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2", + "-o", "ExitOnForwardFailure=yes", "-o", "RequestTTY=no", + ]) + if profile.port is not None: + args.extend(["-p", str(profile.port)]) + if known_hosts and known_hosts.is_file(): + args.extend(["-o", f"UserKnownHostsFile={known_hosts}", "-o", "GlobalKnownHostsFile=none", + "-o", "HostKeyAlias=nanobot-remote", "-o", "HostKeyAlgorithms=ssh-ed25519", + "-o", "UpdateHostKeys=no"]) + return args + + +def ssh_error(stderr: bytes) -> str: + text = stderr.decode("utf-8", errors="replace").lower() + if "host identification has changed" in text: + return "host_key_changed" + if "host key verification failed" in text or "no ed25519 host key is known" in text: + return "host_key_unknown" + if "permission denied" in text: + return "ssh_auth_failed" + if "sudo:" in text: + return "runtime_user_denied" + if "python3" in text and "not found" in text: + return "python_unavailable" + return "ssh_unreachable" + + +async def stop_process(process: asyncio.subprocess.Process) -> None: + if process.returncode is None: + try: + process.terminate() + except ProcessLookupError: + pass + try: + await asyncio.wait_for(process.wait(), 3) + except TimeoutError: + try: + process.kill() + except ProcessLookupError: + pass + await process.wait() + + +async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]: + remote = ["python3", "-c", _PROBE, profile.config_path] + if profile.runtime_user: + remote = ["sudo", "-n", "-H", "-u", profile.runtime_user, "--", *remote] + process = await asyncio.create_subprocess_exec( + *ssh_arguments(profile, known_hosts), profile.host, shlex.join(remote), + stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + try: + stdout, stderr = await asyncio.wait_for(process.communicate(), 20) + if process.returncode: + raise RemoteError(ssh_error(stderr)) + try: + raw = json.loads(stdout) + if not isinstance(raw, dict): + raise ValueError + data = cast(dict[str, Any], raw) + if data.get("error"): + raise RemoteError(str(data["error"])) + if not isinstance(data.get("secret"), str) or not data["secret"]: + raise ValueError + if type(data.get("port")) is not int or not 1 <= data["port"] <= 65535: + raise ValueError + return data + except (ValueError, TypeError): + raise RemoteError("config_invalid") from None + except TimeoutError: + raise RemoteError("ssh_unreachable") from None + finally: + await stop_process(process) + + +@dataclass +class Tunnel: + process: asyncio.subprocess.Process + port: int + + async def close(self) -> None: + await stop_process(self.process) + + +async def open_tunnel( + profile: RemoteProfile, remote_port: int, known_hosts: Path | None = None, + local_port: int = 0, +) -> Tunnel: + # Reserve a loopback candidate. SSH remains responsible for binding and + # ExitOnForwardFailure ensures a collision cannot connect us to another app. + with socket.socket() as candidate: + try: + # Match OpenSSH's listener policy: a just-closed tunnel can leave + # TIME_WAIT connections without another program owning the port. + candidate.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + candidate.bind(("127.0.0.1", local_port)) + candidate.listen(1) + except OSError: + raise RemoteError("local_port_in_use") from None + port = int(candidate.getsockname()[1]) + process = await asyncio.create_subprocess_exec( + *ssh_arguments(profile, known_hosts), "-N", "-L", f"127.0.0.1:{port}:127.0.0.1:{remote_port}", + profile.host, stdin=asyncio.subprocess.DEVNULL, + stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE, + ) + tunnel = Tunnel(process, port) + try: + for _ in range(100): + if process.returncode is not None: + stderr = await process.stderr.read() if process.stderr else b"" + raise RemoteError(ssh_error(stderr)) + try: + reader, writer = await asyncio.wait_for( + asyncio.open_connection("127.0.0.1", port), 0.2, + ) + del reader + writer.close() + await writer.wait_closed() + return tunnel + except (OSError, TimeoutError): + await asyncio.sleep(0.1) + raise RemoteError("ssh_unreachable") + except BaseException: + await tunnel.close() + raise + + +async def scan_host_key(profile: RemoteProfile) -> tuple[str, str]: + """Return an UNVERIFIED key and fingerprint, never silently trust it. + + Resolve SSH aliases with the user's own config. Scanning is deliberately + direct; jump-host-only setups should verify via their existing SSH config. + """ + keyscan = shutil.which("ssh-keyscan") + if not keyscan: + raise RemoteError("ssh_unavailable") + process = await asyncio.create_subprocess_exec( + *ssh_arguments(profile), "-G", profile.host, + stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, + ) + try: + output, _ = await asyncio.wait_for(process.communicate(), 10) + if process.returncode: + raise RemoteError("ssh_unreachable") + finally: + await stop_process(process) + settings = dict(line.split(" ", 1) for line in output.decode().splitlines() if " " in line) + hostname, port = settings.get("hostname", ""), settings.get("port", "22") + if not hostname or hostname.startswith("-") or not port.isdigit(): + raise RemoteError("invalid_profile") + scan = await asyncio.create_subprocess_exec( + keyscan, "-T", "5", "-p", port, "-t", "ed25519", hostname, + stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, + ) + try: + output, _ = await asyncio.wait_for(scan.communicate(), 8) + for line in output.decode().splitlines(): + fields = line.split() + if len(fields) != 3 or fields[1] != "ssh-ed25519": + continue + try: + binary = base64.b64decode(fields[2], validate=True) + except ValueError: + continue + fingerprint = "SHA256:" + base64.b64encode(hashlib.sha256(binary).digest()).decode().rstrip("=") + return f"nanobot-remote ssh-ed25519 {fields[2]}\n", fingerprint + raise RemoteError("host_key_scan_failed") + except TimeoutError: + raise RemoteError("host_key_scan_failed") from None + finally: + await stop_process(scan) diff --git a/nanobot/webui/ssh_config.py b/nanobot/webui/ssh_config.py new file mode 100644 index 000000000..057e4692d --- /dev/null +++ b/nanobot/webui/ssh_config.py @@ -0,0 +1,126 @@ +"""Discover named SSH targets without running SSH, shell hooks, or contacting hosts. + +This is a bounded name index, not an SSH configuration evaluator. OpenSSH still +resolves User, Port, IdentityFile, ProxyJump and Match at connection time. +""" + +from __future__ import annotations + +import glob +import os +import re +import shlex +import stat +from pathlib import Path +from typing import TypedDict + +from nanobot.webui.remote_ssh import RemoteError + + +class SSHHost(TypedDict): + host: str + source: str + ssh_config: str + + +class SSHDiscovery(TypedDict): + hosts: list[SSHHost] + files: list[str] + incomplete: bool + + +def discover_hosts(config_file: str = "") -> SSHDiscovery: + """Read literal Host names, including Include files, with no side effects. + + Wildcard/negated Host patterns are not destinations. Conditional includes + may contribute suggestions; those are not claims that a host is reachable. + Only names and source paths are returned, never arbitrary config contents. + """ + if len(config_file) > 2048 or any(ord(char) < 32 for char in config_file): + raise RemoteError("invalid_profile") + home = Path.home() + user_ssh = home / ".ssh" + system_ssh = (Path(os.environ.get("PROGRAMDATA", "C:/ProgramData")) / "ssh" + if os.name == "nt" else Path("/etc/ssh")) + roots = [(Path(config_file).expanduser(), user_ssh)] if config_file else [ + (user_ssh / "config", user_ssh), (system_ssh / "ssh_config", system_ssh), + ] + result: SSHDiscovery = {"hosts": [], "files": [], "incomplete": False} + visited: set[Path] = set() + names: set[str] = set() + bytes_read = 0 + + def visit(path: Path, base: Path, *, required: bool = False) -> None: + nonlocal bytes_read + try: + path = path.resolve() + if path in visited: + return + if len(visited) >= 64 or bytes_read >= 1_048_576: + result["incomplete"] = True + return + visited.add(path) + info = path.stat() + if not stat.S_ISREG(info.st_mode) or info.st_size > 262_144: + raise ValueError + # Bound reads too, even if the file grows after stat(). + with path.open("rb") as stream: + content = stream.read(min(262_145, 1_048_577 - bytes_read)) + bytes_read += len(content) + if len(content) > 262_144 or bytes_read > 1_048_576: + raise ValueError + lines = content.decode("utf-8").splitlines() + except FileNotFoundError: + if required: + raise RemoteError("local_file_not_found") from None + return + except (OSError, ValueError, RuntimeError): + if required: + raise RemoteError("ssh_config_unreadable") from None + result["incomplete"] = True + return + result["files"].append(str(path)) + for line in lines: + match = re.match(r"^\s*(Host|Include)(?:\s*=\s*|\s+)(.*)$", line, re.I) + if not match: + continue + try: + values = shlex.split(match[2], comments=True) + except ValueError: + result["incomplete"] = True + continue + if match[1].lower() == "host": + for name in values: + if (len(name) > 253 or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9._:@-]*", name) + or name.casefold() in names): + continue + if len(result["hosts"]) >= 200: + result["incomplete"] = True + return + names.add(name.casefold()) + result["hosts"].append({"host": name, "source": str(path), + "ssh_config": str(roots[0][0].expanduser()) if config_file else ""}) + else: + for pattern in values: + # Tokens/environment-dependent paths cannot be resolved without + # a target. Leave them to SSH; never invoke `ssh -G` on page load + # because Match exec can execute arbitrary local commands. + if "$" in pattern or "%" in pattern: + result["incomplete"] = True + continue + expanded = Path(pattern).expanduser() + if not expanded.is_absolute(): + expanded = base / expanded + matches = glob.iglob(str(expanded)) + paths: list[str] = [] + for candidate in matches: + if len(paths) >= 64: + result["incomplete"] = True + break + paths.append(candidate) + for candidate in sorted(paths): + visit(Path(candidate), base) + + for root, base in roots: + visit(root, base, required=bool(config_file)) + return result diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 33b222258..620e3b5db 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -164,6 +164,13 @@ class _WebUIThreadDiagnostics: event_loop_lag_ms: float = 0.0 _WEBUI_MUTATION_PATHS = { + "remote.discover": "/api/remote-instances/discover", + "remote.save": "/api/remote-instances/save", + "remote.connect": "/api/remote-instances/connect", + "remote.disconnect": "/api/remote-instances/disconnect", + "remote.remove": "/api/remote-instances/remove", + "remote.fingerprint": "/api/remote-instances/fingerprint", + "remote.trust": "/api/remote-instances/trust", "automation.enable": "/api/webui/automations/enable", "automation.disable": "/api/webui/automations/disable", "automation.delete": "/api/webui/automations/delete", @@ -372,6 +379,11 @@ class GatewayHTTPHandler: self.ingress = ingress self.workspaces = workspaces self.settings = settings + from nanobot.webui.remote_instances import RemoteInstances + + self.remote_instances = RemoteInstances( + settings.config.path.parent / "webui", local_gateway_id=tokens.instance_id, + ) self.skills_workspace_path = skills_workspace_path self.disabled_skills: set[str] = ( disabled_skills if disabled_skills is not None else set() @@ -512,6 +524,8 @@ class GatewayHTTPHandler: return _http_error(404, "WebUI mutation action not found") def _is_webui_mutation_path(self, path: str) -> bool: + if path.startswith("/api/remote-instances/"): + return True if self.settings_routes.is_mutation_path(path): return True if re.match(r"^/api/sessions/[^/]+/delete$", path): @@ -560,6 +574,8 @@ class GatewayHTTPHandler: request: WsRequest, got: str, ) -> Any | None: + if got == "/api/remote-instances" or got.startswith("/api/remote-instances/"): + return await self._dispatch_remote_instances(connection, request, got) # Token issue endpoint if self.config.token_issue_path: issue_expected = _normalize_config_path(self.config.token_issue_path) @@ -617,6 +633,38 @@ class GatewayHTTPHandler: return connection.respond(404, "Not Found") + async def _dispatch_remote_instances( + self, connection: Any, request: WsRequest, path: str, + ) -> Response: + from pydantic import ValidationError + + from nanobot.webui.remote_ssh import RemoteError + + if not self.check_api_token(request): + return _http_error(401, "Unauthorized") + # A public/reverse-proxied WebUI must never gain access to this machine's + # SSH agent, private keys or network. Same checks as local folder picking. + if not (_is_loopback_host(self.config.host) + and _is_local_browser_request(connection, request.headers)): + return _http_error(403, "remote_connections_local_only") + origin = request.headers.get("Origin", "") + if origin and not _is_loopback_host(urlsplit(origin).hostname or ""): + return _http_error(403, "remote_connections_local_only") + try: + if path == "/api/remote-instances": + return _http_json_response(await self.remote_instances.health(), extra_headers=_NO_STORE_HEADERS) + if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False): + return _http_error(405, "WebSocket required") + payload = getattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, {}) + result = await self.remote_instances.action(path.rsplit("/", 1)[-1], payload) + return _http_json_response(result, extra_headers=_NO_STORE_HEADERS) + except RemoteError as exc: + return _http_error(400, str(exc)) + except ValidationError: + return _http_error(400, "invalid_profile") + except OSError: + return _http_error(500, "local_io_error") + def _log_slow_http(self, path: str, response: Any | None, started: float) -> None: elapsed_ms = int((time.perf_counter() - started) * 1000) if elapsed_ms < _SLOW_WEBUI_HTTP_LOG_MS: diff --git a/tests/webui/test_remote_instances.py b/tests/webui/test_remote_instances.py new file mode 100644 index 000000000..3a26e4f19 --- /dev/null +++ b/tests/webui/test_remote_instances.py @@ -0,0 +1,286 @@ +"""Connection boundaries: no deployment, copied model keys or remote shutdown.""" + +import asyncio +import json +import socket +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import httpx +import pytest +from pydantic import ValidationError +from websockets.datastructures import Headers +from websockets.http11 import Request + +from nanobot.channels.websocket.runtime import WebSocketConfig +from nanobot.webui import remote_ssh +from nanobot.webui.gateway_services import build_gateway_services +from nanobot.webui.remote_instances import RemoteInstances +from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, ssh_arguments, ssh_error + + +@pytest.fixture +def manager(tmp_path): + return RemoteInstances(tmp_path) + + +async def save(manager, **values): + result = await manager.action("save", {"profile": {"name": "Team", "host": "ubuntu@example.test", **values}}) + return result["id"] + + +@pytest.fixture +def ssh(monkeypatch): + process = SimpleNamespace(returncode=None) + tunnel = SimpleNamespace(process=process, port=23456, close=AsyncMock()) + probe = AsyncMock(return_value={"port": 8765, "secret": "private-webui-secret", "hostname": "team-host"}) + monkeypatch.setattr(remote_ssh, "probe", probe) + monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=tunnel)) + state = {"status": 200, "identity": {"protocolVersion": 1, "gatewayId": "remote-one"}} + + def respond(request): + if request.url.path == "/webui/terminal": + assert request.headers["X-Nanobot-Auth"] == "private-webui-secret" + return httpx.Response(state["status"], json=state["identity"]) + return httpx.Response(200, text="nanobot", headers={"content-type": "text/html"}) + + real_client = httpx.AsyncClient + monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(transport=httpx.MockTransport(respond), **kwargs)) + return SimpleNamespace(tunnel=tunnel, probe=probe, state=state) + + +async def test_save_survives_restart_without_credentials(manager): + key = await save(manager) + assert RemoteInstances(manager.path.parent).snapshot()["profiles"][0]["id"] == key + assert "secret" not in manager.path.read_text() + with pytest.raises(ValidationError): + await save(manager, private_key="must-never-save") + + +@pytest.mark.parametrize("host", ["-oProxyCommand=evil", "user@host;whoami", "a\nb", "$(id)", "host name"]) +def test_hosts_cannot_be_shell_or_ssh_options(host): + with pytest.raises(ValidationError): + RemoteProfile(name="Team", host=host) + + +def test_strict_ssh_without_agent_forwarding(monkeypatch): + monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "/usr/bin/ssh") + args = ssh_arguments(RemoteProfile(name="Team", host="my-alias")) + for option in ["StrictHostKeyChecking=yes", "BatchMode=yes", "ForwardAgent=no", "ControlPath=none", "PermitLocalCommand=no", "ExitOnForwardFailure=yes"]: + assert option in args + assert "StrictHostKeyChecking=no" not in args + + +async def test_connect_checks_protocol_and_only_disconnects_tunnel(manager, ssh): + key = await save(manager) + connection = await manager.action("connect", {"id": key}) + assert connection["hostname"] == "team-host" + assert connection["gateway_id"] == "remote-one" + assert connection["url"].startswith("http://127.0.0.1:23456/#/?bootstrapSecret=") + assert "private-webui-secret" not in json.dumps(manager.snapshot()) + assert "private-webui-secret" not in manager.path.read_text() + await manager.action("disconnect", {"id": key}) + ssh.tunnel.close.assert_awaited_once() + assert not manager.snapshot()["profiles"][0]["connected"] + assert len(manager.snapshot()["profiles"]) == 1 + + +@pytest.mark.parametrize(("status", "identity", "error"), [ + (401, {}, "remote_auth_failed"), (404, {}, "incompatible_gateway"), + (200, {"protocolVersion": 2, "gatewayId": "other"}, "incompatible_gateway"), + (200, {"protocolVersion": 1}, "incompatible_gateway"), +]) +async def test_bad_target_closes_tunnel_and_never_returns_launch_url(manager, ssh, status, identity, error): + key = await save(manager) + ssh.state.update(status=status, identity=identity) + with pytest.raises(RemoteError, match=error): + await manager.action("connect", {"id": key}) + ssh.tunnel.close.assert_awaited_once() + assert not manager.connections + + +async def test_server_restart_requires_reconnect_not_local_fallback(manager, ssh): + key = await save(manager) + await manager.action("connect", {"id": key}) + ssh.state["identity"]["gatewayId"] = "restarted" + assert not (await manager.health())["profiles"][0]["connected"] + assert key in manager.connections + ssh.tunnel.close.assert_not_awaited() + + +async def test_connect_to_own_gateway_is_rejected_without_nesting(manager, ssh): + manager.local_gateway_id = "remote-one" + key = await save(manager) + with pytest.raises(RemoteError, match="same_instance"): + await manager.action("connect", {"id": key}) + ssh.tunnel.close.assert_awaited_once() + assert not manager.connections + + +async def test_forget_only_removes_saved_profile(manager, ssh): + key = await save(manager) + await manager.action("connect", {"id": key}) + await manager.action("remove", {"id": key}) + assert manager.snapshot()["profiles"] == [] + ssh.tunnel.close.assert_awaited_once() + + +async def test_closing_local_manager_reaps_ssh(manager, ssh): + key = await save(manager) + await manager.action("connect", {"id": key}) + await manager.close() + ssh.tunnel.close.assert_awaited_once() + assert len(manager.snapshot()["profiles"]) == 1 + + +async def test_refresh_reuses_a_healthy_tunnel(manager, ssh): + key = await save(manager) + first = await manager.action("connect", {"id": key}) + second = await manager.action("connect", {"id": key}) + assert first["url"] == second["url"] + ssh.probe.assert_awaited_once() + ssh.tunnel.close.assert_not_awaited() + + +async def test_reconnect_keeps_origin_and_changing_target_does_not(manager, ssh): + key = await save(manager) + await manager.action("connect", {"id": key}) + assert json.loads(manager.path.read_text())[key]["local_port"] == 23456 + await manager.action("disconnect", {"id": key}) + await manager.action("save", {"id": key, "profile": {"name": "Renamed", "host": "ubuntu@example.test"}}) + assert json.loads(manager.path.read_text())[key]["local_port"] == 23456 + await manager.action("save", {"id": key, "profile": {"name": "Other", "host": "other.example.test"}}) + assert json.loads(manager.path.read_text())[key]["local_port"] == 0 + + +async def test_corrupt_store_not_overwritten(manager): + manager.path.write_text("corrupt") + with pytest.raises(RemoteError, match="profile_store_invalid"): + await save(manager) + assert manager.path.read_text() == "corrupt" + + +async def test_new_host_trust_is_explicit_scoped_and_one_use(manager, ssh, monkeypatch): + key = await save(manager) + ssh.probe.side_effect = RemoteError("host_key_unknown") + with pytest.raises(RemoteError): + await manager.action("connect", {"id": key}) + monkeypatch.setattr(remote_ssh, "scan_host_key", AsyncMock(return_value=("nanobot-remote ssh-ed25519 test-key\n", "SHA256:test"))) + result = await manager.action("fingerprint", {"id": key}) + assert result["fingerprint"] == "SHA256:test" + assert not list(manager.path.parent.glob("remote-hosts/*")) + await manager.action("trust", {"id": key, "challenge": result["challenge"]}) + assert (manager.path.parent / "remote-hosts" / key).read_text() == "nanobot-remote ssh-ed25519 test-key\n" + with pytest.raises(RemoteError, match="host_key_changed"): + await manager.action("trust", {"id": key, "challenge": result["challenge"]}) + with pytest.raises(RemoteError, match="host_key_changed"): + await manager.action("fingerprint", {"id": key}) + + +async def test_changed_known_host_cannot_be_overridden_in_ui(manager, ssh): + key = await save(manager) + ssh.probe.side_effect = RemoteError("host_key_changed") + with pytest.raises(RemoteError, match="host_key_changed"): + await manager.action("connect", {"id": key}) + with pytest.raises(RemoteError, match="host_key_changed"): + await manager.action("fingerprint", {"id": key}) + + +async def test_shutdown_prevents_new_tunnels(manager, ssh): + key = await save(manager) + await manager.close() + with pytest.raises(RemoteError, match="local_io_error"): + await manager.action("connect", {"id": key}) + ssh.probe.assert_not_awaited() + + +@pytest.mark.parametrize(("stderr", "code"), [ + (b"WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED", "host_key_changed"), + (b"Host key verification failed", "host_key_unknown"), + (b"Permission denied (publickey). secret-information", "ssh_auth_failed"), + (b"timed out with private address", "ssh_unreachable"), +]) +def test_errors_never_echo_raw_ssh_output(stderr, code): + assert ssh_error(stderr) == code + + +@pytest.fixture +def gateway(tmp_path): + return build_gateway_services( + config=WebSocketConfig(host="127.0.0.1"), bus=MagicMock(), session_manager=None, + static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json", + default_restrict_to_workspace=False, runtime_model_name=None, + runtime_surface="browser", runtime_capabilities_overrides=None, + ) + + +@pytest.mark.parametrize("action", ["save", "discover", "connect", "remove", "trust"]) +async def test_http_mutations_are_not_gettable_even_with_token(gateway, action): + request = Request(f"/api/remote-instances/{action}", Headers()) + connection = SimpleNamespace(remote_address=("127.0.0.1", 10000)) + result = await gateway.http.dispatch(connection, request) + assert result.status_code == 405 + + +@pytest.mark.parametrize(("peer", "host", "origin", "status"), [ + ("127.0.0.1", "127.0.0.1:8765", "http://127.0.0.1:8765", 200), + ("203.0.113.1", "127.0.0.1:8765", "http://127.0.0.1:8765", 403), + ("127.0.0.1", "bot.example.com", "https://bot.example.com", 403), + ("127.0.0.1", "127.0.0.1:8765", "https://evil.example", 403), +]) +async def test_ssh_access_is_local_and_authenticated(gateway, peer, host, origin, status): + token = gateway.tokens.issue_api_token(60) + connection = SimpleNamespace(remote_address=(peer, 10000)) + request = Request("/api/remote-instances", Headers({"Host": host, "Origin": origin, "Authorization": f"Bearer {token}"})) + result = await gateway.http.dispatch(connection, request) + assert result.status_code == status + request = Request("/api/remote-instances", Headers({"Host": host})) + assert (await gateway.http.dispatch(connection, request)).status_code == 401 + + +async def test_cancellation_reaps_inflight_probe(monkeypatch): + process = MagicMock(returncode=None) + process.communicate = AsyncMock(side_effect=asyncio.CancelledError) + process.wait = AsyncMock(return_value=0) + monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process)) + with pytest.raises(asyncio.CancelledError): + await remote_ssh.probe(RemoteProfile(name="Test", host="example.test")) + process.terminate.assert_called_once() + + +async def test_tunnel_refuses_an_existing_listener(monkeypatch): + spawn = AsyncMock() + monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn) + with socket.socket() as listener: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + with pytest.raises(RemoteError, match="local_port_in_use"): + await remote_ssh.open_tunnel( + RemoteProfile(name="Test", host="example.test"), 8765, + local_port=listener.getsockname()[1], + ) + spawn.assert_not_awaited() + + +async def test_tunnel_reuses_closed_port_with_time_wait(monkeypatch): + with socket.socket() as listener: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + port = listener.getsockname()[1] + with socket.create_connection(("127.0.0.1", port), timeout=1) as peer: + accepted, _ = listener.accept() + accepted.close() # Server-side active close leaves TIME_WAIT after peer closes. + assert peer.recv(1) == b"" + process = MagicMock(returncode=None) + process.wait = AsyncMock(return_value=0) + writer = MagicMock() + writer.wait_closed = AsyncMock() + monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process)) + monkeypatch.setattr(asyncio, "open_connection", AsyncMock(return_value=(None, writer))) + tunnel = await remote_ssh.open_tunnel( + RemoteProfile(name="Test", host="example.test"), 8765, local_port=port, + ) + assert tunnel.port == port + await tunnel.close() diff --git a/tests/webui/test_ssh_config.py b/tests/webui/test_ssh_config.py new file mode 100644 index 000000000..785d36e9b --- /dev/null +++ b/tests/webui/test_ssh_config.py @@ -0,0 +1,137 @@ +"""Name discovery is passive; OpenSSH, not our index, interprets connection options.""" + +import asyncio +import json +import subprocess + +import pytest + +from nanobot.webui.remote_instances import RemoteInstances +from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, ssh_arguments +from nanobot.webui.ssh_config import discover_hosts + + +@pytest.fixture +def ssh_home(tmp_path, monkeypatch): + monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path) + folder = tmp_path / ".ssh" + folder.mkdir() + return folder + + +def test_discover_host_names_quotes_equals_multiple_aliases_and_patterns(ssh_home): + config = ssh_home / "config" + config.write_text('''# Host ignored +Host=one two "three" # comment + HostName not-returned.example + IdentityFile private-key-not-returned +Host * !excluded jump? [ab]bad -unsafe one +Host TWO +Host ipv6:alias +''') + result = discover_hosts(str(config)) + assert [host["host"] for host in result["hosts"]] == ["one", "two", "three", "ipv6:alias"] + assert {host["ssh_config"] for host in result["hosts"]} == {str(config)} + assert "private-key-not-returned" not in json.dumps(result) + assert "not-returned.example" not in json.dumps(result) + + +def test_recursive_includes_are_sorted_relative_to_ssh_root_and_deduplicated(ssh_home): + (ssh_home / "hosts").mkdir() + (ssh_home / "config").write_text('Include "hosts/*.conf"\nHost final\n') + (ssh_home / "hosts" / "b.conf").write_text("Host second\nInclude config\n") + (ssh_home / "hosts" / "a.conf").write_text("Host first\nInclude hosts/b.conf\n") + result = discover_hosts(str(ssh_home / "config")) + assert [host["host"] for host in result["hosts"]] == ["first", "second", "final"] + assert len(result["files"]) == 3 + assert not result["incomplete"] + + +def test_default_config_is_found_without_pinning_a_custom_file(ssh_home): + (ssh_home / "config").write_text("Host default-test\n Port 2222\n") + result = discover_hosts() + host = next(host for host in result["hosts"] if host["host"] == "default-test") + assert host["ssh_config"] == "" + assert host["source"] == str(ssh_home / "config") + + +def test_discovery_never_runs_ssh_match_exec_or_proxy_commands(ssh_home, monkeypatch): + def forbidden(*args, **kwargs): + pytest.fail("Discovery must not execute anything") + + monkeypatch.setattr(subprocess, "run", forbidden) + monkeypatch.setattr(subprocess, "Popen", forbidden) + monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden) + config = ssh_home / "config" + config.write_text('Host safe\n Match exec "touch dangerous"\nProxyCommand command-not-returned\n') + assert [host["host"] for host in discover_hosts(str(config))["hosts"]] == ["safe"] + + +def test_unresolvable_includes_and_invalid_lines_do_not_hide_other_hosts(ssh_home): + config = ssh_home / "config" + config.write_text('Host ok\nInclude ${UNSET}/config %h.conf\nHost "unterminated\nHost good\n') + result = discover_hosts(str(config)) + assert [host["host"] for host in result["hosts"]] == ["ok", "good"] + assert result["incomplete"] + + +@pytest.mark.parametrize("contents", [b"\xff", b"x" * 262145]) +def test_unreadable_or_oversized_custom_config_is_an_explicit_error(ssh_home, contents): + path = ssh_home / "config" + path.write_bytes(contents) + with pytest.raises(RemoteError, match="ssh_config_unreadable"): + discover_hosts(str(path)) + + +def test_missing_explicit_config_is_not_silently_treated_as_empty(ssh_home): + with pytest.raises(RemoteError, match="local_file_not_found"): + discover_hosts(str(ssh_home / "missing")) + + +def test_host_limit_is_bounded_and_reported(ssh_home): + config = ssh_home / "config" + config.write_text("\n".join(f"Host host-{n}" for n in range(250))) + result = discover_hosts(str(config)) + assert len(result["hosts"]) == 200 + assert result["incomplete"] + + +def test_include_read_budget_is_bounded_and_reported(ssh_home): + config = ssh_home / "config" + config.write_text("Include large-*\nHost final\n") + for index in range(6): + (ssh_home / f"large-{index}").write_text(f"Host host-{index}\n#" + "x" * 250000) + result = discover_hosts(str(config)) + assert result["incomplete"] + assert len(result["files"]) == 5 # Root plus four complete included files. + assert result["hosts"][-1]["host"] == "final" + + +@pytest.mark.parametrize("path", ["\nsecret", "\x00bad", "x" * 2049]) +def test_invalid_paths_rejected_before_reading(path): + with pytest.raises(RemoteError, match="invalid_profile"): + discover_hosts(path) + + +@pytest.mark.parametrize(("override", "expected"), [(None, "2222"), (2200, "2200")]) +def test_system_ssh_inherits_config_port_user_and_identity(ssh_home, override, expected): + config = ssh_home / "config" + config.write_text("Host example-test\n HostName 192.0.2.10\n User tester\n Port 2222\n IdentityFile /tmp/test-key\n") + profile = RemoteProfile(name="Test", host="example-test", ssh_config=str(config), port=override) + # This controlled fixture has no Match exec; -G makes no network connections. + result = subprocess.run([*ssh_arguments(profile), "-G", profile.host], + capture_output=True, text=True, check=True) + settings = dict(line.split(" ", 1) for line in result.stdout.splitlines() if " " in line) + assert settings["port"] == expected + assert settings["user"] == "tester" + assert settings["identityfile"] == "/tmp/test-key" + + +async def test_manager_discovery_does_not_save_profiles_or_connect(ssh_home): + config = ssh_home / "config" + config.write_text("Host one\n") + manager = RemoteInstances(ssh_home / "webui") + result = await manager.action("discover", {"ssh_config": str(config)}) + assert result["hosts"][0]["host"] == "one" + assert not manager.path.exists() + assert not manager.connections diff --git a/webui/src/App.tsx b/webui/src/App.tsx index b7951a9ba..3b7ffd18f 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -13,6 +13,8 @@ import { Trans, useTranslation } from "react-i18next"; import { channelUiPresentation } from "@/channel-plugins/registry"; import { StarPrompt } from "@/components/StarPrompt"; import { Sidebar } from "@/components/Sidebar"; +import { RemoteInstances, useRemoteConnections } from "@/components/remote/RemoteInstances"; +import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage"; import { LanguageSwitcher } from "@/components/LanguageSwitcher"; import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/components/SidebarResizeHandle"; import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts"; @@ -130,7 +132,7 @@ const TOKEN_REFRESH_MIN_DELAY_MS = 5_000; const PAIRING_POLL_INTERVAL_MS = 5_000; const PAIRING_IDLE_POLL_INTERVAL_MS = 15_000; const PAIRING_DISMISS_SNOOZE_MS = 30_000; -type ShellView = "chat" | "settings" | "apps" | "automations" | "skills" | "channels"; +type ShellView = "chat" | "settings" | "apps" | "automations" | "skills" | "channels" | "remote"; type ShellRoute = { view: ShellView; activeKey: string | null; @@ -280,6 +282,9 @@ function readShellRoute(): ShellRoute { if (path === "/channels") { return { view: "channels", activeKey, temporary, settingsSection: "channels" }; } + if (path === "/remote") { + return { view: "remote", activeKey, temporary, settingsSection: "overview" }; + } if (path === "/skills") { return { view: "skills", activeKey, temporary, settingsSection: "skills" }; } @@ -1084,12 +1089,12 @@ export default function App() { modelName={state.modelName} ingressLimits={state.ingressLimits} > - + /> ); } @@ -1106,6 +1111,7 @@ function Shell({ onNativeEngineRestart: () => Promise; }) { const { t, i18n } = useTranslation(); + const localActive = useRemoteConnections()?.localActive !== false; const { client, getToken } = useClient(); const { theme, toggle } = useTheme(); const { @@ -2125,6 +2131,12 @@ function Shell({ setMobileSidebarOpen(false); }, [activeKey, navigate]); + const onOpenRemoteConnections = useCallback(() => { + setSessionSearchOpen(false); + navigate({ view: "remote", activeKey, settingsSection: "overview" }); + setMobileSidebarOpen(false); + }, [activeKey, navigate]); + const onOpenSkills = useCallback(() => { setSessionSearchOpen(false); navigate({ view: "skills", activeKey, settingsSection: "skills" }); @@ -2135,6 +2147,7 @@ function Shell({ const actions = { newChat: onNewChat, search: onOpenSessionSearch, apps: onOpenApps, skills: onOpenSkills, automations: onOpenAutomations, channels: onOpenChannels, settings: () => onOpenSettings() }; const handleKeyDown = (event: globalThis.KeyboardEvent) => { + if (!localActive) return; const action = matchSidebarShortcut(event); if (!action) return; event.preventDefault(); @@ -2142,7 +2155,7 @@ function Shell({ }; window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); - }, [onNewChat, onOpenSessionSearch, onOpenApps, onOpenSkills, onOpenAutomations, onOpenChannels, onOpenSettings]); + }, [localActive, onNewChat, onOpenSessionSearch, onOpenApps, onOpenSkills, onOpenAutomations, onOpenChannels, onOpenSettings]); const onSettingsSectionChange = useCallback( (section: SettingsSectionKey) => { @@ -2632,6 +2645,7 @@ function Shell({ }, [updateWorkbenchState]); useEffect(() => { + if (!localActive) return; if (view === "settings") { document.title = t("app.documentTitle.chat", { title: t("settings.sidebar.title"), @@ -2654,6 +2668,10 @@ function Shell({ document.title = t("app.documentTitle.chat", { title: t("settings.nav.channels") }); return; } + if (view === "remote") { + document.title = t("app.documentTitle.chat", { title: t("remote.title") }); + return; + } if (view === "skills") { document.title = t("app.documentTitle.chat", { title: t("settings.nav.skills", { defaultValue: "Skills" }), @@ -2663,7 +2681,7 @@ function Shell({ document.title = activeSession ? t("app.documentTitle.chat", { title: headerTitle }) : t("app.documentTitle.base"); - }, [activeSession, headerTitle, i18n.resolvedLanguage, t, view]); + }, [localActive, activeSession, headerTitle, i18n.resolvedLanguage, t, view]); const pinnedPaneKeys = useMemo( () => new Set(sidebarState.pinned_keys), @@ -2715,10 +2733,11 @@ function Shell({ onOpenApps, onOpenAutomations, onOpenChannels, + onOpenRemoteConnections, onOpenSkills, onSettingsIntent, onOpenSearch: onOpenSessionSearch, - activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" ? view : null, + activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" || view === "remote" ? view : null, onToggleArchived, pinnedKeys: sidebarPinnedTabKeys, archivedKeys: sidebarArchivedTabKeys, @@ -2747,7 +2766,7 @@ function Shell({ return ( - +
- + }> } {view !== "chat" && (
- }> + {view === "remote" ? : }> - + }
)} diff --git a/webui/src/components/Sidebar.tsx b/webui/src/components/Sidebar.tsx index be368c413..3f4752811 100644 --- a/webui/src/components/Sidebar.tsx +++ b/webui/src/components/Sidebar.tsx @@ -9,6 +9,7 @@ import { Brain, CalendarClock, MessageCircle, + MonitorUp, PanelLeftClose, Search, Settings, @@ -22,7 +23,8 @@ import { type SidebarDeleteItem, type SidebarPaneGroup, } from "@/components/ChatList"; -import { ConnectionBadge } from "@/components/ConnectionBadge"; +import { HostSwitcher } from "@/components/remote/HostSwitcher"; +import { useRemoteConnections } from "@/components/remote/RemoteInstances"; import { SIDEBAR_SELECTION_ACTION_ITEM_CLASS, SidebarSelectionHighlight, @@ -68,9 +70,10 @@ interface SidebarProps { onOpenSkills: () => void; onOpenAutomations: () => void; onOpenChannels: () => void; + onOpenRemoteConnections?: () => void; onSettingsIntent?: () => void; onOpenSearch: () => void; - activeUtility?: "apps" | "skills" | "automations" | "channels" | null; + activeUtility?: "apps" | "skills" | "automations" | "channels" | "remote" | null; onToggleArchived: () => void; onCollapse?: () => void; onExpand?: () => void; @@ -108,6 +111,7 @@ function isApplePlatform(): boolean { export function Sidebar(props: SidebarProps) { const { t } = useTranslation(); + const remoteConnections = useRemoteConnections(); const [menuPortalContainer, setMenuPortalContainer] = useState(null); const collapsed = Boolean(props.collapsed); @@ -253,6 +257,16 @@ export function Sidebar(props: SidebarProps) { selectionRef={activeActionRef} icon={} /> + {remoteConnections?.available && props.onOpenRemoteConnections && ( + } + /> + )} {props.archivedCount ? ( } /> - +
diff --git a/webui/src/components/remote/HostSwitcher.tsx b/webui/src/components/remote/HostSwitcher.tsx new file mode 100644 index 000000000..47066d235 --- /dev/null +++ b/webui/src/components/remote/HostSwitcher.tsx @@ -0,0 +1,106 @@ +import { createContext, useContext, useEffect, useRef, useState } from "react"; +import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Server, Settings2, X } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { Button } from "@/components/ui/button"; +import { ConnectionBadge } from "@/components/ConnectionBadge"; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; +import { useClient } from "@/providers/ClientProvider"; +import { cn } from "@/lib/utils"; +import type { ConnectionStatus } from "@/lib/types"; +import type { HostAnchor, EmbeddedHost } from "./host-bridge"; + +export interface HostPicker { + kind: "shell"; + name: string; + hostname: string; + localName: string; + currentId: string | null; + profiles: { id: string; name: string; host: string; ready: boolean }[]; + pending: { id: string; name: string } | null; + error: string; + offline: boolean; + select: (id: string | null) => void; + manage: () => void; + cancel: () => void; + clearError: () => void; + restoreFocus: () => void; +} +interface EmbeddedPicker extends EmbeddedHost { + kind: "embedded"; + open: (anchor: HostAnchor) => void; +} +export const HostNavigationContext = createContext(null); + +function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; portalContainer?: HTMLElement | null }) { + const { t } = useTranslation(); + return { event.preventDefault(); picker.restoreFocus(); }}> + {t("remote.switchHost")} + picker.select(null)} className="gap-2.5"> + + {t("remote.local")}{picker.localName} + {!picker.currentId && } + + {!!picker.profiles.length && } + {picker.profiles.map((profile) => picker.select(profile.id)} className="gap-2.5"> + + {profile.name}{profile.host} + {picker.pending?.id === profile.id ? : picker.currentId === profile.id ? + : profile.ready ? {t("remote.ready")} : null} + )} + {picker.pending && <>{t("remote.cancelSwitch")}} + {picker.error &&
+ {picker.error} +
} + + {t("remote.manageConnections")} +
; +} + +/** Shared sidebar control. Remote frames can only open the trusted shell's menu. */ +export function HostSwitcher({ collapsed = false, portalContainer }: { collapsed?: boolean; portalContainer?: HTMLElement | null }) { + const picker = useContext(HostNavigationContext); + const { client } = useClient(); + const { t } = useTranslation(); + const [status, setStatus] = useState(client.status); + useEffect(() => client.onStatus(setStatus), [client]); + const buttonRef = useRef(null); + if (!picker) return ; + const shell = picker.kind === "shell" ? picker : null; + const remote = picker.kind === "embedded" || !!shell?.currentId; + const pendingName = picker.kind === "shell" ? picker.pending?.name : picker.pendingName; + const failed = !!picker.error || !!shell?.offline || status === "error" || status === "closed"; + const waiting = !!pendingName || status === "connecting" || status === "reconnecting"; + const label = pendingName ? t("remote.connecting") : picker.name; + const detail = pendingName ? t("remote.preparing", { name: pendingName }) : `${picker.name} · ${picker.hostname}`; + const title = picker.error || `${detail} — ${t(failed ? "remote.offline" : `connection.${status}`)}`; + const button = ; + if (!shell) return button; + return {button}; +} + +/** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */ +export function RemoteHostMenu({ picker, anchor, onClose }: { picker: HostPicker; anchor: HostAnchor | null; onClose: () => void }) { + return { if (!open) onClose(); }}> + +

{t("remote.title")}

+ +
+

{t(showForm ? "remote.addDescription" : "remote.description")}

+ {directory?.available && <> + +
+ + {t("remote.local")} + {directory.machine_name && {directory.machine_name}} + {t("remote.current")} +
+
+ {showForm ?
{ event.preventDefault(); void save(); }} className="settings-stack"> +
+ {t(editingId ? "remote.edit" : "remote.addTitle")} + +
+ + setForm({ ...form, host })} /> + setForm({ ...form, name })} /> + + + + setForm({ ...form, port: port === "" ? null : Number(port) })} /> + {(["ssh_config", "identity_file", "config_path", "runtime_user"] as const).map((key) => + setForm({ ...form, [key]: value })} />)} + + +
+

{t("remote.keyHint")}

+ +
+
: null} + + } + {!directory && !directoryError &&
{t("remote.loading")}
} + {directory && !directory.available &&

{t("remote.unavailable")}

} + {pageError && !fingerprint &&
+

{pageError}

+ {directoryError && } +
} +
+ + + { if (!value && !busy) setDisconnecting(null); }}> + {t("remote.disconnectTitle", { name: disconnecting?.name })}{t("remote.disconnectDescription")} + {error &&

{error}

} +
+
+
+ { if (!value && !busy) setRemoving(null); }}> + {t("remote.forgetTitle", { name: removing?.name })}{t("remote.forgetDescription")} + {error &&

{error}

} +
+
+
+ { if (!value && !busy) setFingerprint(null); }}> + {t("remote.verifyTitle")}{t("remote.verifyDescription")} + {fingerprint?.fingerprint} +

{t("remote.verifyHint")}

+ {error &&

{error}

} +
+
+
+ ; +} + +function RemoteField({ label, onChange, ...props }: { + label: string; value: string; onChange: (value: string) => void; + placeholder?: string; required?: boolean; disabled?: boolean; type?: string; min?: number; max?: number; +}) { + const id = useId(); + return {label}}> + onChange(event.target.value)} autoComplete="off" spellCheck={false} /> + ; +} diff --git a/webui/src/components/remote/RemoteInstances.tsx b/webui/src/components/remote/RemoteInstances.tsx new file mode 100644 index 000000000..4dc954547 --- /dev/null +++ b/webui/src/components/remote/RemoteInstances.tsx @@ -0,0 +1,119 @@ +import { createContext, useContext, useEffect, useLayoutEffect, useRef, type ReactNode } from "react"; +import { Loader2, PlugZap } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { Button } from "@/components/ui/button"; +import type { RemoteDirectory } from "@/lib/remote-instances"; +import { useHostSessions } from "./useHostSessions"; +import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher"; +import { useSidebarHostBridge } from "./useSidebarHostBridge"; + +const RemoteContext = createContext<{ + available: boolean; + localActive: boolean; + openHostIds: string[]; + directory: RemoteDirectory | null; + directoryError: boolean; + refresh: () => Promise; + connect: (id: string, stillWanted?: () => boolean) => Promise; + disconnect: (id: string) => Promise; +} | null>(null); +export function useRemoteConnections() { return useContext(RemoteContext); } + +/** Keep host views alive; navigation belongs in each view's sidebar, not a second header. */ +export function RemoteInstances({ children }: { children: ReactNode }) { + const { t } = useTranslation(); + const hosts = useHostSessions(); + const { selected, pending, frames, directory, error } = hosts; + const localPanel = useRef(null); + const lastLocalFocus = useRef(null); + const frameNodes = useRef(new Map()); + const activeHostId = useRef(selected?.id); + activeHostId.current = selected?.id; + const restoreLocalFocus = () => { + if (lastLocalFocus.current?.isConnected) lastLocalFocus.current.focus({ preventScroll: true }); + }; + const message = error ? t(`remote.errors.${error}`, { defaultValue: t("remote.errors.unknown") }) : ""; + const bridge = useSidebarHostBridge(frames, selected?.id, frameNodes, restoreLocalFocus, { pendingName: pending?.name, error: message }); + const restoreFocus = () => { + if (activeHostId.current) bridge.focus(activeHostId.current); + else restoreLocalFocus(); + }; + const available = directory?.available === true || hosts.directoryError; + const activeFrame = frames.find((frame) => frame.connection.id === selected?.id); + const offline = !!selected && (activeFrame?.offline || (!activeFrame && !pending && !!error)); + const switchHost = (id: string) => { + void hosts.connect(id).catch((reason: unknown) => hosts.setError(reason instanceof Error ? reason.message : "unknown")); + }; + const picker: HostPicker = { + kind: "shell", name: selected?.name || t("remote.localShort"), hostname: selected?.hostname || directory?.machine_name || "nanobot", + localName: directory?.machine_name || "nanobot", currentId: selected?.id || null, + profiles: (directory?.profiles || []).map(({ id, name, host }) => ({ id, name, host, + ready: frames.some((frame) => frame.connection.id === id && !frame.offline && frame.loaded) })), + pending, error: message, offline: !!offline, select: (id) => { if (id) switchHost(id); else hosts.local(); }, + manage: () => { hosts.local(); window.location.hash = "/remote"; }, + cancel: hosts.cancel, clearError: () => hosts.setError(""), restoreFocus, + }; + useEffect(() => { if (selected) document.title = `${selected.name} · nanobot`; }, [selected]); + useEffect(() => { + const rememberFocus = (event: FocusEvent) => { + if (event.target instanceof HTMLElement && localPanel.current?.contains(event.target) + && !event.target.closest("[data-host-switcher]")) lastLocalFocus.current = event.target; + }; + document.addEventListener("focusin", rememberFocus); + return () => document.removeEventListener("focusin", rememberFocus); + }, []); + useLayoutEffect(() => { + if (selected) frameNodes.current.get(selected.id)?.focus({ preventScroll: true }); + else restoreLocalFocus(); + }, [selected]); + useEffect(() => { + if (!selected) return; + const stop = (event: KeyboardEvent) => event.stopPropagation(); + document.addEventListener("keydown", stop); + document.addEventListener("keyup", stop); + return () => { document.removeEventListener("keydown", stop); document.removeEventListener("keyup", stop); }; + }, [selected]); + + return frame.connection.id), + directoryError: hosts.directoryError, refresh: hosts.refresh, connect: hosts.connect, disconnect: hosts.disconnect }}> + +
+
+
+ {children} +
+ {frames.map((frame) => { + const active = selected?.id === frame.connection.id; + return
+