Skip to content

The agent that grows with you

fix(webapp): give the Webapp its own public URL and stop reading the dashboard's

emozilla76a8d7695c27
diff --git a/gateway/run_api.py b/gateway/run_api.py
index 88d26836198..0498d1bd366 100644
--- a/gateway/run_api.py
+++ b/gateway/run_api.py
@@ -8,7 +8,8 @@ The native session WebSocket (ticketed ``/api/ws`` — every local CLI/TUI/Deskt
without the dashboard app: importing ``hermes_cli.web_server`` (about 690 routes, ~0.6 s) before the
listener bound stalled every cold start and the control socket's identify. The dashboard is mounted
on its first request (imported off the event loop) or warmed after READY for a supervised gateway
-(``warm_gateway_dashboard``); a gated listener (non-loopback bind or ``dashboard.public_url``) and a
+(``warm_gateway_dashboard``); a gated listener (non-loopback bind, ``webapp.public_url`` on the Webapp's,
+``dashboard.public_url`` on the private one) and a
process that already imported it mount it before the listener starts, exactly as before.
"""
@@ -72,12 +73,17 @@ class GatewayDashboardMount:
# session token is a bearer credential any loopback peer (any OS user) could read from
# GET /, so the gateway-hosted listener never publishes it.
web.app.state.withhold_session_token = True
+ webapp = getattr(self._state, "webapp", None)
+ own_url = _listener_public_url(webapp)
+ if own_url is not None:
+ web.app.state.listener_public_url = own_url
+ elif hasattr(web.app.state, "listener_public_url"):
+ delattr(web.app.state, "listener_public_url")
web._configure_auth_gate(self._state.bound_host, False, None, None)
web.app.state.gateway_runner = self.runner
web.app.state.session_authority = getattr(self.runner, "session_authority", None)
web.app.state.bound_host = self._state.bound_host
web.app.state.bound_port = self._state.bound_port
- webapp = getattr(self._state, "webapp", None)
if webapp is not None:
# The browser-hosted Desktop: its bundle at /, its routes (launch handoff, socket tickets,
# host terminal) on, and the browser credential kept in the home so tabs survive a restart.
@@ -93,6 +99,8 @@ class GatewayDashboardMount:
self.web.app.state.gateway_runner = None
self.web.app.state.session_authority = None
self.web.app.state.withhold_session_token = False
+ if hasattr(self.web.app.state, "listener_public_url"):
+ delattr(self.web.app.state, "listener_public_url")
if self._replaced_session_token is not None:
# Removed, not cleared: a listener mounted next (the private one the gateway falls back
# to) must find the app as main's listener does, with no surface and no bundle set.
@@ -167,10 +175,20 @@ def _listener_socket(family, kind, proto, port: int) -> socket.socket:
return listener
+def _listener_public_url(webapp) -> str | None:
+ """The public URL the listener answers to: the Webapp's own ``webapp.public_url`` ("" for none),
+ never ``dashboard.public_url``, which describes ``hermes dashboard``. None leaves main's listener
+ reading ``dashboard.public_url``."""
+ return None if webapp is None else webapp.public_url
+
+
async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0, webapp=None) -> GatewayAPIHandle:
global _ACTIVE_RUNNER
from gateway.webapp_listener import dial_origin
- from hermes_cli.web_server_boundary import _dashboard_public_hosts, listener_auth_required
+ from hermes_cli.web_server_boundary import (
+ _dashboard_public_hosts, listener_auth_required, public_hosts_engage_gate, public_url_hosts,
+ should_require_auth,
+ )
from hermes_cli.web_server_lifecycle import build_listener_server
# Existing routers/auth helpers share one process-local app. Never rebind it
@@ -179,9 +197,16 @@ async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0, w
if _ACTIVE_RUNNER is not None or (
loaded_web is not None and getattr(loaded_web.app.state, "gateway_runner", None) is not None):
raise RuntimeError("gateway API already started")
- trusted = _dashboard_public_hosts()
+ public_url = _listener_public_url(webapp)
+ if public_url is None:
+ trusted = _dashboard_public_hosts()
+ auth_required = listener_auth_required(host, trusted)
+ else:
+ # What web_server._configure_auth_gate decides for a listener that declares its public URL.
+ trusted = public_url_hosts(public_url)
+ auth_required = should_require_auth(host) or public_hosts_engage_gate(trusted)
state = types.SimpleNamespace(
- bound_host=host, bound_port=None, auth_required=listener_auth_required(host, trusted),
+ bound_host=host, bound_port=None, auth_required=auth_required,
trusted_public_hosts=trusted, gateway_runner=runner,
session_authority=getattr(runner, "session_authority", None), webapp=webapp)
mount = GatewayDashboardMount(runner, state)
diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.py
index 7f7a9b8b047..3ac857eaf67 100644
--- a/gateway/webapp_listener.py
+++ b/gateway/webapp_listener.py
@@ -4,6 +4,8 @@
listener to ``webapp.host``/``webapp.port`` (a stable port, so the browser's URL survives restarts) and
its dashboard mount serves the Webapp bundle. ``webapp.host`` is a loopback address or a wildcard
(``0.0.0.0``/``::``), and a wildcard bind is gated by dashboard sign-in like any non-loopback listener.
+``webapp.public_url`` is the address a reverse proxy or tunnel serves the Webapp at: it engages the same
+sign-in on a loopback bind, and ``dashboard.public_url`` (``hermes dashboard``'s) never applies here.
Native clients (Desktop, the CLI, Ink) dial the loopback address this module derives from the bind.
The browser's credential is the dashboard session token. With the Webapp on, the gateway keeps that
@@ -19,6 +21,7 @@ import secrets
import sys
from dataclasses import dataclass
from pathlib import Path
+from urllib.parse import urlsplit
logger = logging.getLogger(__name__)
@@ -34,6 +37,8 @@ class WebappSettings:
enabled: bool = False
host: str = DEFAULT_HOST
port: int = DEFAULT_PORT
+ #: ``webapp.public_url``: the address a reverse proxy or tunnel serves the Webapp at, or "" for none.
+ public_url: str = ""
@property
def bind(self) -> tuple[str, int]:
@@ -44,10 +49,11 @@ class WebappSettings:
@dataclass(frozen=True)
class WebappMount:
- """What the gateway's dashboard mount needs to serve the Webapp: the built bundle and the home
- whose browser credential it uses."""
+ """What the gateway's dashboard mount needs to serve the Webapp: the built bundle, the home
+ whose browser credential it uses and the Webapp's own public URL ("" for none)."""
dist: Path
home: Path
+ public_url: str = ""
def _config_document(home: Path) -> dict:
@@ -93,7 +99,28 @@ def webapp_settings(home) -> WebappSettings:
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
logger.warning("Webapp stays off: webapp.port must be a port number (1-65535) in %s", path)
return WebappSettings()
- return WebappSettings(enabled=True, host=host.strip(), port=port)
+ public_url = _public_url(block.get("public_url"))
+ if public_url is None:
+ logger.warning("Webapp stays off: webapp.public_url must be an http:// or https:// address with no "
+ "credentials, query or fragment in %s", path)
+ return WebappSettings()
+ return WebappSettings(enabled=True, host=host.strip(), port=port, public_url=public_url)
+
+
+def _public_url(value) -> str | None:
+ """``webapp.public_url`` without a trailing slash, "" when unset, None when malformed (not an
+ http(s) address, or one carrying credentials, a query or a fragment)."""
+ if value is None or value == "":
+ return ""
+ if not isinstance(value, str) or any(c in value for c in "\"'<> \t\r\n?#@\\"):
+ return None
+ url = value.rstrip("/")
+ try:
+ parts = urlsplit(url)
+ port = parts.port # raises ValueError on a malformed port
+ except ValueError:
+ return None
+ return url if parts.scheme in {"http", "https"} and parts.hostname and port != 0 else None
def _is_loopback(host: str) -> bool:
@@ -129,7 +156,8 @@ def listener_plan(home) -> tuple[str, int, WebappMount | None]:
return (*settings.bind, None)
from hermes_cli.config import get_project_root
from hermes_cli.webapp import webapp_dist_dir
- return (*settings.bind, WebappMount(dist=webapp_dist_dir(get_project_root()), home=Path(home)))
+ mount = WebappMount(dist=webapp_dist_dir(get_project_root()), home=Path(home), public_url=settings.public_url)
+ return (*settings.bind, mount)
def browser_session_token(home, *, rotate: bool = False) -> str:
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 3c9ec7b758f..a53c90cfd4a 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -995,7 +995,7 @@ DEFAULT_CONFIG = {
"unicode_cols": 0, # Hard override for terminal column width; 0 = derive from scale.
},
},
- "webapp": {"enabled": False, "host": "127.0.0.1", "port": 9120}, # gateway/webapp_listener.py
+ "webapp": {"enabled": False, "host": "127.0.0.1", "port": 9120, "public_url": ""}, # gateway/webapp_listener.py
"dashboard": {
# Visual theme: "default" | "midnight" | "ember" | "mono" | "cyberpunk" | "rose"
"theme": "default",
diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.py
index 662fc017126..db4df8538eb 100644
--- a/hermes_cli/dashboard_auth/middleware.py
+++ b/hermes_cli/dashboard_auth/middleware.py
@@ -69,6 +69,16 @@ def _safe_next_target(request: Request) -> str:
return quote(f"{path}?{query}" if query else path, safe="")
+def _cross_origin_write_detail(state: object) -> str:
+ """The 403 detail for a cookie write from another origin, naming the public URL setting the
+ listener reads: ``webapp.public_url`` on the gateway's Webapp, ``dashboard.public_url`` elsewhere."""
+ if getattr(state, "ui_surface", None) == "webapp":
+ return ("Cookie-authenticated writes must come from the Webapp's own origin. "
+ "Behind a reverse proxy, set webapp.public_url to the URL the browser uses.")
+ return ("Cookie-authenticated writes must come from the dashboard's own origin. "
+ "Behind a reverse proxy, set dashboard.public_url to the URL the browser uses.")
+
+
def _unauth_response(request: Request, *, reason: str) -> Response:
"""API routes -> 401 JSON with ``login_url``; HTML routes -> 302 -> /login. fetch() follows a
302 opaquely into the cross-origin OAuth dance, so API routes never get redirects; the SPA's
@@ -192,9 +202,7 @@ async def gated_auth_middleware(
at, _rt = read_session_cookies(request)
provider_hint = read_session_provider(request)
if (at or _rt) and request.method not in {"GET", "HEAD", "OPTIONS", "TRACE"} and not cookie_origin_is_allowed(request):
- return JSONResponse(status_code=403, content={
- "detail": "Cookie-authenticated writes must come from the dashboard's own origin. "
- "Behind a reverse proxy, set dashboard.public_url to the URL the browser uses."})
+ return JSONResponse(status_code=403, content={"detail": _cross_origin_write_detail(request.app.state)})
if cookie_logout:
return await call_next(request)
if not at and not _rt:
diff --git a/hermes_cli/dashboard_auth/prefix.py b/hermes_cli/dashboard_auth/prefix.py
index 1e61b5a72d5..c8b86dc8b8e 100644
--- a/hermes_cli/dashboard_auth/prefix.py
+++ b/hermes_cli/dashboard_auth/prefix.py
@@ -114,10 +114,17 @@ def _load_dashboard_section() -> dict:
return section if isinstance(section, dict) else {}
-def resolve_public_url() -> str:
+def resolve_public_url(state=None) -> str:
"""Operator-declared dashboard public URL, or ``""`` (reconstruct from request). Precedence:
``HERMES_DASHBOARD_PUBLIC_URL`` env (blank counts as unset so a provisioned-but-blank secret
- cannot shadow config.yaml), then ``dashboard.public_url``; malformed warns and falls through."""
+ cannot shadow config.yaml), then ``dashboard.public_url``; malformed warns and falls through.
+
+ *state* is the serving app's state. A listener that declares its own public URL there
+ (``listener_public_url``, ``""`` for none: the gateway's Webapp listener, from ``webapp.public_url``)
+ gets that, and the dashboard's setting is never read for it."""
+ own = getattr(state, "listener_public_url", None)
+ if own is not None:
+ return own
env_raw = os.environ.get("HERMES_DASHBOARD_PUBLIC_URL", "")
env_clean = _normalise_public_url(env_raw)
if env_clean:
diff --git a/hermes_cli/dashboard_auth/request_utils.py b/hermes_cli/dashboard_auth/request_utils.py
index 353e3e84318..df21f01784b 100644
--- a/hermes_cli/dashboard_auth/request_utils.py
+++ b/hermes_cli/dashboard_auth/request_utils.py
@@ -87,7 +87,7 @@ def cookie_origin_is_allowed(request: Request) -> bool:
return False
if fetch_sites:
return fetch_sites == ["same-origin"]
- target = urlsplit(resolve_public_url() or str(request.url))
+ target = urlsplit(resolve_public_url(request.app.state) or str(request.url))
return origin == _http_origin(f"{target.scheme}://{target.netloc}")
diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.py
index be029a317fb..942d093bdfd 100644
--- a/hermes_cli/dashboard_auth/routes.py
+++ b/hermes_cli/dashboard_auth/routes.py
@@ -72,7 +72,7 @@ def _redirect_uri(request: Request) -> str:
complete authority (``X-Forwarded-Prefix`` ignored so a baked-in prefix is not doubled);
otherwise ``url_for`` (honours ``X-Forwarded-Host/Proto`` under uvicorn ``proxy_headers``)
with the prefix prepended, which Starlette does not do."""
- public_url = _prefix_mod.resolve_public_url()
+ public_url = _prefix_mod.resolve_public_url(request.app.state)
if public_url:
return f"{public_url}/auth/callback"
base = str(request.url_for("auth_callback"))
diff --git a/hermes_cli/web_routers/mcp.py b/hermes_cli/web_routers/mcp.py
index dfbcb32f594..fefae2dc77a 100644
--- a/hermes_cli/web_routers/mcp.py
+++ b/hermes_cli/web_routers/mcp.py
@@ -71,7 +71,7 @@ def _mcp_oauth_callback_url(request: Request, server_name: str) -> str:
from hermes_cli.dashboard_auth.prefix import prefix_from_request, resolve_public_url
suffix = f"/api/mcp/oauth/callback/{quote(server_name, safe='')}"
- public_url = resolve_public_url()
+ public_url = resolve_public_url(request.app.state)
if public_url:
return f"{public_url}{suffix}"
base = urlparse(str(request.base_url))
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 776a6d794db..605341e6f24 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -361,6 +361,7 @@ from hermes_cli.web_server_boundary import ( # re-exported: web_server.<name> s
_host_header_hostname,
_is_accepted_host,
public_hosts_engage_gate,
+ public_url_hosts,
should_require_auth,
)
@@ -851,8 +852,9 @@ mount_spa(app)
def _no_auth_provider_message(host: str) -> str:
"""Actionable SystemExit text for a gated bind with no registered auth provider.
- Names the exact trigger: on a loopback bind the ONLY trigger is
- dashboard.public_url, so print the offending URL and the remove-it exit.
+ Names the exact trigger: on a loopback bind the ONLY trigger is the public URL
+ (dashboard.public_url, or webapp.public_url for the gateway's Webapp listener),
+ so print the offending URL and the remove-it exit.
Bundled providers expose ``LAST_SKIP_REASON`` so an installed-but-
unconfigured provider is not reported as merely "no providers".
"""
@@ -865,25 +867,30 @@ def _no_auth_provider_message(host: str) -> str:
except Exception:
pass
+ # A listener that declares its own public URL (the gateway's Webapp: webapp.public_url) is
+ # gated by that setting, never by dashboard.public_url.
+ own_url = getattr(app.state, "listener_public_url", None)
+ setting = "dashboard.public_url" if own_url is None else "webapp.public_url"
if host in _LOOPBACK_HOST_VALUES:
- public_url = ""
- try:
- from hermes_cli.dashboard_auth.prefix import resolve_public_url
+ public_url = own_url or ""
+ if own_url is None:
+ try:
+ from hermes_cli.dashboard_auth.prefix import resolve_public_url
- public_url = resolve_public_url()
- except Exception:
- pass
+ public_url = resolve_public_url()
+ except Exception:
+ pass
gate_reason = (
- f"dashboard.public_url is set to "
+ f"{setting} is set to "
f"{public_url or '<a non-loopback URL>'} — an "
f"operator-declared external URL engages the auth gate "
f"even on a loopback bind"
)
fix_hint = (
"If this dashboard should be LOCAL-ONLY (no reverse "
- "proxy), remove dashboard.public_url from config.yaml "
- "(and unset HERMES_DASHBOARD_PUBLIC_URL) to restore the "
- "unauthenticated loopback mode.\n"
+ f"proxy), remove {setting} from config.yaml "
+ + ("(and unset HERMES_DASHBOARD_PUBLIC_URL) " if own_url is None else "")
+ + "to restore the unauthenticated loopback mode.\n"
)
else:
gate_reason = f"the auth gate engages on non-loopback binds ({host})"
@@ -899,7 +906,7 @@ def _no_auth_provider_message(host: str) -> str:
" • OAuth: run `hermes dashboard register` (Nous Portal) or "
"install a DashboardAuthProvider plugin.\n"
"There is no unauthenticated public-dashboard option. For "
- "local-only use, bind 127.0.0.1 and leave dashboard.public_url "
+ f"local-only use, bind 127.0.0.1 and leave {setting} "
"unset; a configured external public URL requires auth even "
"when a local reverse proxy reaches a loopback backend."
)
@@ -948,10 +955,14 @@ def _configure_auth_gate(
# reverse-proxy deployments; resolved once so middleware never reloads
# config. A non-loopback public hostname engages the gate even on a loopback
# backend, else the SPA's local session token becomes remotely reachable.
- app.state.trusted_public_hosts = _dashboard_public_hosts()
+ # A listener that declares its own public URL (``listener_public_url``: the
+ # gateway's, from webapp.public_url) is judged by that one instead.
+ own_url = getattr(app.state, "listener_public_url", None)
+ app.state.trusted_public_hosts = (
+ _dashboard_public_hosts() if own_url is None else public_url_hosts(own_url))
# auth_required drives middleware, SPA-token injection, WS auth, the
# startup refusal, the gate-on banner and uvicorn proxy_headers.
- if _desktop_loopback_auth_exempt(host, ssh_session_token, ssh_owner_nonce):
+ if own_url is None and _desktop_loopback_auth_exempt(host, ssh_session_token, ssh_owner_nonce):
# public_url describes the operator's PUBLIC deployment, not this
# Desktop-owned loopback backend (#96490), which authenticates with the
# per-spawn session token the ticket-only gate would refuse.
diff --git a/hermes_cli/web_server_boundary.py b/hermes_cli/web_server_boundary.py
index 80a1eea39e4..53017723e57 100644
--- a/hermes_cli/web_server_boundary.py
+++ b/hermes_cli/web_server_boundary.py
@@ -34,7 +34,12 @@ def _dashboard_public_hosts() -> frozenset[str]:
"""
from hermes_cli.dashboard_auth.prefix import resolve_public_url
- public_url = resolve_public_url()
+ return public_url_hosts(resolve_public_url())
+
+
+def public_url_hosts(public_url: str) -> frozenset[str]:
+ """The exact hostname *public_url* declares, as the trusted public host set; empty when unset or
+ malformed."""
try:
hostname = urllib.parse.urlparse(public_url).hostname if public_url else None
except ValueError:
diff --git a/tests/gateway/fixtures/webapp_fallback_peer.py b/tests/gateway/fixtures/webapp_fallback_peer.py
index e0f4df3ed10..451e8b49a0d 100644
--- a/tests/gateway/fixtures/webapp_fallback_peer.py
+++ b/tests/gateway/fixtures/webapp_fallback_peer.py
@@ -15,7 +15,7 @@ Run as ``python webapp_fallback_peer.py '<spec json>'`` with an isolated ``HERME
- ``probe_host``: a Host header to send (a public hostname), or null.
Writes ``receipt.json`` into ``HERMES_HOME`` (the gateway redirects stdout). No inference: the model points
-at a closed port and no turn is submitted.
+at a closed port and no turn is submitted. Tests start it with :func:`run`.
"""
import asyncio
import errno
@@ -23,6 +23,7 @@ import json
import os
from pathlib import Path
import socket
+import subprocess
import sys
import traceback
@@ -30,6 +31,30 @@ SEEDED_TOKEN = "seeded-browser-credential-from-an-earlier-0" # 43 URL-safe char
INDEX = "<!doctype html><html><body>WEBAPP_BUNDLE</body></html>"
+def free_port() -> int:
+ with socket.socket() as probe:
+ probe.bind(("127.0.0.1", 0))
+ return probe.getsockname()[1]
+
+
+def run(tmp_path, spec) -> dict:
+ """Run this peer for *spec* in a fresh home under *tmp_path*; returns its receipt."""
+ from tests.gateway.fixtures.local_recovery_probe import child_env
+
+ root = Path(__file__).resolve().parents[3]
+ home, user = tmp_path / "state", tmp_path / "user"
+ for path in (home, user):
+ path.mkdir()
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ PYTHONUNBUFFERED="1")
+ result = subprocess.run([sys.executable, __file__, json.dumps(spec)], cwd=root, env=env,
+ capture_output=True, text=True, timeout=120, check=False)
+ receipt = home / "receipt.json"
+ assert result.returncode == 0, result.stdout + result.stderr + (receipt.read_text() if receipt.exists() else "")
+ return json.loads(receipt.read_text())
+
+
def _config(spec) -> str:
document = {"gateway": {"multiplex_profiles": False},
"model": {"provider": "custom", "default": "no-inference", "base_url": "http://127.0.0.1:1/v1"},
diff --git a/tests/gateway/test_webapp_listener_fallback.py b/tests/gateway/test_webapp_listener_fallback.py
index dad0c9e818a..6f8e1994557 100644
--- a/tests/gateway/test_webapp_listener_fallback.py
+++ b/tests/gateway/test_webapp_listener_fallback.py
@@ -6,37 +6,11 @@ Desktop, CLI and TUI clients still connect, the mount carries none of the Webapp
``hermes webapp --status`` says why the Webapp is not served. Each case runs a real gateway listener
in a child process (``fixtures/webapp_fallback_peer.py``) with its own ``HERMES_HOME``.
"""
-import json
-from pathlib import Path
-import socket
-import subprocess
import sys
import pytest
-from tests.gateway.fixtures.local_recovery_probe import child_env
-
-
-def _free_port() -> int:
- with socket.socket() as probe:
- probe.bind(("127.0.0.1", 0))
- return probe.getsockname()[1]
-
-
-def _run(tmp_path, spec):
- root = Path(__file__).resolve().parents[2]
- home, user = tmp_path / "state", tmp_path / "user"
- for path in (home, user):
- path.mkdir()
- env = child_env()
- env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
- PYTHONUNBUFFERED="1")
- result = subprocess.run(
- [sys.executable, str(root / "tests/gateway/fixtures/webapp_fallback_peer.py"), json.dumps(spec)],
- cwd=root, env=env, capture_output=True, text=True, timeout=120, check=False)
- receipt = home / "receipt.json"
- assert result.returncode == 0, result.stdout + result.stderr + (receipt.read_text() if receipt.exists() else "")
- return json.loads(receipt.read_text())
+from tests.gateway.fixtures.webapp_fallback_peer import free_port as _free_port, run as _run
@pytest.fixture(scope="module")
diff --git a/tests/gateway/test_webapp_public_url.py b/tests/gateway/test_webapp_public_url.py
new file mode 100644
index 00000000000..70e7dda621f
--- /dev/null
+++ b/tests/gateway/test_webapp_public_url.py
@@ -0,0 +1,163 @@
+"""The Webapp's own public URL, ``webapp.public_url``, and never ``dashboard.public_url``.
+
+A user who reaches the gateway's Webapp through a reverse proxy or tunnel sets ``webapp.public_url``.
+On the Webapp listener it engages sign-in even on a loopback bind, it is the one public Host the
+listener accepts, and sign-in and MCP OAuth callbacks are built on it. ``dashboard.public_url``
+describes ``hermes dashboard``: the gateway's Webapp ignores it, and the standalone dashboard keeps
+reading it as before. The live cases run a real gateway listener in a child process
+(``fixtures/webapp_fallback_peer.py``) with its own ``HERMES_HOME``.
+"""
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import webapp_listener as webapp
+from tests.gateway.fixtures.webapp_fallback_peer import free_port, run
+
+WEBAPP_URL = "https://webapp.example.net"
+DASHBOARD_URL = "https://dash.example.net"
+
+
+def _home(tmp_path, config):
+ home = tmp_path / "home"
+ home.mkdir(parents=True)
+ (home / "config.yaml").write_text(config, encoding="utf-8")
+ return home
+
+
+def test_the_webapp_has_no_public_url_unless_configured(tmp_path):
+ assert webapp.webapp_settings(_home(tmp_path, "webapp:\n enabled: true\n")).public_url == ""
+
+
[email protected](("value", "url"), [
+ ("https://webapp.example.net", "https://webapp.example.net"),
+ ("https://webapp.example.net/", "https://webapp.example.net"),
+ ("https://webapp.example.net:8443/hermes/", "https://webapp.example.net:8443/hermes"),
+ ("http://hermes.lan:9120", "http://hermes.lan:9120"),
+ ("''", ""),
+])
+def test_the_webapp_reads_its_public_url(tmp_path, value, url):
+ settings = webapp.webapp_settings(_home(tmp_path, f"webapp:\n enabled: true\n public_url: {value}\n"))
+ assert (settings.enabled, settings.public_url) == (True, url)
+
+
+ "webapp.example.net", # no scheme
+ "ftp://webapp.example.net",
+ "https://",
+ "7",
+ "https://user:[email protected]",
+ "https://webapp.example.net/?next=x",
+ "'https://webapp.example.net/#top'",
+ "'https://webapp.example.net/<script>'",
+])
+def test_a_malformed_webapp_public_url_keeps_the_webapp_off(tmp_path, value):
+ settings = webapp.webapp_settings(_home(tmp_path, f"webapp:\n enabled: true\n public_url: {value}\n"))
+ assert (settings.enabled, settings.bind) == (False, ("127.0.0.1", 0))
+
+
+def test_a_listener_that_declares_its_public_url_never_reads_the_dashboards(monkeypatch):
+ from hermes_cli.dashboard_auth.prefix import resolve_public_url
+
+ monkeypatch.setenv("HERMES_DASHBOARD_PUBLIC_URL", DASHBOARD_URL)
+ assert resolve_public_url(SimpleNamespace(listener_public_url=WEBAPP_URL)) == WEBAPP_URL
+ assert resolve_public_url(SimpleNamespace(listener_public_url="")) == ""
+ # The standalone dashboard declares nothing and reads dashboard.public_url as before.
+ assert resolve_public_url(SimpleNamespace()) == DASHBOARD_URL
+ assert resolve_public_url() == DASHBOARD_URL
+
+
+def _request(state, headers):
+ from starlette.requests import Request
+
+ app = SimpleNamespace(state=state)
+ return Request({"type": "http", "method": "POST", "path": "/api/config", "raw_path": b"/api/config",
+ "query_string": b"", "scheme": "http", "server": ("127.0.0.1", 9120), "root_path": "",
+ "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()], "app": app})
+
+
+def test_the_webapps_mcp_oauth_callback_is_built_on_its_own_public_url(monkeypatch):
+ from hermes_cli.web_routers.mcp import _mcp_oauth_callback_url
+
+ monkeypatch.setenv("HERMES_DASHBOARD_PUBLIC_URL", DASHBOARD_URL)
+ state = SimpleNamespace(listener_public_url=WEBAPP_URL)
+ request = _request(state, {"host": "webapp.example.net"})
+ assert _mcp_oauth_callback_url(request, "srv") == f"{WEBAPP_URL}/api/mcp/oauth/callback/srv"
+
+
+def test_a_browser_without_fetch_metadata_writes_from_the_webapps_public_origin(monkeypatch):
+ # Without Sec-Fetch-Site the Origin is compared with this listener's own public URL.
+ from hermes_cli.dashboard_auth.request_utils import cookie_origin_is_allowed
+
+ monkeypatch.setenv("HERMES_DASHBOARD_PUBLIC_URL", DASHBOARD_URL)
+ state = SimpleNamespace(listener_public_url=WEBAPP_URL, bound_host="127.0.0.1",
+ trusted_public_hosts=frozenset({"webapp.example.net"}))
+ own = _request(state, {"host": "webapp.example.net", "origin": WEBAPP_URL})
+ dashboard = _request(state, {"host": "webapp.example.net", "origin": DASHBOARD_URL})
+ assert cookie_origin_is_allowed(own) is True
+ assert cookie_origin_is_allowed(dashboard) is False
+
+
[email protected](scope="module")
+def own_url(tmp_path_factory):
+ # The "my own URL" shape: a loopback Webapp behind a proxy at webapp.public_url, with sign-in.
+ spec = {"webapp": {"enabled": True, "port": free_port(), "public_url": WEBAPP_URL}, "basic_auth": True,
+ "dashboard_public_url": DASHBOARD_URL, "probe_host": "webapp.example.net"}
+ return run(tmp_path_factory.mktemp("own-url"), spec)
+
+
+def test_the_webapps_public_url_engages_sign_in_on_a_loopback_bind(own_url):
+ assert own_url["start_error"] is None, own_url.get("start_traceback")
+ assert own_url["status"]["state"] == "serving"
+ assert own_url["state"]["auth_required"] is True
+ assert own_url["launch"]["sign_in"] is True
+
+
+def test_the_webapp_trusts_only_its_own_public_host(own_url):
+ assert own_url["state"]["trusted_public_hosts"] == ["webapp.example.net"]
+ assert own_url["probe_host_status_code"] == 200
+
+
+def test_sign_in_callbacks_are_built_on_the_webapps_public_url(own_url):
+ assert own_url["redirect_uri_for_probe_host"] == f"{WEBAPP_URL}/auth/callback"
+
+
[email protected](scope="module")
+def dashboard_url_only(tmp_path_factory):
+ # dashboard.public_url set for `hermes dashboard`, no sign-in provider, a loopback Webapp.
+ spec = {"webapp": {"enabled": True, "port": free_port()}, "dashboard_public_url": DASHBOARD_URL,
+ "probe_host": "dash.example.net"}
+ return run(tmp_path_factory.mktemp("dashboard-url"), spec)
+
+
+def test_the_dashboards_public_url_does_not_gate_the_webapp(dashboard_url_only):
+ assert dashboard_url_only["start_error"] is None, dashboard_url_only.get("start_traceback")
+ assert dashboard_url_only["status"]["state"] == "serving"
+ assert dashboard_url_only["state"]["auth_required"] is False
+ assert dashboard_url_only["launch"].get("sign_in") is None
+
+
+def test_the_webapp_refuses_the_dashboards_public_host(dashboard_url_only):
+ assert dashboard_url_only["state"]["trusted_public_hosts"] == []
+ assert dashboard_url_only["probe_host_status_code"] == 400
+
+
+def test_a_webapp_public_url_without_sign_in_leaves_native_clients_a_listener(tmp_path):
+ spec = {"webapp": {"enabled": True, "port": free_port(), "public_url": WEBAPP_URL}}
+ report = run(tmp_path, spec)
+ assert report["start_error"] is None, report.get("start_traceback")
+ assert report["native_session_list"] is True
+ assert report["status"]["state"] == "unavailable"
+ assert "webapp.public_url" in report["status"]["reason"]
+ assert "dashboard.public_url" not in report["status"]["reason"]
+
+
+def test_a_refused_cookie_write_names_the_setting_its_surface_reads():
+ # Behind a reverse proxy the fix is the public URL that listener reads: webapp.public_url on the
+ # gateway's Webapp, dashboard.public_url on the standalone dashboard.
+ from hermes_cli.dashboard_auth.middleware import _cross_origin_write_detail
+
+ webapp = _cross_origin_write_detail(SimpleNamespace(ui_surface="webapp"))
+ dashboard = _cross_origin_write_detail(SimpleNamespace())
+ assert "webapp.public_url" in webapp and "dashboard.public_url" not in webapp
+ assert "dashboard.public_url" in dashboard
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index ecb46535d4c..26ce992976f 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -3172,11 +3172,13 @@ webapp:
enabled: false # true: the gateway serves the Webapp
host: 127.0.0.1 # loopback address, or 0.0.0.0 / :: for other machines (dashboard sign-in required)
port: 9120 # fixed, so the browser's address stays the same across gateway restarts
+ public_url: "" # the https:// address a reverse proxy or tunnel serves the Webapp at (sign-in required)
```
- `enabled` — the gateway reads it at start; restart the gateway after changing it (`hermes gateway restart`).
- `host` — a loopback address keeps the Webapp on this machine. `0.0.0.0` or `::` makes it reachable from other machines and requires a [dashboard sign-in provider](./features/web-dashboard.md#authentication-gated-mode); without one the gateway serves native clients only and `hermes webapp --status` says why. Restart the gateway after adding the provider. Any other value keeps the Webapp off.
- `port` — when the port is taken, the gateway likewise serves native clients only and `hermes webapp --status` reports why.
+- `public_url` — set it when a reverse proxy or tunnel you run serves the Webapp at its own address (forwarding to `host:port`). It turns on dashboard sign-in even on a loopback `host`, it is the one outside hostname the Webapp accepts requests for, and sign-in callbacks are built on it. Without a sign-in provider the gateway serves native clients only, as for `0.0.0.0`. It must be an `http://` or `https://` address with no credentials, query or fragment; anything else keeps the Webapp off. `dashboard.public_url` is for `hermes dashboard` and never applies to the Webapp.
The Webapp settings are read from the config of the gateway that serves the profile: the default profile's config for named profiles it serves, a standalone profile's own config otherwise.