@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.
Files changed (60) hide show
  1. package/README.md +74 -2
  2. package/agent-meta/manifest.json +16 -0
  3. package/agent-meta/skills/bot-whatsapp/SKILL.md +104 -0
  4. package/build/api.d.ts +7 -0
  5. package/build/api.d.ts.map +1 -0
  6. package/build/api.js +50 -0
  7. package/build/api.js.map +1 -0
  8. package/build/append.d.ts +10 -0
  9. package/build/append.d.ts.map +1 -0
  10. package/build/append.js +13 -0
  11. package/build/append.js.map +1 -0
  12. package/build/consts.d.ts +57 -0
  13. package/build/consts.d.ts.map +1 -0
  14. package/build/consts.js +183 -0
  15. package/build/consts.js.map +1 -0
  16. package/build/errors.d.ts +22 -0
  17. package/build/errors.d.ts.map +1 -0
  18. package/build/errors.js +34 -0
  19. package/build/errors.js.map +1 -0
  20. package/build/index.d.ts +7 -0
  21. package/build/index.d.ts.map +1 -0
  22. package/build/index.js +6 -0
  23. package/build/index.js.map +1 -0
  24. package/build/mock.d.ts +9 -0
  25. package/build/mock.d.ts.map +1 -0
  26. package/build/mock.js +198 -0
  27. package/build/mock.js.map +1 -0
  28. package/build/normalize.d.ts +4 -0
  29. package/build/normalize.d.ts.map +1 -0
  30. package/build/normalize.js +109 -0
  31. package/build/normalize.js.map +1 -0
  32. package/build/plugin.d.ts +13 -0
  33. package/build/plugin.d.ts.map +1 -0
  34. package/build/plugin.js +147 -0
  35. package/build/plugin.js.map +1 -0
  36. package/build/signature.d.ts +4 -0
  37. package/build/signature.d.ts.map +1 -0
  38. package/build/signature.js +20 -0
  39. package/build/signature.js.map +1 -0
  40. package/build/types.d.ts +179 -0
  41. package/build/types.d.ts.map +1 -0
  42. package/build/types.js +2 -0
  43. package/build/types.js.map +1 -0
  44. package/package.json +56 -4
  45. package/src/api.ts +62 -0
  46. package/src/append.ts +18 -0
  47. package/src/consts.ts +206 -0
  48. package/src/errors.ts +37 -0
  49. package/src/index.ts +6 -0
  50. package/src/mock.ts +243 -0
  51. package/src/normalize.ts +131 -0
  52. package/src/plugin.ts +183 -0
  53. package/src/signature.ts +27 -0
  54. package/src/types.ts +174 -0
  55. package/tests/context.ts +85 -0
  56. package/tests/descriptor.spec.ts +64 -0
  57. package/tests/mock-ids.spec.ts +38 -0
  58. package/tests/tsconfig.json +12 -0
  59. package/tests/whatsapp.spec.ts +485 -0
  60. package/tsconfig.json +16 -0
package/src/mock.ts ADDED
@@ -0,0 +1,243 @@
1
+ import { createHash, randomBytes, randomInt } from 'node:crypto'
2
+ import type { BotSimulateInput } from '@owlmeans/bot'
3
+ import type { BotHookRequest } from '@owlmeans/server-bot'
4
+ import type { BotFetch, BotFetchInit, BotMockCall, BotNativeInbound, BotPlatformConnection } from '@owlmeans/server-bot'
5
+ import {
6
+ WHATSAPP_HUB_MODE, WHATSAPP_MESSAGES_FIELD, WHATSAPP_MESSAGING_PRODUCT, WHATSAPP_MOCK_BUSINESS_NAME,
7
+ WHATSAPP_MOCK_ID_BYTES, WHATSAPP_MOCK_NUMBER_PREFIX, WHATSAPP_MOCK_PHONE_ID_BASE, WHATSAPP_MOCK_SENDER_ID,
8
+ WHATSAPP_MOCK_SENDER_NAME, WHATSAPP_SIGNATURE_HEADER, WHATSAPP_TEXT_MAX, WHATSAPP_WEBHOOK_OBJECT,
9
+ } from './consts.js'
10
+ import { whatsappSignatureHelper } from './signature.js'
11
+ import type {
12
+ WhatsAppErrorEnvelope, WhatsAppMessage, WhatsAppMock, WhatsAppMockState, WhatsAppPhoneNumber, WhatsAppSendAnswer,
13
+ WhatsAppWebhook,
14
+ } from './types.js'
15
+
16
+ /**
17
+ * The Cloud API, faked per connection and in process: the same paths, answers and `{ error }`
18
+ * refusals the Graph API gives, no network. `GET /<phone-number-id>` answers the connection's test
19
+ * number, `POST /<phone-number-id>/messages` answers a random `wamid.…` per text or reaction, and the inbound
20
+ * builder writes Meta's webhook payload signed with the app secret (the hook secret when there is none).
21
+ */
22
+ export const makeWhatsAppMock = (): WhatsAppMock => {
23
+ const states = new Map<string, WhatsAppMockState>()
24
+
25
+ const stateOf = (connection: string): WhatsAppMockState => {
26
+ let state = states.get(connection)
27
+ if (state == null) {
28
+ state = { calls: [], sent: new Set(), fed: [] }
29
+ states.set(connection, state)
30
+ }
31
+
32
+ return state
33
+ }
34
+
35
+ /** A stable non-negative integer below `modulo`, derived from a text. */
36
+ const hashOf = (text: string, modulo: number): number =>
37
+ Number.parseInt(createHash('sha256').update(text).digest('hex').slice(0, 13), 16) % modulo
38
+
39
+ const digitsOf = (value: string | undefined): string => (value ?? '').replace(/\D/g, '')
40
+
41
+ const phoneNumberIdOf = (connection: BotPlatformConnection): string => {
42
+ const given = connection.credentials.phoneNumberId ?? ''
43
+ return given !== '' ? given : `${WHATSAPP_MOCK_PHONE_ID_BASE + hashOf(connection.id, 9 * WHATSAPP_MOCK_PHONE_ID_BASE)}`
44
+ }
45
+
46
+ const displayNumberOf = (connection: BotPlatformConnection): string =>
47
+ `${WHATSAPP_MOCK_NUMBER_PREFIX}${`${hashOf(`${connection.id}:number`, 10_000_000)}`.padStart(7, '0')}`
48
+
49
+ const businessAccountOf = (connection: BotPlatformConnection): string =>
50
+ `${WHATSAPP_MOCK_PHONE_ID_BASE + hashOf(`${connection.id}:account`, 9 * WHATSAPP_MOCK_PHONE_ID_BASE)}`
51
+
52
+ /** A customer's `wa_id` from a simulated id: a phone number stays itself, any other text maps to a stable number. */
53
+ const waIdOf = (value: string | undefined): string => {
54
+ if (value == null || value === '') {
55
+ return WHATSAPP_MOCK_SENDER_ID
56
+ }
57
+ if (/^\+?\d{6,15}$/.test(value)) {
58
+ return digitsOf(value)
59
+ }
60
+
61
+ return `1${`${hashOf(value, 10_000_000_000)}`.padStart(10, '0')}`
62
+ }
63
+
64
+ /** A fresh `wamid.…`: random, so no restart and no other process hands out one an inbox already holds. */
65
+ const wamidOf = (connection: string): string =>
66
+ `wamid.${Buffer.from(`mock:${connection}:${randomBytes(WHATSAPP_MOCK_ID_BYTES).toString('hex').toUpperCase()}`, 'utf8').toString('base64')}`
67
+
68
+ const answer = (status: number, body: unknown): Response =>
69
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
70
+
71
+ const refuse = (message: string, code: number = 100, subcode?: number): Response => {
72
+ const envelope: WhatsAppErrorEnvelope = {
73
+ error: {
74
+ message: `(#${code}) ${message}`, type: 'OAuthException', code,
75
+ ...(subcode != null ? { error_subcode: subcode } : {}), fbtrace_id: 'AMockTraceId',
76
+ },
77
+ }
78
+
79
+ return answer(400, envelope)
80
+ }
81
+
82
+ const unknownObject = (id: string): Response => refuse(
83
+ `Unsupported request. Object with ID '${id}' does not exist, cannot be loaded due to missing permissions, or does not support this operation`,
84
+ 100, 33
85
+ )
86
+
87
+ const aborted = (): Error => {
88
+ const error = new Error('The operation was aborted.')
89
+ error.name = 'AbortError'
90
+ return error
91
+ }
92
+
93
+ const phoneNumber = (connection: BotPlatformConnection, id: string, fields: string | null): Response => {
94
+ const full: Required<WhatsAppPhoneNumber> & Record<string, string> = {
95
+ id,
96
+ display_phone_number: displayNumberOf(connection),
97
+ verified_name: connection.label !== '' ? connection.label : WHATSAPP_MOCK_BUSINESS_NAME,
98
+ quality_rating: 'GREEN',
99
+ code_verification_status: 'VERIFIED',
100
+ }
101
+ const wanted = fields != null && fields.trim() !== '' ? fields.split(',').map(field => field.trim()) : Object.keys(full)
102
+
103
+ return answer(200, Object.fromEntries(Object.entries(full).filter(([key]) => key === 'id' || wanted.includes(key))))
104
+ }
105
+
106
+ const messages = (connection: BotPlatformConnection, state: WhatsAppMockState, params: Record<string, unknown>): Response => {
107
+ if (params.messaging_product !== WHATSAPP_MESSAGING_PRODUCT) {
108
+ return refuse('The parameter messaging_product is required.')
109
+ }
110
+ const to = typeof params.to === 'string' ? params.to : ''
111
+ if (to.trim() === '') {
112
+ return refuse('The parameter to is required.')
113
+ }
114
+ const type = typeof params.type === 'string' ? params.type : 'text'
115
+ if (type === 'text') {
116
+ const body = (params.text as { body?: unknown } | undefined)?.body
117
+ if (typeof body !== 'string' || body.trim() === '') {
118
+ return refuse('The parameter text[\'body\'] is required.')
119
+ }
120
+ if (body.length > WHATSAPP_TEXT_MAX) {
121
+ return refuse(`Param text['body'] must be at most ${WHATSAPP_TEXT_MAX} characters long.`)
122
+ }
123
+ } else if (type === 'reaction') {
124
+ const reaction = params.reaction as { message_id?: unknown, emoji?: unknown } | undefined
125
+ if (typeof reaction?.message_id !== 'string' || reaction.message_id === '') {
126
+ return refuse('The parameter reaction[\'message_id\'] is required.')
127
+ }
128
+ if (typeof reaction.emoji !== 'string') {
129
+ return refuse('The parameter reaction[\'emoji\'] is required.')
130
+ }
131
+ } else {
132
+ return refuse(`Param type must be one of {TEXT, REACTION} in this mock — got ${type}.`)
133
+ }
134
+ const id = wamidOf(connection.id)
135
+ if (type === 'text') {
136
+ state.sent.add(id)
137
+ }
138
+ const sent: WhatsAppSendAnswer = {
139
+ messaging_product: WHATSAPP_MESSAGING_PRODUCT,
140
+ contacts: [{ input: to, wa_id: digitsOf(to) }],
141
+ messages: [{ id }],
142
+ }
143
+
144
+ return answer(200, sent)
145
+ }
146
+
147
+ const fetch = (connection: BotPlatformConnection): BotFetch => async (url: string, init?: BotFetchInit) => {
148
+ if (init?.signal?.aborted === true) {
149
+ throw aborted()
150
+ }
151
+ const parsed = new URL(url)
152
+ // `/<version>/<phone-number-id>` or `/<version>/<phone-number-id>/messages`.
153
+ const [, node, edge, ...rest] = parsed.pathname.split('/').filter(segment => segment !== '')
154
+ const method = (init?.method ?? 'GET').toUpperCase()
155
+ const state = stateOf(connection.id)
156
+ const number = phoneNumberIdOf(connection)
157
+
158
+ if (method === 'GET' && node != null && edge == null) {
159
+ state.calls.push({ method: 'phone-number', params: Object.fromEntries(parsed.searchParams), at: new Date().toISOString() })
160
+ return node === number ? phoneNumber(connection, node, parsed.searchParams.get('fields')) : unknownObject(node)
161
+ }
162
+ if (method === 'POST' && node != null && edge === WHATSAPP_MESSAGES_FIELD && rest.length === 0) {
163
+ let params: Record<string, unknown>
164
+ try {
165
+ params = init?.body != null && init.body !== '' ? JSON.parse(init.body) as Record<string, unknown> : {}
166
+ } catch {
167
+ return refuse('Invalid JSON for postcontent')
168
+ }
169
+ state.calls.push({ method: 'messages', params, at: new Date().toISOString() })
170
+ return node === number ? messages(connection, state, params) : unknownObject(node)
171
+ }
172
+
173
+ return refuse(`Unknown path components: /${[edge, ...rest].filter(part => part != null).join('/')}`, 2500)
174
+ }
175
+
176
+ const inbound = (input: BotSimulateInput, connection: BotPlatformConnection): BotNativeInbound => {
177
+ const state = stateOf(connection.id)
178
+ const from = waIdOf(input.sender?.id)
179
+ const display = digitsOf(connection.identity?.username) !== '' ? digitsOf(connection.identity?.username) : displayNumberOf(connection)
180
+ const message: WhatsAppMessage = {
181
+ from,
182
+ id: wamidOf(connection.id),
183
+ timestamp: `${Math.floor(Date.now() / 1000)}`,
184
+ type: 'text',
185
+ text: { body: input.text },
186
+ // The quoted message's author: the business when the fake API sent it, else the customer.
187
+ ...(input.replyTo != null ? { context: { from: state.sent.has(input.replyTo.id) ? display : from, id: input.replyTo.id } } : {}),
188
+ }
189
+ const body: WhatsAppWebhook = {
190
+ object: WHATSAPP_WEBHOOK_OBJECT,
191
+ entry: [{
192
+ id: businessAccountOf(connection),
193
+ changes: [{
194
+ value: {
195
+ messaging_product: WHATSAPP_MESSAGING_PRODUCT,
196
+ metadata: { display_phone_number: display, phone_number_id: connection.identity?.id ?? phoneNumberIdOf(connection) },
197
+ contacts: [{ profile: { name: input.sender?.name ?? WHATSAPP_MOCK_SENDER_NAME }, wa_id: from }],
198
+ messages: [message],
199
+ },
200
+ field: WHATSAPP_MESSAGES_FIELD,
201
+ }],
202
+ }],
203
+ }
204
+ const rawBody = JSON.stringify(body)
205
+ const appSecret = connection.credentials.appSecret ?? ''
206
+
207
+ return {
208
+ body,
209
+ rawBody,
210
+ headers: {
211
+ 'content-type': 'application/json',
212
+ [WHATSAPP_SIGNATURE_HEADER]: whatsappSignatureHelper.sign(rawBody, appSecret !== '' ? appSecret : connection.hookSecret),
213
+ },
214
+ }
215
+ }
216
+
217
+ const challenge: WhatsAppMock['challenge'] = (connection, opts = {}): BotHookRequest => ({
218
+ method: 'GET',
219
+ headers: {},
220
+ query: {
221
+ 'hub.mode': WHATSAPP_HUB_MODE,
222
+ 'hub.challenge': opts.challenge ?? `${randomInt(1_000_000_000, 2_000_000_000)}`,
223
+ 'hub.verify_token': opts.verifyToken ?? (connection.credentials.verifyToken || connection.hookSecret),
224
+ },
225
+ })
226
+
227
+ /** WhatsApp has no receiver (webhook only): a fed payload is kept, never delivered — `simulate` posts instead. */
228
+ const feed = (connection: string, payload: unknown): void => {
229
+ stateOf(connection).fed.push(payload)
230
+ }
231
+
232
+ const calls = (connection: string): BotMockCall[] => [...(states.get(connection)?.calls ?? [])]
233
+
234
+ const reset = (connection?: string): void => {
235
+ if (connection == null) {
236
+ states.clear()
237
+ return
238
+ }
239
+ states.delete(connection)
240
+ }
241
+
242
+ return { fetch, inbound, feed, calls, reset, phoneNumberIdOf, displayNumberOf, challenge }
243
+ }
@@ -0,0 +1,131 @@
1
+ import {
2
+ botCommandHelper, BotChatKind, BotUpdateKind, type BotConnection, type BotMessage, type BotSenderRef,
3
+ } from '@owlmeans/bot'
4
+ import type { BotNormalizedUpdate } from '@owlmeans/server-bot'
5
+ import { WHATSAPP_CAPTIONED_TYPES, WHATSAPP_MESSAGES_FIELD, WHATSAPP_WEBHOOK_OBJECT } from './consts.js'
6
+ import type {
7
+ WhatsAppContact, WhatsAppMessage, WhatsAppMetadata, WhatsAppNormalizer, WhatsAppValue, WhatsAppWebhook,
8
+ } from './types.js'
9
+
10
+ export const createWhatsAppNormalizer = (): WhatsAppNormalizer => {
11
+ const iso = (unix: string | undefined): string => {
12
+ const seconds = Number(unix)
13
+ return new Date((Number.isFinite(seconds) && seconds > 0 ? seconds : Date.now() / 1000) * 1000).toISOString()
14
+ }
15
+
16
+ const digitsOf = (value: string | undefined): string => (value ?? '').replace(/\D/g, '')
17
+
18
+ /** The text a message carries: a text body, a tapped button or list row, a media caption; none for other kinds. */
19
+ const textOf = (message: WhatsAppMessage): string | undefined => {
20
+ switch (message.type) {
21
+ case 'text':
22
+ return typeof message.text?.body === 'string' ? message.text.body : undefined
23
+ case 'interactive':
24
+ return message.interactive?.button_reply?.title ?? message.interactive?.list_reply?.title
25
+ case 'button':
26
+ return message.button?.text ?? message.button?.payload
27
+ default:
28
+ if (WHATSAPP_CAPTIONED_TYPES.includes(message.type)) {
29
+ const media = message[message.type as 'image' | 'video' | 'document']
30
+ return media != null ? media.caption ?? '' : undefined
31
+ }
32
+ return undefined
33
+ }
34
+ }
35
+
36
+ /** The profile of the customer who wrote — by `wa_id`, else the only contact of the change. */
37
+ const contactOf = (value: WhatsAppValue, message: WhatsAppMessage): WhatsAppContact | undefined => {
38
+ const contacts = Array.isArray(value.contacts) ? value.contacts : []
39
+ return contacts.find(contact => contact.wa_id === message.from) ?? (contacts.length === 1 ? contacts[0] : undefined)
40
+ }
41
+
42
+ /** The business number of the change — the bot — as a sender. */
43
+ const botOf = (metadata: WhatsAppMetadata | undefined, connection: BotConnection): BotSenderRef => {
44
+ const id = connection.identity?.id ?? metadata?.phone_number_id ?? ''
45
+ const username = metadata?.display_phone_number ?? connection.identity?.username
46
+ const name = connection.identity?.name
47
+
48
+ return { id, ...(name != null ? { name } : {}), ...(username != null ? { username } : {}), bot: true }
49
+ }
50
+
51
+ const isBotNumber = (number: string | undefined, metadata: WhatsAppMetadata | undefined, connection: BotConnection): boolean => {
52
+ const digits = digitsOf(number)
53
+ return digits !== '' && (digits === digitsOf(metadata?.display_phone_number) || digits === digitsOf(connection.identity?.username))
54
+ }
55
+
56
+ const messageOf = (
57
+ value: WhatsAppValue, message: WhatsAppMessage, text: string, sender: BotSenderRef, connection: BotConnection
58
+ ): BotMessage => {
59
+ const context = message.context
60
+ const quoted = context?.id != null && context.id !== ''
61
+ ? isBotNumber(context.from, value.metadata, connection)
62
+ ? botOf(value.metadata, connection)
63
+ : context.from != null && context.from !== ''
64
+ ? context.from === message.from ? sender : { id: context.from, bot: false }
65
+ : undefined
66
+ : undefined
67
+
68
+ return {
69
+ ref: { chat: message.from, id: message.id },
70
+ text,
71
+ date: iso(message.timestamp),
72
+ ...(context?.id != null && context.id !== ''
73
+ ? { replyTo: { chat: message.from, id: context.id, ...(quoted != null ? { sender: quoted } : {}) } }
74
+ : {}),
75
+ }
76
+ }
77
+
78
+ const changeOf = (value: WhatsAppValue, connection: BotConnection): BotNormalizedUpdate[] => {
79
+ const own = connection.identity?.id
80
+ const number = value.metadata?.phone_number_id
81
+ // One app posts every number's messages to one URL: another number's are not this connection's.
82
+ if (own != null && own !== '' && number != null && number !== '' && number !== own) {
83
+ return []
84
+ }
85
+ const updates: BotNormalizedUpdate[] = []
86
+ for (const message of Array.isArray(value.messages) ? value.messages : []) {
87
+ if (message == null || typeof message.id !== 'string' || typeof message.from !== 'string') {
88
+ continue
89
+ }
90
+ const text = textOf(message)
91
+ if (text == null) {
92
+ continue
93
+ }
94
+ const contact = contactOf(value, message)
95
+ const name = contact?.profile?.name
96
+ const sender: BotSenderRef = { id: message.from, ...(name != null && name !== '' ? { name } : {}), bot: false }
97
+ const command = botCommandHelper.parse(text) ?? undefined
98
+ updates.push({
99
+ platformId: message.id,
100
+ update: {
101
+ kind: command != null ? BotUpdateKind.Command : BotUpdateKind.Message,
102
+ chat: { id: message.from, kind: BotChatKind.Private, ...(sender.name != null ? { title: sender.name } : {}) },
103
+ sender,
104
+ message: messageOf(value, message, text, sender, connection),
105
+ ...(command != null ? { command } : {}),
106
+ // Cloud API messages are one-to-one: every one is written to the bot.
107
+ addressed: true,
108
+ raw: { metadata: value.metadata, ...(contact != null ? { contact } : {}), message },
109
+ },
110
+ })
111
+ }
112
+
113
+ return updates
114
+ }
115
+
116
+ const normalize = (payload: unknown, connection: BotConnection): BotNormalizedUpdate[] => {
117
+ const webhook = payload as WhatsAppWebhook | null
118
+ if (webhook == null || typeof webhook !== 'object' || webhook.object !== WHATSAPP_WEBHOOK_OBJECT
119
+ || !Array.isArray(webhook.entry)) {
120
+ return []
121
+ }
122
+
123
+ return webhook.entry.flatMap(entry => (Array.isArray(entry?.changes) ? entry.changes : [])
124
+ .filter(change => change?.field === WHATSAPP_MESSAGES_FIELD && change.value != null && typeof change.value === 'object')
125
+ .flatMap(change => changeOf(change.value, connection)))
126
+ }
127
+
128
+ return { normalize }
129
+ }
130
+
131
+ export const whatsappNormalizer = createWhatsAppNormalizer()
package/src/plugin.ts ADDED
@@ -0,0 +1,183 @@
1
+ import {
2
+ BotActionKind, BotCredentialsRejected, BotTransport, BotUnsupportedAction,
3
+ } from '@owlmeans/bot'
4
+ import { botHookHelper } from '@owlmeans/server-bot'
5
+ import type {
6
+ BotAuthentication, BotPlatformAction, BotPlatformActionResult, BotPlatformConnection, BotPlatformIdentity,
7
+ BotPlatformPlugin, BotPlatformSession,
8
+ } from '@owlmeans/server-bot'
9
+ import { makeWhatsAppApi } from './api.js'
10
+ import {
11
+ WHATSAPP_API_BASE, WHATSAPP_API_VERSION, WHATSAPP_CREDENTIAL_ERROR_CODES, WHATSAPP_CREDENTIAL_STATUSES,
12
+ WHATSAPP_DESCRIPTOR, WHATSAPP_HUB_MODE, WHATSAPP_MESSAGES_FIELD, WHATSAPP_MESSAGING_PRODUCT,
13
+ WHATSAPP_PHONE_FIELDS, WHATSAPP_PLATFORM, WHATSAPP_SETUP_CONSOLE, WHATSAPP_SETUP_STEPS,
14
+ WHATSAPP_SIGNATURE_HEADER, WHATSAPP_TEXT_MAX, WHATSAPP_VERIFY_CREDENTIALS,
15
+ } from './consts.js'
16
+ import { WhatsAppApiError } from './errors.js'
17
+ import { makeWhatsAppMock } from './mock.js'
18
+ import { whatsappNormalizer } from './normalize.js'
19
+ import { whatsappSignatureHelper } from './signature.js'
20
+ import type { WhatsAppBotPlatformOptions, WhatsAppPhoneNumber, WhatsAppSendAnswer } from './types.js'
21
+
22
+ /**
23
+ * The WhatsApp plugin over the Cloud API (https://developers.facebook.com/docs/whatsapp/cloud-api):
24
+ * `GET /<phone-number-id>` verifies, a person sets the callback URL and verify token in Meta's
25
+ * console (no hook registration), Meta's `hub.challenge` handshake and its `X-Hub-Signature-256`
26
+ * authenticate, and `POST /<phone-number-id>/messages` replies, sends and reacts. Chats are
27
+ * one-to-one with a customer's `wa_id`; nothing can be deleted, muted or banned.
28
+ */
29
+ export const makeWhatsAppBotPlatform = (opts: WhatsAppBotPlatformOptions = {}): BotPlatformPlugin => {
30
+ const root = `${(opts.base ?? WHATSAPP_API_BASE).replace(/\/+$/, '')}/${(opts.version ?? WHATSAPP_API_VERSION).replace(/^\/+|\/+$/g, '')}`
31
+ const mock = makeWhatsAppMock()
32
+ const api = (session: BotPlatformSession) => makeWhatsAppApi(session, root)
33
+
34
+ /** The business number calls go out from — a mock connection without one gets its fake number. */
35
+ const numberOf = (session: BotPlatformSession): string => {
36
+ const given = session.connection.credentials.phoneNumberId ?? ''
37
+ if (given !== '' || session.transport !== BotTransport.Mock) {
38
+ return given
39
+ }
40
+
41
+ return mock.phoneNumberIdOf(session.connection)
42
+ }
43
+
44
+ /** Clipped to the text limit without splitting a surrogate pair. */
45
+ const clip = (text: string): string => {
46
+ if (text.length <= WHATSAPP_TEXT_MAX) {
47
+ return text
48
+ }
49
+ const cut = text.slice(0, WHATSAPP_TEXT_MAX - 1)
50
+
51
+ return `${/[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut}…`
52
+ }
53
+
54
+ /** The verify token Meta's handshake must present: the typed one, else the hook secret (the core defaults it). */
55
+ const verifyTokenOf = (connection: BotPlatformConnection): string =>
56
+ (connection.credentials.verifyToken ?? '') !== '' ? connection.credentials.verifyToken : connection.hookSecret
57
+
58
+ /** The key Meta signs with: the app secret; a mock connection without one signs with its hook secret. */
59
+ const signingKeyOf = (connection: BotPlatformConnection): string => {
60
+ const appSecret = connection.credentials.appSecret ?? ''
61
+ return appSecret !== '' || connection.transport !== BotTransport.Mock ? appSecret : connection.hookSecret
62
+ }
63
+
64
+ const verify = async (session: BotPlatformSession): Promise<BotPlatformIdentity> => {
65
+ const number = numberOf(session)
66
+ if (session.transport === BotTransport.Live) {
67
+ const missing = WHATSAPP_VERIFY_CREDENTIALS.filter(key => (session.connection.credentials[key] ?? '') === '')
68
+ if (missing.length > 0) {
69
+ throw new BotCredentialsRejected(`missing:${missing.join(',')}`)
70
+ }
71
+ }
72
+ let phone: WhatsAppPhoneNumber
73
+ try {
74
+ phone = await api(session).get<WhatsAppPhoneNumber>(encodeURIComponent(number), { fields: WHATSAPP_PHONE_FIELDS })
75
+ } catch (error) {
76
+ if (error instanceof WhatsAppApiError
77
+ && (WHATSAPP_CREDENTIAL_ERROR_CODES.includes(error.code) || WHATSAPP_CREDENTIAL_STATUSES.includes(error.status))) {
78
+ throw new BotCredentialsRejected(`whatsapp:${error.code}`)
79
+ }
80
+ throw error
81
+ }
82
+
83
+ return {
84
+ id: `${phone.id ?? number}`,
85
+ ...(phone.display_phone_number != null && phone.display_phone_number !== '' ? { username: phone.display_phone_number } : {}),
86
+ ...(phone.verified_name != null && phone.verified_name !== '' ? { name: phone.verified_name } : {}),
87
+ }
88
+ }
89
+
90
+ const setup = (connection: BotPlatformConnection): string[] => [
91
+ WHATSAPP_SETUP_CONSOLE,
92
+ connection.hookUrl != null && connection.hookUrl !== ''
93
+ ? `Set the Callback URL to ${connection.hookUrl}`
94
+ : 'Set the Callback URL to this connection\'s hook URL — save the connection from the application\'s public address to see it.',
95
+ `Set the Verify token to ${verifyTokenOf(connection)}`,
96
+ ...WHATSAPP_SETUP_STEPS,
97
+ ]
98
+
99
+ /** A query value as text — the first of a repeated one; a `hub[mode]`-style nested parse is read too. */
100
+ const hubParam = (query: Record<string, unknown> | undefined, name: string): string | undefined => {
101
+ const flat = query?.[`hub.${name}`]
102
+ const nested = (query?.hub as Record<string, unknown> | undefined)?.[name]
103
+ const value = flat ?? nested
104
+
105
+ return Array.isArray(value) ? (typeof value[0] === 'string' ? value[0] : undefined) : typeof value === 'string' ? value : undefined
106
+ }
107
+
108
+ const authenticate: BotPlatformPlugin['authenticate'] = (request, connection): BotAuthentication => {
109
+ const method = request.method.toUpperCase()
110
+ if (method === 'GET') {
111
+ if (hubParam(request.query, 'mode') !== WHATSAPP_HUB_MODE) {
112
+ return { result: 'reject', reason: 'hub-mode' }
113
+ }
114
+ if (!botHookHelper.sameSecret(hubParam(request.query, 'verify_token'), verifyTokenOf(connection))) {
115
+ return { result: 'reject', reason: 'verify-token' }
116
+ }
117
+ const challenge = hubParam(request.query, 'challenge')
118
+ if (challenge == null || challenge === '') {
119
+ return { result: 'reject', reason: 'hub-challenge' }
120
+ }
121
+
122
+ return { result: 'challenge', text: challenge }
123
+ }
124
+ if (method !== 'POST') {
125
+ return { result: 'reject', reason: 'method' }
126
+ }
127
+ const key = signingKeyOf(connection)
128
+ if (key === '') {
129
+ return { result: 'reject', reason: 'app-secret-missing' }
130
+ }
131
+
132
+ return whatsappSignatureHelper.verify(botHookHelper.header(request, WHATSAPP_SIGNATURE_HEADER), botHookHelper.rawText(request), key)
133
+ ? { result: 'ok' }
134
+ : { result: 'reject', reason: 'signature' }
135
+ }
136
+
137
+ const message = async (
138
+ session: BotPlatformSession, to: string, content: Record<string, unknown>
139
+ ): Promise<WhatsAppSendAnswer> => await api(session).post<WhatsAppSendAnswer>(
140
+ `${encodeURIComponent(numberOf(session))}/${WHATSAPP_MESSAGES_FIELD}`,
141
+ { messaging_product: WHATSAPP_MESSAGING_PRODUCT, recipient_type: 'individual', to, ...content }
142
+ )
143
+
144
+ const createdOf = (answer: WhatsAppSendAnswer, chat: string): BotPlatformActionResult => {
145
+ const id = answer?.messages?.[0]?.id
146
+ return typeof id === 'string' && id !== '' ? { message: { chat, id } } : {}
147
+ }
148
+
149
+ const act = async (session: BotPlatformSession, action: BotPlatformAction): Promise<BotPlatformActionResult> => {
150
+ switch (action.kind) {
151
+ case BotActionKind.Reply:
152
+ return createdOf(await message(session, action.to.chat, {
153
+ context: { message_id: action.to.id }, type: 'text', text: { body: clip(action.text) },
154
+ }), action.to.chat)
155
+ case BotActionKind.Send:
156
+ return createdOf(await message(session, action.chat.id, {
157
+ type: 'text', text: { body: clip(action.text) },
158
+ }), action.chat.id)
159
+ case BotActionKind.React:
160
+ await message(session, action.message.chat, {
161
+ type: 'reaction', reaction: { message_id: action.message.id, emoji: action.emoji },
162
+ })
163
+ return {}
164
+ default:
165
+ // The Cloud API cannot delete a customer's message, mute or ban — the core refuses first.
166
+ throw new BotUnsupportedAction(action.kind)
167
+ }
168
+ }
169
+
170
+ return {
171
+ platform: WHATSAPP_PLATFORM,
172
+ descriptor: WHATSAPP_DESCRIPTOR,
173
+ verify,
174
+ setup,
175
+ authenticate,
176
+ normalize: whatsappNormalizer.normalize,
177
+ act,
178
+ mock,
179
+ }
180
+ }
181
+
182
+ /** The built-in instance (`https://graph.facebook.com/v26.0`) — its `mock` is the one simulated connections use. */
183
+ export const whatsappBotPlatform = makeWhatsAppBotPlatform()
@@ -0,0 +1,27 @@
1
+ import { createHmac } from 'node:crypto'
2
+ import { botHookHelper } from '@owlmeans/server-bot'
3
+ import { WHATSAPP_SIGNATURE_PREFIX } from './consts.js'
4
+ import type { WhatsAppSignatureHelper } from './types.js'
5
+
6
+ export const createWhatsAppSignatureHelper = (): WhatsAppSignatureHelper => {
7
+ const digestOf = (rawBody: string, secret: string): string =>
8
+ createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex')
9
+
10
+ const sign = (rawBody: string, secret: string): string => `${WHATSAPP_SIGNATURE_PREFIX}${digestOf(rawBody, secret)}`
11
+
12
+ const verify = (header: string | undefined, rawBody: string, secret: string): boolean => {
13
+ if (typeof header !== 'string' || secret === '') {
14
+ return false
15
+ }
16
+ const presented = header.trim()
17
+ if (!presented.toLowerCase().startsWith(WHATSAPP_SIGNATURE_PREFIX)) {
18
+ return false
19
+ }
20
+
21
+ return botHookHelper.sameSecret(presented.slice(WHATSAPP_SIGNATURE_PREFIX.length).toLowerCase(), digestOf(rawBody, secret))
22
+ }
23
+
24
+ return { sign, verify }
25
+ }
26
+
27
+ export const whatsappSignatureHelper = createWhatsAppSignatureHelper()