setup_platforms.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. """Messaging-platform setup wizards (Telegram, webhooks) and the ``hermes setup
  2. gateway`` flow. setup.py re-exports the public names, and tests monkeypatch prompt/print/env
  3. helpers on hermes_cli.setup, so those are imported lazily per function."""
  4. import contextlib
  5. import logging
  6. import re
  7. from pathlib import Path
  8. logger = logging.getLogger("hermes_cli.setup")
  9. _TELEGRAM_BOT_TOKEN_RE = re.compile(r"^\d+:[A-Za-z0-9_-]{30,}$")
  10. _RULE = "━" * 50
  11. def _is_valid_telegram_bot_token(token: str) -> bool:
  12. return bool(_TELEGRAM_BOT_TOKEN_RE.match(token))
  13. def _profile_name_from_hermes_home(hermes_home) -> str | None:
  14. """Return the active profile name when HERMES_HOME is a profile dir."""
  15. return hermes_home.name if hermes_home.parent.name == "profiles" else None
  16. def _setup_telegram_auto_result():
  17. """Attempt automatic Telegram bot creation via managed QR onboarding."""
  18. from hermes_cli.setup import get_hermes_home
  19. try:
  20. from hermes_cli.telegram_managed_bot import auto_setup_telegram_bot_result
  21. except ImportError:
  22. return None
  23. profile_name: str | None = None
  24. with contextlib.suppress(Exception):
  25. profile_name = _profile_name_from_hermes_home(Path(get_hermes_home()))
  26. return auto_setup_telegram_bot_result(profile_name=profile_name)
  27. def declines_reconfigure(label: str, question: str, *env_vars: str) -> bool:
  28. """True when any of ``env_vars`` is already set and the user does NOT want to reconfigure.
  29. Shared by the core wizards and every platform plugin's ``interactive_setup`` so the
  30. "already configured? Reconfigure? [y/N]" gate has one wording and one default.
  31. """
  32. from hermes_cli.setup import get_env_value, print_info, prompt_yes_no
  33. if not any(get_env_value(v) for v in env_vars):
  34. return False
  35. print_info(f"{label}: already configured")
  36. return not prompt_yes_no(question, False)
  37. def save_prompted(env_var: str, question: str, *, password: bool = False, success_msg: str | None = None,
  38. skip_msg: str | None = None, transform=None) -> str:
  39. """Prompt, persist the (optionally transformed) answer when non-empty, and report either way.
  40. ``success_msg`` may reference ``{value}``. Returns the raw answer ("" when skipped).
  41. """
  42. from hermes_cli.setup import print_success, print_warning, prompt, save_env_value
  43. value = prompt(question, password=password)
  44. if value:
  45. save_env_value(env_var, transform(value) if transform else value)
  46. if success_msg:
  47. print_success(success_msg.format(value=value))
  48. elif skip_msg:
  49. print_warning(skip_msg)
  50. return value
  51. def _save_allowlist(env_var: str, users: str, success_msg: str) -> None:
  52. """Strip spaces, persist the allowlist, and confirm."""
  53. from hermes_cli.setup import print_success, save_env_value
  54. save_env_value(env_var, users.replace(" ", ""))
  55. print_success(success_msg)
  56. def _prompt_allowlist(env_var: str, question: str, success_msg: str, open_msg: str, preset: str | None = None) -> str:
  57. """Persist ``preset`` (or the prompted answer) as an allowlist, warning when it stays open."""
  58. from hermes_cli.setup import print_info, prompt
  59. users = prompt(question) if preset is None else preset
  60. if users:
  61. _save_allowlist(env_var, users, success_msg)
  62. else:
  63. print_info(open_msg)
  64. return users.replace(" ", "")
  65. def _save_port(env_var: str, value: str, default: str) -> None:
  66. """Persist ``value`` as an int port; warn (keeping ``default``) when it isn't one."""
  67. from hermes_cli.setup import print_success, print_warning, save_env_value
  68. if not value:
  69. return
  70. try:
  71. save_env_value(env_var, str(int(value)))
  72. print_success(f"Webhook port set to {value}")
  73. except ValueError:
  74. print_warning(f"Invalid port number, using default {default}")
  75. def _prompt_telegram_bot_token() -> str | None:
  76. from hermes_cli.setup import print_error, print_info, prompt
  77. print_info("Create a bot via @BotFather on Telegram")
  78. while True:
  79. token = prompt("Telegram bot token", password=True)
  80. if not token or _is_valid_telegram_bot_token(token):
  81. return token or None
  82. print_error("Invalid token format. Expected: <numeric_id>:<alphanumeric_hash> "
  83. "(e.g., 123456789:ABCdefGHI-jklMNOpqrSTUvwxYZ)")
  84. def _telegram_allowlist_nudge() -> None:
  85. """Existing config kept as-is: warn when it has no user allowlist."""
  86. from hermes_cli.setup import get_env_value, print_info, prompt, prompt_yes_no
  87. if get_env_value("TELEGRAM_ALLOWED_USERS"):
  88. return
  89. print_info("⚠️ Telegram has no user allowlist - anyone can use your bot!")
  90. if prompt_yes_no("Add allowed users now?", True):
  91. print_info(" To find your Telegram user ID: message @userinfobot")
  92. allowed_users = prompt("Allowed user IDs (comma-separated)")
  93. if allowed_users:
  94. _save_allowlist("TELEGRAM_ALLOWED_USERS", allowed_users, "Telegram allowlist configured")
  95. def _obtain_telegram_token():
  96. """Return (token, setup_result); auto flow first when chosen, else manual paste."""
  97. from hermes_cli.setup import _info, print_error, prompt
  98. _info("How would you like to create your Telegram bot?", None,
  99. " [1] Automatic (recommended)",
  100. " Scan a QR code → confirm in Telegram → done.",
  101. " No token copy-paste needed.", None,
  102. " [2] Manual",
  103. " Create a bot via @BotFather yourself and paste the token.", None)
  104. token = setup_result = None
  105. if prompt("Choice [1/2]", default="1").strip() == "1":
  106. setup_result = _setup_telegram_auto_result()
  107. if setup_result:
  108. token = setup_result.token
  109. if not _is_valid_telegram_bot_token(token):
  110. print_error("Automatic setup returned an invalid Telegram bot token.")
  111. token = setup_result = None
  112. if not token:
  113. _info(None, "Falling back to manual setup...", None)
  114. if not token:
  115. token = _prompt_telegram_bot_token()
  116. return token, setup_result
  117. def _setup_telegram():
  118. """Configure Telegram bot credentials and allowlist."""
  119. from hermes_cli.setup import _info, print_info, print_header, print_success, prompt, prompt_yes_no, save_env_value
  120. print_header("Telegram")
  121. if declines_reconfigure("Telegram", "Reconfigure Telegram?", "TELEGRAM_BOT_TOKEN"):
  122. _telegram_allowlist_nudge()
  123. return
  124. token, setup_result = _obtain_telegram_token()
  125. if not token:
  126. return
  127. save_env_value("TELEGRAM_BOT_TOKEN", token)
  128. print_success("Telegram token saved")
  129. _info(None, "🔒 Security: Restrict who can use your bot",
  130. " To find your Telegram user ID:",
  131. " 1. Message @userinfobot on Telegram",
  132. " 2. It will reply with your numeric ID (e.g., 123456789)", None)
  133. allowed_users = None
  134. detected_id = str(getattr(setup_result, "owner_user_id", None) or "")
  135. if detected_id:
  136. print_success(f"Detected your Telegram user ID: {detected_id}")
  137. if prompt_yes_no("Allow this Telegram account to use the bot?", True):
  138. extra = prompt("Additional allowed user IDs (comma-separated, optional)")
  139. allowed_users = ",".join(dict.fromkeys([detected_id, *filter(None, extra.replace(" ", "").split(","))]))
  140. allowed_users = _prompt_allowlist(
  141. "TELEGRAM_ALLOWED_USERS", "Allowed user IDs (comma-separated, leave empty for open access)",
  142. "Telegram allowlist configured - only listed users can use the bot",
  143. "⚠️ No allowlist set - anyone who finds your bot can use it!", preset=allowed_users)
  144. _info(None, "📬 Home Channel: where Hermes delivers cron job results,",
  145. " cross-platform messages, and notifications.",
  146. " For Telegram DMs, this is your user ID (same as above).")
  147. first_user_id = allowed_users.split(",")[0].strip() if allowed_users else ""
  148. if not first_user_id:
  149. print_info(" You can also set this later by typing /set-home in your Telegram chat.")
  150. save_prompted("TELEGRAM_HOME_CHANNEL", "Home channel ID (leave empty to set later)")
  151. elif prompt_yes_no(f"Use your user ID ({first_user_id}) as the home channel?", True):
  152. save_env_value("TELEGRAM_HOME_CHANNEL", first_user_id)
  153. print_success(f"Telegram home channel set to {first_user_id}")
  154. else:
  155. save_prompted("TELEGRAM_HOME_CHANNEL", "Home channel ID (or leave empty to set later with /set-home in Telegram)")
  156. # _setup_slack and _write_slack_manifest_and_instruct moved to the slack plugin:
  157. # plugins/platforms/slack/adapter.py::interactive_setup (registered via setup_fn and dispatched through the
  158. # plugin path). #41112 / #3823.
  159. # _setup_bluebubbles moved to plugins/platforms/bluebubbles/adapter.py::interactive_setup (setup_fn).
  160. def _setup_webhooks():
  161. """Configure webhook integration."""
  162. from hermes_cli.setup import _info, print_header, print_success, print_warning, prompt, save_env_value
  163. print_header("Webhooks")
  164. if declines_reconfigure("Webhooks", "Reconfigure webhooks?", "WEBHOOK_ENABLED"):
  165. return
  166. print()
  167. print_warning("⚠ Webhook and SMS platforms require exposing gateway ports to the")
  168. print_warning(" internet. For security, run the gateway in a sandboxed environment")
  169. print_warning(" (Docker, VM, etc.) to limit blast radius from prompt injection.")
  170. print()
  171. _info(" Full guide: https://hermes-agent.nousresearch.com/docs/user-guide/messaging/webhooks/", None)
  172. _save_port("WEBHOOK_PORT", prompt("Webhook port (default 8644)"), "8644")
  173. save_prompted("WEBHOOK_SECRET", "Global HMAC secret (shared across all routes)", password=True,
  174. success_msg="Webhook secret saved",
  175. skip_msg="No secret set — you must configure per-route secrets in config.yaml")
  176. save_env_value("WEBHOOK_ENABLED", "true")
  177. print()
  178. print_success("Webhooks enabled! Next steps:")
  179. from hermes_constants import display_hermes_home as _dhh
  180. _info(f" 1. Define webhook routes in {_dhh()}/config.yaml",
  181. " 2. Point your service (GitHub, GitLab, etc.) at:",
  182. " http://your-server:8644/webhooks/<route-name>", None,
  183. " Route configuration guide:",
  184. " https://hermes-agent.nousresearch.com/docs/user-guide/messaging/webhooks/#configuring-routes",
  185. None,
  186. # Printed twice upstream; kept verbatim for output parity.
  187. " Open config in your editor: hermes config edit",
  188. " Open config in your editor: hermes config edit")
  189. # (platform label, credential env var, home-channel env vars — any one satisfies)
  190. _HOME_CHANNEL_CHECKS = (
  191. ("Telegram", "TELEGRAM_BOT_TOKEN", ("TELEGRAM_HOME_CHANNEL",)), ("Discord", "DISCORD_BOT_TOKEN", ("DISCORD_HOME_CHANNEL",)),
  192. ("Slack", "SLACK_BOT_TOKEN", ("SLACK_HOME_CHANNEL",)), ("BlueBubbles", "BLUEBUBBLES_SERVER_URL", ("BLUEBUBBLES_HOME_CHANNEL",)),
  193. ("QQBot", "QQ_APP_ID", ("QQBOT_HOME_CHANNEL", "QQ_HOME_CHANNEL")),
  194. )
  195. def _is_progress(status: str) -> bool:
  196. """A platform counts as configured unless its status says otherwise."""
  197. s = status.lower()
  198. return not (s == "not configured" or s.startswith(("partially", "plugin disabled")))
  199. def _warn_missing_home_channels() -> None:
  200. """Platforms with a token but no home channel."""
  201. from hermes_cli.setup import get_env_value, _info, print_warning
  202. missing_home = [
  203. plat for plat, token_var, home_vars in _HOME_CHANNEL_CHECKS
  204. if get_env_value(token_var) and not any(get_env_value(v) for v in home_vars)]
  205. if not missing_home:
  206. return
  207. print()
  208. print_warning(f"No home channel set for: {', '.join(missing_home)}")
  209. _info(" Without a home channel, cron jobs and cross-platform",
  210. " messages can't be delivered to those platforms.",
  211. " Set one later with /set-home in your chat, or:",
  212. *(f" hermes config set {plat.upper()}_HOME_CHANNEL <channel_id>" for plat in missing_home))
  213. def _restart_running_gateway(any_messaging: bool, supports_systemd: bool) -> None:
  214. """Already running: offer a restart only when this pass may have changed platform config —
  215. a restart interrupts any active session, so it stays behind a prompt."""
  216. from hermes_cli.setup import print_error, prompt_yes_no
  217. from hermes_cli.gateway import (
  218. systemd_restart, launchd_restart, UserSystemdUnavailableError, SystemScopeRequiresRootError,
  219. _system_scope_wizard_would_need_root, _print_system_scope_remediation,
  220. )
  221. import platform as _platform
  222. if supports_systemd and _system_scope_wizard_would_need_root():
  223. _print_system_scope_remediation("restart")
  224. return
  225. if not (any_messaging and prompt_yes_no(" Restart the gateway to pick up changes?", True)):
  226. return
  227. try:
  228. if supports_systemd:
  229. systemd_restart()
  230. elif _platform.system() == "Darwin":
  231. launchd_restart()
  232. elif _platform.system() == "Windows":
  233. from hermes_cli import gateway_windows
  234. gateway_windows.restart()
  235. except UserSystemdUnavailableError as e:
  236. print_error(" Restart failed — user systemd not reachable:")
  237. for line in str(e).splitlines():
  238. print(f" {line}")
  239. except SystemScopeRequiresRootError as e:
  240. # Defense in depth: a race (unit file appearing mid-run) can slip past the pre-check;
  241. # this used to sys.exit(1) the whole wizard.
  242. print_error(f" Restart failed: {e}")
  243. _print_system_scope_remediation("restart")
  244. except Exception as e:
  245. print_error(f" Restart failed: {e}")
  246. def setup_gateway(config: dict):
  247. """Configure messaging platform integrations."""
  248. from hermes_cli.setup import _info, print_header, print_info, print_success, prompt_checklist
  249. from hermes_cli.gateway import _all_platforms, _platform_status, _configure_platform
  250. print_header("Messaging Platforms")
  251. _info("Connect to messaging platforms to chat with Hermes from anywhere.",
  252. "Toggle with Space, confirm with Enter.", None)
  253. platforms = _all_platforms()
  254. # Build checklist, pre-selecting already-configured platforms.
  255. statuses = [_platform_status(plat) for plat in platforms]
  256. items = [f"{plat['emoji']} {plat['label']} ({status})" for plat, status in zip(platforms, statuses)]
  257. pre_selected = [i for i, status in enumerate(statuses) if status == "configured"]
  258. selected = prompt_checklist("Select platforms to configure:", items, pre_selected)
  259. if not selected:
  260. print_info("No platforms selected. Run 'hermes setup gateway' later to configure.")
  261. for idx in selected or ():
  262. _configure_platform(platforms[idx])
  263. # Any platform (built-in or plugin) configured in this pass — via ``_platform_status`` so
  264. # plugin platforms like IRC are counted without another hard-coded env-var list.
  265. any_messaging = any(_is_progress(_platform_status(p)) for p in _all_platforms())
  266. if any_messaging:
  267. print()
  268. print_info(_RULE)
  269. print_success("Messaging platforms configured!")
  270. _warn_missing_home_channels()
  271. # Offer optional persistence even with no messaging platforms: cron can run alone.
  272. from hermes_cli.gateway import _is_service_running, supports_systemd_services
  273. from hermes_cli.gateway_setup_service import ensure_gateway_service
  274. supports_systemd = supports_systemd_services()
  275. print()
  276. if _is_service_running():
  277. _restart_running_gateway(any_messaging, supports_systemd)
  278. else:
  279. # Existing services can start; a new service requires explicit consent.
  280. ensure_gateway_service(context="setup", interactive=True, config=config)
  281. print_info(_RULE)