@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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,153 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 72cc72d: Add `WhatsAppAdapter.toDeliverableEvents(envelope)` and `WhatsAppAdapter.toDeliverableEvent(inbound)`,
|
|
8
|
+
and export the `MetaWebhookEnvelope` type from the package entry.
|
|
9
|
+
|
|
10
|
+
An application that hosts its own WhatsApp Cloud webhook route could parse Meta's envelope, but had
|
|
11
|
+
no public way to turn it into the event `deliver()` accepts with the adapter's sender allowlist and
|
|
12
|
+
group-mention rule applied: the conversion was private and the rules ran only inside `onInbound`. A
|
|
13
|
+
route that copied the private conversion would have admitted every sender the operator refused.
|
|
14
|
+
`toDeliverableEvents` returns the accepted events of an envelope in order, and `onInbound` now
|
|
15
|
+
decides through `toDeliverableEvent`, so both paths apply one rule set and write the same refusal
|
|
16
|
+
line. Neither method calls the backend or the network, and neither verifies the webhook signature;
|
|
17
|
+
the route still does that first. The README's "How inbound arrives" shows the route end to end.
|
|
18
|
+
|
|
19
|
+
Two behaviours change on every inbound path, `onInbound` included. An adapter built with
|
|
20
|
+
`fromCloud` drops a message addressed to another `phone_number_id`, naming that id on stderr once,
|
|
21
|
+
because one Meta app signs every number's webhooks with the same secret. The allowlist refusal line
|
|
22
|
+
names the sender by the last four digits of the number only (`a sender ending in 8888`), where it
|
|
23
|
+
used to print the whole number. `toDeliverableEvents` throws `ConfigurationError`
|
|
24
|
+
(`missing_phone_number_id`) when the adapter's backend declares no `phoneNumberId`, so a backend
|
|
25
|
+
that wraps `WhatsAppCloudBackend` must expose the field instead of silently receiving every
|
|
26
|
+
number's messages.
|
|
27
|
+
|
|
28
|
+
No existing export changes.
|
|
29
|
+
|
|
30
|
+
- 5b14d8d: `WhatsAppStatusReceipt` gains an optional `phoneNumberId`: the `phone_number_id` a Cloud receipt was
|
|
31
|
+
addressed to, read from the webhook's `metadata`. `normalizeStatusReceipts` fills it; the web and
|
|
32
|
+
Baileys backends leave it absent.
|
|
33
|
+
|
|
34
|
+
`WhatsAppCloudBackend.handleWebhookPayload` now applies the own-number rule to status receipts as
|
|
35
|
+
well as to messages. Before, a receipt addressed to another number of the same Meta app, or naming
|
|
36
|
+
no number, still reached `onStatusReceipt`, and a receipt names the recipient's phone number, so in
|
|
37
|
+
a multi-number app one number's handler received another number's customer numbers. Such a receipt
|
|
38
|
+
is now dropped and its number id written to stderr once, as a message already was.
|
|
39
|
+
|
|
40
|
+
The README's Cloud route skips any receipt whose `phoneNumberId` is not the route's own number.
|
|
41
|
+
Additive: no existing field changes.
|
|
42
|
+
|
|
43
|
+
### Patch Changes
|
|
44
|
+
|
|
45
|
+
- 7eae6a1: `WhatsAppAdapter` now delivers every message of a signed Cloud batch to the inbound handler that
|
|
46
|
+
was subscribed when the batch arrived. The backend already did this, but the adapter looked up its
|
|
47
|
+
current handler again for each message, so a `disconnect()` or an unsubscribe inside the handler of
|
|
48
|
+
the first message dropped the rest of the batch while the webhook still answered 200, and Meta did
|
|
49
|
+
not redeliver the dropped messages. A batch that arrives after the unsubscribe still reaches no one.
|
|
50
|
+
- a748c4e: `WhatsAppAdapter.onStatusReceipt` drops a status receipt addressed to another phone number id when
|
|
51
|
+
the adapter's backend declares its `phoneNumberId`, as the adapter already did for messages, and
|
|
52
|
+
names that id once on stderr by its last four digits. Before, a custom backend that declared its
|
|
53
|
+
number had its messages scoped and its receipts forwarded whole, so one number's receipt handler
|
|
54
|
+
saw the customer numbers of another number on the same Meta app. A backend that declares no number
|
|
55
|
+
forwards every receipt, as before.
|
|
56
|
+
- fc65200: `WhatsAppBackend` gains an optional `phoneNumberId`, the Meta Cloud phone number id the backend
|
|
57
|
+
answers for. `WhatsAppAdapter` now reads that field to decide whether a message is addressed to
|
|
58
|
+
another number of the same Meta app, instead of checking whether the backend is an instance of
|
|
59
|
+
`WhatsAppCloudBackend`. Before, a wrapped Cloud backend, a test double, or a `WhatsAppCloudBackend`
|
|
60
|
+
loaded from the package's other module format (ESM beside CJS) lost the check without a word, and
|
|
61
|
+
another number's messages reached the agent. A custom backend that declares `phoneNumberId` now
|
|
62
|
+
gets the same check; one that declares none behaves as before.
|
|
63
|
+
- 646e0ae: An adapter constructed with `new WhatsAppAdapter(new WhatsAppCloudBackend(...))` now drops a
|
|
64
|
+
message addressed to another `phone_number_id`, as an adapter built with `fromCloud` already did.
|
|
65
|
+
Before, the check depended on which construction path built the adapter, so the same Cloud backend
|
|
66
|
+
admitted another number's messages when the adapter was constructed directly.
|
|
67
|
+
`WhatsAppCloudBackend.handleWebhookPayload` applies the same rule, so a route built on the backend
|
|
68
|
+
alone, with no adapter, no longer hands its inbound handler a message addressed to another number
|
|
69
|
+
of the same Meta app or naming no number.
|
|
70
|
+
`WhatsAppCloudBackend` exposes the number it answers for as `phoneNumberId`.
|
|
71
|
+
- a145874: `WhatsAppCloudBackend.handleWebhookPayload` delivers every message of a signed batch to the inbound
|
|
72
|
+
handler that was subscribed when the batch arrived. Before, the handler was looked up again for each
|
|
73
|
+
message, so a `disconnect()` or an unsubscribe inside the handler of the first message skipped the
|
|
74
|
+
rest of the batch with nothing on stderr, and the method still answered `true`: the route answered
|
|
75
|
+
200 and Meta did not redeliver the skipped messages.
|
|
76
|
+
- 0c09b14: `WhatsAppCloudBackend.handleWebhookPayload` answers `false` for a signed body that holds a message
|
|
77
|
+
for the backend's number while no inbound handler is subscribed (before `onInbound`, or after
|
|
78
|
+
`disconnect()` cleared it), dispatches nothing and writes one line to stderr naming the count.
|
|
79
|
+
Before, it answered `true`, so a route answered 200, Meta did not redeliver, and the messages were
|
|
80
|
+
lost with nothing logged. Status receipts with no status handler are still discarded, and a body
|
|
81
|
+
whose messages are all for another number still answers `true`.
|
|
82
|
+
- 9778690: `parseWebhookPayload` returns `null` for a Cloud webhook body with a contact whose `wa_id` or
|
|
83
|
+
`profile.name` is not a string, or a status whose `id`, `status` or `recipient_id` is not a string.
|
|
84
|
+
Before, a contact name of `42` reached the agent as `sender.displayName` 42, and a status with a
|
|
85
|
+
numeric `id` became a receipt whose `wamid` was a number, though both fields are typed as strings.
|
|
86
|
+
`WhatsAppCloudBackend.handleWebhookPayload` answers `false` for such a body and dispatches nothing,
|
|
87
|
+
as it already does for the other shapes the parser refuses.
|
|
88
|
+
- 3a249c3: `verifyWebhookSignature` now throws `ConfigurationError` with code `missing_option` when the app
|
|
89
|
+
secret is empty or whitespace only, instead of checking the signature against it. Anyone can
|
|
90
|
+
compute an HMAC under an empty key, so a webhook route built on an outbound-only adapter
|
|
91
|
+
(`appSecret: ""`) accepted forged envelopes, and a forged envelope can name any allowed sender.
|
|
92
|
+
`WhatsAppCloudBackend.handleWebhookPayload` goes through the same check and now rejects in that
|
|
93
|
+
case. `fromCloud` still accepts an empty `appSecret` for an adapter that only sends. The README
|
|
94
|
+
route now says the secret must be non-empty.
|
|
95
|
+
- 08157ca: The stderr line written when a message addressed to another `phone_number_id` is dropped now names
|
|
96
|
+
that id by its last four digits, the way the allowlist refusal already names a sender, and names a
|
|
97
|
+
message with no id as `no phone number id`. Before, the line carried the id exactly as the
|
|
98
|
+
envelope gave it, so a route that hands `toDeliverableEvents` an unverified body could write a
|
|
99
|
+
forged line through it, and every distinct id was kept in memory for the life of the adapter. The
|
|
100
|
+
set of ids already reported now holds at most one entry per four-digit ending. A log query that
|
|
101
|
+
matched `phone number id "<id>"` needs to match `phone number id ending in <last four digits>`.
|
|
102
|
+
- bc1357c: The stderr line written when a Cloud message that is not text is ignored now names its type only
|
|
103
|
+
when the type is one Meta documents (`image`, `audio`, `sticker` and the rest); any other value is
|
|
104
|
+
named `an unknown type`. Before, the line carried `type` exactly as the envelope gave it, so a route
|
|
105
|
+
that hands `toDeliverableEvents` an unverified body could write a forged line through it, and every
|
|
106
|
+
distinct type was kept in memory for the life of the process. The set of types already reported now
|
|
107
|
+
holds at most one entry per known type plus one for `an unknown type`.
|
|
108
|
+
- a9f33b1: `WhatsAppAdapter.toDeliverableEvent(inbound)` throws `ConfigurationError` (`missing_phone_number_id`)
|
|
109
|
+
for a Cloud message when the adapter's backend declares no `phoneNumberId`, as
|
|
110
|
+
`toDeliverableEvents(envelope)` already did. Before, the single-message method skipped the number
|
|
111
|
+
check on such an adapter, so a route building events one message at a time over a backend that
|
|
112
|
+
wraps `WhatsAppCloudBackend` delivered every number's messages to one agent. WhatsApp Web and
|
|
113
|
+
Baileys messages still convert, and the `onInbound` path is unchanged (see docs/adr/0006).
|
|
114
|
+
- 79df9c2: `parseWebhookPayload` checks the nested shape of a Cloud webhook body and returns `null` when an
|
|
115
|
+
entry has no `changes` array, an entry or change is `null`, or a `messages`, `statuses` or
|
|
116
|
+
`contacts` list is not a list of objects. Before, such a body passed the check and then
|
|
117
|
+
`normalizeInboundMessages`, `normalizeStatusReceipts`, `toDeliverableEvents` and
|
|
118
|
+
`WhatsAppCloudBackend.handleWebhookPayload` threw a `TypeError`.
|
|
119
|
+
|
|
120
|
+
It also returns `null` when a field the inbound rules read is not a string: a
|
|
121
|
+
`metadata.phone_number_id` that is not absent or a string, or a text message whose `id`, `from` or
|
|
122
|
+
`text.body` is not a string. Before, a numeric or `null` `phone_number_id` made
|
|
123
|
+
`toDeliverableEvents` and `handleWebhookPayload` throw a `TypeError`, a numeric `from` threw under
|
|
124
|
+
`allowedSenders`, and a numeric `text.body` was delivered as a number.
|
|
125
|
+
|
|
126
|
+
`WhatsAppCloudBackend.handleWebhookPayload` answers `false` for a signed body `parseWebhookPayload`
|
|
127
|
+
refuses (no `object`, no `entry` array, or a malformed entry, change or list), as it does for a
|
|
128
|
+
signed body that is not JSON, dispatches nothing and writes one line to stderr. Before, it answered
|
|
129
|
+
`true` for a body with no `object` or no `entry` array, so a route built on it answered 200 and
|
|
130
|
+
Meta never redelivered the batch.
|
|
131
|
+
|
|
132
|
+
## 0.4.1
|
|
133
|
+
|
|
134
|
+
### Patch Changes
|
|
135
|
+
|
|
136
|
+
- 1e215ab: The peer floor on `@theokit/gateway` is `>=0.9.0`, which is what these packages have needed since
|
|
137
|
+
they gained `deliver`.
|
|
138
|
+
|
|
139
|
+
`deliver` and `runHandler` arrived in the core at 0.9.0, and the previous release shipped these
|
|
140
|
+
adapters still declaring `>=0.6.0` — a floor `dep-check` had already proven false by building the
|
|
141
|
+
workspace against it: TS4113 on the override, TS2551 on `runHandler`, in all ten packages.
|
|
142
|
+
|
|
143
|
+
It could not be corrected in that release. `dep-check`'s install check packs an adapter and installs
|
|
144
|
+
it the way a consumer would, and until 0.9.0 was on npm no consumer could resolve a package asking
|
|
145
|
+
for it — the check was right about the world as it stood. The floor is raised here, against a
|
|
146
|
+
registry where the version it names exists.
|
|
147
|
+
|
|
148
|
+
Between the two releases a consumer installing against an older core got a build error rather than a
|
|
149
|
+
resolution error: the same failure, later and less clearly. That window is closed.
|
|
150
|
+
|
|
3
151
|
## 0.4.0
|
|
4
152
|
|
|
5
153
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -12,13 +12,124 @@ pin a version number, and named 0.1.0 while the package shipped 0.3.2.)
|
|
|
12
12
|
|
|
13
13
|
**It depends on the backend**, and the two are not alike.
|
|
14
14
|
|
|
15
|
-
`cloud` is an **HTTP webhook** the application
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
15
|
+
`cloud` is an **HTTP webhook** the application hosts, in four steps: verify the signature, parse
|
|
16
|
+
the body, turn it into events with the adapter's rules applied, and deliver each one.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import {
|
|
20
|
+
normalizeStatusReceipts,
|
|
21
|
+
parseWebhookPayload,
|
|
22
|
+
verifyWebhookSignature,
|
|
23
|
+
WhatsAppAdapter,
|
|
24
|
+
} from "@theokit/gateway-whatsapp";
|
|
25
|
+
|
|
26
|
+
// cloud: { accessToken, phoneNumberId, appSecret }, appSecret non-empty; handleMessage: your agent's
|
|
27
|
+
// handler; handleReceipt: what you do with a sent / delivered / read / failed receipt.
|
|
28
|
+
const adapter = WhatsAppAdapter.fromCloud(cloud, { allowedSenders: process.env.WHATSAPP_ALLOWED });
|
|
29
|
+
adapter.onInbound(handleMessage);
|
|
30
|
+
// In-process only: a route served by several instances needs a shared store for this. A claim is
|
|
31
|
+
// kept for Meta's seven-day redelivery window and then forgotten, so the store stays bounded.
|
|
32
|
+
const CLAIM_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
33
|
+
const claimed = new Map<string, number>(); // wamid -> when it was claimed, oldest first
|
|
34
|
+
|
|
35
|
+
/** Claim `wamid` for delivery; false when it is already claimed. */
|
|
36
|
+
function claim(wamid: string): boolean {
|
|
37
|
+
const now = Date.now();
|
|
38
|
+
for (const [id, claimedAt] of claimed) {
|
|
39
|
+
if (now - claimedAt < CLAIM_WINDOW_MS) break; // every later entry is newer
|
|
40
|
+
claimed.delete(id);
|
|
41
|
+
}
|
|
42
|
+
if (claimed.has(wamid)) return false;
|
|
43
|
+
claimed.set(wamid, now);
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function onWebhook(rawBody: string, signature: string | undefined): Promise<number> {
|
|
48
|
+
if (!verifyWebhookSignature(rawBody, signature, cloud.appSecret)) return 401;
|
|
49
|
+
let json: unknown;
|
|
50
|
+
try {
|
|
51
|
+
json = JSON.parse(rawBody);
|
|
52
|
+
} catch {
|
|
53
|
+
return 400;
|
|
54
|
+
}
|
|
55
|
+
const envelope = parseWebhookPayload(json);
|
|
56
|
+
if (envelope === null) return 400;
|
|
57
|
+
for (const event of adapter.toDeliverableEvents(envelope)) {
|
|
58
|
+
const wamid = event.whatsapp.wamid;
|
|
59
|
+
// Claimed before the await, so a redelivery during a slow handler skips it.
|
|
60
|
+
if (!claim(wamid)) continue; // delivered, or being delivered by an earlier request
|
|
61
|
+
if ((await adapter.deliver(event)) !== "ok") {
|
|
62
|
+
claimed.delete(wamid); // Meta's retry may deliver it again
|
|
63
|
+
return 503;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
for (const receipt of normalizeStatusReceipts(envelope)) {
|
|
67
|
+
if (receipt.phoneNumberId !== cloud.phoneNumberId) continue; // another number of the same app
|
|
68
|
+
await handleReceipt(receipt);
|
|
69
|
+
}
|
|
70
|
+
return 200;
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The signature check is the route's job: `toDeliverableEvents` does not do it. It needs the Meta
|
|
75
|
+
app secret: `fromCloud` accepts an empty `appSecret` for an adapter that only sends, but
|
|
76
|
+
`verifyWebhookSignature` throws `ConfigurationError` (`missing_option`) for an empty or
|
|
77
|
+
whitespace-only one, because anyone can compute an HMAC under an empty key. Pass the real secret
|
|
78
|
+
to any adapter that receives webhooks. `theokit/server/webhook`
|
|
79
|
+
exports `whatsapp()` and `whatsappSubscribe()` for the signature and the GET handshake. The method
|
|
80
|
+
applies `allowedSenders` and the group rule exactly as `onInbound` does, so a refused sender yields
|
|
81
|
+
no event and one line on stderr naming only the last four digits of the number. On an adapter built
|
|
82
|
+
with `fromCloud`, or constructed around any backend that declares a `phoneNumberId` (every
|
|
83
|
+
`WhatsAppCloudBackend` does), it also drops messages addressed to another `phone_number_id`: one Meta app signs
|
|
84
|
+
every number's webhooks with the same secret, so a shared route must not hand one number's
|
|
85
|
+
messages to another number's agent. For that reason `toDeliverableEvents`, and
|
|
86
|
+
`toDeliverableEvent` given a Cloud message, throw `ConfigurationError` (`missing_phone_number_id`)
|
|
87
|
+
on an adapter whose backend declares no `phoneNumberId`: a backend that wraps
|
|
88
|
+
`WhatsAppCloudBackend` by delegation must expose the field. A
|
|
89
|
+
route that calls `WhatsAppCloudBackend.handleWebhookPayload`
|
|
90
|
+
directly, with no adapter, gets the same check: the backend's inbound handler receives only
|
|
91
|
+
messages addressed to the backend's own `phoneNumberId`.
|
|
92
|
+
|
|
93
|
+
`parseWebhookPayload` returns `null` for a body whose shape the normalizers cannot read: an entry
|
|
94
|
+
with no `changes` array, a `null` entry or change, a `messages`, `statuses` or `contacts` list
|
|
95
|
+
that is not a list of objects, a `metadata.phone_number_id` that is not a string, a text message
|
|
96
|
+
whose `id`, `from` or `text.body` is not a string, a contact whose `wa_id` or `profile.name` is not
|
|
97
|
+
a string, or a status whose `id`, `status` or `recipient_id` is not a string. The whole body is refused, not just its bad entries, so the route
|
|
98
|
+
answers it (400 in the example) instead of dropping part of a batch unseen. Any non-null envelope
|
|
99
|
+
is safe to hand to `toDeliverableEvents` and `normalizeStatusReceipts`: neither throws on it.
|
|
100
|
+
`WhatsAppCloudBackend.handleWebhookPayload` refuses such a body the same way: it answers `false`,
|
|
101
|
+
as it does for a signed body that is not JSON, dispatches nothing and writes one line to stderr,
|
|
102
|
+
so a route built on it answers non-2xx and Meta redelivers instead of losing the batch. It also
|
|
103
|
+
answers `false` for a body holding a message for its number while no inbound handler is
|
|
104
|
+
subscribed, before `onInbound` or after `disconnect()`. Status receipts with no status handler are
|
|
105
|
+
discarded, because subscribing to them is optional.
|
|
106
|
+
|
|
107
|
+
Answer 200 only when every event returned `ok`. `no_handler` means nothing received the message,
|
|
108
|
+
and `handler_threw` means your handler failed on it; a non-2xx makes Meta retry the whole envelope,
|
|
109
|
+
so a handler that always throws on one message sees it again on every retry. Meta also redelivers
|
|
110
|
+
an envelope it did not see answered in time, so a slow handler causes repeats as well, and such a
|
|
111
|
+
redelivery can arrive while the first request is still running. A retry repeats the events already
|
|
112
|
+
delivered. The route therefore claims a `wamid` before it awaits `deliver()` and skips any `wamid`
|
|
113
|
+
already claimed, which covers both cases; it releases the claim when delivery fails, so Meta's retry
|
|
114
|
+
delivers that message again. One case stays open: when a redelivery was answered 200 because it
|
|
115
|
+
skipped a message that was still running, and that first delivery then fails, Meta does not retry.
|
|
116
|
+
A handler slower than Meta's timeout should answer 200 first and hand the events to a queue.
|
|
117
|
+
|
|
118
|
+
The claim store forgets a `wamid` seven days after claiming it. Without a bound it would hold one
|
|
119
|
+
entry per message for as long as the process runs. Seven days is the retry period Meta's webhook
|
|
120
|
+
documentation gives; it was taken from there and not measured here, so check the current figure
|
|
121
|
+
and keep the window at least that long.
|
|
122
|
+
|
|
123
|
+
Status receipts never reach `onStatusReceipt` on this path: that handler listens to the backend,
|
|
124
|
+
and your route is what receives the webhook. Read them from the envelope with
|
|
125
|
+
`normalizeStatusReceipts`, as above, and skip any whose `phoneNumberId` is not your number: a
|
|
126
|
+
receipt names the recipient's phone number, so another number's receipts are another tenant's
|
|
127
|
+
customer data. `WhatsAppCloudBackend.handleWebhookPayload` applies the same rule before its status
|
|
128
|
+
handler sees a receipt.
|
|
19
129
|
|
|
20
130
|
`baileys` and `web` hold **their own socket** — there is no webhook to host, and messages reach
|
|
21
131
|
`onInbound` once `connect()` resolves.
|
|
132
|
+
|
|
22
133
|
## Choosing a backend
|
|
23
134
|
|
|
24
135
|
| Backend | Needs | Exercised against real WhatsApp |
|