@theokit/gateway-whatsapp 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -756,6 +756,82 @@ var WhatsAppBaileysBackend = class {
756
756
  }
757
757
  };
758
758
 
759
+ // src/inbound-rules.ts
760
+ function digitsOnly(s) {
761
+ return s.replace(/[^\d]/g, "");
762
+ }
763
+ var PHONE_RUN = /[\d][\d+\-().  ]*[\d]|[\d]/g;
764
+ function phoneRuns(s) {
765
+ return (s.match(PHONE_RUN) ?? []).map(digitsOnly);
766
+ }
767
+ function isRefusedBySenderAllowlist(inbound, allowedSenders) {
768
+ if (inbound.fromSelf === true) return false;
769
+ if (allowedSenders === void 0) return false;
770
+ if (isSenderAllowed(inbound.fromPhone, allowedSenders)) return false;
771
+ process.stderr.write(
772
+ `[whatsapp] dropped inbound from ${redactedSender(inbound.fromPhone)}: not in the configured allowlist
773
+ `
774
+ );
775
+ return true;
776
+ }
777
+ function redactedSender(fromPhone) {
778
+ const tail = lastFourDigits(fromPhone);
779
+ return tail.length > 0 ? `a sender ending in ${tail}` : "a sender with no number";
780
+ }
781
+ function lastFourDigits(value) {
782
+ return digitsOnly(value).slice(-4);
783
+ }
784
+ function redactedNumberId(phoneNumberId) {
785
+ if (phoneNumberId === void 0) return "no phone number id";
786
+ const tail = lastFourDigits(phoneNumberId);
787
+ return tail.length > 0 ? `a phone number id ending in ${tail}` : "a phone number id with no digits";
788
+ }
789
+ function isForAnotherNumber(inbound, ownPhoneNumberId, reported) {
790
+ if (ownPhoneNumberId === void 0 || inbound.phoneNumberId === ownPhoneNumberId) return false;
791
+ const other = redactedNumberId(inbound.phoneNumberId);
792
+ if (!reported.has(other)) {
793
+ reported.add(other);
794
+ process.stderr.write(
795
+ `[whatsapp] dropped inbound addressed to ${other}: this adapter answers for "${ownPhoneNumberId}". Logged once per id ending.
796
+ `
797
+ );
798
+ }
799
+ return true;
800
+ }
801
+ function shouldDropGroupMessage(inbound, requireMention, botPhoneId) {
802
+ if (inbound.conversationType !== "group" || !requireMention) return false;
803
+ if (botPhoneId.length === 0) {
804
+ process.stderr.write(
805
+ "[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\n"
806
+ );
807
+ return true;
808
+ }
809
+ return !phoneRuns(inbound.text).some((run) => run.includes(botPhoneId));
810
+ }
811
+ function toMessageEvent(inbound) {
812
+ return {
813
+ id: inbound.wamid,
814
+ platform: "whatsapp",
815
+ sender: { id: inbound.fromPhone, displayName: inbound.contactName },
816
+ channel: { id: inbound.channelId, type: inbound.conversationType },
817
+ text: inbound.text,
818
+ receivedAt: inbound.receivedAt,
819
+ whatsapp: {
820
+ wamid: inbound.wamid,
821
+ phoneNumberId: inbound.phoneNumberId,
822
+ contactName: inbound.contactName,
823
+ channelJid: inbound.channelJid,
824
+ backend: inbound.backend,
825
+ raw: inbound.raw
826
+ }
827
+ };
828
+ }
829
+ function decideInbound(inbound, rules) {
830
+ if (isRefusedBySenderAllowlist(inbound, rules.allowedSenders)) return void 0;
831
+ if (shouldDropGroupMessage(inbound, rules.requireMention, rules.botPhoneId)) return void 0;
832
+ return toMessageEvent(inbound);
833
+ }
834
+
759
835
  // src/backend/cloud/client.ts
760
836
  var WhatsAppCloudClient = class {
761
837
  constructor(opts) {
@@ -931,7 +1007,44 @@ var WhatsAppCloudClient = class {
931
1007
  }
932
1008
  }
933
1009
  };
1010
+ function verifyWebhookSignature(rawBody, signatureHeader, appSecret) {
1011
+ if (appSecret.trim().length === 0) {
1012
+ throw new ConfigurationError({
1013
+ code: "missing_option",
1014
+ message: "gateway-whatsapp: appSecret is required to verify a webhook signature and must not be empty; an HMAC under an empty key is computable by anyone."
1015
+ });
1016
+ }
1017
+ if (signatureHeader === void 0) return false;
1018
+ if (!signatureHeader.startsWith("sha256=")) return false;
1019
+ const receivedHex = signatureHeader.slice(7);
1020
+ if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;
1021
+ const received = Buffer.from(receivedHex, "hex");
1022
+ const expected = crypto.createHmac("sha256", appSecret).update(rawBody).digest();
1023
+ if (received.length !== expected.length) return false;
1024
+ return crypto.timingSafeEqual(received, expected);
1025
+ }
1026
+
1027
+ // src/backend/cloud/webhook.ts
1028
+ var KNOWN_NON_TEXT_TYPES = /* @__PURE__ */ new Set([
1029
+ "audio",
1030
+ "button",
1031
+ "contacts",
1032
+ "document",
1033
+ "image",
1034
+ "interactive",
1035
+ "location",
1036
+ "order",
1037
+ "reaction",
1038
+ "request_welcome",
1039
+ "sticker",
1040
+ "system",
1041
+ "unsupported",
1042
+ "video"
1043
+ ]);
934
1044
  var warnedNonTextTypes = /* @__PURE__ */ new Set();
1045
+ function nonTextTypeLabel(type) {
1046
+ return typeof type === "string" && KNOWN_NON_TEXT_TYPES.has(type) ? type : "an unknown type";
1047
+ }
935
1048
  function verifyWebhookSubscription(query, expectedVerifyToken) {
936
1049
  const mode = query["hub.mode"];
937
1050
  const token = query["hub.verify_token"];
@@ -941,22 +1054,50 @@ function verifyWebhookSubscription(query, expectedVerifyToken) {
941
1054
  if (challenge === void 0 || challenge.length === 0) return null;
942
1055
  return challenge;
943
1056
  }
944
- function verifyWebhookSignature(rawBody, signatureHeader, appSecret) {
945
- if (signatureHeader === void 0) return false;
946
- if (!signatureHeader.startsWith("sha256=")) return false;
947
- const receivedHex = signatureHeader.slice(7);
948
- if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;
949
- const received = Buffer.from(receivedHex, "hex");
950
- const body = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody;
951
- const expected = crypto.createHmac("sha256", appSecret).update(body).digest();
952
- if (received.length !== expected.length) return false;
953
- return crypto.timingSafeEqual(received, expected);
1057
+ function isRecord(value) {
1058
+ return value !== null && typeof value === "object";
1059
+ }
1060
+ function isOptionalRecordArray(value) {
1061
+ return value === void 0 || Array.isArray(value) && value.every(isRecord);
1062
+ }
1063
+ function isWellFormedMetadata(metadata) {
1064
+ if (metadata === void 0 || metadata === null) return true;
1065
+ if (!isRecord(metadata)) return false;
1066
+ return metadata.phone_number_id === void 0 || typeof metadata.phone_number_id === "string";
1067
+ }
1068
+ function isReadableMessage(message) {
1069
+ if (message.type !== "text") return true;
1070
+ if (typeof message.id !== "string" || typeof message.from !== "string") return false;
1071
+ const text = message.text;
1072
+ return text === void 0 || isRecord(text) && typeof text.body === "string";
1073
+ }
1074
+ function isReadableContact(contact) {
1075
+ if (typeof contact.wa_id !== "string") return false;
1076
+ const profile = contact.profile;
1077
+ if (profile === void 0) return true;
1078
+ return isRecord(profile) && (profile.name === void 0 || typeof profile.name === "string");
1079
+ }
1080
+ function isReadableStatus(status) {
1081
+ return typeof status.id === "string" && typeof status.status === "string" && typeof status.recipient_id === "string";
1082
+ }
1083
+ function isOptionalReadableList(list, isReadable) {
1084
+ if (!isOptionalRecordArray(list)) return false;
1085
+ return list === void 0 || list.every(isReadable);
1086
+ }
1087
+ function isWellFormedValue(value) {
1088
+ if (value === void 0 || value === null) return true;
1089
+ if (!isRecord(value)) return false;
1090
+ return isWellFormedMetadata(value.metadata) && isOptionalReadableList(value.contacts, isReadableContact) && isOptionalReadableList(value.messages, isReadableMessage) && isOptionalReadableList(value.statuses, isReadableStatus);
1091
+ }
1092
+ function isWellFormedEntry(entry) {
1093
+ if (!isRecord(entry) || !Array.isArray(entry.changes)) return false;
1094
+ return entry.changes.every((change) => isRecord(change) && isWellFormedValue(change.value));
954
1095
  }
955
1096
  function parseWebhookPayload(json) {
956
- if (json === null || typeof json !== "object") return null;
957
- const env = json;
958
- if (env.object === void 0 || !Array.isArray(env.entry)) return null;
959
- return env;
1097
+ if (!isRecord(json)) return null;
1098
+ if (json.object === void 0 || !Array.isArray(json.entry)) return null;
1099
+ if (!json.entry.every(isWellFormedEntry)) return null;
1100
+ return json;
960
1101
  }
961
1102
  function buildContactMap(value) {
962
1103
  const map = /* @__PURE__ */ new Map();
@@ -982,10 +1123,11 @@ function normalizeInboundMessages(envelope) {
982
1123
  }
983
1124
  function normalizeOneMessage(msg, phoneNumberId, contactByWaId) {
984
1125
  if (msg.type !== "text") {
985
- if (!warnedNonTextTypes.has(msg.type)) {
986
- warnedNonTextTypes.add(msg.type);
1126
+ const label = nonTextTypeLabel(msg.type);
1127
+ if (!warnedNonTextTypes.has(label)) {
1128
+ warnedNonTextTypes.add(label);
987
1129
  process.stderr.write(
988
- `[whatsapp] ignoring ${msg.type} message \u2014 v1 text-only (will be supported in v0.2+).
1130
+ `[whatsapp] ignoring ${label} message \u2014 v1 text-only (will be supported in v0.2+).
989
1131
  `
990
1132
  );
991
1133
  }
@@ -1009,21 +1151,22 @@ function normalizeStatusReceipts(envelope) {
1009
1151
  const out = [];
1010
1152
  for (const entry of envelope.entry) {
1011
1153
  for (const change of entry.changes) {
1012
- const statuses = change.value?.statuses ?? [];
1013
- for (const s of statuses) {
1014
- out.push(metaStatusToReceipt(s));
1154
+ const phoneNumberId = change.value?.metadata?.phone_number_id;
1155
+ for (const s of change.value?.statuses ?? []) {
1156
+ out.push(metaStatusToReceipt(s, phoneNumberId));
1015
1157
  }
1016
1158
  }
1017
1159
  }
1018
1160
  return out;
1019
1161
  }
1020
- function metaStatusToReceipt(s) {
1021
- return {
1162
+ function metaStatusToReceipt(s, phoneNumberId) {
1163
+ const receipt = {
1022
1164
  wamid: s.id,
1023
1165
  status: s.status,
1024
1166
  recipient: s.recipient_id,
1025
1167
  timestamp: Number(s.timestamp) * 1e3 || Date.now()
1026
1168
  };
1169
+ return phoneNumberId === void 0 ? receipt : { ...receipt, phoneNumberId };
1027
1170
  }
1028
1171
 
1029
1172
  // src/backend/cloud/index.ts
@@ -1053,6 +1196,14 @@ var WhatsAppCloudBackend = class {
1053
1196
  */
1054
1197
  generation = 0;
1055
1198
  appSecret;
1199
+ /**
1200
+ * The Meta phone number id this backend sends as and answers for. Declared through
1201
+ * `WhatsAppBackend.phoneNumberId`, so an adapter holding this backend can refuse a signed message
1202
+ * addressed to another number of the same app.
1203
+ */
1204
+ phoneNumberId;
1205
+ /** Foreign phone number id endings already named on stderr, so each is reported once. */
1206
+ reportedForeignNumbers = /* @__PURE__ */ new Set();
1056
1207
  inboundHandler;
1057
1208
  statusHandler;
1058
1209
  constructor(opts) {
@@ -1063,6 +1214,7 @@ var WhatsAppCloudBackend = class {
1063
1214
  ...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
1064
1215
  });
1065
1216
  this.appSecret = opts.appSecret;
1217
+ this.phoneNumberId = opts.phoneNumberId;
1066
1218
  }
1067
1219
  // Cloud has no persistent connection — webhook is push, send is HTTP.
1068
1220
  /**
@@ -1168,8 +1320,24 @@ var WhatsAppCloudBackend = class {
1168
1320
  * Webhook entrypoint. The user calls this from inside their POST /webhook
1169
1321
  * route after `verifyWebhookSubscription` on GET.
1170
1322
  *
1171
- * @returns `true` if signature valid + dispatched (or empty payload).
1172
- * `false` if signature invalid (route should return 401).
1323
+ * Only messages addressed to this backend's `phoneNumberId` reach the inbound handler, and only
1324
+ * status receipts addressed to it reach the status handler. Meta signs every number of one app
1325
+ * with one secret and an app-level webhook URL receives every subscribed number, so a valid
1326
+ * signature does not say which number a message or receipt was for; one for another number, or
1327
+ * naming none, is dropped and its id written to stderr once (`isForAnotherNumber`, the rule
1328
+ * `WhatsAppAdapter` applies too).
1329
+ *
1330
+ * @returns `true` if the signature is valid and the body was dispatched (or held nothing to
1331
+ * dispatch). `false` if the signature is invalid, if the signed body is not JSON or
1332
+ * has a shape {@link parseWebhookPayload} refuses, or if it holds a message for this
1333
+ * number while no inbound handler is subscribed (before `onInbound`, or after
1334
+ * `disconnect()`): the whole body is refused, never a part of it dropped, and one line
1335
+ * on stderr says which. Answer `false` with a non-2xx (401 for a bad signature) so the
1336
+ * drop is seen and Meta redelivers. Status receipts with no status handler subscribed
1337
+ * are discarded on purpose: subscribing to receipts is optional, and refusing them
1338
+ * would make Meta redeliver every receipt to a route that never wants one.
1339
+ * @throws {ConfigurationError} `missing_option` when this backend's `appSecret` is empty or
1340
+ * whitespace only: a signature under an empty key proves nothing.
1173
1341
  */
1174
1342
  async handleWebhookPayload(rawBody, signatureHeader) {
1175
1343
  if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {
@@ -1178,16 +1346,45 @@ var WhatsAppCloudBackend = class {
1178
1346
  const json = this.parseBody(rawBody);
1179
1347
  if (json === void 0) return false;
1180
1348
  const envelope = parseWebhookPayload(json);
1181
- if (envelope === null) return true;
1182
- for (const event of normalizeInboundMessages(envelope)) {
1183
- if (this.inboundHandler === void 0) continue;
1184
- await this.dispatchContained(() => this.inboundHandler?.(event), "handler");
1349
+ if (envelope === null) {
1350
+ process.stderr.write(
1351
+ "[whatsapp-cloud] signed webhook body has a shape the parser refuses (no object, no entry array, or a malformed entry, change or list); refused whole, nothing dispatched\n"
1352
+ );
1353
+ return false;
1354
+ }
1355
+ const messages = normalizeInboundMessages(envelope).filter(
1356
+ (event) => !isForAnotherNumber(event, this.phoneNumberId, this.reportedForeignNumbers)
1357
+ );
1358
+ const inboundHandler = this.inboundHandler;
1359
+ if (messages.length > 0 && inboundHandler === void 0) {
1360
+ process.stderr.write(
1361
+ `[whatsapp-cloud] signed webhook body holds ${messages.length} message(s) for this number and no inbound handler is subscribed; refused whole, nothing dispatched
1362
+ `
1363
+ );
1364
+ return false;
1185
1365
  }
1366
+ if (inboundHandler !== void 0) await this.dispatchInbound(messages, inboundHandler);
1367
+ await this.dispatchStatusReceipts(envelope);
1368
+ return true;
1369
+ }
1370
+ /**
1371
+ * Hand each status receipt addressed to this backend's number to the status handler.
1372
+ *
1373
+ * Same rule as messages: a receipt names the recipient's phone number, so one number's receipts
1374
+ * reaching another number's handler hands one tenant's customer numbers to another tenant.
1375
+ */
1376
+ async dispatchStatusReceipts(envelope) {
1186
1377
  for (const receipt of normalizeStatusReceipts(envelope)) {
1187
1378
  if (this.statusHandler === void 0) continue;
1379
+ if (isForAnotherNumber(receipt, this.phoneNumberId, this.reportedForeignNumbers)) continue;
1188
1380
  await this.dispatchContained(() => this.statusHandler?.(receipt), "status handler");
1189
1381
  }
1190
- return true;
1382
+ }
1383
+ /** Hand each message, already scoped to this backend's number, to the inbound handler. */
1384
+ async dispatchInbound(messages, handler) {
1385
+ for (const event of messages) {
1386
+ await this.dispatchContained(() => handler(event), "handler");
1387
+ }
1191
1388
  }
1192
1389
  /**
1193
1390
  * Parse a signed webhook body, or report `undefined` when it is not JSON.
@@ -1595,6 +1792,19 @@ function defaultBridgeScriptPath() {
1595
1792
  }
1596
1793
  return found;
1597
1794
  }
1795
+
1796
+ // src/own-number.ts
1797
+ function decideForOwnNumber(inbound, ownPhoneNumberId, reported, rules) {
1798
+ if (isForAnotherNumber(inbound, ownPhoneNumberId, reported)) return void 0;
1799
+ return decideInbound(inbound, rules);
1800
+ }
1801
+ function requireOwnPhoneNumberId(ownPhoneNumberId, method) {
1802
+ if (ownPhoneNumberId !== void 0) return ownPhoneNumberId;
1803
+ throw new ConfigurationError({
1804
+ code: "missing_phone_number_id",
1805
+ message: `gateway-whatsapp: ${method} needs the backend to declare its phoneNumberId. One Meta app signs every number's webhooks with one secret, so without it this adapter would deliver every number's messages. Use fromCloud, or expose phoneNumberId on a backend that wraps WhatsAppCloudBackend.`
1806
+ });
1807
+ }
1598
1808
  var WHATSAPP_MAX_TEXT = 4096;
1599
1809
  function splitForWhatsApp(text) {
1600
1810
  return chunkText(text, {
@@ -1618,20 +1828,28 @@ function requireNonEmpty(entries) {
1618
1828
  }
1619
1829
  }
1620
1830
  }
1621
- function digitsOnly(s) {
1622
- return s.replace(/[^\d]/g, "");
1623
- }
1624
- var PHONE_RUN = /[\d][\d+\-().  ]*[\d]|[\d]/g;
1625
- function phoneRuns(s) {
1626
- return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);
1627
- }
1628
1831
  var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1629
1832
  platform = "whatsapp";
1630
1833
  backendImpl;
1631
- requireMention;
1834
+ /**
1835
+ * The bot's number, digits only. Kept as its own field because the documented construction
1836
+ * path is tested by reading it (`fromCloud` defaulting it to the phone number id).
1837
+ */
1632
1838
  botPhoneId;
1633
- /** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */
1634
- allowedSenders;
1839
+ /** The sender allowlist and group rule the inbound path decides by. */
1840
+ rules;
1841
+ /**
1842
+ * The Cloud phone number id this adapter answers for, read from the backend's declared
1843
+ * `phoneNumberId` at construction (so `fromCloud`, `new WhatsAppAdapter(new WhatsAppCloudBackend(...))`
1844
+ * and any backend declaring the field decide alike), `undefined` for a backend that declares none.
1845
+ * Meta signs every number of one app with one secret, so a signed message is only this adapter's
1846
+ * when its `phoneNumberId` is this one.
1847
+ */
1848
+ ownPhoneNumberId;
1849
+ /** Foreign phone number id endings already named on stderr, so each is reported once. */
1850
+ reportedForeignNumbers = /* @__PURE__ */ new Set();
1851
+ /** The rules both inbound paths share; `onInbound` skips the precondition (see `decideForOwnNumber`). */
1852
+ decide = (inbound) => decideForOwnNumber(inbound, this.ownPhoneNumberId, this.reportedForeignNumbers, this.rules);
1635
1853
  /** Mirrors the sibling adapters: guards connect() against opening a second session. */
1636
1854
  connected = false;
1637
1855
  handler;
@@ -1775,9 +1993,16 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1775
1993
  constructor(backendImpl, opts = {}) {
1776
1994
  super();
1777
1995
  this.backendImpl = backendImpl;
1778
- this.requireMention = opts.requireMention ?? true;
1996
+ this.ownPhoneNumberId = backendImpl.phoneNumberId;
1779
1997
  this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
1780
- this.allowedSenders = opts.allowedSenders === void 0 ? void 0 : parseAllowedSenders(opts.allowedSenders);
1998
+ this.rules = {
1999
+ requireMention: opts.requireMention ?? true,
2000
+ botPhoneId: this.botPhoneId,
2001
+ // Absent and empty are different answers. Absent means the operator has not adopted the
2002
+ // filter, and delivery is unchanged. Empty means they configured one and named nobody, which
2003
+ // is a decision — `parseAllowedSenders` is fail-closed and honours it.
2004
+ allowedSenders: opts.allowedSenders === void 0 ? void 0 : parseAllowedSenders(opts.allowedSenders)
2005
+ };
1781
2006
  }
1782
2007
  /** Escape hatch (D180-style) for advanced features. */
1783
2008
  getBackend() {
@@ -1825,62 +2050,13 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1825
2050
  }
1826
2051
  return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
1827
2052
  }
1828
- /**
1829
- * Is this sender refused by a configured allowlist?
1830
- *
1831
- * Runs before the group/mention filter because it answers a different question: that one asks
1832
- * whether a message was meant for us, this one asks whether the sender may reach us at all.
1833
- *
1834
- * The refusal is logged. A silent drop is indistinguishable from a broken gateway, and the
1835
- * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
1836
- */
1837
- isRefusedBySenderAllowlist(inbound) {
1838
- if (inbound.fromSelf === true) return false;
1839
- if (this.allowedSenders === void 0) return false;
1840
- if (isSenderAllowed(inbound.fromPhone, this.allowedSenders)) return false;
1841
- process.stderr.write(
1842
- `[whatsapp] dropped inbound from "${inbound.fromPhone}" \u2014 not in the configured allowlist
1843
- `
1844
- );
1845
- return true;
1846
- }
1847
- /** D309 + EC-7: group filter with digit-only normalization. */
1848
- shouldDropGroupMessage(inbound) {
1849
- if (inbound.conversationType !== "group" || !this.requireMention) return false;
1850
- if (this.botPhoneId.length === 0) {
1851
- process.stderr.write(
1852
- "[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\n"
1853
- );
1854
- return true;
1855
- }
1856
- return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));
1857
- }
1858
- toMessageEvent(inbound) {
1859
- return {
1860
- id: inbound.wamid,
1861
- platform: "whatsapp",
1862
- sender: { id: inbound.fromPhone, displayName: inbound.contactName },
1863
- channel: { id: inbound.channelId, type: inbound.conversationType },
1864
- text: inbound.text,
1865
- receivedAt: inbound.receivedAt,
1866
- whatsapp: {
1867
- wamid: inbound.wamid,
1868
- phoneNumberId: inbound.phoneNumberId,
1869
- contactName: inbound.contactName,
1870
- channelJid: inbound.channelJid,
1871
- backend: inbound.backend,
1872
- raw: inbound.raw
1873
- }
1874
- };
1875
- }
1876
2053
  onInbound(handler) {
1877
2054
  this.inboundUnsubscribe?.();
1878
2055
  this.handler = handler;
1879
2056
  const off = this.backendImpl.onInbound(async (inbound) => {
1880
- if (!this.handler) return;
1881
- if (this.isRefusedBySenderAllowlist(inbound)) return;
1882
- if (this.shouldDropGroupMessage(inbound)) return;
1883
- await this.handler(this.toMessageEvent(inbound));
2057
+ const event = this.decide(inbound);
2058
+ if (event === void 0) return;
2059
+ await handler(event);
1884
2060
  });
1885
2061
  this.inboundUnsubscribe = off;
1886
2062
  return () => {
@@ -1891,11 +2067,67 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1891
2067
  }
1892
2068
  };
1893
2069
  }
1894
- /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
2070
+ /**
2071
+ * The event `onInbound` would hand its handler for this inbound message, or `undefined` when the
2072
+ * sender allowlist refuses it or the group rule drops it. A refusal writes the same stderr line
2073
+ * `onInbound` writes.
2074
+ *
2075
+ * It also drops a message addressed to another phone number id than the one the backend
2076
+ * declares (one app may serve several numbers under one secret), naming that id on stderr once.
2077
+ * A Cloud message on an adapter whose backend declares no `phoneNumberId` throws, as in
2078
+ * `toDeliverableEvents`; a WhatsApp Web or Baileys message has no number to compare.
2079
+ *
2080
+ * Pass the result to `deliver()`. Neither the backend nor the network is called.
2081
+ *
2082
+ * @throws {ConfigurationError} (`missing_phone_number_id`) for a Cloud message when the backend
2083
+ * declares no `phoneNumberId`.
2084
+ * @public
2085
+ */
2086
+ toDeliverableEvent(inbound) {
2087
+ if (inbound.backend === "cloud") {
2088
+ requireOwnPhoneNumberId(this.ownPhoneNumberId, "toDeliverableEvent");
2089
+ }
2090
+ return this.decide(inbound);
2091
+ }
2092
+ /**
2093
+ * The events of one Meta Cloud webhook envelope that may reach the agent, in envelope order, with
2094
+ * the sender allowlist and the group rule applied. Status receipts and non-text messages yield no
2095
+ * event, so a status-only envelope returns `[]`. Each refused or dropped message writes the
2096
+ * same stderr line `onInbound` writes. Messages addressed to another `phone_number_id` are
2097
+ * dropped (see `toDeliverableEvent`).
2098
+ *
2099
+ * The adapter's backend must declare its `phoneNumberId`. `fromCloud` and any
2100
+ * `WhatsAppCloudBackend` do; a backend that wraps one by delegation must expose the field too.
2101
+ * Without it there is no number to compare, and every number of the Meta app would reach this
2102
+ * adapter's agent, so this method fails closed instead (docs/adr/0006).
2103
+ *
2104
+ * The route that receives the webhook verifies `X-Hub-Signature-256` first (with
2105
+ * `verifyWebhookSignature`, or theokit's `whatsapp()` route validator); this method does not. Meta redelivers on timeout, and
2106
+ * `event.whatsapp.wamid` is the key a route can use to ignore a repeat. Neither the backend nor
2107
+ * the network is called.
2108
+ *
2109
+ * @throws {ConfigurationError} (`missing_phone_number_id`) when the backend declares no
2110
+ * `phoneNumberId`.
2111
+ * @public
2112
+ */
2113
+ toDeliverableEvents(envelope) {
2114
+ requireOwnPhoneNumberId(this.ownPhoneNumberId, "toDeliverableEvents");
2115
+ const events = [];
2116
+ for (const inbound of normalizeInboundMessages(envelope)) {
2117
+ const event = this.toDeliverableEvent(inbound);
2118
+ if (event !== void 0) events.push(event);
2119
+ }
2120
+ return events;
2121
+ }
2122
+ /**
2123
+ * Status receipts (sent/delivered/read/failed). Adapter-specific (D307). A receipt names the
2124
+ * customer's number, so one addressed to another phone number id is dropped, as messages are.
2125
+ */
1895
2126
  onStatusReceipt(handler) {
1896
2127
  this.statusUnsubscribe?.();
1897
2128
  this.statusHandler = handler;
1898
2129
  const off = this.backendImpl.onStatusReceipt(async (r) => {
2130
+ if (isForAnotherNumber(r, this.ownPhoneNumberId, this.reportedForeignNumbers)) return;
1899
2131
  await this.statusHandler?.(r);
1900
2132
  });
1901
2133
  this.statusUnsubscribe = off;