@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/CHANGELOG.md +148 -0
- package/README.md +115 -4
- package/dist/index.cjs +326 -94
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +224 -85
- package/dist/index.d.ts +224 -85
- package/dist/index.js +326 -94
- package/dist/index.js.map +1 -1
- package/package.json +19 -4
package/dist/index.cjs
CHANGED
|
@@ -780,6 +780,82 @@ 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 redactedNumberId(phoneNumberId) {
|
|
809
|
+
if (phoneNumberId === void 0) return "no phone number id";
|
|
810
|
+
const tail = lastFourDigits(phoneNumberId);
|
|
811
|
+
return tail.length > 0 ? `a phone number id ending in ${tail}` : "a phone number id with no digits";
|
|
812
|
+
}
|
|
813
|
+
function isForAnotherNumber(inbound, ownPhoneNumberId, reported) {
|
|
814
|
+
if (ownPhoneNumberId === void 0 || inbound.phoneNumberId === ownPhoneNumberId) return false;
|
|
815
|
+
const other = redactedNumberId(inbound.phoneNumberId);
|
|
816
|
+
if (!reported.has(other)) {
|
|
817
|
+
reported.add(other);
|
|
818
|
+
process.stderr.write(
|
|
819
|
+
`[whatsapp] dropped inbound addressed to ${other}: this adapter answers for "${ownPhoneNumberId}". Logged once per id ending.
|
|
820
|
+
`
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
return true;
|
|
824
|
+
}
|
|
825
|
+
function shouldDropGroupMessage(inbound, requireMention, botPhoneId) {
|
|
826
|
+
if (inbound.conversationType !== "group" || !requireMention) return false;
|
|
827
|
+
if (botPhoneId.length === 0) {
|
|
828
|
+
process.stderr.write(
|
|
829
|
+
"[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\n"
|
|
830
|
+
);
|
|
831
|
+
return true;
|
|
832
|
+
}
|
|
833
|
+
return !phoneRuns(inbound.text).some((run) => run.includes(botPhoneId));
|
|
834
|
+
}
|
|
835
|
+
function toMessageEvent(inbound) {
|
|
836
|
+
return {
|
|
837
|
+
id: inbound.wamid,
|
|
838
|
+
platform: "whatsapp",
|
|
839
|
+
sender: { id: inbound.fromPhone, displayName: inbound.contactName },
|
|
840
|
+
channel: { id: inbound.channelId, type: inbound.conversationType },
|
|
841
|
+
text: inbound.text,
|
|
842
|
+
receivedAt: inbound.receivedAt,
|
|
843
|
+
whatsapp: {
|
|
844
|
+
wamid: inbound.wamid,
|
|
845
|
+
phoneNumberId: inbound.phoneNumberId,
|
|
846
|
+
contactName: inbound.contactName,
|
|
847
|
+
channelJid: inbound.channelJid,
|
|
848
|
+
backend: inbound.backend,
|
|
849
|
+
raw: inbound.raw
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
function decideInbound(inbound, rules) {
|
|
854
|
+
if (isRefusedBySenderAllowlist(inbound, rules.allowedSenders)) return void 0;
|
|
855
|
+
if (shouldDropGroupMessage(inbound, rules.requireMention, rules.botPhoneId)) return void 0;
|
|
856
|
+
return toMessageEvent(inbound);
|
|
857
|
+
}
|
|
858
|
+
|
|
783
859
|
// src/backend/cloud/client.ts
|
|
784
860
|
var WhatsAppCloudClient = class {
|
|
785
861
|
constructor(opts) {
|
|
@@ -955,7 +1031,44 @@ var WhatsAppCloudClient = class {
|
|
|
955
1031
|
}
|
|
956
1032
|
}
|
|
957
1033
|
};
|
|
1034
|
+
function verifyWebhookSignature(rawBody, signatureHeader, appSecret) {
|
|
1035
|
+
if (appSecret.trim().length === 0) {
|
|
1036
|
+
throw new ConfigurationError({
|
|
1037
|
+
code: "missing_option",
|
|
1038
|
+
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."
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
if (signatureHeader === void 0) return false;
|
|
1042
|
+
if (!signatureHeader.startsWith("sha256=")) return false;
|
|
1043
|
+
const receivedHex = signatureHeader.slice(7);
|
|
1044
|
+
if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;
|
|
1045
|
+
const received = Buffer.from(receivedHex, "hex");
|
|
1046
|
+
const expected = crypto__namespace.createHmac("sha256", appSecret).update(rawBody).digest();
|
|
1047
|
+
if (received.length !== expected.length) return false;
|
|
1048
|
+
return crypto__namespace.timingSafeEqual(received, expected);
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
// src/backend/cloud/webhook.ts
|
|
1052
|
+
var KNOWN_NON_TEXT_TYPES = /* @__PURE__ */ new Set([
|
|
1053
|
+
"audio",
|
|
1054
|
+
"button",
|
|
1055
|
+
"contacts",
|
|
1056
|
+
"document",
|
|
1057
|
+
"image",
|
|
1058
|
+
"interactive",
|
|
1059
|
+
"location",
|
|
1060
|
+
"order",
|
|
1061
|
+
"reaction",
|
|
1062
|
+
"request_welcome",
|
|
1063
|
+
"sticker",
|
|
1064
|
+
"system",
|
|
1065
|
+
"unsupported",
|
|
1066
|
+
"video"
|
|
1067
|
+
]);
|
|
958
1068
|
var warnedNonTextTypes = /* @__PURE__ */ new Set();
|
|
1069
|
+
function nonTextTypeLabel(type) {
|
|
1070
|
+
return typeof type === "string" && KNOWN_NON_TEXT_TYPES.has(type) ? type : "an unknown type";
|
|
1071
|
+
}
|
|
959
1072
|
function verifyWebhookSubscription(query, expectedVerifyToken) {
|
|
960
1073
|
const mode = query["hub.mode"];
|
|
961
1074
|
const token = query["hub.verify_token"];
|
|
@@ -965,22 +1078,50 @@ function verifyWebhookSubscription(query, expectedVerifyToken) {
|
|
|
965
1078
|
if (challenge === void 0 || challenge.length === 0) return null;
|
|
966
1079
|
return challenge;
|
|
967
1080
|
}
|
|
968
|
-
function
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
if (
|
|
977
|
-
return
|
|
1081
|
+
function isRecord(value) {
|
|
1082
|
+
return value !== null && typeof value === "object";
|
|
1083
|
+
}
|
|
1084
|
+
function isOptionalRecordArray(value) {
|
|
1085
|
+
return value === void 0 || Array.isArray(value) && value.every(isRecord);
|
|
1086
|
+
}
|
|
1087
|
+
function isWellFormedMetadata(metadata) {
|
|
1088
|
+
if (metadata === void 0 || metadata === null) return true;
|
|
1089
|
+
if (!isRecord(metadata)) return false;
|
|
1090
|
+
return metadata.phone_number_id === void 0 || typeof metadata.phone_number_id === "string";
|
|
1091
|
+
}
|
|
1092
|
+
function isReadableMessage(message) {
|
|
1093
|
+
if (message.type !== "text") return true;
|
|
1094
|
+
if (typeof message.id !== "string" || typeof message.from !== "string") return false;
|
|
1095
|
+
const text = message.text;
|
|
1096
|
+
return text === void 0 || isRecord(text) && typeof text.body === "string";
|
|
1097
|
+
}
|
|
1098
|
+
function isReadableContact(contact) {
|
|
1099
|
+
if (typeof contact.wa_id !== "string") return false;
|
|
1100
|
+
const profile = contact.profile;
|
|
1101
|
+
if (profile === void 0) return true;
|
|
1102
|
+
return isRecord(profile) && (profile.name === void 0 || typeof profile.name === "string");
|
|
1103
|
+
}
|
|
1104
|
+
function isReadableStatus(status) {
|
|
1105
|
+
return typeof status.id === "string" && typeof status.status === "string" && typeof status.recipient_id === "string";
|
|
1106
|
+
}
|
|
1107
|
+
function isOptionalReadableList(list, isReadable) {
|
|
1108
|
+
if (!isOptionalRecordArray(list)) return false;
|
|
1109
|
+
return list === void 0 || list.every(isReadable);
|
|
1110
|
+
}
|
|
1111
|
+
function isWellFormedValue(value) {
|
|
1112
|
+
if (value === void 0 || value === null) return true;
|
|
1113
|
+
if (!isRecord(value)) return false;
|
|
1114
|
+
return isWellFormedMetadata(value.metadata) && isOptionalReadableList(value.contacts, isReadableContact) && isOptionalReadableList(value.messages, isReadableMessage) && isOptionalReadableList(value.statuses, isReadableStatus);
|
|
1115
|
+
}
|
|
1116
|
+
function isWellFormedEntry(entry) {
|
|
1117
|
+
if (!isRecord(entry) || !Array.isArray(entry.changes)) return false;
|
|
1118
|
+
return entry.changes.every((change) => isRecord(change) && isWellFormedValue(change.value));
|
|
978
1119
|
}
|
|
979
1120
|
function parseWebhookPayload(json) {
|
|
980
|
-
if (json
|
|
981
|
-
|
|
982
|
-
if (
|
|
983
|
-
return
|
|
1121
|
+
if (!isRecord(json)) return null;
|
|
1122
|
+
if (json.object === void 0 || !Array.isArray(json.entry)) return null;
|
|
1123
|
+
if (!json.entry.every(isWellFormedEntry)) return null;
|
|
1124
|
+
return json;
|
|
984
1125
|
}
|
|
985
1126
|
function buildContactMap(value) {
|
|
986
1127
|
const map = /* @__PURE__ */ new Map();
|
|
@@ -1006,10 +1147,11 @@ function normalizeInboundMessages(envelope) {
|
|
|
1006
1147
|
}
|
|
1007
1148
|
function normalizeOneMessage(msg, phoneNumberId, contactByWaId) {
|
|
1008
1149
|
if (msg.type !== "text") {
|
|
1009
|
-
|
|
1010
|
-
|
|
1150
|
+
const label = nonTextTypeLabel(msg.type);
|
|
1151
|
+
if (!warnedNonTextTypes.has(label)) {
|
|
1152
|
+
warnedNonTextTypes.add(label);
|
|
1011
1153
|
process.stderr.write(
|
|
1012
|
-
`[whatsapp] ignoring ${
|
|
1154
|
+
`[whatsapp] ignoring ${label} message \u2014 v1 text-only (will be supported in v0.2+).
|
|
1013
1155
|
`
|
|
1014
1156
|
);
|
|
1015
1157
|
}
|
|
@@ -1033,21 +1175,22 @@ function normalizeStatusReceipts(envelope) {
|
|
|
1033
1175
|
const out = [];
|
|
1034
1176
|
for (const entry of envelope.entry) {
|
|
1035
1177
|
for (const change of entry.changes) {
|
|
1036
|
-
const
|
|
1037
|
-
for (const s of statuses) {
|
|
1038
|
-
out.push(metaStatusToReceipt(s));
|
|
1178
|
+
const phoneNumberId = change.value?.metadata?.phone_number_id;
|
|
1179
|
+
for (const s of change.value?.statuses ?? []) {
|
|
1180
|
+
out.push(metaStatusToReceipt(s, phoneNumberId));
|
|
1039
1181
|
}
|
|
1040
1182
|
}
|
|
1041
1183
|
}
|
|
1042
1184
|
return out;
|
|
1043
1185
|
}
|
|
1044
|
-
function metaStatusToReceipt(s) {
|
|
1045
|
-
|
|
1186
|
+
function metaStatusToReceipt(s, phoneNumberId) {
|
|
1187
|
+
const receipt = {
|
|
1046
1188
|
wamid: s.id,
|
|
1047
1189
|
status: s.status,
|
|
1048
1190
|
recipient: s.recipient_id,
|
|
1049
1191
|
timestamp: Number(s.timestamp) * 1e3 || Date.now()
|
|
1050
1192
|
};
|
|
1193
|
+
return phoneNumberId === void 0 ? receipt : { ...receipt, phoneNumberId };
|
|
1051
1194
|
}
|
|
1052
1195
|
|
|
1053
1196
|
// src/backend/cloud/index.ts
|
|
@@ -1077,6 +1220,14 @@ var WhatsAppCloudBackend = class {
|
|
|
1077
1220
|
*/
|
|
1078
1221
|
generation = 0;
|
|
1079
1222
|
appSecret;
|
|
1223
|
+
/**
|
|
1224
|
+
* The Meta phone number id this backend sends as and answers for. Declared through
|
|
1225
|
+
* `WhatsAppBackend.phoneNumberId`, so an adapter holding this backend can refuse a signed message
|
|
1226
|
+
* addressed to another number of the same app.
|
|
1227
|
+
*/
|
|
1228
|
+
phoneNumberId;
|
|
1229
|
+
/** Foreign phone number id endings already named on stderr, so each is reported once. */
|
|
1230
|
+
reportedForeignNumbers = /* @__PURE__ */ new Set();
|
|
1080
1231
|
inboundHandler;
|
|
1081
1232
|
statusHandler;
|
|
1082
1233
|
constructor(opts) {
|
|
@@ -1087,6 +1238,7 @@ var WhatsAppCloudBackend = class {
|
|
|
1087
1238
|
...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
|
|
1088
1239
|
});
|
|
1089
1240
|
this.appSecret = opts.appSecret;
|
|
1241
|
+
this.phoneNumberId = opts.phoneNumberId;
|
|
1090
1242
|
}
|
|
1091
1243
|
// Cloud has no persistent connection — webhook is push, send is HTTP.
|
|
1092
1244
|
/**
|
|
@@ -1192,8 +1344,24 @@ var WhatsAppCloudBackend = class {
|
|
|
1192
1344
|
* Webhook entrypoint. The user calls this from inside their POST /webhook
|
|
1193
1345
|
* route after `verifyWebhookSubscription` on GET.
|
|
1194
1346
|
*
|
|
1195
|
-
*
|
|
1196
|
-
*
|
|
1347
|
+
* Only messages addressed to this backend's `phoneNumberId` reach the inbound handler, and only
|
|
1348
|
+
* status receipts addressed to it reach the status handler. Meta signs every number of one app
|
|
1349
|
+
* with one secret and an app-level webhook URL receives every subscribed number, so a valid
|
|
1350
|
+
* signature does not say which number a message or receipt was for; one for another number, or
|
|
1351
|
+
* naming none, is dropped and its id written to stderr once (`isForAnotherNumber`, the rule
|
|
1352
|
+
* `WhatsAppAdapter` applies too).
|
|
1353
|
+
*
|
|
1354
|
+
* @returns `true` if the signature is valid and the body was dispatched (or held nothing to
|
|
1355
|
+
* dispatch). `false` if the signature is invalid, if the signed body is not JSON or
|
|
1356
|
+
* has a shape {@link parseWebhookPayload} refuses, or if it holds a message for this
|
|
1357
|
+
* number while no inbound handler is subscribed (before `onInbound`, or after
|
|
1358
|
+
* `disconnect()`): the whole body is refused, never a part of it dropped, and one line
|
|
1359
|
+
* on stderr says which. Answer `false` with a non-2xx (401 for a bad signature) so the
|
|
1360
|
+
* drop is seen and Meta redelivers. Status receipts with no status handler subscribed
|
|
1361
|
+
* are discarded on purpose: subscribing to receipts is optional, and refusing them
|
|
1362
|
+
* would make Meta redeliver every receipt to a route that never wants one.
|
|
1363
|
+
* @throws {ConfigurationError} `missing_option` when this backend's `appSecret` is empty or
|
|
1364
|
+
* whitespace only: a signature under an empty key proves nothing.
|
|
1197
1365
|
*/
|
|
1198
1366
|
async handleWebhookPayload(rawBody, signatureHeader) {
|
|
1199
1367
|
if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {
|
|
@@ -1202,16 +1370,45 @@ var WhatsAppCloudBackend = class {
|
|
|
1202
1370
|
const json = this.parseBody(rawBody);
|
|
1203
1371
|
if (json === void 0) return false;
|
|
1204
1372
|
const envelope = parseWebhookPayload(json);
|
|
1205
|
-
if (envelope === null)
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1373
|
+
if (envelope === null) {
|
|
1374
|
+
process.stderr.write(
|
|
1375
|
+
"[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"
|
|
1376
|
+
);
|
|
1377
|
+
return false;
|
|
1378
|
+
}
|
|
1379
|
+
const messages = normalizeInboundMessages(envelope).filter(
|
|
1380
|
+
(event) => !isForAnotherNumber(event, this.phoneNumberId, this.reportedForeignNumbers)
|
|
1381
|
+
);
|
|
1382
|
+
const inboundHandler = this.inboundHandler;
|
|
1383
|
+
if (messages.length > 0 && inboundHandler === void 0) {
|
|
1384
|
+
process.stderr.write(
|
|
1385
|
+
`[whatsapp-cloud] signed webhook body holds ${messages.length} message(s) for this number and no inbound handler is subscribed; refused whole, nothing dispatched
|
|
1386
|
+
`
|
|
1387
|
+
);
|
|
1388
|
+
return false;
|
|
1209
1389
|
}
|
|
1390
|
+
if (inboundHandler !== void 0) await this.dispatchInbound(messages, inboundHandler);
|
|
1391
|
+
await this.dispatchStatusReceipts(envelope);
|
|
1392
|
+
return true;
|
|
1393
|
+
}
|
|
1394
|
+
/**
|
|
1395
|
+
* Hand each status receipt addressed to this backend's number to the status handler.
|
|
1396
|
+
*
|
|
1397
|
+
* Same rule as messages: a receipt names the recipient's phone number, so one number's receipts
|
|
1398
|
+
* reaching another number's handler hands one tenant's customer numbers to another tenant.
|
|
1399
|
+
*/
|
|
1400
|
+
async dispatchStatusReceipts(envelope) {
|
|
1210
1401
|
for (const receipt of normalizeStatusReceipts(envelope)) {
|
|
1211
1402
|
if (this.statusHandler === void 0) continue;
|
|
1403
|
+
if (isForAnotherNumber(receipt, this.phoneNumberId, this.reportedForeignNumbers)) continue;
|
|
1212
1404
|
await this.dispatchContained(() => this.statusHandler?.(receipt), "status handler");
|
|
1213
1405
|
}
|
|
1214
|
-
|
|
1406
|
+
}
|
|
1407
|
+
/** Hand each message, already scoped to this backend's number, to the inbound handler. */
|
|
1408
|
+
async dispatchInbound(messages, handler) {
|
|
1409
|
+
for (const event of messages) {
|
|
1410
|
+
await this.dispatchContained(() => handler(event), "handler");
|
|
1411
|
+
}
|
|
1215
1412
|
}
|
|
1216
1413
|
/**
|
|
1217
1414
|
* Parse a signed webhook body, or report `undefined` when it is not JSON.
|
|
@@ -1619,6 +1816,19 @@ function defaultBridgeScriptPath() {
|
|
|
1619
1816
|
}
|
|
1620
1817
|
return found;
|
|
1621
1818
|
}
|
|
1819
|
+
|
|
1820
|
+
// src/own-number.ts
|
|
1821
|
+
function decideForOwnNumber(inbound, ownPhoneNumberId, reported, rules) {
|
|
1822
|
+
if (isForAnotherNumber(inbound, ownPhoneNumberId, reported)) return void 0;
|
|
1823
|
+
return decideInbound(inbound, rules);
|
|
1824
|
+
}
|
|
1825
|
+
function requireOwnPhoneNumberId(ownPhoneNumberId, method) {
|
|
1826
|
+
if (ownPhoneNumberId !== void 0) return ownPhoneNumberId;
|
|
1827
|
+
throw new ConfigurationError({
|
|
1828
|
+
code: "missing_phone_number_id",
|
|
1829
|
+
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.`
|
|
1830
|
+
});
|
|
1831
|
+
}
|
|
1622
1832
|
var WHATSAPP_MAX_TEXT = 4096;
|
|
1623
1833
|
function splitForWhatsApp(text) {
|
|
1624
1834
|
return gateway.chunkText(text, {
|
|
@@ -1642,20 +1852,28 @@ function requireNonEmpty(entries) {
|
|
|
1642
1852
|
}
|
|
1643
1853
|
}
|
|
1644
1854
|
}
|
|
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
1855
|
var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter {
|
|
1653
1856
|
platform = "whatsapp";
|
|
1654
1857
|
backendImpl;
|
|
1655
|
-
|
|
1858
|
+
/**
|
|
1859
|
+
* The bot's number, digits only. Kept as its own field because the documented construction
|
|
1860
|
+
* path is tested by reading it (`fromCloud` defaulting it to the phone number id).
|
|
1861
|
+
*/
|
|
1656
1862
|
botPhoneId;
|
|
1657
|
-
/**
|
|
1658
|
-
|
|
1863
|
+
/** The sender allowlist and group rule the inbound path decides by. */
|
|
1864
|
+
rules;
|
|
1865
|
+
/**
|
|
1866
|
+
* The Cloud phone number id this adapter answers for, read from the backend's declared
|
|
1867
|
+
* `phoneNumberId` at construction (so `fromCloud`, `new WhatsAppAdapter(new WhatsAppCloudBackend(...))`
|
|
1868
|
+
* and any backend declaring the field decide alike), `undefined` for a backend that declares none.
|
|
1869
|
+
* Meta signs every number of one app with one secret, so a signed message is only this adapter's
|
|
1870
|
+
* when its `phoneNumberId` is this one.
|
|
1871
|
+
*/
|
|
1872
|
+
ownPhoneNumberId;
|
|
1873
|
+
/** Foreign phone number id endings already named on stderr, so each is reported once. */
|
|
1874
|
+
reportedForeignNumbers = /* @__PURE__ */ new Set();
|
|
1875
|
+
/** The rules both inbound paths share; `onInbound` skips the precondition (see `decideForOwnNumber`). */
|
|
1876
|
+
decide = (inbound) => decideForOwnNumber(inbound, this.ownPhoneNumberId, this.reportedForeignNumbers, this.rules);
|
|
1659
1877
|
/** Mirrors the sibling adapters: guards connect() against opening a second session. */
|
|
1660
1878
|
connected = false;
|
|
1661
1879
|
handler;
|
|
@@ -1799,9 +2017,16 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
|
|
|
1799
2017
|
constructor(backendImpl, opts = {}) {
|
|
1800
2018
|
super();
|
|
1801
2019
|
this.backendImpl = backendImpl;
|
|
1802
|
-
this.
|
|
2020
|
+
this.ownPhoneNumberId = backendImpl.phoneNumberId;
|
|
1803
2021
|
this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
|
|
1804
|
-
this.
|
|
2022
|
+
this.rules = {
|
|
2023
|
+
requireMention: opts.requireMention ?? true,
|
|
2024
|
+
botPhoneId: this.botPhoneId,
|
|
2025
|
+
// Absent and empty are different answers. Absent means the operator has not adopted the
|
|
2026
|
+
// filter, and delivery is unchanged. Empty means they configured one and named nobody, which
|
|
2027
|
+
// is a decision — `parseAllowedSenders` is fail-closed and honours it.
|
|
2028
|
+
allowedSenders: opts.allowedSenders === void 0 ? void 0 : parseAllowedSenders(opts.allowedSenders)
|
|
2029
|
+
};
|
|
1805
2030
|
}
|
|
1806
2031
|
/** Escape hatch (D180-style) for advanced features. */
|
|
1807
2032
|
getBackend() {
|
|
@@ -1849,62 +2074,13 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
|
|
|
1849
2074
|
}
|
|
1850
2075
|
return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
|
|
1851
2076
|
}
|
|
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
2077
|
onInbound(handler) {
|
|
1901
2078
|
this.inboundUnsubscribe?.();
|
|
1902
2079
|
this.handler = handler;
|
|
1903
2080
|
const off = this.backendImpl.onInbound(async (inbound) => {
|
|
1904
|
-
|
|
1905
|
-
if (
|
|
1906
|
-
|
|
1907
|
-
await this.handler(this.toMessageEvent(inbound));
|
|
2081
|
+
const event = this.decide(inbound);
|
|
2082
|
+
if (event === void 0) return;
|
|
2083
|
+
await handler(event);
|
|
1908
2084
|
});
|
|
1909
2085
|
this.inboundUnsubscribe = off;
|
|
1910
2086
|
return () => {
|
|
@@ -1915,11 +2091,67 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
|
|
|
1915
2091
|
}
|
|
1916
2092
|
};
|
|
1917
2093
|
}
|
|
1918
|
-
/**
|
|
2094
|
+
/**
|
|
2095
|
+
* The event `onInbound` would hand its handler for this inbound message, or `undefined` when the
|
|
2096
|
+
* sender allowlist refuses it or the group rule drops it. A refusal writes the same stderr line
|
|
2097
|
+
* `onInbound` writes.
|
|
2098
|
+
*
|
|
2099
|
+
* It also drops a message addressed to another phone number id than the one the backend
|
|
2100
|
+
* declares (one app may serve several numbers under one secret), naming that id on stderr once.
|
|
2101
|
+
* A Cloud message on an adapter whose backend declares no `phoneNumberId` throws, as in
|
|
2102
|
+
* `toDeliverableEvents`; a WhatsApp Web or Baileys message has no number to compare.
|
|
2103
|
+
*
|
|
2104
|
+
* Pass the result to `deliver()`. Neither the backend nor the network is called.
|
|
2105
|
+
*
|
|
2106
|
+
* @throws {ConfigurationError} (`missing_phone_number_id`) for a Cloud message when the backend
|
|
2107
|
+
* declares no `phoneNumberId`.
|
|
2108
|
+
* @public
|
|
2109
|
+
*/
|
|
2110
|
+
toDeliverableEvent(inbound) {
|
|
2111
|
+
if (inbound.backend === "cloud") {
|
|
2112
|
+
requireOwnPhoneNumberId(this.ownPhoneNumberId, "toDeliverableEvent");
|
|
2113
|
+
}
|
|
2114
|
+
return this.decide(inbound);
|
|
2115
|
+
}
|
|
2116
|
+
/**
|
|
2117
|
+
* The events of one Meta Cloud webhook envelope that may reach the agent, in envelope order, with
|
|
2118
|
+
* the sender allowlist and the group rule applied. Status receipts and non-text messages yield no
|
|
2119
|
+
* event, so a status-only envelope returns `[]`. Each refused or dropped message writes the
|
|
2120
|
+
* same stderr line `onInbound` writes. Messages addressed to another `phone_number_id` are
|
|
2121
|
+
* dropped (see `toDeliverableEvent`).
|
|
2122
|
+
*
|
|
2123
|
+
* The adapter's backend must declare its `phoneNumberId`. `fromCloud` and any
|
|
2124
|
+
* `WhatsAppCloudBackend` do; a backend that wraps one by delegation must expose the field too.
|
|
2125
|
+
* Without it there is no number to compare, and every number of the Meta app would reach this
|
|
2126
|
+
* adapter's agent, so this method fails closed instead (docs/adr/0006).
|
|
2127
|
+
*
|
|
2128
|
+
* The route that receives the webhook verifies `X-Hub-Signature-256` first (with
|
|
2129
|
+
* `verifyWebhookSignature`, or theokit's `whatsapp()` route validator); this method does not. Meta redelivers on timeout, and
|
|
2130
|
+
* `event.whatsapp.wamid` is the key a route can use to ignore a repeat. Neither the backend nor
|
|
2131
|
+
* the network is called.
|
|
2132
|
+
*
|
|
2133
|
+
* @throws {ConfigurationError} (`missing_phone_number_id`) when the backend declares no
|
|
2134
|
+
* `phoneNumberId`.
|
|
2135
|
+
* @public
|
|
2136
|
+
*/
|
|
2137
|
+
toDeliverableEvents(envelope) {
|
|
2138
|
+
requireOwnPhoneNumberId(this.ownPhoneNumberId, "toDeliverableEvents");
|
|
2139
|
+
const events = [];
|
|
2140
|
+
for (const inbound of normalizeInboundMessages(envelope)) {
|
|
2141
|
+
const event = this.toDeliverableEvent(inbound);
|
|
2142
|
+
if (event !== void 0) events.push(event);
|
|
2143
|
+
}
|
|
2144
|
+
return events;
|
|
2145
|
+
}
|
|
2146
|
+
/**
|
|
2147
|
+
* Status receipts (sent/delivered/read/failed). Adapter-specific (D307). A receipt names the
|
|
2148
|
+
* customer's number, so one addressed to another phone number id is dropped, as messages are.
|
|
2149
|
+
*/
|
|
1919
2150
|
onStatusReceipt(handler) {
|
|
1920
2151
|
this.statusUnsubscribe?.();
|
|
1921
2152
|
this.statusHandler = handler;
|
|
1922
2153
|
const off = this.backendImpl.onStatusReceipt(async (r) => {
|
|
2154
|
+
if (isForAnotherNumber(r, this.ownPhoneNumberId, this.reportedForeignNumbers)) return;
|
|
1923
2155
|
await this.statusHandler?.(r);
|
|
1924
2156
|
});
|
|
1925
2157
|
this.statusUnsubscribe = off;
|