@12-apps/messaging 1.0.0 → 1.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 +61 -1
- package/dist/{channel-Cs_vLGl_.d.ts → channel-HEnMO02x.d.ts} +45 -1
- package/dist/{chunk-R3DKM2IV.js → chunk-LNVSQ5IQ.js} +13 -1
- package/dist/chunk-LNVSQ5IQ.js.map +1 -0
- package/dist/{chunk-Y7MG2UDQ.js → chunk-NKH5TCSO.js} +20 -1
- package/dist/chunk-NKH5TCSO.js.map +1 -0
- package/dist/{chunk-72TDAQUW.js → chunk-S5PJXMXM.js} +2 -2
- package/dist/{engine-B5EPo66m.d.ts → engine-DAfm8V5S.d.ts} +39 -2
- package/dist/index.d.ts +30 -5
- package/dist/index.js +86 -2
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +2 -2
- package/dist/whatsapp/index.d.ts +55 -5
- package/dist/whatsapp/index.js +175 -2
- package/dist/whatsapp/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core/channel.ts +58 -0
- package/src/core/engine.ts +9 -0
- package/src/core/errors.ts +31 -0
- package/src/core/inbox.ts +22 -0
- package/src/core/media.ts +84 -0
- package/src/core/memory-store.ts +4 -0
- package/src/core/ports.ts +18 -1
- package/src/core/prisma-store.ts +4 -1
- package/src/core/store.ts +6 -0
- package/src/index.ts +7 -0
- package/src/whatsapp/graph.ts +53 -5
- package/src/whatsapp/index.ts +16 -1
- package/src/whatsapp/media.ts +205 -0
- package/dist/chunk-R3DKM2IV.js.map +0 -1
- package/dist/chunk-Y7MG2UDQ.js.map +0 -1
- /package/dist/{chunk-72TDAQUW.js.map → chunk-S5PJXMXM.js.map} +0 -0
package/dist/whatsapp/index.d.ts
CHANGED
|
@@ -1,17 +1,51 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { f as ChannelSendFailure, s as OutboundContent, N as NormalizedEvent, v as StatusEvent, c as ChannelMedia, a as ChannelAdapter } from '../channel-HEnMO02x.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The only way the adapter reaches Meta: an injected fetch. The global
|
|
5
5
|
* `fetch` satisfies it; a test answers it with a recording fake.
|
|
6
|
+
*
|
|
7
|
+
* A JSON call reads `text()` only. A media download also asks for
|
|
8
|
+
* `redirect: "manual"` (a 3xx comes back as itself, never followed) and reads
|
|
9
|
+
* the binary body through `body` (a stream, read up to the size cap) or, when
|
|
10
|
+
* there is none, `arrayBuffer()`. All three are optional so a text-only fake
|
|
11
|
+
* still satisfies the port.
|
|
6
12
|
*/
|
|
7
|
-
type FetchPort = (url: string, init:
|
|
13
|
+
type FetchPort = (url: string, init: FetchInit) => Promise<FetchResponse>;
|
|
14
|
+
interface FetchInit {
|
|
8
15
|
method: string;
|
|
9
16
|
headers: Record<string, string>;
|
|
10
17
|
body?: string;
|
|
11
|
-
|
|
18
|
+
/** `manual` for a media download: a redirect is answered, never followed. */
|
|
19
|
+
redirect?: "manual" | "follow" | "error";
|
|
20
|
+
/** Aborts the call at a media download's deadline. */
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
}
|
|
23
|
+
interface FetchResponse {
|
|
12
24
|
status: number;
|
|
13
25
|
text(): Promise<string>;
|
|
14
|
-
|
|
26
|
+
arrayBuffer?(): Promise<ArrayBuffer>;
|
|
27
|
+
/** The body as a stream; read chunk by chunk so an oversized one is cut off early. */
|
|
28
|
+
body?: {
|
|
29
|
+
getReader(): FetchBodyReader;
|
|
30
|
+
cancel?(reason?: unknown): Promise<void>;
|
|
31
|
+
} | null;
|
|
32
|
+
headers?: {
|
|
33
|
+
get(name: string): string | null;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
interface FetchBodyReader {
|
|
37
|
+
read(): Promise<{
|
|
38
|
+
done: boolean;
|
|
39
|
+
value?: Uint8Array;
|
|
40
|
+
}>;
|
|
41
|
+
cancel(reason?: unknown): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The hosts Meta serves WhatsApp media from: the URL a media lookup returns is
|
|
45
|
+
* `https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=…`, and the
|
|
46
|
+
* CDN families behind it. `*.` matches any subdomain (not the bare domain).
|
|
47
|
+
*/
|
|
48
|
+
declare const DEFAULT_META_MEDIA_HOSTS: readonly string[];
|
|
15
49
|
/** Where the Graph API is, and through what. Both numbers are config, never constants in the adapter. */
|
|
16
50
|
interface GraphConfig {
|
|
17
51
|
fetch: FetchPort;
|
|
@@ -19,6 +53,12 @@ interface GraphConfig {
|
|
|
19
53
|
baseUrl: string;
|
|
20
54
|
/** `v23.0` — the Graph API version every call is pinned to. */
|
|
21
55
|
apiVersion: string;
|
|
56
|
+
/**
|
|
57
|
+
* The hosts a media URL may point at; any other is refused before the token
|
|
58
|
+
* is sent to it. Exact names, or `*.domain` for its subdomains. Default
|
|
59
|
+
* {@link DEFAULT_META_MEDIA_HOSTS}.
|
|
60
|
+
*/
|
|
61
|
+
mediaHosts?: readonly string[];
|
|
22
62
|
}
|
|
23
63
|
/** A Graph call that did not answer 2xx. Carries Meta's error code; never the token. */
|
|
24
64
|
declare class GraphError extends ChannelSendFailure {
|
|
@@ -32,6 +72,8 @@ interface GraphCall {
|
|
|
32
72
|
token?: string;
|
|
33
73
|
query?: Record<string, string>;
|
|
34
74
|
body?: unknown;
|
|
75
|
+
redirect?: FetchInit["redirect"];
|
|
76
|
+
signal?: AbortSignal;
|
|
35
77
|
}
|
|
36
78
|
/** One Graph call; resolves to the parsed JSON body, or throws {@link GraphError}. */
|
|
37
79
|
declare function graphRequest(graph: GraphConfig, call: GraphCall): Promise<Json>;
|
|
@@ -108,6 +150,14 @@ declare const DEFAULT_OPT_OUT_KEYWORDS: readonly string[];
|
|
|
108
150
|
*/
|
|
109
151
|
declare function isOptOutText(text: string, keywords?: readonly string[]): boolean;
|
|
110
152
|
|
|
153
|
+
/** Download one WhatsApp media object into memory. */
|
|
154
|
+
declare function downloadWhatsAppMedia(graph: GraphConfig, input: {
|
|
155
|
+
token: string;
|
|
156
|
+
mediaId: string;
|
|
157
|
+
maxBytes: number;
|
|
158
|
+
timeoutMs?: number;
|
|
159
|
+
}): Promise<ChannelMedia>;
|
|
160
|
+
|
|
111
161
|
/** The app's own identity on Meta. The secret is the host's, read where it keeps secrets. */
|
|
112
162
|
interface MetaAppCredentials {
|
|
113
163
|
appId: string;
|
|
@@ -177,4 +227,4 @@ interface WhatsAppAdapterConfig {
|
|
|
177
227
|
/** The WhatsApp Cloud adapter. */
|
|
178
228
|
declare function createWhatsAppAdapter(config: WhatsAppAdapterConfig): ChannelAdapter;
|
|
179
229
|
|
|
180
|
-
export { DEFAULT_OPT_OUT_KEYWORDS, type FetchPort, type GraphConfig, GraphError, META_SIGNATURE_HEADER, type MetaAppCredentials, type MetaHandshake, type SignupAccount, type SignupPhoneNumber, WHATSAPP_CHANNEL, WHATSAPP_SERVICE_WINDOW_MS, type WhatsAppAdapterConfig, createWhatsAppAdapter, exchangeSignupCode, graphRequest, isOptOutText, messageBody, parseWhatsAppPayload, parseWhatsAppStatuses, readSignupAccounts, sendWhatsAppMessage, subscribeAppToWaba, verifyMetaSignature, verifyMetaSubscription };
|
|
230
|
+
export { DEFAULT_META_MEDIA_HOSTS, DEFAULT_OPT_OUT_KEYWORDS, type FetchBodyReader, type FetchInit, type FetchPort, type FetchResponse, type GraphConfig, GraphError, META_SIGNATURE_HEADER, type MetaAppCredentials, type MetaHandshake, type SignupAccount, type SignupPhoneNumber, WHATSAPP_CHANNEL, WHATSAPP_SERVICE_WINDOW_MS, type WhatsAppAdapterConfig, createWhatsAppAdapter, downloadWhatsAppMedia, exchangeSignupCode, graphRequest, isOptOutText, messageBody, parseWhatsAppPayload, parseWhatsAppStatuses, readSignupAccounts, sendWhatsAppMessage, subscribeAppToWaba, verifyMetaSignature, verifyMetaSubscription };
|
package/dist/whatsapp/index.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
|
+
ChannelMediaFailure,
|
|
2
3
|
ChannelSendFailure,
|
|
4
|
+
DEFAULT_MEDIA_TIMEOUT_MS,
|
|
5
|
+
isPositiveSafeInteger,
|
|
3
6
|
serviceWindowPolicy
|
|
4
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-NKH5TCSO.js";
|
|
5
8
|
import {
|
|
6
9
|
__name
|
|
7
10
|
} from "../chunk-7QVYU63E.js";
|
|
@@ -164,6 +167,7 @@ function parseWhatsAppStatuses(payload) {
|
|
|
164
167
|
__name(parseWhatsAppStatuses, "parseWhatsAppStatuses");
|
|
165
168
|
|
|
166
169
|
// src/whatsapp/graph.ts
|
|
170
|
+
var DEFAULT_META_MEDIA_HOSTS = ["lookaside.fbsbx.com", "*.fbcdn.net", "*.whatsapp.net"];
|
|
167
171
|
var GraphError = class extends ChannelSendFailure {
|
|
168
172
|
static {
|
|
169
173
|
__name(this, "GraphError");
|
|
@@ -189,7 +193,13 @@ function requestOf(graph, call) {
|
|
|
189
193
|
if (call.body !== void 0) headers["content-type"] = "application/json";
|
|
190
194
|
return {
|
|
191
195
|
url: `${base}/${graph.apiVersion}/${call.path}${query}`,
|
|
192
|
-
init: {
|
|
196
|
+
init: {
|
|
197
|
+
method: call.method,
|
|
198
|
+
headers,
|
|
199
|
+
...call.body !== void 0 ? { body: JSON.stringify(call.body) } : {},
|
|
200
|
+
...call.redirect ? { redirect: call.redirect } : {},
|
|
201
|
+
...call.signal ? { signal: call.signal } : {}
|
|
202
|
+
}
|
|
193
203
|
};
|
|
194
204
|
}
|
|
195
205
|
__name(requestOf, "requestOf");
|
|
@@ -262,6 +272,166 @@ async function sendWhatsAppMessage(graph, input) {
|
|
|
262
272
|
}
|
|
263
273
|
__name(sendWhatsAppMessage, "sendWhatsAppMessage");
|
|
264
274
|
|
|
275
|
+
// src/whatsapp/media.ts
|
|
276
|
+
var OCTET_STREAM = "application/octet-stream";
|
|
277
|
+
function hostAllowed(host, allowed) {
|
|
278
|
+
return allowed.some((entry) => {
|
|
279
|
+
const pattern = entry.toLowerCase();
|
|
280
|
+
return pattern.startsWith("*.") ? host.endsWith(pattern.slice(1)) : host === pattern;
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
__name(hostAllowed, "hostAllowed");
|
|
284
|
+
function checkedMediaUrl(raw, allowed) {
|
|
285
|
+
if (typeof raw !== "string" || raw === "") throw new ChannelMediaFailure("NO_MEDIA_URL", "Graph returned no media url");
|
|
286
|
+
let url;
|
|
287
|
+
try {
|
|
288
|
+
url = new URL(raw);
|
|
289
|
+
} catch {
|
|
290
|
+
throw new ChannelMediaFailure("MEDIA_URL_INVALID", "Graph returned a media url that does not parse");
|
|
291
|
+
}
|
|
292
|
+
if (url.protocol !== "https:") throw new ChannelMediaFailure("MEDIA_URL_REFUSED", "the media url is not https");
|
|
293
|
+
if (url.username || url.password) throw new ChannelMediaFailure("MEDIA_URL_REFUSED", "the media url carries credentials");
|
|
294
|
+
if (url.port !== "") throw new ChannelMediaFailure("MEDIA_URL_REFUSED", "the media url names an explicit port");
|
|
295
|
+
if (!hostAllowed(url.hostname.toLowerCase(), allowed)) {
|
|
296
|
+
throw new ChannelMediaFailure("MEDIA_HOST_REFUSED", `the media host ${url.hostname} is not a Meta media host`);
|
|
297
|
+
}
|
|
298
|
+
return url.toString();
|
|
299
|
+
}
|
|
300
|
+
__name(checkedMediaUrl, "checkedMediaUrl");
|
|
301
|
+
var tooLarge = /* @__PURE__ */ __name((size, maxBytes) => new ChannelMediaFailure("TOO_LARGE", `the media is ${size} bytes, over the ${maxBytes}-byte cap`), "tooLarge");
|
|
302
|
+
function checkDeclaredSize(declared, maxBytes) {
|
|
303
|
+
const size = typeof declared === "number" ? declared : typeof declared === "string" ? Number(declared) : NaN;
|
|
304
|
+
if (Number.isFinite(size) && size > maxBytes) throw tooLarge(size, maxBytes);
|
|
305
|
+
}
|
|
306
|
+
__name(checkDeclaredSize, "checkDeclaredSize");
|
|
307
|
+
function joined(chunks, total) {
|
|
308
|
+
const bytes = new Uint8Array(total);
|
|
309
|
+
let offset = 0;
|
|
310
|
+
for (const chunk of chunks) {
|
|
311
|
+
bytes.set(chunk, offset);
|
|
312
|
+
offset += chunk.length;
|
|
313
|
+
}
|
|
314
|
+
return bytes;
|
|
315
|
+
}
|
|
316
|
+
__name(joined, "joined");
|
|
317
|
+
var timedOut = /* @__PURE__ */ __name((timeoutMs) => new ChannelMediaFailure("TIMEOUT", `the media download did not finish within ${timeoutMs} ms`), "timedOut");
|
|
318
|
+
function deadlineOf(timeoutMs) {
|
|
319
|
+
const controller = new AbortController();
|
|
320
|
+
let timer;
|
|
321
|
+
const expired = new Promise((_resolve, reject) => {
|
|
322
|
+
timer = setTimeout(() => {
|
|
323
|
+
controller.abort();
|
|
324
|
+
reject(timedOut(timeoutMs));
|
|
325
|
+
}, timeoutMs);
|
|
326
|
+
});
|
|
327
|
+
expired.catch(() => void 0);
|
|
328
|
+
return {
|
|
329
|
+
signal: controller.signal,
|
|
330
|
+
race: /* @__PURE__ */ __name(async (promise) => {
|
|
331
|
+
try {
|
|
332
|
+
return await Promise.race([promise, expired]);
|
|
333
|
+
} catch (error) {
|
|
334
|
+
throw controller.signal.aborted ? timedOut(timeoutMs) : error;
|
|
335
|
+
}
|
|
336
|
+
}, "race"),
|
|
337
|
+
clear: /* @__PURE__ */ __name(() => clearTimeout(timer), "clear")
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
__name(deadlineOf, "deadlineOf");
|
|
341
|
+
function discardBody(response) {
|
|
342
|
+
try {
|
|
343
|
+
void Promise.resolve(response.body?.cancel?.()).catch(() => void 0);
|
|
344
|
+
} catch {
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
__name(discardBody, "discardBody");
|
|
348
|
+
async function readStreamCapped(response, maxBytes, deadline) {
|
|
349
|
+
const reader = response.body.getReader();
|
|
350
|
+
const chunks = [];
|
|
351
|
+
let total = 0;
|
|
352
|
+
try {
|
|
353
|
+
for (; ; ) {
|
|
354
|
+
const { done, value } = await deadline.race(reader.read());
|
|
355
|
+
if (done) break;
|
|
356
|
+
if (!value) continue;
|
|
357
|
+
total += value.length;
|
|
358
|
+
if (total > maxBytes) throw tooLarge(total, maxBytes);
|
|
359
|
+
chunks.push(value);
|
|
360
|
+
}
|
|
361
|
+
} catch (error) {
|
|
362
|
+
void reader.cancel().catch(() => void 0);
|
|
363
|
+
throw error;
|
|
364
|
+
}
|
|
365
|
+
return joined(chunks, total);
|
|
366
|
+
}
|
|
367
|
+
__name(readStreamCapped, "readStreamCapped");
|
|
368
|
+
async function readBodyCapped(response, maxBytes, deadline) {
|
|
369
|
+
const declared = response.headers?.get("content-length");
|
|
370
|
+
if (declared) {
|
|
371
|
+
try {
|
|
372
|
+
checkDeclaredSize(declared, maxBytes);
|
|
373
|
+
} catch (error) {
|
|
374
|
+
discardBody(response);
|
|
375
|
+
throw error;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (response.body && typeof response.body.getReader === "function") return readStreamCapped(response, maxBytes, deadline);
|
|
379
|
+
if (!response.arrayBuffer) throw new ChannelMediaFailure("NO_BINARY_BODY", "the fetch port cannot read a binary body");
|
|
380
|
+
const bytes = new Uint8Array(await deadline.race(response.arrayBuffer()));
|
|
381
|
+
if (bytes.length > maxBytes) throw tooLarge(bytes.length, maxBytes);
|
|
382
|
+
return bytes;
|
|
383
|
+
}
|
|
384
|
+
__name(readBodyCapped, "readBodyCapped");
|
|
385
|
+
async function downloadFrom(graph, url, token, deadline) {
|
|
386
|
+
const response = await deadline.race(
|
|
387
|
+
graph.fetch(url, {
|
|
388
|
+
method: "GET",
|
|
389
|
+
headers: { authorization: `Bearer ${token}`, accept: "*/*" },
|
|
390
|
+
redirect: "manual",
|
|
391
|
+
signal: deadline.signal
|
|
392
|
+
})
|
|
393
|
+
);
|
|
394
|
+
if (response.status >= 200 && response.status < 300) return response;
|
|
395
|
+
discardBody(response);
|
|
396
|
+
if (response.status >= 300 && response.status < 400) {
|
|
397
|
+
throw new ChannelMediaFailure("REDIRECT_REFUSED", `the media download answered ${response.status}; redirects are not followed`);
|
|
398
|
+
}
|
|
399
|
+
throw new ChannelMediaFailure(`HTTP_${response.status}`, `the media download answered ${response.status}`);
|
|
400
|
+
}
|
|
401
|
+
__name(downloadFrom, "downloadFrom");
|
|
402
|
+
function checkLimits(maxBytes, timeoutMs) {
|
|
403
|
+
if (!isPositiveSafeInteger(maxBytes) || !isPositiveSafeInteger(timeoutMs)) {
|
|
404
|
+
throw new ChannelMediaFailure("BAD_OPTIONS", "maxBytes and timeoutMs must be positive safe integers");
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
__name(checkLimits, "checkLimits");
|
|
408
|
+
async function downloadWhatsAppMedia(graph, input) {
|
|
409
|
+
const timeoutMs = input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS;
|
|
410
|
+
checkLimits(input.maxBytes, timeoutMs);
|
|
411
|
+
const deadline = deadlineOf(timeoutMs);
|
|
412
|
+
try {
|
|
413
|
+
const meta = await deadline.race(
|
|
414
|
+
graphRequest(graph, {
|
|
415
|
+
method: "GET",
|
|
416
|
+
path: encodeURIComponent(input.mediaId),
|
|
417
|
+
token: input.token,
|
|
418
|
+
redirect: "manual",
|
|
419
|
+
signal: deadline.signal
|
|
420
|
+
})
|
|
421
|
+
);
|
|
422
|
+
const url = checkedMediaUrl(meta.url, graph.mediaHosts ?? DEFAULT_META_MEDIA_HOSTS);
|
|
423
|
+
checkDeclaredSize(meta.file_size, input.maxBytes);
|
|
424
|
+
const response = await downloadFrom(graph, url, input.token, deadline);
|
|
425
|
+
const bytes = await readBodyCapped(response, input.maxBytes, deadline);
|
|
426
|
+
const declaredType = typeof meta.mime_type === "string" && meta.mime_type ? meta.mime_type : null;
|
|
427
|
+
const mimeType = declaredType ?? response.headers?.get("content-type") ?? OCTET_STREAM;
|
|
428
|
+
return { bytes, mimeType, size: bytes.length };
|
|
429
|
+
} finally {
|
|
430
|
+
deadline.clear();
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
__name(downloadWhatsAppMedia, "downloadWhatsAppMedia");
|
|
434
|
+
|
|
265
435
|
// src/whatsapp/signature.ts
|
|
266
436
|
import { createHash, createHmac, timingSafeEqual } from "crypto";
|
|
267
437
|
var META_SIGNATURE_HEADER = "x-hub-signature-256";
|
|
@@ -359,17 +529,20 @@ function createWhatsAppAdapter(config) {
|
|
|
359
529
|
...config.optOutKeywords ? { optOutKeywords: config.optOutKeywords } : {}
|
|
360
530
|
}), "parse"),
|
|
361
531
|
send: /* @__PURE__ */ __name(({ credential, accountId, to, content }) => sendWhatsAppMessage(config.graph, { token: credential, phoneNumberId: accountId, to, content }), "send"),
|
|
532
|
+
fetchMedia: /* @__PURE__ */ __name(({ credential, mediaId, maxBytes, timeoutMs }) => downloadWhatsAppMedia(config.graph, { token: credential, mediaId, maxBytes, ...timeoutMs !== void 0 ? { timeoutMs } : {} }), "fetchMedia"),
|
|
362
533
|
policy: serviceWindowPolicy(WHATSAPP_SERVICE_WINDOW_MS)
|
|
363
534
|
};
|
|
364
535
|
}
|
|
365
536
|
__name(createWhatsAppAdapter, "createWhatsAppAdapter");
|
|
366
537
|
export {
|
|
538
|
+
DEFAULT_META_MEDIA_HOSTS,
|
|
367
539
|
DEFAULT_OPT_OUT_KEYWORDS,
|
|
368
540
|
GraphError,
|
|
369
541
|
META_SIGNATURE_HEADER,
|
|
370
542
|
WHATSAPP_CHANNEL,
|
|
371
543
|
WHATSAPP_SERVICE_WINDOW_MS,
|
|
372
544
|
createWhatsAppAdapter,
|
|
545
|
+
downloadWhatsAppMedia,
|
|
373
546
|
exchangeSignupCode,
|
|
374
547
|
graphRequest,
|
|
375
548
|
isOptOutText,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/whatsapp/opt-out.ts","../../src/whatsapp/parse.ts","../../src/whatsapp/graph.ts","../../src/whatsapp/signature.ts","../../src/whatsapp/signup.ts","../../src/whatsapp/index.ts"],"sourcesContent":["/**\n * The words that opt a contact out, by default: the Portuguese and English\n * stop words a WhatsApp user is told to send. A host replaces the list through\n * the adapter's config.\n */\nexport const DEFAULT_OPT_OUT_KEYWORDS: readonly string[] = [\"PARAR\", \"SAIR\", \"STOP\", \"CANCELAR\"];\n\n/** Upper case, accents stripped, surrounding space, punctuation and emoji trimmed. */\nfunction fold(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/\\p{M}/gu, \"\")\n .replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\")\n .toUpperCase();\n}\n\n/**\n * Is this text an opt-out? Only when the WHOLE message is one keyword —\n * case- and accent-insensitive, ignoring punctuation and emoji around it — so\n * \"parar\", \"PARAR.\" and \"Parar!\" opt out, and \"parar de enviar\" (a sentence,\n * maybe about something else) does not.\n */\nexport function isOptOutText(text: string, keywords: readonly string[] = DEFAULT_OPT_OUT_KEYWORDS): boolean {\n const folded = fold(text);\n return folded.length > 0 && keywords.some((keyword) => fold(keyword) === folded);\n}\n","import type {\n InboundContent,\n InboundMessageEvent,\n NormalizedEvent,\n OptOutEvent,\n ReceiptStatus,\n StatusEvent,\n} from \"../core/types\";\nimport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\n\n/**\n * The WhatsApp Cloud API webhook payload, read defensively: every field is\n * checked before it is trusted, an unknown shape is skipped rather than\n * thrown on, and only `JSON.parse` itself may throw (bytes that are not JSON).\n *\n * Shape: `{ object: \"whatsapp_business_account\", entry: [{ id, changes: [{\n * field, value: { metadata: { phone_number_id }, contacts, messages,\n * statuses, user_preferences } }] }] }`. Events come out in payload order.\n */\n\ntype Json = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is Json => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst list = (value: unknown): Json[] => (Array.isArray(value) ? value.filter(isObject) : []);\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\n/** Meta's timestamps are Unix SECONDS, as a string. Null when absent or malformed. */\nfunction when(value: unknown): Date | null {\n const seconds = typeof value === \"string\" || typeof value === \"number\" ? Number(value) : Number.NaN;\n return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000) : null;\n}\n\ninterface Change {\n value: Json;\n accountId: string;\n}\n\n/** Every `value` of every change, with the account it was delivered to. */\nfunction changes(payload: unknown): Change[] {\n if (!isObject(payload) || payload.object !== \"whatsapp_business_account\") return [];\n return list(payload.entry)\n .flatMap((entry) => list(entry.changes))\n .flatMap((change): Change[] => {\n const value = change.value;\n const accountId = isObject(value) && isObject(value.metadata) ? text(value.metadata.phone_number_id) : null;\n return isObject(value) && accountId ? [{ value, accountId }] : [];\n });\n}\n\n/** One reader per message `type`; null when the type's object is missing or malformed. */\nconst CONTENT_READERS: Readonly<Record<string, (message: Json) => InboundContent | null>> = {\n text: (message) => {\n const body = isObject(message.text) ? text(message.text.body) : null;\n return body ? { kind: \"TEXT\", text: body } : null;\n },\n interactive: (message) => {\n const interactive = isObject(message.interactive) ? message.interactive : {};\n const reply = interactive.button_reply ?? interactive.list_reply;\n const id = isObject(reply) ? text(reply.id) : null;\n return isObject(reply) && id ? { kind: \"INTERACTIVE\", replyId: id, title: text(reply.title) ?? \"\" } : null;\n },\n // A quick-reply button on a template message.\n button: (message) => {\n if (!isObject(message.button)) return null;\n const title = text(message.button.text) ?? \"\";\n return { kind: \"INTERACTIVE\", replyId: text(message.button.payload) ?? title, title };\n },\n audio: (message) => {\n const id = isObject(message.audio) ? text(message.audio.id) : null;\n return isObject(message.audio) && id ? { kind: \"AUDIO\", mediaId: id, mimeType: text(message.audio.mime_type) } : null;\n },\n};\n\n/** The content of one message, by its `type`; anything unread is OTHER. */\nfunction contentOf(message: Json): InboundContent {\n const type = text(message.type) ?? \"unknown\";\n return CONTENT_READERS[type]?.(message) ?? { kind: \"OTHER\", channelType: type };\n}\n\n/** The words a person typed or tapped, for the opt-out check. */\nfunction wordsOf(content: InboundContent): string | null {\n if (content.kind === \"TEXT\") return content.text;\n if (content.kind === \"INTERACTIVE\") return content.title;\n return null;\n}\n\n/** The profile name Meta sends per sender, keyed by wa_id. */\nfunction contactNames(value: Json): Map<string, string> {\n const names = new Map<string, string>();\n for (const contact of list(value.contacts)) {\n const waId = text(contact.wa_id);\n const name = isObject(contact.profile) ? text(contact.profile.name) : null;\n if (waId && name) names.set(waId, name);\n }\n return names;\n}\n\nfunction messageEvent(\n message: Json,\n accountId: string,\n names: Map<string, string>,\n keywords: readonly string[],\n): InboundMessageEvent | null {\n const contactId = text(message.from);\n const externalId = text(message.id);\n const sentAt = when(message.timestamp);\n if (!contactId || !externalId || !sentAt) return null;\n const content = contentOf(message);\n const words = wordsOf(content);\n return {\n type: \"message\",\n accountId,\n contactId,\n contactName: names.get(contactId) ?? null,\n externalId,\n sentAt,\n content,\n optOut: words !== null && isOptOutText(words, keywords),\n };\n}\n\nfunction messageEvents(value: Json, accountId: string, keywords: readonly string[]): InboundMessageEvent[] {\n const names = contactNames(value);\n return list(value.messages).flatMap((message) => messageEvent(message, accountId, names, keywords) ?? []);\n}\n\nconst RECEIPTS: Readonly<Record<string, ReceiptStatus>> = {\n sent: \"SENT\",\n delivered: \"DELIVERED\",\n read: \"READ\",\n failed: \"FAILED\",\n};\n\n/** The first error of a failed status, as `code: title`. */\nfunction errorOf(status: Json): string | null {\n const [first] = list(status.errors);\n if (!first) return null;\n const code = first.code === undefined ? \"\" : String(first.code);\n const title = text(first.title) ?? text(first.message) ?? \"\";\n return [code, title].filter(Boolean).join(\": \") || null;\n}\n\nfunction statusEvents(value: Json, accountId: string): StatusEvent[] {\n const out: StatusEvent[] = [];\n for (const status of list(value.statuses)) {\n const externalId = text(status.id);\n const receipt = RECEIPTS[text(status.status) ?? \"\"];\n const at = when(status.timestamp);\n if (!externalId || !receipt || !at) continue;\n out.push({\n type: \"status\",\n accountId,\n externalId,\n status: receipt,\n at,\n contactId: text(status.recipient_id),\n error: receipt === \"FAILED\" ? errorOf(status) : null,\n });\n }\n return out;\n}\n\n/** Meta's own opt-out: a `user_preferences` change whose value is `stop`. */\nfunction preferenceEvents(value: Json, accountId: string): OptOutEvent[] {\n const out: OptOutEvent[] = [];\n for (const preference of list(value.user_preferences)) {\n const contactId = text(preference.wa_id);\n const at = when(preference.timestamp);\n if (contactId && at && text(preference.value)?.toLowerCase() === \"stop\") {\n out.push({ type: \"opt_out\", accountId, contactId, at });\n }\n }\n return out;\n}\n\n/**\n * Every event in a WhatsApp webhook payload (already `JSON.parse`d): inbound\n * messages (with the opt-out keyword check), delivery receipts, and Meta's\n * own opt-out signal.\n */\nexport function parseWhatsAppPayload(\n payload: unknown,\n options: { optOutKeywords?: readonly string[] } = {},\n): NormalizedEvent[] {\n const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;\n const out: NormalizedEvent[] = [];\n for (const { value, accountId } of changes(payload)) {\n out.push(...messageEvents(value, accountId, keywords), ...statusEvents(value, accountId), ...preferenceEvents(value, accountId));\n }\n return out;\n}\n\n/**\n * Only the delivery receipts of a WhatsApp webhook payload — for a host that\n * tracks receipts of messages it sends some other way (a platform\n * notification number) without mounting the connector.\n */\nexport function parseWhatsAppStatuses(payload: unknown): StatusEvent[] {\n return changes(payload).flatMap(({ value, accountId }) => statusEvents(value, accountId));\n}\n","import { ChannelSendFailure } from \"../core/channel\";\nimport type { OutboundContent } from \"../core/types\";\n\n/**\n * The only way the adapter reaches Meta: an injected fetch. The global\n * `fetch` satisfies it; a test answers it with a recording fake.\n */\nexport type FetchPort = (\n url: string,\n init: { method: string; headers: Record<string, string>; body?: string },\n) => Promise<{ status: number; text(): Promise<string> }>;\n\n/** Where the Graph API is, and through what. Both numbers are config, never constants in the adapter. */\nexport interface GraphConfig {\n fetch: FetchPort;\n /** `https://graph.facebook.com` — no trailing slash needed. */\n baseUrl: string;\n /** `v23.0` — the Graph API version every call is pinned to. */\n apiVersion: string;\n}\n\n/** A Graph call that did not answer 2xx. Carries Meta's error code; never the token. */\nexport class GraphError extends ChannelSendFailure {\n readonly status: number;\n constructor(status: number, code: string, message: string) {\n super(code, message);\n this.name = \"GraphError\";\n this.status = status;\n }\n}\n\ntype Json = Record<string, unknown>;\n\ninterface GraphCall {\n method: \"GET\" | \"POST\";\n path: string;\n token?: string;\n query?: Record<string, string>;\n body?: unknown;\n}\n\n/** Drops trailing \"/\" characters in one linear pass (a regex here backtracks quadratically on library input). */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return end === value.length ? value : value.slice(0, end);\n}\n\n/** The URL and the request init of one call. The token travels in a header, never in the URL. */\nfunction requestOf(graph: GraphConfig, call: GraphCall) {\n const base = trimTrailingSlashes(graph.baseUrl);\n const query = call.query ? `?${new URLSearchParams(call.query).toString()}` : \"\";\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (call.token) headers.authorization = `Bearer ${call.token}`;\n if (call.body !== undefined) headers[\"content-type\"] = \"application/json\";\n return {\n url: `${base}/${graph.apiVersion}/${call.path}${query}`,\n init: { method: call.method, headers, ...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}) },\n };\n}\n\n/** A body as a JSON object; anything else (empty, HTML, an array) as `{}`. */\nfunction objectOf(raw: string): Json {\n try {\n const parsed: unknown = raw ? JSON.parse(raw) : {};\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed) ? (parsed as Json) : {};\n } catch {\n return {};\n }\n}\n\n/** Meta's error envelope (`{ error: { code, message } }`) as a {@link GraphError}. */\nfunction graphErrorOf(status: number, json: Json): GraphError {\n const error = typeof json.error === \"object\" && json.error !== null ? (json.error as Json) : {};\n const code = error.code === undefined ? `HTTP_${status}` : String(error.code);\n const message = typeof error.message === \"string\" ? error.message : `Graph answered ${status}`;\n return new GraphError(status, code, message.slice(0, 300));\n}\n\n/** One Graph call; resolves to the parsed JSON body, or throws {@link GraphError}. */\nexport async function graphRequest(graph: GraphConfig, call: GraphCall): Promise<Json> {\n const { url, init } = requestOf(graph, call);\n const response = await graph.fetch(url, init);\n const json = objectOf(await response.text());\n if (response.status < 200 || response.status >= 300) throw graphErrorOf(response.status, json);\n return json;\n}\n\n/** The Cloud API body for one outbound message. */\nexport function messageBody(to: string, content: OutboundContent): Json {\n const base = { messaging_product: \"whatsapp\", recipient_type: \"individual\", to };\n if (content.kind === \"TEXT\") return { ...base, type: \"text\", text: { body: content.text, preview_url: false } };\n if (content.kind === \"BUTTONS\") {\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"button\",\n body: { text: content.text },\n action: { buttons: content.buttons.map((button) => ({ type: \"reply\", reply: { id: button.id, title: button.title } })) },\n },\n };\n }\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"list\",\n body: { text: content.text },\n action: {\n button: content.buttonLabel,\n sections: content.sections.map((section) => ({\n ...(section.title ? { title: section.title } : {}),\n rows: section.rows.map((row) => ({ id: row.id, title: row.title, ...(row.description ? { description: row.description } : {}) })),\n })),\n },\n },\n };\n}\n\n/** Send one message from a phone number; resolves to its wamid. */\nexport async function sendWhatsAppMessage(\n graph: GraphConfig,\n input: { token: string; phoneNumberId: string; to: string; content: OutboundContent },\n): Promise<{ externalId: string }> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.phoneNumberId)}/messages`,\n token: input.token,\n body: messageBody(input.to, input.content),\n });\n const [first] = Array.isArray(json.messages) ? (json.messages as Json[]) : [];\n const id = first && typeof first.id === \"string\" ? first.id : null;\n if (!id) throw new GraphError(200, \"NO_MESSAGE_ID\", \"Graph accepted the message but returned no id\");\n return { externalId: id };\n}\n","import { createHash, createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Meta's webhook proofs, as standalone functions: the connector's WhatsApp\n * adapter uses them, and so can any other WhatsApp webhook a host runs (a\n * platform notification number's receipts), without mounting the connector.\n */\n\n/** The header Meta signs every webhook POST with. */\nexport const META_SIGNATURE_HEADER = \"x-hub-signature-256\";\n\nconst SIGNATURE = /^sha256=([0-9a-f]{64})$/i;\n\n/**\n * Does `signatureHeader` prove `rawBody` was signed with `appSecret`?\n *\n * HMAC-SHA256 over the RAW body bytes exactly as received (a re-serialized\n * JSON body never matches; hand the bytes, not a decoded string, where the\n * framework gives them), compared in constant time. Fails CLOSED: an empty\n * secret, a missing header, a header in any other shape, or a digest of the\n * wrong length is `false` — never an exception, never `true`.\n */\nexport function verifyMetaSignature(rawBody: string | Uint8Array, signatureHeader: string | null | undefined, appSecret: string): boolean {\n if (!appSecret || !signatureHeader) return false;\n const match = SIGNATURE.exec(signatureHeader.trim());\n if (!match) return false;\n const expected = createHmac(\"sha256\", appSecret).update(rawBody).digest();\n const given = Buffer.from(match[1]!, \"hex\");\n return given.length === expected.length && timingSafeEqual(given, expected);\n}\n\n/** What the subscription handshake answers. */\nexport type MetaHandshake = { ok: true; challenge: string } | { ok: false };\n\n/**\n * Meta's `GET` subscription handshake: `hub.mode=subscribe`, the\n * `hub.verify_token` configured on the app, and a `hub.challenge` to echo.\n * The token is compared in constant time; an empty configured token refuses\n * every handshake.\n */\nexport function verifyMetaSubscription(\n query: Readonly<Record<string, string | undefined>>,\n verifyToken: string,\n): MetaHandshake {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (!verifyToken || mode !== \"subscribe\" || !token || !challenge) return { ok: false };\n // Digests of equal length, so the comparison leaks neither content nor length.\n const digest = (value: string) => createHash(\"sha256\").update(value, \"utf8\").digest();\n return timingSafeEqual(digest(token), digest(verifyToken)) ? { ok: true, challenge } : { ok: false };\n}\n","import { GraphError, graphRequest, type GraphConfig } from \"./graph\";\n\n/**\n * Embedded Signup, server half. The browser half (Meta's SDK popup) hands the\n * host a short-lived `code`; these three calls turn it into a connection:\n *\n * 1. {@link exchangeSignupCode} — the code for a business token;\n * 2. {@link readSignupAccounts} — which WhatsApp Business Accounts the token\n * was granted, and each one's phone numbers (id + display number);\n * 3. {@link subscribeAppToWaba} — subscribe the app to the chosen account's\n * webhooks, so its messages reach the connector.\n *\n * Then the host calls `engine.connect(...)` with the phone number id, the\n * display number and the token, which the engine seals. None of these\n * functions logs or returns anything but what is named.\n */\n\ntype Json = Record<string, unknown>;\n\n/** The app's own identity on Meta. The secret is the host's, read where it keeps secrets. */\nexport interface MetaAppCredentials {\n appId: string;\n appSecret: string;\n}\n\n/** Exchange Embedded Signup's code for a business integration token. */\nexport async function exchangeSignupCode(\n graph: GraphConfig,\n input: MetaAppCredentials & { code: string; redirectUri?: string },\n): Promise<{ accessToken: string }> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: \"oauth/access_token\",\n query: {\n client_id: input.appId,\n client_secret: input.appSecret,\n code: input.code,\n ...(input.redirectUri ? { redirect_uri: input.redirectUri } : {}),\n },\n });\n if (typeof json.access_token !== \"string\" || json.access_token.length === 0) {\n throw new GraphError(200, \"NO_ACCESS_TOKEN\", \"Graph answered the code exchange without a token\");\n }\n return { accessToken: json.access_token };\n}\n\n/** One phone number of a WhatsApp Business Account. */\nexport interface SignupPhoneNumber {\n /** The phone_number_id: the connection's external account id. */\n id: string;\n /** What a person reads (`+55 11 98765-4321`): the connection's display address. */\n displayPhoneNumber: string;\n verifiedName: string | null;\n}\n\nexport interface SignupAccount {\n /** The WABA id: the connection's external parent id. */\n wabaId: string;\n phoneNumbers: SignupPhoneNumber[];\n}\n\n/**\n * The WhatsApp Business Accounts the token was granted (read from the token's\n * own granular scopes, with the app's token), and each one's phone numbers.\n */\nexport async function readSignupAccounts(\n graph: GraphConfig,\n input: MetaAppCredentials & { accessToken: string },\n): Promise<SignupAccount[]> {\n const debug = await graphRequest(graph, {\n method: \"GET\",\n path: \"debug_token\",\n query: { input_token: input.accessToken },\n token: `${input.appId}|${input.appSecret}`,\n });\n const data = typeof debug.data === \"object\" && debug.data !== null ? (debug.data as Json) : {};\n const scopes = Array.isArray(data.granular_scopes) ? (data.granular_scopes as Json[]) : [];\n const wabaIds = new Set(\n scopes\n .filter((scope) => scope.scope === \"whatsapp_business_management\" && Array.isArray(scope.target_ids))\n .flatMap((scope) => (scope.target_ids as unknown[]).filter((id): id is string => typeof id === \"string\")),\n );\n const accounts: SignupAccount[] = [];\n for (const wabaId of wabaIds) {\n accounts.push({ wabaId, phoneNumbers: await readPhoneNumbers(graph, wabaId, input.accessToken) });\n }\n return accounts;\n}\n\nasync function readPhoneNumbers(graph: GraphConfig, wabaId: string, accessToken: string): Promise<SignupPhoneNumber[]> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: `${encodeURIComponent(wabaId)}/phone_numbers`,\n query: { fields: \"id,display_phone_number,verified_name\" },\n token: accessToken,\n });\n const rows = Array.isArray(json.data) ? (json.data as Json[]) : [];\n return rows\n .filter((row) => typeof row.id === \"string\" && typeof row.display_phone_number === \"string\")\n .map((row) => ({\n id: row.id as string,\n displayPhoneNumber: row.display_phone_number as string,\n verifiedName: typeof row.verified_name === \"string\" ? row.verified_name : null,\n }));\n}\n\n/** Subscribe the app to a WABA's webhooks. Resolves when Meta answers `success: true`. */\nexport async function subscribeAppToWaba(graph: GraphConfig, input: { wabaId: string; accessToken: string }): Promise<void> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.wabaId)}/subscribed_apps`,\n token: input.accessToken,\n });\n if (json.success !== true) throw new GraphError(200, \"NOT_SUBSCRIBED\", \"Graph did not confirm the subscription\");\n}\n","/**\n * `@12-apps/messaging/whatsapp` — the WhatsApp Cloud API channel adapter.\n *\n * `createWhatsAppAdapter(config)` is what a host hands the engine. The pieces\n * are exported on their own too: the signature check and the receipt parser\n * serve any WhatsApp webhook (a platform notification number), and the\n * Embedded Signup helpers serve the host's connect flow.\n *\n * `@12-apps/notifications` has its own WhatsApp transport, for one-way\n * notification messages. It is deliberately NOT reused here: this adapter\n * carries a conversation (inbound, the service window, opt-out, receipts),\n * which that transport has no model for.\n */\n\nimport { serviceWindowPolicy, type ChannelAdapter } from \"../core/channel\";\nimport { parseWhatsAppPayload } from \"./parse\";\nimport { sendWhatsAppMessage, type GraphConfig } from \"./graph\";\nimport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription } from \"./signature\";\n\n/** The channel key every WhatsApp row carries. */\nexport const WHATSAPP_CHANNEL = \"whatsapp\";\n\n/** WhatsApp's customer service window: free-form messages only within 24 h of the contact's last message. */\nexport const WHATSAPP_SERVICE_WINDOW_MS = 24 * 60 * 60 * 1000;\n\nexport interface WhatsAppAdapterConfig {\n /** The Meta app's secret: every webhook POST is signed with it. Empty refuses every delivery. */\n appSecret: string;\n /** The token configured on the app's webhook subscription. Empty refuses every handshake. */\n verifyToken: string;\n /** The Graph API: fetch, base URL and version. */\n graph: GraphConfig;\n /** The whole-message words that opt a contact out. Default: PARAR, SAIR, STOP, CANCELAR. */\n optOutKeywords?: readonly string[];\n}\n\n/** The WhatsApp Cloud adapter. */\nexport function createWhatsAppAdapter(config: WhatsAppAdapterConfig): ChannelAdapter {\n return {\n kind: WHATSAPP_CHANNEL,\n handshake: (query) => verifyMetaSubscription(query, config.verifyToken),\n verify: ({ rawBody, header }) => verifyMetaSignature(rawBody, header(META_SIGNATURE_HEADER), config.appSecret),\n parse: (rawBody) =>\n parseWhatsAppPayload(JSON.parse(rawBody) as unknown, {\n ...(config.optOutKeywords ? { optOutKeywords: config.optOutKeywords } : {}),\n }),\n send: ({ credential, accountId, to, content }) =>\n sendWhatsAppMessage(config.graph, { token: credential, phoneNumberId: accountId, to, content }),\n policy: serviceWindowPolicy(WHATSAPP_SERVICE_WINDOW_MS),\n };\n}\n\nexport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription, type MetaHandshake } from \"./signature\";\nexport { parseWhatsAppPayload, parseWhatsAppStatuses } from \"./parse\";\nexport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\nexport { GraphError, graphRequest, messageBody, sendWhatsAppMessage, type FetchPort, type GraphConfig } from \"./graph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src/whatsapp/graph.ts","../../src/whatsapp/media.ts","../../src/whatsapp/signature.ts","../../src/whatsapp/signup.ts","../../src/whatsapp/index.ts"],"sourcesContent":["/**\n * The words that opt a contact out, by default: the Portuguese and English\n * stop words a WhatsApp user is told to send. A host replaces the list through\n * the adapter's config.\n */\nexport const DEFAULT_OPT_OUT_KEYWORDS: readonly string[] = [\"PARAR\", \"SAIR\", \"STOP\", \"CANCELAR\"];\n\n/** Upper case, accents stripped, surrounding space, punctuation and emoji trimmed. */\nfunction fold(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/\\p{M}/gu, \"\")\n .replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\")\n .toUpperCase();\n}\n\n/**\n * Is this text an opt-out? Only when the WHOLE message is one keyword —\n * case- and accent-insensitive, ignoring punctuation and emoji around it — so\n * \"parar\", \"PARAR.\" and \"Parar!\" opt out, and \"parar de enviar\" (a sentence,\n * maybe about something else) does not.\n */\nexport function isOptOutText(text: string, keywords: readonly string[] = DEFAULT_OPT_OUT_KEYWORDS): boolean {\n const folded = fold(text);\n return folded.length > 0 && keywords.some((keyword) => fold(keyword) === folded);\n}\n","import type {\n InboundContent,\n InboundMessageEvent,\n NormalizedEvent,\n OptOutEvent,\n ReceiptStatus,\n StatusEvent,\n} from \"../core/types\";\nimport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\n\n/**\n * The WhatsApp Cloud API webhook payload, read defensively: every field is\n * checked before it is trusted, an unknown shape is skipped rather than\n * thrown on, and only `JSON.parse` itself may throw (bytes that are not JSON).\n *\n * Shape: `{ object: \"whatsapp_business_account\", entry: [{ id, changes: [{\n * field, value: { metadata: { phone_number_id }, contacts, messages,\n * statuses, user_preferences } }] }] }`. Events come out in payload order.\n */\n\ntype Json = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is Json => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst list = (value: unknown): Json[] => (Array.isArray(value) ? value.filter(isObject) : []);\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\n/** Meta's timestamps are Unix SECONDS, as a string. Null when absent or malformed. */\nfunction when(value: unknown): Date | null {\n const seconds = typeof value === \"string\" || typeof value === \"number\" ? Number(value) : Number.NaN;\n return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000) : null;\n}\n\ninterface Change {\n value: Json;\n accountId: string;\n}\n\n/** Every `value` of every change, with the account it was delivered to. */\nfunction changes(payload: unknown): Change[] {\n if (!isObject(payload) || payload.object !== \"whatsapp_business_account\") return [];\n return list(payload.entry)\n .flatMap((entry) => list(entry.changes))\n .flatMap((change): Change[] => {\n const value = change.value;\n const accountId = isObject(value) && isObject(value.metadata) ? text(value.metadata.phone_number_id) : null;\n return isObject(value) && accountId ? [{ value, accountId }] : [];\n });\n}\n\n/** One reader per message `type`; null when the type's object is missing or malformed. */\nconst CONTENT_READERS: Readonly<Record<string, (message: Json) => InboundContent | null>> = {\n text: (message) => {\n const body = isObject(message.text) ? text(message.text.body) : null;\n return body ? { kind: \"TEXT\", text: body } : null;\n },\n interactive: (message) => {\n const interactive = isObject(message.interactive) ? message.interactive : {};\n const reply = interactive.button_reply ?? interactive.list_reply;\n const id = isObject(reply) ? text(reply.id) : null;\n return isObject(reply) && id ? { kind: \"INTERACTIVE\", replyId: id, title: text(reply.title) ?? \"\" } : null;\n },\n // A quick-reply button on a template message.\n button: (message) => {\n if (!isObject(message.button)) return null;\n const title = text(message.button.text) ?? \"\";\n return { kind: \"INTERACTIVE\", replyId: text(message.button.payload) ?? title, title };\n },\n audio: (message) => {\n const id = isObject(message.audio) ? text(message.audio.id) : null;\n return isObject(message.audio) && id ? { kind: \"AUDIO\", mediaId: id, mimeType: text(message.audio.mime_type) } : null;\n },\n};\n\n/** The content of one message, by its `type`; anything unread is OTHER. */\nfunction contentOf(message: Json): InboundContent {\n const type = text(message.type) ?? \"unknown\";\n return CONTENT_READERS[type]?.(message) ?? { kind: \"OTHER\", channelType: type };\n}\n\n/** The words a person typed or tapped, for the opt-out check. */\nfunction wordsOf(content: InboundContent): string | null {\n if (content.kind === \"TEXT\") return content.text;\n if (content.kind === \"INTERACTIVE\") return content.title;\n return null;\n}\n\n/** The profile name Meta sends per sender, keyed by wa_id. */\nfunction contactNames(value: Json): Map<string, string> {\n const names = new Map<string, string>();\n for (const contact of list(value.contacts)) {\n const waId = text(contact.wa_id);\n const name = isObject(contact.profile) ? text(contact.profile.name) : null;\n if (waId && name) names.set(waId, name);\n }\n return names;\n}\n\nfunction messageEvent(\n message: Json,\n accountId: string,\n names: Map<string, string>,\n keywords: readonly string[],\n): InboundMessageEvent | null {\n const contactId = text(message.from);\n const externalId = text(message.id);\n const sentAt = when(message.timestamp);\n if (!contactId || !externalId || !sentAt) return null;\n const content = contentOf(message);\n const words = wordsOf(content);\n return {\n type: \"message\",\n accountId,\n contactId,\n contactName: names.get(contactId) ?? null,\n externalId,\n sentAt,\n content,\n optOut: words !== null && isOptOutText(words, keywords),\n };\n}\n\nfunction messageEvents(value: Json, accountId: string, keywords: readonly string[]): InboundMessageEvent[] {\n const names = contactNames(value);\n return list(value.messages).flatMap((message) => messageEvent(message, accountId, names, keywords) ?? []);\n}\n\nconst RECEIPTS: Readonly<Record<string, ReceiptStatus>> = {\n sent: \"SENT\",\n delivered: \"DELIVERED\",\n read: \"READ\",\n failed: \"FAILED\",\n};\n\n/** The first error of a failed status, as `code: title`. */\nfunction errorOf(status: Json): string | null {\n const [first] = list(status.errors);\n if (!first) return null;\n const code = first.code === undefined ? \"\" : String(first.code);\n const title = text(first.title) ?? text(first.message) ?? \"\";\n return [code, title].filter(Boolean).join(\": \") || null;\n}\n\nfunction statusEvents(value: Json, accountId: string): StatusEvent[] {\n const out: StatusEvent[] = [];\n for (const status of list(value.statuses)) {\n const externalId = text(status.id);\n const receipt = RECEIPTS[text(status.status) ?? \"\"];\n const at = when(status.timestamp);\n if (!externalId || !receipt || !at) continue;\n out.push({\n type: \"status\",\n accountId,\n externalId,\n status: receipt,\n at,\n contactId: text(status.recipient_id),\n error: receipt === \"FAILED\" ? errorOf(status) : null,\n });\n }\n return out;\n}\n\n/** Meta's own opt-out: a `user_preferences` change whose value is `stop`. */\nfunction preferenceEvents(value: Json, accountId: string): OptOutEvent[] {\n const out: OptOutEvent[] = [];\n for (const preference of list(value.user_preferences)) {\n const contactId = text(preference.wa_id);\n const at = when(preference.timestamp);\n if (contactId && at && text(preference.value)?.toLowerCase() === \"stop\") {\n out.push({ type: \"opt_out\", accountId, contactId, at });\n }\n }\n return out;\n}\n\n/**\n * Every event in a WhatsApp webhook payload (already `JSON.parse`d): inbound\n * messages (with the opt-out keyword check), delivery receipts, and Meta's\n * own opt-out signal.\n */\nexport function parseWhatsAppPayload(\n payload: unknown,\n options: { optOutKeywords?: readonly string[] } = {},\n): NormalizedEvent[] {\n const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;\n const out: NormalizedEvent[] = [];\n for (const { value, accountId } of changes(payload)) {\n out.push(...messageEvents(value, accountId, keywords), ...statusEvents(value, accountId), ...preferenceEvents(value, accountId));\n }\n return out;\n}\n\n/**\n * Only the delivery receipts of a WhatsApp webhook payload — for a host that\n * tracks receipts of messages it sends some other way (a platform\n * notification number) without mounting the connector.\n */\nexport function parseWhatsAppStatuses(payload: unknown): StatusEvent[] {\n return changes(payload).flatMap(({ value, accountId }) => statusEvents(value, accountId));\n}\n","import { ChannelSendFailure } from \"../core/channel\";\nimport type { OutboundContent } from \"../core/types\";\n\n/**\n * The only way the adapter reaches Meta: an injected fetch. The global\n * `fetch` satisfies it; a test answers it with a recording fake.\n *\n * A JSON call reads `text()` only. A media download also asks for\n * `redirect: \"manual\"` (a 3xx comes back as itself, never followed) and reads\n * the binary body through `body` (a stream, read up to the size cap) or, when\n * there is none, `arrayBuffer()`. All three are optional so a text-only fake\n * still satisfies the port.\n */\nexport type FetchPort = (url: string, init: FetchInit) => Promise<FetchResponse>;\n\nexport interface FetchInit {\n method: string;\n headers: Record<string, string>;\n body?: string;\n /** `manual` for a media download: a redirect is answered, never followed. */\n redirect?: \"manual\" | \"follow\" | \"error\";\n /** Aborts the call at a media download's deadline. */\n signal?: AbortSignal;\n}\n\nexport interface FetchResponse {\n status: number;\n text(): Promise<string>;\n arrayBuffer?(): Promise<ArrayBuffer>;\n /** The body as a stream; read chunk by chunk so an oversized one is cut off early. */\n body?: { getReader(): FetchBodyReader; cancel?(reason?: unknown): Promise<void> } | null;\n headers?: { get(name: string): string | null };\n}\n\nexport interface FetchBodyReader {\n read(): Promise<{ done: boolean; value?: Uint8Array }>;\n cancel(reason?: unknown): Promise<void>;\n}\n\n/**\n * The hosts Meta serves WhatsApp media from: the URL a media lookup returns is\n * `https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=…`, and the\n * CDN families behind it. `*.` matches any subdomain (not the bare domain).\n */\nexport const DEFAULT_META_MEDIA_HOSTS: readonly string[] = [\"lookaside.fbsbx.com\", \"*.fbcdn.net\", \"*.whatsapp.net\"];\n\n/** Where the Graph API is, and through what. Both numbers are config, never constants in the adapter. */\nexport interface GraphConfig {\n fetch: FetchPort;\n /** `https://graph.facebook.com` — no trailing slash needed. */\n baseUrl: string;\n /** `v23.0` — the Graph API version every call is pinned to. */\n apiVersion: string;\n /**\n * The hosts a media URL may point at; any other is refused before the token\n * is sent to it. Exact names, or `*.domain` for its subdomains. Default\n * {@link DEFAULT_META_MEDIA_HOSTS}.\n */\n mediaHosts?: readonly string[];\n}\n\n/** A Graph call that did not answer 2xx. Carries Meta's error code; never the token. */\nexport class GraphError extends ChannelSendFailure {\n readonly status: number;\n constructor(status: number, code: string, message: string) {\n super(code, message);\n this.name = \"GraphError\";\n this.status = status;\n }\n}\n\ntype Json = Record<string, unknown>;\n\ninterface GraphCall {\n method: \"GET\" | \"POST\";\n path: string;\n token?: string;\n query?: Record<string, string>;\n body?: unknown;\n redirect?: FetchInit[\"redirect\"];\n signal?: AbortSignal;\n}\n\n/** Drops trailing \"/\" characters in one linear pass (a regex here backtracks quadratically on library input). */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return end === value.length ? value : value.slice(0, end);\n}\n\n/** The URL and the request init of one call. The token travels in a header, never in the URL. */\nfunction requestOf(graph: GraphConfig, call: GraphCall) {\n const base = trimTrailingSlashes(graph.baseUrl);\n const query = call.query ? `?${new URLSearchParams(call.query).toString()}` : \"\";\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (call.token) headers.authorization = `Bearer ${call.token}`;\n if (call.body !== undefined) headers[\"content-type\"] = \"application/json\";\n return {\n url: `${base}/${graph.apiVersion}/${call.path}${query}`,\n init: {\n method: call.method,\n headers,\n ...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}),\n ...(call.redirect ? { redirect: call.redirect } : {}),\n ...(call.signal ? { signal: call.signal } : {}),\n } satisfies FetchInit,\n };\n}\n\n/** A body as a JSON object; anything else (empty, HTML, an array) as `{}`. */\nfunction objectOf(raw: string): Json {\n try {\n const parsed: unknown = raw ? JSON.parse(raw) : {};\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed) ? (parsed as Json) : {};\n } catch {\n return {};\n }\n}\n\n/** Meta's error envelope (`{ error: { code, message } }`) as a {@link GraphError}. */\nfunction graphErrorOf(status: number, json: Json): GraphError {\n const error = typeof json.error === \"object\" && json.error !== null ? (json.error as Json) : {};\n const code = error.code === undefined ? `HTTP_${status}` : String(error.code);\n const message = typeof error.message === \"string\" ? error.message : `Graph answered ${status}`;\n return new GraphError(status, code, message.slice(0, 300));\n}\n\n/** One Graph call; resolves to the parsed JSON body, or throws {@link GraphError}. */\nexport async function graphRequest(graph: GraphConfig, call: GraphCall): Promise<Json> {\n const { url, init } = requestOf(graph, call);\n const response = await graph.fetch(url, init);\n const json = objectOf(await response.text());\n if (response.status < 200 || response.status >= 300) throw graphErrorOf(response.status, json);\n return json;\n}\n\n/** The Cloud API body for one outbound message. */\nexport function messageBody(to: string, content: OutboundContent): Json {\n const base = { messaging_product: \"whatsapp\", recipient_type: \"individual\", to };\n if (content.kind === \"TEXT\") return { ...base, type: \"text\", text: { body: content.text, preview_url: false } };\n if (content.kind === \"BUTTONS\") {\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"button\",\n body: { text: content.text },\n action: { buttons: content.buttons.map((button) => ({ type: \"reply\", reply: { id: button.id, title: button.title } })) },\n },\n };\n }\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"list\",\n body: { text: content.text },\n action: {\n button: content.buttonLabel,\n sections: content.sections.map((section) => ({\n ...(section.title ? { title: section.title } : {}),\n rows: section.rows.map((row) => ({ id: row.id, title: row.title, ...(row.description ? { description: row.description } : {}) })),\n })),\n },\n },\n };\n}\n\n/** Send one message from a phone number; resolves to its wamid. */\nexport async function sendWhatsAppMessage(\n graph: GraphConfig,\n input: { token: string; phoneNumberId: string; to: string; content: OutboundContent },\n): Promise<{ externalId: string }> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.phoneNumberId)}/messages`,\n token: input.token,\n body: messageBody(input.to, input.content),\n });\n const [first] = Array.isArray(json.messages) ? (json.messages as Json[]) : [];\n const id = first && typeof first.id === \"string\" ? first.id : null;\n if (!id) throw new GraphError(200, \"NO_MESSAGE_ID\", \"Graph accepted the message but returned no id\");\n return { externalId: id };\n}\n","import { ChannelMediaFailure, DEFAULT_MEDIA_TIMEOUT_MS, isPositiveSafeInteger, type ChannelMedia } from \"../core/channel\";\nimport { DEFAULT_META_MEDIA_HOSTS, graphRequest, type FetchResponse, type GraphConfig } from \"./graph\";\n\n/**\n * A WhatsApp media download, the Cloud API way: `GET /{version}/{media-id}`\n * with the business token answers `{ url, mime_type, file_size }`, and a\n * `GET` of that URL with the same token answers the bytes.\n *\n * The token travels in the Authorization header only, and only to a Meta\n * media host over https: the URL comes from Meta, but it is still checked\n * against the configured hosts before the token is sent to it, and a redirect\n * is refused rather than followed to wherever it points. The size is capped\n * twice — the declared `file_size` before the download, the bytes actually\n * read during it — the whole download has a deadline, and the media lives\n * only in the returned memory.\n */\n\nconst OCTET_STREAM = \"application/octet-stream\";\n\n/** Does `host` match one allowlist entry: an exact name, or `*.domain` for its subdomains. */\nfunction hostAllowed(host: string, allowed: readonly string[]): boolean {\n return allowed.some((entry) => {\n const pattern = entry.toLowerCase();\n // \"*.fbcdn.net\" matches \"x.fbcdn.net\" through its \".fbcdn.net\" suffix, never \"fbcdn.net\" or \"evilfbcdn.net\".\n return pattern.startsWith(\"*.\") ? host.endsWith(pattern.slice(1)) : host === pattern;\n });\n}\n\n/** The media URL Meta returned, checked: https, no userinfo, an allowed host. */\nfunction checkedMediaUrl(raw: unknown, allowed: readonly string[]): string {\n if (typeof raw !== \"string\" || raw === \"\") throw new ChannelMediaFailure(\"NO_MEDIA_URL\", \"Graph returned no media url\");\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new ChannelMediaFailure(\"MEDIA_URL_INVALID\", \"Graph returned a media url that does not parse\");\n }\n if (url.protocol !== \"https:\") throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url is not https\");\n if (url.username || url.password) throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url carries credentials\");\n if (url.port !== \"\") throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url names an explicit port\");\n if (!hostAllowed(url.hostname.toLowerCase(), allowed)) {\n throw new ChannelMediaFailure(\"MEDIA_HOST_REFUSED\", `the media host ${url.hostname} is not a Meta media host`);\n }\n return url.toString();\n}\n\nconst tooLarge = (size: number, maxBytes: number) =>\n new ChannelMediaFailure(\"TOO_LARGE\", `the media is ${size} bytes, over the ${maxBytes}-byte cap`);\n\n/** A declared size over the cap refuses the download before it starts. */\nfunction checkDeclaredSize(declared: unknown, maxBytes: number): void {\n const size = typeof declared === \"number\" ? declared : typeof declared === \"string\" ? Number(declared) : NaN;\n if (Number.isFinite(size) && size > maxBytes) throw tooLarge(size, maxBytes);\n}\n\n/** Concatenate the chunks read so far. */\nfunction joined(chunks: Uint8Array[], total: number): Uint8Array {\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/** The download's deadline: one abort signal for both calls, and a race for every read. */\ninterface Deadline {\n signal: AbortSignal;\n /** `promise`, or a `TIMEOUT` failure once the deadline passes — whichever comes first. */\n race<T>(promise: Promise<T>): Promise<T>;\n clear(): void;\n}\n\nconst timedOut = (timeoutMs: number) =>\n new ChannelMediaFailure(\"TIMEOUT\", `the media download did not finish within ${timeoutMs} ms`);\n\nfunction deadlineOf(timeoutMs: number): Deadline {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(timedOut(timeoutMs));\n }, timeoutMs);\n });\n // The race below observes it; this only keeps an unobserved expiry from being reported unhandled.\n expired.catch(() => undefined);\n return {\n signal: controller.signal,\n race: async (promise) => {\n try {\n return await Promise.race([promise, expired]);\n } catch (error) {\n // A port that honours the signal rejects with its own abort error: it is the deadline all the same.\n throw controller.signal.aborted ? timedOut(timeoutMs) : error;\n }\n },\n clear: () => clearTimeout(timer),\n };\n}\n\n/** Release a body that will not be read; never throws. */\nfunction discardBody(response: FetchResponse): void {\n try {\n void Promise.resolve(response.body?.cancel?.()).catch(() => undefined);\n } catch {\n // A body that cannot even be cancelled is left to the garbage collector.\n }\n}\n\n/** Read a stream, cancelling it the moment it passes the cap or the deadline. */\nasync function readStreamCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {\n const reader = response.body!.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await deadline.race(reader.read());\n if (done) break;\n if (!value) continue;\n total += value.length;\n if (total > maxBytes) throw tooLarge(total, maxBytes);\n chunks.push(value);\n }\n } catch (error) {\n void reader.cancel().catch(() => undefined);\n throw error;\n }\n return joined(chunks, total);\n}\n\n/** The body's bytes, never more than `maxBytes` of them — whatever the headers declared. */\nasync function readBodyCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {\n const declared = response.headers?.get(\"content-length\");\n if (declared) {\n try {\n checkDeclaredSize(declared, maxBytes);\n } catch (error) {\n discardBody(response);\n throw error;\n }\n }\n if (response.body && typeof response.body.getReader === \"function\") return readStreamCapped(response, maxBytes, deadline);\n if (!response.arrayBuffer) throw new ChannelMediaFailure(\"NO_BINARY_BODY\", \"the fetch port cannot read a binary body\");\n // Only for a port with no stream: it reads the WHOLE body before the cap can be checked.\n const bytes = new Uint8Array(await deadline.race(response.arrayBuffer()));\n if (bytes.length > maxBytes) throw tooLarge(bytes.length, maxBytes);\n return bytes;\n}\n\n/** GET the media URL with the token in a header; a redirect or a non-2xx is refused, its body discarded. */\nasync function downloadFrom(graph: GraphConfig, url: string, token: string, deadline: Deadline): Promise<FetchResponse> {\n const response = await deadline.race(\n graph.fetch(url, {\n method: \"GET\",\n headers: { authorization: `Bearer ${token}`, accept: \"*/*\" },\n redirect: \"manual\",\n signal: deadline.signal,\n }),\n );\n if (response.status >= 200 && response.status < 300) return response;\n discardBody(response);\n if (response.status >= 300 && response.status < 400) {\n throw new ChannelMediaFailure(\"REDIRECT_REFUSED\", `the media download answered ${response.status}; redirects are not followed`);\n }\n throw new ChannelMediaFailure(`HTTP_${response.status}`, `the media download answered ${response.status}`);\n}\n\n/** A cap or deadline that would not bound anything (NaN, Infinity, 0, negative, fractional) is refused. */\nfunction checkLimits(maxBytes: number, timeoutMs: number): void {\n if (!isPositiveSafeInteger(maxBytes) || !isPositiveSafeInteger(timeoutMs)) {\n throw new ChannelMediaFailure(\"BAD_OPTIONS\", \"maxBytes and timeoutMs must be positive safe integers\");\n }\n}\n\n/** Download one WhatsApp media object into memory. */\nexport async function downloadWhatsAppMedia(\n graph: GraphConfig,\n input: { token: string; mediaId: string; maxBytes: number; timeoutMs?: number },\n): Promise<ChannelMedia> {\n const timeoutMs = input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS;\n checkLimits(input.maxBytes, timeoutMs);\n const deadline = deadlineOf(timeoutMs);\n try {\n const meta = await deadline.race(\n graphRequest(graph, {\n method: \"GET\",\n path: encodeURIComponent(input.mediaId),\n token: input.token,\n redirect: \"manual\",\n signal: deadline.signal,\n }),\n );\n const url = checkedMediaUrl(meta.url, graph.mediaHosts ?? DEFAULT_META_MEDIA_HOSTS);\n checkDeclaredSize(meta.file_size, input.maxBytes);\n const response = await downloadFrom(graph, url, input.token, deadline);\n const bytes = await readBodyCapped(response, input.maxBytes, deadline);\n const declaredType = typeof meta.mime_type === \"string\" && meta.mime_type ? meta.mime_type : null;\n const mimeType = declaredType ?? response.headers?.get(\"content-type\") ?? OCTET_STREAM;\n return { bytes, mimeType, size: bytes.length };\n } finally {\n deadline.clear();\n }\n}\n","import { createHash, createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Meta's webhook proofs, as standalone functions: the connector's WhatsApp\n * adapter uses them, and so can any other WhatsApp webhook a host runs (a\n * platform notification number's receipts), without mounting the connector.\n */\n\n/** The header Meta signs every webhook POST with. */\nexport const META_SIGNATURE_HEADER = \"x-hub-signature-256\";\n\nconst SIGNATURE = /^sha256=([0-9a-f]{64})$/i;\n\n/**\n * Does `signatureHeader` prove `rawBody` was signed with `appSecret`?\n *\n * HMAC-SHA256 over the RAW body bytes exactly as received (a re-serialized\n * JSON body never matches; hand the bytes, not a decoded string, where the\n * framework gives them), compared in constant time. Fails CLOSED: an empty\n * secret, a missing header, a header in any other shape, or a digest of the\n * wrong length is `false` — never an exception, never `true`.\n */\nexport function verifyMetaSignature(rawBody: string | Uint8Array, signatureHeader: string | null | undefined, appSecret: string): boolean {\n if (!appSecret || !signatureHeader) return false;\n const match = SIGNATURE.exec(signatureHeader.trim());\n if (!match) return false;\n const expected = createHmac(\"sha256\", appSecret).update(rawBody).digest();\n const given = Buffer.from(match[1]!, \"hex\");\n return given.length === expected.length && timingSafeEqual(given, expected);\n}\n\n/** What the subscription handshake answers. */\nexport type MetaHandshake = { ok: true; challenge: string } | { ok: false };\n\n/**\n * Meta's `GET` subscription handshake: `hub.mode=subscribe`, the\n * `hub.verify_token` configured on the app, and a `hub.challenge` to echo.\n * The token is compared in constant time; an empty configured token refuses\n * every handshake.\n */\nexport function verifyMetaSubscription(\n query: Readonly<Record<string, string | undefined>>,\n verifyToken: string,\n): MetaHandshake {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (!verifyToken || mode !== \"subscribe\" || !token || !challenge) return { ok: false };\n // Digests of equal length, so the comparison leaks neither content nor length.\n const digest = (value: string) => createHash(\"sha256\").update(value, \"utf8\").digest();\n return timingSafeEqual(digest(token), digest(verifyToken)) ? { ok: true, challenge } : { ok: false };\n}\n","import { GraphError, graphRequest, type GraphConfig } from \"./graph\";\n\n/**\n * Embedded Signup, server half. The browser half (Meta's SDK popup) hands the\n * host a short-lived `code`; these three calls turn it into a connection:\n *\n * 1. {@link exchangeSignupCode} — the code for a business token;\n * 2. {@link readSignupAccounts} — which WhatsApp Business Accounts the token\n * was granted, and each one's phone numbers (id + display number);\n * 3. {@link subscribeAppToWaba} — subscribe the app to the chosen account's\n * webhooks, so its messages reach the connector.\n *\n * Then the host calls `engine.connect(...)` with the phone number id, the\n * display number and the token, which the engine seals. None of these\n * functions logs or returns anything but what is named.\n */\n\ntype Json = Record<string, unknown>;\n\n/** The app's own identity on Meta. The secret is the host's, read where it keeps secrets. */\nexport interface MetaAppCredentials {\n appId: string;\n appSecret: string;\n}\n\n/** Exchange Embedded Signup's code for a business integration token. */\nexport async function exchangeSignupCode(\n graph: GraphConfig,\n input: MetaAppCredentials & { code: string; redirectUri?: string },\n): Promise<{ accessToken: string }> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: \"oauth/access_token\",\n query: {\n client_id: input.appId,\n client_secret: input.appSecret,\n code: input.code,\n ...(input.redirectUri ? { redirect_uri: input.redirectUri } : {}),\n },\n });\n if (typeof json.access_token !== \"string\" || json.access_token.length === 0) {\n throw new GraphError(200, \"NO_ACCESS_TOKEN\", \"Graph answered the code exchange without a token\");\n }\n return { accessToken: json.access_token };\n}\n\n/** One phone number of a WhatsApp Business Account. */\nexport interface SignupPhoneNumber {\n /** The phone_number_id: the connection's external account id. */\n id: string;\n /** What a person reads (`+55 11 98765-4321`): the connection's display address. */\n displayPhoneNumber: string;\n verifiedName: string | null;\n}\n\nexport interface SignupAccount {\n /** The WABA id: the connection's external parent id. */\n wabaId: string;\n phoneNumbers: SignupPhoneNumber[];\n}\n\n/**\n * The WhatsApp Business Accounts the token was granted (read from the token's\n * own granular scopes, with the app's token), and each one's phone numbers.\n */\nexport async function readSignupAccounts(\n graph: GraphConfig,\n input: MetaAppCredentials & { accessToken: string },\n): Promise<SignupAccount[]> {\n const debug = await graphRequest(graph, {\n method: \"GET\",\n path: \"debug_token\",\n query: { input_token: input.accessToken },\n token: `${input.appId}|${input.appSecret}`,\n });\n const data = typeof debug.data === \"object\" && debug.data !== null ? (debug.data as Json) : {};\n const scopes = Array.isArray(data.granular_scopes) ? (data.granular_scopes as Json[]) : [];\n const wabaIds = new Set(\n scopes\n .filter((scope) => scope.scope === \"whatsapp_business_management\" && Array.isArray(scope.target_ids))\n .flatMap((scope) => (scope.target_ids as unknown[]).filter((id): id is string => typeof id === \"string\")),\n );\n const accounts: SignupAccount[] = [];\n for (const wabaId of wabaIds) {\n accounts.push({ wabaId, phoneNumbers: await readPhoneNumbers(graph, wabaId, input.accessToken) });\n }\n return accounts;\n}\n\nasync function readPhoneNumbers(graph: GraphConfig, wabaId: string, accessToken: string): Promise<SignupPhoneNumber[]> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: `${encodeURIComponent(wabaId)}/phone_numbers`,\n query: { fields: \"id,display_phone_number,verified_name\" },\n token: accessToken,\n });\n const rows = Array.isArray(json.data) ? (json.data as Json[]) : [];\n return rows\n .filter((row) => typeof row.id === \"string\" && typeof row.display_phone_number === \"string\")\n .map((row) => ({\n id: row.id as string,\n displayPhoneNumber: row.display_phone_number as string,\n verifiedName: typeof row.verified_name === \"string\" ? row.verified_name : null,\n }));\n}\n\n/** Subscribe the app to a WABA's webhooks. Resolves when Meta answers `success: true`. */\nexport async function subscribeAppToWaba(graph: GraphConfig, input: { wabaId: string; accessToken: string }): Promise<void> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.wabaId)}/subscribed_apps`,\n token: input.accessToken,\n });\n if (json.success !== true) throw new GraphError(200, \"NOT_SUBSCRIBED\", \"Graph did not confirm the subscription\");\n}\n","/**\n * `@12-apps/messaging/whatsapp` — the WhatsApp Cloud API channel adapter.\n *\n * `createWhatsAppAdapter(config)` is what a host hands the engine. The pieces\n * are exported on their own too: the signature check and the receipt parser\n * serve any WhatsApp webhook (a platform notification number), and the\n * Embedded Signup helpers serve the host's connect flow.\n *\n * `@12-apps/notifications` has its own WhatsApp transport, for one-way\n * notification messages. It is deliberately NOT reused here: this adapter\n * carries a conversation (inbound, the service window, opt-out, receipts),\n * which that transport has no model for.\n */\n\nimport { serviceWindowPolicy, type ChannelAdapter } from \"../core/channel\";\nimport { parseWhatsAppPayload } from \"./parse\";\nimport { sendWhatsAppMessage, type GraphConfig } from \"./graph\";\nimport { downloadWhatsAppMedia } from \"./media\";\nimport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription } from \"./signature\";\n\n/** The channel key every WhatsApp row carries. */\nexport const WHATSAPP_CHANNEL = \"whatsapp\";\n\n/** WhatsApp's customer service window: free-form messages only within 24 h of the contact's last message. */\nexport const WHATSAPP_SERVICE_WINDOW_MS = 24 * 60 * 60 * 1000;\n\nexport interface WhatsAppAdapterConfig {\n /** The Meta app's secret: every webhook POST is signed with it. Empty refuses every delivery. */\n appSecret: string;\n /** The token configured on the app's webhook subscription. Empty refuses every handshake. */\n verifyToken: string;\n /** The Graph API: fetch, base URL and version. */\n graph: GraphConfig;\n /** The whole-message words that opt a contact out. Default: PARAR, SAIR, STOP, CANCELAR. */\n optOutKeywords?: readonly string[];\n}\n\n/** The WhatsApp Cloud adapter. */\nexport function createWhatsAppAdapter(config: WhatsAppAdapterConfig): ChannelAdapter {\n return {\n kind: WHATSAPP_CHANNEL,\n handshake: (query) => verifyMetaSubscription(query, config.verifyToken),\n verify: ({ rawBody, header }) => verifyMetaSignature(rawBody, header(META_SIGNATURE_HEADER), config.appSecret),\n parse: (rawBody) =>\n parseWhatsAppPayload(JSON.parse(rawBody) as unknown, {\n ...(config.optOutKeywords ? { optOutKeywords: config.optOutKeywords } : {}),\n }),\n send: ({ credential, accountId, to, content }) =>\n sendWhatsAppMessage(config.graph, { token: credential, phoneNumberId: accountId, to, content }),\n fetchMedia: ({ credential, mediaId, maxBytes, timeoutMs }) =>\n downloadWhatsAppMedia(config.graph, { token: credential, mediaId, maxBytes, ...(timeoutMs !== undefined ? { timeoutMs } : {}) }),\n policy: serviceWindowPolicy(WHATSAPP_SERVICE_WINDOW_MS),\n };\n}\n\nexport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription, type MetaHandshake } from \"./signature\";\nexport { parseWhatsAppPayload, parseWhatsAppStatuses } from \"./parse\";\nexport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\nexport {\n DEFAULT_META_MEDIA_HOSTS,\n GraphError,\n graphRequest,\n messageBody,\n sendWhatsAppMessage,\n type FetchBodyReader,\n type FetchInit,\n type FetchPort,\n type FetchResponse,\n type GraphConfig,\n} from \"./graph\";\nexport { downloadWhatsAppMedia } from \"./media\";\nexport {\n exchangeSignupCode,\n readSignupAccounts,\n subscribeAppToWaba,\n type MetaAppCredentials,\n type SignupAccount,\n type SignupPhoneNumber,\n} from \"./signup\";\n"],"mappings":";;;;;;;;;;;;AAKO,IAAM,2BAA8C,CAAC,SAAS,QAAQ,QAAQ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|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"description": "A channel-agnostic conversational messaging connector: channel connections with sealed credentials, a durable inbox of raw webhook deliveries, conversations with an owner state and a structured summary, messages with delivery statuses, an opt-out, a per-channel send policy and a text-retention sweep, behind a channel adapter port. WhatsApp Cloud is the first adapter (./whatsapp), with its signature check, payload parser, Graph sender and Embedded Signup helpers. Framework-neutral webhook routes (./server), dep-free job blueprints and the package-owned Prisma partial + migrations.",
|
package/src/core/channel.ts
CHANGED
|
@@ -44,6 +44,16 @@ export interface ChannelAdapter {
|
|
|
44
44
|
*/
|
|
45
45
|
send(input: ChannelSendInput): Promise<{ externalId: string }>;
|
|
46
46
|
|
|
47
|
+
/**
|
|
48
|
+
* Download one inbound message's media (a voice note) by the channel's media
|
|
49
|
+
* id, into memory. OPTIONAL: a channel with no media leaves it out, and the
|
|
50
|
+
* engine refuses a download through it (`UNSUPPORTED`). Throws
|
|
51
|
+
* {@link ChannelMediaFailure} when the channel refuses, or when the media is
|
|
52
|
+
* larger than `maxBytes` — declared OR actual — or past its deadline (`TIMEOUT`). The same rule as `send`: the
|
|
53
|
+
* opened credential is never logged, put in an error, or returned.
|
|
54
|
+
*/
|
|
55
|
+
fetchMedia?(input: ChannelMediaInput): Promise<ChannelMedia>;
|
|
56
|
+
|
|
47
57
|
/** When this channel lets the tenant send free-form messages. */
|
|
48
58
|
readonly policy: SendPolicy;
|
|
49
59
|
}
|
|
@@ -60,6 +70,54 @@ export interface ChannelSendInput {
|
|
|
60
70
|
content: OutboundContent;
|
|
61
71
|
}
|
|
62
72
|
|
|
73
|
+
export interface ChannelMediaInput {
|
|
74
|
+
/** The opened credential of the connection the message arrived through. */
|
|
75
|
+
credential: string;
|
|
76
|
+
/** The connection's account on the channel (WhatsApp's phone_number_id). */
|
|
77
|
+
accountId: string;
|
|
78
|
+
/** The channel's id for the media, as the inbound message carried it. */
|
|
79
|
+
mediaId: string;
|
|
80
|
+
/** The most bytes the caller accepts. Larger media is refused, never truncated. */
|
|
81
|
+
maxBytes: number;
|
|
82
|
+
/**
|
|
83
|
+
* The deadline for the whole download, lookup and body included; past it the
|
|
84
|
+
* calls are aborted and the download fails `TIMEOUT`. Default
|
|
85
|
+
* {@link DEFAULT_MEDIA_TIMEOUT_MS}.
|
|
86
|
+
*/
|
|
87
|
+
timeoutMs?: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The default deadline of one media download: 30 s. */
|
|
91
|
+
export const DEFAULT_MEDIA_TIMEOUT_MS = 30_000;
|
|
92
|
+
|
|
93
|
+
/** Is `value` a usable byte cap or deadline: a positive safe integer (never NaN, Infinity or 0). */
|
|
94
|
+
export function isPositiveSafeInteger(value: unknown): value is number {
|
|
95
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Downloaded media: in memory only. The package never stores it. */
|
|
99
|
+
export interface ChannelMedia {
|
|
100
|
+
bytes: Uint8Array;
|
|
101
|
+
/** The channel's MIME type for it (`audio/ogg; codecs=opus`), or `application/octet-stream`. */
|
|
102
|
+
mimeType: string;
|
|
103
|
+
/** `bytes.length`. */
|
|
104
|
+
size: number;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* A media download the channel refused, or the adapter refused to finish.
|
|
109
|
+
* `TOO_LARGE` is the size cap, declared or actual; every other code is the
|
|
110
|
+
* adapter's or the channel's. Never carries the credential.
|
|
111
|
+
*/
|
|
112
|
+
export class ChannelMediaFailure extends Error {
|
|
113
|
+
readonly code: string;
|
|
114
|
+
constructor(code: string, message: string) {
|
|
115
|
+
super(message);
|
|
116
|
+
this.name = "ChannelMediaFailure";
|
|
117
|
+
this.code = code;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
63
121
|
/** A channel refused or failed a send. `code` is the channel's own, as text. */
|
|
64
122
|
export class ChannelSendFailure extends Error {
|
|
65
123
|
readonly code: string;
|
package/src/core/engine.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { connect, markError, revoke, type ConnectInput } from "./connections";
|
|
2
2
|
import { engineContext } from "./context";
|
|
3
3
|
import { processDelivery, receiveDelivery, reconcileInbox } from "./inbox";
|
|
4
|
+
import { downloadMedia, type DownloadMediaOptions } from "./media";
|
|
4
5
|
import type { MessagingEngineConfig } from "./ports";
|
|
5
6
|
import { sweepRetention } from "./retention";
|
|
6
7
|
import { sendMessage, type SendInput } from "./sender";
|
|
@@ -32,6 +33,14 @@ export function createMessagingEngine(config: MessagingEngineConfig) {
|
|
|
32
33
|
// ── Sending ──────────────────────────────────────────────────────────────
|
|
33
34
|
send: (input: SendInput) => sendMessage(ctx, input),
|
|
34
35
|
|
|
36
|
+
// ── Media ────────────────────────────────────────────────────────────────
|
|
37
|
+
/**
|
|
38
|
+
* Download an inbound audio message's media into memory (`{ bytes, mimeType, size }`),
|
|
39
|
+
* through its connection. Nothing is stored; throws `MessagingMediaError`.
|
|
40
|
+
*/
|
|
41
|
+
downloadMedia: (tenantId: string, messageId: string, options?: DownloadMediaOptions) =>
|
|
42
|
+
downloadMedia(ctx, tenantId, messageId, options),
|
|
43
|
+
|
|
35
44
|
// ── Connections ──────────────────────────────────────────────────────────
|
|
36
45
|
connect: (input: ConnectInput) => connect(ctx, input),
|
|
37
46
|
revoke: (tenantId: string, connectionId: string, reason?: string | null) => revoke(ctx, tenantId, connectionId, reason),
|