@theokit/gateway-whatsapp 0.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/CHANGELOG.md +31 -0
- package/README.md +7 -0
- package/dist/bridge/whatsapp-web-bridge.mjs +140 -0
- package/dist/index.cjs +809 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +428 -0
- package/dist/index.d.ts +428 -0
- package/dist/index.js +769 -0
- package/dist/index.js.map +1 -0
- package/package.json +54 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,809 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var gateway = require('@theokit/gateway');
|
|
4
|
+
var crypto = require('crypto');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
var child_process = require('child_process');
|
|
7
|
+
var fs = require('fs');
|
|
8
|
+
|
|
9
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
10
|
+
function _interopNamespace(e) {
|
|
11
|
+
if (e && e.__esModule) return e;
|
|
12
|
+
var n = Object.create(null);
|
|
13
|
+
if (e) {
|
|
14
|
+
Object.keys(e).forEach(function (k) {
|
|
15
|
+
if (k !== 'default') {
|
|
16
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
17
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
18
|
+
enumerable: true,
|
|
19
|
+
get: function () { return e[k]; }
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
n.default = e;
|
|
25
|
+
return Object.freeze(n);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
|
|
29
|
+
var path__namespace = /*#__PURE__*/_interopNamespace(path);
|
|
30
|
+
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
|
|
31
|
+
|
|
32
|
+
// src/adapter.ts
|
|
33
|
+
|
|
34
|
+
// src/split.ts
|
|
35
|
+
var WHATSAPP_MAX_TEXT = 4096;
|
|
36
|
+
function findWhatsAppCutPoint(remaining) {
|
|
37
|
+
let cut = remaining.lastIndexOf("\n\n", WHATSAPP_MAX_TEXT);
|
|
38
|
+
if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf("\n", WHATSAPP_MAX_TEXT);
|
|
39
|
+
if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf(" ", WHATSAPP_MAX_TEXT);
|
|
40
|
+
if (cut <= 0) cut = WHATSAPP_MAX_TEXT;
|
|
41
|
+
if (cut < remaining.length) {
|
|
42
|
+
const code = remaining.charCodeAt(cut);
|
|
43
|
+
if (code >= 56320 && code <= 57343) cut -= 1;
|
|
44
|
+
}
|
|
45
|
+
return cut <= 0 ? WHATSAPP_MAX_TEXT : cut;
|
|
46
|
+
}
|
|
47
|
+
function splitForWhatsApp(text) {
|
|
48
|
+
if (text.length <= WHATSAPP_MAX_TEXT) {
|
|
49
|
+
const single = text.trim();
|
|
50
|
+
return single.length > 0 ? [single] : [];
|
|
51
|
+
}
|
|
52
|
+
const chunks = [];
|
|
53
|
+
let remaining = text;
|
|
54
|
+
while (remaining.length > WHATSAPP_MAX_TEXT) {
|
|
55
|
+
const cut = findWhatsAppCutPoint(remaining);
|
|
56
|
+
chunks.push(remaining.slice(0, cut));
|
|
57
|
+
remaining = remaining.slice(cut).replace(/^[\s]+/, "");
|
|
58
|
+
}
|
|
59
|
+
if (remaining.length > 0) chunks.push(remaining);
|
|
60
|
+
return chunks.map((p) => p.trim()).filter((p) => p.length > 0);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/adapter.ts
|
|
64
|
+
function digitsOnly(s) {
|
|
65
|
+
return s.replace(/[^\d]/g, "");
|
|
66
|
+
}
|
|
67
|
+
var WhatsAppAdapter = class extends gateway.BasePlatformAdapter {
|
|
68
|
+
platform = "whatsapp";
|
|
69
|
+
backendImpl;
|
|
70
|
+
requireMention;
|
|
71
|
+
botPhoneId;
|
|
72
|
+
handler;
|
|
73
|
+
statusHandler;
|
|
74
|
+
// EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
|
|
75
|
+
inboundUnsubscribe;
|
|
76
|
+
statusUnsubscribe;
|
|
77
|
+
/** Construct from a pre-built backend (used by the static factories + tests). */
|
|
78
|
+
constructor(backendImpl, opts = {}) {
|
|
79
|
+
super();
|
|
80
|
+
this.backendImpl = backendImpl;
|
|
81
|
+
this.requireMention = opts.requireMention ?? true;
|
|
82
|
+
this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
|
|
83
|
+
}
|
|
84
|
+
/** Escape hatch (D180-style) for advanced features. */
|
|
85
|
+
getBackend() {
|
|
86
|
+
return this.backendImpl;
|
|
87
|
+
}
|
|
88
|
+
async connect() {
|
|
89
|
+
return this.backendImpl.connect();
|
|
90
|
+
}
|
|
91
|
+
async disconnect() {
|
|
92
|
+
this.inboundUnsubscribe?.();
|
|
93
|
+
this.inboundUnsubscribe = void 0;
|
|
94
|
+
this.statusUnsubscribe?.();
|
|
95
|
+
this.statusUnsubscribe = void 0;
|
|
96
|
+
this.handler = void 0;
|
|
97
|
+
this.statusHandler = void 0;
|
|
98
|
+
await this.backendImpl.disconnect();
|
|
99
|
+
}
|
|
100
|
+
async sendMessage(out) {
|
|
101
|
+
if (out.text.length === 0) {
|
|
102
|
+
return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
|
|
103
|
+
}
|
|
104
|
+
const parts = splitForWhatsApp(out.text);
|
|
105
|
+
if (parts.length === 0) {
|
|
106
|
+
return {
|
|
107
|
+
ok: false,
|
|
108
|
+
error: { code: "empty_text", message: "Text reduced to zero parts after splitting." }
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
let lastWamid;
|
|
112
|
+
const isGroup = out.channel.type === "group";
|
|
113
|
+
for (const part of parts) {
|
|
114
|
+
const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });
|
|
115
|
+
if (!r.ok) {
|
|
116
|
+
return {
|
|
117
|
+
ok: false,
|
|
118
|
+
error: { code: r.error?.code ?? "unknown", message: r.error?.message ?? "Send failed." }
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
lastWamid = r.wamid;
|
|
122
|
+
}
|
|
123
|
+
return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
|
|
124
|
+
}
|
|
125
|
+
/** D309 + EC-7: group filter with digit-only normalization. */
|
|
126
|
+
shouldDropGroupMessage(inbound) {
|
|
127
|
+
if (inbound.conversationType !== "group" || !this.requireMention) return false;
|
|
128
|
+
if (this.botPhoneId.length === 0) return true;
|
|
129
|
+
const textDigits = digitsOnly(inbound.text);
|
|
130
|
+
return !textDigits.includes(this.botPhoneId);
|
|
131
|
+
}
|
|
132
|
+
toMessageEvent(inbound) {
|
|
133
|
+
return {
|
|
134
|
+
id: inbound.wamid,
|
|
135
|
+
platform: "whatsapp",
|
|
136
|
+
sender: { id: inbound.fromPhone, displayName: inbound.contactName },
|
|
137
|
+
channel: { id: inbound.channelId, type: inbound.conversationType },
|
|
138
|
+
text: inbound.text,
|
|
139
|
+
receivedAt: inbound.receivedAt,
|
|
140
|
+
whatsapp: {
|
|
141
|
+
wamid: inbound.wamid,
|
|
142
|
+
phoneNumberId: inbound.phoneNumberId,
|
|
143
|
+
contactName: inbound.contactName,
|
|
144
|
+
backend: inbound.backend,
|
|
145
|
+
raw: inbound.raw
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
onInbound(handler) {
|
|
150
|
+
this.inboundUnsubscribe?.();
|
|
151
|
+
this.handler = handler;
|
|
152
|
+
this.inboundUnsubscribe = this.backendImpl.onInbound(async (inbound) => {
|
|
153
|
+
if (!this.handler) return;
|
|
154
|
+
if (this.shouldDropGroupMessage(inbound)) return;
|
|
155
|
+
await this.handler(this.toMessageEvent(inbound));
|
|
156
|
+
});
|
|
157
|
+
return () => {
|
|
158
|
+
this.inboundUnsubscribe?.();
|
|
159
|
+
this.inboundUnsubscribe = void 0;
|
|
160
|
+
this.handler = void 0;
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
/** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
|
|
164
|
+
onStatusReceipt(handler) {
|
|
165
|
+
this.statusUnsubscribe?.();
|
|
166
|
+
this.statusHandler = handler;
|
|
167
|
+
this.statusUnsubscribe = this.backendImpl.onStatusReceipt(async (r) => {
|
|
168
|
+
await this.statusHandler?.(r);
|
|
169
|
+
});
|
|
170
|
+
return () => {
|
|
171
|
+
this.statusUnsubscribe?.();
|
|
172
|
+
this.statusUnsubscribe = void 0;
|
|
173
|
+
this.statusHandler = void 0;
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
// src/errors.ts
|
|
179
|
+
var WhatsAppConnectTimeoutError = class extends Error {
|
|
180
|
+
constructor(timeoutMs) {
|
|
181
|
+
super(`WhatsApp web bridge connect timed out after ${timeoutMs}ms (QR code not scanned?)`);
|
|
182
|
+
this.name = "WhatsAppConnectTimeoutError";
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
function cloudErrorCode(status, errCode) {
|
|
186
|
+
if (errCode === 190 || status === 401) return "auth_failed";
|
|
187
|
+
if (errCode === 130 || errCode === 131 || status === 429) return "rate_limit";
|
|
188
|
+
if (status === 400 || errCode === 100) return "invalid_request";
|
|
189
|
+
if (status >= 500) return "server_error";
|
|
190
|
+
return "unknown";
|
|
191
|
+
}
|
|
192
|
+
function mapWhatsAppCloudError(status, body) {
|
|
193
|
+
const parsed = body !== null && typeof body === "object" ? body : {};
|
|
194
|
+
const errCode = parsed.error?.code ?? 0;
|
|
195
|
+
const errMsg = parsed.error?.message ?? `HTTP ${status}`;
|
|
196
|
+
const code = cloudErrorCode(status, errCode);
|
|
197
|
+
if (code === "auth_failed") return { code, message: `Bearer token rejected: ${errMsg}` };
|
|
198
|
+
if (code === "rate_limit") return { code, message: `Throttled: ${errMsg}` };
|
|
199
|
+
return { code, message: errMsg };
|
|
200
|
+
}
|
|
201
|
+
function mapWhatsAppWebError(ipcError) {
|
|
202
|
+
const msg = ipcError ?? "unknown bridge error";
|
|
203
|
+
if (msg.includes("AUTHENTICATION") || msg.includes("UNAUTHORIZED")) {
|
|
204
|
+
return { code: "auth_failed", message: msg };
|
|
205
|
+
}
|
|
206
|
+
if (msg.includes("RATE") || msg.includes("THROTTLE")) {
|
|
207
|
+
return { code: "rate_limit", message: msg };
|
|
208
|
+
}
|
|
209
|
+
if (msg.includes("PROTOCOL") || msg.includes("DISCONNECT")) {
|
|
210
|
+
return { code: "server_error", message: msg };
|
|
211
|
+
}
|
|
212
|
+
if (msg.includes("TIMEOUT")) {
|
|
213
|
+
return { code: "timeout", message: msg };
|
|
214
|
+
}
|
|
215
|
+
return { code: "unknown", message: msg };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// src/backend/cloud/client.ts
|
|
219
|
+
var WhatsAppCloudClient = class {
|
|
220
|
+
constructor(opts) {
|
|
221
|
+
this.opts = opts;
|
|
222
|
+
this.fetchImpl = opts.fetch ?? fetch;
|
|
223
|
+
const apiVersion = opts.apiVersion ?? "v18.0";
|
|
224
|
+
this.baseUrl = `https://graph.facebook.com/${apiVersion}/${opts.phoneNumberId}`;
|
|
225
|
+
}
|
|
226
|
+
opts;
|
|
227
|
+
fetchImpl;
|
|
228
|
+
baseUrl;
|
|
229
|
+
/** Send a text message. v1 scope — no media (D286 deferred). */
|
|
230
|
+
async sendText(to, body, isGroup) {
|
|
231
|
+
const req = isGroup ? {
|
|
232
|
+
messaging_product: "whatsapp",
|
|
233
|
+
to,
|
|
234
|
+
type: "text",
|
|
235
|
+
text: { body, preview_url: false }
|
|
236
|
+
} : {
|
|
237
|
+
messaging_product: "whatsapp",
|
|
238
|
+
recipient_type: "individual",
|
|
239
|
+
to,
|
|
240
|
+
type: "text",
|
|
241
|
+
text: { body, preview_url: false }
|
|
242
|
+
};
|
|
243
|
+
let response;
|
|
244
|
+
try {
|
|
245
|
+
response = await this.fetchImpl(`${this.baseUrl}/messages`, {
|
|
246
|
+
method: "POST",
|
|
247
|
+
headers: {
|
|
248
|
+
"content-type": "application/json",
|
|
249
|
+
authorization: `Bearer ${this.opts.accessToken}`
|
|
250
|
+
},
|
|
251
|
+
body: JSON.stringify(req)
|
|
252
|
+
});
|
|
253
|
+
} catch (cause) {
|
|
254
|
+
return {
|
|
255
|
+
ok: false,
|
|
256
|
+
error: {
|
|
257
|
+
code: "server_error",
|
|
258
|
+
message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
if (!response.ok) {
|
|
263
|
+
const errBody = await response.json().catch(() => ({}));
|
|
264
|
+
return { ok: false, error: mapWhatsAppCloudError(response.status, errBody) };
|
|
265
|
+
}
|
|
266
|
+
const data = await response.json();
|
|
267
|
+
const wamid = data.messages?.[0]?.id;
|
|
268
|
+
if (wamid === void 0) {
|
|
269
|
+
return { ok: false, error: { code: "unknown", message: "Meta returned no wamid." } };
|
|
270
|
+
}
|
|
271
|
+
return { ok: true, wamid };
|
|
272
|
+
}
|
|
273
|
+
/** Mark an inbound message as read (status receipt back to user). */
|
|
274
|
+
async markAsRead(wamid) {
|
|
275
|
+
const body = {
|
|
276
|
+
messaging_product: "whatsapp",
|
|
277
|
+
status: "read",
|
|
278
|
+
message_id: wamid
|
|
279
|
+
};
|
|
280
|
+
try {
|
|
281
|
+
const response = await this.fetchImpl(`${this.baseUrl}/messages`, {
|
|
282
|
+
method: "POST",
|
|
283
|
+
headers: {
|
|
284
|
+
"content-type": "application/json",
|
|
285
|
+
authorization: `Bearer ${this.opts.accessToken}`
|
|
286
|
+
},
|
|
287
|
+
body: JSON.stringify(body)
|
|
288
|
+
});
|
|
289
|
+
return response.ok;
|
|
290
|
+
} catch {
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
var warnedNonTextTypes = /* @__PURE__ */ new Set();
|
|
296
|
+
function verifyWebhookSubscription(query, expectedVerifyToken) {
|
|
297
|
+
const mode = query["hub.mode"];
|
|
298
|
+
const token = query["hub.verify_token"];
|
|
299
|
+
const challenge = query["hub.challenge"];
|
|
300
|
+
if (mode !== "subscribe") return null;
|
|
301
|
+
if (token === void 0 || token !== expectedVerifyToken) return null;
|
|
302
|
+
if (challenge === void 0 || challenge.length === 0) return null;
|
|
303
|
+
return challenge;
|
|
304
|
+
}
|
|
305
|
+
function verifyWebhookSignature(rawBody, signatureHeader, appSecret) {
|
|
306
|
+
if (signatureHeader === void 0) return false;
|
|
307
|
+
if (!signatureHeader.startsWith("sha256=")) return false;
|
|
308
|
+
const receivedHex = signatureHeader.slice(7);
|
|
309
|
+
if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;
|
|
310
|
+
const received = Buffer.from(receivedHex, "hex");
|
|
311
|
+
const body = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody;
|
|
312
|
+
const expected = crypto__namespace.createHmac("sha256", appSecret).update(body).digest();
|
|
313
|
+
if (received.length !== expected.length) return false;
|
|
314
|
+
return crypto__namespace.timingSafeEqual(received, expected);
|
|
315
|
+
}
|
|
316
|
+
function parseWebhookPayload(json) {
|
|
317
|
+
if (json === null || typeof json !== "object") return null;
|
|
318
|
+
const env = json;
|
|
319
|
+
if (env.object === void 0 || !Array.isArray(env.entry)) return null;
|
|
320
|
+
return env;
|
|
321
|
+
}
|
|
322
|
+
function buildContactMap(value) {
|
|
323
|
+
const map = /* @__PURE__ */ new Map();
|
|
324
|
+
for (const c of value.contacts ?? []) map.set(c.wa_id, c.profile?.name);
|
|
325
|
+
return map;
|
|
326
|
+
}
|
|
327
|
+
function processChange(change, out) {
|
|
328
|
+
const value = change.value;
|
|
329
|
+
if (value === void 0 || value === null) return;
|
|
330
|
+
const phoneNumberId = value.metadata?.phone_number_id;
|
|
331
|
+
const contactByWaId = buildContactMap(value);
|
|
332
|
+
for (const msg of value.messages ?? []) {
|
|
333
|
+
const normalized = normalizeOneMessage(msg, phoneNumberId, contactByWaId);
|
|
334
|
+
if (normalized !== null) out.push(normalized);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function normalizeInboundMessages(envelope) {
|
|
338
|
+
const out = [];
|
|
339
|
+
for (const entry of envelope.entry) {
|
|
340
|
+
for (const change of entry.changes) processChange(change, out);
|
|
341
|
+
}
|
|
342
|
+
return out;
|
|
343
|
+
}
|
|
344
|
+
function normalizeOneMessage(msg, phoneNumberId, contactByWaId) {
|
|
345
|
+
if (msg.type !== "text") {
|
|
346
|
+
if (!warnedNonTextTypes.has(msg.type)) {
|
|
347
|
+
warnedNonTextTypes.add(msg.type);
|
|
348
|
+
process.stderr.write(
|
|
349
|
+
`[whatsapp] ignoring ${msg.type} message \u2014 v1 text-only (will be supported in v0.2+).
|
|
350
|
+
`
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
return null;
|
|
354
|
+
}
|
|
355
|
+
const body = msg.text?.body ?? "";
|
|
356
|
+
return {
|
|
357
|
+
wamid: msg.id,
|
|
358
|
+
fromPhone: msg.from,
|
|
359
|
+
phoneNumberId,
|
|
360
|
+
contactName: contactByWaId.get(msg.from),
|
|
361
|
+
conversationType: "dm",
|
|
362
|
+
channelId: msg.from,
|
|
363
|
+
text: body,
|
|
364
|
+
receivedAt: Number(msg.timestamp) * 1e3 || Date.now(),
|
|
365
|
+
backend: "cloud",
|
|
366
|
+
raw: msg
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
function normalizeStatusReceipts(envelope) {
|
|
370
|
+
const out = [];
|
|
371
|
+
for (const entry of envelope.entry) {
|
|
372
|
+
for (const change of entry.changes) {
|
|
373
|
+
const statuses = change.value?.statuses ?? [];
|
|
374
|
+
for (const s of statuses) {
|
|
375
|
+
out.push(metaStatusToReceipt(s));
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return out;
|
|
380
|
+
}
|
|
381
|
+
function metaStatusToReceipt(s) {
|
|
382
|
+
return {
|
|
383
|
+
wamid: s.id,
|
|
384
|
+
status: s.status,
|
|
385
|
+
recipient: s.recipient_id,
|
|
386
|
+
timestamp: Number(s.timestamp) * 1e3 || Date.now()
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// src/backend/cloud/index.ts
|
|
391
|
+
var WhatsAppCloudBackend = class {
|
|
392
|
+
kind = "cloud";
|
|
393
|
+
client;
|
|
394
|
+
appSecret;
|
|
395
|
+
inboundHandler;
|
|
396
|
+
statusHandler;
|
|
397
|
+
constructor(opts) {
|
|
398
|
+
this.client = new WhatsAppCloudClient({
|
|
399
|
+
accessToken: opts.accessToken,
|
|
400
|
+
phoneNumberId: opts.phoneNumberId,
|
|
401
|
+
apiVersion: opts.apiVersion,
|
|
402
|
+
...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
|
|
403
|
+
});
|
|
404
|
+
this.appSecret = opts.appSecret;
|
|
405
|
+
}
|
|
406
|
+
// Cloud has no persistent connection — webhook is push, send is HTTP.
|
|
407
|
+
async connect() {
|
|
408
|
+
return true;
|
|
409
|
+
}
|
|
410
|
+
async disconnect() {
|
|
411
|
+
this.inboundHandler = void 0;
|
|
412
|
+
this.statusHandler = void 0;
|
|
413
|
+
}
|
|
414
|
+
async send(message) {
|
|
415
|
+
return this.client.sendText(message.to, message.text, message.isGroup);
|
|
416
|
+
}
|
|
417
|
+
onInbound(handler) {
|
|
418
|
+
this.inboundHandler = handler;
|
|
419
|
+
return () => {
|
|
420
|
+
this.inboundHandler = void 0;
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
onStatusReceipt(handler) {
|
|
424
|
+
this.statusHandler = handler;
|
|
425
|
+
return () => {
|
|
426
|
+
this.statusHandler = void 0;
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Webhook entrypoint. The user calls this from inside their POST /webhook
|
|
431
|
+
* route after `verifyWebhookSubscription` on GET.
|
|
432
|
+
*
|
|
433
|
+
* @returns `true` if signature valid + dispatched (or empty payload).
|
|
434
|
+
* `false` if signature invalid (route should return 401).
|
|
435
|
+
*/
|
|
436
|
+
async handleWebhookPayload(rawBody, signatureHeader) {
|
|
437
|
+
if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
const json = JSON.parse(
|
|
441
|
+
typeof rawBody === "string" ? rawBody : rawBody.toString("utf8")
|
|
442
|
+
);
|
|
443
|
+
const envelope = parseWebhookPayload(json);
|
|
444
|
+
if (envelope === null) return true;
|
|
445
|
+
const inbounds = normalizeInboundMessages(envelope);
|
|
446
|
+
for (const event of inbounds) {
|
|
447
|
+
if (this.inboundHandler !== void 0) {
|
|
448
|
+
await this.inboundHandler(event);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
const statuses = normalizeStatusReceipts(envelope);
|
|
452
|
+
for (const receipt of statuses) {
|
|
453
|
+
if (this.statusHandler !== void 0) {
|
|
454
|
+
await this.statusHandler(receipt);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return true;
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
|
|
461
|
+
// src/backend/web/ipc.ts
|
|
462
|
+
function parseEvent(line) {
|
|
463
|
+
if (line.length === 0) return null;
|
|
464
|
+
try {
|
|
465
|
+
const parsed = JSON.parse(line);
|
|
466
|
+
if (parsed === null || typeof parsed !== "object") return null;
|
|
467
|
+
if (typeof parsed.event !== "string") return null;
|
|
468
|
+
return parsed;
|
|
469
|
+
} catch {
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
function formatCommand(cmd) {
|
|
474
|
+
return `${JSON.stringify(cmd)}
|
|
475
|
+
`;
|
|
476
|
+
}
|
|
477
|
+
var LineBuffer = class {
|
|
478
|
+
buffer = "";
|
|
479
|
+
push(chunk) {
|
|
480
|
+
this.buffer += chunk;
|
|
481
|
+
const out = [];
|
|
482
|
+
let idx = this.buffer.indexOf("\n");
|
|
483
|
+
while (idx !== -1) {
|
|
484
|
+
out.push(this.buffer.slice(0, idx));
|
|
485
|
+
this.buffer = this.buffer.slice(idx + 1);
|
|
486
|
+
idx = this.buffer.indexOf("\n");
|
|
487
|
+
}
|
|
488
|
+
return out;
|
|
489
|
+
}
|
|
490
|
+
/** Test seam — current pending bytes. */
|
|
491
|
+
get pending() {
|
|
492
|
+
return this.buffer;
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
var BRIDGE_PROCESS_TAG = "whatsapp-web-bridge";
|
|
496
|
+
function pidFilePath(theokitHome, sessionId) {
|
|
497
|
+
return path__namespace.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);
|
|
498
|
+
}
|
|
499
|
+
function defaultTheokitHome() {
|
|
500
|
+
return process.env.THEOKIT_HOME ?? path__namespace.join(process.env.HOME ?? "/tmp", ".theokit");
|
|
501
|
+
}
|
|
502
|
+
function pidBelongsToOurBridge(pid) {
|
|
503
|
+
try {
|
|
504
|
+
const cmdline = fs__namespace.readFileSync(`/proc/${pid}/cmdline`, "utf8");
|
|
505
|
+
return cmdline.includes(BRIDGE_PROCESS_TAG);
|
|
506
|
+
} catch {
|
|
507
|
+
try {
|
|
508
|
+
const out = child_process.execSync(`ps -p ${pid} -o args=`, {
|
|
509
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
510
|
+
}).toString();
|
|
511
|
+
return out.includes(BRIDGE_PROCESS_TAG);
|
|
512
|
+
} catch {
|
|
513
|
+
return false;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
function killIfOurBridge(stalePid) {
|
|
518
|
+
if (!Number.isFinite(stalePid) || stalePid <= 0) return;
|
|
519
|
+
if (!pidBelongsToOurBridge(stalePid)) return;
|
|
520
|
+
try {
|
|
521
|
+
process.kill(stalePid, "SIGTERM");
|
|
522
|
+
} catch {
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
function cleanupStaleLock(lockFile) {
|
|
526
|
+
const raw = fs__namespace.readFileSync(lockFile, "utf8").trim();
|
|
527
|
+
killIfOurBridge(Number.parseInt(raw, 10));
|
|
528
|
+
try {
|
|
529
|
+
fs__namespace.unlinkSync(lockFile);
|
|
530
|
+
} catch {
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
function acquirePidLock(sessionId, theokitHome) {
|
|
534
|
+
const home = theokitHome ?? defaultTheokitHome();
|
|
535
|
+
fs__namespace.mkdirSync(home, { recursive: true });
|
|
536
|
+
const lockFile = pidFilePath(home, sessionId);
|
|
537
|
+
if (fs__namespace.existsSync(lockFile)) cleanupStaleLock(lockFile);
|
|
538
|
+
return lockFile;
|
|
539
|
+
}
|
|
540
|
+
function spawnBridge(opts) {
|
|
541
|
+
const home = opts.theokitHome ?? defaultTheokitHome();
|
|
542
|
+
const lockFile = acquirePidLock(opts.sessionId, home);
|
|
543
|
+
const child = child_process.spawn(
|
|
544
|
+
"node",
|
|
545
|
+
[opts.bridgeScriptPath, "--tag", BRIDGE_PROCESS_TAG, "--session", opts.sessionId],
|
|
546
|
+
{
|
|
547
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
548
|
+
detached: false
|
|
549
|
+
}
|
|
550
|
+
);
|
|
551
|
+
if (child.pid !== void 0) {
|
|
552
|
+
fs__namespace.writeFileSync(lockFile, String(child.pid), { mode: 384 });
|
|
553
|
+
}
|
|
554
|
+
if (child.stderr !== null) {
|
|
555
|
+
child.stderr.pipe(process.stderr);
|
|
556
|
+
}
|
|
557
|
+
return { child, pidFilePath: lockFile };
|
|
558
|
+
}
|
|
559
|
+
async function terminateBridge(handle) {
|
|
560
|
+
const { child, pidFilePath: lockFile } = handle;
|
|
561
|
+
if (child.pid !== void 0 && !child.killed) {
|
|
562
|
+
try {
|
|
563
|
+
child.kill("SIGTERM");
|
|
564
|
+
} catch {
|
|
565
|
+
}
|
|
566
|
+
const exited = await waitForExit(child, 3e3);
|
|
567
|
+
if (!exited) {
|
|
568
|
+
try {
|
|
569
|
+
child.kill("SIGKILL");
|
|
570
|
+
} catch {
|
|
571
|
+
}
|
|
572
|
+
await waitForExit(child, 1e3);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
try {
|
|
576
|
+
fs__namespace.unlinkSync(lockFile);
|
|
577
|
+
} catch {
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
function waitForExit(child, timeoutMs) {
|
|
581
|
+
return new Promise((resolve2) => {
|
|
582
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
583
|
+
resolve2(true);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
let resolved = false;
|
|
587
|
+
const onExit = () => {
|
|
588
|
+
if (resolved) return;
|
|
589
|
+
resolved = true;
|
|
590
|
+
resolve2(true);
|
|
591
|
+
};
|
|
592
|
+
child.once("exit", onExit);
|
|
593
|
+
setTimeout(() => {
|
|
594
|
+
if (resolved) return;
|
|
595
|
+
resolved = true;
|
|
596
|
+
child.removeListener("exit", onExit);
|
|
597
|
+
resolve2(false);
|
|
598
|
+
}, timeoutMs).unref();
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// src/backend/web/index.ts
|
|
603
|
+
var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
|
|
604
|
+
var DEFAULT_SEND_TIMEOUT_MS = 3e4;
|
|
605
|
+
var WhatsAppWebBackend = class {
|
|
606
|
+
constructor(opts) {
|
|
607
|
+
this.opts = opts;
|
|
608
|
+
}
|
|
609
|
+
opts;
|
|
610
|
+
kind = "web";
|
|
611
|
+
handle;
|
|
612
|
+
buffer = new LineBuffer();
|
|
613
|
+
inboundHandler;
|
|
614
|
+
statusHandler;
|
|
615
|
+
pending = /* @__PURE__ */ new Map();
|
|
616
|
+
msgIdCounter = 0;
|
|
617
|
+
botPhone;
|
|
618
|
+
connected = false;
|
|
619
|
+
// EC-6: emitter resolvers for `event: "ready"`.
|
|
620
|
+
readyResolvers = [];
|
|
621
|
+
spawnBridgeHandle() {
|
|
622
|
+
return this.opts.spawnFactory ? this.opts.spawnFactory() : spawnBridge({
|
|
623
|
+
sessionId: this.opts.sessionId,
|
|
624
|
+
bridgeScriptPath: this.opts.bridgeScriptPath ?? defaultBridgeScriptPath(),
|
|
625
|
+
...this.opts.theokitHome !== void 0 ? { theokitHome: this.opts.theokitHome } : {}
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
wireStdout() {
|
|
629
|
+
if (this.handle?.child.stdout === null || this.handle === void 0) return;
|
|
630
|
+
this.handle.child.stdout.setEncoding("utf8");
|
|
631
|
+
this.handle.child.stdout.on("data", (chunk) => {
|
|
632
|
+
for (const line of this.buffer.push(chunk)) {
|
|
633
|
+
const event = parseEvent(line);
|
|
634
|
+
if (event !== null) this.dispatch(event);
|
|
635
|
+
}
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
async cleanupHandle() {
|
|
639
|
+
if (this.handle === void 0) return;
|
|
640
|
+
await terminateBridge(this.handle).catch(() => {
|
|
641
|
+
});
|
|
642
|
+
this.handle = void 0;
|
|
643
|
+
}
|
|
644
|
+
async connect() {
|
|
645
|
+
if (this.connected) return true;
|
|
646
|
+
this.handle = this.spawnBridgeHandle();
|
|
647
|
+
this.wireStdout();
|
|
648
|
+
const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
|
|
649
|
+
const ready = new Promise((resolve2) => this.readyResolvers.push(resolve2));
|
|
650
|
+
let timer;
|
|
651
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
652
|
+
timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);
|
|
653
|
+
});
|
|
654
|
+
try {
|
|
655
|
+
const phone = await Promise.race([ready, timeout]);
|
|
656
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
657
|
+
this.botPhone = phone;
|
|
658
|
+
this.connected = true;
|
|
659
|
+
return true;
|
|
660
|
+
} catch (err) {
|
|
661
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
662
|
+
await this.cleanupHandle();
|
|
663
|
+
throw err;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
async disconnect() {
|
|
667
|
+
if (!this.connected || this.handle === void 0) return;
|
|
668
|
+
try {
|
|
669
|
+
if (this.handle.child.stdin !== null && !this.handle.child.stdin.destroyed) {
|
|
670
|
+
this.handle.child.stdin.write(formatCommand({ cmd: "shutdown" }));
|
|
671
|
+
}
|
|
672
|
+
} catch {
|
|
673
|
+
}
|
|
674
|
+
await terminateBridge(this.handle);
|
|
675
|
+
this.handle = void 0;
|
|
676
|
+
this.connected = false;
|
|
677
|
+
for (const [_, p] of this.pending) {
|
|
678
|
+
clearTimeout(p.timer);
|
|
679
|
+
p.resolve({ ok: false, error: { code: "server_error", message: "Bridge disconnected." } });
|
|
680
|
+
}
|
|
681
|
+
this.pending.clear();
|
|
682
|
+
this.readyResolvers = [];
|
|
683
|
+
}
|
|
684
|
+
async send(message) {
|
|
685
|
+
if (!this.connected || this.handle === void 0 || this.handle.child.stdin === null) {
|
|
686
|
+
return { ok: false, error: { code: "server_error", message: "Bridge not connected." } };
|
|
687
|
+
}
|
|
688
|
+
const msgId = `out-${++this.msgIdCounter}`;
|
|
689
|
+
const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
|
|
690
|
+
return new Promise((resolve2) => {
|
|
691
|
+
const timer = setTimeout(() => {
|
|
692
|
+
this.pending.delete(msgId);
|
|
693
|
+
resolve2({
|
|
694
|
+
ok: false,
|
|
695
|
+
error: { code: "timeout", message: `Bridge send timed out after ${timeoutMs}ms.` }
|
|
696
|
+
});
|
|
697
|
+
}, timeoutMs);
|
|
698
|
+
this.pending.set(msgId, { resolve: resolve2, timer });
|
|
699
|
+
try {
|
|
700
|
+
this.handle.child.stdin.write(
|
|
701
|
+
formatCommand({ cmd: "send", msgId, to: message.to, text: message.text })
|
|
702
|
+
);
|
|
703
|
+
} catch (err) {
|
|
704
|
+
clearTimeout(timer);
|
|
705
|
+
this.pending.delete(msgId);
|
|
706
|
+
resolve2({
|
|
707
|
+
ok: false,
|
|
708
|
+
error: mapWhatsAppWebError(err instanceof Error ? err.message : String(err))
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
onInbound(handler) {
|
|
714
|
+
this.inboundHandler = handler;
|
|
715
|
+
return () => {
|
|
716
|
+
this.inboundHandler = void 0;
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
onStatusReceipt(handler) {
|
|
720
|
+
this.statusHandler = handler;
|
|
721
|
+
return () => {
|
|
722
|
+
this.statusHandler = void 0;
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
handleReady(event) {
|
|
726
|
+
for (const r of this.readyResolvers) r(event.botPhone);
|
|
727
|
+
this.readyResolvers = [];
|
|
728
|
+
}
|
|
729
|
+
handleMessage(event) {
|
|
730
|
+
if (this.inboundHandler === void 0) return;
|
|
731
|
+
const normalized = {
|
|
732
|
+
wamid: event.msgId,
|
|
733
|
+
fromPhone: event.from,
|
|
734
|
+
contactName: event.contactName,
|
|
735
|
+
conversationType: event.isGroup ? "group" : "dm",
|
|
736
|
+
channelId: event.chatId,
|
|
737
|
+
text: event.body,
|
|
738
|
+
receivedAt: event.timestamp || Date.now(),
|
|
739
|
+
backend: "web",
|
|
740
|
+
raw: event
|
|
741
|
+
};
|
|
742
|
+
void this.inboundHandler(normalized);
|
|
743
|
+
}
|
|
744
|
+
handleSendAck(event) {
|
|
745
|
+
const pending = this.pending.get(event.msgId);
|
|
746
|
+
if (pending === void 0) return;
|
|
747
|
+
this.pending.delete(event.msgId);
|
|
748
|
+
clearTimeout(pending.timer);
|
|
749
|
+
if (event.success) {
|
|
750
|
+
pending.resolve(event.wamid !== void 0 ? { ok: true, wamid: event.wamid } : { ok: true });
|
|
751
|
+
} else {
|
|
752
|
+
pending.resolve({ ok: false, error: mapWhatsAppWebError(event.error) });
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
handleStatus(event) {
|
|
756
|
+
if (this.statusHandler === void 0) return;
|
|
757
|
+
void this.statusHandler({
|
|
758
|
+
wamid: event.msgId,
|
|
759
|
+
status: event.status,
|
|
760
|
+
recipient: event.recipient,
|
|
761
|
+
timestamp: event.timestamp || Date.now()
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
dispatch(event) {
|
|
765
|
+
switch (event.event) {
|
|
766
|
+
case "ready":
|
|
767
|
+
this.handleReady(event);
|
|
768
|
+
return;
|
|
769
|
+
case "message":
|
|
770
|
+
this.handleMessage(event);
|
|
771
|
+
return;
|
|
772
|
+
case "send_ack":
|
|
773
|
+
this.handleSendAck(event);
|
|
774
|
+
return;
|
|
775
|
+
case "status":
|
|
776
|
+
this.handleStatus(event);
|
|
777
|
+
return;
|
|
778
|
+
case "error":
|
|
779
|
+
process.stderr.write(`[whatsapp-web bridge] ${event.message}
|
|
780
|
+
`);
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
};
|
|
785
|
+
function defaultBridgeScriptPath() {
|
|
786
|
+
return path__namespace.resolve(
|
|
787
|
+
path__namespace.dirname(new URL((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).pathname),
|
|
788
|
+
"../../bridge/whatsapp-web-bridge.mjs"
|
|
789
|
+
);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
exports.LineBuffer = LineBuffer;
|
|
793
|
+
exports.WhatsAppAdapter = WhatsAppAdapter;
|
|
794
|
+
exports.WhatsAppCloudBackend = WhatsAppCloudBackend;
|
|
795
|
+
exports.WhatsAppConnectTimeoutError = WhatsAppConnectTimeoutError;
|
|
796
|
+
exports.WhatsAppWebBackend = WhatsAppWebBackend;
|
|
797
|
+
exports.digitsOnly = digitsOnly;
|
|
798
|
+
exports.formatCommand = formatCommand;
|
|
799
|
+
exports.mapWhatsAppCloudError = mapWhatsAppCloudError;
|
|
800
|
+
exports.mapWhatsAppWebError = mapWhatsAppWebError;
|
|
801
|
+
exports.normalizeInboundMessages = normalizeInboundMessages;
|
|
802
|
+
exports.normalizeStatusReceipts = normalizeStatusReceipts;
|
|
803
|
+
exports.parseEvent = parseEvent;
|
|
804
|
+
exports.parseWebhookPayload = parseWebhookPayload;
|
|
805
|
+
exports.splitForWhatsApp = splitForWhatsApp;
|
|
806
|
+
exports.verifyWebhookSignature = verifyWebhookSignature;
|
|
807
|
+
exports.verifyWebhookSubscription = verifyWebhookSubscription;
|
|
808
|
+
//# sourceMappingURL=index.cjs.map
|
|
809
|
+
//# sourceMappingURL=index.cjs.map
|