run_inbound_unauthorized.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. """Copy and owner-side signalling for unauthorized inbound senders.
  2. Two audiences, two rules:
  3. * The **stranger** gets either a pairing code (behaviour ``pair``) or nothing at all (behaviour
  4. ``ignore``: an allowlist is configured, so any reply would leak that the bot exists).
  5. * The **owner** is the one who can fix a mis-typed allowlist, so an ignored DM is logged at
  6. WARNING with the sender's ID and the allowlist / pairing-mode fix, and surfaced once per
  7. (platform, user) per gateway process in the platform's home channel when one is configured.
  8. No pairing request is minted for an ignored sender: strangers must not create server state
  9. when the owner has restricted access.
  10. """
  11. from __future__ import annotations
  12. import logging
  13. from collections import OrderedDict
  14. from agent.i18n import t
  15. from gateway.pairing import CODE_TTL_SECONDS, _allowlist_env_for_platform
  16. # Display names come from the stranger. Bound them and keep the mention/markdown surface small in
  17. # the owner's channel: a name is never a reason to render a link, mention or new section.
  18. _MAX_SENDER_NAME_CHARS = 64
  19. # Distinct (platform, user_id) senders remembered per process; a bot rotating IDs evicts the oldest
  20. # instead of growing the set without limit.
  21. _MAX_SEEN_SENDERS = 2048
  22. logger = logging.getLogger("gateway.run")
  23. def pairing_profile_arg(pairing_store) -> str:
  24. """``-p <profile> `` when the store belongs to a non-default profile, else ``""``."""
  25. store_profile = getattr(pairing_store, "profile", None)
  26. if isinstance(store_profile, str) and store_profile and store_profile != "default":
  27. return f"-p {store_profile} "
  28. return ""
  29. def pairing_code_reply(platform_name: str, code: str, profile_arg: str = "") -> str:
  30. """The DM a first-time sender receives: what happened, how long the code lives, what to do
  31. whether they are the owner or a guest, and that they must message again after approval."""
  32. hours = max(1, CODE_TTL_SECONDS // 3600)
  33. validity = t("gateway.pairing.validity_hour" if hours == 1 else "gateway.pairing.validity_hours", hours=hours)
  34. approve_cmd = f"hermes {profile_arg}pairing approve {platform_name} {code}"
  35. return t("gateway.pairing.code_reply", code=code, validity=validity, approve_cmd=approve_cmd)
  36. def pairing_rate_limited_reply() -> str:
  37. return t("gateway.pairing.rate_limited")
  38. def unauthorized_owner_hint(
  39. platform_name: str, user_id: str, user_name: str = "", *, hermes_home: str,
  40. ) -> str:
  41. """One-line hint for the owner (log + home channel): who was dropped and how to let them in.
  42. No pairing request is minted for an ignored sender (a configured allowlist means the owner chose
  43. to restrict access), so the ways in are the allowlist itself or switching the platform to
  44. pairing mode."""
  45. from gateway.session import neutralize_untrusted_inline_text
  46. safe_name = neutralize_untrusted_inline_text(user_name or "", max_chars=_MAX_SENDER_NAME_CHARS)
  47. # Mention and link sigils are stripped so a hostile display name cannot ping the channel or
  48. # smuggle a link; the ID next to it is the value the owner actually acts on.
  49. safe_name = "".join(ch for ch in safe_name if ch not in "@<>[]()`*_~#").strip()
  50. who = f"{safe_name} ({user_id})" if safe_name else str(user_id)
  51. env_var = _allowlist_env_for_platform(platform_name)
  52. allowlist = (
  53. t("gateway.unauthorized.owner_hint_env", env_var=env_var, home=hermes_home)
  54. if env_var else t("gateway.unauthorized.owner_hint_generic")
  55. )
  56. return t("gateway.unauthorized.owner_notice", platform=platform_name, who=who, allowlist=allowlist, home=hermes_home)
  57. class UnauthorizedOwnerNotifier:
  58. """Tells the owner's home channel about the first drop of each unrecognized DM sender.
  59. One notice per (platform, user_id) per gateway process: the first drop is the useful signal (an
  60. owner who typo'd their own ID); repeats would only let a stranger spam the home channel.
  61. """
  62. def __init__(self, max_seen: int = _MAX_SEEN_SENDERS) -> None:
  63. self._seen: OrderedDict[tuple[str, str], None] = OrderedDict()
  64. self._max_seen = max(1, int(max_seen))
  65. def first_time(self, platform_name: str, user_id: str) -> bool:
  66. key = (platform_name, str(user_id))
  67. if key in self._seen:
  68. self._seen.move_to_end(key)
  69. return False
  70. self._seen[key] = None
  71. while len(self._seen) > self._max_seen:
  72. self._seen.popitem(last=False)
  73. return True
  74. async def notify(self, runner, source, hint: str) -> None:
  75. """Best-effort post to the source platform's home channel; silent when none is configured."""
  76. for platform, _cfg, home, transport in runner._home_channel_transports():
  77. if platform != source.platform:
  78. continue
  79. if str(home.chat_id) == str(source.chat_id):
  80. # The stranger's DM *is* the home channel (misconfiguration); posting there would
  81. # answer the unauthorized user, which the ignore behaviour exists to prevent.
  82. return
  83. # Automatic operator diagnostic on the home channel; same boundary as the state.db warning.
  84. from gateway.warning_notifications import present_notification
  85. await present_notification(
  86. lambda: runner._send_home_channel_message(
  87. platform, home, transport, f"⚠️ {hint}", "unauthorized-sender notice failed for %s:%s: %s",
  88. ),
  89. platform=platform,
  90. )
  91. return