webapp.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. """Webapp-only routes: the host terminal (loopback or authenticated binds), the
  2. one-use ticket each browser socket dial mints (``/api/webapp/socket-ticket?socket=`` for
  3. ``/api/ws`` on this same origin, the host terminal and each voice stream), and the one-use
  4. handoffs (child window, auto-opened launch tab) for the private, loopback Webapp session."""
  5. from __future__ import annotations
  6. import ipaddress
  7. import json
  8. import logging
  9. import os
  10. import secrets
  11. import sys
  12. import threading
  13. import time
  14. from fastapi import APIRouter, HTTPException, Request, WebSocket
  15. from fastapi.responses import HTMLResponse, JSONResponse
  16. from hermes_cli.dashboard_auth.request_utils import _http_origin
  17. from hermes_cli.web_server_surface import policy, private_launch
  18. from hermes_cli.web_session_sockets import (
  19. GATEWAY_SOCKET, HOST_TERMINAL_SOCKET, SPEAK_STREAM_SOCKET, TRANSCRIBE_STREAM_SOCKET)
  20. _log = logging.getLogger("hermes_cli.web_server")
  21. router = APIRouter()
  22. WINDOW_TICKET_TTL_SECONDS = 30
  23. #: A sandboxed (snap/Flatpak) browser's cold start can take several seconds to reach the page.
  24. LAUNCH_TICKET_TTL_SECONDS = 60
  25. _MAX_WINDOW_TICKETS = 128
  26. _ticket_lock = threading.Lock()
  27. #: Who a socket opened with the loopback session token is (``chat_ws.gateway_ws`` gives a
  28. #: ``?token=`` socket the same identity, and REST mutations are forwarded as it).
  29. SESSION_TOKEN_OWNER = {"user_id": "legacy-token-owner", "provider": "session-token", "issuer": ""}
  30. def _require_private_webapp(request: Request) -> None:
  31. if not private_launch(request.app.state):
  32. raise HTTPException(404, "Private Webapp window handoff is unavailable")
  33. @router.websocket("/api/host-terminal")
  34. async def host_terminal_ws(ws: WebSocket) -> None:
  35. from hermes_cli import web_host_terminal
  36. from hermes_cli.web_host_terminal_sessions import host_terminal
  37. from hermes_cli.web_server_chat import _PTY_BRIDGE_AVAILABLE, PtyUnavailableError, _pty_fail, _ws_gate
  38. gate = await _ws_gate(ws, HOST_TERMINAL_SOCKET)
  39. if gate is None:
  40. return
  41. peer, mode, cred = gate
  42. if not web_host_terminal.request_allowed():
  43. await ws.close(code=4403, reason="host terminal requires authenticated Webapp")
  44. return
  45. await ws.accept()
  46. _log.info("host terminal accepted peer=%s mode=%s cred=%s", peer, mode, cred)
  47. if not _PTY_BRIDGE_AVAILABLE:
  48. await _pty_fail(
  49. ws, PtyUnavailableError("Pseudo-terminal support is not installed on this host."), surface="Terminal")
  50. return
  51. await host_terminal(ws)
  52. def _mint_handoff_ticket(state, ttl: float, *, launch: bool) -> str:
  53. """One-use ticket that ``/webapp/window-session`` exchanges for this start's session token. The
  54. store keeps ``(expiry, browser credential generation, launch)``, never the credential itself."""
  55. from hermes_cli import browser_credential
  56. now = time.monotonic()
  57. with _ticket_lock:
  58. tickets = getattr(state, "webapp_window_tickets", {})
  59. tickets = {key: value for key, value in tickets.items()
  60. if value[0] > now and browser_credential.is_current(value[1])}
  61. state.webapp_window_tickets = tickets
  62. if len(tickets) >= _MAX_WINDOW_TICKETS:
  63. raise HTTPException(429, "Too many pending Webapp windows; try again shortly")
  64. ticket = secrets.token_urlsafe(32)
  65. tickets[ticket] = (now + ttl, browser_credential.generation(), launch)
  66. return ticket
  67. def mint_launch_ticket(state) -> str:
  68. """Ticket for the browser the server opens itself: a launcher's argv carries this, not the token."""
  69. return _mint_handoff_ticket(state, LAUNCH_TICKET_TTL_SECONDS, launch=True)
  70. def mint_printed_launch_ticket(state) -> str:
  71. """Ticket for a launch link the user opens by hand where nothing identifies the redeeming
  72. connection's owner (macOS, the BSDs, WSL): it spends without that check, as a window ticket does, so
  73. ``hermes webapp`` prints it and never passes it to a browser launcher."""
  74. return _mint_handoff_ticket(state, LAUNCH_TICKET_TTL_SECONDS, launch=False)
  75. def _loopback_peer_uid(client: tuple[str, int], server: tuple[str, int]) -> int | None:
  76. """Owner UID of the client end of a local TCP connection, from Linux ``/proc/net/tcp*``.
  77. Both ends of a loopback connection are listed with their socket owner; the client's is
  78. the row whose local address is *client* and remote address is *server*. None when absent
  79. (another network namespace, a closed connection) or unreadable.
  80. """
  81. def _normal(host: str | bytes, port: int):
  82. address = ipaddress.ip_address(host)
  83. return getattr(address, "ipv4_mapped", None) or address, port
  84. def _row_address(field: str):
  85. host_hex, port_hex = field.split(":")
  86. raw = bytes.fromhex(host_hex)
  87. # The kernel prints each 32-bit word of the address in host byte order.
  88. packed = b"".join(int.from_bytes(raw[i:i + 4], "big").to_bytes(4, sys.byteorder)
  89. for i in range(0, len(raw), 4))
  90. return _normal(packed, int(port_hex, 16))
  91. try:
  92. wanted = (_normal(*client), _normal(*server))
  93. except ValueError:
  94. return None
  95. for table in ("/proc/net/tcp", "/proc/net/tcp6"):
  96. try:
  97. with open(table, encoding="ascii") as stream:
  98. rows = stream.read().splitlines()[1:]
  99. except OSError:
  100. continue
  101. for row in rows:
  102. fields = row.split()
  103. try:
  104. if (_row_address(fields[1]), _row_address(fields[2])) == wanted:
  105. return int(fields[7])
  106. except (IndexError, ValueError):
  107. continue
  108. return None
  109. def _peer_is_server_user(request: Request, platform: str = sys.platform) -> bool:
  110. """Whether a launch ticket that crossed a browser launcher's argv may be spent over this
  111. request's connection on *platform* (a ``sys.platform`` value, this host's by default).
  112. Linux checks that the connection belongs to the OS user running the server. Windows checks
  113. nothing and always says yes: the protection there is that the ticket travels only in the
  114. launcher's command line, which only its own user, SYSTEM and elevated administrators can read.
  115. Elsewhere (macOS, the BSDs) every local user can read the launcher's argv and nothing here
  116. identifies the connection's owner, so an argv-carried launch ticket cannot be redeemed; WSL
  117. never mints one. Authenticated child-window tickets and the launch tickets ``hermes webapp``
  118. prints for the user to open by hand (``mint_printed_launch_ticket``) do not use this launcher
  119. channel.
  120. """
  121. if platform == "win32":
  122. return True
  123. if platform != "linux":
  124. return False
  125. client, server = request.client, request.scope.get("server")
  126. if client is None or not server:
  127. return False
  128. return _loopback_peer_uid((client.host, client.port), (server[0], server[1])) == os.getuid() # windows-footgun: ok — Linux-only branch
  129. @router.post("/api/webapp/window-ticket")
  130. async def issue_window_ticket(request: Request):
  131. from hermes_cli.web_server import _require_token
  132. _require_private_webapp(request)
  133. _require_token(request)
  134. ticket = _mint_handoff_ticket(request.app.state, WINDOW_TICKET_TTL_SECONDS, launch=False)
  135. return JSONResponse({"ticket": ticket}, headers={"Cache-Control": "no-store"})
  136. def _ticket_principal(request: Request) -> tuple[dict, str | None]:
  137. """``({user_id, provider, issuer}, session_token)`` of the caller: its verified login (no
  138. token), or on an unauthenticated loopback bind ``SESSION_TOKEN_OWNER`` and the session token
  139. it presented."""
  140. session = getattr(request.state, "session", None)
  141. if session is not None:
  142. return {"user_id": session.user_id, "provider": session.provider,
  143. "issuer": getattr(session, "issuer", "") or ""}, None
  144. if not getattr(request.app.state, "auth_required", False):
  145. from hermes_cli.web_server import _SESSION_HEADER_NAME, _has_valid_session_token
  146. presented = (request.headers.get(_SESSION_HEADER_NAME)
  147. or request.headers.get("authorization", "").removeprefix("Bearer "))
  148. if _has_valid_session_token(request):
  149. return dict(SESSION_TOKEN_OWNER), presented
  150. raise HTTPException(status_code=401, detail="Unauthorized")
  151. def mint_socket_ticket(identity: dict, socket: str, *, session_token: str | None = None,
  152. sign_in: str | None = None, profile_home: str | None = None) -> str:
  153. """A one-use ticket that opens only *socket* (``web_session_sockets.GATEWAY_SOCKET``,
  154. ``HOST_TERMINAL_SOCKET`` or one of ``AUDIO_SOCKETS``) as *identity*. Minted with
  155. *session_token*, or by a login whose sign-in binding was checked against the browser credential
  156. of generation *sign_in* (``hermes_cli.webapp_sign_in``), it records that credential's generation
  157. (``hermes_cli.browser_credential``): it opens nothing once that credential is replaced, and the
  158. socket it opens closes when the browser signs out. With *profile_home* the socket it opens answers
  159. for that profile (``chat_ws.gateway_ws``)."""
  160. from hermes_cli.browser_credential import generation_of
  161. from hermes_cli.dashboard_auth.ws_tickets import mint_ticket
  162. extra = {"socket": socket}
  163. if session_token is not None:
  164. extra["session_token"] = generation_of(session_token)
  165. if sign_in is not None:
  166. extra["sign_in"] = sign_in
  167. if profile_home is not None:
  168. extra["profile_home"] = profile_home
  169. return mint_ticket(user_id=identity["user_id"], provider=identity["provider"],
  170. issuer=identity.get("issuer", ""), extra=extra)
  171. def _socket_ticket_response(request: Request, identity: dict, socket: str, session_token: str | None,
  172. profile_home: str | None = None) -> JSONResponse:
  173. from hermes_cli.dashboard_auth.ws_tickets import TTL_SECONDS
  174. from hermes_cli.webapp_sign_in import sign_in_of
  175. ticket = mint_socket_ticket(identity, socket, session_token=session_token, sign_in=sign_in_of(request),
  176. profile_home=profile_home)
  177. return JSONResponse({"ticket": ticket, "ttl_seconds": TTL_SECONDS}, headers={"Cache-Control": "no-store"})
  178. #: Every socket a Webapp page dials with a one-use ticket from ``POST /api/webapp/socket-ticket``, by
  179. #: its ``web_session_sockets`` name: the ``web_server_surface.SurfacePolicy`` field that lets a surface
  180. #: mint it, and whether the mint checks the profile the page will dial (400/404), so a stale tab learns
  181. #: its profile is gone there rather than from a socket that keeps closing.
  182. SOCKET_TICKETS: dict[str, tuple[str, bool]] = {
  183. GATEWAY_SOCKET: ("gateway_ticket", True),
  184. HOST_TERMINAL_SOCKET: ("host_terminal", False),
  185. SPEAK_STREAM_SOCKET: ("gateway_ticket", False),
  186. TRANSCRIBE_STREAM_SOCKET: ("gateway_ticket", False),
  187. }
  188. @router.post("/api/webapp/socket-ticket")
  189. async def issue_socket_ticket(request: Request, socket: str = "", profile: str | None = None):
  190. """The browser's one-use ticket for one dial of *socket* on this same origin: ``gateway`` for
  191. ``/api/ws`` (also offered as the ``hermes-gateway-ticket.`` subprotocol), ``host-terminal`` for
  192. ``/api/host-terminal``, ``speak-stream`` and ``transcribe-stream`` for ``/api/audio/<name>``. The
  193. upgrade gate (``web_server_chat._consume_ws_ticket``) redeems it as this caller's login; it opens
  194. that socket and nothing else, so the browser mints one per dial. Minted locally: the server that
  195. serves this page runs the socket's sessions. A ``gateway`` ticket minted with *profile* names
  196. it: that socket answers a request that names no profile for *profile*, as a native ticket does
  197. (``chat_ws.gateway_ws``), never for the gateway's launch profile."""
  198. from hermes_cli.web_server_cron import _cron_profile_home
  199. if socket not in SOCKET_TICKETS:
  200. raise HTTPException(400, "Unknown socket")
  201. surface, checks_profile = SOCKET_TICKETS[socket]
  202. if not getattr(policy(request.app.state), surface):
  203. raise HTTPException(404, f"Webapp {socket} tickets are unavailable on this surface")
  204. identity, session_token = _ticket_principal(request)
  205. profile_home = None
  206. if checks_profile:
  207. _name, home = _cron_profile_home(profile)
  208. if socket == GATEWAY_SOCKET and profile:
  209. profile_home = str(home)
  210. return _socket_ticket_response(request, identity, socket, session_token, profile_home=profile_home)
  211. @router.post("/webapp/window-session")
  212. async def redeem_window_ticket(request: Request):
  213. from hermes_cli import browser_credential
  214. _require_private_webapp(request)
  215. # This endpoint deliberately sits outside /api: the child window or launch
  216. # tab has no session yet. Only a purpose-specific ticket can exchange for
  217. # the existing one.
  218. # Private links use the actual bind origin, which may differ from a
  219. # configured loopback public_url. Host validation remains in middleware;
  220. # proxy-normalized ASGI scheme/Host (not raw forwarded headers) are trusted.
  221. origins = request.headers.getlist("origin")
  222. origin = _http_origin(origins[0]) if len(origins) == 1 else None
  223. target_origin = _http_origin(f"{request.url.scheme}://{request.url.netloc}")
  224. if origin is None or origin != target_origin:
  225. raise HTTPException(403, "Webapp window handoff requires a same-origin request")
  226. # Keep the unauthenticated exchange body-free; never parse an arbitrary
  227. # JSON/multipart payload just to extract a fixed-size capability.
  228. ticket = request.headers.get("X-Hermes-Window-Ticket", "")
  229. with _ticket_lock:
  230. tickets = getattr(request.app.state, "webapp_window_tickets", {})
  231. entry = tickets.get(ticket)
  232. # A launch ticket crossed a browser launcher's argv: only a connection owned by this
  233. # server's user may spend it, and a refused attempt must not burn it for the real browser.
  234. if entry is not None and entry[2] and not _peer_is_server_user(request):
  235. entry = None
  236. elif entry is not None:
  237. del tickets[ticket]
  238. token = browser_credential.current_if(entry[1]) if entry is not None and entry[0] > time.monotonic() else None
  239. if token is None:
  240. raise HTTPException(403, "Webapp window link expired or was already used; open a new window")
  241. return JSONResponse({"token": token}, headers={"Cache-Control": "no-store"})
  242. # The credential goes to this tab's sessionStorage, where the Webapp reads it at boot
  243. # (browser-launch-session.ts), never into a URL: the browser keeps every address it opens in its history.
  244. _LAUNCH_SCRIPT = r"""
  245. const basePath = __BASE_PATH__;
  246. const params = new URLSearchParams(location.hash.slice(1));
  247. history.replaceState(null, '', location.pathname);
  248. const ticket = params.get('ticket') || '';
  249. const show = message => { document.getElementById('status').textContent = message; };
  250. const fail = () => show('This launch link was already used or has expired. Run hermes webapp again for a new one.');
  251. if (!/^[A-Za-z0-9_-]{43}$/.test(ticket)) {
  252. fail();
  253. } else {
  254. fetch(`${basePath}/webapp/window-session`, {
  255. method: 'POST', credentials: 'same-origin', headers: {'X-Hermes-Window-Ticket': ticket}
  256. }).then(response => response.ok ? response.json() : Promise.reject()).then(({token}) => {
  257. if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw new Error();
  258. try {
  259. sessionStorage.setItem(`hermes.webapp.session.v1:${JSON.stringify([location.origin, basePath])}`, token);
  260. } catch {
  261. show('This browser does not let the Webapp keep its sign-in in this tab. Allow site data for this '
  262. + 'address, then run hermes webapp again.');
  263. return;
  264. }
  265. const target = new URL(`${basePath}/`, location.origin);
  266. target.search = params.get('query') || '';
  267. location.replace(target.href);
  268. }).catch(fail);
  269. }
  270. """
  271. def _handoff_page(request: Request, title: str, status: str, script: str) -> HTMLResponse:
  272. """Credential-free, uncached page whose only script is *script* (``__BASE_PATH__`` bound)."""
  273. from hermes_cli.web_server_dashboard import _normalise_prefix
  274. prefix = _normalise_prefix(request.headers.get("x-forwarded-prefix"))
  275. nonce = secrets.token_urlsafe(16)
  276. script = script.replace("__BASE_PATH__", json.dumps(prefix).replace("</", "<\\/"))
  277. return HTMLResponse(
  278. '<!doctype html><meta charset="utf-8"><meta name="referrer" content="no-referrer">'
  279. f'<title>{title}</title><p id="status">{status}</p>'
  280. f'<script nonce="{nonce}">{script}</script>',
  281. headers={
  282. "Cache-Control": "no-store",
  283. "Referrer-Policy": "no-referrer",
  284. "Content-Security-Policy": f"default-src 'none'; script-src 'nonce-{nonce}'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
  285. },
  286. )
  287. @router.get("/webapp/launch")
  288. async def launch_page(request: Request):
  289. """Where the server's own browser-open lands: spends the one-use launch ticket from the
  290. fragment (never sent to the server), keeps the credential it receives in this tab's
  291. sessionStorage and enters the Webapp at an address that carries neither."""
  292. _require_private_webapp(request)
  293. return _handoff_page(request, "Opening Hermes", "Opening Hermes Webapp…", _LAUNCH_SCRIPT)
  294. # No credential appears in this public page or in its URL. The fragment
  295. # names a transient channel; the authorized parent mints a one-use ticket.
  296. _WINDOW_SCRIPT = r"""
  297. const basePath = __BASE_PATH__;
  298. const params = new URLSearchParams(location.hash.slice(1));
  299. history.replaceState(null, '', location.pathname);
  300. const id = params.get('channel') || '';
  301. const status = document.getElementById('status');
  302. if (!/^[a-f0-9-]{36}$/.test(id)) {
  303. status.textContent = 'Open this window from an authorized Hermes Webapp tab.';
  304. } else {
  305. const channel = new BroadcastChannel(`hermes.webapp.window:${id}`);
  306. let receiving = false;
  307. let finished = false;
  308. const controller = new AbortController();
  309. const fail = message => {
  310. if (finished) return;
  311. finished = true;
  312. controller.abort();
  313. status.textContent = message;
  314. channel.postMessage({type: 'error'});
  315. channel.close();
  316. clearTimeout(timeout);
  317. };
  318. const timeout = setTimeout(() => fail('This window link expired. Open a new window from the original tab.'), 30000);
  319. channel.onmessage = async event => {
  320. if (receiving) return;
  321. if (event.data?.error) { fail(event.data.error); return; }
  322. const ticket = event.data?.ticket;
  323. if (typeof ticket !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(ticket)) return;
  324. receiving = true;
  325. try {
  326. const response = await fetch(`${basePath}/webapp/window-session`, {
  327. method: 'POST', credentials: 'same-origin',
  328. headers: {'X-Hermes-Window-Ticket': ticket}, signal: controller.signal
  329. });
  330. if (!response.ok) throw new Error('Window authorization expired. Open a new window from the original tab.');
  331. const {token} = await response.json();
  332. if (finished) return;
  333. if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw new Error('Invalid window authorization.');
  334. sessionStorage.setItem(`hermes.webapp.session.v1:${JSON.stringify([location.origin, basePath])}`, token);
  335. const target = new URL(`${basePath}/`, location.origin);
  336. target.search = params.get('query') || '';
  337. target.hash = params.get('route') || '/';
  338. channel.postMessage({type: 'done'});
  339. finished = true;
  340. clearTimeout(timeout);
  341. channel.close();
  342. location.replace(target.href);
  343. } catch (error) { fail(error.message || 'Could not authorize this window. Open it again from the original tab.'); }
  344. };
  345. channel.postMessage({type: 'ready'});
  346. }
  347. """
  348. @router.get("/webapp/window")
  349. async def child_window_page(request: Request):
  350. _require_private_webapp(request)
  351. return _handoff_page(request, "Opening Hermes", "Authorizing this Hermes window…", _WINDOW_SCRIPT)