feat(webui): complete remote pairing and connection recovery

This commit is contained in:
Xubin Ren committed 2026-10-02 11:36:34 +08:00
1 parent 11889c018e
commit 192ca6e49e
52 files changed
+7313 -675

No files matched your search

+5
View File
@@ -97,6 +97,11 @@ app = typer.Typer(
console = Console()
# Server-console pairing stays outside the agent/gateway lifecycle.
from nanobot.cli.remote import app as remote_app # noqa: E402
app.add_typer(remote_app, name="remote")
def version_callback(value: bool):
if value:
console.print(f"{__logo__} nanobot v{__version__}")
+139
View File
@@ -0,0 +1,139 @@
"""Server-console commands for explicit remote WebUI device authorization."""
from __future__ import annotations
import ipaddress
import os
import subprocess
import sys
import time
from pathlib import Path
import typer
from click import IntRange
app = typer.Typer(help="Pair this server with a local nanobot. No public WebUI or relay.")
def _default_host() -> str:
"""Use only a globally reachable address reported by this SSH session.
A cloud's outbound address or a NAT/private address is not evidence of the
inbound SSH destination. Do not contact an external IP lookup service.
"""
fields = os.environ.get("SSH_CONNECTION", "").split()
try:
address = ipaddress.ip_address(fields[2]) if len(fields) == 4 else None
return str(address) if address and address.is_global else ""
except ValueError:
return ""
def _default_ssh_user() -> str | None:
"""Suggest the existing login account, including when invoked through sudo."""
import pwd
current = pwd.getpwuid(os.getuid())
if current.pw_uid:
return current.pw_name
users = [u.pw_name for u in pwd.getpwall() if 1000 <= u.pw_uid < 65534 and u.pw_shell.endswith(("/bash", "/sh", "/zsh"))]
sudo_user = os.environ.get("SUDO_USER")
if sudo_user in users:
return sudo_user
return users[0] if len(users) == 1 else None
@app.command()
def pair(
request: str = typer.Argument(help="Public pairing request copied from your local WebUI"),
host: str = typer.Option("", help="Server IP or hostname reachable from your computer"),
ssh_user: str = typer.Option("", help="Existing non-root SSH login account"),
port: int = typer.Option(22, min=1, max=65535, help="Existing SSH port; not changed"),
config: Path | None = typer.Option(None, help="Existing nanobot config; discovered if omitted"),
) -> None:
"""Run in your server terminal, then open the returned link on your computer."""
from nanobot.webui.remote_pairing import fingerprint, read_request, return_link
from nanobot.webui.remote_ssh import RemoteError
try:
if sys.platform != "linux":
raise RemoteError("pair_linux_required")
from nanobot.webui.remote_pair_server import authorize, metadata
invitation = read_request(request)
host_key = " ".join(Path("/etc/ssh/ssh_host_ed25519_key.pub").read_text().split()[:2])
if config is None:
from nanobot.webui.remote_discovery import (
_LOCATE, # pyright: ignore[reportPrivateUsage]
RemoteInspection,
)
result = subprocess.run([sys.executable, "-c", _LOCATE, str(Path.home() / ".nanobot/config.json")], capture_output=True, text=True, timeout=8)
records = [line.partition("NANOBOT_REMOTE:")[2] for line in result.stdout.splitlines() if "NANOBOT_REMOTE:" in line]
candidates = RemoteInspection.model_validate_json(records[-1]).candidates if records else []
if len(candidates) == 1:
config = Path(candidates[0].config_path)
elif candidates:
for index, item in enumerate(candidates, 1):
typer.echo(f'{index}. {item.service or "nanobot"} — {item.config_path}')
choice = int(typer.prompt("Which nanobot?", type=IntRange(1, len(candidates))))
config = Path(candidates[choice - 1].config_path)
else:
config = Path(typer.prompt("Path to your nanobot config"))
config = config.expanduser().resolve()
details = metadata(config)
if not ssh_user:
ssh_user = _default_ssh_user() or typer.prompt("SSH login account")
if not host:
host = _default_host() or typer.prompt("Server public IP or hostname (shown in your cloud console)")
typer.echo(f"\nAuthorize {invitation.label} to use nanobot on {ssh_user}@{host}?\nConfig: {config}\nServer fingerprint: {fingerprint(host_key)}")
typer.echo("This grants full nanobot WebUI access, including configured tools and settings.\nA dedicated SSH key can only reach this nanobot port; no shell or other forwarding.\nAuthorization lasts 90 days. No existing keys, firewall rules or model settings change.")
typer.confirm("Authorize this computer?", abort=True, default=False)
# Check the service is running before granting access; no credential is sent.
import socket
with socket.create_connection(("127.0.0.1", details["port"]), timeout=5):
pass
code = authorize(invitation, host=host, user=ssh_user, ssh_port=port, config=config,
host_key=host_key, until=int(time.time()) + 90 * 86400)
link = return_link(invitation, code)
if link:
typer.echo("\nReturn to nanobot on your computer to finish connecting:")
typer.echo("Open this link in the same computer/browser that started pairing.\n")
typer.echo(link)
typer.echo("\nIf your terminal cannot open links, paste this connection code into nanobot:\n")
else:
typer.echo("\nPaste this connection code into the same local nanobot window:\n")
typer.echo(code)
typer.echo(f"\nTo revoke new connections: nanobot remote revoke {invitation.id} --ssh-user {ssh_user}")
typer.echo("Close any already-open remote sessions as well. Re-pair after changing the WebUI secret or port.")
except (OSError, ValueError, KeyError, subprocess.SubprocessError, RemoteError) as exc:
typer.echo(f"Pairing not completed: {str(exc) if isinstance(exc, RemoteError) else 'check server config, login account and SSH installation'}. Existing settings were not reset.", err=True)
if str(exc) == "config_permission":
typer.echo("The nanobot config belongs to another account. Run this command in its installation environment as the server administrator, or ask that administrator to pair it. Do not make the config publicly readable.", err=True)
raise typer.Exit(1) from None
@app.command()
def revoke(device: str, ssh_user: str = typer.Option("", help="SSH account used when pairing")) -> None:
"""Remove only this device's managed SSH authorization, preserving other keys."""
import getpass
from nanobot.webui.remote_ssh import RemoteError
try:
if sys.platform != "linux":
raise RemoteError("pair_linux_required")
from nanobot.webui.remote_pair_server import as_account
user = ssh_user or getpass.getuser()
typer.confirm(f"Revoke device {device} for SSH account {user}?", abort=True, default=False)
as_account(user, "revoke", {"id": device})
typer.echo("Authorization removed. Already-open SSH sessions must also be closed.")
except (OSError, KeyError, RemoteError, subprocess.SubprocessError):
typer.echo("Could not revoke. Check the device ID and run as the SSH account or server administrator.", err=True)
raise typer.Exit(1) from None
if __name__ == "__main__":
app()
+32 -14
View File
@@ -1,4 +1,4 @@
"""Native directory picker used by a locally hosted WebUI."""
"""Native path pickers used by a locally hosted WebUI; never read file contents."""
from __future__ import annotations
@@ -9,6 +9,7 @@ import sys
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Literal
_PICKER_TIMEOUT_SECONDS = 300
_COMMON_ENV_KEYS = (
@@ -66,7 +67,8 @@ class _PickerCommand:
cancel_markers: tuple[str, ...] = ()
def _picker_command() -> _PickerCommand | None:
def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerCommand | None:
title = "Select Workspace Directory" if kind == "folder" else "Select SSH key or configuration file"
if sys.platform == "darwin":
executable = shutil.which("osascript")
if executable is None:
@@ -75,9 +77,9 @@ def _picker_command() -> _PickerCommand | None:
argv=(
executable,
"-e",
'set selectedFolder to choose folder with prompt "Select Workspace Directory"',
f'set selectedPath to choose {kind} with prompt "{title}"',
"-e",
"POSIX path of selectedFolder",
"POSIX path of selectedPath",
),
cancel_codes=frozenset({1}),
cancel_markers=("user canceled", "(-128)"),
@@ -87,14 +89,22 @@ def _picker_command() -> _PickerCommand | None:
executable = shutil.which("powershell.exe") or shutil.which("powershell")
if executable is None:
return None
dialog = (
"$dialog=New-Object System.Windows.Forms.FolderBrowserDialog;"
f"$dialog.Description='{title}';"
"$dialog.ShowNewFolderButton=$true;"
) if kind == "folder" else (
"$dialog=New-Object System.Windows.Forms.OpenFileDialog;"
f"$dialog.Title='{title}';"
"$dialog.CheckFileExists=$true;$dialog.Multiselect=$false;"
)
selected = "SelectedPath" if kind == "folder" else "FileName"
script = (
"Add-Type -AssemblyName System.Windows.Forms;"
"$dialog=New-Object System.Windows.Forms.FolderBrowserDialog;"
"$dialog.Description='Select Workspace Directory';"
"$dialog.ShowNewFolderButton=$true;"
+ dialog +
"if($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK){"
"[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();"
"[Console]::Out.Write($dialog.SelectedPath)}"
f"[Console]::Out.Write($dialog.{selected})}}"
)
return _PickerCommand(
argv=(
@@ -117,15 +127,15 @@ def _picker_command() -> _PickerCommand | None:
argv=(
zenity,
"--file-selection",
"--directory",
"--title=Select Workspace Directory",
*(("--directory",) if kind == "folder" else ()),
f"--title={title}",
),
cancel_codes=frozenset({1}),
)
kdialog = shutil.which("kdialog")
if kdialog is not None:
return _PickerCommand(
argv=(kdialog, "--getexistingdirectory", str(Path.home())),
argv=(kdialog, "--getexistingdirectory" if kind == "folder" else "--getopenfilename", str(Path.home())),
cancel_codes=frozenset({1}),
)
return None
@@ -167,7 +177,15 @@ async def _stop_process(process: asyncio.subprocess.Process) -> None:
async def pick_native_folder() -> str | None:
"""Open the platform directory picker and return an existing absolute path."""
command = _picker_command()
return await _pick_native_path(_picker_command(), "directory")
async def pick_native_file() -> str | None:
"""Choose an existing local file without opening, uploading or copying it."""
return await _pick_native_path(_picker_command("file"), "file")
async def _pick_native_path(command: _PickerCommand | None, kind: str) -> str | None:
if command is None:
raise NativeFolderPickerError("native folder picker is unavailable on this host")
@@ -206,6 +224,6 @@ async def pick_native_folder() -> str | None:
if not selected:
return None
path = Path(selected).expanduser()
if not path.is_absolute() or not path.is_dir():
raise NativeFolderPickerError("native folder picker returned an invalid directory")
if not path.is_absolute() or not (path.is_dir() if kind == "directory" else path.is_file()):
raise NativeFolderPickerError(f"native path picker returned an invalid {kind}")
return str(path)
+133
View File
@@ -0,0 +1,133 @@
"""Locate remote nanobot configurations without reading credentials or using sudo.
Only the selected account's config and named nanobot systemd units are inspected.
An alternate service account is returned as a choice, never silently impersonated.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, run_check
_LOCATE = r'''
import getpass, json, os, pathlib, re, shlex, socket, stat, subprocess, sys
try:
import pwd
except ImportError:
pwd = None
candidates = []
incomplete = False
current_user = pwd.getpwuid(os.getuid()).pw_name if pwd else getpass.getuser()
def add(path, user="", service=""):
global incomplete
if len(candidates) >= 8:
incomplete = True
return
try:
path = pathlib.Path(path).expanduser()
if not path.is_absolute():
return
exists = stat.S_ISREG(path.stat().st_mode)
except PermissionError:
# A declared service config can be offered even when the SSH account
# cannot stat it. The later explicit choice still needs sudo permission.
exists = bool(service)
except (OSError, ValueError):
return
user = "" if user == current_user else user
item = {"config_path": str(path), "runtime_user": user, "service": service}
if exists and not any(x["config_path"] == item["config_path"] and x["runtime_user"] == user for x in candidates):
candidates.append(item)
add(sys.argv[1])
def systemctl(*args):
result = subprocess.run(["systemctl", *args, "--no-pager"],
capture_output=True, text=True, timeout=2)
if result.returncode:
raise OSError("systemctl unavailable")
return result.stdout
try:
units = [line.split()[0] for line in systemctl("list-units", "--all", "--plain", "--no-legend", "nanobot*.service").splitlines() if line.split()]
units = [name for name in units if re.fullmatch(r"nanobot[a-zA-Z0-9_.@-]*\.service", name)]
incomplete = len(units) > 8
if units and pwd:
records = systemctl("show", *units[:8], "--property=Id,User,ExecStart,WorkingDirectory")
for block in records.strip().split("\n\n"):
fields = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
service = fields.get("Id", "")
if service not in units[:8]:
continue
user = fields.get("User") or "root"
if not re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_-]*", user):
continue
try:
home = pathlib.Path(pwd.getpwnam(user).pw_dir)
tokens = shlex.split(fields.get("ExecStart", ""))
except (KeyError, ValueError):
incomplete = True
continue
config = None
for index, token in enumerate(tokens):
if token.startswith("--config="):
config = token.split("=", 1)[1]
break
if token in {"--config", "-c"} and index + 1 < len(tokens):
config = tokens[index + 1]
break
if config and ("$" in config or "%" in config):
incomplete = True
continue
if config:
if config.startswith("~/"):
path = home / config[2:]
elif pathlib.Path(config).is_absolute():
path = pathlib.Path(config)
else:
path = pathlib.Path(fields.get("WorkingDirectory") or str(home)) / config
else:
path = home / ".nanobot/config.json"
add(path, user, service)
except (OSError, subprocess.TimeoutExpired):
incomplete = True
print("\n\x1eNANOBOT_REMOTE:" + json.dumps({"hostname": socket.gethostname(), "candidates": candidates, "incomplete": incomplete}))
'''
class RemoteLocation(BaseModel):
model_config = ConfigDict(extra="ignore", strict=True)
config_path: str = Field(min_length=1, max_length=2048)
runtime_user: str = Field(default="", max_length=64, pattern=r"^([a-zA-Z_][a-zA-Z0-9_-]*)?$")
service: str = Field(default="", max_length=256, pattern=r"^([a-zA-Z0-9_.@-]+\.service)?$")
@field_validator("config_path")
@classmethod
def safe_path(cls, value: str) -> str:
return RemoteProfile.safe_path(value)
class RemoteInspection(BaseModel):
model_config = ConfigDict(extra="ignore", strict=True)
hostname: str = Field(min_length=1, max_length=253)
candidates: list[RemoteLocation] = Field(max_length=8)
incomplete: bool
async def inspect(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]:
# Inspection is always performed as the SSH login, even when an old profile
# has a service account. Discovery must not implicitly escalate privileges.
result = await run_check(profile.model_copy(update={"runtime_user": ""}), _LOCATE, known_hosts)
try:
return RemoteInspection.model_validate(result).model_dump()
except ValidationError:
raise RemoteError("probe_failed") from None
+263 -46
View File
@@ -18,13 +18,18 @@ 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_proxy import RemoteProxy
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, Tunnel
_HEALTH_TIMEOUT_SECONDS = 12
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)
proxy_origin: bool = False
pair_id: str = ""
@dataclass
@@ -34,7 +39,9 @@ class Connection:
hostname: str
config_path: str
gateway_id: str
proxy: RemoteProxy
error: str = ""
paired: bool = False
class RemoteInstances:
@@ -43,11 +50,19 @@ class RemoteInstances:
def __init__(self, directory: Path, *, local_gateway_id: str = "") -> None:
self.path = directory / "remote-instances.json"
self.local_gateway_id = local_gateway_id
# Public identity, not an authentication capability. A new local manager
# cannot renew a cached iframe's old proxy credentials after restart.
self._view_session = uuid.uuid4().hex
self.connections: dict[str, Connection] = {}
self._proxies: dict[int, RemoteProxy] = {}
self._lock = asyncio.Lock()
self._picker_lock = asyncio.Lock()
self._unverified: dict[str, tuple[str, str, float]] = {}
self._unknown_hosts: set[str] = set()
self._closed = False
from nanobot.webui.remote_pairing import PairStore
self.pairing = PairStore(directory)
def _known_hosts(self, key: str) -> Path:
return self.path.parent / "remote-hosts" / key
@@ -75,39 +90,108 @@ class RemoteInstances:
))
self.path.chmod(0o600)
def _remember_origins(self, profiles: dict[str, _SavedProfile], port: int = 0) -> set[int]:
# Browser storage outlives edits, Forget and gateway restarts. Keep a
# small append-only port ledger, including pre-ledger saved profiles,
# so a new target never inherits a retired target's browser origin.
path = self.path.with_name("remote-origin-ports.json")
try:
raw: object = json.loads(path.read_text()) if path.exists() else []
if not isinstance(raw, list):
raise ValueError
ports: set[int] = set()
for value in cast(list[object], raw):
if type(value) is not int or not 1 <= value <= 65535:
raise ValueError
ports.add(value)
except (ValueError, TypeError, OSError):
raise RemoteError("profile_store_invalid") from None
ports.update(profile.local_port for profile in profiles.values() if profile.local_port)
if port:
ports.add(port)
path.parent.mkdir(parents=True, exist_ok=True)
_write_text_atomic(path, json.dumps(sorted(ports)))
path.chmod(0o600)
return ports
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()
]}
profiles: list[dict[str, Any]] = []
for key, profile in self._read().items():
connection = self.connections.get(key)
error = (connection.error or ("" if connection.tunnel.active else "ssh_unreachable")) if connection else "disconnected"
item = {"id": key, **profile.model_dump(exclude={"local_port", "proxy_origin", "pair_id"}),
"connected": connection is not None and not error,
"connection_error": error}
if connection:
item["gateway_id"] = connection.gateway_id
item["view_id"] = self._view_session
if profile.pair_id:
item.update(paired=True, revoke_command=
f"nanobot remote revoke {profile.pair_id} --ssh-user {profile.host.split('@')[0]}")
expiry = self.pairing.authorization_until(profile.pair_id)
if expiry is not None:
item["authorized_until"] = expiry
profiles.append(item)
return {"available": True, "machine_name": socket.gethostname(), "profiles": profiles}
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:
# Hold a lifetime lease through every credential-bearing request. Final
# shutdown cannot release the listeners halfway through a health check.
try:
# Includes lock contention and all response reads, not just each
# socket read. Return the directory before the browser's 20s budget.
async with asyncio.timeout(_HEALTH_TIMEOUT_SECONDS):
async with self._lock:
await asyncio.gather(*(self._check(item) for item in self.connections.values()))
except TimeoutError:
pass
return self.snapshot()
async def _check(self, connection: Connection) -> None:
if not connection.tunnel.active:
connection.error = "ssh_unreachable"
return
try:
async with httpx.AsyncClient(timeout=20, 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 in {401, 403}:
connection.error = "remote_auth_failed"
elif response.status_code != 200:
connection.error = "remote_unreachable"
else:
raw_identity = response.json()
identity = cast(dict[str, Any], raw_identity) if isinstance(raw_identity, dict) else {}
if (type(identity.get("protocolVersion")) is not int
or identity.get("protocolVersion") != 1 or not isinstance(identity.get("gatewayId"), str)):
connection.error = "incompatible_gateway"
elif identity["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()
except (httpx.HTTPError, ValueError, AttributeError):
connection.error = connection.tunnel.error or "remote_unreachable"
if connection.paired and connection.error == "ssh_auth_failed":
connection.error = "pair_authorization_rejected"
except asyncio.CancelledError:
connection.error = "remote_unreachable"
raise
async def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
if action == "pick_file":
from nanobot.webui.native_folder_picker import NativeFolderPickerError, pick_native_file
if self._closed or self._picker_lock.locked():
raise RemoteError("file_picker_unavailable")
# The route is authenticated and loopback-only. No caller-provided
# command, file content or initial directory enters the OS dialog.
async with self._picker_lock:
try:
return {"path": await pick_native_file()}
except NativeFolderPickerError:
raise RemoteError("file_picker_unavailable") from None
if action == "discover":
from nanobot.webui.ssh_config import discover_hosts
@@ -121,31 +205,114 @@ class RemoteInstances:
raise RemoteError("local_io_error")
profiles = self._read()
key = str(payload.get("id", ""))
if action == "pair_start":
return_origin = payload.get("return_origin", "")
if not isinstance(return_origin, str):
raise RemoteError("pair_invalid")
return self.pairing.start(return_origin)
if action == "pair_cancel":
self.pairing.cancel(key)
return {"cancelled": True}
if action in {"pair_preview", "pair_finish"}:
code = payload.get("code", "")
if not isinstance(code, str):
raise RemoteError("pair_invalid")
if action == "pair_preview":
return self.pairing.preview(key, code)
if len(profiles) >= 20 and key not in profiles:
raise RemoteError("profile_limit")
# Completion is idempotent. No browser-provided host/path/key is
# trusted as a substitute for the encrypted server receipt.
if key in profiles:
return {"id": key, **self.snapshot()}
receipt = self.pairing.finish(key, code)
profile = self.pairing.profile(receipt)
known = self._known_hosts(key)
known.parent.mkdir(parents=True, exist_ok=True)
_write_text_atomic(known, "nanobot-remote " + receipt.host_key + "\n")
known.chmod(0o600)
profiles[key] = _SavedProfile(**profile.model_dump(), pair_id=key)
self._write(profiles)
return {"id": key, **self.snapshot()}
if action == "save":
profile = RemoteProfile.model_validate(payload.get("profile"))
if key and key not in profiles:
raise RemoteError("profile_not_found")
if key and profiles[key].pair_id:
raise RemoteError("pair_managed")
if key and profiles[key].model_dump(include=set(RemoteProfile.model_fields)) == profile.model_dump():
# Retrying a slow browser load must not count as editing a
# live SSH connection. Real changes still require disconnect.
return {"id": key, **self.snapshot()}
if not key:
destination = profile.model_dump(exclude={"name"})
for saved_key, saved in profiles.items():
if saved.model_dump(include=set(destination)) == destination:
# Reopening Add after a failed attempt should reuse
# its entry, without renaming it or closing live views.
return {"id": saved_key, **self.snapshot()}
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")
connection = self.connections.get(key)
if connection:
if connection.tunnel.active and not connection.error:
raise RemoteError("disconnect_before_edit")
# A fresh tab offers Edit for an offline profile. Release its
# failed tunnel here instead of demanding a hidden Disconnect.
await connection.proxy.pause()
del self.connections[key]
target_changed = key in profiles and any(
getattr(profiles[key], field) != getattr(profile, field)
for field in ("host", "port", "ssh_config")
)
instance_changed = target_changed or (key in profiles and any(
getattr(profiles[key], field) != getattr(profile, field)
for field in ("config_path", "runtime_user", "identity_file")
))
if instance_changed:
self._remember_origins(profiles)
local_port = profiles[key].local_port if key in profiles and not instance_changed else 0
proxy_origin = bool(local_port and profiles[key].proxy_origin)
profiles[key] = _SavedProfile(**profile.model_dump(), local_port=local_port,
proxy_origin=proxy_origin)
self._write(profiles)
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":
if action == "pair_route":
profile = profiles[key]
if not profile.pair_id:
raise RemoteError("pair_invalid")
existing = self.connections.get(key)
if existing and existing.tunnel.active and not existing.error:
raise RemoteError("disconnect_before_edit")
route_id = str(payload.get("route_id", ""))
if route_id:
source = profiles.get(route_id)
if source is None or source.pair_id:
raise RemoteError("profile_not_found")
config = await remote_ssh.pairing_route(source, profile.host.split("@")[-1])
path = self.pairing.path(profile.pair_id) / "ssh_route"
_write_text_atomic(path, config)
path.chmod(0o600)
profile.ssh_config = str(path)
else:
profile.ssh_config = ""
self._write(profiles)
return self.snapshot()
if action in {"connect", "inspect"}:
try:
if action == "inspect":
if profiles[key].pair_id:
raise RemoteError("pair_managed")
from nanobot.webui.remote_discovery import inspect
return await inspect(profiles[key], self._known_hosts(key))
return await self._connect(key, profiles[key])
except RemoteError as exc:
if str(exc) == "host_key_unknown":
@@ -175,8 +342,11 @@ class RemoteInstances:
if action in {"disconnect", "remove"}:
connection = self.connections.pop(key, None)
if connection:
await connection.tunnel.close()
await connection.proxy.pause()
if action == "remove":
self._remember_origins(profiles)
if profiles[key].pair_id:
self.pairing.forget(profiles[key].pair_id)
del profiles[key]
self._write(profiles)
self._known_hosts(key).unlink(missing_ok=True)
@@ -188,25 +358,41 @@ class RemoteInstances:
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}
"url": f"{connection.proxy.origin}/#/?bootstrapSecret={quote(connection.proxy.secret, safe='')}",
"gateway_id": connection.gateway_id, "view_id": self._view_session}
async def _connect(self, key: str, profile: _SavedProfile) -> dict[str, Any]:
existing = self.connections.get(key)
if existing:
await self.health()
await self._check(existing)
if not existing.error:
return self._launch(key, profile, existing)
await existing.tunnel.close()
await existing.proxy.pause()
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)
transport: RemoteProfile = profile
if profile.pair_id:
data = self.pairing.connection(profile.pair_id)
transport = remote_ssh.PairedSSHProfile(**profile.model_dump(include=set(RemoteProfile.model_fields)))
else:
data = await remote_ssh.probe(profile, known_hosts)
used_ports = self._remember_origins(self._read())
# Retire browser origins from the earlier transparent tunnel. Those
# origins may still contain remote secrets in old tabs/localStorage.
local_port = profile.local_port if profile.proxy_origin else 0
proxy = self._proxies.get(local_port)
if proxy is not None:
tunnel = proxy.tunnel
tunnel.resume(transport, data["port"], known_hosts)
else:
tunnel = await remote_ssh.open_tunnel(
transport, data["port"], known_hosts, excluded_ports=used_ports,
)
base = f"http://127.0.0.1:{tunnel.port}"
try:
async with httpx.AsyncClient(timeout=8, trust_env=False, follow_redirects=False) as client:
async with httpx.AsyncClient(timeout=20, trust_env=False, follow_redirects=False) as client:
response = await client.get(
f"{base}/webui/terminal", headers={"X-Nanobot-Auth": data["secret"]},
)
@@ -218,28 +404,58 @@ class RemoteInstances:
if not isinstance(raw_identity, dict):
raise RemoteError("incompatible_gateway")
identity = cast(dict[str, Any], raw_identity)
if (identity.get("protocolVersion") != 1
if (type(identity.get("protocolVersion")) is not int or 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")
# SSH aliases identify routes, not nanobot instances. Don't open
# two independent browser views of the same live gateway.
if any(item.gateway_id == identity["gatewayId"]
for item in self.connections.values()):
raise RemoteError("duplicate_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")
issue_path = data.get("token_issue_path", "")
if not isinstance(issue_path, str):
raise RemoteError("incompatible_gateway")
if proxy is None:
proxy = await RemoteProxy.open(
tunnel, data["secret"], identity["gatewayId"], issue_path,
local_port=local_port, excluded_ports=used_ports,
)
else:
proxy.resume(data["secret"], identity["gatewayId"], issue_path)
connection = Connection(
tunnel, data["secret"], str(data.get("hostname", profile.host)),
str(data.get("config_path", profile.config_path)), identity["gatewayId"],
str(data.get("config_path", profile.config_path)), identity["gatewayId"], proxy,
paired=bool(profile.pair_id),
)
profiles = self._read()
profiles[key].local_port = tunnel.port
self._remember_origins(profiles, proxy.port)
profiles[key].local_port = proxy.port
profiles[key].proxy_origin = True
self._write(profiles)
self._proxies[proxy.port] = proxy
self.connections[key] = connection
return self._launch(key, profile, connection)
except BaseException as exc:
await tunnel.close()
if proxy is not None and proxy.port in self._proxies:
await proxy.pause()
else:
# No launch URL has been returned for this new origin. All
# internal HTTP requests have finished; retaining it would leak
# a listener on every failed attempt with local_port still zero.
if proxy is not None:
await proxy.close()
else:
await tunnel.close()
if isinstance(exc, httpx.HTTPError):
raise RemoteError("remote_unreachable") from None
if profile.pair_id and tunnel.error == "ssh_auth_failed":
raise RemoteError("pair_authorization_rejected") from None
raise RemoteError(tunnel.error or "remote_unreachable") from None
if isinstance(exc, ValueError):
raise RemoteError("incompatible_gateway") from None
raise
@@ -247,5 +463,6 @@ class RemoteInstances:
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()))
proxies, self._proxies = self._proxies, {}
self.connections.clear()
await asyncio.gather(*(proxy.close() for proxy in proxies.values()))
+213
View File
@@ -0,0 +1,213 @@
"""Explicit server-side authorization for relay-free remote WebUI pairing.
Only an already-authorized server operator runs this module. No daemon, sudoers
rule, listener or SSH policy is installed. The dedicated key executes one fixed
stdio bridge, with all OpenSSH forwarding and interactive features disabled.
"""
from __future__ import annotations
import datetime
import fcntl
import json
import os
import shlex
import socket
import stat
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any
from nanobot.webui.remote_pairing import PairReceipt, PairRequest, private_write, public_key, seal
from nanobot.webui.remote_ssh import RemoteError
# No dynamic command, destination or environment input is accepted by the bridge.
# SSH_ORIGINAL_COMMAND is deliberately ignored. Each invocation is one TCP stream.
_BRIDGE = '''import os, socket, threading
s = socket.create_connection(("127.0.0.1", PORT), timeout=10)
s.settimeout(None)
def send():
try:
while True:
data = os.read(0, 65536)
if not data:
break
s.sendall(data)
s.shutdown(socket.SHUT_WR)
except OSError:
s.close()
threading.Thread(target=send, daemon=True).start()
try:
while True:
data = s.recv(65536)
if not data:
break
while data:
data = data[os.write(1, data):]
finally:
s.close()
'''
def metadata(config: Path) -> dict[str, Any]:
"""Read only the WebUI credential out of the operator-selected config."""
try:
raw = json.loads(config.read_text())
ws = raw.get("channels", {}).get("websocket", {})
secret = ws.get("tokenIssueSecret") or ws.get("token_issue_secret") or ws.get("token")
if not ws.get("enabled") or not isinstance(secret, str) or not secret.strip() or "${" in secret:
raise RemoteError("webui_auth_required")
if ws.get("publicWsUrl") or ws.get("public_ws_url") or ws.get("trustedProxyAuth") or ws.get("trusted_proxy_auth"):
raise RemoteError("incompatible_gateway")
port = ws.get("port", 8765)
if type(port) is not int or not 1 <= port <= 65535:
raise ValueError
return {"port": port, "secret": secret, "hostname": socket.gethostname(),
"config_path": str(config.resolve()),
"token_issue_path": ws.get("tokenIssuePath") or ws.get("token_issue_path") or ""}
except PermissionError:
raise RemoteError("config_permission") from None
except (OSError, ValueError, TypeError, AttributeError):
raise RemoteError("config_invalid") from None
def _directory(path: Path) -> None:
if path.is_symlink():
raise RemoteError("pair_ssh_layout")
path.mkdir(mode=0o700, exist_ok=True)
info = path.stat()
if info.st_uid != os.getuid() or info.st_mode & 0o022:
raise RemoteError("pair_ssh_layout")
def write_authorization(home: Path, request: PairRequest, port: int, until: int) -> None:
"""Runs as the SSH account, never with root privileges over another home."""
request.check_expiry()
ssh = home / ".ssh"
_directory(ssh)
root = ssh / "nanobot-remote"
_directory(root)
target = root / request.id
# Only our lock file; do not change permissions/content of unrelated keys.
lock = os.open(root / "lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
with os.fdopen(lock, "r+") as guard:
fcntl.flock(guard, fcntl.LOCK_EX)
if target.exists():
raise RemoteError("pair_used")
target.mkdir(mode=0o700)
try:
bridge = target / "bridge.py"
private_write(bridge, _BRIDGE.replace("PORT", str(port)).encode())
command = shlex.join(["/usr/bin/python3", "-I", "-S", str(bridge)]).replace("\\", "\\\\").replace('"', '\\"')
expiry = datetime.datetime.fromtimestamp(until, datetime.UTC).strftime("%Y%m%d%H%M%SZ")
line = f'restrict,expiry-time="{expiry}",command="{command}" {request.ssh_key} nanobot-remote:{request.id}\n'
private_write(target / "authorization", line.encode())
_update_keys(ssh / "authorized_keys", add=line)
except BaseException:
# Never remove an existing directory or unrelated key on rollback.
for name in ("bridge.py", "authorization"):
(target / name).unlink(missing_ok=True)
target.rmdir()
raise
def _update_keys(path: Path, *, add: str = "", remove: str = "") -> None:
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "r+") as handle:
info = os.fstat(handle.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_nlink != 1 or info.st_mode & 0o022:
raise RemoteError("pair_ssh_layout")
fcntl.flock(handle, fcntl.LOCK_EX)
original = handle.read(1024 * 1024 + 1)
if len(original) > 1024 * 1024:
raise RemoteError("pair_ssh_layout")
if add:
handle.seek(0, 2)
handle.write(("\n" if original and not original.endswith("\n") else "") + add)
else:
# Exact managed line, not a substring/comment match.
replacement = "".join(line for line in original.splitlines(keepends=True) if line != remove)
if replacement == original:
return
temporary_fd, temporary_name = tempfile.mkstemp(prefix=".nanobot-revoke-", dir=path.parent)
try:
with os.fdopen(temporary_fd, "w") as output:
output.write(replacement)
output.flush()
os.fsync(output.fileno())
os.fchmod(output.fileno(), stat.S_IMODE(info.st_mode))
os.replace(temporary_name, path)
finally:
Path(temporary_name).unlink(missing_ok=True)
handle.flush()
os.fsync(handle.fileno())
def remove_authorization(home: Path, key: str) -> None:
from nanobot.webui.remote_pairing import PairStore
# Validate before joining any path, even for a manually typed revoke command.
PairStore(home).path(key)
root = home / ".ssh" / "nanobot-remote"
_directory(home / ".ssh")
_directory(root)
target = root / key
if target.is_symlink() or not target.is_dir():
raise RemoteError("pair_invalid")
lock = os.open(root / "lock", os.O_RDWR | os.O_NOFOLLOW)
with os.fdopen(lock, "r+") as guard:
fcntl.flock(guard, fcntl.LOCK_EX)
line = (target / "authorization").read_text()
if not line.endswith(f" nanobot-remote:{key}\n") or "\n" in line[:-1]:
raise RemoteError("pair_invalid")
_update_keys(home / ".ssh/authorized_keys", remove=line)
# Keep the non-secret receipt/bridge for an auditable, retryable revoke.
def as_account(user: str, operation: str, data: dict[str, Any]) -> None:
import pwd
account = pwd.getpwnam(user)
if account.pw_uid == 0 or account.pw_shell.endswith(("/nologin", "/false")):
raise RemoteError("pair_login_user")
if os.getuid() not in (0, account.pw_uid):
raise RemoteError("config_permission")
child = dict(data, home=account.pw_dir, operation=operation)
# Drop all supplementary groups *before* any write in a user-owned home.
options: dict[str, Any] = {}
if os.getuid() == 0:
options = {"user": account.pw_uid, "group": account.pw_gid, "extra_groups": []}
result = subprocess.run(
[sys.executable, "-m", "nanobot.webui.remote_pair_server"],
input=json.dumps(child), text=True, capture_output=True, timeout=20, **options,
)
if result.returncode:
code = result.stdout.strip()
raise RemoteError(code if code in {"pair_used", "pair_expired", "pair_ssh_layout", "pair_invalid"} else "pair_install_failed")
def authorize(request: PairRequest, *, host: str, user: str, ssh_port: int,
config: Path, host_key: str, until: int) -> str:
request.check_expiry()
receipt = PairReceipt(id=request.id, ssh_key=request.ssh_key, host=host, user=user,
ssh_port=ssh_port, host_key=public_key(host_key), authorized_until=until,
**metadata(config))
encrypted = seal(request, receipt) # Fail crypto/validation before authorizing anything.
as_account(user, "install", {"request": request.model_dump(), "port": receipt.port, "until": until})
return encrypted
if __name__ == "__main__":
try:
data = json.loads(sys.stdin.read(32768))
if data["operation"] == "install":
write_authorization(Path(data["home"]), PairRequest.model_validate(data["request"]), data["port"], data["until"])
elif data["operation"] == "revoke":
remove_authorization(Path(data["home"]), data["id"])
else:
raise RemoteError("pair_invalid")
except Exception as exc:
print(str(exc) if isinstance(exc, RemoteError) else "pair_install_failed")
sys.exit(1)
+322
View File
@@ -0,0 +1,322 @@
"""Copy/paste pairing protocol. Private material never enters the WebUI response.
The request is public. A receipt is encrypted for the requesting local instance;
its provenance is the user's trusted server terminal, not a public relay. SSH's
host key is pinned from that receipt before any credential-bearing connection.
"""
from __future__ import annotations
import base64
import hashlib
import json
import os
import re
import secrets
import socket
import time
import uuid
from pathlib import Path
from typing import Any, cast
from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ed25519, x25519
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile
_TTL = 600
_CONTEXT = b"nanobot-remote-pair-v1"
def local_return_origin(value: str) -> str:
"""Only the local top-level WebUI can receive a pairing link. No redirects."""
if value == "":
return value
match = re.fullmatch(r"http://(127\.0\.0\.1|localhost|\[::1\])(?::([0-9]{1,5}))?", value)
if not match or (match[2] is not None and not 1 <= int(match[2]) <= 65535):
raise ValueError("local return address required")
return value
def return_link(request: PairRequest, code: str) -> str:
# Fragment data is never sent in the HTTP request or Referer. The frontend
# scrubs it before authentication and still requires a confirmation.
if not request.return_origin:
return ""
if not re.fullmatch(r"nbpc1\.[A-Za-z0-9_-]{1,32762}", code):
raise RemoteError("pair_invalid")
return f"{local_return_origin(request.return_origin)}/#/remote?pairing={code}"
def encode(value: bytes) -> str:
return base64.urlsafe_b64encode(value).decode().rstrip("=")
def decode(value: str) -> bytes:
return base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True)
def pack(prefix: str, data: dict[str, Any]) -> str:
return prefix + encode(json.dumps(data, separators=(",", ":")).encode())
def unpack(prefix: str, value: str) -> dict[str, Any]:
if len(value) > 32768:
raise RemoteError("pair_invalid")
value = "".join(value.split())
try:
if not value.startswith(prefix):
raise ValueError
raw = json.loads(decode(value[len(prefix):]))
if not isinstance(raw, dict):
raise ValueError
return cast(dict[str, Any], raw)
except (ValueError, TypeError, UnicodeError):
raise RemoteError("pair_invalid") from None
def public_key(value: str) -> str:
"""Accept exactly one Ed25519 key, without options, comments or newlines."""
try:
key = serialization.load_ssh_public_key(value.encode())
except UnsupportedAlgorithm:
raise ValueError("Ed25519 required") from None
if not isinstance(key, ed25519.Ed25519PublicKey):
raise ValueError("Ed25519 required")
canonical = key.public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode()
if canonical != value:
raise ValueError("non-canonical key")
return value
def fingerprint(key: str) -> str:
return "SHA256:" + base64.b64encode(hashlib.sha256(base64.b64decode(key.split()[1])).digest()).decode().rstrip("=")
class PairRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
id: str
expires: int
label: str = Field(min_length=1, max_length=64, pattern=r"^[\w .@-]+$")
ssh_key: str = Field(max_length=256)
exchange_key: str = Field(min_length=43, max_length=43)
return_origin: str = Field(default="", max_length=64)
@field_validator("return_origin")
@classmethod
def valid_return_origin(cls, value: str) -> str:
return local_return_origin(value)
@field_validator("id")
@classmethod
def valid_id(cls, value: str) -> str:
if str(uuid.UUID(value)) != value:
raise ValueError("invalid id")
return value
@field_validator("ssh_key")
@classmethod
def valid_key(cls, value: str) -> str:
return public_key(value)
@field_validator("exchange_key")
@classmethod
def valid_exchange(cls, value: str) -> str:
x25519.X25519PublicKey.from_public_bytes(decode(value))
return value
def check_expiry(self) -> None:
if not time.time() < self.expires <= time.time() + _TTL + 60:
raise RemoteError("pair_expired")
def read_request(value: str) -> PairRequest:
try:
request = PairRequest.model_validate(unpack("nbpr1.", value))
request.check_expiry()
return request
except (ValidationError, ValueError):
raise RemoteError("pair_invalid") from None
class PairReceipt(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
id: str
ssh_key: str
host: str = Field(min_length=1, max_length=253, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9.:-]*$")
user: str = Field(min_length=1, max_length=64, pattern=r"^[a-zA-Z_][a-zA-Z0-9_-]*$")
ssh_port: int = Field(ge=1, le=65535)
host_key: str
hostname: str = Field(min_length=1, max_length=253)
config_path: str = Field(min_length=1, max_length=2048)
port: int = Field(ge=1, le=65535)
secret: str = Field(min_length=1, max_length=4096, repr=False)
token_issue_path: str = Field(default="", max_length=2048)
authorized_until: int
@field_validator("host_key", "ssh_key")
@classmethod
def valid_key(cls, value: str) -> str:
return public_key(value)
def preview(self) -> dict[str, Any]:
return {"id": self.id, "host": f"{self.user}@{self.host}", "port": self.ssh_port,
"hostname": self.hostname, "fingerprint": fingerprint(self.host_key),
"authorized_until": self.authorized_until,
"revoke_command": f"nanobot remote revoke {self.id} --ssh-user {self.user}"}
def _derive(shared: bytes, request_id: str) -> bytes:
return HKDF(algorithm=hashes.SHA256(), length=32, salt=request_id.encode(), info=_CONTEXT).derive(shared)
def seal(request: PairRequest, receipt: PairReceipt) -> str:
private = x25519.X25519PrivateKey.generate()
peer = x25519.X25519PublicKey.from_public_bytes(decode(request.exchange_key))
nonce = secrets.token_bytes(12)
encrypted = AESGCM(_derive(private.exchange(peer), request.id)).encrypt(
nonce, receipt.model_dump_json().encode(), _CONTEXT + request.id.encode(),
)
return pack("nbpc1.", {"id": request.id, "key": encode(private.public_key().public_bytes_raw()),
"nonce": encode(nonce), "data": encode(encrypted)})
def private_write(path: Path, content: bytes) -> None:
# Callers own the private parent directory. Never overwrite or follow links.
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "wb") as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
class PairStore:
def __init__(self, directory: Path) -> None:
self.root = directory / "remote-pairing"
def path(self, key: str) -> Path:
try:
if str(uuid.UUID(key)) != key:
raise ValueError
except (ValueError, AttributeError):
raise RemoteError("pair_invalid") from None
return self.root / key
def start(self, return_origin: str = "") -> dict[str, Any]:
try:
return_origin = local_return_origin(return_origin)
except (ValueError, TypeError):
raise RemoteError("pair_invalid") from None
self.root.mkdir(mode=0o700, parents=True, exist_ok=True)
if self.root.is_symlink():
raise RemoteError("local_io_error")
self.root.chmod(0o700)
# Bound abandoned requests without deleting completed device identities.
pending = 0
for path in self.root.iterdir():
if path.is_dir() and not (path / "receipt").exists():
if path.stat().st_mtime < time.time() - _TTL:
self.cancel(path.name)
else:
pending += 1
if pending >= 8:
raise RemoteError("pair_limit")
key = str(uuid.uuid4())
path = self.path(key)
path.mkdir(mode=0o700)
ssh = ed25519.Ed25519PrivateKey.generate()
exchange = x25519.X25519PrivateKey.generate()
request = PairRequest(id=key, expires=int(time.time()) + _TTL,
label="".join(c for c in socket.gethostname() if c.isalnum() or c in ".-_")[:64] or "Computer",
ssh_key=ssh.public_key().public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode(),
exchange_key=encode(exchange.public_key().public_bytes_raw()),
return_origin=return_origin)
private_write(path / "identity", ssh.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption()))
private_write(path / "exchange", exchange.private_bytes_raw())
private_write(path / "request", request.model_dump_json().encode())
return {"id": key, "expires": request.expires,
"command": "nanobot remote pair " + pack("nbpr1.", request.model_dump(exclude_defaults=True))}
def _decrypt(self, key: str, code: str, *, pending: bool, require_active: bool = True) -> PairReceipt:
path = self.path(key)
try:
request = PairRequest.model_validate_json((path / "request").read_bytes())
if pending:
request.check_expiry()
envelope = unpack("nbpc1.", code)
if envelope.get("id") != key:
raise ValueError
private = x25519.X25519PrivateKey.from_private_bytes((path / "exchange").read_bytes())
peer = x25519.X25519PublicKey.from_public_bytes(decode(envelope["key"]))
clear = AESGCM(_derive(private.exchange(peer), key)).decrypt(
decode(envelope["nonce"]), decode(envelope["data"]), _CONTEXT + key.encode(),
)
receipt = PairReceipt.model_validate_json(clear)
if receipt.id != key or receipt.ssh_key != request.ssh_key:
raise ValueError
if require_active and receipt.authorized_until <= time.time():
raise RemoteError("pair_authorization_expired")
return receipt
except (OSError, ValueError, TypeError, KeyError, InvalidTag):
raise RemoteError("pair_invalid") from None
def preview(self, key: str, code: str) -> dict[str, Any]:
return self._decrypt(key, code, pending=True).preview()
def finish(self, key: str, code: str) -> PairReceipt:
receipt = self._decrypt(key, code, pending=True)
path = self.path(key) / "receipt"
if path.exists():
if path.read_text() != code:
raise RemoteError("pair_used")
else:
private_write(path, code.encode())
return receipt
def connection(self, key: str) -> dict[str, Any]:
try:
code = (self.path(key) / "receipt").read_text()
except OSError:
raise RemoteError("pair_invalid") from None
return self._decrypt(key, code, pending=False).model_dump()
def authorization_until(self, key: str) -> int | None:
"""Expose only the expiry for display, including already-expired grants.
Connecting still goes through connection(), which rejects expired grants.
A missing/unreadable receipt must not hide every other saved server.
"""
try:
code = (self.path(key) / "receipt").read_text()
return self._decrypt(key, code, pending=False, require_active=False).authorized_until
except (OSError, RemoteError):
return None
def cancel(self, key: str) -> None:
path = self.path(key)
if path.is_symlink() or (path / "receipt").exists():
return
for name in ("identity", "exchange", "request"):
(path / name).unlink(missing_ok=True)
if path.exists():
path.rmdir()
def forget(self, key: str) -> None:
"""Destroy only this managed local identity; server revocation is separate."""
path = self.path(key)
if path.is_symlink():
raise RemoteError("local_io_error")
for name in ("identity", "exchange", "request", "receipt", "ssh_route"):
(path / name).unlink(missing_ok=True)
if path.exists():
path.rmdir()
def profile(self, receipt: PairReceipt, ssh_config: str = "") -> RemoteProfile:
return RemoteProfile(name=receipt.hostname[:64], host=f"{receipt.user}@{receipt.host}",
port=receipt.ssh_port, config_path=receipt.config_path,
identity_file=str(self.path(receipt.id) / "identity"),
ssh_config=ssh_config)
+368
View File
@@ -0,0 +1,368 @@
"""A browser origin with local capabilities, not reusable remote credentials.
The private SSH listener is never published. This proxy drains its requests
before releasing that listener; a process reclaiming the public browser port
after shutdown can receive only capabilities from an already-dead proxy.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import math
import re
import secrets
import socket
import time
from collections import OrderedDict
from dataclasses import dataclass
from typing import Any, cast
import httpx
from aiohttp import WSMsgType, web
from cryptography.fernet import Fernet, InvalidToken
from websockets.asyncio.client import connect
from websockets.exceptions import WebSocketException
from websockets.typing import Origin
from yarl import URL
from nanobot.webui.remote_ssh import Tunnel, _listen # pyright: ignore[reportPrivateUsage]
_MAX_BYTES = 64 * 1024 * 1024
_MAX_CAPABILITIES = 10000
_MEDIA_PATH = r"/api/media/[A-Za-z0-9_-]{22}/[A-Za-z0-9_-]+"
# Consume absolute URLs unchanged before matching gateway-relative media paths.
# An external site's similarly named route is not this proxy's capability.
_MEDIA = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.-]*:)?//[^\s<>\"'`()]+|"
rf"(?<![A-Za-z0-9_/%:.~-])(?P<media>{_MEDIA_PATH})")
_REQUEST_HEADERS = {"accept", "accept-language", "content-type", "range", "if-range"}
_RESPONSE_HEADERS = {
"content-type", "content-range", "accept-ranges", "content-disposition",
"content-security-policy", "x-content-type-options", "last-modified",
}
@dataclass(frozen=True)
class _Grant:
remote: str
expires: float
path: str = ""
class RemoteProxy:
"""Owns the public listener, local credentials and a private SSH transport."""
def __init__(self, tunnel: Tunnel, secret: str, gateway_id: str, issue_path: str) -> None:
self.tunnel = tunnel
self.secret = secrets.token_urlsafe(32)
self.port = 0
self._remote_secret = secret
self._gateway_id = gateway_id
self._issue_path = issue_path.rstrip("/") or ""
# Reload caches are scoped to WS pathname. A fresh process must not
# reuse cached transcripts containing a previous proxy's media grants.
self._ws_path = "/remote-session/" + secrets.token_urlsafe(18)
self._api: dict[str, _Grant] = {}
self._ws: dict[str, _Grant] = {}
self._media_cipher = Fernet(Fernet.generate_key())
self._media_cache: OrderedDict[str, str] = OrderedDict()
self._tasks: set[asyncio.Task[Any]] = set()
self._bootstrap_lock = asyncio.Lock()
self._enabled = True
self._runner: web.AppRunner | None = None
@classmethod
async def open(
cls, tunnel: Tunnel, secret: str, gateway_id: str, issue_path: str = "",
*, local_port: int = 0, excluded_ports: set[int] | None = None,
) -> RemoteProxy:
self = cls(tunnel, secret, gateway_id, issue_path)
listener = _listen(local_port, excluded_ports or set())
self.port = int(listener.getsockname()[1])
app = web.Application(client_max_size=_MAX_BYTES)
app.router.add_route("*", "/{path:.*}", self._handle)
self._runner = web.AppRunner(app, access_log=None, handler_cancellation=True)
try:
await self._runner.setup()
await web.SockSite(self._runner, listener).start()
return self
except BaseException:
listener.close()
await self._runner.cleanup()
raise
@property
def active(self) -> bool:
return self._enabled and self.tunnel.active
@property
def origin(self) -> str:
return f"http://127.0.0.1:{self.port}"
def resume(self, secret: str, gateway_id: str, issue_path: str = "") -> None:
if gateway_id != self._gateway_id:
self._ws_path = "/remote-session/" + secrets.token_urlsafe(18)
self._api.clear()
self._ws.clear()
self._media_cipher = Fernet(Fernet.generate_key())
self._media_cache.clear()
self._remote_secret = secret
self._gateway_id = gateway_id
self._issue_path = issue_path.rstrip("/") or ""
self._enabled = True
async def pause(self) -> None:
self._enabled = False
tasks = list(self._tasks)
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
self._api.clear()
self._ws.clear()
await self.tunnel.pause()
async def close(self) -> None:
await self.pause()
if self._runner is not None:
await self._runner.cleanup()
self._runner = None
self._remote_secret = ""
self._media_cipher = Fernet(Fernet.generate_key())
self._media_cache.clear()
await self.tunnel.close()
def _credential(self, request: web.Request, *, bootstrap: bool = False) -> str:
# Decode query names once. Reject duplicates and mixed aliases rather
# than allowing the client and upstream to disagree about precedence.
auth = request.headers.getall("Authorization", [])
issue = request.headers.getall("X-Nanobot-Auth", [])
query = request.rel_url.query.getall("token", [])
if len(auth) + len(issue) + len(query) > 1:
raise web.HTTPUnauthorized()
if auth:
scheme, _, value = auth[0].partition(" ")
if scheme.lower() != "bearer" or not value:
raise web.HTTPUnauthorized()
return value
if bootstrap and issue:
return issue[0]
if not bootstrap and query:
return query[0]
return ""
def _grant(self, token: str, grants: dict[str, _Grant], *, consume: bool = False) -> _Grant:
grant = grants.pop(token, None) if consume else grants.get(token)
if grant is None or grant.expires <= time.monotonic():
raise web.HTTPUnauthorized()
return grant
async def _handle(self, request: web.Request) -> web.StreamResponse:
if (request.headers.getall("Host", []) != [f"127.0.0.1:{self.port}"]
or request.headers.getall("Origin", []) not in ([], [self.origin])):
raise web.HTTPForbidden()
if not self.active:
raise web.HTTPServiceUnavailable()
task = asyncio.current_task()
assert task is not None
self._tasks.add(task)
try:
# The upstream gateway uses the raw path (not unquoted path) for
# routing. Keep it intact and do not normalize escaped separators.
path = request.rel_url.raw_path.rstrip("/") or "/"
if path == self._issue_path:
raise web.HTTPForbidden()
if request.headers.get("Upgrade", "").lower() == "websocket":
if path != self._ws_path:
raise web.HTTPNotFound()
grant = self._grant(self._credential(request), self._ws, consume=True)
return await self._websocket(request, grant)
if path == "/webui/bootstrap":
if request.method != "GET":
raise web.HTTPMethodNotAllowed(request.method, ["GET"])
supplied = self._credential(request, bootstrap=True)
if not secrets.compare_digest(supplied.encode(), self.secret.encode()):
raise web.HTTPUnauthorized()
async with self._bootstrap_lock:
return await self._bootstrap()
if path == "/webui/terminal":
raise web.HTTPForbidden()
return await self._http(request, path)
except (httpx.HTTPError, WebSocketException, OSError, ValueError):
# Never reflect upstream URLs, credentials or raw exception text.
raise web.HTTPBadGateway(text="Remote connection unavailable") from None
finally:
self._tasks.discard(task)
def _headers(self, request: web.Request) -> dict[str, str]:
headers = {key: value for key, value in request.headers.items()
if key.lower() in _REQUEST_HEADERS}
headers["Host"] = f"127.0.0.1:{self.port}"
headers["Origin"] = self.origin
return headers
def _upstream(self, path: str) -> str:
return f"http://127.0.0.1:{self.tunnel.port}{path}"
async def _bootstrap(self) -> web.Response:
now = time.monotonic()
for grants in (self._api, self._ws):
for key in [key for key, value in grants.items() if value.expires <= now]:
del grants[key]
if len(grants) >= _MAX_CAPABILITIES:
raise web.HTTPTooManyRequests()
async with httpx.AsyncClient(trust_env=False, timeout=20) as client:
response = await client.get(self._upstream("/webui/bootstrap"), headers={
"X-Nanobot-Auth": self._remote_secret, "Host": f"127.0.0.1:{self.port}",
})
if response.status_code != 200:
raise web.HTTPBadGateway(text="Remote authentication unavailable")
payload: object = response.json()
if not isinstance(payload, dict):
raise ValueError("invalid bootstrap")
data = cast(dict[str, Any], payload)
terminal = data.get("terminal")
if not isinstance(terminal, dict):
raise ValueError("invalid terminal")
terminal = cast(dict[str, Any], terminal)
ttl, ws_path = data.get("expires_in"), data.get("ws_path")
if (terminal.get("gatewayId") != self._gateway_id
or terminal.get("protocolVersion") != 1
or not isinstance(ttl, (float, int)) or not math.isfinite(ttl) or not 0 < ttl <= 86400
or not isinstance(ws_path, str) or not ws_path.startswith("/")
or ws_path.startswith("//") or "?" in ws_path or "#" in ws_path
or any(ord(c) < 33 for c in ws_path)
or not isinstance(data.get("token"), str) or not data["token"]
or not isinstance(data.get("api_token"), str) or not data["api_token"]):
raise ValueError("incompatible bootstrap")
token, api_token = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
# Count elapsed upstream time against the remote token's TTL.
self._ws[token] = _Grant(data["token"], now + ttl, ws_path)
self._api[api_token] = _Grant(data["api_token"], now + ttl)
result = {key: data[key] for key in (
"limits", "model_name", "runtime_surface", "runtime_capabilities",
) if key in data}
result.update(token=token, api_token=api_token, expires_in=ttl,
terminal={"protocolVersion": 1, "gatewayId": self._gateway_id},
ws_path=self._ws_path, ws_url=f"ws://127.0.0.1:{self.port}{self._ws_path}")
return web.json_response(result, headers={"Cache-Control": "no-store"})
def _local_media(self, match: re.Match[str]) -> str:
remote = match.group("media")
if remote is None:
return match.group()
existing = self._media_cache.get(remote)
if existing:
self._media_cache.move_to_end(remote)
return existing
# Authenticated encryption hides the remote bearer URL without retaining
# an unbounded mapping. Eviction only changes future URL spelling: every
# previously issued URL still works for this proxy's lifetime.
local = "/api/media/local/" + self._media_cipher.encrypt(remote.encode()).decode()
if len(self._media_cache) >= _MAX_CAPABILITIES:
self._media_cache.popitem(last=False)
self._media_cache[remote] = local
return local
def _remote_media(self, path: str) -> str:
prefix = "/api/media/local/"
if not path.startswith(prefix):
raise web.HTTPUnauthorized()
try:
remote = self._media_cipher.decrypt(path[len(prefix):].encode()).decode()
except (InvalidToken, UnicodeError, ValueError):
raise web.HTTPUnauthorized() from None
if not re.fullmatch(_MEDIA_PATH, remote):
raise web.HTTPUnauthorized()
return remote
def _rewrite(self, value: Any) -> Any:
if isinstance(value, str):
return _MEDIA.sub(self._local_media, value)
if isinstance(value, list):
return [self._rewrite(item) for item in cast(list[Any], value)]
if isinstance(value, dict):
return {key: self._rewrite(item) for key, item in cast(dict[str, Any], value).items()}
return value
async def _http(self, request: web.Request, path: str) -> web.StreamResponse:
url = request.rel_url.with_query([
(key, value) for key, value in request.rel_url.query.items() if key != "token"
])
headers = self._headers(request)
if path.startswith("/api/media/"):
remote = self._remote_media(path)
url = URL(remote).with_query(url.query)
elif path.startswith("/api/"):
grant = self._grant(self._credential(request), self._api)
headers["Authorization"] = "Bearer " + grant.remote
# HTTP API and static responses are read-only. WebUI writes travel over
# its authenticated multiplex WebSocket, not an arbitrary HTTP relay.
if request.method not in {"GET", "HEAD"}:
raise web.HTTPMethodNotAllowed(request.method, ["GET", "HEAD"])
async with httpx.AsyncClient(trust_env=False, timeout=30) as client:
async with client.stream(request.method, self._upstream(str(url)), headers=headers) as upstream:
if upstream.is_redirect:
raise web.HTTPBadGateway(text="Unexpected remote redirect")
outgoing = {key: value for key, value in upstream.headers.items()
if key.lower() in _RESPONSE_HEADERS}
outgoing["Cache-Control"] = "no-store"
if "application/json" in upstream.headers.get("content-type", ""):
body = bytearray()
async for chunk in upstream.aiter_bytes():
body.extend(chunk)
if len(body) > _MAX_BYTES:
raise ValueError("response too large")
if request.method == "HEAD":
return web.Response(status=upstream.status_code, headers=outgoing)
return web.Response(body=json.dumps(self._rewrite(json.loads(body))).encode(),
status=upstream.status_code, headers=outgoing)
result = web.StreamResponse(status=upstream.status_code, headers=outgoing)
await result.prepare(request)
async for chunk in upstream.aiter_bytes():
await result.write(chunk)
await result.write_eof()
return result
async def _websocket(self, request: web.Request, grant: _Grant) -> web.WebSocketResponse:
# An already-connected socket fixes the upstream and disables all WS
# redirects. Its HTTP authority still matches the browser's origin.
upstream_socket = socket.socket()
upstream_socket.setblocking(False)
try:
await asyncio.wait_for(asyncio.get_running_loop().sock_connect(
upstream_socket, ("127.0.0.1", self.tunnel.port),
), 20)
query = [(key, value) for key, value in request.rel_url.query.items() if key != "token"]
query.append(("token", grant.remote))
url = URL(f"ws://127.0.0.1:{self.port}").with_path(grant.path, encoded=True).with_query(query)
async with connect(str(url), sock=upstream_socket, proxy=None, origin=Origin(self.origin),
max_size=_MAX_BYTES, open_timeout=20, close_timeout=2) as upstream:
browser = web.WebSocketResponse(max_msg_size=_MAX_BYTES, heartbeat=30)
await browser.prepare(request)
async def receive() -> None:
try:
async for message in upstream:
if isinstance(message, bytes):
await browser.send_bytes(message)
else:
await browser.send_str(json.dumps(self._rewrite(json.loads(message))))
finally:
await browser.close()
reader = asyncio.create_task(receive())
try:
async for message in browser:
if message.type in {WSMsgType.TEXT, WSMsgType.BINARY}:
await upstream.send(message.data)
finally:
reader.cancel()
await asyncio.gather(reader, return_exceptions=True)
await browser.close()
return browser
finally:
# connect owns the socket after handoff; close is also safe if
# cancellation occurred before the protocol took ownership.
with contextlib.suppress(OSError):
upstream_socket.close()
+250 -53
View File
@@ -8,12 +8,13 @@ from __future__ import annotations
import asyncio
import base64
import contextlib
import hashlib
import json
import os
import shlex
import shutil
import socket
from dataclasses import dataclass
from pathlib import Path
from typing import Any, cast
@@ -43,9 +44,27 @@ class RemoteProfile(BaseModel):
return value
class PairedSSHProfile(RemoteProfile):
"""Internal transport marker. Not accepted by the editable profile API."""
def transport_arguments(profile: RemoteProfile, remote_port: int, known_hosts: Path | None) -> list[str]:
args = ssh_arguments(profile, known_hosts)
if isinstance(profile, PairedSSHProfile):
# The server key's forced command owns the fixed destination. Do not
# request forwarding or execute the ordinary credential probe.
return [*args, profile.host, "nanobot-remote-bridge"]
return [*args, "-W", f"127.0.0.1:{remote_port}", profile.host]
# Frame the result so login banners don't get mistaken for invalid config JSON.
_PROBE_PREFIX = b"\x1eNANOBOT_REMOTE:"
# Fixed program, quoted as one shell argument. No user-supplied shell commands.
_PROBE = r'''
import json, os, pathlib, socket, sys
def emit(value):
print("\n\x1eNANOBOT_REMOTE:" + json.dumps(value))
try:
path = pathlib.Path(sys.argv[1]).expanduser()
data = json.loads(path.read_text())
@@ -57,15 +76,20 @@ try:
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)}))
if ws.get("trustedProxyAuth") or ws.get("trusted_proxy_auth"):
raise ValueError("incompatible_gateway")
emit({"port": ws.get("port", 8765), "secret": secret,
"token_issue_path": ws.get("tokenIssuePath") or ws.get("token_issue_path") or "",
"hostname": socket.gethostname(), "config_path": str(path)})
except FileNotFoundError:
print(json.dumps({"error": "config_not_found"}))
emit({"error": "config_not_found"})
except PermissionError:
print(json.dumps({"error": "config_permission"}))
emit({"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"}))
emit({"error": code if code in {"webui_disabled", "webui_auth_required", "public_ws_unsupported", "incompatible_gateway"} else "config_invalid"})
except (AttributeError, TypeError):
emit({"error": "config_invalid"})
'''
@@ -74,6 +98,8 @@ def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> li
if not executable:
raise RemoteError("ssh_unavailable")
args = [executable]
if isinstance(profile, PairedSSHProfile) and not profile.ssh_config:
args.extend(["-F", os.devnull])
for flag, value in [("-F", profile.ssh_config), ("-i", profile.identity_file)]:
if value:
path = Path(value).expanduser()
@@ -88,9 +114,19 @@ def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> li
"-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=10",
"-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2",
"-o", "ExitOnForwardFailure=yes", "-o", "RequestTTY=no",
# Interactive aliases may start tmux or another shell automatically.
# This connection runs only our fixed probe and forwarding transport.
# Older clients lack these settings and the corresponding behavior.
"-o", "IgnoreUnknown=StdinNull,ForkAfterAuthentication,RemoteCommand",
"-o", "RemoteCommand=none",
"-o", "ClearAllForwardings=yes", "-o", "StdinNull=no",
"-o", "ForkAfterAuthentication=no",
])
if profile.port is not None:
args.extend(["-p", str(profile.port)])
if isinstance(profile, PairedSSHProfile):
# Never fall back to a user's unrelated identity or agent for this grant.
args.extend(["-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none"])
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",
@@ -104,10 +140,28 @@ def ssh_error(stderr: bytes) -> str:
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 "unprotected private key file" in text or "bad permissions" in text:
return "ssh_key_permissions"
if "agent refused operation" in text or "signing failed" in text:
return "ssh_agent_refused"
if "bad configuration option" in text or "terminating, 1 bad configuration" in text:
return "ssh_config_invalid"
if "administratively prohibited" in text:
return "ssh_forwarding_denied"
if "open failed: connect failed" in text:
return "remote_unreachable"
if "too many authentication failures" in text:
return "ssh_too_many_keys"
if "permission denied" in text:
return "ssh_auth_failed"
if "connection refused" in text:
return "ssh_refused"
if "could not resolve hostname" in text:
return "ssh_host_not_found"
if "connection closed" in text or "connection reset" in text:
return "ssh_connection_closed"
if "python3" in text and "not found" in text:
return "python_unavailable"
return "ssh_unreachable"
@@ -129,8 +183,11 @@ async def stop_process(process: asyncio.subprocess.Process) -> None:
await process.wait()
async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]:
remote = ["python3", "-c", _PROBE, profile.config_path]
async def run_check(
profile: RemoteProfile, program: str, known_hosts: Path | None = None,
) -> dict[str, Any]:
"""Run a fixed read-only program with SSH's existing identity and trust policy."""
remote = ["python3", "-c", program, profile.config_path]
if profile.runtime_user:
remote = ["sudo", "-n", "-H", "-u", profile.runtime_user, "--", *remote]
process = await asyncio.create_subprocess_exec(
@@ -143,73 +200,213 @@ async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict
if process.returncode:
raise RemoteError(ssh_error(stderr))
try:
raw = json.loads(stdout)
records = [line[len(_PROBE_PREFIX):] for line in stdout.split(b"\n")
if line.startswith(_PROBE_PREFIX)]
if len(records) != 1:
raise ValueError
raw = json.loads(records[0])
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
raise RemoteError("probe_failed") from None
except TimeoutError:
raise RemoteError("ssh_unreachable") from None
finally:
await stop_process(process)
async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]:
data = await run_check(profile, _PROBE, known_hosts)
if (not isinstance(data.get("secret"), str) or not data["secret"]
or type(data.get("port")) is not int or not 1 <= data["port"] <= 65535):
raise RemoteError("probe_failed")
return data
async def pairing_route(source: RemoteProfile, target_host: str) -> str:
"""Explicitly reuse a saved route, never its identities or target settings."""
process = await asyncio.create_subprocess_exec(
*ssh_arguments(source), "-G", source.host,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL,
stdin=asyncio.subprocess.DEVNULL,
)
try:
output, _ = await asyncio.wait_for(process.communicate(), 10)
if process.returncode:
raise RemoteError("ssh_config_invalid")
values = dict(line.split(" ", 1) for line in output.decode().splitlines() if " " in line)
if values.get("hostname", "").lower() != target_host.lower():
raise RemoteError("pair_route_mismatch")
if values.get("proxyjump", "none") != "none":
raise RemoteError("pair_route_unsupported")
lines = ["Host *"]
for option in ("proxycommand", "bindaddress", "bindinterface"):
value = values.get(option, "none")
if value != "none":
lines.append(f" {option} {value}")
return "\n".join(lines) + "\n"
except TimeoutError:
raise RemoteError("ssh_unreachable") from None
finally:
await stop_process(process)
@dataclass
class Tunnel:
process: asyncio.subprocess.Process
port: int
"""Own a private loopback transport; upstream bytes only use SSH pipes.
Pausing closes streams, not the listener: other browser tabs may still retry
that origin. Only final owner shutdown relinquishes the listening socket.
"""
def __init__(self, args: list[str], port: int) -> None:
self.args = args
self.port = port
self.server: asyncio.Server | None = None
self.enabled = True
self.error = ""
self._streams: set[asyncio.Task[None]] = set()
@property
def active(self) -> bool:
return self.enabled and self.server is not None and self.server.is_serving()
def resume(self, profile: RemoteProfile, remote_port: int, known_hosts: Path) -> None:
self.args = transport_arguments(profile, remote_port, known_hosts)
self.error = ""
self.enabled = True
def accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
if not self.active or len(self._streams) >= 32:
writer.close()
return
task = asyncio.create_task(self._relay(reader, writer))
self._streams.add(task)
def finished(task: asyncio.Task[None]) -> None:
self._streams.discard(task)
# Cancellation can happen before _relay enters its try/finally.
writer.close()
task.add_done_callback(finished)
async def _relay(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
process: asyncio.subprocess.Process | None = None
pumps: list[asyncio.Task[None]] = []
stderr = bytearray()
async def copy(source: asyncio.StreamReader, destination: asyncio.StreamWriter) -> None:
while data := await source.read(65536):
destination.write(data)
await destination.drain()
if destination.can_write_eof():
destination.write_eof()
async def drain_errors(source: asyncio.StreamReader) -> None:
while data := await source.read(4096):
stderr.extend(data[:max(0, 8192 - len(stderr))])
try:
# Shield process creation so cancellation cannot lose a spawned child
# before we have its handle and can reap it.
spawn = asyncio.create_task(asyncio.create_subprocess_exec(
*self.args, stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
))
try:
process = await asyncio.shield(spawn)
except asyncio.CancelledError:
process = await spawn
raise
assert process is not None
assert process.stdin is not None and process.stdout is not None and process.stderr is not None
pumps = [asyncio.create_task(copy(reader, process.stdin)),
asyncio.create_task(copy(process.stdout, writer)),
asyncio.create_task(drain_errors(process.stderr))]
done, _ = await asyncio.wait(pumps[:2], return_when=asyncio.FIRST_COMPLETED)
for task in done:
await task
# Preserve a client's half-close while draining the final response.
# Conversely, EOF from SSH must wake an idle keepalive client.
await pumps[1]
pumps[0].cancel()
process.stdin.close()
await asyncio.wait_for(process.wait(), 3)
await pumps[2]
if process.returncode:
self.error = ssh_error(bytes(stderr))
except (OSError, ConnectionError):
self.error = "ssh_unreachable"
finally:
for task in pumps:
task.cancel()
await asyncio.gather(*pumps, return_exceptions=True)
if process is not None:
await stop_process(process)
writer.close()
with contextlib.suppress(OSError):
await writer.wait_closed()
async def pause(self) -> None:
self.enabled = False
streams = list(self._streams)
for task in streams:
task.cancel()
await asyncio.gather(*streams, return_exceptions=True)
async def close(self) -> None:
await stop_process(self.process)
await self.pause()
if self.server is not None:
self.server.close()
await self.server.wait_closed()
def _listen(local_port: int, excluded_ports: set[int]) -> socket.socket:
# Never release the chosen socket between validation and use. Windows reuse
# has different semantics; exclusive binding rejects existing listeners.
rejected: list[socket.socket] = []
try:
for _ in range(128):
listener = socket.socket()
try:
if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
listener.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
else:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", local_port))
listener.listen()
if not local_port and listener.getsockname()[1] in excluded_ports:
rejected.append(listener)
continue
listener.setblocking(False)
return listener
except BaseException:
listener.close()
raise
raise RemoteError("local_port_in_use")
except OSError:
raise RemoteError("local_port_in_use") from None
finally:
for listener in rejected:
listener.close()
async def open_tunnel(
profile: RemoteProfile, remote_port: int, known_hosts: Path | None = None,
local_port: int = 0,
*, excluded_ports: set[int] | None = None,
) -> 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)
args = transport_arguments(profile, remote_port, known_hosts)
listener = _listen(local_port, excluded_ports or set())
tunnel = Tunnel(args, int(listener.getsockname()[1]))
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")
tunnel.server = await asyncio.start_server(tunnel.accept, sock=listener)
return tunnel
except BaseException:
listener.close()
await tunnel.close()
raise
+7
View File
@@ -165,6 +165,13 @@ class _WebUIThreadDiagnostics:
_WEBUI_MUTATION_PATHS = {
"remote.discover": "/api/remote-instances/discover",
"remote.pair_start": "/api/remote-instances/pair_start",
"remote.pair_preview": "/api/remote-instances/pair_preview",
"remote.pair_finish": "/api/remote-instances/pair_finish",
"remote.pair_cancel": "/api/remote-instances/pair_cancel",
"remote.pair_route": "/api/remote-instances/pair_route",
"remote.inspect": "/api/remote-instances/inspect",
"remote.pick_file": "/api/remote-instances/pick_file",
"remote.save": "/api/remote-instances/save",
"remote.connect": "/api/remote-instances/connect",
"remote.disconnect": "/api/remote-instances/disconnect",