@12-apps/messaging 0.0.0-stage → 1.1.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/ADOPTING.md +119 -0
- package/README.md +157 -2
- package/dist/channel-Cs_vLGl_.d.ts +293 -0
- package/dist/chunk-72TDAQUW.js +136 -0
- package/dist/chunk-72TDAQUW.js.map +1 -0
- package/dist/chunk-7QVYU63E.js +7 -0
- package/dist/chunk-7QVYU63E.js.map +1 -0
- package/dist/chunk-R3DKM2IV.js +42 -0
- package/dist/chunk-R3DKM2IV.js.map +1 -0
- package/dist/chunk-Y7MG2UDQ.js +36 -0
- package/dist/chunk-Y7MG2UDQ.js.map +1 -0
- package/dist/engine-DTnp2zUL.d.ts +431 -0
- package/dist/index.d.ts +97 -0
- package/dist/index.js +999 -0
- package/dist/index.js.map +1 -0
- package/dist/manifest/index.d.ts +36 -0
- package/dist/manifest/index.js +14 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/manifest/server.d.ts +21 -0
- package/dist/manifest/server.js +17 -0
- package/dist/manifest/server.js.map +1 -0
- package/dist/server/index.d.ts +78 -0
- package/dist/server/index.js +15 -0
- package/dist/server/index.js.map +1 -0
- package/dist/whatsapp/index.d.ts +180 -0
- package/dist/whatsapp/index.js +385 -0
- package/dist/whatsapp/index.js.map +1 -0
- package/package.json +90 -4
- package/prisma/messaging.prisma +140 -0
- package/prisma/migrations/20261114120000_messaging_connector/migration.sql +110 -0
- package/src/core/channel.ts +106 -0
- package/src/core/connections.ts +67 -0
- package/src/core/context.ts +28 -0
- package/src/core/engine.ts +64 -0
- package/src/core/errors.ts +53 -0
- package/src/core/hash.ts +6 -0
- package/src/core/inbound.ts +240 -0
- package/src/core/inbox.ts +139 -0
- package/src/core/memory-store.ts +273 -0
- package/src/core/ports.ts +129 -0
- package/src/core/prisma-store.ts +354 -0
- package/src/core/retention.ts +27 -0
- package/src/core/sender.ts +106 -0
- package/src/core/store.ts +217 -0
- package/src/core/types.ts +189 -0
- package/src/index.ts +54 -0
- package/src/manifest/index.ts +32 -0
- package/src/manifest/server.ts +18 -0
- package/src/server/index.ts +22 -0
- package/src/server/jobs.ts +99 -0
- package/src/server/webhook.ts +92 -0
- package/src/whatsapp/graph.ts +136 -0
- package/src/whatsapp/index.ts +64 -0
- package/src/whatsapp/opt-out.ts +26 -0
- package/src/whatsapp/parse.ts +200 -0
- package/src/whatsapp/signature.ts +52 -0
- package/src/whatsapp/signup.ts +115 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { WireRawResponse, WireRequest, WireResponse, WireRoute, WireRouteAnswer } from "@12-apps/wiring";
|
|
2
|
+
|
|
3
|
+
import type { MessagingEngine } from "../core/engine";
|
|
4
|
+
import { errorText } from "../core/errors";
|
|
5
|
+
import type { MessagingLogger } from "../core/ports";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The webhook routes, one pair per channel the engine serves:
|
|
9
|
+
*
|
|
10
|
+
* - `GET /webhooks/messaging/:channel` — the channel's subscription handshake;
|
|
11
|
+
* - `POST /webhooks/messaging/:channel` — a delivery.
|
|
12
|
+
*
|
|
13
|
+
* ONE URL per channel, not per tenant: a channel like WhatsApp delivers every
|
|
14
|
+
* connected account's events to the single callback configured on the app, so
|
|
15
|
+
* the tenant cannot come from the path. It is resolved later, in the job, from
|
|
16
|
+
* the event's own account id against the connections — and an account nobody
|
|
17
|
+
* connected resolves to nobody.
|
|
18
|
+
*
|
|
19
|
+
* The POST, in order: refuse an unknown channel (404); verify the signature
|
|
20
|
+
* over the RAW bytes, and on a bad one answer 401 and STORE NOTHING (fail
|
|
21
|
+
* closed); persist the raw body; answer 200; the job processes it. Nothing is
|
|
22
|
+
* parsed or resolved before the row exists. A store failure answers 500 so the
|
|
23
|
+
* channel redelivers. Bodies are machine codes: the reader is a server.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export interface MessagingApiConfig {
|
|
27
|
+
/** The mounted engine (`createMessagingEngine`). */
|
|
28
|
+
engine: Pick<MessagingEngine, "adapter" | "receive">;
|
|
29
|
+
/** The manifest's `messaging` namespace. */
|
|
30
|
+
logger: MessagingLogger;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const refuse = (status: number, error: string): WireResponse => ({ status, body: { error } });
|
|
34
|
+
|
|
35
|
+
function handshake(config: MessagingApiConfig, request: WireRequest<unknown>): WireRouteAnswer {
|
|
36
|
+
const channel = request.params.channel ?? "";
|
|
37
|
+
const adapter = config.engine.adapter(channel);
|
|
38
|
+
if (!adapter) return refuse(404, "unknown_channel");
|
|
39
|
+
const answer = adapter.handshake(request.query);
|
|
40
|
+
if (!answer) return refuse(404, "no_handshake");
|
|
41
|
+
if (!answer.ok) {
|
|
42
|
+
config.logger.warn(`messaging.webhook: ${channel} handshake refused`);
|
|
43
|
+
return refuse(403, "forbidden");
|
|
44
|
+
}
|
|
45
|
+
// The challenge is echoed as the bare body, which a JSON envelope would break.
|
|
46
|
+
const raw: WireRawResponse = {
|
|
47
|
+
response: new Response(answer.challenge, { status: 200, headers: { "content-type": "text/plain; charset=utf-8" } }),
|
|
48
|
+
};
|
|
49
|
+
return raw;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function deliver(config: MessagingApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {
|
|
53
|
+
const channel = request.params.channel ?? "";
|
|
54
|
+
const adapter = config.engine.adapter(channel);
|
|
55
|
+
if (!adapter) return refuse(404, "unknown_channel");
|
|
56
|
+
const raw = request.request;
|
|
57
|
+
if (!raw) return refuse(400, "raw_request_required");
|
|
58
|
+
|
|
59
|
+
// The signature is over the bytes as received, so it is checked on the bytes;
|
|
60
|
+
// only then are they decoded (the body size limit is the host framework's).
|
|
61
|
+
const rawBytes = new Uint8Array(await raw.arrayBuffer());
|
|
62
|
+
if (!adapter.verify({ rawBody: rawBytes, header: (name) => raw.headers.get(name) })) {
|
|
63
|
+
config.logger.warn(`messaging.webhook: ${channel} signature rejected`);
|
|
64
|
+
return refuse(401, "unauthorized");
|
|
65
|
+
}
|
|
66
|
+
const rawBody = new TextDecoder().decode(rawBytes);
|
|
67
|
+
try {
|
|
68
|
+
const { fresh } = await config.engine.receive(channel, rawBody);
|
|
69
|
+
return { status: 200, body: { received: true, duplicate: !fresh } };
|
|
70
|
+
} catch (error) {
|
|
71
|
+
config.logger.error(`messaging.webhook: ${channel} delivery not stored: ${errorText(error)}`);
|
|
72
|
+
return refuse(500, "not_stored");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The two webhook descriptors. Public by design (`kind: "webhook"`): a channel cannot sign in. */
|
|
77
|
+
export function webhookRoutes(config: MessagingApiConfig): WireRoute<unknown, WireRouteAnswer>[] {
|
|
78
|
+
return [
|
|
79
|
+
{
|
|
80
|
+
method: "GET",
|
|
81
|
+
path: "/webhooks/messaging/:channel",
|
|
82
|
+
kind: "webhook",
|
|
83
|
+
handle: async (request) => handshake(config, request),
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
method: "POST",
|
|
87
|
+
path: "/webhooks/messaging/:channel",
|
|
88
|
+
kind: "webhook",
|
|
89
|
+
handle: (request) => deliver(config, request),
|
|
90
|
+
},
|
|
91
|
+
];
|
|
92
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { ChannelSendFailure } from "../core/channel";
|
|
2
|
+
import type { OutboundContent } from "../core/types";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The only way the adapter reaches Meta: an injected fetch. The global
|
|
6
|
+
* `fetch` satisfies it; a test answers it with a recording fake.
|
|
7
|
+
*/
|
|
8
|
+
export type FetchPort = (
|
|
9
|
+
url: string,
|
|
10
|
+
init: { method: string; headers: Record<string, string>; body?: string },
|
|
11
|
+
) => Promise<{ status: number; text(): Promise<string> }>;
|
|
12
|
+
|
|
13
|
+
/** Where the Graph API is, and through what. Both numbers are config, never constants in the adapter. */
|
|
14
|
+
export interface GraphConfig {
|
|
15
|
+
fetch: FetchPort;
|
|
16
|
+
/** `https://graph.facebook.com` — no trailing slash needed. */
|
|
17
|
+
baseUrl: string;
|
|
18
|
+
/** `v23.0` — the Graph API version every call is pinned to. */
|
|
19
|
+
apiVersion: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A Graph call that did not answer 2xx. Carries Meta's error code; never the token. */
|
|
23
|
+
export class GraphError extends ChannelSendFailure {
|
|
24
|
+
readonly status: number;
|
|
25
|
+
constructor(status: number, code: string, message: string) {
|
|
26
|
+
super(code, message);
|
|
27
|
+
this.name = "GraphError";
|
|
28
|
+
this.status = status;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type Json = Record<string, unknown>;
|
|
33
|
+
|
|
34
|
+
interface GraphCall {
|
|
35
|
+
method: "GET" | "POST";
|
|
36
|
+
path: string;
|
|
37
|
+
token?: string;
|
|
38
|
+
query?: Record<string, string>;
|
|
39
|
+
body?: unknown;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Drops trailing "/" characters in one linear pass (a regex here backtracks quadratically on library input). */
|
|
43
|
+
function trimTrailingSlashes(value: string): string {
|
|
44
|
+
let end = value.length;
|
|
45
|
+
while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
|
|
46
|
+
return end === value.length ? value : value.slice(0, end);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The URL and the request init of one call. The token travels in a header, never in the URL. */
|
|
50
|
+
function requestOf(graph: GraphConfig, call: GraphCall) {
|
|
51
|
+
const base = trimTrailingSlashes(graph.baseUrl);
|
|
52
|
+
const query = call.query ? `?${new URLSearchParams(call.query).toString()}` : "";
|
|
53
|
+
const headers: Record<string, string> = { accept: "application/json" };
|
|
54
|
+
if (call.token) headers.authorization = `Bearer ${call.token}`;
|
|
55
|
+
if (call.body !== undefined) headers["content-type"] = "application/json";
|
|
56
|
+
return {
|
|
57
|
+
url: `${base}/${graph.apiVersion}/${call.path}${query}`,
|
|
58
|
+
init: { method: call.method, headers, ...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}) },
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A body as a JSON object; anything else (empty, HTML, an array) as `{}`. */
|
|
63
|
+
function objectOf(raw: string): Json {
|
|
64
|
+
try {
|
|
65
|
+
const parsed: unknown = raw ? JSON.parse(raw) : {};
|
|
66
|
+
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? (parsed as Json) : {};
|
|
67
|
+
} catch {
|
|
68
|
+
return {};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Meta's error envelope (`{ error: { code, message } }`) as a {@link GraphError}. */
|
|
73
|
+
function graphErrorOf(status: number, json: Json): GraphError {
|
|
74
|
+
const error = typeof json.error === "object" && json.error !== null ? (json.error as Json) : {};
|
|
75
|
+
const code = error.code === undefined ? `HTTP_${status}` : String(error.code);
|
|
76
|
+
const message = typeof error.message === "string" ? error.message : `Graph answered ${status}`;
|
|
77
|
+
return new GraphError(status, code, message.slice(0, 300));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** One Graph call; resolves to the parsed JSON body, or throws {@link GraphError}. */
|
|
81
|
+
export async function graphRequest(graph: GraphConfig, call: GraphCall): Promise<Json> {
|
|
82
|
+
const { url, init } = requestOf(graph, call);
|
|
83
|
+
const response = await graph.fetch(url, init);
|
|
84
|
+
const json = objectOf(await response.text());
|
|
85
|
+
if (response.status < 200 || response.status >= 300) throw graphErrorOf(response.status, json);
|
|
86
|
+
return json;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The Cloud API body for one outbound message. */
|
|
90
|
+
export function messageBody(to: string, content: OutboundContent): Json {
|
|
91
|
+
const base = { messaging_product: "whatsapp", recipient_type: "individual", to };
|
|
92
|
+
if (content.kind === "TEXT") return { ...base, type: "text", text: { body: content.text, preview_url: false } };
|
|
93
|
+
if (content.kind === "BUTTONS") {
|
|
94
|
+
return {
|
|
95
|
+
...base,
|
|
96
|
+
type: "interactive",
|
|
97
|
+
interactive: {
|
|
98
|
+
type: "button",
|
|
99
|
+
body: { text: content.text },
|
|
100
|
+
action: { buttons: content.buttons.map((button) => ({ type: "reply", reply: { id: button.id, title: button.title } })) },
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
...base,
|
|
106
|
+
type: "interactive",
|
|
107
|
+
interactive: {
|
|
108
|
+
type: "list",
|
|
109
|
+
body: { text: content.text },
|
|
110
|
+
action: {
|
|
111
|
+
button: content.buttonLabel,
|
|
112
|
+
sections: content.sections.map((section) => ({
|
|
113
|
+
...(section.title ? { title: section.title } : {}),
|
|
114
|
+
rows: section.rows.map((row) => ({ id: row.id, title: row.title, ...(row.description ? { description: row.description } : {}) })),
|
|
115
|
+
})),
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Send one message from a phone number; resolves to its wamid. */
|
|
122
|
+
export async function sendWhatsAppMessage(
|
|
123
|
+
graph: GraphConfig,
|
|
124
|
+
input: { token: string; phoneNumberId: string; to: string; content: OutboundContent },
|
|
125
|
+
): Promise<{ externalId: string }> {
|
|
126
|
+
const json = await graphRequest(graph, {
|
|
127
|
+
method: "POST",
|
|
128
|
+
path: `${encodeURIComponent(input.phoneNumberId)}/messages`,
|
|
129
|
+
token: input.token,
|
|
130
|
+
body: messageBody(input.to, input.content),
|
|
131
|
+
});
|
|
132
|
+
const [first] = Array.isArray(json.messages) ? (json.messages as Json[]) : [];
|
|
133
|
+
const id = first && typeof first.id === "string" ? first.id : null;
|
|
134
|
+
if (!id) throw new GraphError(200, "NO_MESSAGE_ID", "Graph accepted the message but returned no id");
|
|
135
|
+
return { externalId: id };
|
|
136
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/messaging/whatsapp` — the WhatsApp Cloud API channel adapter.
|
|
3
|
+
*
|
|
4
|
+
* `createWhatsAppAdapter(config)` is what a host hands the engine. The pieces
|
|
5
|
+
* are exported on their own too: the signature check and the receipt parser
|
|
6
|
+
* serve any WhatsApp webhook (a platform notification number), and the
|
|
7
|
+
* Embedded Signup helpers serve the host's connect flow.
|
|
8
|
+
*
|
|
9
|
+
* `@12-apps/notifications` has its own WhatsApp transport, for one-way
|
|
10
|
+
* notification messages. It is deliberately NOT reused here: this adapter
|
|
11
|
+
* carries a conversation (inbound, the service window, opt-out, receipts),
|
|
12
|
+
* which that transport has no model for.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { serviceWindowPolicy, type ChannelAdapter } from "../core/channel";
|
|
16
|
+
import { parseWhatsAppPayload } from "./parse";
|
|
17
|
+
import { sendWhatsAppMessage, type GraphConfig } from "./graph";
|
|
18
|
+
import { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription } from "./signature";
|
|
19
|
+
|
|
20
|
+
/** The channel key every WhatsApp row carries. */
|
|
21
|
+
export const WHATSAPP_CHANNEL = "whatsapp";
|
|
22
|
+
|
|
23
|
+
/** WhatsApp's customer service window: free-form messages only within 24 h of the contact's last message. */
|
|
24
|
+
export const WHATSAPP_SERVICE_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
25
|
+
|
|
26
|
+
export interface WhatsAppAdapterConfig {
|
|
27
|
+
/** The Meta app's secret: every webhook POST is signed with it. Empty refuses every delivery. */
|
|
28
|
+
appSecret: string;
|
|
29
|
+
/** The token configured on the app's webhook subscription. Empty refuses every handshake. */
|
|
30
|
+
verifyToken: string;
|
|
31
|
+
/** The Graph API: fetch, base URL and version. */
|
|
32
|
+
graph: GraphConfig;
|
|
33
|
+
/** The whole-message words that opt a contact out. Default: PARAR, SAIR, STOP, CANCELAR. */
|
|
34
|
+
optOutKeywords?: readonly string[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The WhatsApp Cloud adapter. */
|
|
38
|
+
export function createWhatsAppAdapter(config: WhatsAppAdapterConfig): ChannelAdapter {
|
|
39
|
+
return {
|
|
40
|
+
kind: WHATSAPP_CHANNEL,
|
|
41
|
+
handshake: (query) => verifyMetaSubscription(query, config.verifyToken),
|
|
42
|
+
verify: ({ rawBody, header }) => verifyMetaSignature(rawBody, header(META_SIGNATURE_HEADER), config.appSecret),
|
|
43
|
+
parse: (rawBody) =>
|
|
44
|
+
parseWhatsAppPayload(JSON.parse(rawBody) as unknown, {
|
|
45
|
+
...(config.optOutKeywords ? { optOutKeywords: config.optOutKeywords } : {}),
|
|
46
|
+
}),
|
|
47
|
+
send: ({ credential, accountId, to, content }) =>
|
|
48
|
+
sendWhatsAppMessage(config.graph, { token: credential, phoneNumberId: accountId, to, content }),
|
|
49
|
+
policy: serviceWindowPolicy(WHATSAPP_SERVICE_WINDOW_MS),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription, type MetaHandshake } from "./signature";
|
|
54
|
+
export { parseWhatsAppPayload, parseWhatsAppStatuses } from "./parse";
|
|
55
|
+
export { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from "./opt-out";
|
|
56
|
+
export { GraphError, graphRequest, messageBody, sendWhatsAppMessage, type FetchPort, type GraphConfig } from "./graph";
|
|
57
|
+
export {
|
|
58
|
+
exchangeSignupCode,
|
|
59
|
+
readSignupAccounts,
|
|
60
|
+
subscribeAppToWaba,
|
|
61
|
+
type MetaAppCredentials,
|
|
62
|
+
type SignupAccount,
|
|
63
|
+
type SignupPhoneNumber,
|
|
64
|
+
} from "./signup";
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The words that opt a contact out, by default: the Portuguese and English
|
|
3
|
+
* stop words a WhatsApp user is told to send. A host replaces the list through
|
|
4
|
+
* the adapter's config.
|
|
5
|
+
*/
|
|
6
|
+
export const DEFAULT_OPT_OUT_KEYWORDS: readonly string[] = ["PARAR", "SAIR", "STOP", "CANCELAR"];
|
|
7
|
+
|
|
8
|
+
/** Upper case, accents stripped, surrounding space, punctuation and emoji trimmed. */
|
|
9
|
+
function fold(text: string): string {
|
|
10
|
+
return text
|
|
11
|
+
.normalize("NFD")
|
|
12
|
+
.replace(/\p{M}/gu, "")
|
|
13
|
+
.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "")
|
|
14
|
+
.toUpperCase();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Is this text an opt-out? Only when the WHOLE message is one keyword —
|
|
19
|
+
* case- and accent-insensitive, ignoring punctuation and emoji around it — so
|
|
20
|
+
* "parar", "PARAR." and "Parar!" opt out, and "parar de enviar" (a sentence,
|
|
21
|
+
* maybe about something else) does not.
|
|
22
|
+
*/
|
|
23
|
+
export function isOptOutText(text: string, keywords: readonly string[] = DEFAULT_OPT_OUT_KEYWORDS): boolean {
|
|
24
|
+
const folded = fold(text);
|
|
25
|
+
return folded.length > 0 && keywords.some((keyword) => fold(keyword) === folded);
|
|
26
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
InboundContent,
|
|
3
|
+
InboundMessageEvent,
|
|
4
|
+
NormalizedEvent,
|
|
5
|
+
OptOutEvent,
|
|
6
|
+
ReceiptStatus,
|
|
7
|
+
StatusEvent,
|
|
8
|
+
} from "../core/types";
|
|
9
|
+
import { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from "./opt-out";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The WhatsApp Cloud API webhook payload, read defensively: every field is
|
|
13
|
+
* checked before it is trusted, an unknown shape is skipped rather than
|
|
14
|
+
* thrown on, and only `JSON.parse` itself may throw (bytes that are not JSON).
|
|
15
|
+
*
|
|
16
|
+
* Shape: `{ object: "whatsapp_business_account", entry: [{ id, changes: [{
|
|
17
|
+
* field, value: { metadata: { phone_number_id }, contacts, messages,
|
|
18
|
+
* statuses, user_preferences } }] }] }`. Events come out in payload order.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
type Json = Record<string, unknown>;
|
|
22
|
+
|
|
23
|
+
const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
|
+
const list = (value: unknown): Json[] => (Array.isArray(value) ? value.filter(isObject) : []);
|
|
25
|
+
const text = (value: unknown): string | null => (typeof value === "string" && value.length > 0 ? value : null);
|
|
26
|
+
|
|
27
|
+
/** Meta's timestamps are Unix SECONDS, as a string. Null when absent or malformed. */
|
|
28
|
+
function when(value: unknown): Date | null {
|
|
29
|
+
const seconds = typeof value === "string" || typeof value === "number" ? Number(value) : Number.NaN;
|
|
30
|
+
return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000) : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface Change {
|
|
34
|
+
value: Json;
|
|
35
|
+
accountId: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Every `value` of every change, with the account it was delivered to. */
|
|
39
|
+
function changes(payload: unknown): Change[] {
|
|
40
|
+
if (!isObject(payload) || payload.object !== "whatsapp_business_account") return [];
|
|
41
|
+
return list(payload.entry)
|
|
42
|
+
.flatMap((entry) => list(entry.changes))
|
|
43
|
+
.flatMap((change): Change[] => {
|
|
44
|
+
const value = change.value;
|
|
45
|
+
const accountId = isObject(value) && isObject(value.metadata) ? text(value.metadata.phone_number_id) : null;
|
|
46
|
+
return isObject(value) && accountId ? [{ value, accountId }] : [];
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One reader per message `type`; null when the type's object is missing or malformed. */
|
|
51
|
+
const CONTENT_READERS: Readonly<Record<string, (message: Json) => InboundContent | null>> = {
|
|
52
|
+
text: (message) => {
|
|
53
|
+
const body = isObject(message.text) ? text(message.text.body) : null;
|
|
54
|
+
return body ? { kind: "TEXT", text: body } : null;
|
|
55
|
+
},
|
|
56
|
+
interactive: (message) => {
|
|
57
|
+
const interactive = isObject(message.interactive) ? message.interactive : {};
|
|
58
|
+
const reply = interactive.button_reply ?? interactive.list_reply;
|
|
59
|
+
const id = isObject(reply) ? text(reply.id) : null;
|
|
60
|
+
return isObject(reply) && id ? { kind: "INTERACTIVE", replyId: id, title: text(reply.title) ?? "" } : null;
|
|
61
|
+
},
|
|
62
|
+
// A quick-reply button on a template message.
|
|
63
|
+
button: (message) => {
|
|
64
|
+
if (!isObject(message.button)) return null;
|
|
65
|
+
const title = text(message.button.text) ?? "";
|
|
66
|
+
return { kind: "INTERACTIVE", replyId: text(message.button.payload) ?? title, title };
|
|
67
|
+
},
|
|
68
|
+
audio: (message) => {
|
|
69
|
+
const id = isObject(message.audio) ? text(message.audio.id) : null;
|
|
70
|
+
return isObject(message.audio) && id ? { kind: "AUDIO", mediaId: id, mimeType: text(message.audio.mime_type) } : null;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/** The content of one message, by its `type`; anything unread is OTHER. */
|
|
75
|
+
function contentOf(message: Json): InboundContent {
|
|
76
|
+
const type = text(message.type) ?? "unknown";
|
|
77
|
+
return CONTENT_READERS[type]?.(message) ?? { kind: "OTHER", channelType: type };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The words a person typed or tapped, for the opt-out check. */
|
|
81
|
+
function wordsOf(content: InboundContent): string | null {
|
|
82
|
+
if (content.kind === "TEXT") return content.text;
|
|
83
|
+
if (content.kind === "INTERACTIVE") return content.title;
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The profile name Meta sends per sender, keyed by wa_id. */
|
|
88
|
+
function contactNames(value: Json): Map<string, string> {
|
|
89
|
+
const names = new Map<string, string>();
|
|
90
|
+
for (const contact of list(value.contacts)) {
|
|
91
|
+
const waId = text(contact.wa_id);
|
|
92
|
+
const name = isObject(contact.profile) ? text(contact.profile.name) : null;
|
|
93
|
+
if (waId && name) names.set(waId, name);
|
|
94
|
+
}
|
|
95
|
+
return names;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function messageEvent(
|
|
99
|
+
message: Json,
|
|
100
|
+
accountId: string,
|
|
101
|
+
names: Map<string, string>,
|
|
102
|
+
keywords: readonly string[],
|
|
103
|
+
): InboundMessageEvent | null {
|
|
104
|
+
const contactId = text(message.from);
|
|
105
|
+
const externalId = text(message.id);
|
|
106
|
+
const sentAt = when(message.timestamp);
|
|
107
|
+
if (!contactId || !externalId || !sentAt) return null;
|
|
108
|
+
const content = contentOf(message);
|
|
109
|
+
const words = wordsOf(content);
|
|
110
|
+
return {
|
|
111
|
+
type: "message",
|
|
112
|
+
accountId,
|
|
113
|
+
contactId,
|
|
114
|
+
contactName: names.get(contactId) ?? null,
|
|
115
|
+
externalId,
|
|
116
|
+
sentAt,
|
|
117
|
+
content,
|
|
118
|
+
optOut: words !== null && isOptOutText(words, keywords),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function messageEvents(value: Json, accountId: string, keywords: readonly string[]): InboundMessageEvent[] {
|
|
123
|
+
const names = contactNames(value);
|
|
124
|
+
return list(value.messages).flatMap((message) => messageEvent(message, accountId, names, keywords) ?? []);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const RECEIPTS: Readonly<Record<string, ReceiptStatus>> = {
|
|
128
|
+
sent: "SENT",
|
|
129
|
+
delivered: "DELIVERED",
|
|
130
|
+
read: "READ",
|
|
131
|
+
failed: "FAILED",
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
/** The first error of a failed status, as `code: title`. */
|
|
135
|
+
function errorOf(status: Json): string | null {
|
|
136
|
+
const [first] = list(status.errors);
|
|
137
|
+
if (!first) return null;
|
|
138
|
+
const code = first.code === undefined ? "" : String(first.code);
|
|
139
|
+
const title = text(first.title) ?? text(first.message) ?? "";
|
|
140
|
+
return [code, title].filter(Boolean).join(": ") || null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function statusEvents(value: Json, accountId: string): StatusEvent[] {
|
|
144
|
+
const out: StatusEvent[] = [];
|
|
145
|
+
for (const status of list(value.statuses)) {
|
|
146
|
+
const externalId = text(status.id);
|
|
147
|
+
const receipt = RECEIPTS[text(status.status) ?? ""];
|
|
148
|
+
const at = when(status.timestamp);
|
|
149
|
+
if (!externalId || !receipt || !at) continue;
|
|
150
|
+
out.push({
|
|
151
|
+
type: "status",
|
|
152
|
+
accountId,
|
|
153
|
+
externalId,
|
|
154
|
+
status: receipt,
|
|
155
|
+
at,
|
|
156
|
+
contactId: text(status.recipient_id),
|
|
157
|
+
error: receipt === "FAILED" ? errorOf(status) : null,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Meta's own opt-out: a `user_preferences` change whose value is `stop`. */
|
|
164
|
+
function preferenceEvents(value: Json, accountId: string): OptOutEvent[] {
|
|
165
|
+
const out: OptOutEvent[] = [];
|
|
166
|
+
for (const preference of list(value.user_preferences)) {
|
|
167
|
+
const contactId = text(preference.wa_id);
|
|
168
|
+
const at = when(preference.timestamp);
|
|
169
|
+
if (contactId && at && text(preference.value)?.toLowerCase() === "stop") {
|
|
170
|
+
out.push({ type: "opt_out", accountId, contactId, at });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Every event in a WhatsApp webhook payload (already `JSON.parse`d): inbound
|
|
178
|
+
* messages (with the opt-out keyword check), delivery receipts, and Meta's
|
|
179
|
+
* own opt-out signal.
|
|
180
|
+
*/
|
|
181
|
+
export function parseWhatsAppPayload(
|
|
182
|
+
payload: unknown,
|
|
183
|
+
options: { optOutKeywords?: readonly string[] } = {},
|
|
184
|
+
): NormalizedEvent[] {
|
|
185
|
+
const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;
|
|
186
|
+
const out: NormalizedEvent[] = [];
|
|
187
|
+
for (const { value, accountId } of changes(payload)) {
|
|
188
|
+
out.push(...messageEvents(value, accountId, keywords), ...statusEvents(value, accountId), ...preferenceEvents(value, accountId));
|
|
189
|
+
}
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Only the delivery receipts of a WhatsApp webhook payload — for a host that
|
|
195
|
+
* tracks receipts of messages it sends some other way (a platform
|
|
196
|
+
* notification number) without mounting the connector.
|
|
197
|
+
*/
|
|
198
|
+
export function parseWhatsAppStatuses(payload: unknown): StatusEvent[] {
|
|
199
|
+
return changes(payload).flatMap(({ value, accountId }) => statusEvents(value, accountId));
|
|
200
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Meta's webhook proofs, as standalone functions: the connector's WhatsApp
|
|
5
|
+
* adapter uses them, and so can any other WhatsApp webhook a host runs (a
|
|
6
|
+
* platform notification number's receipts), without mounting the connector.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** The header Meta signs every webhook POST with. */
|
|
10
|
+
export const META_SIGNATURE_HEADER = "x-hub-signature-256";
|
|
11
|
+
|
|
12
|
+
const SIGNATURE = /^sha256=([0-9a-f]{64})$/i;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Does `signatureHeader` prove `rawBody` was signed with `appSecret`?
|
|
16
|
+
*
|
|
17
|
+
* HMAC-SHA256 over the RAW body bytes exactly as received (a re-serialized
|
|
18
|
+
* JSON body never matches; hand the bytes, not a decoded string, where the
|
|
19
|
+
* framework gives them), compared in constant time. Fails CLOSED: an empty
|
|
20
|
+
* secret, a missing header, a header in any other shape, or a digest of the
|
|
21
|
+
* wrong length is `false` — never an exception, never `true`.
|
|
22
|
+
*/
|
|
23
|
+
export function verifyMetaSignature(rawBody: string | Uint8Array, signatureHeader: string | null | undefined, appSecret: string): boolean {
|
|
24
|
+
if (!appSecret || !signatureHeader) return false;
|
|
25
|
+
const match = SIGNATURE.exec(signatureHeader.trim());
|
|
26
|
+
if (!match) return false;
|
|
27
|
+
const expected = createHmac("sha256", appSecret).update(rawBody).digest();
|
|
28
|
+
const given = Buffer.from(match[1]!, "hex");
|
|
29
|
+
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** What the subscription handshake answers. */
|
|
33
|
+
export type MetaHandshake = { ok: true; challenge: string } | { ok: false };
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Meta's `GET` subscription handshake: `hub.mode=subscribe`, the
|
|
37
|
+
* `hub.verify_token` configured on the app, and a `hub.challenge` to echo.
|
|
38
|
+
* The token is compared in constant time; an empty configured token refuses
|
|
39
|
+
* every handshake.
|
|
40
|
+
*/
|
|
41
|
+
export function verifyMetaSubscription(
|
|
42
|
+
query: Readonly<Record<string, string | undefined>>,
|
|
43
|
+
verifyToken: string,
|
|
44
|
+
): MetaHandshake {
|
|
45
|
+
const mode = query["hub.mode"];
|
|
46
|
+
const token = query["hub.verify_token"];
|
|
47
|
+
const challenge = query["hub.challenge"];
|
|
48
|
+
if (!verifyToken || mode !== "subscribe" || !token || !challenge) return { ok: false };
|
|
49
|
+
// Digests of equal length, so the comparison leaks neither content nor length.
|
|
50
|
+
const digest = (value: string) => createHash("sha256").update(value, "utf8").digest();
|
|
51
|
+
return timingSafeEqual(digest(token), digest(verifyToken)) ? { ok: true, challenge } : { ok: false };
|
|
52
|
+
}
|