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
@@ -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.
|
||||||
@@ -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) |
|
| 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) |
|
| Dependency setup, WebUI transport, config, Windows, prompts, or persistence | [`.agent/gotchas.md`](.agent/gotchas.md) |
|
||||||
| Reusing verification evidence | [`.agent/workflow.md`](.agent/workflow.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) |
|
| Contribution or publication | [`CONTRIBUTING.md`](CONTRIBUTING.md), [`docs/releasing.md`](docs/releasing.md) |
|
||||||
|
|
||||||
## Development constraints
|
## Development constraints
|
||||||
|
|||||||
@@ -35,6 +35,10 @@ PRs are welcome for:
|
|||||||
For riskier or larger changes, please open an issue or draft PR early so the
|
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.
|
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
|
### Starting Work
|
||||||
|
|
||||||
Before making changes, sync your local checkout and create a topic branch.
|
Before making changes, sync your local checkout and create a topic branch.
|
||||||
|
|||||||
@@ -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
|
- The remote server needs `python3` and an already running nanobot WebUI with
|
||||||
a configured `tokenIssueSecret` (or `token`) in its configuration file.
|
a configured `tokenIssueSecret` (or `token`) in its configuration file.
|
||||||
- The remote gateway must support the authenticated `/webui/terminal`
|
- 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
|
The initial transport supports HTTP on the server's loopback address; SSH
|
||||||
encrypts the connection. A configured public WebSocket URL or trusted-proxy
|
encrypts the connection. A configured public WebSocket URL or trusted-proxy
|
||||||
authentication is not supported by this SSH connection mode.
|
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
|
fresh authentication per stream. Pair again after upgrading the server to install
|
||||||
the guarded bridge; upgrading nanobot alone does not rewrite existing grants.
|
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
|
The interface's HTML, JS, CSS and bundled images come from your **local nanobot
|
||||||
refreshes do not download the same bundle again. HTML, API responses, credentials
|
installation**, not the server. Versioned local assets can be cached in the
|
||||||
and media capabilities remain uncached by the proxy. Initial authentication,
|
browser; HTML is revalidated. API responses, credentials and media capabilities
|
||||||
uncached assets and network latency still affect the first connection; reuse
|
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.
|
does not bypass a blocked SSH route or VPN policy.
|
||||||
|
|
||||||
## Using the remote instance
|
## Using the remote instance
|
||||||
|
|
||||||
The remote instance's **own complete WebUI** fills the main window. Its UI
|
The **local WebUI** displays the selected server's data. Interface updates follow
|
||||||
version follows the server, independently of the local
|
your local installation; model settings, channels, tools and conversations still
|
||||||
installation. Model settings, channels, tools and conversations belong to that
|
belong to the server. Every host uses an isolated browser origin and runtime, but
|
||||||
server. The isolated remote view cannot navigate the local application's
|
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
|
top-level window. The first version has been exercised in macOS Chrome; native
|
||||||
desktop-host packaging and other platforms still need their own acceptance.
|
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
|
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
|
**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…**.
|
opens upward and shows the computer name, recent hosts, and **Manage connections…**.
|
||||||
|
|||||||
@@ -806,6 +806,7 @@ class WebSocketChannel(BaseChannel):
|
|||||||
client_id = client_id[:128]
|
client_id = client_id[:128]
|
||||||
|
|
||||||
default_chat_id = str(uuid.uuid4())
|
default_chat_id = str(uuid.uuid4())
|
||||||
|
from nanobot.webui.client_contract import gateway_identity
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await connection.send(
|
await connection.send(
|
||||||
@@ -814,9 +815,8 @@ class WebSocketChannel(BaseChannel):
|
|||||||
"event": "ready",
|
"event": "ready",
|
||||||
"chat_id": default_chat_id,
|
"chat_id": default_chat_id,
|
||||||
"client_id": client_id,
|
"client_id": client_id,
|
||||||
**({"terminal": {
|
**({"terminal": gateway_identity(self.gateway.tokens.instance_id)}
|
||||||
"protocolVersion": 1, "gatewayId": self.gateway.tokens.instance_id,
|
if _query_first(query, "terminal_protocol") == "1" else {}),
|
||||||
}} if _query_first(query, "terminal_protocol") == "1" else {}),
|
|
||||||
},
|
},
|
||||||
ensure_ascii=False,
|
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.utils.helpers import _write_text_atomic # pyright: ignore[reportPrivateUsage]
|
||||||
from nanobot.webui import remote_ssh
|
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_proxy import RemoteProxy
|
||||||
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, Tunnel
|
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.
|
# between servers on every reconnect. Not an editable API field.
|
||||||
local_port: int = Field(default=0, ge=0, le=65535)
|
local_port: int = Field(default=0, ge=0, le=65535)
|
||||||
proxy_origin: bool = False
|
proxy_origin: bool = False
|
||||||
|
local_client_origin: bool = False
|
||||||
pair_id: str = ""
|
pair_id: str = ""
|
||||||
|
|
||||||
|
|
||||||
@@ -60,6 +62,7 @@ class RemoteInstances:
|
|||||||
self._unverified: dict[str, tuple[str, str, float]] = {}
|
self._unverified: dict[str, tuple[str, str, float]] = {}
|
||||||
self._unknown_hosts: set[str] = set()
|
self._unknown_hosts: set[str] = set()
|
||||||
self._closed = False
|
self._closed = False
|
||||||
|
self._compatibility: dict[str, Compatibility] = {}
|
||||||
from nanobot.webui.remote_pairing import PairStore
|
from nanobot.webui.remote_pairing import PairStore
|
||||||
|
|
||||||
self.pairing = PairStore(directory)
|
self.pairing = PairStore(directory)
|
||||||
@@ -129,12 +132,16 @@ class RemoteInstances:
|
|||||||
for key, profile in self._read().items():
|
for key, profile in self._read().items():
|
||||||
connection = self.connections.get(key)
|
connection = self.connections.get(key)
|
||||||
error = (connection.error or ("" if connection.tunnel.active else "ssh_unreachable")) if connection else "disconnected"
|
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,
|
"connected": connection is not None and not error,
|
||||||
"connection_error": error}
|
"connection_error": error}
|
||||||
if connection:
|
if connection:
|
||||||
item["gateway_id"] = connection.gateway_id
|
item["gateway_id"] = connection.gateway_id
|
||||||
item["view_id"] = self._view_session
|
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:
|
if profile.pair_id:
|
||||||
item.update(paired=True, revoke_command=
|
item.update(paired=True, revoke_command=
|
||||||
f"nanobot remote revoke {profile.pair_id} --ssh-user {profile.host.split('@')[0]}")
|
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.
|
# display names, addresses alone, or transient gateway IDs.
|
||||||
item["instance_id"] = instances.setdefault(receipt.destination(), key)
|
item["instance_id"] = instances.setdefault(receipt.destination(), key)
|
||||||
profiles.append(item)
|
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]:
|
async def health(self) -> dict[str, Any]:
|
||||||
# Hold a lifetime lease through every credential-bearing request. Final
|
# Hold a lifetime lease through every credential-bearing request. Final
|
||||||
@@ -185,7 +195,13 @@ class RemoteInstances:
|
|||||||
elif identity["gatewayId"] != connection.gateway_id:
|
elif identity["gatewayId"] != connection.gateway_id:
|
||||||
connection.error = "instance_changed"
|
connection.error = "instance_changed"
|
||||||
else:
|
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):
|
except (httpx.HTTPError, ValueError, AttributeError):
|
||||||
connection.error = connection.tunnel.error or "remote_unreachable"
|
connection.error = connection.tunnel.error or "remote_unreachable"
|
||||||
if connection.paired and connection.error == "ssh_auth_failed":
|
if connection.paired and connection.error == "ssh_auth_failed":
|
||||||
@@ -411,6 +427,7 @@ class RemoteInstances:
|
|||||||
if connection:
|
if connection:
|
||||||
await connection.proxy.pause()
|
await connection.proxy.pause()
|
||||||
if action == "remove":
|
if action == "remove":
|
||||||
|
self._compatibility.pop(key, None)
|
||||||
if pair_id:
|
if pair_id:
|
||||||
self.pairing.forget(pair_id)
|
self.pairing.forget(pair_id)
|
||||||
self._known_hosts(key).unlink(missing_ok=True)
|
self._known_hosts(key).unlink(missing_ok=True)
|
||||||
@@ -435,6 +452,7 @@ class RemoteInstances:
|
|||||||
del self.connections[key]
|
del self.connections[key]
|
||||||
if len(self.connections) >= 4:
|
if len(self.connections) >= 4:
|
||||||
raise RemoteError("connection_limit")
|
raise RemoteError("connection_limit")
|
||||||
|
self._compatibility.pop(key, None)
|
||||||
known_hosts = self._known_hosts(key)
|
known_hosts = self._known_hosts(key)
|
||||||
transport: RemoteProfile = profile
|
transport: RemoteProfile = profile
|
||||||
if profile.pair_id:
|
if profile.pair_id:
|
||||||
@@ -445,7 +463,9 @@ class RemoteInstances:
|
|||||||
used_ports = self._remember_origins(self._read())
|
used_ports = self._remember_origins(self._read())
|
||||||
# Retire browser origins from the earlier transparent tunnel. Those
|
# Retire browser origins from the earlier transparent tunnel. Those
|
||||||
# origins may still contain remote secrets in old tabs/localStorage.
|
# 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)
|
proxy = self._proxies.get(local_port)
|
||||||
if proxy is not None:
|
if proxy is not None:
|
||||||
tunnel = proxy.tunnel
|
tunnel = proxy.tunnel
|
||||||
@@ -481,10 +501,11 @@ class RemoteInstances:
|
|||||||
await self._check(item)
|
await self._check(item)
|
||||||
if any(not item.error for _, item in duplicates):
|
if any(not item.error for _, item in duplicates):
|
||||||
raise RemoteError("duplicate_instance")
|
raise RemoteError("duplicate_instance")
|
||||||
# Require the installed WebUI too, not just a port answering HTTP.
|
# The host supplies data only. Its frontend need not be installed.
|
||||||
page = await client.get(base + "/")
|
report = assess_webui_contract(identity.get("webui"))
|
||||||
if page.status_code != 200 or "text/html" not in page.headers.get("content-type", ""):
|
self._compatibility[key] = report
|
||||||
raise RemoteError("webui_unavailable")
|
if error := compatibility_error(report):
|
||||||
|
raise RemoteError(error)
|
||||||
issue_path = data.get("token_issue_path", "")
|
issue_path = data.get("token_issue_path", "")
|
||||||
if not isinstance(issue_path, str):
|
if not isinstance(issue_path, str):
|
||||||
raise RemoteError("incompatible_gateway")
|
raise RemoteError("incompatible_gateway")
|
||||||
@@ -504,6 +525,7 @@ class RemoteInstances:
|
|||||||
self._remember_origins(profiles, proxy.port)
|
self._remember_origins(profiles, proxy.port)
|
||||||
profiles[key].local_port = proxy.port
|
profiles[key].local_port = proxy.port
|
||||||
profiles[key].proxy_origin = True
|
profiles[key].proxy_origin = True
|
||||||
|
profiles[key].local_client_origin = True
|
||||||
self._write(profiles)
|
self._write(profiles)
|
||||||
# A failed route must not block a newly verified route to this bot.
|
# A failed route must not block a newly verified route to this bot.
|
||||||
# Retire it only after the replacement is saved; retain its profile
|
# 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 websockets.typing import Origin
|
||||||
from yarl import URL
|
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_BYTES = 64 * 1024 * 1024
|
||||||
_MAX_CAPABILITIES = 10000
|
_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_-]+"
|
_MEDIA_PATH = r"/api/media/[A-Za-z0-9_-]{22}/[A-Za-z0-9_-]+"
|
||||||
# Consume absolute URLs unchanged before matching gateway-relative media paths.
|
# Consume absolute URLs unchanged before matching gateway-relative media paths.
|
||||||
# An external site's similarly named route is not this proxy's capability.
|
# 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._bootstrap_lock = asyncio.Lock()
|
||||||
self._enabled = True
|
self._enabled = True
|
||||||
self._runner: web.AppRunner | None = None
|
self._runner: web.AppRunner | None = None
|
||||||
|
self.assets = LocalClientAssets()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def open(
|
async def open(
|
||||||
@@ -79,6 +85,8 @@ class RemoteProxy:
|
|||||||
*, local_port: int = 0, excluded_ports: set[int] | None = None,
|
*, local_port: int = 0, excluded_ports: set[int] | None = None,
|
||||||
) -> RemoteProxy:
|
) -> RemoteProxy:
|
||||||
self = cls(tunnel, secret, gateway_id, issue_path)
|
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())
|
listener = _listen(local_port, excluded_ports or set())
|
||||||
self.port = int(listener.getsockname()[1])
|
self.port = int(listener.getsockname()[1])
|
||||||
app = web.Application(client_max_size=_MAX_BYTES)
|
app = web.Application(client_max_size=_MAX_BYTES)
|
||||||
@@ -188,6 +196,8 @@ class RemoteProxy:
|
|||||||
return await self._bootstrap()
|
return await self._bootstrap()
|
||||||
if path == "/webui/terminal":
|
if path == "/webui/terminal":
|
||||||
raise web.HTTPForbidden()
|
raise web.HTTPForbidden()
|
||||||
|
if not path.startswith("/api/"):
|
||||||
|
return self.assets.response(request)
|
||||||
return await self._http(request, path)
|
return await self._http(request, path)
|
||||||
except (httpx.HTTPError, WebSocketException, OSError, ValueError):
|
except (httpx.HTTPError, WebSocketException, OSError, ValueError):
|
||||||
# Never reflect upstream URLs, credentials or raw exception text.
|
# Never reflect upstream URLs, credentials or raw exception text.
|
||||||
@@ -226,6 +236,11 @@ class RemoteProxy:
|
|||||||
if not isinstance(terminal, dict):
|
if not isinstance(terminal, dict):
|
||||||
raise ValueError("invalid terminal")
|
raise ValueError("invalid terminal")
|
||||||
terminal = cast(dict[str, Any], 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")
|
ttl, ws_path = data.get("expires_in"), data.get("ws_path")
|
||||||
if (terminal.get("gatewayId") != self._gateway_id
|
if (terminal.get("gatewayId") != self._gateway_id
|
||||||
or terminal.get("protocolVersion") != 1
|
or terminal.get("protocolVersion") != 1
|
||||||
@@ -246,6 +261,7 @@ class RemoteProxy:
|
|||||||
result.update(token=token, api_token=api_token, expires_in=ttl,
|
result.update(token=token, api_token=api_token, expires_in=ttl,
|
||||||
terminal={"protocolVersion": 1, "gatewayId": self._gateway_id},
|
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}")
|
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"})
|
return web.json_response(result, headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
def _local_media(self, match: re.Match[str]) -> str:
|
def _local_media(self, match: re.Match[str]) -> str:
|
||||||
@@ -297,7 +313,7 @@ class RemoteProxy:
|
|||||||
elif path.startswith("/api/"):
|
elif path.startswith("/api/"):
|
||||||
grant = self._grant(self._credential(request), self._api)
|
grant = self._grant(self._credential(request), self._api)
|
||||||
headers["Authorization"] = "Bearer " + grant.remote
|
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.
|
# its authenticated multiplex WebSocket, not an arbitrary HTTP relay.
|
||||||
if request.method not in {"GET", "HEAD"}:
|
if request.method not in {"GET", "HEAD"}:
|
||||||
raise web.HTTPMethodNotAllowed(request.method, ["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()
|
outgoing = {key: value for key, value in upstream.headers.items()
|
||||||
if key.lower() in _RESPONSE_HEADERS}
|
if key.lower() in _RESPONSE_HEADERS}
|
||||||
outgoing["Cache-Control"] = "no-store"
|
outgoing["Cache-Control"] = "no-store"
|
||||||
upstream_cache = upstream.headers.get("cache-control", "").lower()
|
# Remote documents/media are data, never executable client code.
|
||||||
if (upstream.status_code == 200 and _STATIC_ASSET.fullmatch(path)
|
# Keep them sandboxed even if a host omits or relaxes its headers.
|
||||||
and not request.rel_url.query and "set-cookie" not in upstream.headers
|
outgoing["X-Content-Type-Options"] = "nosniff"
|
||||||
and "public" in upstream_cache and "immutable" in upstream_cache
|
outgoing["Content-Security-Policy"] = (
|
||||||
and "no-store" not in upstream_cache and "private" not in upstream_cache
|
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:"
|
||||||
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)
|
|
||||||
if "application/json" in upstream.headers.get("content-type", ""):
|
if "application/json" in upstream.headers.get("content-type", ""):
|
||||||
body = bytearray()
|
body = bytearray()
|
||||||
async for chunk in upstream.aiter_bytes():
|
async for chunk in upstream.aiter_bytes():
|
||||||
|
|||||||
@@ -736,7 +736,9 @@ class GatewayHTTPHandler:
|
|||||||
elif not is_local_browser:
|
elif not is_local_browser:
|
||||||
return _http_error(403, "bootstrap is localhost-only")
|
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:
|
if terminal_probe:
|
||||||
# Capability probing does not allocate credentials or acquire client leases.
|
# Capability probing does not allocate credentials or acquire client leases.
|
||||||
return _http_json_response(terminal, extra_headers=_NO_STORE_HEADERS)
|
return _http_json_response(terminal, extra_headers=_NO_STORE_HEADERS)
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -7,6 +7,7 @@ from websockets.datastructures import Headers
|
|||||||
from websockets.http11 import Request
|
from websockets.http11 import Request
|
||||||
|
|
||||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
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.gateway_tokens import GatewayTokenStore
|
||||||
from nanobot.webui.ws_http import GatewayHTTPHandler
|
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):
|
for _ in range(3):
|
||||||
response = handler._handle_bootstrap(connection, request, terminal_probe=True)
|
response = handler._handle_bootstrap(connection, request, terminal_probe=True)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert json.loads(response.body) == {
|
assert json.loads(response.body) == gateway_identity(handler.tokens.instance_id)
|
||||||
"protocolVersion": 1, "gatewayId": handler.tokens.instance_id,
|
|
||||||
}
|
|
||||||
assert "no-store" in response.headers["Cache-Control"]
|
assert "no-store" in response.headers["Cache-Control"]
|
||||||
assert not handler.tokens.api_tokens and not handler.tokens.issued_tokens
|
assert not handler.tokens.api_tokens and not handler.tokens.issued_tokens
|
||||||
assert GatewayTokenStore().instance_id != handler.tokens.instance_id
|
assert GatewayTokenStore().instance_id != handler.tokens.instance_id
|
||||||
@@ -16,6 +16,7 @@ from websockets.http11 import Request
|
|||||||
|
|
||||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||||
from nanobot.webui import remote_instances, remote_ssh
|
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.gateway_services import build_gateway_services
|
||||||
from nanobot.webui.remote_instances import RemoteInstances
|
from nanobot.webui.remote_instances import RemoteInstances
|
||||||
from nanobot.webui.remote_proxy import RemoteProxy
|
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"})
|
probe = AsyncMock(return_value={"port": 8765, "secret": "private-webui-secret", "hostname": "team-host"})
|
||||||
monkeypatch.setattr(remote_ssh, "probe", probe)
|
monkeypatch.setattr(remote_ssh, "probe", probe)
|
||||||
monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=tunnel))
|
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):
|
def respond(request):
|
||||||
if request.url.path == "/webui/terminal":
|
if request.url.path == "/webui/terminal":
|
||||||
assert request.headers["X-Nanobot-Auth"] == "private-webui-secret"
|
assert request.headers["X-Nanobot-Auth"] == "private-webui-secret"
|
||||||
return httpx.Response(state["status"], json=state["identity"])
|
return httpx.Response(state["status"], json=state["identity"])
|
||||||
return httpx.Response(200, text="<!doctype html><title>nanobot</title>", headers={"content-type": "text/html"})
|
raise AssertionError(f"A data-only host must not be asked for a frontend: {request.url.path}")
|
||||||
|
|
||||||
real_client = httpx.AsyncClient
|
real_client = httpx.AsyncClient
|
||||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(transport=httpx.MockTransport(respond), **kwargs))
|
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(transport=httpx.MockTransport(respond), **kwargs))
|
||||||
@@ -69,6 +70,48 @@ async def test_save_survives_restart_without_credentials(manager):
|
|||||||
await save(manager, private_key="must-never-save")
|
await save(manager, private_key="must-never-save")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("contract,code", [
|
||||||
|
(None, "webui_compatibility_unknown"),
|
||||||
|
({**webui_contract(), "min_protocol": 2, "max_protocol": 2}, "client_update_required"),
|
||||||
|
({**webui_contract(), "capabilities": []}, "host_update_required"),
|
||||||
|
])
|
||||||
|
async def test_contract_failure_keeps_profile_and_reports_correct_update_target(manager, ssh, contract, code):
|
||||||
|
key = await save(manager)
|
||||||
|
ssh.state["identity"]["webui"] = contract
|
||||||
|
with pytest.raises(RemoteError, match=code):
|
||||||
|
await manager.action("connect", {"id": key})
|
||||||
|
RemoteProxy.open.assert_not_awaited()
|
||||||
|
ssh.tunnel.close.assert_awaited_once()
|
||||||
|
snapshot = manager.snapshot()
|
||||||
|
assert len(snapshot["profiles"]) == 1
|
||||||
|
assert snapshot["profiles"][0]["connection_error"] == code
|
||||||
|
assert not snapshot["profiles"][0]["connected"]
|
||||||
|
assert snapshot["profiles"][0]["compatibility"]["status"] != "compatible"
|
||||||
|
assert not manager.connections
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_upgrade_rechecks_compatibility_without_new_pairing(manager, ssh):
|
||||||
|
key = await save(manager)
|
||||||
|
ssh.state["identity"].pop("webui")
|
||||||
|
with pytest.raises(RemoteError, match="webui_compatibility_unknown"):
|
||||||
|
await manager.action("connect", {"id": key})
|
||||||
|
saved = manager.path.read_text(encoding="utf-8")
|
||||||
|
ssh.state["identity"]["webui"] = {**webui_contract(), "version": "9.0.0"}
|
||||||
|
await manager.action("connect", {"id": key})
|
||||||
|
assert manager.snapshot()["profiles"][0]["compatibility"]["status"] == "compatible"
|
||||||
|
# The stable saved host remains; only its reserved local origin is added.
|
||||||
|
assert set(json.loads(manager.path.read_text(encoding="utf-8"))) == set(json.loads(saved))
|
||||||
|
|
||||||
|
|
||||||
|
async def test_host_contract_change_invalidates_live_proxy(manager, ssh):
|
||||||
|
key = await save(manager)
|
||||||
|
await manager.action("connect", {"id": key})
|
||||||
|
ssh.state["identity"]["webui"] = {**webui_contract(), "capabilities": []}
|
||||||
|
await manager.health()
|
||||||
|
ssh.proxy.pause.assert_awaited_once()
|
||||||
|
assert manager.snapshot()["profiles"][0]["connection_error"] == "host_update_required"
|
||||||
|
|
||||||
|
|
||||||
async def test_new_local_manager_has_new_view_identity_for_same_remote(manager, ssh):
|
async def test_new_local_manager_has_new_view_identity_for_same_remote(manager, ssh):
|
||||||
key = await save(manager)
|
key = await save(manager)
|
||||||
first = await manager.action("connect", {"id": key})
|
first = await manager.action("connect", {"id": key})
|
||||||
@@ -531,16 +574,19 @@ async def test_old_profile_origin_is_remembered_before_first_edit(manager, ssh):
|
|||||||
assert RemoteInstances(manager.path.parent)._remember_origins({}) == {23456}
|
assert RemoteInstances(manager.path.parent)._remember_origins({}) == {23456}
|
||||||
|
|
||||||
|
|
||||||
async def test_legacy_transparent_origin_is_not_reused(manager, ssh):
|
@pytest.mark.parametrize("proxy_origin", [False, True])
|
||||||
|
async def test_legacy_transparent_or_remote_code_origin_is_not_reused(manager, ssh, proxy_origin):
|
||||||
key = await save(manager)
|
key = await save(manager)
|
||||||
old = json.loads(manager.path.read_text())
|
old = json.loads(manager.path.read_text())
|
||||||
old[key]["local_port"] = 12345
|
old[key]["local_port"] = 12345
|
||||||
|
old[key]["proxy_origin"] = proxy_origin
|
||||||
manager.path.write_text(json.dumps(old))
|
manager.path.write_text(json.dumps(old))
|
||||||
await manager.action("connect", {"id": key})
|
await manager.action("connect", {"id": key})
|
||||||
kwargs = RemoteProxy.open.call_args.kwargs
|
kwargs = RemoteProxy.open.call_args.kwargs
|
||||||
assert kwargs["local_port"] == 0
|
assert kwargs["local_port"] == 0
|
||||||
assert 12345 in kwargs["excluded_ports"]
|
assert 12345 in kwargs["excluded_ports"]
|
||||||
assert json.loads(manager.path.read_text())[key]["proxy_origin"] is True
|
assert json.loads(manager.path.read_text())[key]["proxy_origin"] is True
|
||||||
|
assert json.loads(manager.path.read_text())[key]["local_client_origin"] is True
|
||||||
assert "proxy_origin" not in manager.snapshot()["profiles"][0]
|
assert "proxy_origin" not in manager.snapshot()["profiles"][0]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -21,7 +21,9 @@ from websockets.http11 import Request
|
|||||||
|
|
||||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||||
from nanobot.webui import remote_ssh
|
from nanobot.webui import remote_ssh
|
||||||
|
from nanobot.webui.client_contract import webui_contract
|
||||||
from nanobot.webui.gateway_services import build_gateway_services
|
from nanobot.webui.gateway_services import build_gateway_services
|
||||||
|
from nanobot.webui.local_client_assets import LocalClientAssets
|
||||||
from nanobot.webui.remote_proxy import RemoteProxy
|
from nanobot.webui.remote_proxy import RemoteProxy
|
||||||
from nanobot.webui.remote_ssh import RemoteProfile, open_tunnel
|
from nanobot.webui.remote_ssh import RemoteProfile, open_tunnel
|
||||||
|
|
||||||
@@ -31,6 +33,13 @@ MEDIA = "/api/media/AAAAAAAAAAAAAAAAAAAAAA/remoteFilePayload"
|
|||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
async def remote(tmp_path, monkeypatch):
|
async def remote(tmp_path, monkeypatch):
|
||||||
|
assets = tmp_path / "local-dist"
|
||||||
|
assets.mkdir()
|
||||||
|
(assets / "index.html").write_text("<!doctype html><title>Local nanobot</title>", encoding="utf-8")
|
||||||
|
(assets / "assets").mkdir()
|
||||||
|
for name in ["index-AbcD1234.js", "index-AbcD1234.css", "index.js"]:
|
||||||
|
(assets / "assets" / name).write_text("local client asset", encoding="utf-8")
|
||||||
|
monkeypatch.setattr("nanobot.webui.remote_proxy.LocalClientAssets", lambda: LocalClientAssets(assets))
|
||||||
config = WebSocketConfig(host="127.0.0.1", token_issue_secret=ROOT, path="/custom/ws")
|
config = WebSocketConfig(host="127.0.0.1", token_issue_secret=ROOT, path="/custom/ws")
|
||||||
services = build_gateway_services(
|
services = build_gateway_services(
|
||||||
config=config, bus=MagicMock(), session_manager=None, static_dist_path=None,
|
config=config, bus=MagicMock(), session_manager=None, static_dist_path=None,
|
||||||
@@ -39,8 +48,10 @@ async def remote(tmp_path, monkeypatch):
|
|||||||
runtime_surface="browser", runtime_capabilities_overrides=None,
|
runtime_surface="browser", runtime_capabilities_overrides=None,
|
||||||
)
|
)
|
||||||
seen, children = [], []
|
seen, children = [], []
|
||||||
|
# Frozen initial wire declaration: current client vs an independently defined host.
|
||||||
state = SimpleNamespace(block=asyncio.Event(), entered=asyncio.Event(), ws_redirect=False,
|
state = SimpleNamespace(block=asyncio.Event(), entered=asyncio.Event(), ws_redirect=False,
|
||||||
asset_cache="public, max-age=31536000, immutable")
|
contract={"version": "0.3.5", "min_protocol": 1, "max_protocol": 1,
|
||||||
|
"capabilities": ["webui.core.v1"]})
|
||||||
|
|
||||||
async def process(connection, request):
|
async def process(connection, request):
|
||||||
seen.append(request)
|
seen.append(request)
|
||||||
@@ -48,7 +59,7 @@ async def remote(tmp_path, monkeypatch):
|
|||||||
if path.startswith("/assets/"):
|
if path.startswith("/assets/"):
|
||||||
response = connection.respond(200, "fixture asset")
|
response = connection.respond(200, "fixture asset")
|
||||||
response.headers["Content-Type"] = "application/javascript"
|
response.headers["Content-Type"] = "application/javascript"
|
||||||
response.headers["Cache-Control"] = state.asset_cache
|
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
||||||
if "private" in request.path:
|
if "private" in request.path:
|
||||||
response.headers["Cache-Control"] = "private, no-store"
|
response.headers["Cache-Control"] = "private, no-store"
|
||||||
if "cookie" in request.path:
|
if "cookie" in request.path:
|
||||||
@@ -75,7 +86,14 @@ async def remote(tmp_path, monkeypatch):
|
|||||||
response.headers["Content-Type"] = "image/png"
|
response.headers["Content-Type"] = "image/png"
|
||||||
response.headers["Content-Range"] = "bytes 0-4/10"
|
response.headers["Content-Range"] = "bytes 0-4/10"
|
||||||
return response
|
return response
|
||||||
return await services.endpoint.process_request(connection, request, is_allowed=lambda _: True)
|
response = await services.endpoint.process_request(connection, request, is_allowed=lambda _: True)
|
||||||
|
if path == "/webui/bootstrap" and response.status_code == 200:
|
||||||
|
payload = json.loads(response.body)
|
||||||
|
payload["terminal"]["webui"] = state.contract
|
||||||
|
response.body = json.dumps(payload).encode()
|
||||||
|
del response.headers["Content-Length"]
|
||||||
|
response.headers["Content-Length"] = str(len(response.body))
|
||||||
|
return response
|
||||||
|
|
||||||
async def messages(ws):
|
async def messages(ws):
|
||||||
assert ws in services.endpoint.webui_connections
|
assert ws in services.endpoint.webui_connections
|
||||||
@@ -130,29 +148,65 @@ async def bootstrap(remote, headers=None):
|
|||||||
|
|
||||||
@pytest.mark.parametrize("path,cacheable", [
|
@pytest.mark.parametrize("path,cacheable", [
|
||||||
("/assets/index-AbcD1234.js", True), ("/assets/index-AbcD1234.css", True),
|
("/assets/index-AbcD1234.js", True), ("/assets/index-AbcD1234.css", True),
|
||||||
("/assets/private-AbcD1234.js", False), ("/assets/cookie-AbcD1234.js", False),
|
("/assets/index.js", False), ("/", False),
|
||||||
("/assets/index-AbcD1234.js?token=secret", False), ("/assets/config.json", False),
|
|
||||||
("/assets/index.js", False), ("/assets/index-AbcD1234.html", False),
|
|
||||||
])
|
])
|
||||||
async def test_cache_only_versioned_public_build_assets(remote, path, cacheable):
|
async def test_only_local_assets_are_served_and_versioned_files_cached(remote, path, cacheable):
|
||||||
response = await remote.client.get(remote.proxy.origin + path)
|
response = await remote.client.get(remote.proxy.origin + path)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.headers["cache-control"] == ("private, max-age=31536000, immutable" if cacheable else "no-store")
|
assert response.headers["cache-control"] == ("private, max-age=31536000, immutable" if cacheable else "no-cache")
|
||||||
|
assert response.headers["x-nanobot-ui"] == "local"
|
||||||
assert "set-cookie" not in response.headers
|
assert "set-cookie" not in response.headers
|
||||||
|
assert remote.seen == []
|
||||||
|
assert "local" in response.text.lower()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("directive", ["no-cache", 'no-cache="Content-Type"', "must-revalidate"])
|
@pytest.mark.parametrize("path", ["/assets/remote-only-AbcD1234.js", "/auth/callback", "/missing",
|
||||||
async def test_proxy_preserves_upstream_asset_revalidation(remote, directive):
|
"/assets/%2e%2e/config.json", "/assets/%2e%2e/%2e%2e/config.json", "/assets/foo%5cbar.js"])
|
||||||
remote.state.asset_cache = f"public, max-age=0, immutable, {directive}"
|
async def test_missing_local_files_never_fall_back_to_remote_html_or_code(remote, path):
|
||||||
response = await remote.client.get(remote.proxy.origin + "/assets/index-AbcD1234.js")
|
assert (await remote.client.get(remote.proxy.origin + path)).status_code == 404
|
||||||
assert response.status_code == 200
|
assert remote.seen == []
|
||||||
assert response.headers["cache-control"] == "no-store"
|
|
||||||
|
|
||||||
|
|
||||||
async def test_proxy_does_not_extend_upstream_asset_freshness(remote):
|
async def test_static_symlink_cannot_escape_local_bundle(remote, tmp_path):
|
||||||
remote.state.asset_cache = "public, max-age=60, immutable"
|
outside = tmp_path / "private.js"
|
||||||
response = await remote.client.get(remote.proxy.origin + "/assets/index-AbcD1234.js")
|
outside.write_text("not a UI asset", encoding="utf-8")
|
||||||
assert response.headers["cache-control"] == "private, max-age=60, immutable"
|
link = remote.proxy.assets.directory / "assets" / "escape.js"
|
||||||
|
try:
|
||||||
|
link.symlink_to(outside)
|
||||||
|
except OSError:
|
||||||
|
pytest.skip("This platform does not permit unprivileged symlinks")
|
||||||
|
assert (await remote.client.get(remote.proxy.origin + "/assets/escape.js")).status_code == 404
|
||||||
|
assert remote.seen == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_compressed_sibling_cannot_escape_local_bundle(remote, tmp_path):
|
||||||
|
outside = tmp_path / "private.gz"
|
||||||
|
outside.write_bytes(b"not a UI asset")
|
||||||
|
link = remote.proxy.assets.directory / "assets" / "index.js.gz"
|
||||||
|
try:
|
||||||
|
link.symlink_to(outside)
|
||||||
|
except OSError:
|
||||||
|
pytest.skip("This platform does not permit unprivileged symlinks")
|
||||||
|
response = await remote.client.get(remote.proxy.origin + "/assets/index.js", headers={
|
||||||
|
"Accept-Encoding": "gzip",
|
||||||
|
})
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert remote.seen == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("contract,error", [
|
||||||
|
(None, "webui_compatibility_unknown"),
|
||||||
|
({**webui_contract(), "min_protocol": 2, "max_protocol": 2}, "client_update_required"),
|
||||||
|
({**webui_contract(), "capabilities": []}, "host_update_required"),
|
||||||
|
])
|
||||||
|
async def test_bootstrap_rechecks_contract_before_issuing_local_credentials(remote, contract, error):
|
||||||
|
remote.state.contract = contract
|
||||||
|
response = await remote.client.get(remote.proxy.origin + "/webui/bootstrap",
|
||||||
|
headers={"X-Nanobot-Auth": remote.proxy.secret})
|
||||||
|
assert response.status_code == 409
|
||||||
|
assert response.json()["error"] == error
|
||||||
|
assert "token" not in response.json() and ROOT not in response.text
|
||||||
|
assert not remote.proxy._api and not remote.proxy._ws
|
||||||
|
|
||||||
|
|
||||||
async def test_remote_credentials_never_leave_the_backend(remote):
|
async def test_remote_credentials_never_leave_the_backend(remote):
|
||||||
@@ -237,13 +291,16 @@ async def test_signed_media_wrapped_over_http_and_websocket_and_range_preserved(
|
|||||||
response = await remote.client.get(remote.proxy.origin + local, headers={"Range": "bytes=0-4"})
|
response = await remote.client.get(remote.proxy.origin + local, headers={"Range": "bytes=0-4"})
|
||||||
assert response.status_code == 206 and response.content == b"bytes"
|
assert response.status_code == 206 and response.content == b"bytes"
|
||||||
assert response.headers["content-range"] == "bytes 0-4/10"
|
assert response.headers["content-range"] == "bytes 0-4/10"
|
||||||
|
assert response.headers["x-content-type-options"] == "nosniff"
|
||||||
|
assert response.headers["content-security-policy"].startswith("sandbox;")
|
||||||
|
assert "allow-scripts" not in response.headers["content-security-policy"]
|
||||||
assert remote.seen[-1].headers["Range"] == "bytes=0-4"
|
assert remote.seen[-1].headers["Range"] == "bytes=0-4"
|
||||||
assert (await remote.client.get(remote.proxy.origin + MEDIA)).status_code == 401
|
assert (await remote.client.get(remote.proxy.origin + MEDIA)).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
async def test_http_and_websocket_redirects_cannot_disclose_credentials(remote):
|
async def test_http_and_websocket_redirects_cannot_disclose_credentials(remote):
|
||||||
response = await remote.client.get(remote.proxy.origin + "/redirect")
|
response = await remote.client.get(remote.proxy.origin + "/redirect")
|
||||||
assert response.status_code == 502
|
assert response.status_code == 404
|
||||||
assert ROOT not in response.text and "location" not in response.headers
|
assert ROOT not in response.text and "location" not in response.headers
|
||||||
assert "set-cookie" not in response.headers
|
assert "set-cookie" not in response.headers
|
||||||
remote.state.ws_redirect = True
|
remote.state.ws_redirect = True
|
||||||
|
|||||||
Reference in new issue
Block a user