@owlmeans/bot-whatsapp 0.0.0-stage → 0.2.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/README.md +74 -2
- package/agent-meta/manifest.json +16 -0
- package/agent-meta/skills/bot-whatsapp/SKILL.md +104 -0
- package/build/api.d.ts +7 -0
- package/build/api.d.ts.map +1 -0
- package/build/api.js +50 -0
- package/build/api.js.map +1 -0
- package/build/append.d.ts +10 -0
- package/build/append.d.ts.map +1 -0
- package/build/append.js +13 -0
- package/build/append.js.map +1 -0
- package/build/consts.d.ts +57 -0
- package/build/consts.d.ts.map +1 -0
- package/build/consts.js +183 -0
- package/build/consts.js.map +1 -0
- package/build/errors.d.ts +22 -0
- package/build/errors.d.ts.map +1 -0
- package/build/errors.js +34 -0
- package/build/errors.js.map +1 -0
- package/build/index.d.ts +7 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +6 -0
- package/build/index.js.map +1 -0
- package/build/mock.d.ts +9 -0
- package/build/mock.d.ts.map +1 -0
- package/build/mock.js +198 -0
- package/build/mock.js.map +1 -0
- package/build/normalize.d.ts +4 -0
- package/build/normalize.d.ts.map +1 -0
- package/build/normalize.js +109 -0
- package/build/normalize.js.map +1 -0
- package/build/plugin.d.ts +13 -0
- package/build/plugin.d.ts.map +1 -0
- package/build/plugin.js +147 -0
- package/build/plugin.js.map +1 -0
- package/build/signature.d.ts +4 -0
- package/build/signature.d.ts.map +1 -0
- package/build/signature.js +20 -0
- package/build/signature.js.map +1 -0
- package/build/types.d.ts +179 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.js +2 -0
- package/build/types.js.map +1 -0
- package/package.json +56 -4
- package/src/api.ts +62 -0
- package/src/append.ts +18 -0
- package/src/consts.ts +206 -0
- package/src/errors.ts +37 -0
- package/src/index.ts +6 -0
- package/src/mock.ts +243 -0
- package/src/normalize.ts +131 -0
- package/src/plugin.ts +183 -0
- package/src/signature.ts +27 -0
- package/src/types.ts +174 -0
- package/tests/context.ts +85 -0
- package/tests/descriptor.spec.ts +64 -0
- package/tests/mock-ids.spec.ts +38 -0
- package/tests/tsconfig.json +12 -0
- package/tests/whatsapp.spec.ts +485 -0
- package/tsconfig.json +16 -0
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test'
|
|
2
|
+
import {
|
|
3
|
+
BotActionKind, BotChatKind, BotConnectionStatus, BotCredentialsRejected, BotReceiveMode,
|
|
4
|
+
BotSignatureRejected, BotTransport, BotUnsupportedAction, BotUpdateKind, botTextHelper, makeBotHookProtocols,
|
|
5
|
+
type BotConnection, type BotUpdate,
|
|
6
|
+
} from '@owlmeans/bot'
|
|
7
|
+
import { BotInboxStatus } from '@owlmeans/server-bot'
|
|
8
|
+
import { botHandler } from '@owlmeans/server-bot'
|
|
9
|
+
import { botMockHelper } from './context.js'
|
|
10
|
+
import { serveBotHookEntrypoints } from '@owlmeans/server-bot'
|
|
11
|
+
import { WHATSAPP_PLATFORM, WHATSAPP_SIGNATURE_HEADER } from '../src/consts.js'
|
|
12
|
+
import { WhatsAppApiError } from '../src/errors.js'
|
|
13
|
+
import { makeWhatsAppBotPlatform, whatsappBotPlatform } from '../src/plugin.js'
|
|
14
|
+
import { whatsappSignatureHelper } from '../src/signature.js'
|
|
15
|
+
import type { WhatsAppMock } from '../src/types.js'
|
|
16
|
+
import type { BotPlatformConnection } from '@owlmeans/server-bot'
|
|
17
|
+
import type { BotRuntime } from '@owlmeans/server-bot'
|
|
18
|
+
import { invoke, makeTestBot, scopeOf, type TestBot } from './context.js'
|
|
19
|
+
|
|
20
|
+
// Payload shapes follow https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages
|
|
21
|
+
// (text, interactive, button) — the ids and numbers are Meta's own examples.
|
|
22
|
+
const PHONE_ID = '106540352242922'
|
|
23
|
+
const DISPLAY = '15550783881'
|
|
24
|
+
const CUSTOMER = '16505551234'
|
|
25
|
+
|
|
26
|
+
/** The business number as `GET /<phone-number-id>` answered it. */
|
|
27
|
+
const connection: BotConnection = {
|
|
28
|
+
id: 'wa-1', scope: 'org', platform: 'whatsapp', label: 'Bakery', transport: BotTransport.Live,
|
|
29
|
+
status: BotConnectionStatus.Connected, enabled: true, receive: BotReceiveMode.Webhook,
|
|
30
|
+
identity: { id: PHONE_ID, username: DISPLAY, name: 'Owl Bakery' },
|
|
31
|
+
credentialsSet: ['accessToken', 'appSecret', 'phoneNumberId', 'verifyToken'],
|
|
32
|
+
createdAt: '2026-10-01T00:00:00.000Z', updatedAt: '2026-10-01T00:00:00.000Z',
|
|
33
|
+
}
|
|
34
|
+
const plugin = whatsappBotPlatform
|
|
35
|
+
const mock = plugin.mock as WhatsAppMock
|
|
36
|
+
|
|
37
|
+
const webhook = (
|
|
38
|
+
value: Record<string, unknown>, extra: Record<string, unknown>[] = [],
|
|
39
|
+
metadata: Record<string, string> = { display_phone_number: DISPLAY, phone_number_id: PHONE_ID }
|
|
40
|
+
) => ({
|
|
41
|
+
object: 'whatsapp_business_account',
|
|
42
|
+
entry: [{
|
|
43
|
+
id: '102290129340398',
|
|
44
|
+
changes: [{
|
|
45
|
+
value: { messaging_product: 'whatsapp', metadata, ...value },
|
|
46
|
+
field: 'messages',
|
|
47
|
+
}, ...extra],
|
|
48
|
+
}],
|
|
49
|
+
})
|
|
50
|
+
const contacts = [{ profile: { name: 'Sheena Nelson' }, wa_id: CUSTOMER }]
|
|
51
|
+
|
|
52
|
+
const one = (payload: unknown) => {
|
|
53
|
+
const updates = plugin.normalize(payload, connection)
|
|
54
|
+
expect(updates.length).toBe(1)
|
|
55
|
+
return updates[0]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
describe('@owlmeans/bot-whatsapp — WhatsApp normalization (Cloud API webhook shapes)', () => {
|
|
59
|
+
test('a text message: a private chat with the customer, addressed, deduplicated by its wamid', () => {
|
|
60
|
+
const { platformId, update } = one(webhook({
|
|
61
|
+
contacts,
|
|
62
|
+
messages: [{ from: CUSTOMER, id: 'wamid.TEXT1', timestamp: '1749416383', type: 'text', text: { body: 'Does it come in another color?' } }],
|
|
63
|
+
}))
|
|
64
|
+
|
|
65
|
+
expect(platformId).toBe('wamid.TEXT1')
|
|
66
|
+
expect(update).toMatchObject({
|
|
67
|
+
kind: BotUpdateKind.Message,
|
|
68
|
+
chat: { id: CUSTOMER, kind: BotChatKind.Private, title: 'Sheena Nelson' },
|
|
69
|
+
sender: { id: CUSTOMER, name: 'Sheena Nelson', bot: false },
|
|
70
|
+
message: { ref: { chat: CUSTOMER, id: 'wamid.TEXT1' }, text: 'Does it come in another color?', date: '2025-06-08T20:59:43.000Z' },
|
|
71
|
+
addressed: true,
|
|
72
|
+
})
|
|
73
|
+
expect(update.message?.replyTo).toBeUndefined()
|
|
74
|
+
expect(update.command).toBeUndefined()
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('a reply carries its context: quoting the business is a reply to the bot, quoting oneself is not', () => {
|
|
78
|
+
const toBot = one(webhook({
|
|
79
|
+
contacts,
|
|
80
|
+
messages: [{
|
|
81
|
+
from: CUSTOMER, id: 'wamid.R1', timestamp: '1749416383', type: 'text', text: { body: 'and on Sunday?' },
|
|
82
|
+
context: { from: DISPLAY, id: 'wamid.BOT1' },
|
|
83
|
+
}],
|
|
84
|
+
})).update
|
|
85
|
+
expect(toBot.message?.replyTo).toEqual({
|
|
86
|
+
chat: CUSTOMER, id: 'wamid.BOT1', sender: { id: PHONE_ID, name: 'Owl Bakery', username: DISPLAY, bot: true },
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
const toSelf = one(webhook({
|
|
90
|
+
contacts,
|
|
91
|
+
messages: [{
|
|
92
|
+
from: CUSTOMER, id: 'wamid.R2', timestamp: '1749416383', type: 'text', text: { body: 'see above' },
|
|
93
|
+
context: { from: CUSTOMER, id: 'wamid.OWN' },
|
|
94
|
+
}],
|
|
95
|
+
})).update
|
|
96
|
+
expect(toSelf.message?.replyTo).toEqual({ chat: CUSTOMER, id: 'wamid.OWN', sender: { id: CUSTOMER, name: 'Sheena Nelson', bot: false } })
|
|
97
|
+
|
|
98
|
+
const forwarded = one(webhook({
|
|
99
|
+
contacts,
|
|
100
|
+
messages: [{ from: CUSTOMER, id: 'wamid.F1', timestamp: '1', type: 'text', text: { body: 'fwd' }, context: { forwarded: true } }],
|
|
101
|
+
})).update
|
|
102
|
+
expect(forwarded.message?.replyTo).toBeUndefined()
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
test('interactive button and list replies and a template quick-reply button read as their text', () => {
|
|
106
|
+
const button = one(webhook({
|
|
107
|
+
contacts,
|
|
108
|
+
messages: [{
|
|
109
|
+
context: { from: DISPLAY, id: 'wamid.ASK' }, from: CUSTOMER, id: 'wamid.I1', timestamp: '1', type: 'interactive',
|
|
110
|
+
interactive: { type: 'button_reply', button_reply: { id: 'cancel-button', title: 'Cancel' } },
|
|
111
|
+
}],
|
|
112
|
+
})).update
|
|
113
|
+
expect([button.message?.text, button.message?.replyTo?.id, button.message?.replyTo?.sender?.bot]).toEqual(['Cancel', 'wamid.ASK', true])
|
|
114
|
+
|
|
115
|
+
const list = one(webhook({
|
|
116
|
+
contacts,
|
|
117
|
+
messages: [{
|
|
118
|
+
from: CUSTOMER, id: 'wamid.L1', timestamp: '1', type: 'interactive',
|
|
119
|
+
interactive: { type: 'list_reply', list_reply: { id: 'priority_express', title: 'Priority Mail Express', description: 'Next Day to 2 Days' } },
|
|
120
|
+
}],
|
|
121
|
+
})).update
|
|
122
|
+
expect(list.message?.text).toBe('Priority Mail Express')
|
|
123
|
+
|
|
124
|
+
const quick = one(webhook({
|
|
125
|
+
contacts,
|
|
126
|
+
messages: [{ from: CUSTOMER, id: 'wamid.B1', timestamp: '1', type: 'button', button: { payload: 'Unsubscribe', text: 'Unsubscribe' } }],
|
|
127
|
+
})).update
|
|
128
|
+
expect(quick.message?.text).toBe('Unsubscribe')
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
test('a media caption is the text; a slash command is a command', () => {
|
|
132
|
+
const photo = one(webhook({
|
|
133
|
+
contacts,
|
|
134
|
+
messages: [{ from: CUSTOMER, id: 'wamid.P1', timestamp: '1', type: 'image', image: { id: 'm1', mime_type: 'image/jpeg', caption: 'this cake' } }],
|
|
135
|
+
})).update
|
|
136
|
+
expect(photo.message?.text).toBe('this cake')
|
|
137
|
+
|
|
138
|
+
const command = one(webhook({
|
|
139
|
+
contacts,
|
|
140
|
+
messages: [{ from: CUSTOMER, id: 'wamid.C1', timestamp: '1', type: 'text', text: { body: '/order 2 croissants' } }],
|
|
141
|
+
})).update
|
|
142
|
+
expect([command.kind, command.command]).toEqual([BotUpdateKind.Command, { name: 'order', args: '2 croissants' }])
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
test('several messages, changes and entries become several updates, each sender named from its contact', () => {
|
|
146
|
+
const payload = webhook({
|
|
147
|
+
contacts: [...contacts, { profile: { name: 'Ann' }, wa_id: '447700900123' }],
|
|
148
|
+
messages: [
|
|
149
|
+
{ from: '447700900123', id: 'wamid.M1', timestamp: '1', type: 'text', text: { body: 'first' } },
|
|
150
|
+
{ from: CUSTOMER, id: 'wamid.M2', timestamp: '2', type: 'text', text: { body: 'second' } },
|
|
151
|
+
],
|
|
152
|
+
}, [{
|
|
153
|
+
field: 'messages',
|
|
154
|
+
value: {
|
|
155
|
+
messaging_product: 'whatsapp', metadata: { display_phone_number: DISPLAY, phone_number_id: PHONE_ID },
|
|
156
|
+
messages: [{ from: CUSTOMER, id: 'wamid.M3', timestamp: '3', type: 'text', text: { body: 'third' } }],
|
|
157
|
+
},
|
|
158
|
+
}])
|
|
159
|
+
|
|
160
|
+
expect(plugin.normalize(payload, connection).map(({ platformId, update }) => [platformId, update.sender?.name ?? null, update.message?.text]))
|
|
161
|
+
.toEqual([['wamid.M1', 'Ann', 'first'], ['wamid.M2', 'Sheena Nelson', 'second'], ['wamid.M3', null, 'third']])
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
test('statuses, unread kinds, another number\'s messages and garbage normalize to nothing', () => {
|
|
165
|
+
expect(plugin.normalize(webhook({
|
|
166
|
+
statuses: [{ id: 'wamid.S1', status: 'delivered', timestamp: '1750263773', recipient_id: CUSTOMER, conversation: { id: 'c', origin: { type: 'service' } }, pricing: { billable: true, pricing_model: 'CBP', category: 'service' } }],
|
|
167
|
+
}), connection)).toEqual([])
|
|
168
|
+
expect(plugin.normalize(webhook({
|
|
169
|
+
contacts,
|
|
170
|
+
messages: [
|
|
171
|
+
{ from: CUSTOMER, id: 'wamid.X1', timestamp: '1', type: 'reaction', reaction: { message_id: 'wamid.BOT1', emoji: '👍' } },
|
|
172
|
+
{ from: CUSTOMER, id: 'wamid.X2', timestamp: '1', type: 'sticker', sticker: { id: 's' } },
|
|
173
|
+
{ from: CUSTOMER, id: 'wamid.X3', timestamp: '1', type: 'unsupported', errors: [{ code: 131051 }] },
|
|
174
|
+
],
|
|
175
|
+
}), connection)).toEqual([])
|
|
176
|
+
const elsewhere = webhook(
|
|
177
|
+
{ contacts, messages: [{ from: CUSTOMER, id: 'wamid.E1', timestamp: '1', type: 'text', text: { body: 'hi' } }] },
|
|
178
|
+
[], { display_phone_number: '15550000000', phone_number_id: '999' }
|
|
179
|
+
)
|
|
180
|
+
expect(plugin.normalize(elsewhere, connection)).toEqual([])
|
|
181
|
+
expect(plugin.normalize({ ...webhook({ contacts, messages: [] }), object: 'page' }, connection)).toEqual([])
|
|
182
|
+
expect(plugin.normalize({ nope: true }, connection)).toEqual([])
|
|
183
|
+
expect(plugin.normalize(null, connection)).toEqual([])
|
|
184
|
+
})
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
describe('@owlmeans/bot-whatsapp — WhatsApp hook authentication', () => {
|
|
188
|
+
const platformConnection: BotPlatformConnection = {
|
|
189
|
+
...connection,
|
|
190
|
+
credentials: { accessToken: 'EAAG-token', phoneNumberId: PHONE_ID, appSecret: 'app-secret-1', verifyToken: 'the-hook-secret' },
|
|
191
|
+
hookSecret: 'the-hook-secret',
|
|
192
|
+
}
|
|
193
|
+
const handshake = (query: Record<string, unknown>) => plugin.authenticate({ method: 'GET', headers: {}, query }, platformConnection)
|
|
194
|
+
|
|
195
|
+
test('the hub.challenge handshake is answered only for subscribe with the connection\'s verify token', () => {
|
|
196
|
+
const valid = { 'hub.mode': 'subscribe', 'hub.verify_token': 'the-hook-secret', 'hub.challenge': '1158201444' }
|
|
197
|
+
|
|
198
|
+
expect(handshake(valid)).toEqual({ result: 'challenge', text: '1158201444' })
|
|
199
|
+
expect(handshake({ hub: { mode: 'subscribe', verify_token: 'the-hook-secret', challenge: '7' } })).toEqual({ result: 'challenge', text: '7' })
|
|
200
|
+
expect(handshake({ ...valid, 'hub.verify_token': 'guess' })).toEqual({ result: 'reject', reason: 'verify-token' })
|
|
201
|
+
expect(handshake({ ...valid, 'hub.verify_token': undefined })).toEqual({ result: 'reject', reason: 'verify-token' })
|
|
202
|
+
expect(handshake({ ...valid, 'hub.mode': 'unsubscribe' })).toEqual({ result: 'reject', reason: 'hub-mode' })
|
|
203
|
+
expect(handshake({ ...valid, 'hub.challenge': '' })).toEqual({ result: 'reject', reason: 'hub-challenge' })
|
|
204
|
+
// A typed verify token wins over the hook secret.
|
|
205
|
+
const typed = { ...platformConnection, credentials: { ...platformConnection.credentials, verifyToken: 'typed-token' } }
|
|
206
|
+
expect(plugin.authenticate({ method: 'GET', headers: {}, query: valid }, typed)).toEqual({ result: 'reject', reason: 'verify-token' })
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
test('X-Hub-Signature-256 is the HMAC-SHA256 of the raw bytes with the app secret', () => {
|
|
210
|
+
// Meta escapes non-ASCII in the bytes it signs — only the raw body verifies, never a re-serialization.
|
|
211
|
+
const rawBody = '{"object":"whatsapp_business_account","entry":[{"id":"1","changes":[{"value":{"messages":[{"text":{"body":"caf\\u00e9"}}]},"field":"messages"}]}]}'
|
|
212
|
+
const body = JSON.parse(rawBody)
|
|
213
|
+
const signature = whatsappSignatureHelper.sign(rawBody, 'app-secret-1')
|
|
214
|
+
const post = (headers: Record<string, string>, raw: string | null = rawBody) =>
|
|
215
|
+
plugin.authenticate({ method: 'POST', headers, body, ...(raw != null ? { rawBody: raw } : {}) }, platformConnection)
|
|
216
|
+
|
|
217
|
+
expect(signature).toMatch(/^sha256=[0-9a-f]{64}$/)
|
|
218
|
+
expect(post({ [WHATSAPP_SIGNATURE_HEADER]: signature })).toEqual({ result: 'ok' })
|
|
219
|
+
expect(post({ 'X-Hub-Signature-256': signature.toUpperCase().replace('SHA256=', 'sha256=') })).toEqual({ result: 'ok' })
|
|
220
|
+
expect(post({ [WHATSAPP_SIGNATURE_HEADER]: whatsappSignatureHelper.sign(rawBody, 'another-secret') })).toEqual({ result: 'reject', reason: 'signature' })
|
|
221
|
+
expect(post({ [WHATSAPP_SIGNATURE_HEADER]: signature }, rawBody.replace('caf', 'cav'))).toEqual({ result: 'reject', reason: 'signature' })
|
|
222
|
+
expect(post({ [WHATSAPP_SIGNATURE_HEADER]: signature }, null)).toEqual({ result: 'reject', reason: 'signature' })
|
|
223
|
+
expect(post({ [WHATSAPP_SIGNATURE_HEADER]: signature.slice('sha256='.length) })).toEqual({ result: 'reject', reason: 'signature' })
|
|
224
|
+
expect(post({})).toEqual({ result: 'reject', reason: 'signature' })
|
|
225
|
+
expect(plugin.authenticate({ method: 'PUT', headers: {} }, platformConnection)).toEqual({ result: 'reject', reason: 'method' })
|
|
226
|
+
const unsigned = { ...platformConnection, credentials: { ...platformConnection.credentials, appSecret: '' } }
|
|
227
|
+
expect(plugin.authenticate({ method: 'POST', headers: { [WHATSAPP_SIGNATURE_HEADER]: whatsappSignatureHelper.sign(rawBody, 'the-hook-secret') }, body, rawBody }, unsigned))
|
|
228
|
+
.toEqual({ result: 'reject', reason: 'app-secret-missing' })
|
|
229
|
+
})
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
describe('@owlmeans/bot-whatsapp — WhatsApp Graph API and mock', () => {
|
|
233
|
+
const live: BotPlatformConnection = {
|
|
234
|
+
...connection, credentials: { accessToken: 'EAAG-token', phoneNumberId: PHONE_ID, appSecret: 's' }, hookSecret: 'h',
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
test('verify GETs the phone number with a Bearer token — base and version are overridable', async () => {
|
|
238
|
+
const seen: [string, string | undefined][] = []
|
|
239
|
+
const platform = makeWhatsAppBotPlatform({ base: 'https://graph.example.org/', version: 'v99.0' })
|
|
240
|
+
const identity = await platform.verify({
|
|
241
|
+
connection: live,
|
|
242
|
+
transport: BotTransport.Live,
|
|
243
|
+
fetch: async (url, init) => {
|
|
244
|
+
seen.push([url, init?.headers?.authorization])
|
|
245
|
+
expect(init?.method).toBe('GET')
|
|
246
|
+
return new Response(JSON.stringify({ display_phone_number: '15555555555', verified_name: 'Support Number', id: PHONE_ID }))
|
|
247
|
+
},
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
expect(seen).toEqual([[`https://graph.example.org/v99.0/${PHONE_ID}?fields=display_phone_number%2Cverified_name`, 'Bearer EAAG-token']])
|
|
251
|
+
expect(identity).toEqual({ id: PHONE_ID, username: '15555555555', name: 'Support Number' })
|
|
252
|
+
})
|
|
253
|
+
|
|
254
|
+
test('a refused token is BotCredentialsRejected; a transport fault never carries the token', async () => {
|
|
255
|
+
const refused = plugin.verify({
|
|
256
|
+
connection: live,
|
|
257
|
+
transport: BotTransport.Live,
|
|
258
|
+
fetch: async () => new Response(JSON.stringify({
|
|
259
|
+
error: { message: 'Error validating access token: Session has expired', type: 'OAuthException', code: 190, fbtrace_id: 'A' },
|
|
260
|
+
}), { status: 401 }),
|
|
261
|
+
})
|
|
262
|
+
await expect(refused).rejects.toBeInstanceOf(BotCredentialsRejected)
|
|
263
|
+
await expect(refused).rejects.toThrow('bot:credentials-rejected:whatsapp:190')
|
|
264
|
+
|
|
265
|
+
const unreachable = plugin.act({
|
|
266
|
+
connection: live,
|
|
267
|
+
transport: BotTransport.Live,
|
|
268
|
+
fetch: async () => { throw new TypeError('fetch failed: Authorization: Bearer EAAG-token') },
|
|
269
|
+
}, { kind: BotActionKind.Send, chat: { id: CUSTOMER, kind: BotChatKind.Private }, text: 'hi' })
|
|
270
|
+
await expect(unreachable).rejects.toBeInstanceOf(WhatsAppApiError)
|
|
271
|
+
await expect(unreachable).rejects.toThrow('bot:platform:whatsapp:503:POST messages: unreachable')
|
|
272
|
+
|
|
273
|
+
const missing = plugin.verify({ connection: { ...live, credentials: { accessToken: 'x' } }, transport: BotTransport.Live, fetch: async () => new Response('{}') })
|
|
274
|
+
await expect(missing).rejects.toThrow('bot:credentials-rejected:missing:phoneNumberId')
|
|
275
|
+
})
|
|
276
|
+
|
|
277
|
+
test('delete, mute and ban are refused by the plugin itself', async () => {
|
|
278
|
+
const session = { connection: live, transport: BotTransport.Live, fetch: async () => new Response('{}') }
|
|
279
|
+
|
|
280
|
+
await expect(plugin.act(session, { kind: BotActionKind.Delete, message: { chat: CUSTOMER, id: 'wamid.1' } })).rejects.toBeInstanceOf(BotUnsupportedAction)
|
|
281
|
+
await expect(plugin.act(session, { kind: BotActionKind.Mute, chat: CUSTOMER, user: CUSTOMER, until: new Date() })).rejects.toThrow('bot:unsupported-action:mute')
|
|
282
|
+
await expect(plugin.act(session, { kind: BotActionKind.Ban, chat: CUSTOMER, user: CUSTOMER })).rejects.toThrow('bot:unsupported-action:ban')
|
|
283
|
+
})
|
|
284
|
+
|
|
285
|
+
test('the mock answers like the Graph API: wamids, contacts, `{ error }` refusals, recorded calls', async () => {
|
|
286
|
+
const mockConnection: BotPlatformConnection = { ...live, id: `mock-${Date.now()}`, transport: BotTransport.Mock, credentials: {} }
|
|
287
|
+
const fetch = plugin.mock.fetch(mockConnection)
|
|
288
|
+
const number = mock.phoneNumberIdOf(mockConnection)
|
|
289
|
+
const post = async (body: object, id: string = number): Promise<any> =>
|
|
290
|
+
await (await fetch(`https://graph.facebook.com/v26.0/${id}/messages`, { method: 'POST', body: JSON.stringify(body) })).json()
|
|
291
|
+
const text = (body: string) => ({ messaging_product: 'whatsapp', recipient_type: 'individual', to: CUSTOMER, type: 'text', text: { body } })
|
|
292
|
+
|
|
293
|
+
expect(number).toMatch(/^\d{15}$/)
|
|
294
|
+
const first = await post(text('one'))
|
|
295
|
+
const second = await post(text('two'))
|
|
296
|
+
expect(first.contacts).toEqual([{ input: CUSTOMER, wa_id: CUSTOMER }])
|
|
297
|
+
expect([first.messages[0].id.startsWith('wamid.'), first.messages[0].id === second.messages[0].id]).toEqual([true, false])
|
|
298
|
+
expect((await post(text(' '))).error).toMatchObject({ code: 100, type: 'OAuthException', message: '(#100) The parameter text[\'body\'] is required.' })
|
|
299
|
+
expect((await post(text('x'), '123')).error).toMatchObject({ code: 100, error_subcode: 33 })
|
|
300
|
+
const phone = await (await fetch(`https://graph.facebook.com/v26.0/${number}?fields=verified_name`)).json()
|
|
301
|
+
expect(phone).toEqual({ id: number, verified_name: 'Bakery' })
|
|
302
|
+
expect(plugin.mock.calls(mockConnection.id).map(call => call.method)).toEqual(['messages', 'messages', 'messages', 'messages', 'phone-number'])
|
|
303
|
+
})
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
describe('@owlmeans/bot-whatsapp — WhatsApp through the service (mock transport)', () => {
|
|
307
|
+
const runtimes: BotRuntime[] = []
|
|
308
|
+
afterEach(async () => {
|
|
309
|
+
await Promise.all(runtimes.splice(0).map(async runtime => { await runtime.stop() }))
|
|
310
|
+
})
|
|
311
|
+
const hook = makeBotHookProtocols({ base: { alias: 'api:bot:hook', path: '/bot/hook' } })
|
|
312
|
+
|
|
313
|
+
const connect = async (bot: TestBot, scope: string, credentials?: Record<string, string>) => {
|
|
314
|
+
const saved = await bot.service.connections.save(scope, {
|
|
315
|
+
platform: 'whatsapp', label: 'Bakery', transport: BotTransport.Mock, ...(credentials != null ? { credentials } : {}),
|
|
316
|
+
}, 'https://shop.example.com')
|
|
317
|
+
return await bot.service.connections.verify(scope, saved.id)
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
test('a service given the plugin lists WhatsApp\'s descriptor', () => {
|
|
321
|
+
expect(makeTestBot().service.platforms().map(entry => entry.platform)).toEqual([WHATSAPP_PLATFORM])
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
test('save → verify: a webhook connection with the mock number and the manual setup steps', async () => {
|
|
325
|
+
const bot = makeTestBot()
|
|
326
|
+
const scope = scopeOf()
|
|
327
|
+
const verified = await connect(bot, scope)
|
|
328
|
+
const record = await bot.connections.get(verified.id)
|
|
329
|
+
const opened = { ...verified, credentials: {}, hookSecret: record.hookSecret }
|
|
330
|
+
|
|
331
|
+
expect([verified.status, verified.receive, verified.hookUrl]).toEqual([
|
|
332
|
+
BotConnectionStatus.Connected, BotReceiveMode.Webhook, `https://shop.example.com/api/bot/hook/whatsapp/${verified.id}`,
|
|
333
|
+
])
|
|
334
|
+
expect(verified.identity).toEqual({ id: mock.phoneNumberIdOf(opened), username: mock.displayNumberOf(opened), name: 'Bakery' })
|
|
335
|
+
expect(verified.credentialsSet).toContain('verifyToken')
|
|
336
|
+
expect(verified.setup?.[1]).toBe(`Set the Callback URL to ${verified.hookUrl}`)
|
|
337
|
+
expect(verified.setup?.[2]).toBe(`Set the Verify token to ${record.hookSecret}`)
|
|
338
|
+
expect(verified.setup?.some(step => step.includes('"messages"'))).toBe(true)
|
|
339
|
+
expect(mock.calls(verified.id).map(call => [call.method, call.params])).toEqual([['phone-number', { fields: 'display_phone_number,verified_name' }]])
|
|
340
|
+
})
|
|
341
|
+
|
|
342
|
+
test('simulate → runtime: a handler replies and reacts — the Cloud API bodies, activity as mock', async () => {
|
|
343
|
+
const bot = makeTestBot()
|
|
344
|
+
const scope = scopeOf()
|
|
345
|
+
const connection = await connect(bot, scope)
|
|
346
|
+
// The application's own keyword group with its fixed answer, matched by the handler.
|
|
347
|
+
const hours = { id: 'group-hours', keywords: ['open'], reply: 'We open at 7.' }
|
|
348
|
+
const seen: BotUpdate[] = []
|
|
349
|
+
const runtime = bot.service.runtime([botHandler('answer', async (update, actions) => {
|
|
350
|
+
seen.push(update)
|
|
351
|
+
if (botTextHelper.matched(update.message?.text ?? '', hours.keywords).length > 0) {
|
|
352
|
+
const reply = await actions.reply(update, hours.reply, { ref: hours.id })
|
|
353
|
+
expect(reply.ok).toBe(true)
|
|
354
|
+
expect(reply.message?.chat).toBe(update.chat.id)
|
|
355
|
+
expect(reply.message?.id.startsWith('wamid.')).toBe(true)
|
|
356
|
+
expect((await actions.react(update, '🥐', { ref: hours.id })).ok).toBe(true)
|
|
357
|
+
}
|
|
358
|
+
})])
|
|
359
|
+
runtimes.push(runtime)
|
|
360
|
+
|
|
361
|
+
const { update } = await bot.service.simulate(scope, connection.id, { text: 'When are you OPEN?', sender: { id: '+447700900123', name: 'Ann' } })
|
|
362
|
+
expect(await runtime.dispatch()).toBe(1)
|
|
363
|
+
|
|
364
|
+
const [message] = seen
|
|
365
|
+
expect([message.chat, message.sender, message.addressed, message.message?.text]).toEqual([
|
|
366
|
+
{ id: '447700900123', kind: BotChatKind.Private, title: 'Ann' }, { id: '447700900123', name: 'Ann', bot: false }, true, 'When are you OPEN?',
|
|
367
|
+
])
|
|
368
|
+
expect((await bot.updates.get(update)).status).toBe(BotInboxStatus.Done)
|
|
369
|
+
const sent = mock.calls(connection.id).filter(call => call.method === 'messages').map(call => call.params)
|
|
370
|
+
expect(sent).toEqual([
|
|
371
|
+
{
|
|
372
|
+
messaging_product: 'whatsapp', recipient_type: 'individual', to: '447700900123',
|
|
373
|
+
context: { message_id: message.message!.ref.id }, type: 'text', text: { body: 'We open at 7.' },
|
|
374
|
+
},
|
|
375
|
+
{
|
|
376
|
+
messaging_product: 'whatsapp', recipient_type: 'individual', to: '447700900123',
|
|
377
|
+
type: 'reaction', reaction: { message_id: message.message!.ref.id, emoji: '🥐' },
|
|
378
|
+
},
|
|
379
|
+
])
|
|
380
|
+
const activity = await bot.service.activity.list(scope)
|
|
381
|
+
expect(activity.map(entry => [entry.action, entry.ok, entry.transport, entry.ref, entry.update, entry.target])).toEqual([
|
|
382
|
+
[BotActionKind.React, true, BotTransport.Mock, hours.id, update, { chat: '447700900123', message: message.message!.ref.id }],
|
|
383
|
+
[BotActionKind.Reply, true, BotTransport.Mock, hours.id, update, { chat: '447700900123', message: message.message!.ref.id }],
|
|
384
|
+
])
|
|
385
|
+
})
|
|
386
|
+
|
|
387
|
+
test('a simulated reply to the bot\'s own message is a reply to the bot', async () => {
|
|
388
|
+
const bot = makeTestBot()
|
|
389
|
+
const scope = scopeOf()
|
|
390
|
+
const connection = await connect(bot, scope)
|
|
391
|
+
const actions = await bot.service.actions({ scope, connection: connection.id })
|
|
392
|
+
const sent = await actions.send(CUSTOMER, 'Your order is ready')
|
|
393
|
+
const { update } = await bot.service.simulate(scope, connection.id, { text: 'thanks', sender: { id: CUSTOMER }, replyTo: { id: sent.message!.id } })
|
|
394
|
+
|
|
395
|
+
expect((await bot.updates.get(update)).update.message?.replyTo).toEqual({
|
|
396
|
+
chat: CUSTOMER, id: sent.message!.id, sender: { id: connection.identity!.id, name: 'Bakery', username: connection.identity!.username, bot: true },
|
|
397
|
+
})
|
|
398
|
+
})
|
|
399
|
+
|
|
400
|
+
test('delete, mute and ban answer ok:false with a failed activity — never a throw', async () => {
|
|
401
|
+
const bot = makeTestBot()
|
|
402
|
+
const scope = scopeOf()
|
|
403
|
+
const connection = await connect(bot, scope)
|
|
404
|
+
const runtime = bot.service.runtime([botHandler('moderate', async (update, actions) => {
|
|
405
|
+
expect([actions.supports(BotActionKind.Reply), actions.supports(BotActionKind.React), actions.supports(BotActionKind.Delete)])
|
|
406
|
+
.toEqual([true, true, false])
|
|
407
|
+
expect(await actions.delete(update)).toEqual({ ok: false, error: 'WhatsApp cannot delete messages.', code: 'bot:unsupported-action:delete' })
|
|
408
|
+
expect(await actions.mute(update, { minutes: 5 })).toEqual({ ok: false, error: 'WhatsApp cannot mute members.', code: 'bot:unsupported-action:mute' })
|
|
409
|
+
expect(await actions.ban(update)).toEqual({ ok: false, error: 'WhatsApp cannot ban members.', code: 'bot:unsupported-action:ban' })
|
|
410
|
+
})])
|
|
411
|
+
runtimes.push(runtime)
|
|
412
|
+
await bot.service.simulate(scope, connection.id, { text: 'spam' })
|
|
413
|
+
await runtime.dispatch()
|
|
414
|
+
|
|
415
|
+
expect((await bot.service.activity.list(scope)).map(entry => [entry.action, entry.ok, entry.transport])).toEqual([
|
|
416
|
+
[BotActionKind.Ban, false, BotTransport.Mock], [BotActionKind.Mute, false, BotTransport.Mock], [BotActionKind.Delete, false, BotTransport.Mock],
|
|
417
|
+
])
|
|
418
|
+
expect(mock.calls(connection.id).filter(call => call.method === 'messages')).toEqual([])
|
|
419
|
+
})
|
|
420
|
+
|
|
421
|
+
test('the hook routes: the GET handshake answers hub.challenge; a signed POST is stored once; forged or stale ones are refused', async () => {
|
|
422
|
+
const bot = makeTestBot()
|
|
423
|
+
const scope = scopeOf()
|
|
424
|
+
const connection = await connect(bot, scope)
|
|
425
|
+
const record = await bot.connections.get(connection.id)
|
|
426
|
+
const bindings = serveBotHookEntrypoints(hook)
|
|
427
|
+
bot.context.registerEntrypoints(bindings)
|
|
428
|
+
const at = (alias: string) => bindings.find(binding => binding.alias === alias)!
|
|
429
|
+
const params = { platform: 'whatsapp', connection: connection.id }
|
|
430
|
+
const opened = { ...connection, credentials: {}, hookSecret: record.hookSecret }
|
|
431
|
+
|
|
432
|
+
const handshake = mock.challenge(opened, { challenge: '1158201444' })
|
|
433
|
+
expect(await invoke(at(hook.challenge.alias), { params, query: handshake.query })).toBe('1158201444')
|
|
434
|
+
await expect(invoke(at(hook.challenge.alias), { params, query: mock.challenge(opened, { verifyToken: 'guess' }).query }))
|
|
435
|
+
.rejects.toBeInstanceOf(BotSignatureRejected)
|
|
436
|
+
|
|
437
|
+
const signed = botMockHelper.inbound('whatsapp', { text: 'hello' }, record)
|
|
438
|
+
const request = { params, headers: signed.headers, body: signed.body, original: { rawBody: signed.rawBody } }
|
|
439
|
+
expect(await invoke(at(hook.receive.alias), request)).toEqual({ ok: true })
|
|
440
|
+
expect(await invoke(at(hook.receive.alias), request)).toEqual({ ok: true })
|
|
441
|
+
expect(await bot.updates.count({ connection: connection.id })).toBe(1)
|
|
442
|
+
|
|
443
|
+
const forged = botMockHelper.inbound('whatsapp', { text: 'forged' }, { ...record, hookSecret: 'not-the-secret' })
|
|
444
|
+
await expect(invoke(at(hook.receive.alias), { params, headers: forged.headers, body: forged.body, original: { rawBody: forged.rawBody } }))
|
|
445
|
+
.rejects.toBeInstanceOf(BotSignatureRejected)
|
|
446
|
+
await expect(invoke(at(hook.receive.alias), {
|
|
447
|
+
params, headers: signed.headers, body: signed.body, original: { rawBody: signed.rawBody.replace('hello', 'hellO') },
|
|
448
|
+
})).rejects.toBeInstanceOf(BotSignatureRejected)
|
|
449
|
+
|
|
450
|
+
const statuses = JSON.stringify(webhook({ statuses: [{ id: 'wamid.S', status: 'read', timestamp: '1', recipient_id: CUSTOMER }] }))
|
|
451
|
+
const receipt = await bot.service.receive('whatsapp', connection.id, {
|
|
452
|
+
method: 'POST', headers: { [WHATSAPP_SIGNATURE_HEADER]: whatsappSignatureHelper.sign(statuses, record.hookSecret) }, rawBody: statuses,
|
|
453
|
+
})
|
|
454
|
+
expect(receipt).toEqual({ reply: { ok: true }, updates: [] })
|
|
455
|
+
expect(await bot.updates.count({ connection: connection.id })).toBe(1)
|
|
456
|
+
})
|
|
457
|
+
|
|
458
|
+
test('a mock connection with an app secret is signed and checked with it, not with the hook secret', async () => {
|
|
459
|
+
const bot = makeTestBot()
|
|
460
|
+
const scope = scopeOf()
|
|
461
|
+
const connection = await connect(bot, scope, { appSecret: 'mock-app-secret' })
|
|
462
|
+
const record = await bot.connections.get(connection.id)
|
|
463
|
+
|
|
464
|
+
const { update } = await bot.service.simulate(scope, connection.id, { text: 'signed with the app secret' })
|
|
465
|
+
expect((await bot.updates.get(update)).update.message?.text).toBe('signed with the app secret')
|
|
466
|
+
|
|
467
|
+
const signedByApp = botMockHelper.inbound('whatsapp', { text: 'a' }, { ...record, credentials: { appSecret: 'mock-app-secret' } })
|
|
468
|
+
const signedByHook = botMockHelper.inbound('whatsapp', { text: 'b' }, record)
|
|
469
|
+
const receive = async (inbound: typeof signedByApp) => await bot.service.receive('whatsapp', connection.id, {
|
|
470
|
+
method: 'POST', headers: inbound.headers, body: inbound.body, rawBody: inbound.rawBody,
|
|
471
|
+
})
|
|
472
|
+
expect((await receive(signedByApp)).updates.length).toBe(1)
|
|
473
|
+
await expect(receive(signedByHook)).rejects.toBeInstanceOf(BotSignatureRejected)
|
|
474
|
+
})
|
|
475
|
+
|
|
476
|
+
test('a live connection needs its credentials to verify', async () => {
|
|
477
|
+
const bot = makeTestBot()
|
|
478
|
+
const scope = scopeOf()
|
|
479
|
+
const saved = await bot.service.connections.save(scope, { platform: 'whatsapp', label: 'Live', credentials: { accessToken: 'x' } })
|
|
480
|
+
|
|
481
|
+
await expect(bot.service.connections.verify(scope, saved.id)).rejects.toBeInstanceOf(BotCredentialsRejected)
|
|
482
|
+
const failed = await bot.service.connections.get(scope, saved.id)
|
|
483
|
+
expect([failed.status, failed.lastError]).toEqual([BotConnectionStatus.Failed, 'bot:credentials-rejected:missing:phoneNumberId,appSecret'])
|
|
484
|
+
})
|
|
485
|
+
})
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": [
|
|
3
|
+
"@owlmeans/dep-config/tsconfig.base.json",
|
|
4
|
+
"@owlmeans/dep-config/tsconfig.node.json"
|
|
5
|
+
],
|
|
6
|
+
"compilerOptions": {
|
|
7
|
+
"rootDir": "./src/",
|
|
8
|
+
"outDir": "./build/"
|
|
9
|
+
},
|
|
10
|
+
"exclude": [
|
|
11
|
+
"./dist/**/*",
|
|
12
|
+
"./build/**/*",
|
|
13
|
+
"./tests/**/*",
|
|
14
|
+
"./*.ts"
|
|
15
|
+
]
|
|
16
|
+
}
|