From 5aa91b66cc4dab7b5ba025813af031ba77044702 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:42:30 +0800 Subject: [PATCH] feat(remote): serve local WebUI with an explicit host contract --- .agent/review-guide.md | 73 ++++++++++++++++++++ AGENTS.md | 1 + CONTRIBUTING.md | 4 ++ docs/guides/remote-instances.md | 56 +++++++++++++--- nanobot/channels/websocket/runtime.py | 6 +- nanobot/webui/client_contract.py | 70 ++++++++++++++++++++ nanobot/webui/local_client_assets.py | 47 +++++++++++++ nanobot/webui/remote_instances.py | 38 ++++++++--- nanobot/webui/remote_proxy.py | 38 +++++++---- nanobot/webui/ws_http.py | 4 +- tests/webui/test_client_contract.py | 59 +++++++++++++++++ tests/webui/test_gateway_terminal.py | 5 +- tests/webui/test_remote_instances.py | 52 ++++++++++++++- tests/webui/test_remote_proxy.py | 95 +++++++++++++++++++++------ 14 files changed, 489 insertions(+), 59 deletions(-) create mode 100644 .agent/review-guide.md create mode 100644 nanobot/webui/client_contract.py create mode 100644 nanobot/webui/local_client_assets.py create mode 100644 tests/webui/test_client_contract.py diff --git a/.agent/review-guide.md b/.agent/review-guide.md new file mode 100644 index 000000000..4a3df25ff --- /dev/null +++ b/.agent/review-guide.md @@ -0,0 +1,73 @@ +# Review guide: independently updated WebUI clients and hosts + +Apply this checklist to changes to WebUI HTTP, WebSocket events/mutations, +bootstrap, capabilities, host switching, and persisted browser state. Read this +alongside the design and security constraints, not instead of them. + +## Compatibility is a contract, not a package-version comparison + +- The local installation owns executable WebUI assets. A remote host supplies + authenticated data, events, and media, never replacement JavaScript or CSS. +- Negotiate the WebUI protocol in `webui/client_contract.py`. The pre-existing + terminal `protocolVersion` is a separate contract; do not overload it. +- Different package versions may use the same protocol. New hosts should keep + the previously supported protocol when possible. Extra fields and unknown + optional capabilities must not break older clients. +- Add optional features as named capabilities. Gate their controls and requests + at their owning interface; do not require a server upgrade for unrelated + features. Raise the core protocol floor only for an intentional breaking + change with a documented support window and migration path. +- Missing/malformed metadata means **compatibility unconfirmed**, not “old + server,” “bad SSH key,” or “network error.” Do not infer support from matching + package versions. An unconfirmed core contract cannot authorize mutations. +- A package update being available is not proof of incompatibility. Optional + update notices must use verified release data, be dismissible, and never + interrupt an otherwise compatible session. + +## Required proof for a changed contract + +- Current client/current host, current client/oldest supported host, and oldest + supported client/current host. State the supported protocol range explicitly; + never claim every historical nanobot release is supported. +- Unknown, missing, malformed and future metadata; overlapping and disjoint + protocol ranges; unknown optional capabilities; missing required capability. +- Assert the actual public bootstrap/read/mutation/event behavior, not only a + version-comparison helper. Keep an older client/host fixture independent of + the implementation under test. Test the affected optional feature's fallback. +- Reconnect after a host restart or upgrade. Previously issued credentials and + stale cached compatibility must not bypass a changed host contract. +- Prove local HTML/JS/CSS are used even when remote static files are missing or + different. Missing local assets fail locally, never fall back to remote code. +- HTTP reads, streamed messages, upload/download, cancellation, multiple tabs, + and a response arriving after switching hosts remain scoped to their host. +- Preserve drafts/preferences without mixing authentication, model choices, + conversation history, file paths, or command execution across host origins. + +## Update UX and operator safety + +- Report the local version, host version (or “not reported”), compatibility, + and which machine needs updating. A newer host must not be told to downgrade + when the client needs updating. +- Keep compatible version differences quiet. Show missing optional capabilities + at the affected control. Block only unsupported core sessions or operations. +- Reuse the application's settings rows, menus and dialogs. Do not introduce a + second settings drawer or a persistent global warning for an optional update. +- Explain that updating this computer does not update its hosts. Use the installation + environment that owns the running process: installer/uv/pipx/pip, checkout, + container, and service-managed deployments are not interchangeable. +- Never silently install, restart, downgrade, revoke credentials, or reset + configuration. Back up configuration/data and consider active tasks before + an explicitly requested update. Verify the running process after restart, + not merely whichever `nanobot` executable happens to be on PATH. +- Update user documentation with the change. Do not present planned support or + fixture-only tests as a completed real-server acceptance test. + +## Current baseline + +WebUI protocol **1** with capability **`webui.core.v1`** is the initial explicit +client/host contract. It covers the existing authenticated WebUI read, mutation, +event, and media interfaces. Hosts predating this declaration are unconfirmed; +the local-client mode requires updating them to a build that declares support. +Their independent server WebUI remains a separate way to use that installation. +This is an intentional prerequisite for local-client mode, not a blanket claim +that legacy nanobot installations no longer function. diff --git a/AGENTS.md b/AGENTS.md index 8f098bd67..7eac06e96 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,7 @@ The Python gateway owns agent execution, sessions, tools, memory, and security p | Path permissions, HTTP/MCP, or shell isolation | [`.agent/security.md`](.agent/security.md) | | Dependency setup, WebUI transport, config, Windows, prompts, or persistence | [`.agent/gotchas.md`](.agent/gotchas.md) | | Reusing verification evidence | [`.agent/workflow.md`](.agent/workflow.md) | +| WebUI/host compatibility | [`.agent/review-guide.md`](.agent/review-guide.md) | | Contribution or publication | [`CONTRIBUTING.md`](CONTRIBUTING.md), [`docs/releasing.md`](docs/releasing.md) | ## Development constraints diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 255a87a2b..6a1e1d2e9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -35,6 +35,10 @@ PRs are welcome for: For riskier or larger changes, please open an issue or draft PR early so the shape of the work can be discussed before the implementation grows too large. +WebUI and remote-host interface changes must follow the +[client/host compatibility review checklist](.agent/review-guide.md), including +independent client/server upgrades, host isolation, and actionable update guidance. + ### Starting Work Before making changes, sync your local checkout and create a topic branch. diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.md index f4152b8e6..0daea6ea6 100644 --- a/docs/guides/remote-instances.md +++ b/docs/guides/remote-instances.md @@ -224,7 +224,8 @@ and forced TTY are disabled for the fixed nanobot probe. - The remote server needs `python3` and an already running nanobot WebUI with a configured `tokenIssueSecret` (or `token`) in its configuration file. - The remote gateway must support the authenticated `/webui/terminal` - identity probe, protocol version 1, and have the WebUI bundle installed. + identity probe and the supported WebUI client contract. The local installation + must have its WebUI bundle; the remote host only needs the backend endpoints. The initial transport supports HTTP on the server's loopback address; SSH encrypts the connection. A configured public WebSocket URL or trusted-proxy authentication is not supported by this SSH connection mode. @@ -271,21 +272,58 @@ checks expiry and revocation on every new stream. Older bridges still work with fresh authentication per stream. Pair again after upgrading the server to install the guarded bridge; upgrading nanobot alone does not rewrite existing grants. -Versioned public JS/CSS and other build assets are cached in this browser, so -refreshes do not download the same bundle again. HTML, API responses, credentials -and media capabilities remain uncached by the proxy. Initial authentication, -uncached assets and network latency still affect the first connection; reuse +The interface's HTML, JS, CSS and bundled images come from your **local nanobot +installation**, not the server. Versioned local assets can be cached in the +browser; HTML is revalidated. API responses, credentials and media capabilities +remain uncached by the proxy. Initial authentication and network latency still +affect the first connection; reuse does not bypass a blocked SSH route or VPN policy. ## Using the remote instance -The remote instance's **own complete WebUI** fills the main window. Its UI -version follows the server, independently of the local -installation. Model settings, channels, tools and conversations belong to that -server. The isolated remote view cannot navigate the local application's +The **local WebUI** displays the selected server's data. Interface updates follow +your local installation; model settings, channels, tools and conversations still +belong to the server. Every host uses an isolated browser origin and runtime, but +all of them load the same locally installed frontend. The server's static WebUI +bundle is not required for this mode. The isolated view cannot navigate the local application's top-level window. The first version has been exercised in macOS Chrome; native desktop-host packaging and other platforms still need their own acceptance. +When upgrading from the earlier remote-page mode, the first reconnect reserves +a fresh local browser origin. This prevents previously loaded remote service +workers or cached code from controlling the local client. Saved SSH profiles, +pairing authorizations, and server conversations remain intact; origin-local +browser preferences may return to their defaults. Finish or copy unsent drafts +before restarting the local application for this upgrade. + +### Versions and updating the right machine + +Open a server's **… → Version & compatibility** in **Manage connections…** to see +the local and server versions and the compatibility result. Matching package +versions are not required: both sides must support a common WebUI protocol. +Compatible version differences do not show an update warning. + +- **Compatibility not confirmed:** the host has not advertised a supported + WebUI contract. This is not evidence of a broken key, VPN issue, or simply an + old version. Local-client mode cannot safely proceed until support is confirmed. + For older installations, update nanobot on that server and reconnect. +- **Update this server:** its advertised contract lacks the client's required + core features. Update the server, not merely this computer. +- **Update this computer:** the host requires a newer client protocol. Update + the local installation; do not downgrade the server. + +The initial explicit contract is WebUI protocol 1 with `webui.core.v1`. Older +hosts without this metadata need a compatible update to use local-client mode; +their own server WebUI is unaffected. The terminal transport protocol is separate. + +Use the [update instructions](../quick-start.md#updating) for the same installation +method and environment that run nanobot on the target machine. For a container, +update the deployed image; for a service, update its actual environment rather +than an unrelated shell installation. Back up configuration and data and finish +active tasks before a required restart. Verify the version of the restarted +process, then reconnect. Version checks do not install packages, restart a host, +or change its model, channel, or SSH configuration automatically. + The host switcher lives beside **Settings at the bottom of the sidebar**, showing **Local** or your saved server name. It is also available in Settings. Its menu opens upward and shows the computer name, recent hosts, and **Manage connections…**. diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py index 927e7986a..e9207b911 100644 --- a/nanobot/channels/websocket/runtime.py +++ b/nanobot/channels/websocket/runtime.py @@ -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, ) diff --git a/nanobot/webui/client_contract.py b/nanobot/webui/client_contract.py new file mode 100644 index 000000000..345ea1035 --- /dev/null +++ b/nanobot/webui/client_contract.py @@ -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"]] diff --git a/nanobot/webui/local_client_assets.py b/nanobot/webui/local_client_assets.py new file mode 100644 index 000000000..d665d8f76 --- /dev/null +++ b/nanobot/webui/local_client_assets.py @@ -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", + }) diff --git a/nanobot/webui/remote_instances.py b/nanobot/webui/remote_instances.py index 274ee09b6..b846c43c4 100644 --- a/nanobot/webui/remote_instances.py +++ b/nanobot/webui/remote_instances.py @@ -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 diff --git a/nanobot/webui/remote_proxy.py b/nanobot/webui/remote_proxy.py index 30fbf9d98..34c787463 100644 --- a/nanobot/webui/remote_proxy.py +++ b/nanobot/webui/remote_proxy.py @@ -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(): diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 14f9b609c..b80d0879b 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -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) diff --git a/tests/webui/test_client_contract.py b/tests/webui/test_client_contract.py new file mode 100644 index 000000000..9b3cd21e3 --- /dev/null +++ b/tests/webui/test_client_contract.py @@ -0,0 +1,59 @@ +"""Published package versions never substitute for wire compatibility.""" + +import pytest + +from nanobot.webui.client_contract import assess_webui_contract, compatibility_error, webui_contract + + +def test_initial_host_declaration_is_an_independent_wire_fixture(): + # Frozen initial host payload; intentionally not built using the current producer. + initial_host = { + "version": "0.3.5", + "min_protocol": 1, + "max_protocol": 1, + "capabilities": ["webui.core.v1"], + } + assert assess_webui_contract(initial_host)["status"] == "compatible" + + +def test_current_producer_remains_acceptable_to_initial_client(): + # Initial client's advertised requirement, independent of today's constants. + contract = webui_contract() + assert contract["min_protocol"] <= 1 <= contract["max_protocol"] + assert "webui.core.v1" in contract["capabilities"] + + +@pytest.mark.parametrize("version", ["0.0.1", "9.99.0", "0.3.5.dev17", "custom-build"]) +def test_independently_released_hosts_share_a_protocol(version): + report = assess_webui_contract({**webui_contract(), "version": version}) + assert report["status"] == "compatible" + assert report["host_version"] == version + assert compatibility_error(report) == "" + + +@pytest.mark.parametrize("value", [None, {}, "1", {"min_protocol": True, "max_protocol": 1}, + {"min_protocol": 2, "max_protocol": 1, "capabilities": []}, + {"min_protocol": 1, "max_protocol": 1, "capabilities": "webui.core.v1"}, + {"min_protocol": 1, "max_protocol": 1, "capabilities": [123]}, +]) +def test_missing_or_malformed_metadata_is_unknown_not_outdated(value): + report = assess_webui_contract(value) + assert report["status"] == "unknown" + assert compatibility_error(report) == "webui_compatibility_unknown" + + +def test_new_host_can_explicitly_retain_old_protocol_support(): + assert assess_webui_contract({**webui_contract(), "max_protocol": 2})["status"] == "compatible" + + +def test_recovery_targets_the_correct_machine(): + future = {**webui_contract(), "min_protocol": 2, "max_protocol": 2} + assert compatibility_error(assess_webui_contract(future)) == "client_update_required" + missing = {**webui_contract(), "capabilities": []} + assert compatibility_error(assess_webui_contract(missing)) == "host_update_required" + + +def test_unknown_optional_capabilities_do_not_break_connection(): + value = webui_contract() + value["capabilities"] = ["webui.core.v1", "a-future-optional-feature"] + assert assess_webui_contract(value)["status"] == "compatible" diff --git a/tests/webui/test_gateway_terminal.py b/tests/webui/test_gateway_terminal.py index 6ba30d9e0..cafbe679b 100644 --- a/tests/webui/test_gateway_terminal.py +++ b/tests/webui/test_gateway_terminal.py @@ -7,6 +7,7 @@ from websockets.datastructures import Headers from websockets.http11 import Request from nanobot.channels.websocket.runtime import WebSocketConfig +from nanobot.webui.client_contract import gateway_identity from nanobot.webui.gateway_tokens import GatewayTokenStore from nanobot.webui.ws_http import GatewayHTTPHandler @@ -22,9 +23,7 @@ def test_terminal_probe_is_private_stable_and_does_not_issue_credentials(): for _ in range(3): response = handler._handle_bootstrap(connection, request, terminal_probe=True) assert response.status_code == 200 - assert json.loads(response.body) == { - "protocolVersion": 1, "gatewayId": handler.tokens.instance_id, - } + assert json.loads(response.body) == gateway_identity(handler.tokens.instance_id) assert "no-store" in response.headers["Cache-Control"] assert not handler.tokens.api_tokens and not handler.tokens.issued_tokens assert GatewayTokenStore().instance_id != handler.tokens.instance_id diff --git a/tests/webui/test_remote_instances.py b/tests/webui/test_remote_instances.py index adfba8209..4edda4f54 100644 --- a/tests/webui/test_remote_instances.py +++ b/tests/webui/test_remote_instances.py @@ -16,6 +16,7 @@ from websockets.http11 import Request from nanobot.channels.websocket.runtime import WebSocketConfig from nanobot.webui import remote_instances, remote_ssh +from nanobot.webui.client_contract import webui_contract from nanobot.webui.gateway_services import build_gateway_services from nanobot.webui.remote_instances import RemoteInstances from nanobot.webui.remote_proxy import RemoteProxy @@ -48,13 +49,13 @@ def ssh(monkeypatch): probe = AsyncMock(return_value={"port": 8765, "secret": "private-webui-secret", "hostname": "team-host"}) monkeypatch.setattr(remote_ssh, "probe", probe) monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=tunnel)) - state = {"status": 200, "identity": {"protocolVersion": 1, "gatewayId": "remote-one"}} + state = {"status": 200, "identity": {"protocolVersion": 1, "gatewayId": "remote-one", "webui": webui_contract()}} def respond(request): if request.url.path == "/webui/terminal": assert request.headers["X-Nanobot-Auth"] == "private-webui-secret" return httpx.Response(state["status"], json=state["identity"]) - return httpx.Response(200, text="