setup_wizard.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. """Interactive setup wizard for the WhatsApp Cloud API adapter: the 6 Meta credentials + recipient
  2. allowlist, an auto-generated verify token, and exact follow-up instructions for what can't happen
  3. inside the wizard process (cloudflared, gateway, Meta's webhook dashboard, recipient list).
  4. Intentionally does NOT smoke-test the webhook: the gateway and the tunnel both run in separate
  5. processes the user starts AFTER this wizard exits, so any in-wizard probe would fail."""
  6. from __future__ import annotations
  7. from hermes_cli.cli_output import line_input
  8. import re
  9. import secrets
  10. import sys
  11. from typing import Optional
  12. # --- Field-shape validators: each returns (ok, reason_if_not_ok) so obviously-malformed input is
  13. # rejected before saving, sparing a round trip with Meta's 401 / 400 errors.
  14. def _rules_validator(label: str, rules):
  15. """Validator from ``(fails(stripped), reason)`` rules, checked in order after the required check.
  16. ``reason`` may be a str or a ``fn(stripped) -> str``."""
  17. def validate(value: str) -> tuple[bool, Optional[str]]:
  18. if not value:
  19. return False, f"{label} is required"
  20. s = value.strip()
  21. for fails, reason in rules:
  22. if fails(s):
  23. return False, reason(s) if callable(reason) else reason
  24. return True, None
  25. return validate
  26. def _numeric_id_validator(label: str, lo: int, hi: int, expected: str):
  27. """Validator for a numeric Meta ID whose digit count must fall in [lo, hi]."""
  28. return _rules_validator(label, (
  29. (lambda s: not s.isdigit(), f"{label} must be numeric"),
  30. (lambda s: len(s) < lo or len(s) > hi, f"{label} looks wrong (expected {expected})")))
  31. # Phone Number ID is a 15-17 digit numeric ID assigned by Meta — NOT a phone number. The #1 setup
  32. # mistake is pasting the actual phone number (10-11 digits), which Graph rejects with "Object with
  33. # ID does not exist."
  34. _validate_phone_number_id = _rules_validator("Phone Number ID", (
  35. (lambda s: not s.isdigit(), "Phone Number ID must be numeric (no '+', spaces, or dashes)"),
  36. (lambda s: 10 <= len(s) <= 12, # phone-number-sized: almost certainly the number itself
  37. "That looks like a phone number — but this field needs the "
  38. "Phone Number ID (Meta's internal ID, 15-17 digits, e.g. "
  39. "'7794189252778687'). Look just BELOW the 'From' dropdown in "
  40. "API Setup → it's labelled 'Phone number ID'."),
  41. (lambda s: len(s) < 13, "Phone Number ID looks too short (expected 13-18 digits)"),
  42. (lambda s: len(s) > 20, "Phone Number ID looks too long (expected 13-18 digits)")))
  43. # WABA ID: similar length range as Phone Number ID. App ID: typically 15-16 digits.
  44. _validate_waba_id = _numeric_id_validator("WABA ID", 10, 25, "10-25 digits")
  45. _validate_app_id = _numeric_id_validator("App ID", 13, 20, "15-16 digits")
  46. # App Secret is a 32-character lowercase hex string.
  47. _validate_app_secret = _rules_validator("App Secret", (
  48. (lambda s: not re.fullmatch(r"[0-9a-f]+", s.lower()),
  49. "App Secret should be a hex string (only digits 0-9 and "
  50. "letters a-f). Make sure you copied the 'App secret' from "
  51. "Settings → Basic, not some other token."),
  52. (lambda s: len(s) != 32, lambda s: f"App Secret should be exactly 32 hex characters (got {len(s)})")))
  53. # Common paste mistakes for the access-token field: (prefixes, what it actually is).
  54. _FOREIGN_TOKEN_PREFIXES = (
  55. (("sk-",), "That's an OpenAI key (starts with 'sk-'), not a Meta "
  56. "WhatsApp access token. Meta tokens start with 'EAA'."),
  57. (("xoxb-", "xoxp-"), "That's a Slack token, not a Meta WhatsApp access token. "
  58. "Meta tokens start with 'EAA'."),
  59. (("ghp_", "gho_"), "That's a GitHub token, not a Meta WhatsApp access "
  60. "token. Meta tokens start with 'EAA'."))
  61. def _not_meta_token_reason(s: str) -> str:
  62. for prefixes, reason in _FOREIGN_TOKEN_PREFIXES:
  63. if s.startswith(prefixes):
  64. return reason
  65. return ("Meta WhatsApp access tokens start with 'EAA'. Check that "
  66. "you're copying from the right place (API Setup → 'Generate "
  67. "access token', or Business Settings → System Users → "
  68. "'Generate token' for a permanent one).")
  69. # Meta access tokens (temp and System User alike) start with ``EAA``, 100-300+ chars.
  70. _validate_access_token = _rules_validator("Access token", (
  71. (lambda s: not s.startswith("EAA"), _not_meta_token_reason),
  72. (lambda s: len(s) < 100, lambda s: f"Access token looks too short ({len(s)} chars, expected 100+)")))
  73. # --- Prompt helpers
  74. def _prompt(message: str, default: Optional[str] = None, secret: bool = False) -> str:
  75. """Read one line; "" on EOF / Ctrl+C / empty. ``default`` is shown but NOT auto-applied so a
  76. real value stays distinguishable from a masked preview; ``secret`` reads via ``getpass``."""
  77. try:
  78. suffix = f" [{default}]" if default else ""
  79. if secret and sys.stdin.isatty():
  80. import getpass
  81. return getpass.getpass(f"{message}{suffix} (input hidden): ").strip()
  82. return line_input(f"{message}{suffix}: ").strip()
  83. except (EOFError, KeyboardInterrupt):
  84. print()
  85. return ""
  86. def _prompt_validated(
  87. message: str, validator, *, current: Optional[str] = None, help_text: Optional[str] = None,
  88. secret: bool = False) -> Optional[str]:
  89. """Repeat the prompt until a valid value or the user gives up (None: empty answer, Ctrl+C).
  90. ``current`` is shown as the default on wizard re-runs."""
  91. if help_text:
  92. for line in help_text.strip().splitlines():
  93. print(f" {line}")
  94. attempts = 0
  95. while True:
  96. attempts += 1
  97. value = _prompt(f" → {message}", default=current, secret=secret)
  98. if not value:
  99. return None
  100. ok, reason = validator(value)
  101. if ok:
  102. return value.strip()
  103. print(f" ✗ {reason}")
  104. if attempts >= 3:
  105. try:
  106. if not input(" Try again, or press Enter to skip: ").strip():
  107. return None
  108. except (EOFError, KeyboardInterrupt):
  109. return None
  110. attempts = 0
  111. # --- Wizard
  112. def _header(title: str) -> None:
  113. _lines("─" * 50, title, "─" * 50)
  114. def _lines(*lines: str) -> None:
  115. """print() each line; ``""`` yields a blank line."""
  116. for line in lines:
  117. print(line)
  118. def _persist(env_var: str, value: Optional[str], current: Optional[str],
  119. saved: str = " ✓ Saved: {v}", kept: str = " ✓ Keeping existing: {v}") -> Optional[str]:
  120. """Save ``value`` to .env, else keep ``current``; prints the matching line. Returns the effective
  121. value (None when neither exists). ``{v}`` in ``saved``/``kept`` is the value."""
  122. from hermes_cli.config import save_env_value
  123. if value:
  124. save_env_value(env_var, value)
  125. print(saved.format(v=value))
  126. return value
  127. if current:
  128. print(kept.format(v=current))
  129. return current or None
  130. # Credential steps 1-3: (step title, env var, prompt label, validator, secret, preview chars of
  131. # the existing value shown as default (0 = full), "saved" line, "kept" line, lines printed when
  132. # nothing is configured, abort-when-missing, help text).
  133. _CREDENTIAL_STEPS = (
  134. ("STEP 1 — Phone Number ID", "WHATSAPP_CLOUD_PHONE_NUMBER_ID", "Phone Number ID",
  135. _validate_phone_number_id, False, 0, " ✓ Saved: {v}", " ✓ Keeping existing: {v}",
  136. ("\n✗ Phone Number ID is required. Aborting.",), True,
  137. "Found in: App Dashboard → WhatsApp → API Setup, in the\n"
  138. "'Send and receive messages' section.\n"
  139. "Look BELOW the 'From' dropdown — there's a 'Phone number ID'\n"
  140. "line with the value (15-17 digits, e.g. '7794189252778687').\n"
  141. "It is NOT the phone number itself (+1 555-...). That's the\n"
  142. "single most common setup mistake."),
  143. ("STEP 2 — Access Token", "WHATSAPP_CLOUD_ACCESS_TOKEN", "Access Token",
  144. _validate_access_token, True, 15, " ✓ Saved (token hidden)", " ✓ Keeping existing token",
  145. ("\n✗ Access Token is required. Aborting.",), True,
  146. "Two options for getting one:\n\n"
  147. " (a) TEMP — App Dashboard → WhatsApp → API Setup →\n"
  148. " 'Generate access token' button. Lasts 24 hours.\n"
  149. " Fine for testing today; you'll have to regenerate\n"
  150. " tomorrow.\n\n"
  151. " (b) PERMANENT (production) — System User token. One-time\n"
  152. " setup, never expires:\n"
  153. " • business.facebook.com → Settings → System users →\n"
  154. " Add → Admin role\n"
  155. " • Assign Assets → your app (Manage app), your\n"
  156. " WhatsApp account (Manage WABAs)\n"
  157. " • Generate token → expiration: Never → permissions:\n"
  158. " business_management, whatsapp_business_messaging,\n"
  159. " whatsapp_business_management\n\n"
  160. "Tokens start with 'EAA'."),
  161. ("STEP 3 — App Secret (required for webhook signature verification)", "WHATSAPP_CLOUD_APP_SECRET",
  162. "App Secret", _validate_app_secret, True, 8, " ✓ Saved (secret hidden)",
  163. " ✓ Keeping existing App Secret",
  164. ("\n⚠ Skipping App Secret — inbound webhooks will be refused",
  165. " until you set WHATSAPP_CLOUD_APP_SECRET manually."), False,
  166. "Found in: App Dashboard → Settings → Basic →\n"
  167. "'App secret' field (click 'Show', enter your Facebook password).\n\n"
  168. "If 'Show' doesn't appear, you may need Admin role on the app.\n"
  169. "It's a 32-character lowercase hex string.\n\n"
  170. "Without the App Secret, inbound webhook POSTs are refused\n"
  171. "with HTTP 503 (we can't verify they actually came from Meta)."))
  172. # Optional step-4 IDs: (prompt label, env var, validator, help text).
  173. _OPTIONAL_ID_STEPS = (
  174. ("App ID (optional, press Enter to skip)", "WHATSAPP_CLOUD_APP_ID", _validate_app_id,
  175. "Found in: App Dashboard → Settings → Basic → 'App ID' at the\n"
  176. "top of the page. Numeric, ~15-16 digits.\n"
  177. "Not required for messaging — useful only for analytics later."),
  178. ("WABA ID (optional, press Enter to skip)", "WHATSAPP_CLOUD_WABA_ID", _validate_waba_id,
  179. "WhatsApp Business Account ID. Found in: App Dashboard →\n"
  180. "WhatsApp → API Setup, near the top — 'WhatsApp Business\n"
  181. "Account ID'. Numeric, ~15+ digits.\n"
  182. "When set, inbound webhooks must match this business account."))
  183. def _credential_step(step) -> bool:
  184. """Run one _CREDENTIAL_STEPS entry. Returns True when the wizard must abort."""
  185. from hermes_cli.config import get_env_value
  186. title, env_var, label, validator, secret, preview, saved, kept, missing, required, help_text = step
  187. _header(title)
  188. current = get_env_value(env_var) or None
  189. shown = (current[:preview] + "...") if (preview and current) else current
  190. value = _prompt_validated(label, validator, current=shown, secret=secret, help_text=help_text)
  191. if _persist(env_var, value, current, saved, kept) is None:
  192. _lines(*missing)
  193. if required:
  194. return True
  195. print()
  196. return False
  197. def _step_optional_ids() -> dict:
  198. """STEP 4: optional App ID / WABA ID. Returns {env var: effective value or None}."""
  199. from hermes_cli.config import get_env_value
  200. _header("STEP 4 — App ID & WABA ID (optional; WABA ID binds inbound webhooks)")
  201. ids = {}
  202. for label, env_var, validator, help_text in _OPTIONAL_ID_STEPS:
  203. current = get_env_value(env_var) or None
  204. value = _prompt_validated(label, validator, current=current, help_text=help_text)
  205. ids[env_var] = _persist(env_var, value, current)
  206. print()
  207. return ids
  208. def _step_verify_token() -> str:
  209. """STEP 5: generate (or keep) the webhook verify token; returns the effective token."""
  210. from hermes_cli.config import get_env_value, save_env_value
  211. _header("STEP 5 — Verify Token (auto-generated)")
  212. verify_token = get_env_value("WHATSAPP_CLOUD_VERIFY_TOKEN") or None
  213. regen = "y"
  214. if verify_token:
  215. print(f" An existing verify token is already set ({verify_token[:8]}...).")
  216. try:
  217. regen = input(" Generate a new one? [y/N]: ").strip().lower()
  218. except (EOFError, KeyboardInterrupt):
  219. regen = "n"
  220. if regen in {"y", "yes"}:
  221. label = "New verify token" if verify_token else "Generated"
  222. verify_token = secrets.token_urlsafe(32)
  223. save_env_value("WHATSAPP_CLOUD_VERIFY_TOKEN", verify_token)
  224. print(f" ✓ {label}: {verify_token}")
  225. else:
  226. print(" ✓ Keeping existing verify token")
  227. _lines("", " → COPY THIS TOKEN NOW. You'll paste it into Meta's webhook",
  228. " configuration dialog (next step).", "")
  229. return verify_token
  230. def _step_allowlist() -> None:
  231. """STEP 6: recipient allowlist (spaces/dashes/'+' stripped from each entry)."""
  232. from hermes_cli.config import get_env_value, save_env_value
  233. _header("STEP 6 — Recipient Allowlist")
  234. _lines(
  235. "", " Who is allowed to message the bot? (Comma-separated phone",
  236. " numbers with country code, no '+' / spaces / dashes. Use '*'",
  237. " to allow anyone — only safe if you've also configured Meta's",
  238. " recipient whitelist for app-development mode.)", "")
  239. allow_default = get_env_value("WHATSAPP_CLOUD_ALLOWED_USERS") or None
  240. try:
  241. allowed = line_input(
  242. f" → Allowed users{' [' + allow_default + ']' if allow_default else ''}: "
  243. ).strip() or (allow_default or "")
  244. except (EOFError, KeyboardInterrupt):
  245. allowed = ""
  246. if allowed:
  247. allowed = ",".join(re.sub(r"[\s\-+]", "", part) for part in allowed.split(",") if part.strip())
  248. save_env_value("WHATSAPP_CLOUD_ALLOWED_USERS", allowed)
  249. print(f" ✓ Saved: {allowed}")
  250. else:
  251. _lines(" ⚠ No allowlist — every inbound message will be denied.",
  252. " Re-run this wizard or set WHATSAPP_CLOUD_ALLOWED_USERS manually.")
  253. print()
  254. def run_whatsapp_cloud_setup() -> int:
  255. """Interactive wizard for the WhatsApp Cloud API adapter. Returns 0 on success, 1 on abort."""
  256. _lines(
  257. "", "☤ WhatsApp Business Cloud API Setup", "=" * 50, "",
  258. "This wizard configures Hermes to talk to WhatsApp via Meta's",
  259. "official Cloud API. It's the production-grade path:", "",
  260. " • No QR codes, no Node.js bridge subprocess",
  261. " • Stable connection — no account-ban risk",
  262. " • Business account required (not personal WhatsApp)",
  263. " • Public webhook URL required (Cloudflare Tunnel, ngrok,",
  264. " or your own reverse proxy with TLS)", "",
  265. "If you don't have a Meta app set up yet, follow these steps",
  266. "FIRST, then come back and re-run this wizard:", "",
  267. " 1. https://developers.facebook.com/apps → Create App",
  268. " → 'Connect with customers through WhatsApp'",
  269. " 2. App Dashboard → WhatsApp → API Setup",
  270. " 3. Click 'Generate access token' (temp 24h token is fine to",
  271. " start; switch to a System User permanent token later)", "")
  272. try:
  273. input("Press Enter to continue, or Ctrl+C to abort... ")
  274. except (EOFError, KeyboardInterrupt):
  275. print("\nSetup cancelled.")
  276. return 1
  277. print()
  278. if any(_credential_step(step) for step in _CREDENTIAL_STEPS):
  279. return 1
  280. effective_waba = _step_optional_ids()["WHATSAPP_CLOUD_WABA_ID"]
  281. verify_token = _step_verify_token()
  282. _step_allowlist()
  283. _header("SETUP COMPLETE — Next steps")
  284. _lines(
  285. "", " Hermes needs a public HTTPS URL to receive WhatsApp messages.",
  286. " The recommended path is Cloudflare Tunnel (free, no port",
  287. " forwarding, no DNS setup).", "",
  288. " 1. Install cloudflared (one-time, if you don't have it):",
  289. " Windows: winget install Cloudflare.cloudflared",
  290. " macOS: brew install cloudflared",
  291. " Linux: https://github.com/cloudflare/cloudflared/releases", "",
  292. " Alternatives: ngrok, or your own domain + reverse proxy",
  293. " with TLS.", "",
  294. " 2. Start the tunnel in a separate terminal:",
  295. " cloudflared tunnel --url http://localhost:8090",
  296. " Note the printed https://<random>.trycloudflare.com URL.", "",
  297. " 3. Start the Hermes gateway in another terminal:",
  298. " hermes gateway", "",
  299. " 4. Verify your local config is reachable. From a third",
  300. " terminal, with the tunnel URL substituted:", "",
  301. " curl 'https://YOUR-TUNNEL.trycloudflare.com/whatsapp/webhook?\\",
  302. f" hub.mode=subscribe&hub.verify_token={verify_token}&\\",
  303. " hub.challenge=hello'", "",
  304. " Expected: HTTP 200 with body 'hello'.",
  305. " Also try: curl https://YOUR-TUNNEL.trycloudflare.com/health",
  306. " (should return JSON with verify_token_configured: true).", "",
  307. " 5. Configure Meta to point at your tunnel:",
  308. " App Dashboard → WhatsApp → Configuration → Edit webhook",
  309. " Callback URL: <tunnel-url>/whatsapp/webhook",
  310. f" Verify Token: {verify_token}",
  311. " → Click 'Verify and save'",
  312. " → Then 'Manage' webhook fields → subscribe to 'messages'", "",
  313. " 6. Add your phone to Meta's recipient list:",
  314. " App Dashboard → WhatsApp → API Setup → 'To' →",
  315. " 'Manage phone number list'", "",
  316. " 7. DM the bot's test number from your phone.", "")
  317. _header("Optional: polish your bot's WhatsApp profile")
  318. _lines(
  319. "", " WhatsApp shows a display name and profile picture for your bot",
  320. " in every chat header and contact list. These are set in Meta's",
  321. " Business Manager, not via this wizard — but here's where to do",
  322. " it once you're up and running:", "",
  323. " • Display name + profile picture:",
  324. " https://business.facebook.com/wa/manage/phone-numbers/"
  325. + (f"?waba_id={effective_waba}" if effective_waba else ""))
  326. if not effective_waba:
  327. print(" (select your WhatsApp Business Account on that page)")
  328. _lines(
  329. " Display-name changes go through a ~24-48h Meta review.", "",
  330. " • About, description, website, hours, business category:",
  331. " Same page → click your phone number → 'Edit profile'.", "",
  332. " • Verified badge (the green check):",
  333. " Requires Meta's business verification process —",
  334. " Business Manager → Security Center → Start Verification.", "",
  335. " Docs: https://hermes-agent.nousresearch.com/docs/user-guide/",
  336. " messaging/whatsapp-cloud", "")
  337. return 0