whatsapp_identity.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. """Shared helpers for canonicalising WhatsApp sender identity.
  2. The bridge can surface one human as a LID (``999...@lid``) or a phone JID
  3. (``1555...@s.whatsapp.net``) within one conversation. Authorisation (:mod:`gateway.run`) and
  4. session keys (:mod:`gateway.session`) both resolve aliases here so they never drift apart;
  5. plugins should use :func:`canonical_whatsapp_identifier` to line up with Hermes' session keys.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import logging
  10. import re
  11. from typing import Set
  12. from hermes_constants import get_hermes_dir
  13. logger = logging.getLogger(__name__)
  14. # WhatsApp JIDs are numeric (or plus-prefixed) with ``@``/``.``/``:`` separators.
  15. # Explicit ASCII class so full-width digits / Unicode word chars can't sneak through.
  16. _SAFE_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9@.+\-]+$")
  17. # "Just a phone number": optional ``+`` then digits and human separators.
  18. # Anything carrying ``@`` is already a JID (``@g.us``, ``@lid``, ``status@broadcast``).
  19. _BARE_PHONE_RE = re.compile(r"^\+?[\d\s().\-]+$")
  20. def normalize_whatsapp_identifier(value: str) -> str:
  21. """Strip JID/LID/device/plus syntax down to the bare numeric identifier:
  22. ``"6012:47@s.whatsapp.net"``, ``"6012@lid"`` and ``"+6012"`` all become ``"6012"``."""
  23. return str(value or "").strip().replace("+", "", 1).split(":", 1)[0].split("@", 1)[0]
  24. def to_whatsapp_jid(value: str) -> str:
  25. """Normalize an *outbound* target to a bridge-safe JID (inverse of normalize). Baileys'
  26. ``jidDecode`` crashes on a bare phone, so bare phones become ``<digits>@s.whatsapp.net``;
  27. ``user:device@domain`` collapses to ``user@domain``; anything else is returned unchanged
  28. so the bridge can surface a real error. ``""`` for empty input."""
  29. if not value:
  30. return ""
  31. normalized = str(value).strip()
  32. if ":" in normalized and "@" in normalized:
  33. prefix, _, domain = normalized.partition("@")
  34. normalized = f"{prefix.split(':', 1)[0]}@{domain}"
  35. if "@" in normalized:
  36. return normalized
  37. if _BARE_PHONE_RE.fullmatch(normalized):
  38. digits = re.sub(r"\D+", "", normalized)
  39. if digits:
  40. return f"{digits}@s.whatsapp.net"
  41. return normalized
  42. def normalize_whatsapp_mention_jid(value: str) -> str:
  43. """Return a valid participant JID for an outbound mention, or ``""``."""
  44. jid = to_whatsapp_jid(value)
  45. user, separator, domain = jid.partition("@")
  46. return (
  47. jid
  48. if separator
  49. and user.isascii()
  50. and user.isdigit()
  51. and domain in {"s.whatsapp.net", "lid"}
  52. else ""
  53. )
  54. def expand_whatsapp_aliases(identifier: str) -> set[str]:
  55. """All identifiers transitively reachable via the bridge's ``lid-mapping-*.json`` files;
  56. always includes the normalized input itself (empty set if it normalizes to empty)."""
  57. normalized = normalize_whatsapp_identifier(identifier)
  58. if not normalized:
  59. return set()
  60. session_dir = get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")
  61. resolved: set[str] = set()
  62. queue = [normalized]
  63. while queue:
  64. current = queue.pop(0)
  65. # _SAFE_IDENTIFIER_RE: defense-in-depth against path separators / traversal in the
  66. # ``lid-mapping-{current}`` filename (the fixed prefix already prevents escape).
  67. if not current or current in resolved or not _SAFE_IDENTIFIER_RE.match(current):
  68. continue
  69. resolved.add(current)
  70. for suffix in ("", "_reverse"):
  71. mapping_path = session_dir / f"lid-mapping-{current}{suffix}.json"
  72. if not mapping_path.exists():
  73. continue
  74. try:
  75. # utf-8-sig: our fix for BOM'd lid-mapping files written on Windows.
  76. mapped = normalize_whatsapp_identifier(
  77. json.loads(mapping_path.read_text(encoding="utf-8-sig"))
  78. )
  79. except (OSError, json.JSONDecodeError) as exc:
  80. logger.debug("whatsapp_identity: failed to read %s: %s", mapping_path, exc)
  81. continue
  82. if mapped and mapped not in resolved:
  83. queue.append(mapped)
  84. return resolved
  85. def canonical_whatsapp_identifier(identifier: str) -> str:
  86. """Stable sender identity across phone-JID/LID variants (DM ``chat_id`` and group
  87. ``participant_id`` alike): the shortest alias from :func:`expand_whatsapp_aliases`, which
  88. degrades to the normalized input when no mapping files exist. ``""`` for empty input."""
  89. normalized = normalize_whatsapp_identifier(identifier)
  90. if not normalized:
  91. return ""
  92. # expand_whatsapp_aliases includes ``normalized`` itself, so min() degrades to it
  93. # when no lid-mapping files are present.
  94. aliases = expand_whatsapp_aliases(normalized)
  95. return min(aliases, key=lambda c: (len(c), c))