@12-apps/messaging 1.4.0 → 1.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/README.md +39 -0
- package/dist/chunk-RXJNLPY4.js +560 -0
- package/dist/chunk-RXJNLPY4.js.map +1 -0
- package/dist/whatsapp/index.js +22 -536
- package/dist/whatsapp/index.js.map +1 -1
- package/dist/whatsapp-web/index.d.ts +369 -0
- package/dist/whatsapp-web/index.js +588 -0
- package/dist/whatsapp-web/index.js.map +1 -0
- package/package.json +5 -1
- package/src/whatsapp-web/adapter.ts +62 -0
- package/src/whatsapp-web/auth-state.ts +92 -0
- package/src/whatsapp-web/baileys-port.ts +146 -0
- package/src/whatsapp-web/envelope.ts +87 -0
- package/src/whatsapp-web/index.ts +36 -0
- package/src/whatsapp-web/media.ts +78 -0
- package/src/whatsapp-web/normalize.ts +183 -0
- package/src/whatsapp-web/session.ts +306 -0
package/README.md
CHANGED
|
@@ -177,6 +177,7 @@ with `setTranscript` (it is deleted with the text), and drop the buffer.
|
|
|
177
177
|
|---|---|
|
|
178
178
|
| `@12-apps/messaging` | `createMessagingEngine`, the ports, the store port with `createPrismaMessagingStore` and `createMemoryMessagingStore`, the adapter interface, the errors, the types. |
|
|
179
179
|
| `@12-apps/messaging/whatsapp` | `createWhatsAppAdapter`, and standalone: `verifyMetaSignature`, `verifyMetaSubscription`, `parseWhatsAppPayload`, `parseWhatsAppStatuses`, `isOptOutText`, the Graph sender, `downloadWhatsAppMedia`, and the Embedded Signup helpers `exchangeSignupCode`, `readSignupAccounts`, `subscribeAppToWaba`. |
|
|
180
|
+
| `@12-apps/messaging/whatsapp-web` | UNOFFICIAL. `createWhatsAppWebSession` (a linked device over Baileys), `createWhatsAppWebAdapter` (the same `ChannelAdapter`), `createMemoryAuthStateStore`, and the pure `normalizeUpsert`, `normalizeUpdates`, `encodeEnvelope`, `parseEnvelope`. See below. |
|
|
180
181
|
| `@12-apps/messaging/inbound-guard` | `normalizeInbound`, `screenInbound`, `DEFAULT_INBOUND_RULES`, `wrapForAgent`, `parseClassification`: the screen a host runs on untrusted inbound text before a model reads it. Pure, no I/O, no channel. |
|
|
181
182
|
| `@12-apps/messaging/server` | `createApiMessaging` (the webhook route pair, in `@12-apps/wiring`'s `WireRoute` shape) and `MESSAGING_JOBS`. |
|
|
182
183
|
| `@12-apps/messaging/manifest`, `/manifest/server` | The wiring manifests. |
|
|
@@ -185,6 +186,44 @@ The signature check and the receipt parser are exported on their own because a
|
|
|
185
186
|
host that sends WhatsApp messages some other way (a platform notification
|
|
186
187
|
number) needs exactly those two and nothing else.
|
|
187
188
|
|
|
189
|
+
## WhatsApp Web (unofficial)
|
|
190
|
+
|
|
191
|
+
`@12-apps/messaging/whatsapp-web` is a second transport for WhatsApp. It is a linked device over the WhatsApp Web protocol, through [Baileys](https://github.com/WhiskeySockets/Baileys) (MIT). It sits beside the Cloud API adapter and has the same `ChannelAdapter` contract, so a host switches a number between the two by mounting one adapter or the other.
|
|
192
|
+
|
|
193
|
+
**Read this before using it:**
|
|
194
|
+
- **It is not Meta's API.** WhatsApp's terms forbid unofficial clients, and the number it runs on can be banned. Never put a store's only number on it without the store owner's informed yes.
|
|
195
|
+
- **A linked session's keys are the whole account.** Whoever holds the auth state reads and sends every chat. The package writes no key itself: the host passes an `AuthStateStore` and decides where it lives (an encrypted column, a secrets manager). Nothing is logged or put in an error.
|
|
196
|
+
- **A personal account carries other people's messages.** Where they are kept, and for how long, is the host's decision.
|
|
197
|
+
|
|
198
|
+
**Baileys is not a dependency.** The host installs `baileys` (v7) and passes the module in. The package never imports it, and a test fails if a source file does.
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
import * as baileys from "baileys";
|
|
202
|
+
import { createWhatsAppWebAdapter, createWhatsAppWebSession } from "@12-apps/messaging/whatsapp-web";
|
|
203
|
+
|
|
204
|
+
const session = createWhatsAppWebSession({
|
|
205
|
+
baileys,
|
|
206
|
+
authStore, // the host's, sealed
|
|
207
|
+
deliver: (rawBody) => engine.receive("whatsapp", rawBody),
|
|
208
|
+
onStatus: (status) => showPairing(status), // qr | pairing-code | open | logged-out | failed …
|
|
209
|
+
});
|
|
210
|
+
await session.start();
|
|
211
|
+
const engine = createMessagingEngine({ adapters: [createWhatsAppWebAdapter({ sessions: session })], /* … */ });
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
| | |
|
|
215
|
+
|---|---|
|
|
216
|
+
| **Pairing** | `onStatus` reports `qr`: show it on the phone under *Linked devices › Link a device*. With `pairingPhoneNumber`, the session asks ONCE for a code instead (`pairing-code`). After pairing, `creds.update` is saved on every change, and the next `start()` resumes without pairing. |
|
|
217
|
+
| **Inbound** | Each live socket event is normalized into the SAME `NormalizedEvent`s the Cloud parser produces, then handed to `deliver` as a small JSON envelope, in socket order. The envelope holds no Baileys objects and no media keys. The inbox, dedupe, processing job and retention are the engine's, unchanged. A failed `deliver` is reported through `onError`, because a socket does not redeliver. |
|
|
218
|
+
| **What is skipped** | Groups, broadcasts, Status, channels, the account's own messages (`fromMe`), history sync (`append`) and protocol messages. The engine's conversation is one contact. |
|
|
219
|
+
| **Outbound** | `send` goes through the session's socket. Personal accounts have no buttons or lists, so `BUTTONS` and `LIST` become numbered lines under the text, and the answer arrives as `TEXT`. Failures are `ChannelSendFailure`: `NOT_CONNECTED`, the socket's code, or `NO_MESSAGE_ID`. |
|
|
220
|
+
| **Receipts** | `messages.update` on our own messages maps to `SENT` / `DELIVERED` / `READ` / `FAILED`. |
|
|
221
|
+
| **Media** | The last `mediaCacheSize` (200) audio messages stay in memory. `fetchMedia` downloads by message id, with the size cap and the deadline. After a restart an older audio is `NOT_FOUND`. |
|
|
222
|
+
| **Reconnects** | An unexpected close reconnects with exponential backoff (5 attempts from 2 s), and 515 (restart after pairing) reconnects at once. 401 (logged out) clears the keys and stops. 440 (replaced) and 403 stop. |
|
|
223
|
+
| **Webhook** | None. `verify` fails closed, so the webhook route answers 401 to any POST for the channel. |
|
|
224
|
+
| **Policy** | No service window by default (`OPEN_SEND_POLICY`); the 24 h window is a Business API rule. |
|
|
225
|
+
| **Channel key** | `whatsapp` by default, so the switch keeps the connections and conversations. Pass `kind: "whatsapp-web"` to run both side by side. The connection's credential is unused: the keys live in the auth store. |
|
|
226
|
+
|
|
188
227
|
## Screening inbound text before a model reads it
|
|
189
228
|
|
|
190
229
|
`@12-apps/messaging/inbound-guard` is for a host that hands inbound messages
|
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ChannelMediaFailure,
|
|
3
|
+
ChannelSendFailure,
|
|
4
|
+
DEFAULT_MEDIA_TIMEOUT_MS,
|
|
5
|
+
isPositiveSafeInteger,
|
|
6
|
+
serviceWindowPolicy
|
|
7
|
+
} from "./chunk-NKH5TCSO.js";
|
|
8
|
+
import {
|
|
9
|
+
__name
|
|
10
|
+
} from "./chunk-7QVYU63E.js";
|
|
11
|
+
|
|
12
|
+
// src/whatsapp/opt-out.ts
|
|
13
|
+
var DEFAULT_OPT_OUT_KEYWORDS = ["PARAR", "SAIR", "STOP", "CANCELAR"];
|
|
14
|
+
function fold(text2) {
|
|
15
|
+
return text2.normalize("NFD").replace(/\p{M}/gu, "").replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "").toUpperCase();
|
|
16
|
+
}
|
|
17
|
+
__name(fold, "fold");
|
|
18
|
+
function isOptOutText(text2, keywords = DEFAULT_OPT_OUT_KEYWORDS) {
|
|
19
|
+
const folded = fold(text2);
|
|
20
|
+
return folded.length > 0 && keywords.some((keyword) => fold(keyword) === folded);
|
|
21
|
+
}
|
|
22
|
+
__name(isOptOutText, "isOptOutText");
|
|
23
|
+
|
|
24
|
+
// src/whatsapp/parse.ts
|
|
25
|
+
var isObject = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isObject");
|
|
26
|
+
var list = /* @__PURE__ */ __name((value) => Array.isArray(value) ? value.filter(isObject) : [], "list");
|
|
27
|
+
var text = /* @__PURE__ */ __name((value) => typeof value === "string" && value.length > 0 ? value : null, "text");
|
|
28
|
+
function when(value) {
|
|
29
|
+
const seconds = typeof value === "string" || typeof value === "number" ? Number(value) : Number.NaN;
|
|
30
|
+
return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1e3) : null;
|
|
31
|
+
}
|
|
32
|
+
__name(when, "when");
|
|
33
|
+
function changes(payload) {
|
|
34
|
+
if (!isObject(payload) || payload.object !== "whatsapp_business_account") return [];
|
|
35
|
+
return list(payload.entry).flatMap((entry) => list(entry.changes)).flatMap((change) => {
|
|
36
|
+
const value = change.value;
|
|
37
|
+
const accountId = isObject(value) && isObject(value.metadata) ? text(value.metadata.phone_number_id) : null;
|
|
38
|
+
return isObject(value) && accountId ? [{ value, accountId }] : [];
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
__name(changes, "changes");
|
|
42
|
+
var CONTENT_READERS = {
|
|
43
|
+
text: /* @__PURE__ */ __name((message) => {
|
|
44
|
+
const body = isObject(message.text) ? text(message.text.body) : null;
|
|
45
|
+
return body ? { kind: "TEXT", text: body } : null;
|
|
46
|
+
}, "text"),
|
|
47
|
+
interactive: /* @__PURE__ */ __name((message) => {
|
|
48
|
+
const interactive = isObject(message.interactive) ? message.interactive : {};
|
|
49
|
+
const reply = interactive.button_reply ?? interactive.list_reply;
|
|
50
|
+
const id = isObject(reply) ? text(reply.id) : null;
|
|
51
|
+
return isObject(reply) && id ? { kind: "INTERACTIVE", replyId: id, title: text(reply.title) ?? "" } : null;
|
|
52
|
+
}, "interactive"),
|
|
53
|
+
// A quick-reply button on a template message.
|
|
54
|
+
button: /* @__PURE__ */ __name((message) => {
|
|
55
|
+
if (!isObject(message.button)) return null;
|
|
56
|
+
const title = text(message.button.text) ?? "";
|
|
57
|
+
return { kind: "INTERACTIVE", replyId: text(message.button.payload) ?? title, title };
|
|
58
|
+
}, "button"),
|
|
59
|
+
audio: /* @__PURE__ */ __name((message) => {
|
|
60
|
+
const id = isObject(message.audio) ? text(message.audio.id) : null;
|
|
61
|
+
return isObject(message.audio) && id ? { kind: "AUDIO", mediaId: id, mimeType: text(message.audio.mime_type) } : null;
|
|
62
|
+
}, "audio")
|
|
63
|
+
};
|
|
64
|
+
function contentOf(message) {
|
|
65
|
+
const type = text(message.type) ?? "unknown";
|
|
66
|
+
return CONTENT_READERS[type]?.(message) ?? { kind: "OTHER", channelType: type };
|
|
67
|
+
}
|
|
68
|
+
__name(contentOf, "contentOf");
|
|
69
|
+
function wordsOf(content) {
|
|
70
|
+
if (content.kind === "TEXT") return content.text;
|
|
71
|
+
if (content.kind === "INTERACTIVE") return content.title;
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
__name(wordsOf, "wordsOf");
|
|
75
|
+
function contactNames(value) {
|
|
76
|
+
const names = /* @__PURE__ */ new Map();
|
|
77
|
+
for (const contact of list(value.contacts)) {
|
|
78
|
+
const waId = text(contact.wa_id);
|
|
79
|
+
const name = isObject(contact.profile) ? text(contact.profile.name) : null;
|
|
80
|
+
if (waId && name) names.set(waId, name);
|
|
81
|
+
}
|
|
82
|
+
return names;
|
|
83
|
+
}
|
|
84
|
+
__name(contactNames, "contactNames");
|
|
85
|
+
function messageEvent(message, accountId, names, keywords) {
|
|
86
|
+
const contactId = text(message.from);
|
|
87
|
+
const externalId = text(message.id);
|
|
88
|
+
const sentAt = when(message.timestamp);
|
|
89
|
+
if (!contactId || !externalId || !sentAt) return null;
|
|
90
|
+
const content = contentOf(message);
|
|
91
|
+
const words = wordsOf(content);
|
|
92
|
+
return {
|
|
93
|
+
type: "message",
|
|
94
|
+
accountId,
|
|
95
|
+
contactId,
|
|
96
|
+
contactName: names.get(contactId) ?? null,
|
|
97
|
+
externalId,
|
|
98
|
+
sentAt,
|
|
99
|
+
content,
|
|
100
|
+
optOut: words !== null && isOptOutText(words, keywords)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
__name(messageEvent, "messageEvent");
|
|
104
|
+
function messageEvents(value, accountId, keywords) {
|
|
105
|
+
const names = contactNames(value);
|
|
106
|
+
return list(value.messages).flatMap((message) => messageEvent(message, accountId, names, keywords) ?? []);
|
|
107
|
+
}
|
|
108
|
+
__name(messageEvents, "messageEvents");
|
|
109
|
+
var RECEIPTS = {
|
|
110
|
+
sent: "SENT",
|
|
111
|
+
delivered: "DELIVERED",
|
|
112
|
+
read: "READ",
|
|
113
|
+
failed: "FAILED"
|
|
114
|
+
};
|
|
115
|
+
function errorOf(status) {
|
|
116
|
+
const [first] = list(status.errors);
|
|
117
|
+
if (!first) return null;
|
|
118
|
+
const code = first.code === void 0 ? "" : String(first.code);
|
|
119
|
+
const title = text(first.title) ?? text(first.message) ?? "";
|
|
120
|
+
return [code, title].filter(Boolean).join(": ") || null;
|
|
121
|
+
}
|
|
122
|
+
__name(errorOf, "errorOf");
|
|
123
|
+
function statusEvents(value, accountId) {
|
|
124
|
+
const out = [];
|
|
125
|
+
for (const status of list(value.statuses)) {
|
|
126
|
+
const externalId = text(status.id);
|
|
127
|
+
const receipt = RECEIPTS[text(status.status) ?? ""];
|
|
128
|
+
const at = when(status.timestamp);
|
|
129
|
+
if (!externalId || !receipt || !at) continue;
|
|
130
|
+
out.push({
|
|
131
|
+
type: "status",
|
|
132
|
+
accountId,
|
|
133
|
+
externalId,
|
|
134
|
+
status: receipt,
|
|
135
|
+
at,
|
|
136
|
+
contactId: text(status.recipient_id),
|
|
137
|
+
error: receipt === "FAILED" ? errorOf(status) : null,
|
|
138
|
+
callbackData: text(status.biz_opaque_callback_data)
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
__name(statusEvents, "statusEvents");
|
|
144
|
+
function preferenceEvents(value, accountId) {
|
|
145
|
+
const out = [];
|
|
146
|
+
for (const preference of list(value.user_preferences)) {
|
|
147
|
+
const contactId = text(preference.wa_id);
|
|
148
|
+
const at = when(preference.timestamp);
|
|
149
|
+
if (contactId && at && text(preference.value)?.toLowerCase() === "stop") {
|
|
150
|
+
out.push({ type: "opt_out", accountId, contactId, at });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
__name(preferenceEvents, "preferenceEvents");
|
|
156
|
+
function parseWhatsAppPayload(payload, options = {}) {
|
|
157
|
+
const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;
|
|
158
|
+
const out = [];
|
|
159
|
+
for (const { value, accountId } of changes(payload)) {
|
|
160
|
+
out.push(...messageEvents(value, accountId, keywords), ...statusEvents(value, accountId), ...preferenceEvents(value, accountId));
|
|
161
|
+
}
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
__name(parseWhatsAppPayload, "parseWhatsAppPayload");
|
|
165
|
+
function parseWhatsAppStatuses(payload) {
|
|
166
|
+
return changes(payload).flatMap(({ value, accountId }) => statusEvents(value, accountId));
|
|
167
|
+
}
|
|
168
|
+
__name(parseWhatsAppStatuses, "parseWhatsAppStatuses");
|
|
169
|
+
|
|
170
|
+
// src/whatsapp/graph.ts
|
|
171
|
+
var DEFAULT_META_MEDIA_HOSTS = ["lookaside.fbsbx.com", "*.fbcdn.net", "*.whatsapp.net"];
|
|
172
|
+
var GraphError = class extends ChannelSendFailure {
|
|
173
|
+
static {
|
|
174
|
+
__name(this, "GraphError");
|
|
175
|
+
}
|
|
176
|
+
status;
|
|
177
|
+
constructor(status, code, message) {
|
|
178
|
+
super(code, message);
|
|
179
|
+
this.name = "GraphError";
|
|
180
|
+
this.status = status;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
function trimTrailingSlashes(value) {
|
|
184
|
+
let end = value.length;
|
|
185
|
+
while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
|
|
186
|
+
return end === value.length ? value : value.slice(0, end);
|
|
187
|
+
}
|
|
188
|
+
__name(trimTrailingSlashes, "trimTrailingSlashes");
|
|
189
|
+
function requestOf(graph, call) {
|
|
190
|
+
const base = trimTrailingSlashes(graph.baseUrl);
|
|
191
|
+
const query = call.query ? `?${new URLSearchParams(call.query).toString()}` : "";
|
|
192
|
+
const headers = { accept: "application/json" };
|
|
193
|
+
if (call.token) headers.authorization = `Bearer ${call.token}`;
|
|
194
|
+
if (call.body !== void 0) headers["content-type"] = "application/json";
|
|
195
|
+
return {
|
|
196
|
+
url: `${base}/${graph.apiVersion}/${call.path}${query}`,
|
|
197
|
+
init: {
|
|
198
|
+
method: call.method,
|
|
199
|
+
headers,
|
|
200
|
+
...call.body !== void 0 ? { body: JSON.stringify(call.body) } : {},
|
|
201
|
+
...call.redirect ? { redirect: call.redirect } : {},
|
|
202
|
+
...call.signal ? { signal: call.signal } : {}
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
__name(requestOf, "requestOf");
|
|
207
|
+
function objectOf(raw) {
|
|
208
|
+
try {
|
|
209
|
+
const parsed = raw ? JSON.parse(raw) : {};
|
|
210
|
+
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
|
|
211
|
+
} catch {
|
|
212
|
+
return {};
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
__name(objectOf, "objectOf");
|
|
216
|
+
function graphErrorOf(status, json) {
|
|
217
|
+
const error = typeof json.error === "object" && json.error !== null ? json.error : {};
|
|
218
|
+
const code = error.code === void 0 ? `HTTP_${status}` : String(error.code);
|
|
219
|
+
const message = typeof error.message === "string" ? error.message : `Graph answered ${status}`;
|
|
220
|
+
return new GraphError(status, code, message.slice(0, 300));
|
|
221
|
+
}
|
|
222
|
+
__name(graphErrorOf, "graphErrorOf");
|
|
223
|
+
async function graphRequest(graph, call) {
|
|
224
|
+
const { url, init } = requestOf(graph, call);
|
|
225
|
+
const response = await graph.fetch(url, init);
|
|
226
|
+
const json = objectOf(await response.text());
|
|
227
|
+
if (response.status < 200 || response.status >= 300) throw graphErrorOf(response.status, json);
|
|
228
|
+
return json;
|
|
229
|
+
}
|
|
230
|
+
__name(graphRequest, "graphRequest");
|
|
231
|
+
function messageBody(to, content) {
|
|
232
|
+
const base = { messaging_product: "whatsapp", recipient_type: "individual", to };
|
|
233
|
+
if (content.kind === "TEXT") return { ...base, type: "text", text: { body: content.text, preview_url: false } };
|
|
234
|
+
if (content.kind === "BUTTONS") {
|
|
235
|
+
return {
|
|
236
|
+
...base,
|
|
237
|
+
type: "interactive",
|
|
238
|
+
interactive: {
|
|
239
|
+
type: "button",
|
|
240
|
+
body: { text: content.text },
|
|
241
|
+
action: { buttons: content.buttons.map((button) => ({ type: "reply", reply: { id: button.id, title: button.title } })) }
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
...base,
|
|
247
|
+
type: "interactive",
|
|
248
|
+
interactive: {
|
|
249
|
+
type: "list",
|
|
250
|
+
body: { text: content.text },
|
|
251
|
+
action: {
|
|
252
|
+
button: content.buttonLabel,
|
|
253
|
+
sections: content.sections.map((section) => ({
|
|
254
|
+
...section.title ? { title: section.title } : {},
|
|
255
|
+
rows: section.rows.map((row) => ({ id: row.id, title: row.title, ...row.description ? { description: row.description } : {} }))
|
|
256
|
+
}))
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
__name(messageBody, "messageBody");
|
|
262
|
+
async function sendWhatsAppMessage(graph, input) {
|
|
263
|
+
const json = await graphRequest(graph, {
|
|
264
|
+
method: "POST",
|
|
265
|
+
path: `${encodeURIComponent(input.phoneNumberId)}/messages`,
|
|
266
|
+
token: input.token,
|
|
267
|
+
body: messageBody(input.to, input.content)
|
|
268
|
+
});
|
|
269
|
+
const [first] = Array.isArray(json.messages) ? json.messages : [];
|
|
270
|
+
const id = first && typeof first.id === "string" ? first.id : null;
|
|
271
|
+
if (!id) throw new GraphError(200, "NO_MESSAGE_ID", "Graph accepted the message but returned no id");
|
|
272
|
+
return { externalId: id };
|
|
273
|
+
}
|
|
274
|
+
__name(sendWhatsAppMessage, "sendWhatsAppMessage");
|
|
275
|
+
|
|
276
|
+
// src/whatsapp/media.ts
|
|
277
|
+
var OCTET_STREAM = "application/octet-stream";
|
|
278
|
+
function hostAllowed(host, allowed) {
|
|
279
|
+
return allowed.some((entry) => {
|
|
280
|
+
const pattern = entry.toLowerCase();
|
|
281
|
+
return pattern.startsWith("*.") ? host.endsWith(pattern.slice(1)) : host === pattern;
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
__name(hostAllowed, "hostAllowed");
|
|
285
|
+
function checkedMediaUrl(raw, allowed) {
|
|
286
|
+
if (typeof raw !== "string" || raw === "") throw new ChannelMediaFailure("NO_MEDIA_URL", "Graph returned no media url");
|
|
287
|
+
let url;
|
|
288
|
+
try {
|
|
289
|
+
url = new URL(raw);
|
|
290
|
+
} catch {
|
|
291
|
+
throw new ChannelMediaFailure("MEDIA_URL_INVALID", "Graph returned a media url that does not parse");
|
|
292
|
+
}
|
|
293
|
+
if (url.protocol !== "https:") throw new ChannelMediaFailure("MEDIA_URL_REFUSED", "the media url is not https");
|
|
294
|
+
if (url.username || url.password) throw new ChannelMediaFailure("MEDIA_URL_REFUSED", "the media url carries credentials");
|
|
295
|
+
if (url.port !== "") throw new ChannelMediaFailure("MEDIA_URL_REFUSED", "the media url names an explicit port");
|
|
296
|
+
if (!hostAllowed(url.hostname.toLowerCase(), allowed)) {
|
|
297
|
+
throw new ChannelMediaFailure("MEDIA_HOST_REFUSED", `the media host ${url.hostname} is not a Meta media host`);
|
|
298
|
+
}
|
|
299
|
+
return url.toString();
|
|
300
|
+
}
|
|
301
|
+
__name(checkedMediaUrl, "checkedMediaUrl");
|
|
302
|
+
var tooLarge = /* @__PURE__ */ __name((size, maxBytes) => new ChannelMediaFailure("TOO_LARGE", `the media is ${size} bytes, over the ${maxBytes}-byte cap`), "tooLarge");
|
|
303
|
+
function checkDeclaredSize(declared, maxBytes) {
|
|
304
|
+
const size = typeof declared === "number" ? declared : typeof declared === "string" ? Number(declared) : NaN;
|
|
305
|
+
if (Number.isFinite(size) && size > maxBytes) throw tooLarge(size, maxBytes);
|
|
306
|
+
}
|
|
307
|
+
__name(checkDeclaredSize, "checkDeclaredSize");
|
|
308
|
+
function joined(chunks, total) {
|
|
309
|
+
const bytes = new Uint8Array(total);
|
|
310
|
+
let offset = 0;
|
|
311
|
+
for (const chunk of chunks) {
|
|
312
|
+
bytes.set(chunk, offset);
|
|
313
|
+
offset += chunk.length;
|
|
314
|
+
}
|
|
315
|
+
return bytes;
|
|
316
|
+
}
|
|
317
|
+
__name(joined, "joined");
|
|
318
|
+
var timedOut = /* @__PURE__ */ __name((timeoutMs) => new ChannelMediaFailure("TIMEOUT", `the media download did not finish within ${timeoutMs} ms`), "timedOut");
|
|
319
|
+
function deadlineOf(timeoutMs) {
|
|
320
|
+
const controller = new AbortController();
|
|
321
|
+
let timer;
|
|
322
|
+
const expired = new Promise((_resolve, reject) => {
|
|
323
|
+
timer = setTimeout(() => {
|
|
324
|
+
controller.abort();
|
|
325
|
+
reject(timedOut(timeoutMs));
|
|
326
|
+
}, timeoutMs);
|
|
327
|
+
});
|
|
328
|
+
expired.catch(() => void 0);
|
|
329
|
+
return {
|
|
330
|
+
signal: controller.signal,
|
|
331
|
+
race: /* @__PURE__ */ __name(async (promise) => {
|
|
332
|
+
try {
|
|
333
|
+
return await Promise.race([promise, expired]);
|
|
334
|
+
} catch (error) {
|
|
335
|
+
throw controller.signal.aborted ? timedOut(timeoutMs) : error;
|
|
336
|
+
}
|
|
337
|
+
}, "race"),
|
|
338
|
+
clear: /* @__PURE__ */ __name(() => clearTimeout(timer), "clear")
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
__name(deadlineOf, "deadlineOf");
|
|
342
|
+
function discardBody(response) {
|
|
343
|
+
try {
|
|
344
|
+
void Promise.resolve(response.body?.cancel?.()).catch(() => void 0);
|
|
345
|
+
} catch {
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
__name(discardBody, "discardBody");
|
|
349
|
+
async function readStreamCapped(response, maxBytes, deadline) {
|
|
350
|
+
const reader = response.body.getReader();
|
|
351
|
+
const chunks = [];
|
|
352
|
+
let total = 0;
|
|
353
|
+
try {
|
|
354
|
+
for (; ; ) {
|
|
355
|
+
const { done, value } = await deadline.race(reader.read());
|
|
356
|
+
if (done) break;
|
|
357
|
+
if (!value) continue;
|
|
358
|
+
total += value.length;
|
|
359
|
+
if (total > maxBytes) throw tooLarge(total, maxBytes);
|
|
360
|
+
chunks.push(value);
|
|
361
|
+
}
|
|
362
|
+
} catch (error) {
|
|
363
|
+
void reader.cancel().catch(() => void 0);
|
|
364
|
+
throw error;
|
|
365
|
+
}
|
|
366
|
+
return joined(chunks, total);
|
|
367
|
+
}
|
|
368
|
+
__name(readStreamCapped, "readStreamCapped");
|
|
369
|
+
async function readBodyCapped(response, maxBytes, deadline) {
|
|
370
|
+
const declared = response.headers?.get("content-length");
|
|
371
|
+
if (declared) {
|
|
372
|
+
try {
|
|
373
|
+
checkDeclaredSize(declared, maxBytes);
|
|
374
|
+
} catch (error) {
|
|
375
|
+
discardBody(response);
|
|
376
|
+
throw error;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (response.body && typeof response.body.getReader === "function") return readStreamCapped(response, maxBytes, deadline);
|
|
380
|
+
if (!response.arrayBuffer) throw new ChannelMediaFailure("NO_BINARY_BODY", "the fetch port cannot read a binary body");
|
|
381
|
+
const bytes = new Uint8Array(await deadline.race(response.arrayBuffer()));
|
|
382
|
+
if (bytes.length > maxBytes) throw tooLarge(bytes.length, maxBytes);
|
|
383
|
+
return bytes;
|
|
384
|
+
}
|
|
385
|
+
__name(readBodyCapped, "readBodyCapped");
|
|
386
|
+
async function downloadFrom(graph, url, token, deadline) {
|
|
387
|
+
const response = await deadline.race(
|
|
388
|
+
graph.fetch(url, {
|
|
389
|
+
method: "GET",
|
|
390
|
+
headers: { authorization: `Bearer ${token}`, accept: "*/*" },
|
|
391
|
+
redirect: "manual",
|
|
392
|
+
signal: deadline.signal
|
|
393
|
+
})
|
|
394
|
+
);
|
|
395
|
+
if (response.status >= 200 && response.status < 300) return response;
|
|
396
|
+
discardBody(response);
|
|
397
|
+
if (response.status >= 300 && response.status < 400) {
|
|
398
|
+
throw new ChannelMediaFailure("REDIRECT_REFUSED", `the media download answered ${response.status}; redirects are not followed`);
|
|
399
|
+
}
|
|
400
|
+
throw new ChannelMediaFailure(`HTTP_${response.status}`, `the media download answered ${response.status}`);
|
|
401
|
+
}
|
|
402
|
+
__name(downloadFrom, "downloadFrom");
|
|
403
|
+
function checkLimits(maxBytes, timeoutMs) {
|
|
404
|
+
if (!isPositiveSafeInteger(maxBytes) || !isPositiveSafeInteger(timeoutMs)) {
|
|
405
|
+
throw new ChannelMediaFailure("BAD_OPTIONS", "maxBytes and timeoutMs must be positive safe integers");
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
__name(checkLimits, "checkLimits");
|
|
409
|
+
async function downloadWhatsAppMedia(graph, input) {
|
|
410
|
+
const timeoutMs = input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS;
|
|
411
|
+
checkLimits(input.maxBytes, timeoutMs);
|
|
412
|
+
const deadline = deadlineOf(timeoutMs);
|
|
413
|
+
try {
|
|
414
|
+
const meta = await deadline.race(
|
|
415
|
+
graphRequest(graph, {
|
|
416
|
+
method: "GET",
|
|
417
|
+
path: encodeURIComponent(input.mediaId),
|
|
418
|
+
token: input.token,
|
|
419
|
+
redirect: "manual",
|
|
420
|
+
signal: deadline.signal
|
|
421
|
+
})
|
|
422
|
+
);
|
|
423
|
+
const url = checkedMediaUrl(meta.url, graph.mediaHosts ?? DEFAULT_META_MEDIA_HOSTS);
|
|
424
|
+
checkDeclaredSize(meta.file_size, input.maxBytes);
|
|
425
|
+
const response = await downloadFrom(graph, url, input.token, deadline);
|
|
426
|
+
const bytes = await readBodyCapped(response, input.maxBytes, deadline);
|
|
427
|
+
const declaredType = typeof meta.mime_type === "string" && meta.mime_type ? meta.mime_type : null;
|
|
428
|
+
const mimeType = declaredType ?? response.headers?.get("content-type") ?? OCTET_STREAM;
|
|
429
|
+
return { bytes, mimeType, size: bytes.length };
|
|
430
|
+
} finally {
|
|
431
|
+
deadline.clear();
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
__name(downloadWhatsAppMedia, "downloadWhatsAppMedia");
|
|
435
|
+
|
|
436
|
+
// src/whatsapp/signature.ts
|
|
437
|
+
import { createHash, createHmac, timingSafeEqual } from "crypto";
|
|
438
|
+
var META_SIGNATURE_HEADER = "x-hub-signature-256";
|
|
439
|
+
var SIGNATURE = /^sha256=([0-9a-f]{64})$/i;
|
|
440
|
+
function verifyMetaSignature(rawBody, signatureHeader, appSecret) {
|
|
441
|
+
if (!appSecret || !signatureHeader) return false;
|
|
442
|
+
const match = SIGNATURE.exec(signatureHeader.trim());
|
|
443
|
+
if (!match) return false;
|
|
444
|
+
const expected = createHmac("sha256", appSecret).update(rawBody).digest();
|
|
445
|
+
const given = Buffer.from(match[1], "hex");
|
|
446
|
+
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
447
|
+
}
|
|
448
|
+
__name(verifyMetaSignature, "verifyMetaSignature");
|
|
449
|
+
function verifyMetaSubscription(query, verifyToken) {
|
|
450
|
+
const mode = query["hub.mode"];
|
|
451
|
+
const token = query["hub.verify_token"];
|
|
452
|
+
const challenge = query["hub.challenge"];
|
|
453
|
+
if (!verifyToken || mode !== "subscribe" || !token || !challenge) return { ok: false };
|
|
454
|
+
const digest = /* @__PURE__ */ __name((value) => createHash("sha256").update(value, "utf8").digest(), "digest");
|
|
455
|
+
return timingSafeEqual(digest(token), digest(verifyToken)) ? { ok: true, challenge } : { ok: false };
|
|
456
|
+
}
|
|
457
|
+
__name(verifyMetaSubscription, "verifyMetaSubscription");
|
|
458
|
+
|
|
459
|
+
// src/whatsapp/signup.ts
|
|
460
|
+
async function exchangeSignupCode(graph, input) {
|
|
461
|
+
const json = await graphRequest(graph, {
|
|
462
|
+
method: "GET",
|
|
463
|
+
path: "oauth/access_token",
|
|
464
|
+
query: {
|
|
465
|
+
client_id: input.appId,
|
|
466
|
+
client_secret: input.appSecret,
|
|
467
|
+
code: input.code,
|
|
468
|
+
...input.redirectUri ? { redirect_uri: input.redirectUri } : {}
|
|
469
|
+
}
|
|
470
|
+
});
|
|
471
|
+
if (typeof json.access_token !== "string" || json.access_token.length === 0) {
|
|
472
|
+
throw new GraphError(200, "NO_ACCESS_TOKEN", "Graph answered the code exchange without a token");
|
|
473
|
+
}
|
|
474
|
+
return { accessToken: json.access_token };
|
|
475
|
+
}
|
|
476
|
+
__name(exchangeSignupCode, "exchangeSignupCode");
|
|
477
|
+
async function readSignupAccounts(graph, input) {
|
|
478
|
+
const debug = await graphRequest(graph, {
|
|
479
|
+
method: "GET",
|
|
480
|
+
path: "debug_token",
|
|
481
|
+
query: { input_token: input.accessToken },
|
|
482
|
+
token: `${input.appId}|${input.appSecret}`
|
|
483
|
+
});
|
|
484
|
+
const data = typeof debug.data === "object" && debug.data !== null ? debug.data : {};
|
|
485
|
+
const scopes = Array.isArray(data.granular_scopes) ? data.granular_scopes : [];
|
|
486
|
+
const wabaIds = new Set(
|
|
487
|
+
scopes.filter((scope) => scope.scope === "whatsapp_business_management" && Array.isArray(scope.target_ids)).flatMap((scope) => scope.target_ids.filter((id) => typeof id === "string"))
|
|
488
|
+
);
|
|
489
|
+
const accounts = [];
|
|
490
|
+
for (const wabaId of wabaIds) {
|
|
491
|
+
accounts.push({ wabaId, phoneNumbers: await readPhoneNumbers(graph, wabaId, input.accessToken) });
|
|
492
|
+
}
|
|
493
|
+
return accounts;
|
|
494
|
+
}
|
|
495
|
+
__name(readSignupAccounts, "readSignupAccounts");
|
|
496
|
+
async function readPhoneNumbers(graph, wabaId, accessToken) {
|
|
497
|
+
const json = await graphRequest(graph, {
|
|
498
|
+
method: "GET",
|
|
499
|
+
path: `${encodeURIComponent(wabaId)}/phone_numbers`,
|
|
500
|
+
query: { fields: "id,display_phone_number,verified_name" },
|
|
501
|
+
token: accessToken
|
|
502
|
+
});
|
|
503
|
+
const rows = Array.isArray(json.data) ? json.data : [];
|
|
504
|
+
return rows.filter((row) => typeof row.id === "string" && typeof row.display_phone_number === "string").map((row) => ({
|
|
505
|
+
id: row.id,
|
|
506
|
+
displayPhoneNumber: row.display_phone_number,
|
|
507
|
+
verifiedName: typeof row.verified_name === "string" ? row.verified_name : null
|
|
508
|
+
}));
|
|
509
|
+
}
|
|
510
|
+
__name(readPhoneNumbers, "readPhoneNumbers");
|
|
511
|
+
async function subscribeAppToWaba(graph, input) {
|
|
512
|
+
const json = await graphRequest(graph, {
|
|
513
|
+
method: "POST",
|
|
514
|
+
path: `${encodeURIComponent(input.wabaId)}/subscribed_apps`,
|
|
515
|
+
token: input.accessToken
|
|
516
|
+
});
|
|
517
|
+
if (json.success !== true) throw new GraphError(200, "NOT_SUBSCRIBED", "Graph did not confirm the subscription");
|
|
518
|
+
}
|
|
519
|
+
__name(subscribeAppToWaba, "subscribeAppToWaba");
|
|
520
|
+
|
|
521
|
+
// src/whatsapp/index.ts
|
|
522
|
+
var WHATSAPP_CHANNEL = "whatsapp";
|
|
523
|
+
var WHATSAPP_SERVICE_WINDOW_MS = 24 * 60 * 60 * 1e3;
|
|
524
|
+
function createWhatsAppAdapter(config) {
|
|
525
|
+
return {
|
|
526
|
+
kind: WHATSAPP_CHANNEL,
|
|
527
|
+
handshake: /* @__PURE__ */ __name((query) => verifyMetaSubscription(query, config.verifyToken), "handshake"),
|
|
528
|
+
verify: /* @__PURE__ */ __name(({ rawBody, header }) => verifyMetaSignature(rawBody, header(META_SIGNATURE_HEADER), config.appSecret), "verify"),
|
|
529
|
+
parse: /* @__PURE__ */ __name((rawBody) => parseWhatsAppPayload(JSON.parse(rawBody), {
|
|
530
|
+
...config.optOutKeywords ? { optOutKeywords: config.optOutKeywords } : {}
|
|
531
|
+
}), "parse"),
|
|
532
|
+
send: /* @__PURE__ */ __name(({ credential, accountId, to, content }) => sendWhatsAppMessage(config.graph, { token: credential, phoneNumberId: accountId, to, content }), "send"),
|
|
533
|
+
fetchMedia: /* @__PURE__ */ __name(({ credential, mediaId, maxBytes, timeoutMs }) => downloadWhatsAppMedia(config.graph, { token: credential, mediaId, maxBytes, ...timeoutMs !== void 0 ? { timeoutMs } : {} }), "fetchMedia"),
|
|
534
|
+
policy: serviceWindowPolicy(WHATSAPP_SERVICE_WINDOW_MS)
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
__name(createWhatsAppAdapter, "createWhatsAppAdapter");
|
|
538
|
+
|
|
539
|
+
export {
|
|
540
|
+
DEFAULT_OPT_OUT_KEYWORDS,
|
|
541
|
+
isOptOutText,
|
|
542
|
+
parseWhatsAppPayload,
|
|
543
|
+
parseWhatsAppStatuses,
|
|
544
|
+
DEFAULT_META_MEDIA_HOSTS,
|
|
545
|
+
GraphError,
|
|
546
|
+
graphRequest,
|
|
547
|
+
messageBody,
|
|
548
|
+
sendWhatsAppMessage,
|
|
549
|
+
downloadWhatsAppMedia,
|
|
550
|
+
META_SIGNATURE_HEADER,
|
|
551
|
+
verifyMetaSignature,
|
|
552
|
+
verifyMetaSubscription,
|
|
553
|
+
exchangeSignupCode,
|
|
554
|
+
readSignupAccounts,
|
|
555
|
+
subscribeAppToWaba,
|
|
556
|
+
WHATSAPP_CHANNEL,
|
|
557
|
+
WHATSAPP_SERVICE_WINDOW_MS,
|
|
558
|
+
createWhatsAppAdapter
|
|
559
|
+
};
|
|
560
|
+
//# sourceMappingURL=chunk-RXJNLPY4.js.map
|