@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/CHANGELOG.md +166 -0
- package/README.md +118 -4
- package/dist/index.cjs +346 -96
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +241 -93
- package/dist/index.d.ts +241 -93
- package/dist/index.js +346 -96
- package/dist/index.js.map +1 -1
- package/package.json +18 -3
package/dist/index.js
CHANGED
|
@@ -756,6 +756,84 @@ 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 shouldDropGroupMessage(inbound, requireMention, botPhoneId) {
|
|
785
|
+
if (inbound.conversationType !== "group" || !requireMention) return false;
|
|
786
|
+
if (botPhoneId.length === 0) {
|
|
787
|
+
process.stderr.write(
|
|
788
|
+
"[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\n"
|
|
789
|
+
);
|
|
790
|
+
return true;
|
|
791
|
+
}
|
|
792
|
+
return !phoneRuns(inbound.text).some((run) => run.includes(botPhoneId));
|
|
793
|
+
}
|
|
794
|
+
function toMessageEvent(inbound) {
|
|
795
|
+
return {
|
|
796
|
+
id: inbound.wamid,
|
|
797
|
+
platform: "whatsapp",
|
|
798
|
+
sender: { id: inbound.fromPhone, displayName: inbound.contactName },
|
|
799
|
+
channel: { id: inbound.channelId, type: inbound.conversationType },
|
|
800
|
+
text: inbound.text,
|
|
801
|
+
receivedAt: inbound.receivedAt,
|
|
802
|
+
whatsapp: {
|
|
803
|
+
wamid: inbound.wamid,
|
|
804
|
+
phoneNumberId: inbound.phoneNumberId,
|
|
805
|
+
contactName: inbound.contactName,
|
|
806
|
+
channelJid: inbound.channelJid,
|
|
807
|
+
backend: inbound.backend,
|
|
808
|
+
raw: inbound.raw
|
|
809
|
+
}
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
function decideInbound(inbound, rules) {
|
|
813
|
+
if (isRefusedBySenderAllowlist(inbound, rules.allowedSenders)) return void 0;
|
|
814
|
+
if (shouldDropGroupMessage(inbound, rules.requireMention, rules.botPhoneId)) return void 0;
|
|
815
|
+
return toMessageEvent(inbound);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// src/foreign-number.ts
|
|
819
|
+
function redactedNumberId(phoneNumberId) {
|
|
820
|
+
if (phoneNumberId === void 0) return "no phone number id";
|
|
821
|
+
const tail = lastFourDigits(phoneNumberId);
|
|
822
|
+
return tail.length > 0 ? `a phone number id ending in ${tail}` : "a phone number id with no digits";
|
|
823
|
+
}
|
|
824
|
+
function isForAnotherNumber(inbound, ownPhoneNumberId, reported) {
|
|
825
|
+
if (ownPhoneNumberId === void 0 || inbound.phoneNumberId === ownPhoneNumberId) return false;
|
|
826
|
+
const other = redactedNumberId(inbound.phoneNumberId);
|
|
827
|
+
if (!reported.has(other)) {
|
|
828
|
+
reported.add(other);
|
|
829
|
+
process.stderr.write(
|
|
830
|
+
`[whatsapp] dropped inbound addressed to ${other}: this adapter answers for "${ownPhoneNumberId}". Logged once per id ending.
|
|
831
|
+
`
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
return true;
|
|
835
|
+
}
|
|
836
|
+
|
|
759
837
|
// src/backend/cloud/client.ts
|
|
760
838
|
var WhatsAppCloudClient = class {
|
|
761
839
|
constructor(opts) {
|
|
@@ -931,7 +1009,44 @@ var WhatsAppCloudClient = class {
|
|
|
931
1009
|
}
|
|
932
1010
|
}
|
|
933
1011
|
};
|
|
1012
|
+
function verifyWebhookSignature(rawBody, signatureHeader, appSecret) {
|
|
1013
|
+
if (appSecret.trim().length === 0) {
|
|
1014
|
+
throw new ConfigurationError({
|
|
1015
|
+
code: "missing_option",
|
|
1016
|
+
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."
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
if (signatureHeader === void 0) return false;
|
|
1020
|
+
if (!signatureHeader.startsWith("sha256=")) return false;
|
|
1021
|
+
const receivedHex = signatureHeader.slice(7);
|
|
1022
|
+
if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;
|
|
1023
|
+
const received = Buffer.from(receivedHex, "hex");
|
|
1024
|
+
const expected = crypto.createHmac("sha256", appSecret).update(rawBody).digest();
|
|
1025
|
+
if (received.length !== expected.length) return false;
|
|
1026
|
+
return crypto.timingSafeEqual(received, expected);
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// src/backend/cloud/webhook.ts
|
|
1030
|
+
var KNOWN_NON_TEXT_TYPES = /* @__PURE__ */ new Set([
|
|
1031
|
+
"audio",
|
|
1032
|
+
"button",
|
|
1033
|
+
"contacts",
|
|
1034
|
+
"document",
|
|
1035
|
+
"image",
|
|
1036
|
+
"interactive",
|
|
1037
|
+
"location",
|
|
1038
|
+
"order",
|
|
1039
|
+
"reaction",
|
|
1040
|
+
"request_welcome",
|
|
1041
|
+
"sticker",
|
|
1042
|
+
"system",
|
|
1043
|
+
"unsupported",
|
|
1044
|
+
"video"
|
|
1045
|
+
]);
|
|
934
1046
|
var warnedNonTextTypes = /* @__PURE__ */ new Set();
|
|
1047
|
+
function nonTextTypeLabel(type) {
|
|
1048
|
+
return typeof type === "string" && KNOWN_NON_TEXT_TYPES.has(type) ? type : "an unknown type";
|
|
1049
|
+
}
|
|
935
1050
|
function verifyWebhookSubscription(query, expectedVerifyToken) {
|
|
936
1051
|
const mode = query["hub.mode"];
|
|
937
1052
|
const token = query["hub.verify_token"];
|
|
@@ -941,22 +1056,50 @@ function verifyWebhookSubscription(query, expectedVerifyToken) {
|
|
|
941
1056
|
if (challenge === void 0 || challenge.length === 0) return null;
|
|
942
1057
|
return challenge;
|
|
943
1058
|
}
|
|
944
|
-
function
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
if (
|
|
953
|
-
return
|
|
1059
|
+
function isRecord(value) {
|
|
1060
|
+
return value !== null && typeof value === "object";
|
|
1061
|
+
}
|
|
1062
|
+
function isOptionalRecordArray(value) {
|
|
1063
|
+
return value === void 0 || Array.isArray(value) && value.every(isRecord);
|
|
1064
|
+
}
|
|
1065
|
+
function isWellFormedMetadata(metadata) {
|
|
1066
|
+
if (metadata === void 0 || metadata === null) return true;
|
|
1067
|
+
if (!isRecord(metadata)) return false;
|
|
1068
|
+
return metadata.phone_number_id === void 0 || typeof metadata.phone_number_id === "string";
|
|
1069
|
+
}
|
|
1070
|
+
function isReadableMessage(message) {
|
|
1071
|
+
if (message.type !== "text") return true;
|
|
1072
|
+
if (typeof message.id !== "string" || typeof message.from !== "string") return false;
|
|
1073
|
+
const text = message.text;
|
|
1074
|
+
return text === void 0 || isRecord(text) && typeof text.body === "string";
|
|
1075
|
+
}
|
|
1076
|
+
function isReadableContact(contact) {
|
|
1077
|
+
if (typeof contact.wa_id !== "string") return false;
|
|
1078
|
+
const profile = contact.profile;
|
|
1079
|
+
if (profile === void 0) return true;
|
|
1080
|
+
return isRecord(profile) && (profile.name === void 0 || typeof profile.name === "string");
|
|
1081
|
+
}
|
|
1082
|
+
function isReadableStatus(status) {
|
|
1083
|
+
return typeof status.id === "string" && typeof status.status === "string" && typeof status.recipient_id === "string";
|
|
1084
|
+
}
|
|
1085
|
+
function isOptionalReadableList(list, isReadable) {
|
|
1086
|
+
if (!isOptionalRecordArray(list)) return false;
|
|
1087
|
+
return list === void 0 || list.every(isReadable);
|
|
1088
|
+
}
|
|
1089
|
+
function isWellFormedValue(value) {
|
|
1090
|
+
if (value === void 0 || value === null) return true;
|
|
1091
|
+
if (!isRecord(value)) return false;
|
|
1092
|
+
return isWellFormedMetadata(value.metadata) && isOptionalReadableList(value.contacts, isReadableContact) && isOptionalReadableList(value.messages, isReadableMessage) && isOptionalReadableList(value.statuses, isReadableStatus);
|
|
1093
|
+
}
|
|
1094
|
+
function isWellFormedEntry(entry) {
|
|
1095
|
+
if (!isRecord(entry) || !Array.isArray(entry.changes)) return false;
|
|
1096
|
+
return entry.changes.every((change) => isRecord(change) && isWellFormedValue(change.value));
|
|
954
1097
|
}
|
|
955
1098
|
function parseWebhookPayload(json) {
|
|
956
|
-
if (json
|
|
957
|
-
|
|
958
|
-
if (
|
|
959
|
-
return
|
|
1099
|
+
if (!isRecord(json)) return null;
|
|
1100
|
+
if (json.object === void 0 || !Array.isArray(json.entry)) return null;
|
|
1101
|
+
if (!json.entry.every(isWellFormedEntry)) return null;
|
|
1102
|
+
return json;
|
|
960
1103
|
}
|
|
961
1104
|
function buildContactMap(value) {
|
|
962
1105
|
const map = /* @__PURE__ */ new Map();
|
|
@@ -982,10 +1125,11 @@ function normalizeInboundMessages(envelope) {
|
|
|
982
1125
|
}
|
|
983
1126
|
function normalizeOneMessage(msg, phoneNumberId, contactByWaId) {
|
|
984
1127
|
if (msg.type !== "text") {
|
|
985
|
-
|
|
986
|
-
|
|
1128
|
+
const label = nonTextTypeLabel(msg.type);
|
|
1129
|
+
if (!warnedNonTextTypes.has(label)) {
|
|
1130
|
+
warnedNonTextTypes.add(label);
|
|
987
1131
|
process.stderr.write(
|
|
988
|
-
`[whatsapp] ignoring ${
|
|
1132
|
+
`[whatsapp] ignoring ${label} message \u2014 v1 text-only (will be supported in v0.2+).
|
|
989
1133
|
`
|
|
990
1134
|
);
|
|
991
1135
|
}
|
|
@@ -1009,21 +1153,22 @@ function normalizeStatusReceipts(envelope) {
|
|
|
1009
1153
|
const out = [];
|
|
1010
1154
|
for (const entry of envelope.entry) {
|
|
1011
1155
|
for (const change of entry.changes) {
|
|
1012
|
-
const
|
|
1013
|
-
for (const s of statuses) {
|
|
1014
|
-
out.push(metaStatusToReceipt(s));
|
|
1156
|
+
const phoneNumberId = change.value?.metadata?.phone_number_id;
|
|
1157
|
+
for (const s of change.value?.statuses ?? []) {
|
|
1158
|
+
out.push(metaStatusToReceipt(s, phoneNumberId));
|
|
1015
1159
|
}
|
|
1016
1160
|
}
|
|
1017
1161
|
}
|
|
1018
1162
|
return out;
|
|
1019
1163
|
}
|
|
1020
|
-
function metaStatusToReceipt(s) {
|
|
1021
|
-
|
|
1164
|
+
function metaStatusToReceipt(s, phoneNumberId) {
|
|
1165
|
+
const receipt = {
|
|
1022
1166
|
wamid: s.id,
|
|
1023
1167
|
status: s.status,
|
|
1024
1168
|
recipient: s.recipient_id,
|
|
1025
1169
|
timestamp: Number(s.timestamp) * 1e3 || Date.now()
|
|
1026
1170
|
};
|
|
1171
|
+
return phoneNumberId === void 0 ? receipt : { ...receipt, phoneNumberId };
|
|
1027
1172
|
}
|
|
1028
1173
|
|
|
1029
1174
|
// src/backend/cloud/index.ts
|
|
@@ -1053,6 +1198,14 @@ var WhatsAppCloudBackend = class {
|
|
|
1053
1198
|
*/
|
|
1054
1199
|
generation = 0;
|
|
1055
1200
|
appSecret;
|
|
1201
|
+
/**
|
|
1202
|
+
* The Meta phone number id this backend sends as and answers for. Declared through
|
|
1203
|
+
* `WhatsAppBackend.phoneNumberId`, so an adapter holding this backend can refuse a signed message
|
|
1204
|
+
* addressed to another number of the same app.
|
|
1205
|
+
*/
|
|
1206
|
+
phoneNumberId;
|
|
1207
|
+
/** Foreign phone number id endings already named on stderr, so each is reported once. */
|
|
1208
|
+
reportedForeignNumbers = /* @__PURE__ */ new Set();
|
|
1056
1209
|
inboundHandler;
|
|
1057
1210
|
statusHandler;
|
|
1058
1211
|
constructor(opts) {
|
|
@@ -1063,6 +1216,7 @@ var WhatsAppCloudBackend = class {
|
|
|
1063
1216
|
...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
|
|
1064
1217
|
});
|
|
1065
1218
|
this.appSecret = opts.appSecret;
|
|
1219
|
+
this.phoneNumberId = opts.phoneNumberId;
|
|
1066
1220
|
}
|
|
1067
1221
|
// Cloud has no persistent connection — webhook is push, send is HTTP.
|
|
1068
1222
|
/**
|
|
@@ -1168,26 +1322,74 @@ var WhatsAppCloudBackend = class {
|
|
|
1168
1322
|
* Webhook entrypoint. The user calls this from inside their POST /webhook
|
|
1169
1323
|
* route after `verifyWebhookSubscription` on GET.
|
|
1170
1324
|
*
|
|
1171
|
-
*
|
|
1172
|
-
*
|
|
1325
|
+
* Only messages addressed to this backend's `phoneNumberId` reach the inbound handler, and only
|
|
1326
|
+
* status receipts addressed to it reach the status handler. Meta signs every number of one app
|
|
1327
|
+
* with one secret and an app-level webhook URL receives every subscribed number, so a valid
|
|
1328
|
+
* signature does not say which number a message or receipt was for; one for another number, or
|
|
1329
|
+
* naming none, is dropped and its id written to stderr once (`isForAnotherNumber`, the rule
|
|
1330
|
+
* `WhatsAppAdapter` applies too).
|
|
1331
|
+
*
|
|
1332
|
+
* @returns `true` if the signature is valid and the body was dispatched (or held nothing to
|
|
1333
|
+
* dispatch). `false` if the signature is invalid (answer 401), or if the body holds a
|
|
1334
|
+
* message for this number while no inbound handler is subscribed (before `onInbound`,
|
|
1335
|
+
* or after `disconnect()`): the whole body is refused, never a part of it dropped, and
|
|
1336
|
+
* one line on stderr says which; answer non-2xx so Meta redelivers once a handler is
|
|
1337
|
+
* subscribed. `"unreadable_body"` if the signature is valid but the body is not JSON
|
|
1338
|
+
* or has a shape {@link parseWebhookPayload} refuses: nothing is dispatched and one
|
|
1339
|
+
* line on stderr says why. This is not forgery, and redelivery cannot recover it:
|
|
1340
|
+
* Meta resends the same bytes, which are refused again. Answer it differently from a
|
|
1341
|
+
* bad signature (the README example answers 200 so Meta stops retrying). Status receipts with no status handler subscribed
|
|
1342
|
+
* are discarded on purpose: subscribing to receipts is optional, and refusing them
|
|
1343
|
+
* would make Meta redeliver every receipt to a route that never wants one.
|
|
1344
|
+
* @throws {ConfigurationError} `missing_option` when this backend's `appSecret` is empty or
|
|
1345
|
+
* whitespace only: a signature under an empty key proves nothing.
|
|
1173
1346
|
*/
|
|
1174
1347
|
async handleWebhookPayload(rawBody, signatureHeader) {
|
|
1175
1348
|
if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {
|
|
1176
1349
|
return false;
|
|
1177
1350
|
}
|
|
1178
1351
|
const json = this.parseBody(rawBody);
|
|
1179
|
-
if (json === void 0) return
|
|
1352
|
+
if (json === void 0) return "unreadable_body";
|
|
1180
1353
|
const envelope = parseWebhookPayload(json);
|
|
1181
|
-
if (envelope === null)
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1354
|
+
if (envelope === null) {
|
|
1355
|
+
process.stderr.write(
|
|
1356
|
+
"[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"
|
|
1357
|
+
);
|
|
1358
|
+
return "unreadable_body";
|
|
1359
|
+
}
|
|
1360
|
+
const messages = normalizeInboundMessages(envelope).filter(
|
|
1361
|
+
(event) => !isForAnotherNumber(event, this.phoneNumberId, this.reportedForeignNumbers)
|
|
1362
|
+
);
|
|
1363
|
+
const inboundHandler = this.inboundHandler;
|
|
1364
|
+
if (messages.length > 0 && inboundHandler === void 0) {
|
|
1365
|
+
process.stderr.write(
|
|
1366
|
+
`[whatsapp-cloud] signed webhook body holds ${messages.length} message(s) for this number and no inbound handler is subscribed; refused whole, nothing dispatched
|
|
1367
|
+
`
|
|
1368
|
+
);
|
|
1369
|
+
return false;
|
|
1185
1370
|
}
|
|
1371
|
+
if (inboundHandler !== void 0) await this.dispatchInbound(messages, inboundHandler);
|
|
1372
|
+
await this.dispatchStatusReceipts(envelope);
|
|
1373
|
+
return true;
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Hand each status receipt addressed to this backend's number to the status handler.
|
|
1377
|
+
*
|
|
1378
|
+
* Same rule as messages: a receipt names the recipient's phone number, so one number's receipts
|
|
1379
|
+
* reaching another number's handler hands one tenant's customer numbers to another tenant.
|
|
1380
|
+
*/
|
|
1381
|
+
async dispatchStatusReceipts(envelope) {
|
|
1186
1382
|
for (const receipt of normalizeStatusReceipts(envelope)) {
|
|
1187
1383
|
if (this.statusHandler === void 0) continue;
|
|
1384
|
+
if (isForAnotherNumber(receipt, this.phoneNumberId, this.reportedForeignNumbers)) continue;
|
|
1188
1385
|
await this.dispatchContained(() => this.statusHandler?.(receipt), "status handler");
|
|
1189
1386
|
}
|
|
1190
|
-
|
|
1387
|
+
}
|
|
1388
|
+
/** Hand each message, already scoped to this backend's number, to the inbound handler. */
|
|
1389
|
+
async dispatchInbound(messages, handler) {
|
|
1390
|
+
for (const event of messages) {
|
|
1391
|
+
await this.dispatchContained(() => handler(event), "handler");
|
|
1392
|
+
}
|
|
1191
1393
|
}
|
|
1192
1394
|
/**
|
|
1193
1395
|
* Parse a signed webhook body, or report `undefined` when it is not JSON.
|
|
@@ -1595,6 +1797,28 @@ function defaultBridgeScriptPath() {
|
|
|
1595
1797
|
}
|
|
1596
1798
|
return found;
|
|
1597
1799
|
}
|
|
1800
|
+
|
|
1801
|
+
// src/own-number.ts
|
|
1802
|
+
function decideForOwnNumber(inbound, ownPhoneNumberId, reported, rules) {
|
|
1803
|
+
if (isForAnotherNumber(inbound, ownPhoneNumberId, reported)) return void 0;
|
|
1804
|
+
return decideInbound(inbound, rules);
|
|
1805
|
+
}
|
|
1806
|
+
function requireOwnPhoneNumberId(ownPhoneNumberId, method) {
|
|
1807
|
+
if (ownPhoneNumberId !== void 0) return ownPhoneNumberId;
|
|
1808
|
+
throw new ConfigurationError({
|
|
1809
|
+
code: "missing_phone_number_id",
|
|
1810
|
+
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.`
|
|
1811
|
+
});
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
// src/refuse-attachments.ts
|
|
1815
|
+
function refuseAttachments(out) {
|
|
1816
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
1817
|
+
return {
|
|
1818
|
+
ok: false,
|
|
1819
|
+
error: { code: "attachments_unsupported", message: "whatsapp adapter cannot send attachments" }
|
|
1820
|
+
};
|
|
1821
|
+
}
|
|
1598
1822
|
var WHATSAPP_MAX_TEXT = 4096;
|
|
1599
1823
|
function splitForWhatsApp(text) {
|
|
1600
1824
|
return chunkText(text, {
|
|
@@ -1603,7 +1827,8 @@ function splitForWhatsApp(text) {
|
|
|
1603
1827
|
lastResort: "last-boundary",
|
|
1604
1828
|
surrogateGuard: true,
|
|
1605
1829
|
stripLeading: /^\s+/,
|
|
1606
|
-
trimParts: true
|
|
1830
|
+
trimParts: true,
|
|
1831
|
+
keepTableRows: true
|
|
1607
1832
|
});
|
|
1608
1833
|
}
|
|
1609
1834
|
|
|
@@ -1618,20 +1843,28 @@ function requireNonEmpty(entries) {
|
|
|
1618
1843
|
}
|
|
1619
1844
|
}
|
|
1620
1845
|
}
|
|
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
1846
|
var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
|
|
1629
1847
|
platform = "whatsapp";
|
|
1630
1848
|
backendImpl;
|
|
1631
|
-
|
|
1849
|
+
/**
|
|
1850
|
+
* The bot's number, digits only. Kept as its own field because the documented construction
|
|
1851
|
+
* path is tested by reading it (`fromCloud` defaulting it to the phone number id).
|
|
1852
|
+
*/
|
|
1632
1853
|
botPhoneId;
|
|
1633
|
-
/**
|
|
1634
|
-
|
|
1854
|
+
/** The sender allowlist and group rule the inbound path decides by. */
|
|
1855
|
+
rules;
|
|
1856
|
+
/**
|
|
1857
|
+
* The Cloud phone number id this adapter answers for, read from the backend's declared
|
|
1858
|
+
* `phoneNumberId` at construction (so `fromCloud`, `new WhatsAppAdapter(new WhatsAppCloudBackend(...))`
|
|
1859
|
+
* and any backend declaring the field decide alike), `undefined` for a backend that declares none.
|
|
1860
|
+
* Meta signs every number of one app with one secret, so a signed message is only this adapter's
|
|
1861
|
+
* when its `phoneNumberId` is this one.
|
|
1862
|
+
*/
|
|
1863
|
+
ownPhoneNumberId;
|
|
1864
|
+
/** Foreign phone number id endings already named on stderr, so each is reported once. */
|
|
1865
|
+
reportedForeignNumbers = /* @__PURE__ */ new Set();
|
|
1866
|
+
/** The rules both inbound paths share; `onInbound` skips the precondition (see `decideForOwnNumber`). */
|
|
1867
|
+
decide = (inbound) => decideForOwnNumber(inbound, this.ownPhoneNumberId, this.reportedForeignNumbers, this.rules);
|
|
1635
1868
|
/** Mirrors the sibling adapters: guards connect() against opening a second session. */
|
|
1636
1869
|
connected = false;
|
|
1637
1870
|
handler;
|
|
@@ -1775,9 +2008,16 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
|
|
|
1775
2008
|
constructor(backendImpl, opts = {}) {
|
|
1776
2009
|
super();
|
|
1777
2010
|
this.backendImpl = backendImpl;
|
|
1778
|
-
this.
|
|
2011
|
+
this.ownPhoneNumberId = backendImpl.phoneNumberId;
|
|
1779
2012
|
this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
|
|
1780
|
-
this.
|
|
2013
|
+
this.rules = {
|
|
2014
|
+
requireMention: opts.requireMention ?? true,
|
|
2015
|
+
botPhoneId: this.botPhoneId,
|
|
2016
|
+
// Absent and empty are different answers. Absent means the operator has not adopted the
|
|
2017
|
+
// filter, and delivery is unchanged. Empty means they configured one and named nobody, which
|
|
2018
|
+
// is a decision — `parseAllowedSenders` is fail-closed and honours it.
|
|
2019
|
+
allowedSenders: opts.allowedSenders === void 0 ? void 0 : parseAllowedSenders(opts.allowedSenders)
|
|
2020
|
+
};
|
|
1781
2021
|
}
|
|
1782
2022
|
/** Escape hatch (D180-style) for advanced features. */
|
|
1783
2023
|
getBackend() {
|
|
@@ -1800,6 +2040,9 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
|
|
|
1800
2040
|
await this.backendImpl.disconnect();
|
|
1801
2041
|
}
|
|
1802
2042
|
async sendMessage(out) {
|
|
2043
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
2044
|
+
}
|
|
2045
|
+
async sendText(out) {
|
|
1803
2046
|
if (out.text.length === 0) {
|
|
1804
2047
|
return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
|
|
1805
2048
|
}
|
|
@@ -1825,62 +2068,13 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
|
|
|
1825
2068
|
}
|
|
1826
2069
|
return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
|
|
1827
2070
|
}
|
|
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
2071
|
onInbound(handler) {
|
|
1877
2072
|
this.inboundUnsubscribe?.();
|
|
1878
2073
|
this.handler = handler;
|
|
1879
2074
|
const off = this.backendImpl.onInbound(async (inbound) => {
|
|
1880
|
-
|
|
1881
|
-
if (
|
|
1882
|
-
|
|
1883
|
-
await this.handler(this.toMessageEvent(inbound));
|
|
2075
|
+
const event = this.decide(inbound);
|
|
2076
|
+
if (event === void 0) return;
|
|
2077
|
+
await handler(event);
|
|
1884
2078
|
});
|
|
1885
2079
|
this.inboundUnsubscribe = off;
|
|
1886
2080
|
return () => {
|
|
@@ -1891,11 +2085,67 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
|
|
|
1891
2085
|
}
|
|
1892
2086
|
};
|
|
1893
2087
|
}
|
|
1894
|
-
/**
|
|
2088
|
+
/**
|
|
2089
|
+
* The event `onInbound` would hand its handler for this inbound message, or `undefined` when the
|
|
2090
|
+
* sender allowlist refuses it or the group rule drops it. A refusal writes the same stderr line
|
|
2091
|
+
* `onInbound` writes.
|
|
2092
|
+
*
|
|
2093
|
+
* It also drops a message addressed to another phone number id than the one the backend
|
|
2094
|
+
* declares (one app may serve several numbers under one secret), naming that id on stderr once.
|
|
2095
|
+
* A Cloud message on an adapter whose backend declares no `phoneNumberId` throws, as in
|
|
2096
|
+
* `toDeliverableEvents`; a WhatsApp Web or Baileys message has no number to compare.
|
|
2097
|
+
*
|
|
2098
|
+
* Pass the result to `deliver()`. Neither the backend nor the network is called.
|
|
2099
|
+
*
|
|
2100
|
+
* @throws {ConfigurationError} (`missing_phone_number_id`) for a Cloud message when the backend
|
|
2101
|
+
* declares no `phoneNumberId`.
|
|
2102
|
+
* @public
|
|
2103
|
+
*/
|
|
2104
|
+
toDeliverableEvent(inbound) {
|
|
2105
|
+
if (inbound.backend === "cloud") {
|
|
2106
|
+
requireOwnPhoneNumberId(this.ownPhoneNumberId, "toDeliverableEvent");
|
|
2107
|
+
}
|
|
2108
|
+
return this.decide(inbound);
|
|
2109
|
+
}
|
|
2110
|
+
/**
|
|
2111
|
+
* The events of one Meta Cloud webhook envelope that may reach the agent, in envelope order, with
|
|
2112
|
+
* the sender allowlist and the group rule applied. Status receipts and non-text messages yield no
|
|
2113
|
+
* event, so a status-only envelope returns `[]`. Each refused or dropped message writes the
|
|
2114
|
+
* same stderr line `onInbound` writes. Messages addressed to another `phone_number_id` are
|
|
2115
|
+
* dropped (see `toDeliverableEvent`).
|
|
2116
|
+
*
|
|
2117
|
+
* The adapter's backend must declare its `phoneNumberId`. `fromCloud` and any
|
|
2118
|
+
* `WhatsAppCloudBackend` do; a backend that wraps one by delegation must expose the field too.
|
|
2119
|
+
* Without it there is no number to compare, and every number of the Meta app would reach this
|
|
2120
|
+
* adapter's agent, so this method fails closed instead (docs/adr/0006).
|
|
2121
|
+
*
|
|
2122
|
+
* The route that receives the webhook verifies `X-Hub-Signature-256` first (with
|
|
2123
|
+
* `verifyWebhookSignature`, or theokit's `whatsapp()` route validator); this method does not. Meta redelivers on timeout, and
|
|
2124
|
+
* `event.whatsapp.wamid` is the key a route can use to ignore a repeat. Neither the backend nor
|
|
2125
|
+
* the network is called.
|
|
2126
|
+
*
|
|
2127
|
+
* @throws {ConfigurationError} (`missing_phone_number_id`) when the backend declares no
|
|
2128
|
+
* `phoneNumberId`.
|
|
2129
|
+
* @public
|
|
2130
|
+
*/
|
|
2131
|
+
toDeliverableEvents(envelope) {
|
|
2132
|
+
requireOwnPhoneNumberId(this.ownPhoneNumberId, "toDeliverableEvents");
|
|
2133
|
+
const events = [];
|
|
2134
|
+
for (const inbound of normalizeInboundMessages(envelope)) {
|
|
2135
|
+
const event = this.toDeliverableEvent(inbound);
|
|
2136
|
+
if (event !== void 0) events.push(event);
|
|
2137
|
+
}
|
|
2138
|
+
return events;
|
|
2139
|
+
}
|
|
2140
|
+
/**
|
|
2141
|
+
* Status receipts (sent/delivered/read/failed). Adapter-specific (D307). A receipt names the
|
|
2142
|
+
* customer's number, so one addressed to another phone number id is dropped, as messages are.
|
|
2143
|
+
*/
|
|
1895
2144
|
onStatusReceipt(handler) {
|
|
1896
2145
|
this.statusUnsubscribe?.();
|
|
1897
2146
|
this.statusHandler = handler;
|
|
1898
2147
|
const off = this.backendImpl.onStatusReceipt(async (r) => {
|
|
2148
|
+
if (isForAnotherNumber(r, this.ownPhoneNumberId, this.reportedForeignNumbers)) return;
|
|
1899
2149
|
await this.statusHandler?.(r);
|
|
1900
2150
|
});
|
|
1901
2151
|
this.statusUnsubscribe = off;
|