link.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. """Account linking to the shared Team Gateway bot, done from the instance itself.
  2. A relay-fronted deployment (Hermes Cloud with Team Gateway) reaches Telegram, Discord and Slack
  3. only through the connector's SHARED bot: the gateway turns every direct adapter off
  4. (``config_env._relay``), and the connector routes a chat account's messages to this instance once
  5. that account is linked (``/link <code>`` DMed to the shared bot). The Portal can mint those codes;
  6. this module lets the instance's own dashboard and Desktop do it too, so a user who opens Channels
  7. on the instance gets a working setup instead of a bot of their own the relay will never run.
  8. Codes are minted with the gateway's per-gateway secret, which lives only in the gateway process
  9. (``self_provision_relay``), so the dashboard reaches these calls through the ``relay-link``
  10. control-socket verb. Wire: ``POST /manage/link``, ``/manage/link/state``, ``/manage/link-status``
  11. and ``/manage/unlink`` on the connector, all authenticated with the WS-upgrade bearer.
  12. A Portal-managed agent (the connector's ``/manage/access/list`` answers ``managedBy: portal``) is
  13. the exception: there the Portal access setting is the only input, so a code minted with the
  14. gateway bearer carries no owner and its redeem binds nothing. For those agents linking happens in
  15. the Portal, which mints owner-attested codes; the instance only lists the linked accounts.
  16. """
  17. from __future__ import annotations
  18. import json
  19. import os
  20. import urllib.error
  21. import urllib.request
  22. from typing import Any, Callable, Optional
  23. _HTTP_TIMEOUT_S = 10.0
  24. # Longer than one connector call so the dashboard sees the connector's answer, not a socket timeout.
  25. CONTROL_TIMEOUT_S = _HTTP_TIMEOUT_S + 5.0
  26. class RelayLinkError(RuntimeError):
  27. """A link call that cannot be served; ``code`` is a stable slug the surfaces translate."""
  28. def __init__(self, code: str, message: str, status: int = 0) -> None:
  29. super().__init__(message)
  30. self.code = code
  31. self.status = status
  32. def _bot_entry(platform: str) -> dict:
  33. from gateway.relay import _relay_bot_ids_map
  34. entry = _relay_bot_ids_map().get(platform)
  35. return entry if isinstance(entry, dict) else {}
  36. def shared_bot_url(platform: str, code: Optional[str] = None) -> Optional[str]:
  37. """Where to DM the shared bot, from the ``GATEWAY_RELAY_BOT_IDS`` entry the Portal stamps
  38. (same rule as the Portal's ``buildBotDmUrl``). None when the entry names no reachable handle."""
  39. entry = _bot_entry(platform)
  40. if platform == "telegram":
  41. username = str(entry.get("username") or "").strip().lstrip("@")
  42. return f"https://t.me/{username}" if username else None
  43. if platform == "discord":
  44. bot_id = str(entry.get("botId") or "").strip()
  45. return f"https://discord.com/users/{bot_id}" if bot_id else None
  46. if platform == "whatsapp":
  47. number = "".join(ch for ch in str(entry.get("waNumber") or entry.get("botId") or "") if ch.isdigit())
  48. if not number:
  49. return None
  50. from urllib.parse import quote
  51. return f"https://wa.me/{number}?text={quote(f'/link {code}' if code else '/link')}"
  52. return None
  53. def relay_channel_view() -> tuple[frozenset[str], bool]:
  54. """``(platforms the shared bots carry here, direct adapters are switched off)``.
  55. The second half mirrors ``config_env._relay``: only the ``GATEWAY_RELAY_URL`` env stamp without
  56. ``GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS`` makes the relay exclusive. Reads this process's env, which
  57. on a hosted instance is the container stamp every process shares."""
  58. from gateway.relay import relay_fronted_platforms, relay_url
  59. from utils import is_truthy_value
  60. if not relay_url():
  61. return frozenset(), False
  62. exclusive = bool(os.environ.get("GATEWAY_RELAY_URL", "").strip()) and not is_truthy_value(
  63. os.environ.get("GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS"))
  64. return frozenset(relay_fronted_platforms()), exclusive
  65. def _bearer_and_base() -> tuple[str, str]:
  66. from gateway.relay import _connector_url, relay_connection_auth, relay_url
  67. from gateway.relay.auth import make_upgrade_token
  68. dial_url = relay_url()
  69. if not dial_url:
  70. raise RelayLinkError("relay_not_configured", "Team Gateway is not configured on this instance.")
  71. gateway_id, secret = relay_connection_auth()
  72. if not (gateway_id and secret):
  73. raise RelayLinkError(
  74. "relay_not_provisioned",
  75. "The gateway has not connected to Team Gateway yet. Wait a minute and try again.")
  76. return make_upgrade_token(gateway_id, secret), _connector_url(dial_url, "")
  77. # Connector HTTP status -> (slug, sentence the surfaces show). Anything else 4xx is a refusal; 5xx/408/429
  78. # mean "try again" (``connector_unavailable``).
  79. _HTTP_REFUSALS: dict[int, tuple[str, str]] = {
  80. 401: ("relay_not_authorized",
  81. "Team Gateway no longer accepts this instance's credentials. Restart the gateway to reconnect it."),
  82. 403: ("platform_not_provisioned", "Team Gateway is not set up for this platform on this instance."),
  83. 409: ("instance_not_bound", "This instance is not bound to Team Gateway yet. Restart the gateway and try again."),
  84. }
  85. def _http_error(code: int, reason: str) -> RelayLinkError:
  86. if code in _HTTP_REFUSALS:
  87. slug, message = _HTTP_REFUSALS[code]
  88. return RelayLinkError(slug, message, code)
  89. if code >= 500 or code in (408, 429):
  90. return RelayLinkError("connector_unavailable", "Team Gateway is not answering right now. Try again shortly.", code)
  91. return RelayLinkError("connector_refused", reason or f"Team Gateway answered HTTP {code}.", code)
  92. def _post(path: str, body: dict) -> dict:
  93. from gateway.relay import _json_post
  94. from gateway.relay.http_diagnostics import connector_reason, read_error_body, redact_excerpt
  95. token, base = _bearer_and_base()
  96. try:
  97. with _json_post(f"{base}{path}", token, body, _HTTP_TIMEOUT_S) as resp:
  98. payload = json.loads(resp.read().decode() or "{}")
  99. except urllib.error.HTTPError as exc:
  100. reason = redact_excerpt(connector_reason(read_error_body(exc)), (token,))
  101. raise _http_error(exc.code, reason) from exc
  102. except (urllib.error.URLError, OSError, ValueError) as exc:
  103. raise RelayLinkError("connector_unreachable", f"Could not reach Team Gateway: {exc}") from exc
  104. return payload if isinstance(payload, dict) else {}
  105. def _get(path: str) -> dict:
  106. from gateway.relay.http_diagnostics import connector_reason, read_error_body, redact_excerpt
  107. token, base = _bearer_and_base()
  108. req = urllib.request.Request(f"{base}{path}", method="GET", headers={
  109. "Authorization": f"Bearer {token}", "Accept": "application/json"})
  110. try:
  111. with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT_S) as resp:
  112. payload = json.loads(resp.read().decode() or "{}")
  113. except urllib.error.HTTPError as exc:
  114. reason = redact_excerpt(connector_reason(read_error_body(exc)), (token,))
  115. raise _http_error(exc.code, reason) from exc
  116. except (urllib.error.URLError, OSError, ValueError) as exc:
  117. raise RelayLinkError("connector_unreachable", f"Could not reach Team Gateway: {exc}") from exc
  118. return payload if isinstance(payload, dict) else {}
  119. def portal_agents_url() -> str:
  120. """The Portal this instance signs in to (operator override, stored login, then default)."""
  121. from hermes_cli.auth import get_provider_auth_state
  122. from hermes_cli.auth_nous import _nous_portal_base_url
  123. return f"{_nous_portal_base_url(get_provider_auth_state('nous') or {})}/agents"
  124. def managed_by() -> str:
  125. """``portal`` when the Portal access setting governs this agent, else ``connector``.
  126. A connector that does not serve access grants (no route: 404) has no Portal setting either."""
  127. try:
  128. payload = _get("/manage/access/list")
  129. except RelayLinkError as exc:
  130. if exc.status == 404:
  131. return "connector"
  132. raise
  133. return "portal" if payload.get("managedBy") == "portal" else "connector"
  134. def _managed_by_for_listing() -> str:
  135. # The list must not disappear when only this question fails: minting re-asks and refuses.
  136. try:
  137. return managed_by()
  138. except RelayLinkError:
  139. return "unknown"
  140. def request_link(platform: str) -> dict[str, Any]:
  141. """Mint a one-time code that binds the chat account which DMs it to this instance."""
  142. from gateway.relay import relay_fronted_platforms
  143. if platform not in relay_fronted_platforms():
  144. raise RelayLinkError("platform_not_fronted", f"Team Gateway does not carry {platform} on this instance.")
  145. if managed_by() == "portal":
  146. raise RelayLinkError(
  147. "managed_by_portal",
  148. "Accounts for this agent are linked from Nous Portal: open the agent there and use Message platforms.",
  149. 409)
  150. payload = _post("/manage/link", {"platform": platform})
  151. code = str(payload.get("code") or "").strip()
  152. if not code:
  153. raise RelayLinkError("connector_refused", "Team Gateway did not issue a link code.")
  154. return {"platform": platform, "code": code, "command": f"/link {code}",
  155. "expires_at": payload.get("expiresAt"), "bot_url": shared_bot_url(platform, code)}
  156. def link_code_state(code: str) -> dict[str, Any]:
  157. """``pending`` until redeemed; ``inactive`` once used or expired; ``refused`` with a reason."""
  158. payload = _post("/manage/link/state", {"code": code})
  159. return {"state": payload.get("state") or "inactive", "reason": payload.get("reason")}
  160. def link_status() -> dict[str, Any]:
  161. """Accounts linked to this instance, per fronted platform, plus each shared bot's DM link."""
  162. from gateway.relay import relay_fronted_platforms
  163. platforms = sorted(relay_fronted_platforms())
  164. payload = _post("/manage/link-status", {"platforms": platforms}) if platforms else {}
  165. accounts = {row.get("platform"): row.get("accounts") or []
  166. for row in payload.get("statuses") or [] if isinstance(row, dict)}
  167. return {"managed_by": _managed_by_for_listing() if platforms else "connector", "portal_url": portal_agents_url(),
  168. "platforms": [{"platform": p, "bot_url": shared_bot_url(p), "accounts": accounts.get(p, [])}
  169. for p in platforms]}
  170. def unlink(platform: str, platform_user_id: str) -> dict[str, Any]:
  171. _post("/manage/unlink", {"platform": platform, "platformUserId": platform_user_id})
  172. return {"unlinked": True}
  173. _ACTIONS: dict[str, Callable[[dict], dict[str, Any]]] = {
  174. "request": lambda p: request_link(str(p.get("platform") or "")),
  175. "state": lambda p: link_code_state(str(p.get("code") or "")),
  176. "status": lambda p: link_status(),
  177. "unlink": lambda p: unlink(str(p.get("platform") or ""), str(p.get("platform_user_id") or "")),
  178. }
  179. def relay_link_verb(params: dict) -> dict[str, Any]:
  180. """Control-socket ``relay-link`` verb: ``{"action": request|state|status|unlink, ...}``.
  181. Answers ``{"ok": True, ...}`` or ``{"ok": False, "error": slug, "message", "status"}`` so the
  182. dashboard can tell "not ready yet" from a connector refusal; never raises."""
  183. action = _ACTIONS.get(str(params.get("action") or ""))
  184. if action is None:
  185. return {"ok": False, "error": "unknown_action", "message": "Unknown relay-link action."}
  186. try:
  187. return {"ok": True, **action(params)}
  188. except RelayLinkError as exc:
  189. return {"ok": False, "error": exc.code, "message": str(exc), "status": exc.status}