@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 CHANGED
@@ -1,5 +1,171 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 4850c43: `WhatsAppCloudBackend.handleWebhookPayload` now resolves `"unreadable_body"` (not `false`) for a
8
+ signed body that is not JSON or that `parseWebhookPayload` refuses, so a route can answer it
9
+ differently from a bad signature (`false`, 401). The return type widens from `boolean` to
10
+ `boolean | "unreadable_body"`; the package is 0.x, so this is a minor bump. A route that tested
11
+ `!ok` and answered 401 now answers 200 for such a body, which stops Meta's useless redeliveries.
12
+
13
+ ### Patch Changes
14
+
15
+ - 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
16
+
17
+ `@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
18
+ `filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
19
+ carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
20
+ `supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
21
+ field. The runner and the router refuse an outbound carrying attachments as
22
+ `attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
23
+ `supportsAttachments`.
24
+
25
+ `@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
26
+ `sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
27
+ when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
28
+ than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
29
+
30
+ Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
31
+ with `attachments_unsupported` and makes no platform call, instead of sending the text and
32
+ dropping the image.
33
+
34
+ The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
35
+ throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
36
+ as a handler error is. Dispatch still does not throw.
37
+
38
+ - 17c0713: Keep Markdown table rows whole when Discord, Slack, Teams, Telegram, WhatsApp and Mattermost split a long reply. A cut that fell inside a table row now moves back to the start of that row when the row fits in a part, so each row reaches the platform byte-identical. `chunkText` gains the opt-in `keepTableRows` option; text with no table row splits into the same chunks as before.
39
+
40
+ ## 0.5.0
41
+
42
+ ### Minor Changes
43
+
44
+ - 72cc72d: Add `WhatsAppAdapter.toDeliverableEvents(envelope)` and `WhatsAppAdapter.toDeliverableEvent(inbound)`,
45
+ and export the `MetaWebhookEnvelope` type from the package entry.
46
+
47
+ An application that hosts its own WhatsApp Cloud webhook route could parse Meta's envelope, but had
48
+ no public way to turn it into the event `deliver()` accepts with the adapter's sender allowlist and
49
+ group-mention rule applied: the conversion was private and the rules ran only inside `onInbound`. A
50
+ route that copied the private conversion would have admitted every sender the operator refused.
51
+ `toDeliverableEvents` returns the accepted events of an envelope in order, and `onInbound` now
52
+ decides through `toDeliverableEvent`, so both paths apply one rule set and write the same refusal
53
+ line. Neither method calls the backend or the network, and neither verifies the webhook signature;
54
+ the route still does that first. The README's "How inbound arrives" shows the route end to end.
55
+
56
+ Two behaviours change on every inbound path, `onInbound` included. An adapter built with
57
+ `fromCloud` drops a message addressed to another `phone_number_id`, naming that id on stderr once,
58
+ because one Meta app signs every number's webhooks with the same secret. The allowlist refusal line
59
+ names the sender by the last four digits of the number only (`a sender ending in 8888`), where it
60
+ used to print the whole number. `toDeliverableEvents` throws `ConfigurationError`
61
+ (`missing_phone_number_id`) when the adapter's backend declares no `phoneNumberId`, so a backend
62
+ that wraps `WhatsAppCloudBackend` must expose the field instead of silently receiving every
63
+ number's messages.
64
+
65
+ No existing export changes.
66
+
67
+ - 5b14d8d: `WhatsAppStatusReceipt` gains an optional `phoneNumberId`: the `phone_number_id` a Cloud receipt was
68
+ addressed to, read from the webhook's `metadata`. `normalizeStatusReceipts` fills it; the web and
69
+ Baileys backends leave it absent.
70
+
71
+ `WhatsAppCloudBackend.handleWebhookPayload` now applies the own-number rule to status receipts as
72
+ well as to messages. Before, a receipt addressed to another number of the same Meta app, or naming
73
+ no number, still reached `onStatusReceipt`, and a receipt names the recipient's phone number, so in
74
+ a multi-number app one number's handler received another number's customer numbers. Such a receipt
75
+ is now dropped and its number id written to stderr once, as a message already was.
76
+
77
+ The README's Cloud route skips any receipt whose `phoneNumberId` is not the route's own number.
78
+ Additive: no existing field changes.
79
+
80
+ ### Patch Changes
81
+
82
+ - 7eae6a1: `WhatsAppAdapter` now delivers every message of a signed Cloud batch to the inbound handler that
83
+ was subscribed when the batch arrived. The backend already did this, but the adapter looked up its
84
+ current handler again for each message, so a `disconnect()` or an unsubscribe inside the handler of
85
+ the first message dropped the rest of the batch while the webhook still answered 200, and Meta did
86
+ not redeliver the dropped messages. A batch that arrives after the unsubscribe still reaches no one.
87
+ - a748c4e: `WhatsAppAdapter.onStatusReceipt` drops a status receipt addressed to another phone number id when
88
+ the adapter's backend declares its `phoneNumberId`, as the adapter already did for messages, and
89
+ names that id once on stderr by its last four digits. Before, a custom backend that declared its
90
+ number had its messages scoped and its receipts forwarded whole, so one number's receipt handler
91
+ saw the customer numbers of another number on the same Meta app. A backend that declares no number
92
+ forwards every receipt, as before.
93
+ - fc65200: `WhatsAppBackend` gains an optional `phoneNumberId`, the Meta Cloud phone number id the backend
94
+ answers for. `WhatsAppAdapter` now reads that field to decide whether a message is addressed to
95
+ another number of the same Meta app, instead of checking whether the backend is an instance of
96
+ `WhatsAppCloudBackend`. Before, a wrapped Cloud backend, a test double, or a `WhatsAppCloudBackend`
97
+ loaded from the package's other module format (ESM beside CJS) lost the check without a word, and
98
+ another number's messages reached the agent. A custom backend that declares `phoneNumberId` now
99
+ gets the same check; one that declares none behaves as before.
100
+ - 646e0ae: An adapter constructed with `new WhatsAppAdapter(new WhatsAppCloudBackend(...))` now drops a
101
+ message addressed to another `phone_number_id`, as an adapter built with `fromCloud` already did.
102
+ Before, the check depended on which construction path built the adapter, so the same Cloud backend
103
+ admitted another number's messages when the adapter was constructed directly.
104
+ `WhatsAppCloudBackend.handleWebhookPayload` applies the same rule, so a route built on the backend
105
+ alone, with no adapter, no longer hands its inbound handler a message addressed to another number
106
+ of the same Meta app or naming no number.
107
+ `WhatsAppCloudBackend` exposes the number it answers for as `phoneNumberId`.
108
+ - a145874: `WhatsAppCloudBackend.handleWebhookPayload` delivers every message of a signed batch to the inbound
109
+ handler that was subscribed when the batch arrived. Before, the handler was looked up again for each
110
+ message, so a `disconnect()` or an unsubscribe inside the handler of the first message skipped the
111
+ rest of the batch with nothing on stderr, and the method still answered `true`: the route answered
112
+ 200 and Meta did not redeliver the skipped messages.
113
+ - 0c09b14: `WhatsAppCloudBackend.handleWebhookPayload` answers `false` for a signed body that holds a message
114
+ for the backend's number while no inbound handler is subscribed (before `onInbound`, or after
115
+ `disconnect()` cleared it), dispatches nothing and writes one line to stderr naming the count.
116
+ Before, it answered `true`, so a route answered 200, Meta did not redeliver, and the messages were
117
+ lost with nothing logged. Status receipts with no status handler are still discarded, and a body
118
+ whose messages are all for another number still answers `true`.
119
+ - 9778690: `parseWebhookPayload` returns `null` for a Cloud webhook body with a contact whose `wa_id` or
120
+ `profile.name` is not a string, or a status whose `id`, `status` or `recipient_id` is not a string.
121
+ Before, a contact name of `42` reached the agent as `sender.displayName` 42, and a status with a
122
+ numeric `id` became a receipt whose `wamid` was a number, though both fields are typed as strings.
123
+ `WhatsAppCloudBackend.handleWebhookPayload` answers `false` for such a body and dispatches nothing,
124
+ as it already does for the other shapes the parser refuses.
125
+ - 3a249c3: `verifyWebhookSignature` now throws `ConfigurationError` with code `missing_option` when the app
126
+ secret is empty or whitespace only, instead of checking the signature against it. Anyone can
127
+ compute an HMAC under an empty key, so a webhook route built on an outbound-only adapter
128
+ (`appSecret: ""`) accepted forged envelopes, and a forged envelope can name any allowed sender.
129
+ `WhatsAppCloudBackend.handleWebhookPayload` goes through the same check and now rejects in that
130
+ case. `fromCloud` still accepts an empty `appSecret` for an adapter that only sends. The README
131
+ route now says the secret must be non-empty.
132
+ - 08157ca: The stderr line written when a message addressed to another `phone_number_id` is dropped now names
133
+ that id by its last four digits, the way the allowlist refusal already names a sender, and names a
134
+ message with no id as `no phone number id`. Before, the line carried the id exactly as the
135
+ envelope gave it, so a route that hands `toDeliverableEvents` an unverified body could write a
136
+ forged line through it, and every distinct id was kept in memory for the life of the adapter. The
137
+ set of ids already reported now holds at most one entry per four-digit ending. A log query that
138
+ matched `phone number id "<id>"` needs to match `phone number id ending in <last four digits>`.
139
+ - bc1357c: The stderr line written when a Cloud message that is not text is ignored now names its type only
140
+ when the type is one Meta documents (`image`, `audio`, `sticker` and the rest); any other value is
141
+ named `an unknown type`. Before, the line carried `type` exactly as the envelope gave it, so a route
142
+ that hands `toDeliverableEvents` an unverified body could write a forged line through it, and every
143
+ distinct type was kept in memory for the life of the process. The set of types already reported now
144
+ holds at most one entry per known type plus one for `an unknown type`.
145
+ - a9f33b1: `WhatsAppAdapter.toDeliverableEvent(inbound)` throws `ConfigurationError` (`missing_phone_number_id`)
146
+ for a Cloud message when the adapter's backend declares no `phoneNumberId`, as
147
+ `toDeliverableEvents(envelope)` already did. Before, the single-message method skipped the number
148
+ check on such an adapter, so a route building events one message at a time over a backend that
149
+ wraps `WhatsAppCloudBackend` delivered every number's messages to one agent. WhatsApp Web and
150
+ Baileys messages still convert, and the `onInbound` path is unchanged (see docs/adr/0006).
151
+ - 79df9c2: `parseWebhookPayload` checks the nested shape of a Cloud webhook body and returns `null` when an
152
+ entry has no `changes` array, an entry or change is `null`, or a `messages`, `statuses` or
153
+ `contacts` list is not a list of objects. Before, such a body passed the check and then
154
+ `normalizeInboundMessages`, `normalizeStatusReceipts`, `toDeliverableEvents` and
155
+ `WhatsAppCloudBackend.handleWebhookPayload` threw a `TypeError`.
156
+
157
+ It also returns `null` when a field the inbound rules read is not a string: a
158
+ `metadata.phone_number_id` that is not absent or a string, or a text message whose `id`, `from` or
159
+ `text.body` is not a string. Before, a numeric or `null` `phone_number_id` made
160
+ `toDeliverableEvents` and `handleWebhookPayload` throw a `TypeError`, a numeric `from` threw under
161
+ `allowedSenders`, and a numeric `text.body` was delivered as a number.
162
+
163
+ `WhatsAppCloudBackend.handleWebhookPayload` answers `false` for a signed body `parseWebhookPayload`
164
+ refuses (no `object`, no `entry` array, or a malformed entry, change or list), as it does for a
165
+ signed body that is not JSON, dispatches nothing and writes one line to stderr. Before, it answered
166
+ `true` for a body with no `object` or no `entry` array, so a route built on it answered 200 and
167
+ Meta never redelivered the batch.
168
+
3
169
  ## 0.4.1
4
170
 
5
171
  ### Patch Changes
package/README.md CHANGED
@@ -12,13 +12,127 @@ 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 must authenticate: Meta signs with
16
- `X-Hub-Signature-256` over the raw body, and `theokit/server/webhook` exports `whatsapp()` and
17
- `whatsappSubscribe()` for the signature and the GET handshake. Parsed events go to
18
- `adapter.deliver(event)`.
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 too, and tells it from a forgery: a
101
+ bad signature answers `false` (answer 401), while a signed body that is not JSON or that the parser
102
+ refuses answers `"unreadable_body"`. Either way it dispatches nothing; the second also writes one
103
+ line to stderr. A route should answer `"unreadable_body"` with something other than 401, such as 200:
104
+ the signature proves Meta sent it, and a non-2xx only makes Meta redeliver the same bytes, which are
105
+ refused again until Meta gives up, so redelivery cannot recover it (fix the parser, not the retry). It also
106
+ answers `false` for a body holding a message for its number while no inbound handler is
107
+ subscribed, before `onInbound` or after `disconnect()`. Status receipts with no status handler are
108
+ discarded, because subscribing to them is optional.
109
+
110
+ Answer 200 only when every event returned `ok`. `no_handler` means nothing received the message,
111
+ and `handler_threw` means your handler failed on it; a non-2xx makes Meta retry the whole envelope,
112
+ so a handler that always throws on one message sees it again on every retry. Meta also redelivers
113
+ an envelope it did not see answered in time, so a slow handler causes repeats as well, and such a
114
+ redelivery can arrive while the first request is still running. A retry repeats the events already
115
+ delivered. The route therefore claims a `wamid` before it awaits `deliver()` and skips any `wamid`
116
+ already claimed, which covers both cases; it releases the claim when delivery fails, so Meta's retry
117
+ delivers that message again. One case stays open: when a redelivery was answered 200 because it
118
+ skipped a message that was still running, and that first delivery then fails, Meta does not retry.
119
+ A handler slower than Meta's timeout should answer 200 first and hand the events to a queue.
120
+
121
+ The claim store forgets a `wamid` seven days after claiming it. Without a bound it would hold one
122
+ entry per message for as long as the process runs. Seven days is the retry period Meta's webhook
123
+ documentation gives; it was taken from there and not measured here, so check the current figure
124
+ and keep the window at least that long.
125
+
126
+ Status receipts never reach `onStatusReceipt` on this path: that handler listens to the backend,
127
+ and your route is what receives the webhook. Read them from the envelope with
128
+ `normalizeStatusReceipts`, as above, and skip any whose `phoneNumberId` is not your number: a
129
+ receipt names the recipient's phone number, so another number's receipts are another tenant's
130
+ customer data. `WhatsAppCloudBackend.handleWebhookPayload` applies the same rule before its status
131
+ handler sees a receipt.
19
132
 
20
133
  `baileys` and `web` hold **their own socket** — there is no webhook to host, and messages reach
21
134
  `onInbound` once `connect()` resolves.
135
+
22
136
  ## Choosing a backend
23
137
 
24
138
  | Backend | Needs | Exercised against real WhatsApp |