fix(webui): run SSH probes on Windows hosts with python

This commit is contained in:
Xubin Ren committed 2026-11-18 20:15:13 +08:00
1 parent 307b3bce82
commit b18ca98aff
14 files changed
+110 -54

No files matched your search

+2
View File
@@ -51,6 +51,8 @@ After SSH signs in, a read-only check looks for the selected account's config an
If nothing is found, the dialog confirms **SSH connected** and asks for the server's config path and optional service account. Docker, custom service names, user services and non-systemd deployments may need this manual step. Failure to find a config is not proof that nanobot is absent. Finding a config is also not proof that its WebUI is running: the normal authenticated gateway check still happens before opening.
For an existing Windows SSH setup, make Python 3 available to the SSH login as `python` or `python3`. The server's nanobot configuration must be UTF-8 JSON. Windows support here does not extend to the quick-pairing command.
SSH failures keep the entered address and offer **SSH login settings** for the local key path, SSH config and port. Connection refusal, name resolution, connection closure and authentication rejection have distinct messages. The application does not infer a missing key from a closed connection, nor change VPN, proxy or network-interface settings automatically. A custom SSH config outside standard locations must still be explicitly supplied by its owner.
## Find a server you already use
+1 -1
View File
@@ -81,7 +81,7 @@ class PairingTarget(TypedDict):
def metadata(config: Path) -> PairingTarget:
"""Read the fixed loopback target and its credential from the selected config."""
try:
raw = json.loads(config.read_text())
raw = json.loads(config.read_text(encoding="utf-8"))
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:
+46 -31
View File
@@ -12,7 +12,6 @@ import contextlib
import hashlib
import json
import os
import shlex
import shutil
import socket
from pathlib import Path
@@ -63,14 +62,14 @@ def transport_arguments(profile: RemoteProfile, remote_port: int, known_hosts: P
# 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.
# Fixed program sent over SSH stdin, not interpreted by the remote shell.
_PROBE = r'''
import json, os, pathlib, socket, sys
import json, 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())
data = json.loads(path.read_text(encoding="utf-8"))
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"):
@@ -141,36 +140,52 @@ 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(
*ssh_arguments(profile, known_hosts), profile.host, shlex.join(remote),
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
args = ssh_arguments(profile, known_hosts)
sudo = f"sudo -n -H -u {profile.runtime_user} -- " if profile.runtime_user else ""
# A Python string literal keeps spaces, Unicode and shell metacharacters
# in the path out of the command line on both cmd.exe and Unix shells.
script = f"import sys; sys.argv.append({profile.config_path!a})\n{program}".encode("utf-8")
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), 20)
if process.returncode:
raise RemoteError(ssh_error(stderr))
try:
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"]))
return data
except (ValueError, TypeError):
raise RemoteError("probe_failed") from None
async with asyncio.timeout(20):
for executable in ("python3", "python"):
process = await asyncio.create_subprocess_exec(
*args, profile.host, f"{sudo}{executable} -",
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try:
stdout, stderr = await process.communicate(script)
finally:
await stop_process(process)
if process.returncode == 0:
break
# Missing command: POSIX 127, cmd.exe 9009 (truncated to 49
# by POSIX SSH clients), or PowerShell's exception marker.
if not sudo and (process.returncode in {49, 127, 9009} or (
process.returncode == 1 and b"CommandNotFoundException" in stderr
)):
continue
error = ssh_error(stderr)
raise RemoteError("probe_failed" if error == "ssh_unreachable" and process.returncode != 255 else error)
else:
raise RemoteError("python_unavailable")
except TimeoutError:
raise RemoteError("ssh_unreachable") from None
finally:
await stop_process(process)
try:
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"]))
return data
except (ValueError, TypeError):
raise RemoteError("probe_failed") from None
async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]:
+41 -2
View File
@@ -1042,6 +1042,32 @@ async def test_probe_ignores_shell_banners_without_exposing_them(monkeypatch, ba
assert await remote_ssh.probe(RemoteProfile(name="Test", host="example.test")) == data
@pytest.mark.parametrize(("returncode", "stderr", "expected_error"), [
(127, b"python3: not found", ""),
(49, b"'python3' is not recognized as an internal or external command", ""),
(1, b"FullyQualifiedErrorId : CommandNotFoundException", ""),
(255, b"Permission denied (publickey).", "ssh_auth_failed"),
(1, b"Traceback (most recent call last):", "probe_failed"),
])
async def test_probe_only_retries_when_the_remote_interpreter_is_missing(monkeypatch, returncode, stderr, expected_error):
data = {"port": 8765, "secret": "synthetic-root"}
attempt = MagicMock(returncode=returncode, communicate=AsyncMock(return_value=(b"", stderr)))
fallback = MagicMock(returncode=0, communicate=AsyncMock(return_value=(
remote_ssh._PROBE_PREFIX + json.dumps(data).encode() + b"\r\n", b"",
)))
spawn = AsyncMock(side_effect=[attempt, fallback])
monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
profile = RemoteProfile(name="Test", host="example.test", config_path=r"C:\測試 & 100%\config.json")
if expected_error:
with pytest.raises(RemoteError, match=f"^{expected_error}$"):
await remote_ssh.probe(profile)
spawn.assert_awaited_once()
else:
assert await remote_ssh.probe(profile) == data
assert [call.args[-1] for call in spawn.await_args_list] == ["python3 -", "python -"]
assert attempt.communicate.await_args == fallback.communicate.await_args
@pytest.mark.parametrize("output", [
b"Welcome. Password required for private-user.",
b'\x1eNANOBOT_REMOTE:{"port": 8765, "secret": "s"}\n\x1eNANOBOT_REMOTE:{}',
@@ -1055,15 +1081,28 @@ async def test_invalid_probe_protocol_is_not_reported_as_bad_config(monkeypatch,
await remote_ssh.probe(RemoteProfile(name="Test", host="example.test"))
@pytest.mark.parametrize("config", ["invalid JSON", "[]", '{"channels": null}', '{"channels": {"websocket": []}}'])
@pytest.mark.parametrize("config", [b"invalid JSON", b"[]", b'{"channels": null}', b'{"channels": {"websocket": []}}', b'{"name":"\xff"}'])
def test_probe_reports_malformed_config_as_config_error(tmp_path, config):
path = tmp_path / "config.json"
path.write_text(config)
path.write_bytes(config)
result = subprocess.run([sys.executable, "-c", remote_ssh._PROBE, str(path)],
capture_output=True, text=True, check=True)
assert json.loads(result.stdout.split("NANOBOT_REMOTE:")[1]) == {"error": "config_invalid"}
def test_probe_reads_config_as_utf8_independently_of_locale(tmp_path, monkeypatch):
path = tmp_path / "config.json"
path.write_text(json.dumps({"channels": {"websocket": {
"enabled": True, "token": "synthetic-root", "tokenIssuePath": "/测试",
}}}, ensure_ascii=False), encoding="utf-8")
monkeypatch.setenv("PYTHONUTF8", "0")
monkeypatch.setenv("PYTHONCOERCECLOCALE", "0")
monkeypatch.setenv("LC_ALL", "C")
result = subprocess.run([sys.executable, "-c", remote_ssh._PROBE, str(path)],
capture_output=True, text=True, check=True)
assert json.loads(result.stdout.split("NANOBOT_REMOTE:")[1])["token_issue_path"] == "/测试"
async def test_tunnel_refuses_an_existing_listener(monkeypatch):
spawn = AsyncMock()
monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "The file chooser couldn't open. You can paste a local file path instead.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"python_unavailable": "SSH signed in, but couldn't start Python 3. Make python3 or python available to the SSH login on the server.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"config_invalid": "Couldn't read the server's nanobot configuration. Check that the selected file is valid UTF-8 JSON.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
"public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "No se pudo abrir el selector. Puedes pegar la ruta de un archivo local.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"python_unavailable": "SSH signed in, but couldn't start Python 3. Make python3 or python available to the SSH login on the server.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"config_invalid": "Couldn't read the server's nanobot configuration. Check that the selected file is valid UTF-8 JSON.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
"public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "Impossible d’ouvrir le sélecteur. Vous pouvez saisir le chemin d’un fichier local.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"python_unavailable": "SSH signed in, but couldn't start Python 3. Make python3 or python available to the SSH login on the server.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"config_invalid": "Couldn't read the server's nanobot configuration. Check that the selected file is valid UTF-8 JSON.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
"public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "Pemilih file tidak dapat dibuka. Tempel jalur file lokal sebagai gantinya.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"python_unavailable": "SSH signed in, but couldn't start Python 3. Make python3 or python available to the SSH login on the server.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"config_invalid": "Couldn't read the server's nanobot configuration. Check that the selected file is valid UTF-8 JSON.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
"public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "ファイル選択画面を開けませんでした。ローカルファイルのパスを入力してください。",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"python_unavailable": "SSH signed in, but couldn't start Python 3. Make python3 or python available to the SSH login on the server.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"config_invalid": "Couldn't read the server's nanobot configuration. Check that the selected file is valid UTF-8 JSON.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
"public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "파일 선택 창을 열 수 없습니다. 로컬 파일 경로를 직접 입력할 수 있습니다.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"python_unavailable": "SSH signed in, but couldn't start Python 3. Make python3 or python available to the SSH login on the server.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"config_invalid": "Couldn't read the server's nanobot configuration. Check that the selected file is valid UTF-8 JSON.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
"public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "Não foi possível abrir o seletor. Você pode colar o caminho de um arquivo local.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"python_unavailable": "SSH signed in, but couldn't start Python 3. Make python3 or python available to the SSH login on the server.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"config_invalid": "Couldn't read the server's nanobot configuration. Check that the selected file is valid UTF-8 JSON.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
"public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "Không thể mở hộp thoại chọn tệp. Bạn có thể dán đường dẫn tệp cục bộ.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"python_unavailable": "SSH signed in, but couldn't start Python 3. Make python3 or python available to the SSH login on the server.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"config_invalid": "Couldn't read the server's nanobot configuration. Check that the selected file is valid UTF-8 JSON.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
"public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "本机找不到指定的 SSH 配置文件或私钥。",
"file_picker_unavailable": "无法打开文件选择窗口,也可以直接填写本机文件路径。",
"runtime_user_denied": "SSH 已登录,但不能免密切换到这个运行账号,请与服务器管理员确认。",
"python_unavailable": "服务器需要 python3 来读取已有的 nanobot 配置。",
"python_unavailable": "SSH 已登录,但找不到 Python 3。请确认服务器上的 SSH 登录账号能运行 python3 或 python。",
"config_not_found": "找不到 nanobot 配置,请在「连接选项」中填写它在服务器上的路径。",
"config_permission": "SSH 账号无权读取 nanobot 配置,请在「连接选项」中填写 nanobot 的运行账号。",
"config_invalid": "无法读取服务器上的 nanobot 配置。",
"config_invalid": "无法读取服务器上的 nanobot 配置。请确认所选文件是有效的 UTF-8 JSON。",
"webui_disabled": "服务器的 WebUI 尚未启用,请先在服务器上开启。",
"webui_auth_required": "服务器需要在配置中设置 WebUI 登录密钥。这里不需要模型 Key。",
"public_ws_unsupported": "这台服务器设置了公网 WebSocket 地址。首版支持通过 SSH 连接回环地址上的 WebUI。",
+2 -2
View File
@@ -331,10 +331,10 @@
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "無法開啟檔案選擇視窗,也可以直接填寫本機檔案路徑。",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"python_unavailable": "SSH signed in, but couldn't start Python 3. Make python3 or python available to the SSH login on the server.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"config_invalid": "Couldn't read the server's nanobot configuration. Check that the selected file is valid UTF-8 JSON.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
"public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",