Skip to content

Your lightweight open-source personal agent.

fix(remote): detect Tencent public address and clarify this-server prompts

Xubin Rene59c2bf79a20
diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.md
index 504b8327c..28547ba0b 100644
--- a/docs/guides/remote-instances.md
+++ b/docs/guides/remote-instances.md
@@ -46,8 +46,15 @@ prepare a local SSH key or know the service account/config path:
IP/hostname and an existing non-root SSH login account when prompted.
A single existing login account (including the original account under sudo)
is selected automatically and shown in the authorization summary. A global
- server address reported by the SSH session can also be selected automatically;
- private/NAT addresses are never guessed. Use `--ssh-user` or `--host` to override.
+ server address reported by the SSH session can also be selected automatically.
+ On recognized Tencent Cloud Linux instances, pairing can instead read this
+ server's public IPv4 from the fixed, instance-local metadata endpoint, without
+ cloud API keys. Only that public-address field is read; no role credentials or
+ user data are requested. If neither source is available, enter **this server's**
+ public IP from the cloud console, not your computer's IP. Private addresses and
+ public-IP lookup services (which may report a shared NAT/proxy) are not used.
+ The detected address is shown in the authorization summary, not proof that SSH
+ is reachable. Use `--ssh-user` or `--host` to override.
3. Review the **full nanobot access** authorization on the server and confirm it.
If its config belongs to another service account, the command first asks
**Continue as server administrator?**. Confirm to continue via your existing
diff --git a/nanobot/cli/remote.py b/nanobot/cli/remote.py
index f9819521c..5281cc26e 100644
--- a/nanobot/cli/remote.py
+++ b/nanobot/cli/remote.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import http.client
import ipaddress
import os
import shlex
@@ -19,17 +20,50 @@ app = typer.Typer(help="Pair this server with a local nanobot. No public WebUI o
def _default_host() -> str:
- """Use only a globally reachable address reported by this SSH session.
+ """Suggest this server's address from the SSH session or instance metadata.
- 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.
+ Outbound-IP lookup services can return a shared NAT/proxy, not this server.
+ Only the recognized cloud's fixed public-address metadata field is queried.
"""
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 ""
+ if address and address.is_global and not address.is_multicast:
+ return str(address)
except ValueError:
+ pass
+ return _tencent_public_host()
+
+
+def _tencent_public_host() -> str:
+ """Read one non-secret field on Tencent instances; never probe other clouds.
+
+ This is an operator-run setup command, not an agent HTTP tool. Keep metadata
+ access fixed and local: no arbitrary URLs, redirects, proxies or credentials.
+ A literal link-local endpoint avoids DNS/proxy delays on non-cloud networks.
+ Unsupported installations and unavailable metadata keep the manual fallback.
+ """
+ try:
+ if sys.platform != "linux" or Path("/sys/class/dmi/id/sys_vendor").read_text().strip() != "Tencent Cloud":
+ return ""
+ except (OSError, UnicodeError):
+ return ""
+ connection = http.client.HTTPConnection("169.254.0.23", timeout=1)
+ try:
+ connection.request("GET", "/latest/meta-data/public-ipv4",
+ headers={"Host": "metadata.tencentyun.com"})
+ response = connection.getresponse()
+ if response.status != 200:
+ return ""
+ raw = response.read(64)
+ if len(raw) >= 64:
+ return ""
+ address = ipaddress.IPv4Address(raw.decode("ascii").strip())
+ return str(address) if address.is_global and not address.is_multicast else ""
+ except (OSError, ValueError, http.client.HTTPException):
return ""
+ finally:
+ connection.close()
def _default_ssh_user() -> str | None:
@@ -79,7 +113,7 @@ def _pair_as_administrator(request: str, config: Path, host: str, ssh_user: str,
@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"),
+ host: str = typer.Option("", help="Public IP or hostname of this server, 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"),
@@ -124,8 +158,12 @@ def pair(
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)}")
+ host = _default_host()
+ if not host:
+ typer.echo("Could not detect this server's public address.\n"
+ "Use the public IP shown for this server in your cloud console, not your computer's IP.")
+ host = typer.prompt("This server's public IP or hostname")
+ typer.echo(f"\nAuthorize {invitation.label} to use nanobot on this server ({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.")
if not typer.confirm("Authorize this computer?", default=False):
typer.echo("Cancelled. No device was authorized. Run the pairing command again when ready.")
diff --git a/tests/cli/test_remote_pair_admin.py b/tests/cli/test_remote_pair_admin.py
index fc25536b1..c20f2a930 100644
--- a/tests/cli/test_remote_pair_admin.py
+++ b/tests/cli/test_remote_pair_admin.py
@@ -165,3 +165,37 @@ def test_protected_parent_directory_offers_same_recovery(protected, monkeypatch)
assert "Continue as server administrator?" in result.output
protected.metadata.assert_not_called()
protected.run.assert_not_called()
+
+
+def test_detected_address_skips_ip_prompt_and_identifies_this_server(protected):
+ protected.metadata.side_effect = None
+ protected.metadata.return_value = {"port": 8765}
+ result = CliRunner().invoke(remote.app, protected.args, input="n\n")
+ assert result.exit_code == 0, result.output
+ assert "on this server ([email protected])" in result.output
+ assert "This server's public IP or hostname:" not in result.output
+ assert "Could not detect" not in result.output
+ protected.authorize.assert_not_called()
+
+
+def test_manual_fallback_names_this_server_not_the_local_computer(protected, monkeypatch):
+ protected.metadata.side_effect = None
+ protected.metadata.return_value = {"port": 8765}
+ monkeypatch.setattr(remote, "_default_host", lambda: "")
+ result = CliRunner().invoke(remote.app, protected.args, input="43.156.243.141\nn\n")
+ assert result.exit_code == 0, result.output
+ assert "This server's public IP or hostname:" in result.output
+ assert "not your computer's IP" in result.output
+ assert "on this server ([email protected])" in result.output
+ protected.authorize.assert_not_called()
+
+
+def test_explicit_host_skips_address_detection(protected, monkeypatch):
+ protected.metadata.side_effect = None
+ protected.metadata.return_value = {"port": 8765}
+ detect = Mock()
+ monkeypatch.setattr(remote, "_default_host", detect)
+ result = CliRunner().invoke(remote.app, protected.args + ["--host", "server.example"], input="n\n")
+ assert result.exit_code == 0, result.output
+ assert "on this server ([email protected])" in result.output
+ detect.assert_not_called()
diff --git a/tests/cli/test_remote_pair_defaults.py b/tests/cli/test_remote_pair_defaults.py
index 458f2d7f8..016a21e21 100644
--- a/tests/cli/test_remote_pair_defaults.py
+++ b/tests/cli/test_remote_pair_defaults.py
@@ -32,4 +32,5 @@ def test_pair_suggests_existing_login_account(monkeypatch, uid, sudo_user, expec
])
def test_only_global_ssh_server_address_can_be_suggested(monkeypatch, connection, expected):
monkeypatch.setenv("SSH_CONNECTION", connection)
+ monkeypatch.setattr(remote, "_tencent_public_host", lambda: "")
assert remote._default_host() == expected
diff --git a/tests/cli/test_remote_pair_host.py b/tests/cli/test_remote_pair_host.py
new file mode 100644
index 000000000..b9220cbbf
--- /dev/null
+++ b/tests/cli/test_remote_pair_host.py
@@ -0,0 +1,100 @@
+"""Pairing knows whose public IP it needs, without querying arbitrary metadata."""
+
+import http.client
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+
+from nanobot.cli import remote
+
+
+def metadata(monkeypatch):
+ monkeypatch.setattr(remote.sys, "platform", "linux")
+ monkeypatch.setattr(Path, "read_text", lambda _: "Tencent Cloud\n")
+ response = Mock(status=200)
+ response.read.return_value = b"43.156.243.141\n"
+ connection = Mock()
+ connection.getresponse.return_value = response
+ factory = Mock(return_value=connection)
+ monkeypatch.setattr(remote.http.client, "HTTPConnection", factory)
+ return factory, connection, response
+
+
+def test_tencent_uses_only_fixed_public_address_field(metadata, monkeypatch):
+ factory, connection, response = metadata
+ monkeypatch.setenv("HTTP_PROXY", "http://proxy.invalid:8888")
+ assert remote._tencent_public_host() == "43.156.243.141"
+ factory.assert_called_once_with("169.254.0.23", timeout=1)
+ connection.request.assert_called_once_with("GET", "/latest/meta-data/public-ipv4",
+ headers={"Host": "metadata.tencentyun.com"})
+ response.read.assert_called_once_with(64)
+ connection.close.assert_called_once()
+
+
[email protected]("vendor", ["Amazon EC2", "Google", "QEMU", "", "Tencent Cloud impostor"])
+def test_other_machines_do_not_probe_metadata(metadata, monkeypatch, vendor):
+ factory, _, _ = metadata
+ monkeypatch.setattr(Path, "read_text", lambda _: vendor)
+ assert remote._tencent_public_host() == ""
+ factory.assert_not_called()
+
+
[email protected]("platform", ["darwin", "win32"])
+def test_non_linux_never_probes(metadata, monkeypatch, platform):
+ factory, _, _ = metadata
+ monkeypatch.setattr(remote.sys, "platform", platform)
+ assert remote._tencent_public_host() == ""
+ factory.assert_not_called()
+
+
[email protected]("error", [PermissionError(), FileNotFoundError(), UnicodeError()])
+def test_unreadable_machine_identity_falls_back(metadata, monkeypatch, error):
+ factory, _, _ = metadata
+ monkeypatch.setattr(Path, "read_text", Mock(side_effect=error))
+ assert remote._tencent_public_host() == ""
+ factory.assert_not_called()
+
+
[email protected]("value", [b"10.0.0.8", b"127.0.0.1", b"169.254.0.23", b"100.64.0.1",
+ b"0.0.0.0", b"224.0.0.1", b"255.255.255.255", b"::1", b"2606:4700::1111",
+ b"8.8.8.8\n1.1.1.1", b"host.example", b"", b"\xff", b"x" * 64,
+ b"8.8.8.8" + b" " * 57, b"{\"credentials\":\"never-used\"}"])
+def test_only_one_bounded_global_ipv4_is_accepted(metadata, value):
+ _, connection, response = metadata
+ response.read.return_value = value
+ assert remote._tencent_public_host() == ""
+ connection.close.assert_called_once()
+
+
[email protected]("status", [301, 302, 401, 403, 404, 500])
+def test_redirects_and_errors_are_not_followed(metadata, status):
+ _, connection, response = metadata
+ response.status = status
+ assert remote._tencent_public_host() == ""
+ response.read.assert_not_called()
+ assert connection.request.call_count == 1
+ connection.close.assert_called_once()
+
+
[email protected]("error", [TimeoutError(), ConnectionRefusedError(), http.client.HTTPException()])
+def test_failed_lookup_falls_back_and_closes_connection(metadata, error):
+ _, connection, _ = metadata
+ connection.getresponse.side_effect = error
+ assert remote._tencent_public_host() == ""
+ connection.close.assert_called_once()
+
+
[email protected]("ssh_connection", ["", "proxy 50000 10.0.0.8 22", "invalid",
+ "proxy 50000 224.0.0.1 22"])
+def test_cloud_console_without_public_ssh_address_uses_instance_metadata(metadata, monkeypatch, ssh_connection):
+ monkeypatch.setenv("SSH_CONNECTION", ssh_connection)
+ assert remote._default_host() == "43.156.243.141"
+
+
+def test_public_ssh_address_takes_precedence(metadata, monkeypatch):
+ factory, _, _ = metadata
+ monkeypatch.setenv("SSH_CONNECTION", "1.1.1.1 50000 8.8.8.8 22")
+ assert remote._default_host() == "8.8.8.8"
+ factory.assert_not_called()