feat(remote): serve local WebUI with an explicit host contract
This commit is contained in:
1 parent
02ce0cfb6f
commit
5aa91b66cc
14 files changed
+489
-59
No files matched your search
@@ -806,6 +806,7 @@ class WebSocketChannel(BaseChannel):
|
||||
client_id = client_id[:128]
|
||||
|
||||
default_chat_id = str(uuid.uuid4())
|
||||
from nanobot.webui.client_contract import gateway_identity
|
||||
|
||||
try:
|
||||
await connection.send(
|
||||
@@ -814,9 +815,8 @@ class WebSocketChannel(BaseChannel):
|
||||
"event": "ready",
|
||||
"chat_id": default_chat_id,
|
||||
"client_id": client_id,
|
||||
**({"terminal": {
|
||||
"protocolVersion": 1, "gatewayId": self.gateway.tokens.instance_id,
|
||||
}} if _query_first(query, "terminal_protocol") == "1" else {}),
|
||||
**({"terminal": gateway_identity(self.gateway.tokens.instance_id)}
|
||||
if _query_first(query, "terminal_protocol") == "1" else {}),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""The contract between a shipped WebUI and an independently updated gateway.
|
||||
|
||||
Package versions are display metadata, not compatibility decisions. Adding an
|
||||
optional capability must not raise the protocol floor for unrelated features.
|
||||
See .agent/review-guide.md before changing this contract.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, TypedDict, cast
|
||||
|
||||
from nanobot import __version__
|
||||
|
||||
WEBUI_PROTOCOL = 1
|
||||
CORE_CAPABILITY = "webui.core.v1"
|
||||
|
||||
|
||||
class Compatibility(TypedDict):
|
||||
status: Literal["compatible", "unknown", "update_host", "update_client"]
|
||||
client_version: str
|
||||
host_version: str
|
||||
|
||||
|
||||
def webui_contract() -> dict[str, object]:
|
||||
return {
|
||||
"version": __version__,
|
||||
"min_protocol": WEBUI_PROTOCOL,
|
||||
"max_protocol": WEBUI_PROTOCOL,
|
||||
"capabilities": [CORE_CAPABILITY],
|
||||
}
|
||||
|
||||
|
||||
def gateway_identity(gateway_id: str) -> dict[str, object]:
|
||||
# protocolVersion belongs to the pre-existing terminal transport contract.
|
||||
# Do not overload it with the version of the independently shipped WebUI.
|
||||
return {"protocolVersion": 1, "gatewayId": gateway_id, "webui": webui_contract()}
|
||||
|
||||
|
||||
def assess_webui_contract(value: object) -> Compatibility:
|
||||
result: Compatibility = {
|
||||
"status": "unknown", "client_version": __version__, "host_version": "",
|
||||
}
|
||||
if not isinstance(value, dict):
|
||||
return result
|
||||
# Only the mapping shape is established here; validate each value below.
|
||||
data = cast(dict[object, object], value)
|
||||
version = data.get("version")
|
||||
if isinstance(version, str) and len(version) <= 80 and version.isprintable():
|
||||
result["host_version"] = version
|
||||
minimum, maximum = data.get("min_protocol"), data.get("max_protocol")
|
||||
capabilities = data.get("capabilities")
|
||||
if (type(minimum) is not int or type(maximum) is not int
|
||||
or not 1 <= minimum <= maximum
|
||||
or not isinstance(capabilities, list)
|
||||
or not all(isinstance(item, str) for item in cast(list[object], capabilities))):
|
||||
return result
|
||||
if minimum > WEBUI_PROTOCOL:
|
||||
result["status"] = "update_client"
|
||||
elif maximum < WEBUI_PROTOCOL or CORE_CAPABILITY not in capabilities:
|
||||
result["status"] = "update_host"
|
||||
else:
|
||||
result["status"] = "compatible"
|
||||
return result
|
||||
|
||||
|
||||
def compatibility_error(report: Compatibility) -> str:
|
||||
return {
|
||||
"compatible": "", "unknown": "webui_compatibility_unknown",
|
||||
"update_host": "host_update_required", "update_client": "client_update_required",
|
||||
}[report["status"]]
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Serve only the installed client's assets on each isolated host origin.
|
||||
|
||||
Missing files never fall through to the remote host. Remote data must not be
|
||||
able to replace executable frontend code, styles, or the application's shell.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
from nanobot.webui.build import default_webui_dist_dir
|
||||
|
||||
_HASHED_ASSET = re.compile(r"assets/[^/]+-[A-Za-z0-9_-]{8,}\.(?:js|css|woff2?|ttf|svg|png|webp|ico)$")
|
||||
_ROOT_FILES = {"index.html", "manifest.json", "asset-manifest.json", "sw.js",
|
||||
"notification.wav", "favicon.ico", "robots.txt"}
|
||||
|
||||
|
||||
class LocalClientAssets:
|
||||
def __init__(self, directory: Path | None = None) -> None:
|
||||
self.directory = (directory or default_webui_dist_dir()).resolve()
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
return (self.directory / "index.html").is_file()
|
||||
|
||||
def response(self, request: web.Request) -> web.FileResponse:
|
||||
if request.method not in {"GET", "HEAD"}:
|
||||
raise web.HTTPMethodNotAllowed(request.method, ["GET", "HEAD"])
|
||||
relative = request.path.lstrip("/") or "index.html"
|
||||
if (relative not in _ROOT_FILES and not relative.startswith(("assets/", "brand/", "fonts/"))
|
||||
or ".." in relative.split("/") or "\\" in relative):
|
||||
raise web.HTTPNotFound()
|
||||
candidate = (self.directory / relative).resolve()
|
||||
if not candidate.is_relative_to(self.directory) or not candidate.is_file():
|
||||
raise web.HTTPNotFound()
|
||||
# FileResponse may automatically choose a compressed sibling.
|
||||
for suffix in (".br", ".gz"):
|
||||
if not candidate.with_name(candidate.name + suffix).resolve().is_relative_to(self.directory):
|
||||
raise web.HTTPNotFound()
|
||||
cache = "private, max-age=31536000, immutable" if _HASHED_ASSET.fullmatch(relative) else "no-cache"
|
||||
return web.FileResponse(candidate, headers={
|
||||
"Cache-Control": cache, "X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "no-referrer", "X-Nanobot-UI": "local",
|
||||
})
|
||||
@@ -18,6 +18,7 @@ from pydantic import Field
|
||||
|
||||
from nanobot.utils.helpers import _write_text_atomic # pyright: ignore[reportPrivateUsage]
|
||||
from nanobot.webui import remote_ssh
|
||||
from nanobot.webui.client_contract import Compatibility, assess_webui_contract, compatibility_error
|
||||
from nanobot.webui.remote_proxy import RemoteProxy
|
||||
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, Tunnel
|
||||
|
||||
@@ -29,6 +30,7 @@ class _SavedProfile(RemoteProfile):
|
||||
# between servers on every reconnect. Not an editable API field.
|
||||
local_port: int = Field(default=0, ge=0, le=65535)
|
||||
proxy_origin: bool = False
|
||||
local_client_origin: bool = False
|
||||
pair_id: str = ""
|
||||
|
||||
|
||||
@@ -60,6 +62,7 @@ class RemoteInstances:
|
||||
self._unverified: dict[str, tuple[str, str, float]] = {}
|
||||
self._unknown_hosts: set[str] = set()
|
||||
self._closed = False
|
||||
self._compatibility: dict[str, Compatibility] = {}
|
||||
from nanobot.webui.remote_pairing import PairStore
|
||||
|
||||
self.pairing = PairStore(directory)
|
||||
@@ -129,12 +132,16 @@ class RemoteInstances:
|
||||
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"}),
|
||||
item = {"id": key, **profile.model_dump(exclude={"local_port", "proxy_origin", "local_client_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 key in self._compatibility:
|
||||
item["compatibility"] = self._compatibility[key]
|
||||
if not connection and (compatibility_failure := compatibility_error(self._compatibility[key])):
|
||||
item["connection_error"] = compatibility_failure
|
||||
if profile.pair_id:
|
||||
item.update(paired=True, revoke_command=
|
||||
f"nanobot remote revoke {profile.pair_id} --ssh-user {profile.host.split('@')[0]}")
|
||||
@@ -147,7 +154,10 @@ class RemoteInstances:
|
||||
# display names, addresses alone, or transient gateway IDs.
|
||||
item["instance_id"] = instances.setdefault(receipt.destination(), key)
|
||||
profiles.append(item)
|
||||
return {"available": True, "machine_name": socket.gethostname(), "profiles": profiles}
|
||||
from nanobot import __version__
|
||||
|
||||
return {"available": True, "machine_name": socket.gethostname(),
|
||||
"client_version": __version__, "profiles": profiles}
|
||||
|
||||
async def health(self) -> dict[str, Any]:
|
||||
# Hold a lifetime lease through every credential-bearing request. Final
|
||||
@@ -185,7 +195,13 @@ class RemoteInstances:
|
||||
elif identity["gatewayId"] != connection.gateway_id:
|
||||
connection.error = "instance_changed"
|
||||
else:
|
||||
connection.error = ""
|
||||
report = assess_webui_contract(identity.get("webui"))
|
||||
for key, item in self.connections.items():
|
||||
if item is connection:
|
||||
self._compatibility[key] = report
|
||||
connection.error = compatibility_error(report)
|
||||
if connection.error:
|
||||
await connection.proxy.pause()
|
||||
except (httpx.HTTPError, ValueError, AttributeError):
|
||||
connection.error = connection.tunnel.error or "remote_unreachable"
|
||||
if connection.paired and connection.error == "ssh_auth_failed":
|
||||
@@ -411,6 +427,7 @@ class RemoteInstances:
|
||||
if connection:
|
||||
await connection.proxy.pause()
|
||||
if action == "remove":
|
||||
self._compatibility.pop(key, None)
|
||||
if pair_id:
|
||||
self.pairing.forget(pair_id)
|
||||
self._known_hosts(key).unlink(missing_ok=True)
|
||||
@@ -435,6 +452,7 @@ class RemoteInstances:
|
||||
del self.connections[key]
|
||||
if len(self.connections) >= 4:
|
||||
raise RemoteError("connection_limit")
|
||||
self._compatibility.pop(key, None)
|
||||
known_hosts = self._known_hosts(key)
|
||||
transport: RemoteProfile = profile
|
||||
if profile.pair_id:
|
||||
@@ -445,7 +463,9 @@ class RemoteInstances:
|
||||
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
|
||||
# Retire origins that previously executed remote-provided JS, including
|
||||
# persistent service workers. They cannot intercept this local client.
|
||||
local_port = profile.local_port if profile.proxy_origin and profile.local_client_origin else 0
|
||||
proxy = self._proxies.get(local_port)
|
||||
if proxy is not None:
|
||||
tunnel = proxy.tunnel
|
||||
@@ -481,10 +501,11 @@ class RemoteInstances:
|
||||
await self._check(item)
|
||||
if any(not item.error for _, item in duplicates):
|
||||
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")
|
||||
# The host supplies data only. Its frontend need not be installed.
|
||||
report = assess_webui_contract(identity.get("webui"))
|
||||
self._compatibility[key] = report
|
||||
if error := compatibility_error(report):
|
||||
raise RemoteError(error)
|
||||
issue_path = data.get("token_issue_path", "")
|
||||
if not isinstance(issue_path, str):
|
||||
raise RemoteError("incompatible_gateway")
|
||||
@@ -504,6 +525,7 @@ class RemoteInstances:
|
||||
self._remember_origins(profiles, proxy.port)
|
||||
profiles[key].local_port = proxy.port
|
||||
profiles[key].proxy_origin = True
|
||||
profiles[key].local_client_origin = True
|
||||
self._write(profiles)
|
||||
# A failed route must not block a newly verified route to this bot.
|
||||
# Retire it only after the replacement is saved; retain its profile
|
||||
|
||||
@@ -27,11 +27,16 @@ 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]
|
||||
from nanobot.webui.client_contract import assess_webui_contract, compatibility_error
|
||||
from nanobot.webui.local_client_assets import LocalClientAssets
|
||||
from nanobot.webui.remote_ssh import (
|
||||
RemoteError,
|
||||
Tunnel,
|
||||
_listen, # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
|
||||
_MAX_BYTES = 64 * 1024 * 1024
|
||||
_MAX_CAPABILITIES = 10000
|
||||
_STATIC_ASSET = re.compile(r"/assets/[^/]+-[A-Za-z0-9_-]{8,}\.(?:js|css|woff2?|ttf|svg|png|webp|ico)$")
|
||||
_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.
|
||||
@@ -72,6 +77,7 @@ class RemoteProxy:
|
||||
self._bootstrap_lock = asyncio.Lock()
|
||||
self._enabled = True
|
||||
self._runner: web.AppRunner | None = None
|
||||
self.assets = LocalClientAssets()
|
||||
|
||||
@classmethod
|
||||
async def open(
|
||||
@@ -79,6 +85,8 @@ class RemoteProxy:
|
||||
*, local_port: int = 0, excluded_ports: set[int] | None = None,
|
||||
) -> RemoteProxy:
|
||||
self = cls(tunnel, secret, gateway_id, issue_path)
|
||||
if not self.assets.available:
|
||||
raise RemoteError("local_webui_unavailable")
|
||||
listener = _listen(local_port, excluded_ports or set())
|
||||
self.port = int(listener.getsockname()[1])
|
||||
app = web.Application(client_max_size=_MAX_BYTES)
|
||||
@@ -188,6 +196,8 @@ class RemoteProxy:
|
||||
return await self._bootstrap()
|
||||
if path == "/webui/terminal":
|
||||
raise web.HTTPForbidden()
|
||||
if not path.startswith("/api/"):
|
||||
return self.assets.response(request)
|
||||
return await self._http(request, path)
|
||||
except (httpx.HTTPError, WebSocketException, OSError, ValueError):
|
||||
# Never reflect upstream URLs, credentials or raw exception text.
|
||||
@@ -226,6 +236,11 @@ class RemoteProxy:
|
||||
if not isinstance(terminal, dict):
|
||||
raise ValueError("invalid terminal")
|
||||
terminal = cast(dict[str, Any], terminal)
|
||||
report = assess_webui_contract(terminal.get("webui"))
|
||||
error = compatibility_error(report)
|
||||
if error:
|
||||
return web.json_response({"error": error, "compatibility": report}, status=409,
|
||||
headers={"Cache-Control": "no-store"})
|
||||
ttl, ws_path = data.get("expires_in"), data.get("ws_path")
|
||||
if (terminal.get("gatewayId") != self._gateway_id
|
||||
or terminal.get("protocolVersion") != 1
|
||||
@@ -246,6 +261,7 @@ class RemoteProxy:
|
||||
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}")
|
||||
result["host_compatibility"] = report
|
||||
return web.json_response(result, headers={"Cache-Control": "no-store"})
|
||||
|
||||
def _local_media(self, match: re.Match[str]) -> str:
|
||||
@@ -297,7 +313,7 @@ class RemoteProxy:
|
||||
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
|
||||
# HTTP API 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"])
|
||||
@@ -308,16 +324,12 @@ class RemoteProxy:
|
||||
outgoing = {key: value for key, value in upstream.headers.items()
|
||||
if key.lower() in _RESPONSE_HEADERS}
|
||||
outgoing["Cache-Control"] = "no-store"
|
||||
upstream_cache = upstream.headers.get("cache-control", "").lower()
|
||||
if (upstream.status_code == 200 and _STATIC_ASSET.fullmatch(path)
|
||||
and not request.rel_url.query and "set-cookie" not in upstream.headers
|
||||
and "public" in upstream_cache and "immutable" in upstream_cache
|
||||
and "no-store" not in upstream_cache and "private" not in upstream_cache
|
||||
and "no-cache" not in upstream_cache and "must-revalidate" not in upstream_cache
|
||||
and "application/json" not in upstream.headers.get("content-type", "")):
|
||||
# Only versioned public build assets, never HTML, API data,
|
||||
# credentials or media capabilities. Keep caches browser-local.
|
||||
outgoing["Cache-Control"] = re.sub(r"\bpublic\b", "private", upstream_cache)
|
||||
# Remote documents/media are data, never executable client code.
|
||||
# Keep them sandboxed even if a host omits or relaxes its headers.
|
||||
outgoing["X-Content-Type-Options"] = "nosniff"
|
||||
outgoing["Content-Security-Policy"] = (
|
||||
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:"
|
||||
)
|
||||
if "application/json" in upstream.headers.get("content-type", ""):
|
||||
body = bytearray()
|
||||
async for chunk in upstream.aiter_bytes():
|
||||
|
||||
@@ -736,7 +736,9 @@ class GatewayHTTPHandler:
|
||||
elif not is_local_browser:
|
||||
return _http_error(403, "bootstrap is localhost-only")
|
||||
|
||||
terminal = {"protocolVersion": 1, "gatewayId": self.tokens.instance_id}
|
||||
from nanobot.webui.client_contract import gateway_identity
|
||||
|
||||
terminal = gateway_identity(self.tokens.instance_id)
|
||||
if terminal_probe:
|
||||
# Capability probing does not allocate credentials or acquire client leases.
|
||||
return _http_json_response(terminal, extra_headers=_NO_STORE_HEADERS)
|
||||
|
||||
Reference in new issue
Block a user