Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions hermes_cli/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -1881,8 +1881,6 @@ def generate_systemd_unit(system: bool = False, run_as_user: str | None = None)
Environment="HERMES_HOME={hermes_home}"
Restart=always
RestartSec=60
RestartMaxDelaySec=300
RestartSteps=5
RestartForceExitStatus={GATEWAY_SERVICE_RESTART_EXIT_CODE}
KillMode=mixed
KillSignal=SIGTERM
Expand Down Expand Up @@ -1916,8 +1914,6 @@ def generate_systemd_unit(system: bool = False, run_as_user: str | None = None)
Environment="HERMES_HOME={hermes_home}"
Restart=always
RestartSec=60
RestartMaxDelaySec=300
RestartSteps=5
RestartForceExitStatus={GATEWAY_SERVICE_RESTART_EXIT_CODE}
KillMode=mixed
KillSignal=SIGTERM
Expand Down
8 changes: 7 additions & 1 deletion hermes_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -971,7 +971,13 @@ def _tui_build_needed(tui_dir: Path) -> bool:

def _hermes_ink_bundle_stale(tui_dir: Path) -> bool:
ink_root = tui_dir / "packages" / "hermes-ink"
bundle = ink_root / "dist" / "ink-bundle.js"
# The @hermes/ink package build emits dist/entry-exports.js (see
# ui-tui/packages/hermes-ink/package.json). Older code checked for the
# pre-rename ink-bundle.js sentinel, which made every embedded dashboard
# chat connection run `npm run build` before accepting /api/pty. Behind
# Nginx that delayed the WebSocket handshake long enough to show
# "[session ended]" / 502 on restored sessions.
bundle = ink_root / "dist" / "entry-exports.js"
if not bundle.exists():
return True
bm = bundle.stat().st_mtime
Expand Down
39 changes: 32 additions & 7 deletions hermes_cli/web_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,7 +595,7 @@ async def get_status():
from hermes_state import SessionDB
db = SessionDB()
try:
sessions = db.list_sessions_rich(limit=50)
sessions = db.list_sessions_rich(limit=50, order_by_last_active=True)
now = time.time()
active_sessions = sum(
1 for s in sessions
Expand Down Expand Up @@ -764,7 +764,7 @@ async def get_sessions(limit: int = 20, offset: int = 0):
from hermes_state import SessionDB
db = SessionDB()
try:
sessions = db.list_sessions_rich(limit=limit, offset=offset)
sessions = db.list_sessions_rich(limit=limit, offset=offset, order_by_last_active=True)
total = db.session_count()
now = time.time()
for s in sessions:
Expand Down Expand Up @@ -2902,13 +2902,24 @@ def _is_public_bind() -> bool:


def _ws_client_is_allowed(ws: "WebSocket") -> bool:
"""Check if the WebSocket client IP is acceptable.

Allows loopback always; allows any IP when bound to all-interfaces
(--insecure mode, guarded by session token auth).
"""Check if the WebSocket client is acceptable.

Allows loopback clients always; allows any IP when bound to all-interfaces
(--insecure mode, guarded by session token auth). For the documented
loopback-behind-reverse-proxy deployment, Uvicorn may replace ws.client
with the X-Forwarded-For address. In that case we still allow the request
when the upstream Host header targets the dashboard's bound host (Nginx
sets Host to 127.0.0.1:9119), preserving the DNS-rebinding guard for WS
routes.
"""
if _is_public_bind():
return True

bound_host = getattr(app.state, "bound_host", "")
host_header = ws.headers.get("host", "")
if bound_host and _is_accepted_host(host_header, bound_host):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This changes only the peer-IP check. A normal public reverse proxy still presents a browser Origin for its public hostname, while the separate Host/Origin guard compares that Origin to the loopback bound_host; this PR does not modify that path, so the reported origin_mismatch remains. Please route the configured trusted public URL through the Host/Origin policy rather than bypassing this peer check.

return True

client_host = ws.client.host if ws.client else ""
if not client_host:
return True
Expand Down Expand Up @@ -4050,6 +4061,13 @@ def start_server(
app.state.bound_host = host
app.state.bound_port = port

# Uvicorn's WebSocket scope uses the socket peer address for ws.client.
# When the loopback-only dashboard is intentionally exposed through a
# same-host reverse proxy, the socket peer is already 127.0.0.1, but
# enabling proxy headers keeps HTTP URL/client metadata consistent with
# the deployment docs while only trusting local proxies.
forwarded_allow_ips = "127.0.0.1,::1"

if open_browser:
import webbrowser

Expand All @@ -4060,4 +4078,11 @@ def _open():
threading.Thread(target=_open, daemon=True).start()

print(f" Hermes Web UI → http://{host}:{port}")
uvicorn.run(app, host=host, port=port, log_level="warning")
uvicorn.run(
app,
host=host,
port=port,
log_level="warning",
proxy_headers=True,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not enable proxy headers unconditionally for loopback binds. The current design keeps the loopback peer as the security boundary and enables forwarded-header handling only for authenticated public binds; preserve that distinction when salvaging the proxy case.

forwarded_allow_ips=forwarded_allow_ips,
)
18 changes: 13 additions & 5 deletions hermes_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1028,13 +1028,21 @@ def list_sessions_rich(
params = []

if not include_children:
# Show root sessions and branch sessions (whose parent ended with
# end_reason='branched' before the child was created), while still
# hiding sub-agent runs and compression continuations (which also
# carry a parent_session_id but were spawned while the parent was
# still live — i.e., started_at < parent.ended_at).
# Show root sessions, compression chain anchors, and branch sessions
# (whose parent ended with end_reason='branched' before the child
# was created), while still hiding sub-agent runs and live
# compression continuations. A compression root can itself have a
# parent after repeated context compaction; include every
# ``end_reason='compression'`` anchor so projection below can walk
# to the latest live tip rather than leaving later continuations
# invisible.
where_clauses.append(
"(s.parent_session_id IS NULL"
" OR (s.end_reason = 'compression'"
" AND NOT EXISTS (SELECT 1 FROM sessions p"
" WHERE p.id = s.parent_session_id"
" AND p.end_reason = 'compression'"
" AND s.started_at >= p.ended_at))"
" OR EXISTS (SELECT 1 FROM sessions p"
" WHERE p.id = s.parent_session_id"
" AND p.end_reason = 'branched'"
Expand Down
2 changes: 1 addition & 1 deletion tests/hermes_cli/test_tui_npm_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def _touch_tui_entry(root: Path) -> None:


def _touch_ink_bundle(root: Path) -> None:
bundle = root / "packages" / "hermes-ink" / "dist" / "ink-bundle.js"
bundle = root / "packages" / "hermes-ink" / "dist" / "entry-exports.js"
bundle.parent.mkdir(parents=True, exist_ok=True)
bundle.write_text("export {}")

Expand Down
34 changes: 34 additions & 0 deletions tests/hermes_cli/test_web_server_host_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,40 @@ def test_case_insensitive_comparison(self):
assert _is_accepted_host("LocalHost:9119", "127.0.0.1")


class TestWebSocketClientAllowlist:
"""WebSocket allowlist tests for loopback reverse proxy deployments."""

def test_loopback_reverse_proxy_host_header_is_allowed(self, monkeypatch):
from starlette.datastructures import Headers

import hermes_cli.web_server as ws

class DummyClient:
host = "203.0.113.10"

class DummyWebSocket:
client = DummyClient()
headers = Headers({"host": "127.0.0.1:9119"})

monkeypatch.setattr(ws.app.state, "bound_host", "127.0.0.1", raising=False)
assert ws._ws_client_is_allowed(DummyWebSocket())

def test_attacker_host_header_is_rejected_for_non_loopback_client(self, monkeypatch):
from starlette.datastructures import Headers

import hermes_cli.web_server as ws

class DummyClient:
host = "203.0.113.10"

class DummyWebSocket:
client = DummyClient()
headers = Headers({"host": "evil.example"})

monkeypatch.setattr(ws.app.state, "bound_host", "127.0.0.1", raising=False)
assert not ws._ws_client_is_allowed(DummyWebSocket())


class TestHostHeaderMiddleware:
"""End-to-end test via the FastAPI app — verify the middleware
rejects bad Host headers with 400."""
Expand Down
36 changes: 34 additions & 2 deletions tests/test_hermes_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -2186,7 +2186,7 @@ def test_subagent_session_still_hidden(self, db):
assert "root" in ids

def test_compression_child_still_hidden(self, db):
"""Compression continuation sessions remain hidden (parent ended with 'compression')."""
"""Live compression continuation sessions stay hidden behind their root entry."""
import time as _time
t0 = _time.time()
db.create_session("root", "cli")
Expand All @@ -2204,7 +2204,39 @@ def test_compression_child_still_hidden(self, db):

sessions = db.list_sessions_rich(project_compression_tips=False)
ids = [s["id"] for s in sessions]
assert "continuation" not in ids, "Compression continuation should stay hidden"
assert "continuation" not in ids, "Live compression continuation should stay hidden"

def test_repeated_compression_chain_surfaces_latest_tip(self, db):
"""Repeated compression creates compression anchors with parents.

Those intermediate anchors must remain visible to the projection query;
otherwise the latest live continuation is hidden from /sessions.
"""
t0 = 1709500000.0
db.create_session("root", "cli")
db.create_session("mid", "cli", parent_session_id="root")
db.create_session("tip", "cli", parent_session_id="mid")
with db._lock:
db._conn.execute(
"UPDATE sessions SET started_at=?, ended_at=?, end_reason='compression' WHERE id=?",
(t0, t0 + 10, "root"),
)
db._conn.execute(
"UPDATE sessions SET started_at=?, ended_at=?, end_reason='compression' WHERE id=?",
(t0 + 11, t0 + 20, "mid"),
)
db._conn.execute(
"UPDATE sessions SET started_at=? WHERE id=?",
(t0 + 21, "tip"),
)
db._conn.commit()
db.append_message("tip", "user", "latest visible conversation")

sessions = db.list_sessions_rich(order_by_last_active=True)
ids = [s["id"] for s in sessions]
assert "tip" in ids
assert "mid" not in ids
assert "root" not in ids


class TestCompressionChainProjection:
Expand Down