dashboard_register.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. """``hermes dashboard register`` — register a self-hosted dashboard OAuth client.
  2. Automates the Nous Portal ``/local-dashboards`` flow: resolve a fresh Nous access token, POST
  3. ``{portal}/api/oauth/self-hosted-client`` (the ``agent:`` prefix is applied server-side),
  4. write ``HERMES_DASHBOARD_OAUTH_CLIENT_ID`` (+ portal/public URL when warranted) into ``.env``
  5. idempotently, then print the gate-engagement hint.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import os
  10. import random
  11. import sys
  12. import urllib.error
  13. import urllib.request
  14. from typing import Optional
  15. from urllib.parse import urlparse
  16. _DEFAULT_PORTAL = "https://portal.nousresearch.com"
  17. # Docker-style adjective_noun names; the portal keys on row id, so collisions are harmless.
  18. _NAME_ADJECTIVES = (
  19. "amber", "bold", "brave", "bright", "calm", "clever", "cosmic", "crisp",
  20. "dreamy", "eager", "electric", "fancy", "gentle", "golden", "happy",
  21. "hidden", "jolly", "keen", "lively", "lucid", "lunar", "mellow", "merry",
  22. "mighty", "nimble", "noble", "polished", "quiet", "quirky", "rapid",
  23. "serene", "sharp", "shiny", "silent", "snappy", "solar", "spry", "stellar",
  24. "sunny", "swift", "tidy", "vivid", "vibrant", "witty", "zesty")
  25. _NAME_NOUNS = (
  26. "albatross", "antelope", "badger", "beacon", "comet", "condor", "cypress",
  27. "dolphin", "ember", "falcon", "ferret", "galaxy", "glacier", "harbor",
  28. "heron", "ibex", "jaguar", "kestrel", "lantern", "lynx", "meadow", "nebula",
  29. "ocelot", "orchid", "otter", "panther", "petrel", "quasar", "raven", "reef",
  30. "sparrow", "summit", "tundra", "vortex", "walrus", "willow", "yarrow",
  31. "kepler", "tesla", "curie", "hopper", "turing", "lovelace")
  32. def _generate_dashboard_name() -> str:
  33. return f"{random.choice(_NAME_ADJECTIVES)}_{random.choice(_NAME_NOUNS)}"
  34. def _resolve_portal_base_url(override: Optional[str] = None) -> str:
  35. """Portal base URL: explicit *override* (must be the token's issuer), then the login's stored
  36. ``portal_base_url``, then production."""
  37. if isinstance(override, str) and override.strip():
  38. return override.rstrip("/")
  39. try:
  40. from hermes_cli.auth import DEFAULT_NOUS_PORTAL_URL, get_provider_auth_state
  41. base = (get_provider_auth_state("nous") or {}).get("portal_base_url")
  42. chosen = base if isinstance(base, str) and base.strip() else str(DEFAULT_NOUS_PORTAL_URL)
  43. return chosen.rstrip("/")
  44. except Exception:
  45. return _DEFAULT_PORTAL
  46. def _register_self_hosted_client(
  47. *, access_token: str, portal_base_url: str, name: Optional[str], custom_redirect_uri: Optional[str],
  48. existing_client_id: Optional[str] = None, timeout: float = 15.0) -> dict:
  49. """POST to the portal's self-hosted-client endpoint and return the JSON body.
  50. ``existing_client_id`` makes the portal update that record in place (idempotent re-runs;
  51. the portal mints a fresh client if the id no longer resolves, so passing it is always safe).
  52. ``name`` is ``None`` on the update path without ``--name`` (portal keeps the stored name).
  53. Raises RuntimeError with a user-facing message on non-2xx or transport failure.
  54. """
  55. fields = (("name", name), ("custom_redirect_uri", custom_redirect_uri),
  56. ("client_id", existing_client_id))
  57. req = urllib.request.Request(
  58. f"{portal_base_url.rstrip('/')}/api/oauth/self-hosted-client",
  59. data=json.dumps({k: v for k, v in fields if v}).encode("utf-8"), method="POST",
  60. headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json",
  61. "Accept": "application/json"})
  62. try:
  63. with urllib.request.urlopen(req, timeout=timeout) as resp:
  64. payload = json.loads(resp.read().decode())
  65. except urllib.error.HTTPError as exc:
  66. try: # structured JSON errors: {error, error_description}
  67. err_body = json.loads(exc.read().decode())
  68. detail = err_body.get("error_description") or err_body.get("error") or ""
  69. except Exception:
  70. detail = ""
  71. if exc.code == 401:
  72. message = ("Nous Portal rejected the access token (401). "
  73. "Try `hermes auth add nous` to re-authenticate.")
  74. elif exc.code == 403:
  75. message = detail or "Your account is not permitted to register a self-hosted dashboard."
  76. else:
  77. message = f"Portal returned HTTP {exc.code}" + (f": {detail}" if detail else "")
  78. raise RuntimeError(message) from exc
  79. except urllib.error.URLError as exc:
  80. raise RuntimeError(f"Could not reach Nous Portal at {portal_base_url}: {exc.reason}") from exc
  81. if not isinstance(payload, dict) or not payload.get("client_id"):
  82. raise RuntimeError("Portal returned an unexpected response (no client_id).")
  83. return payload
  84. def _print_post_register_hint(
  85. *, client_id: str, portal_base_url: str, custom_redirect_uri: Optional[str],
  86. wrote_portal_url: bool, public_url: str = "") -> None:
  87. """Print the success summary + the gate-engagement caveat."""
  88. from hermes_cli.config import get_env_path
  89. print(f"\n Wrote to {get_env_path()}:\n HERMES_DASHBOARD_OAUTH_CLIENT_ID={client_id}")
  90. if wrote_portal_url:
  91. print(" HERMES_DASHBOARD_PORTAL_URL=" + str(portal_base_url))
  92. if public_url:
  93. print(" HERMES_DASHBOARD_PUBLIC_URL=" + str(public_url))
  94. print(
  95. "\n Heads up — Nous login only *engages* on a non-loopback bind. A plain\n"
  96. " `hermes dashboard` (localhost) leaves the gate off and serves locally\n"
  97. " without auth, which is fine for your own machine.\n")
  98. if custom_redirect_uri:
  99. try: # example host matches the one the user registered
  100. host = urlparse(custom_redirect_uri).hostname or "your-host"
  101. except Exception:
  102. host = "your-host"
  103. print(
  104. " To require Nous login on your registered host, run the dashboard\n"
  105. f" bound publicly (it must be reachable at https://{host}) and log in\n"
  106. " at its /login page.")
  107. else:
  108. print(
  109. " To require Nous login (e.g. exposing on your LAN or a public host):\n"
  110. " hermes dashboard --host 0.0.0.0\n"
  111. " …then log in at the dashboard's /login page.")
  112. print(
  113. "\n If the dashboard is already running, restart it to pick up the new env.\n"
  114. f" Manage or revoke this dashboard at {portal_base_url}/local-dashboards")
  115. def _env_value(key: str) -> Optional[str]:
  116. """Stored ``.env`` value, or ``None`` on any read failure."""
  117. from hermes_cli.config import get_env_value
  118. try:
  119. return get_env_value(key)
  120. except Exception:
  121. return None
  122. def _save_env_quietly(key: str, value: str) -> bool:
  123. """Persist *key*; False on failure (non-fatal: only client_id is load-bearing)."""
  124. from hermes_cli.config import save_env_value
  125. try:
  126. save_env_value(key, value)
  127. return True
  128. except Exception:
  129. return False
  130. def _public_url_from_redirect(redirect_uri: Optional[str]) -> str:
  131. """Origin (``scheme://host[:port]``) of *redirect_uri*, or ``""`` — the runtime appends
  132. ``/auth/callback`` to HERMES_DASHBOARD_PUBLIC_URL, so the raw URI would double the path."""
  133. try:
  134. parsed = urlparse(redirect_uri or "")
  135. if parsed.scheme in ("http", "https") and parsed.netloc:
  136. return f"{parsed.scheme}://{parsed.netloc}"
  137. except Exception:
  138. pass
  139. return ""
  140. def cmd_dashboard_register(args) -> None:
  141. """Register a self-hosted dashboard OAuth client with Nous Portal."""
  142. from hermes_cli.auth import AuthError, resolve_nous_access_token
  143. from hermes_cli.config import is_managed, save_env_value
  144. # Managed installs get the client id stamped in by the orchestrator (save_env_value refuses).
  145. if is_managed():
  146. print("✗ `hermes dashboard register` is not available in a managed/hosted install.\n"
  147. " The dashboard OAuth client is provisioned by the hosting platform.")
  148. sys.exit(1)
  149. try:
  150. access_token = resolve_nous_access_token()
  151. except Exception as exc:
  152. if isinstance(exc, AuthError) and getattr(exc, "relogin_required", False):
  153. print("✗ You're not logged into Nous Portal.\n"
  154. " Run `hermes setup` (or `hermes auth add nous`) first, then retry.")
  155. else:
  156. print(f"✗ Could not resolve a Nous Portal access token: {exc}")
  157. sys.exit(1)
  158. # An explicitly supplied portal (flag or env) is persisted in place; an inferred one is
  159. # written only if absent so .env isn't cluttered for the common production case.
  160. portal_override = getattr(args, "portal_url", None) or os.environ.get("HERMES_DASHBOARD_PORTAL_URL")
  161. custom_portal_supplied = bool(isinstance(portal_override, str) and portal_override.strip())
  162. portal_base_url = _resolve_portal_base_url(portal_override)
  163. # Re-sending a locally held client_id makes the portal UPDATE that record (idempotent).
  164. stored = _env_value("HERMES_DASHBOARD_OAUTH_CLIENT_ID")
  165. existing_client_id = (stored.strip() or None) if isinstance(stored, str) else None
  166. # Auto-name ONLY a first registration; a re-run without --name keeps the stored name.
  167. name = getattr(args, "name", None) or (None if existing_client_id else _generate_dashboard_name())
  168. custom_redirect_uri = getattr(args, "redirect_uri", None)
  169. try:
  170. result = _register_self_hosted_client(
  171. access_token=access_token, portal_base_url=portal_base_url, name=name,
  172. custom_redirect_uri=custom_redirect_uri, existing_client_id=existing_client_id)
  173. except RuntimeError as exc:
  174. print(f"✗ Registration failed: {exc}")
  175. sys.exit(1)
  176. client_id = str(result["client_id"])
  177. registered_name = str(result.get("name") or name or "")
  178. # The portal echoes back the same client_id when it updated in place.
  179. verb = "Updated" if existing_client_id and client_id == existing_client_id else "Registered"
  180. print(f'✓ {verb} dashboard "{registered_name}"')
  181. try: # client_id is load-bearing: fatal on failure
  182. save_env_value("HERMES_DASHBOARD_OAUTH_CLIENT_ID", client_id)
  183. except Exception as exc:
  184. print(f"✗ Failed to write HERMES_DASHBOARD_OAUTH_CLIENT_ID to .env: {exc}\n"
  185. f" Set it manually: HERMES_DASHBOARD_OAUTH_CLIENT_ID={client_id}")
  186. sys.exit(1)
  187. # Explicit portal → always persist (the user asked); inferred → only if unset AND non-default.
  188. existing_portal = _env_value("HERMES_DASHBOARD_PORTAL_URL")
  189. should_write_portal = (
  190. existing_portal != portal_base_url
  191. if custom_portal_supplied
  192. else not existing_portal and portal_base_url.rstrip("/") != _DEFAULT_PORTAL)
  193. wrote_portal_url = should_write_portal and _save_env_quietly("HERMES_DASHBOARD_PORTAL_URL", portal_base_url)
  194. # Public URL from --redirect-uri: written when supplied and different; never localhost-only.
  195. public_url = _public_url_from_redirect(custom_redirect_uri)
  196. wrote_public_url = bool(
  197. public_url
  198. and _env_value("HERMES_DASHBOARD_PUBLIC_URL") != public_url
  199. and _save_env_quietly("HERMES_DASHBOARD_PUBLIC_URL", public_url))
  200. _print_post_register_hint(
  201. client_id=client_id, portal_base_url=portal_base_url, custom_redirect_uri=custom_redirect_uri,
  202. wrote_portal_url=wrote_portal_url, public_url=public_url if wrote_public_url else "")