pairing.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. """CLI commands for the DM pairing system."""
  2. def pairing_command(args):
  3. """Handle hermes pairing subcommands."""
  4. from gateway.pairing import PairingStore
  5. store = PairingStore()
  6. handlers = {
  7. "list": lambda: _cmd_list(store),
  8. "approve": lambda: _cmd_approve(store, args.platform, args.code),
  9. "revoke": lambda: _cmd_revoke(store, args.platform, args.user_id),
  10. "clear-pending": lambda: _cmd_clear_pending(store),
  11. }
  12. handler = handlers.get(getattr(args, "pairing_action", None))
  13. if handler is None:
  14. print("Usage: hermes pairing {list|approve|revoke|clear-pending}")
  15. print("Run 'hermes pairing --help' for details.")
  16. else:
  17. handler()
  18. def _cmd_list(store):
  19. """List all pending and approved users."""
  20. pending = store.list_pending()
  21. approved = store.list_approved()
  22. if not pending and not approved:
  23. print("No pairing data found. No one has tried to pair yet~")
  24. return
  25. if pending:
  26. print(f"\n Pending Pairing Requests ({len(pending)}):")
  27. print(f" {'Platform':<12} {'Request ID':<18} {'User ID':<20} {'Name':<20} {'Age'}")
  28. print(f" {'--------':<12} {'----------':<18} {'-------':<20} {'----':<20} {'---'}")
  29. for p in pending:
  30. print(
  31. f" {p['platform']:<12} {(p.get('request_id') or '-'):<18} {p['user_id']:<20} "
  32. f"{(p.get('user_name') or ''):<20} {p['age_minutes']}m ago"
  33. )
  34. print("\n Approve with: hermes pairing approve <platform> <request-id>")
  35. print(" The code the bot DM'd the user also works if they relay it.")
  36. else:
  37. print("\n No pending pairing requests.")
  38. if approved:
  39. print(f"\n Approved Users ({len(approved)}):")
  40. print(f" {'Platform':<12} {'User ID':<20} {'Name':<20}")
  41. print(f" {'--------':<12} {'-------':<20} {'----':<20}")
  42. for a in approved:
  43. print(f" {a['platform']:<12} {a['user_id']:<20} {(a.get('user_name') or ''):<20}")
  44. else:
  45. print("\n No approved users.")
  46. print()
  47. def _cmd_approve(store, platform: str, code: str):
  48. """Approve a pairing request id (from ``pairing list``) or a DM'd code."""
  49. platform = platform.lower().strip()
  50. code = code.strip()
  51. if store.looks_like_request_id(code):
  52. result = store.approve_request(platform, code)
  53. else:
  54. result = store.approve_code(platform, code.upper())
  55. if result:
  56. uid, name = result["user_id"], result.get("user_name") or ""
  57. display = f"{name} ({uid})" if name else uid
  58. print(f"\n Approved! User {display} on {platform} can now use the bot~")
  59. print(" They'll be recognized automatically on their next message.\n")
  60. elif store._is_locked_out(platform):
  61. # approve_code returns None for both invalid codes and lockout — say which.
  62. # Tell the operator it's lockout so they don't chase a "wrong code" rabbit hole (#10195).
  63. import time as _time
  64. lockout_until = store._load_json(store._rate_limit_path()).get(f"_lockout:{platform}", 0)
  65. mins = max(0, int(lockout_until - _time.time())) // 60
  66. print(f"\n Platform '{platform}' is locked out after too many failed approval attempts.")
  67. print(f" Lockout clears in ~{mins} minute(s).")
  68. print(f" To reset sooner, delete the '_lockout:{platform}' entry from ~/.hermes/platforms/pairing/_rate_limits.json\n")
  69. else:
  70. print(f"\n Pairing request or code '{code}' not found or expired for platform '{platform}'.")
  71. print(" Run 'hermes pairing list' to see pending requests.\n")
  72. def _cmd_revoke(store, platform: str, user_id: str):
  73. """Revoke a user's access."""
  74. platform = platform.lower().strip()
  75. if store.revoke(platform, user_id):
  76. print(f"\n Revoked access for user {user_id} on {platform}.\n")
  77. else:
  78. print(f"\n User {user_id} not found in approved list for {platform}.\n")
  79. def _cmd_clear_pending(store):
  80. """Clear all pending pairing codes."""
  81. count = store.clear_pending()
  82. if count:
  83. print(f"\n Cleared {count} pending pairing request(s).\n")
  84. else:
  85. print("\n No pending requests to clear.\n")