@theokit/gateway-whatsapp 0.4.1 → 0.6.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.cjs CHANGED
@@ -780,6 +780,84 @@ var WhatsAppBaileysBackend = class {
780
780
  }
781
781
  };
782
782
 
783
+ // src/inbound-rules.ts
784
+ function digitsOnly(s) {
785
+ return s.replace(/[^\d]/g, "");
786
+ }
787
+ var PHONE_RUN = /[\d][\d+\-().  ]*[\d]|[\d]/g;
788
+ function phoneRuns(s) {
789
+ return (s.match(PHONE_RUN) ?? []).map(digitsOnly);
790
+ }
791
+ function isRefusedBySenderAllowlist(inbound, allowedSenders) {
792
+ if (inbound.fromSelf === true) return false;
793
+ if (allowedSenders === void 0) return false;
794
+ if (isSenderAllowed(inbound.fromPhone, allowedSenders)) return false;
795
+ process.stderr.write(
796
+ `[whatsapp] dropped inbound from ${redactedSender(inbound.fromPhone)}: not in the configured allowlist
797
+ `
798
+ );
799
+ return true;
800
+ }
801
+ function redactedSender(fromPhone) {
802
+ const tail = lastFourDigits(fromPhone);
803
+ return tail.length > 0 ? `a sender ending in ${tail}` : "a sender with no number";
804
+ }
805
+ function lastFourDigits(value) {
806
+ return digitsOnly(value).slice(-4);
807
+ }
808
+ function shouldDropGroupMessage(inbound, requireMention, botPhoneId) {
809
+ if (inbound.conversationType !== "group" || !requireMention) return false;
810
+ if (botPhoneId.length === 0) {
811
+ process.stderr.write(
812
+ "[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\n"
813
+ );
814
+ return true;
815
+ }
816
+ return !phoneRuns(inbound.text).some((run) => run.includes(botPhoneId));
817
+ }
818
+ function toMessageEvent(inbound) {
819
+ return {
820
+ id: inbound.wamid,
821
+ platform: "whatsapp",
822
+ sender: { id: inbound.fromPhone, displayName: inbound.contactName },
823
+ channel: { id: inbound.channelId, type: inbound.conversationType },
824
+ text: inbound.text,
825
+ receivedAt: inbound.receivedAt,
826
+ whatsapp: {
827
+ wamid: inbound.wamid,
828
+ phoneNumberId: inbound.phoneNumberId,
829
+ contactName: inbound.contactName,
830
+ channelJid: inbound.channelJid,
831
+ backend: inbound.backend,
832
+ raw: inbound.raw
833
+ }
834
+ };
835
+ }
836
+ function decideInbound(inbound, rules) {
837
+ if (isRefusedBySenderAllowlist(inbound, rules.allowedSenders)) return void 0;
838
+ if (shouldDropGroupMessage(inbound, rules.requireMention, rules.botPhoneId)) return void 0;
839
+ return toMessageEvent(inbound);
840
+ }
841
+
842
+ // src/foreign-number.ts
843
+ function redactedNumberId(phoneNumberId) {
844
+ if (phoneNumberId === void 0) return "no phone number id";
845
+ const tail = lastFourDigits(phoneNumberId);
846
+ return tail.length > 0 ? `a phone number id ending in ${tail}` : "a phone number id with no digits";
847
+ }
848
+ function isForAnotherNumber(inbound, ownPhoneNumberId, reported) {
849
+ if (ownPhoneNumberId === void 0 || inbound.phoneNumberId === ownPhoneNumberId) return false;
850
+ const other = redactedNumberId(inbound.phoneNumberId);
851
+ if (!reported.has(other)) {
852
+ reported.add(other);
853
+ process.stderr.write(
854
+ `[whatsapp] dropped inbound addressed to ${other}: this adapter answers for "${ownPhoneNumberId}". Logged once per id ending.
855
+ `
856
+ );
857
+ }
858
+ return true;
859
+ }
860
+
783
861
  // src/backend/cloud/client.ts
784
862
  var WhatsAppCloudClient = class {
785
863
  constructor(opts) {
@@ -955,7 +1033,44 @@ var WhatsAppCloudClient = class {
955
1033
  }
956
1034
  }
957
1035
  };
1036
+ function verifyWebhookSignature(rawBody, signatureHeader, appSecret) {
1037
+ if (appSecret.trim().length === 0) {
1038
+ throw new ConfigurationError({
1039
+ code: "missing_option",
1040
+ 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."
1041
+ });
1042
+ }
1043
+ if (signatureHeader === void 0) return false;
1044
+ if (!signatureHeader.startsWith("sha256=")) return false;
1045
+ const receivedHex = signatureHeader.slice(7);
1046
+ if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;
1047
+ const received = Buffer.from(receivedHex, "hex");
1048
+ const expected = crypto__namespace.createHmac("sha256", appSecret).update(rawBody).digest();
1049
+ if (received.length !== expected.length) return false;
1050
+ return crypto__namespace.timingSafeEqual(received, expected);
1051
+ }
1052
+
1053
+ // src/backend/cloud/webhook.ts
1054
+ var KNOWN_NON_TEXT_TYPES = /* @__PURE__ */ new Set([
1055
+ "audio",
1056
+ "button",
1057
+ "contacts",
1058
+ "document",
1059
+ "image",
1060
+ "interactive",
1061
+ "location",
1062
+ "order",
1063
+ "reaction",
1064
+ "request_welcome",
1065
+ "sticker",
1066
+ "system",
1067
+ "unsupported",
1068
+ "video"
1069
+ ]);
958
1070
  var warnedNonTextTypes = /* @__PURE__ */ new Set();
1071
+ function nonTextTypeLabel(type) {
1072
+ return typeof type === "string" && KNOWN_NON_TEXT_TYPES.has(type) ? type : "an unknown type";
1073
+ }
959
1074
  function verifyWebhookSubscription(query, expectedVerifyToken) {
960
1075
  const mode = query["hub.mode"];
961
1076
  const token = query["hub.verify_token"];
@@ -965,22 +1080,50 @@ function verifyWebhookSubscription(query, expectedVerifyToken) {
965
1080
  if (challenge === void 0 || challenge.length === 0) return null;
966
1081
  return challenge;
967
1082
  }
968
- function verifyWebhookSignature(rawBody, signatureHeader, appSecret) {
969
- if (signatureHeader === void 0) return false;
970
- if (!signatureHeader.startsWith("sha256=")) return false;
971
- const receivedHex = signatureHeader.slice(7);
972
- if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;
973
- const received = Buffer.from(receivedHex, "hex");
974
- const body = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody;
975
- const expected = crypto__namespace.createHmac("sha256", appSecret).update(body).digest();
976
- if (received.length !== expected.length) return false;
977
- return crypto__namespace.timingSafeEqual(received, expected);
1083
+ function isRecord(value) {
1084
+ return value !== null && typeof value === "object";
1085
+ }
1086
+ function isOptionalRecordArray(value) {
1087
+ return value === void 0 || Array.isArray(value) && value.every(isRecord);
1088
+ }
1089
+ function isWellFormedMetadata(metadata) {
1090
+ if (metadata === void 0 || metadata === null) return true;
1091
+ if (!isRecord(metadata)) return false;
1092
+ return metadata.phone_number_id === void 0 || typeof metadata.phone_number_id === "string";
1093
+ }
1094
+ function isReadableMessage(message) {
1095
+ if (message.type !== "text") return true;
1096
+ if (typeof message.id !== "string" || typeof message.from !== "string") return false;
1097
+ const text = message.text;
1098
+ return text === void 0 || isRecord(text) && typeof text.body === "string";
1099
+ }
1100
+ function isReadableContact(contact) {
1101
+ if (typeof contact.wa_id !== "string") return false;
1102
+ const profile = contact.profile;
1103
+ if (profile === void 0) return true;
1104
+ return isRecord(profile) && (profile.name === void 0 || typeof profile.name === "string");
1105
+ }
1106
+ function isReadableStatus(status) {
1107
+ return typeof status.id === "string" && typeof status.status === "string" && typeof status.recipient_id === "string";
1108
+ }
1109
+ function isOptionalReadableList(list, isReadable) {
1110
+ if (!isOptionalRecordArray(list)) return false;
1111
+ return list === void 0 || list.every(isReadable);
1112
+ }
1113
+ function isWellFormedValue(value) {
1114
+ if (value === void 0 || value === null) return true;
1115
+ if (!isRecord(value)) return false;
1116
+ return isWellFormedMetadata(value.metadata) && isOptionalReadableList(value.contacts, isReadableContact) && isOptionalReadableList(value.messages, isReadableMessage) && isOptionalReadableList(value.statuses, isReadableStatus);
1117
+ }
1118
+ function isWellFormedEntry(entry) {
1119
+ if (!isRecord(entry) || !Array.isArray(entry.changes)) return false;
1120
+ return entry.changes.every((change) => isRecord(change) && isWellFormedValue(change.value));
978
1121
  }
979
1122
  function parseWebhookPayload(json) {
980
- if (json === null || typeof json !== "object") return null;
981
- const env = json;
982
- if (env.object === void 0 || !Array.isArray(env.entry)) return null;
983
- return env;
1123
+ if (!isRecord(json)) return null;
1124
+ if (json.object === void 0 || !Array.isArray(json.entry)) return null;
1125
+ if (!json.entry.every(isWellFormedEntry)) return null;
1126
+ return json;
984
1127
  }
985
1128
  function buildContactMap(value) {
986
1129
  const map = /* @__PURE__ */ new Map();
@@ -1006,10 +1149,11 @@ function normalizeInboundMessages(envelope) {
1006
1149
  }
1007
1150
  function normalizeOneMessage(msg, phoneNumberId, contactByWaId) {
1008
1151
  if (msg.type !== "text") {
1009
- if (!warnedNonTextTypes.has(msg.type)) {
1010
- warnedNonTextTypes.add(msg.type);
1152
+ const label = nonTextTypeLabel(msg.type);
1153
+ if (!warnedNonTextTypes.has(label)) {
1154
+ warnedNonTextTypes.add(label);
1011
1155
  process.stderr.write(
1012
- `[whatsapp] ignoring ${msg.type} message \u2014 v1 text-only (will be supported in v0.2+).
1156
+ `[whatsapp] ignoring ${label} message \u2014 v1 text-only (will be supported in v0.2+).
1013
1157
  `
1014
1158
  );
1015
1159
  }
@@ -1033,21 +1177,22 @@ function normalizeStatusReceipts(envelope) {
1033
1177
  const out = [];
1034
1178
  for (const entry of envelope.entry) {
1035
1179
  for (const change of entry.changes) {
1036
- const statuses = change.value?.statuses ?? [];
1037
- for (const s of statuses) {
1038
- out.push(metaStatusToReceipt(s));
1180
+ const phoneNumberId = change.value?.metadata?.phone_number_id;
1181
+ for (const s of change.value?.statuses ?? []) {
1182
+ out.push(metaStatusToReceipt(s, phoneNumberId));
1039
1183
  }
1040
1184
  }
1041
1185
  }
1042
1186
  return out;
1043
1187
  }
1044
- function metaStatusToReceipt(s) {
1045
- return {
1188
+ function metaStatusToReceipt(s, phoneNumberId) {
1189
+ const receipt = {
1046
1190
  wamid: s.id,
1047
1191
  status: s.status,
1048
1192
  recipient: s.recipient_id,
1049
1193
  timestamp: Number(s.timestamp) * 1e3 || Date.now()
1050
1194
  };
1195
+ return phoneNumberId === void 0 ? receipt : { ...receipt, phoneNumberId };
1051
1196
  }
1052
1197
 
1053
1198
  // src/backend/cloud/index.ts
@@ -1077,6 +1222,14 @@ var WhatsAppCloudBackend = class {
1077
1222
  */
1078
1223
  generation = 0;
1079
1224
  appSecret;
1225
+ /**
1226
+ * The Meta phone number id this backend sends as and answers for. Declared through
1227
+ * `WhatsAppBackend.phoneNumberId`, so an adapter holding this backend can refuse a signed message
1228
+ * addressed to another number of the same app.
1229
+ */
1230
+ phoneNumberId;
1231
+ /** Foreign phone number id endings already named on stderr, so each is reported once. */
1232
+ reportedForeignNumbers = /* @__PURE__ */ new Set();
1080
1233
  inboundHandler;
1081
1234
  statusHandler;
1082
1235
  constructor(opts) {
@@ -1087,6 +1240,7 @@ var WhatsAppCloudBackend = class {
1087
1240
  ...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
1088
1241
  });
1089
1242
  this.appSecret = opts.appSecret;
1243
+ this.phoneNumberId = opts.phoneNumberId;
1090
1244
  }
1091
1245
  // Cloud has no persistent connection — webhook is push, send is HTTP.
1092
1246
  /**
@@ -1192,26 +1346,74 @@ var WhatsAppCloudBackend = class {
1192
1346
  * Webhook entrypoint. The user calls this from inside their POST /webhook
1193
1347
  * route after `verifyWebhookSubscription` on GET.
1194
1348
  *
1195
- * @returns `true` if signature valid + dispatched (or empty payload).
1196
- * `false` if signature invalid (route should return 401).
1349
+ * Only messages addressed to this backend's `phoneNumberId` reach the inbound handler, and only
1350
+ * status receipts addressed to it reach the status handler. Meta signs every number of one app
1351
+ * with one secret and an app-level webhook URL receives every subscribed number, so a valid
1352
+ * signature does not say which number a message or receipt was for; one for another number, or
1353
+ * naming none, is dropped and its id written to stderr once (`isForAnotherNumber`, the rule
1354
+ * `WhatsAppAdapter` applies too).
1355
+ *
1356
+ * @returns `true` if the signature is valid and the body was dispatched (or held nothing to
1357
+ * dispatch). `false` if the signature is invalid (answer 401), or if the body holds a
1358
+ * message for this number while no inbound handler is subscribed (before `onInbound`,
1359
+ * or after `disconnect()`): the whole body is refused, never a part of it dropped, and
1360
+ * one line on stderr says which; answer non-2xx so Meta redelivers once a handler is
1361
+ * subscribed. `"unreadable_body"` if the signature is valid but the body is not JSON
1362
+ * or has a shape {@link parseWebhookPayload} refuses: nothing is dispatched and one
1363
+ * line on stderr says why. This is not forgery, and redelivery cannot recover it:
1364
+ * Meta resends the same bytes, which are refused again. Answer it differently from a
1365
+ * bad signature (the README example answers 200 so Meta stops retrying). Status receipts with no status handler subscribed
1366
+ * are discarded on purpose: subscribing to receipts is optional, and refusing them
1367
+ * would make Meta redeliver every receipt to a route that never wants one.
1368
+ * @throws {ConfigurationError} `missing_option` when this backend's `appSecret` is empty or
1369
+ * whitespace only: a signature under an empty key proves nothing.
1197
1370
  */
1198
1371
  async handleWebhookPayload(rawBody, signatureHeader) {
1199
1372
  if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {
1200
1373
  return false;
1201
1374
  }
1202
1375
  const json = this.parseBody(rawBody);
1203
- if (json === void 0) return false;
1376
+ if (json === void 0) return "unreadable_body";
1204
1377
  const envelope = parseWebhookPayload(json);
1205
- if (envelope === null) return true;
1206
- for (const event of normalizeInboundMessages(envelope)) {
1207
- if (this.inboundHandler === void 0) continue;
1208
- await this.dispatchContained(() => this.inboundHandler?.(event), "handler");
1378
+ if (envelope === null) {
1379
+ process.stderr.write(
1380
+ "[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"
1381
+ );
1382
+ return "unreadable_body";
1383
+ }
1384
+ const messages = normalizeInboundMessages(envelope).filter(
1385
+ (event) => !isForAnotherNumber(event, this.phoneNumberId, this.reportedForeignNumbers)
1386
+ );
1387
+ const inboundHandler = this.inboundHandler;
1388
+ if (messages.length > 0 && inboundHandler === void 0) {
1389
+ process.stderr.write(
1390
+ `[whatsapp-cloud] signed webhook body holds ${messages.length} message(s) for this number and no inbound handler is subscribed; refused whole, nothing dispatched
1391
+ `
1392
+ );
1393
+ return false;
1209
1394
  }
1395
+ if (inboundHandler !== void 0) await this.dispatchInbound(messages, inboundHandler);
1396
+ await this.dispatchStatusReceipts(envelope);
1397
+ return true;
1398
+ }
1399
+ /**
1400
+ * Hand each status receipt addressed to this backend's number to the status handler.
1401
+ *
1402
+ * Same rule as messages: a receipt names the recipient's phone number, so one number's receipts
1403
+ * reaching another number's handler hands one tenant's customer numbers to another tenant.
1404
+ */
1405
+ async dispatchStatusReceipts(envelope) {
1210
1406
  for (const receipt of normalizeStatusReceipts(envelope)) {
1211
1407
  if (this.statusHandler === void 0) continue;
1408
+ if (isForAnotherNumber(receipt, this.phoneNumberId, this.reportedForeignNumbers)) continue;
1212
1409
  await this.dispatchContained(() => this.statusHandler?.(receipt), "status handler");
1213
1410
  }
1214
- return true;
1411
+ }
1412
+ /** Hand each message, already scoped to this backend's number, to the inbound handler. */
1413
+ async dispatchInbound(messages, handler) {
1414
+ for (const event of messages) {
1415
+ await this.dispatchContained(() => handler(event), "handler");
1416
+ }
1215
1417
  }
1216
1418
  /**
1217
1419
  * Parse a signed webhook body, or report `undefined` when it is not JSON.
@@ -1619,6 +1821,28 @@ function defaultBridgeScriptPath() {
1619
1821
  }
1620
1822
  return found;
1621
1823
  }
1824
+
1825
+ // src/own-number.ts
1826
+ function decideForOwnNumber(inbound, ownPhoneNumberId, reported, rules) {
1827
+ if (isForAnotherNumber(inbound, ownPhoneNumberId, reported)) return void 0;
1828
+ return decideInbound(inbound, rules);
1829
+ }
1830
+ function requireOwnPhoneNumberId(ownPhoneNumberId, method) {
1831
+ if (ownPhoneNumberId !== void 0) return ownPhoneNumberId;
1832
+ throw new ConfigurationError({
1833
+ code: "missing_phone_number_id",
1834
+ 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.`
1835
+ });
1836
+ }
1837
+
1838
+ // src/refuse-attachments.ts
1839
+ function refuseAttachments(out) {
1840
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
1841
+ return {
1842
+ ok: false,
1843
+ error: { code: "attachments_unsupported", message: "whatsapp adapter cannot send attachments" }
1844
+ };
1845
+ }
1622
1846
  var WHATSAPP_MAX_TEXT = 4096;
1623
1847
  function splitForWhatsApp(text) {
1624
1848
  return gateway.chunkText(text, {
@@ -1627,7 +1851,8 @@ function splitForWhatsApp(text) {
1627
1851
  lastResort: "last-boundary",
1628
1852
  surrogateGuard: true,
1629
1853
  stripLeading: /^\s+/,
1630
- trimParts: true
1854
+ trimParts: true,
1855
+ keepTableRows: true
1631
1856
  });
1632
1857
  }
1633
1858
 
@@ -1642,20 +1867,28 @@ function requireNonEmpty(entries) {
1642
1867
  }
1643
1868
  }
1644
1869
  }
1645
- function digitsOnly(s) {
1646
- return s.replace(/[^\d]/g, "");
1647
- }
1648
- var PHONE_RUN = /[\d][\d+\-().  ]*[\d]|[\d]/g;
1649
- function phoneRuns(s) {
1650
- return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);
1651
- }
1652
1870
  var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter {
1653
1871
  platform = "whatsapp";
1654
1872
  backendImpl;
1655
- requireMention;
1873
+ /**
1874
+ * The bot's number, digits only. Kept as its own field because the documented construction
1875
+ * path is tested by reading it (`fromCloud` defaulting it to the phone number id).
1876
+ */
1656
1877
  botPhoneId;
1657
- /** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */
1658
- allowedSenders;
1878
+ /** The sender allowlist and group rule the inbound path decides by. */
1879
+ rules;
1880
+ /**
1881
+ * The Cloud phone number id this adapter answers for, read from the backend's declared
1882
+ * `phoneNumberId` at construction (so `fromCloud`, `new WhatsAppAdapter(new WhatsAppCloudBackend(...))`
1883
+ * and any backend declaring the field decide alike), `undefined` for a backend that declares none.
1884
+ * Meta signs every number of one app with one secret, so a signed message is only this adapter's
1885
+ * when its `phoneNumberId` is this one.
1886
+ */
1887
+ ownPhoneNumberId;
1888
+ /** Foreign phone number id endings already named on stderr, so each is reported once. */
1889
+ reportedForeignNumbers = /* @__PURE__ */ new Set();
1890
+ /** The rules both inbound paths share; `onInbound` skips the precondition (see `decideForOwnNumber`). */
1891
+ decide = (inbound) => decideForOwnNumber(inbound, this.ownPhoneNumberId, this.reportedForeignNumbers, this.rules);
1659
1892
  /** Mirrors the sibling adapters: guards connect() against opening a second session. */
1660
1893
  connected = false;
1661
1894
  handler;
@@ -1799,9 +2032,16 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1799
2032
  constructor(backendImpl, opts = {}) {
1800
2033
  super();
1801
2034
  this.backendImpl = backendImpl;
1802
- this.requireMention = opts.requireMention ?? true;
2035
+ this.ownPhoneNumberId = backendImpl.phoneNumberId;
1803
2036
  this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
1804
- this.allowedSenders = opts.allowedSenders === void 0 ? void 0 : parseAllowedSenders(opts.allowedSenders);
2037
+ this.rules = {
2038
+ requireMention: opts.requireMention ?? true,
2039
+ botPhoneId: this.botPhoneId,
2040
+ // Absent and empty are different answers. Absent means the operator has not adopted the
2041
+ // filter, and delivery is unchanged. Empty means they configured one and named nobody, which
2042
+ // is a decision — `parseAllowedSenders` is fail-closed and honours it.
2043
+ allowedSenders: opts.allowedSenders === void 0 ? void 0 : parseAllowedSenders(opts.allowedSenders)
2044
+ };
1805
2045
  }
1806
2046
  /** Escape hatch (D180-style) for advanced features. */
1807
2047
  getBackend() {
@@ -1824,6 +2064,9 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1824
2064
  await this.backendImpl.disconnect();
1825
2065
  }
1826
2066
  async sendMessage(out) {
2067
+ return refuseAttachments(out) ?? this.sendText(out);
2068
+ }
2069
+ async sendText(out) {
1827
2070
  if (out.text.length === 0) {
1828
2071
  return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
1829
2072
  }
@@ -1849,62 +2092,13 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1849
2092
  }
1850
2093
  return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
1851
2094
  }
1852
- /**
1853
- * Is this sender refused by a configured allowlist?
1854
- *
1855
- * Runs before the group/mention filter because it answers a different question: that one asks
1856
- * whether a message was meant for us, this one asks whether the sender may reach us at all.
1857
- *
1858
- * The refusal is logged. A silent drop is indistinguishable from a broken gateway, and the
1859
- * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
1860
- */
1861
- isRefusedBySenderAllowlist(inbound) {
1862
- if (inbound.fromSelf === true) return false;
1863
- if (this.allowedSenders === void 0) return false;
1864
- if (isSenderAllowed(inbound.fromPhone, this.allowedSenders)) return false;
1865
- process.stderr.write(
1866
- `[whatsapp] dropped inbound from "${inbound.fromPhone}" \u2014 not in the configured allowlist
1867
- `
1868
- );
1869
- return true;
1870
- }
1871
- /** D309 + EC-7: group filter with digit-only normalization. */
1872
- shouldDropGroupMessage(inbound) {
1873
- if (inbound.conversationType !== "group" || !this.requireMention) return false;
1874
- if (this.botPhoneId.length === 0) {
1875
- process.stderr.write(
1876
- "[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\n"
1877
- );
1878
- return true;
1879
- }
1880
- return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));
1881
- }
1882
- toMessageEvent(inbound) {
1883
- return {
1884
- id: inbound.wamid,
1885
- platform: "whatsapp",
1886
- sender: { id: inbound.fromPhone, displayName: inbound.contactName },
1887
- channel: { id: inbound.channelId, type: inbound.conversationType },
1888
- text: inbound.text,
1889
- receivedAt: inbound.receivedAt,
1890
- whatsapp: {
1891
- wamid: inbound.wamid,
1892
- phoneNumberId: inbound.phoneNumberId,
1893
- contactName: inbound.contactName,
1894
- channelJid: inbound.channelJid,
1895
- backend: inbound.backend,
1896
- raw: inbound.raw
1897
- }
1898
- };
1899
- }
1900
2095
  onInbound(handler) {
1901
2096
  this.inboundUnsubscribe?.();
1902
2097
  this.handler = handler;
1903
2098
  const off = this.backendImpl.onInbound(async (inbound) => {
1904
- if (!this.handler) return;
1905
- if (this.isRefusedBySenderAllowlist(inbound)) return;
1906
- if (this.shouldDropGroupMessage(inbound)) return;
1907
- await this.handler(this.toMessageEvent(inbound));
2099
+ const event = this.decide(inbound);
2100
+ if (event === void 0) return;
2101
+ await handler(event);
1908
2102
  });
1909
2103
  this.inboundUnsubscribe = off;
1910
2104
  return () => {
@@ -1915,11 +2109,67 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1915
2109
  }
1916
2110
  };
1917
2111
  }
1918
- /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
2112
+ /**
2113
+ * The event `onInbound` would hand its handler for this inbound message, or `undefined` when the
2114
+ * sender allowlist refuses it or the group rule drops it. A refusal writes the same stderr line
2115
+ * `onInbound` writes.
2116
+ *
2117
+ * It also drops a message addressed to another phone number id than the one the backend
2118
+ * declares (one app may serve several numbers under one secret), naming that id on stderr once.
2119
+ * A Cloud message on an adapter whose backend declares no `phoneNumberId` throws, as in
2120
+ * `toDeliverableEvents`; a WhatsApp Web or Baileys message has no number to compare.
2121
+ *
2122
+ * Pass the result to `deliver()`. Neither the backend nor the network is called.
2123
+ *
2124
+ * @throws {ConfigurationError} (`missing_phone_number_id`) for a Cloud message when the backend
2125
+ * declares no `phoneNumberId`.
2126
+ * @public
2127
+ */
2128
+ toDeliverableEvent(inbound) {
2129
+ if (inbound.backend === "cloud") {
2130
+ requireOwnPhoneNumberId(this.ownPhoneNumberId, "toDeliverableEvent");
2131
+ }
2132
+ return this.decide(inbound);
2133
+ }
2134
+ /**
2135
+ * The events of one Meta Cloud webhook envelope that may reach the agent, in envelope order, with
2136
+ * the sender allowlist and the group rule applied. Status receipts and non-text messages yield no
2137
+ * event, so a status-only envelope returns `[]`. Each refused or dropped message writes the
2138
+ * same stderr line `onInbound` writes. Messages addressed to another `phone_number_id` are
2139
+ * dropped (see `toDeliverableEvent`).
2140
+ *
2141
+ * The adapter's backend must declare its `phoneNumberId`. `fromCloud` and any
2142
+ * `WhatsAppCloudBackend` do; a backend that wraps one by delegation must expose the field too.
2143
+ * Without it there is no number to compare, and every number of the Meta app would reach this
2144
+ * adapter's agent, so this method fails closed instead (docs/adr/0006).
2145
+ *
2146
+ * The route that receives the webhook verifies `X-Hub-Signature-256` first (with
2147
+ * `verifyWebhookSignature`, or theokit's `whatsapp()` route validator); this method does not. Meta redelivers on timeout, and
2148
+ * `event.whatsapp.wamid` is the key a route can use to ignore a repeat. Neither the backend nor
2149
+ * the network is called.
2150
+ *
2151
+ * @throws {ConfigurationError} (`missing_phone_number_id`) when the backend declares no
2152
+ * `phoneNumberId`.
2153
+ * @public
2154
+ */
2155
+ toDeliverableEvents(envelope) {
2156
+ requireOwnPhoneNumberId(this.ownPhoneNumberId, "toDeliverableEvents");
2157
+ const events = [];
2158
+ for (const inbound of normalizeInboundMessages(envelope)) {
2159
+ const event = this.toDeliverableEvent(inbound);
2160
+ if (event !== void 0) events.push(event);
2161
+ }
2162
+ return events;
2163
+ }
2164
+ /**
2165
+ * Status receipts (sent/delivered/read/failed). Adapter-specific (D307). A receipt names the
2166
+ * customer's number, so one addressed to another phone number id is dropped, as messages are.
2167
+ */
1919
2168
  onStatusReceipt(handler) {
1920
2169
  this.statusUnsubscribe?.();
1921
2170
  this.statusHandler = handler;
1922
2171
  const off = this.backendImpl.onStatusReceipt(async (r) => {
2172
+ if (isForAnotherNumber(r, this.ownPhoneNumberId, this.reportedForeignNumbers)) return;
1923
2173
  await this.statusHandler?.(r);
1924
2174
  });
1925
2175
  this.statusUnsubscribe = off;