profile_routing.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. """Profile-based routing: route senders/locations to different profiles.
  2. Matching is conjunctive; the highest additive specificity wins (``gateway.profile_routes``
  3. in config.yaml): user_id 16, thread_id 8, chat_id 4, guild_id 2, else the default profile.
  4. For Discord threads/forum posts ``parent_chat_id`` carries the direct parent, so a
  5. channel route also matches any thread/post under it.
  6. A route applies only to messages received by the bot of its ``bot_profile`` (default: the
  7. default profile's shared bot). Telegram DM ``chat_id == user_id`` for EVERY bot, so without
  8. this a ``chat_id`` route meant for the shared bot would re-home the same user's DM with a
  9. dedicated secondary bot into another profile (#104933).
  10. """
  11. from __future__ import annotations
  12. import logging
  13. from dataclasses import dataclass
  14. from typing import Any, Dict, List, Optional
  15. logger = logging.getLogger(__name__)
  16. # Baileys and Cloud share phone/JID/LID identity rules; other platforms compare exactly.
  17. _WHATSAPP_IDENTITY_PLATFORMS = {"whatsapp", "whatsapp_cloud"}
  18. _WHATSAPP_NON_USER_SUFFIXES = ("@g.us", "@broadcast", "@newsletter")
  19. def _is_whatsapp_non_user_chat(chat_id: Optional[str]) -> bool:
  20. """True for group / broadcast / newsletter JIDs — not a sender identity."""
  21. return bool(chat_id) and str(chat_id).strip().lower().endswith(_WHATSAPP_NON_USER_SUFFIXES)
  22. def _whatsapp_user_chat_ids_match(platform: str, left: Optional[str], right: Optional[str]) -> bool:
  23. """True when two WhatsApp *user* chat_ids refer to the same person.
  24. Uses ``expand_whatsapp_aliases`` (same helper as session keys and adapter allowlists) so a bare
  25. number, JID and LID collapse to one identity. Group/broadcast JIDs are chats, not senders;
  26. non-WhatsApp platforms → False.
  27. """
  28. if (
  29. (platform or "").strip().lower() not in _WHATSAPP_IDENTITY_PLATFORMS
  30. or not left or not right
  31. or _is_whatsapp_non_user_chat(left) or _is_whatsapp_non_user_chat(right)
  32. ):
  33. return False
  34. from gateway.whatsapp_identity import expand_whatsapp_aliases
  35. left_aliases = expand_whatsapp_aliases(str(left))
  36. return bool(left_aliases and left_aliases & expand_whatsapp_aliases(str(right)))
  37. class ProfileRouteRejected(RuntimeError):
  38. """An explicit route matched a profile this gateway does not serve (``profile``, when known)."""
  39. @property
  40. def profile(self):
  41. return self.args[1] if len(self.args) > 1 else None
  42. def __str__(self):
  43. return str(self.args[0]) if self.args else ''
  44. @dataclass(frozen=True)
  45. class ProfileRoute:
  46. """A single routing rule that maps a platform scope to a profile."""
  47. name: str
  48. platform: str
  49. profile: str
  50. guild_id: Optional[str] = None
  51. chat_id: Optional[str] = None
  52. thread_id: Optional[str] = None
  53. enabled: bool = True
  54. bot_profile: Optional[str] = None # None = the default profile's bot
  55. user_id: Optional[str] = None
  56. @property
  57. def specificity(self) -> int:
  58. """Higher value = more specific match."""
  59. return 2 * bool(self.guild_id) + 4 * bool(self.chat_id) + 8 * bool(self.thread_id) + 16 * bool(self.user_id)
  60. def matches(
  61. self, platform: str, guild_id: Optional[str] = None, chat_id: Optional[str] = None,
  62. thread_id: Optional[str] = None, parent_chat_id: Optional[str] = None,
  63. adapter_profile: Optional[str] = None, user_id: Optional[str] = None,
  64. ) -> bool:
  65. """True if every discriminator the route declares holds (AND).
  66. ``chat_id`` matches the channel directly or as the parent of a thread/forum post; WhatsApp
  67. ``chat_id`` also matches across number/JID/LID after the exact check (groups/broadcasts stay exact-only).
  68. ``adapter_profile`` is the profile owning the receiving bot (``None`` = default); it must equal
  69. the route's ``bot_profile``.
  70. """
  71. if not self.enabled or self.platform != platform:
  72. return False
  73. if _bot_profile_key(self.bot_profile) != _bot_profile_key(adapter_profile):
  74. return False
  75. if self.user_id is not None and (not self.user_id.strip() or self.user_id != user_id):
  76. return False
  77. if self.thread_id and self.thread_id != thread_id:
  78. return False
  79. if (
  80. self.chat_id
  81. and self.chat_id not in (chat_id, parent_chat_id)
  82. and not _whatsapp_user_chat_ids_match(platform, self.chat_id, chat_id)
  83. and not _whatsapp_user_chat_ids_match(platform, self.chat_id, parent_chat_id)
  84. ):
  85. return False
  86. return not (self.guild_id and self.guild_id != guild_id)
  87. def _bot_profile_key(name: Optional[str]) -> Optional[str]:
  88. """``None`` for the default profile, else the profile name (mirrors ``set_owner_profile``)."""
  89. name = (name or "").strip()
  90. return None if not name or name == "default" else name
  91. def _coerce_route_id(value: Any) -> Optional[str]:
  92. """Normalize a route discriminator to str for strict equality matching.
  93. YAML loads unquoted numeric IDs as ``int`` while ``SessionSource`` fields are ``str``. Only
  94. ``int`` (not ``bool``) is coerced; floats stringify to something (``"123.0"``) that can never
  95. match, so they get a load-time warning instead.
  96. ``bool`` is an ``int`` subclass but never a valid id; floats and other types stringify to something
  97. (``"123.0"``) that can never equal an inbound id — recreating the silent no-match this exists to fix —
  98. so they are passed through with a load-time warning instead of being silently "fixed" (#86470).
  99. """
  100. if value is None or isinstance(value, str):
  101. return value
  102. if isinstance(value, int) and not isinstance(value, bool):
  103. return str(value)
  104. logger.warning(
  105. "Profile route discriminator %r (type %s) can never match an inbound "
  106. "id — quote it in config.yaml (e.g. chat_id: \"%s\").",
  107. value, type(value).__name__, value,
  108. )
  109. return str(value)
  110. def parse_profile_routes(raw: Optional[list[dict[str, Any]]]) -> list[ProfileRoute]:
  111. """Parse profile_routes from config.yaml, sorted most-specific-first."""
  112. if not raw:
  113. return []
  114. routes: list[ProfileRoute] = []
  115. for entry in raw:
  116. if not isinstance(entry, dict):
  117. continue
  118. name = entry.get("name", "")
  119. platform = entry.get("platform", "")
  120. profile = entry.get("profile", "")
  121. if not platform or not profile:
  122. logger.warning("Skipping profile route %s: missing platform or profile", name)
  123. continue
  124. # Validate profile name to prevent path traversal (lazy import: cycle).
  125. try:
  126. from hermes_cli.profiles import normalize_profile_name, validate_profile_name
  127. profile = normalize_profile_name(profile)
  128. validate_profile_name(profile)
  129. except (ValueError, ImportError):
  130. logger.warning("Skipping profile route %s: invalid profile name %r", name, profile)
  131. continue
  132. has_user_id, user_id = "user_id" in entry, entry.get("user_id")
  133. if has_user_id and (user_id is None or isinstance(user_id, str) and not user_id.strip()):
  134. logger.warning("Skipping profile route %s: user_id cannot be null or empty", name)
  135. continue
  136. routes.append(ProfileRoute(
  137. name=name, platform=platform, profile=profile,
  138. guild_id=_coerce_route_id(entry.get("guild_id")),
  139. chat_id=_coerce_route_id(entry.get("chat_id")),
  140. thread_id=_coerce_route_id(entry.get("thread_id")),
  141. user_id=_coerce_route_id(user_id),
  142. enabled=entry.get("enabled", True),
  143. bot_profile=_bot_profile_key(entry.get("bot_profile")),
  144. ))
  145. routes.sort(key=lambda r: r.specificity, reverse=True)
  146. logger.debug("Loaded %d profile routes (most-specific-first)", len(routes))
  147. return routes
  148. def match_profile_route(
  149. routes: list[ProfileRoute], platform: str, guild_id: Optional[str] = None, chat_id: Optional[str] = None,
  150. thread_id: Optional[str] = None, parent_chat_id: Optional[str] = None,
  151. adapter_profile: Optional[str] = None, user_id: Optional[str] = None,
  152. ) -> Optional[ProfileRoute]:
  153. """Return the first (most specific) matching route, or None."""
  154. for route in routes:
  155. if route.matches(platform, guild_id=guild_id, chat_id=chat_id, thread_id=thread_id,
  156. parent_chat_id=parent_chat_id, adapter_profile=adapter_profile,
  157. user_id=user_id):
  158. return route
  159. return None