owner_message_gate.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Pure classifier for the WhatsApp bridge's bot-mode dispatch loop.
  3. *
  4. * Centralises the "should this fromMe message be forwarded as fromOwner?"
  5. * decision so the gate can be unit-tested without spinning up Baileys or
  6. * the Express server.
  7. *
  8. * Lives next to `outbound_ids.js` rather than inline in `bridge.js`
  9. * because the previous implementation accidentally bypassed the
  10. * customer-side allowlist when forwarding owner-typed messages — see
  11. * the regression test in `owner_message_gate.test.mjs`.
  12. *
  13. * Caller responsibilities:
  14. * - Only invoke in bot mode. Self-chat mode has its own self-chat
  15. * pinning logic and must not delegate here.
  16. * - Pre-filter group / status JIDs (the gate doesn't know about them).
  17. * - On `drop_allowlist`, log the rejection so operators can audit
  18. * accidental allowlist mismatches.
  19. *
  20. * Returned actions:
  21. * - 'pass' : non-fromMe, fall through to existing handling
  22. * - 'drop_echo' : fromMe and matches a recently-sent /send id
  23. * - 'drop_disabled' : fromMe but operator hasn't opted into forwarding
  24. * - 'drop_allowlist' : fromMe and the *customer chatId* isn't on the
  25. * allowlist (owner-typed reply to a stranger)
  26. * - 'forward_owner' : fromMe, owner-typed, allowlisted — forward with
  27. * fromOwner: true
  28. */
  29. export function classifyOwnerMessageGate({
  30. fromMe,
  31. fromOwnerEnabled,
  32. recentlySent,
  33. allowlistMatches,
  34. messageId,
  35. chatId,
  36. }) {
  37. if (!fromMe) {
  38. return { action: 'pass' };
  39. }
  40. if (recentlySent && recentlySent.has(messageId)) {
  41. return { action: 'drop_echo' };
  42. }
  43. if (!fromOwnerEnabled) {
  44. return { action: 'drop_disabled' };
  45. }
  46. // Allowlist gate: check the *customer* chatId, not the sender. The
  47. // sender is the owner's own number/LID and won't be on the allowlist
  48. // by construction. Without this check, any contact the owner happens
  49. // to reply to leaks into Hermes and triggers implicit handover in the
  50. // gateway-policy plugin.
  51. if (typeof allowlistMatches === 'function' && !allowlistMatches(chatId)) {
  52. return { action: 'drop_allowlist' };
  53. }
  54. return { action: 'forward_owner' };
  55. }