@jexkcode/baileys 1.2.0 → 1.3.1
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 +29 -0
- package/lib/Builders/A2UI.d.ts +275 -0
- package/lib/Builders/A2UI.js +422 -0
- package/lib/Socket/index.js +23 -0
- package/lib/Utils/auto-reconnect.d.ts +54 -0
- package/lib/Utils/auto-reconnect.js +214 -0
- package/lib/Utils/chat-export.d.ts +52 -0
- package/lib/Utils/chat-export.js +248 -0
- package/lib/Utils/decode-wa-message.js +2 -2
- package/lib/Utils/index.d.ts +7 -0
- package/lib/Utils/index.js +7 -0
- package/lib/Utils/message-search.d.ts +44 -0
- package/lib/Utils/message-search.js +250 -0
- package/lib/Utils/messages.js +86 -0
- package/lib/Utils/mini-app.d.ts +93 -0
- package/lib/Utils/mini-app.js +447 -0
- package/lib/Utils/mock-socket.d.ts +60 -0
- package/lib/Utils/mock-socket.js +253 -0
- package/lib/Utils/transcribe.d.ts +12 -0
- package/lib/Utils/transcribe.js +107 -0
- package/lib/Utils/username.d.ts +3 -0
- package/lib/Utils/username.js +73 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JAP@Add --- "Mini App" sender.
|
|
3
|
+
*
|
|
4
|
+
* Two delivery modes (both are real WhatsApp "mini app" patterns):
|
|
5
|
+
*
|
|
6
|
+
* 1. `url` — rich interactive card + CTA button opening your web app
|
|
7
|
+
* (in-app webview when supported, else the system browser). Optional
|
|
8
|
+
* `params` are appended as query string, so the app knows who opened it.
|
|
9
|
+
* 2. `flow` — WhatsApp Flows launch button (native-flow name `flow`; its
|
|
10
|
+
* payload contains the `flow_action` field): a TRUE native in-chat mini app
|
|
11
|
+
* (forms/screens rendered inside WhatsApp, no browser at all).
|
|
12
|
+
* Requires a flow ID registered & published in Flows Manager. Both modes
|
|
13
|
+
* can be combined — the card then carries two buttons.
|
|
14
|
+
*
|
|
15
|
+
* ```js
|
|
16
|
+
* import { sendMiniApp } from '@japofc/baileys'
|
|
17
|
+
* await sendMiniApp(sock, jid, {
|
|
18
|
+
* title: 'My Mini App',
|
|
19
|
+
* body: 'Tap the button to open the app 👇',
|
|
20
|
+
* url: 'https://myapp.example.com',
|
|
21
|
+
* params: { ref: 'wa-bot' }, // → ?ref=wa-bot
|
|
22
|
+
* flow: { id: '123456789', cta: '📝 Isi Form', screen: 'WELCOME' }, // optional
|
|
23
|
+
* thumbnail: 'https://myapp.example.com/icon.png', // url or Buffer (optional)
|
|
24
|
+
* })
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
import { Boom } from '@hapi/boom';
|
|
28
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
29
|
+
|
|
30
|
+
// JexkCode@Port - this fork has no fetchBuffer in messages-media, so a small safe one lives here:
|
|
31
|
+
// http(s) only, timeout, size cap, no redirects, and (by default) no private/loopback hosts.
|
|
32
|
+
const isPrivateHost = (host) => {
|
|
33
|
+
const h = String(host || '').toLowerCase().replace(/^\[|\]$/g, '');
|
|
34
|
+
return h === 'localhost' || h === '0.0.0.0' || h === '::1' || h.endsWith('.local') || h.endsWith('.internal') ||
|
|
35
|
+
/^(127\.|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.)/.test(h) || /^(fc|fd|fe80)/.test(h);
|
|
36
|
+
};
|
|
37
|
+
const fetchBuffer = async (url, { timeoutMs = 10000, maxContentLength = 512 * 1024, allowPrivate = false, headers, fetchImpl } = {}) => {
|
|
38
|
+
const u = new URL(url);
|
|
39
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Boom('only http(s) URLs are allowed', { statusCode: 400 });
|
|
40
|
+
if (!allowPrivate && isPrivateHost(u.hostname)) throw new Boom('private/loopback hosts are blocked', { statusCode: 400 });
|
|
41
|
+
const controller = new AbortController();
|
|
42
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
43
|
+
try {
|
|
44
|
+
const res = await (fetchImpl || fetch)(u, { headers, signal: controller.signal, redirect: 'error' });
|
|
45
|
+
if (!res.ok) throw new Boom('HTTP ' + res.status, { statusCode: 502 });
|
|
46
|
+
const len = Number(res.headers.get('content-length')) || 0;
|
|
47
|
+
if (len > maxContentLength) throw new Boom('file too large', { statusCode: 400 });
|
|
48
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
49
|
+
if (buf.length > maxContentLength) throw new Boom('file too large', { statusCode: 400 });
|
|
50
|
+
return buf;
|
|
51
|
+
}
|
|
52
|
+
finally { clearTimeout(timer); }
|
|
53
|
+
};
|
|
54
|
+
export const MINI_APP_DEFAULT_BUTTON_TEXT = '🚀 Open App';
|
|
55
|
+
const MAX_THUMBNAIL_BYTES = 512 * 1024;
|
|
56
|
+
const resolveThumbnail = async (thumbnail, options = {}) => {
|
|
57
|
+
if (!thumbnail) {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
if (Buffer.isBuffer(thumbnail)) {
|
|
61
|
+
return thumbnail;
|
|
62
|
+
}
|
|
63
|
+
if (typeof thumbnail === 'string') {
|
|
64
|
+
let buf;
|
|
65
|
+
try {
|
|
66
|
+
buf = await fetchBuffer(thumbnail, {
|
|
67
|
+
timeoutMs: options.thumbnailTimeoutMs ?? options.timeoutMs ?? 10_000,
|
|
68
|
+
maxContentLength: options.thumbnailMaxBytes ?? MAX_THUMBNAIL_BYTES,
|
|
69
|
+
allowPrivate: !!options.allowPrivateThumbnail,
|
|
70
|
+
headers: options.thumbnailHeaders,
|
|
71
|
+
dispatcher: options.dispatcher,
|
|
72
|
+
fetchImpl: options.fetchImpl
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
if (err instanceof Boom) throw err;
|
|
77
|
+
throw new Boom(`miniApp.thumbnail: failed to fetch ${thumbnail} (${err?.message || err})`, { statusCode: 400 });
|
|
78
|
+
}
|
|
79
|
+
if (!buf.length || buf.length > (options.thumbnailMaxBytes ?? MAX_THUMBNAIL_BYTES)) {
|
|
80
|
+
throw new Boom(`miniApp.thumbnail: must be 1–${options.thumbnailMaxBytes ?? MAX_THUMBNAIL_BYTES} bytes`, { statusCode: 400 });
|
|
81
|
+
}
|
|
82
|
+
return buf;
|
|
83
|
+
}
|
|
84
|
+
throw new Boom('miniApp.thumbnail must be a Buffer or a URL string', { statusCode: 400 });
|
|
85
|
+
};
|
|
86
|
+
const normalizeFlowConfig = (flow) => {
|
|
87
|
+
if (!flow) {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
const cfg = typeof flow === 'string' ? { id: flow } : flow;
|
|
91
|
+
if (!cfg || typeof cfg !== 'object' || !cfg.id || typeof cfg.id !== 'string') {
|
|
92
|
+
throw new Boom('miniApp.flow.id is required (your published WhatsApp Flow ID)', { statusCode: 400 });
|
|
93
|
+
}
|
|
94
|
+
return cfg;
|
|
95
|
+
};
|
|
96
|
+
const appendUrlParams = (link, params) => {
|
|
97
|
+
if (!params || typeof params !== 'object' || !Object.keys(params).length) {
|
|
98
|
+
return link;
|
|
99
|
+
}
|
|
100
|
+
let u;
|
|
101
|
+
try {
|
|
102
|
+
u = new URL(link);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new Boom(`miniApp.url is not a valid URL: ${link}`, { statusCode: 400 });
|
|
106
|
+
}
|
|
107
|
+
for (const [k, v] of Object.entries(params)) {
|
|
108
|
+
u.searchParams.set(k, String(v));
|
|
109
|
+
}
|
|
110
|
+
return u.toString();
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Build `sendMessage`-ready content for a Mini App card.
|
|
114
|
+
* Needs `url`, `flow`, or both. Thumbnail failures are non-fatal: the card is
|
|
115
|
+
* still built, just without the image.
|
|
116
|
+
*/
|
|
117
|
+
export const buildMiniAppContent = async ({ title, body, text, url, appUrl, flow, params, secret, expiresIn, buttonText, buttons = [], footer, thumbnail, useWebview = true, openWebview = false, onThumbnailError, thumbnailTimeoutMs, thumbnailMaxBytes, allowPrivateThumbnail, thumbnailHeaders, dispatcher, fetchImpl, ...passthrough } = {}) => {
|
|
118
|
+
const link = url || appUrl;
|
|
119
|
+
const flowCfg = normalizeFlowConfig(flow);
|
|
120
|
+
if ((!link || typeof link !== 'string') && !flowCfg) {
|
|
121
|
+
throw new Boom('miniApp needs either `url` (webview app) or `flow` (WhatsApp Flow) — or both', { statusCode: 400 });
|
|
122
|
+
}
|
|
123
|
+
const mainText = body || text;
|
|
124
|
+
if (!mainText || typeof mainText !== 'string') {
|
|
125
|
+
throw new Boom('miniApp.body (or text) is required', { statusCode: 400 });
|
|
126
|
+
}
|
|
127
|
+
// JAP@Add --- when a `secret` (or `expiresIn`) is supplied, sign the opener
|
|
128
|
+
// URL via createMiniAppLink so the web app can verify + expire it; otherwise
|
|
129
|
+
// keep the plain, backward-compatible query append.
|
|
130
|
+
const finalUrl = link
|
|
131
|
+
? (secret || expiresIn != null ? createMiniAppLink(link, params, { secret, expiresIn }) : appendUrlParams(link, params))
|
|
132
|
+
: undefined;
|
|
133
|
+
let thumb;
|
|
134
|
+
try {
|
|
135
|
+
thumb = await resolveThumbnail(thumbnail, { thumbnailTimeoutMs, thumbnailMaxBytes, allowPrivateThumbnail, thumbnailHeaders, dispatcher, fetchImpl });
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
if (typeof onThumbnailError === 'function') {
|
|
139
|
+
try {
|
|
140
|
+
onThumbnailError(err);
|
|
141
|
+
}
|
|
142
|
+
catch { }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const cardTitle = title || 'Mini App';
|
|
146
|
+
// JAP@Add (v2.4.6): `openWebview` opt-in emits a REAL in-app webview button
|
|
147
|
+
// (native-flow `open_webview`) instead of `cta_url`. Default stays `cta_url`
|
|
148
|
+
// because it renders on regular (non-Business) accounts, whereas `open_webview`
|
|
149
|
+
// needs the in-app-webview capability — so we don't silently regress existing
|
|
150
|
+
// callers. `useWebview` still toggles cta_url's (WA-ignored) webview_interaction
|
|
151
|
+
// flag for backward compatibility.
|
|
152
|
+
const urlButton = finalUrl
|
|
153
|
+
? (openWebview
|
|
154
|
+
? { buttonText: buttonText || MINI_APP_DEFAULT_BUTTON_TEXT, webview: { url: finalUrl, inAppWebview: true } }
|
|
155
|
+
: { buttonText: buttonText || MINI_APP_DEFAULT_BUTTON_TEXT, url: finalUrl, useWebview })
|
|
156
|
+
: undefined;
|
|
157
|
+
const nativeFlow = [
|
|
158
|
+
...(urlButton ? [urlButton] : []),
|
|
159
|
+
...(flowCfg ? [{ buttonText: flowCfg.cta || '📝 Open', flow: flowCfg }] : []),
|
|
160
|
+
...buttons
|
|
161
|
+
];
|
|
162
|
+
const content = {
|
|
163
|
+
text: mainText,
|
|
164
|
+
footer: footer ?? cardTitle,
|
|
165
|
+
nativeFlow,
|
|
166
|
+
...passthrough
|
|
167
|
+
};
|
|
168
|
+
// NOTE: only attach `thumbnail` when we actually have one — the ad-reply
|
|
169
|
+
// builder throws on a present-but-non-Buffer thumbnail value.
|
|
170
|
+
if (finalUrl) {
|
|
171
|
+
const externalAdReply = {
|
|
172
|
+
title: cardTitle,
|
|
173
|
+
body: mainText.slice(0, 120),
|
|
174
|
+
url: finalUrl,
|
|
175
|
+
mediaType: 1,
|
|
176
|
+
largeThumbnail: !!thumb
|
|
177
|
+
};
|
|
178
|
+
if (thumb) {
|
|
179
|
+
externalAdReply.thumbnail = thumb;
|
|
180
|
+
}
|
|
181
|
+
content.externalAdReply = content.externalAdReply || externalAdReply;
|
|
182
|
+
}
|
|
183
|
+
return content;
|
|
184
|
+
};
|
|
185
|
+
/**
|
|
186
|
+
* Standalone sender (same style as `sendButtons` / `sendInteractiveMessage`):
|
|
187
|
+
* `sendMiniApp(sock, jid, miniApp, options?)`. A `sock.sendMiniApp` alias exists too.
|
|
188
|
+
*/
|
|
189
|
+
export const sendMiniApp = async (sock, jid, miniApp, options = {}) => {
|
|
190
|
+
if (!sock || typeof sock.sendMessage !== 'function') {
|
|
191
|
+
throw new Boom('sendMiniApp(sock, ...) requires an active Baileys socket', { statusCode: 400 });
|
|
192
|
+
}
|
|
193
|
+
return sock.sendMessage(jid, await buildMiniAppContent(miniApp), options);
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* JAP@Add --- canonical, order-independent serialization of the params that get
|
|
198
|
+
* signed. `sig` itself is never part of its own signature. Shared by the link
|
|
199
|
+
* builder and every verifier so sign/verify can never disagree.
|
|
200
|
+
*/
|
|
201
|
+
const canonicalPayload = (searchParams) =>
|
|
202
|
+
[...searchParams.entries()]
|
|
203
|
+
.filter(([k]) => k !== 'sig')
|
|
204
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
205
|
+
.map(([k, v]) => `${k}=${v}`)
|
|
206
|
+
.join('&');
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* JAP@Add --- build a mini-app deep link with optional HMAC-signed params, so
|
|
210
|
+
* your web app can verify the opener came from your bot untampered — and,
|
|
211
|
+
* optionally, that the link hasn't expired.
|
|
212
|
+
*
|
|
213
|
+
* `createMiniAppLink('https://app.example.com', { uid: '123' }, { secret })`
|
|
214
|
+
* → `'https://app.example.com/?uid=123&sig=…'`
|
|
215
|
+
* `createMiniAppLink(url, { uid: '1' }, { secret, expiresIn: 3600 })`
|
|
216
|
+
* → adds a signed `exp` (unix seconds); the link stops verifying after an hour.
|
|
217
|
+
*
|
|
218
|
+
* @param {string} baseUrl
|
|
219
|
+
* @param {Record<string, string|number|boolean>} [params]
|
|
220
|
+
* @param {object} [opts]
|
|
221
|
+
* @param {string} [opts.secret] HMAC-SHA256 key; when set, a `sig` is appended
|
|
222
|
+
* @param {number} [opts.expiresIn] lifetime in SECONDS from now (signed into `exp`)
|
|
223
|
+
* @param {() => number} [opts.now=Date.now] injectable clock (ms)
|
|
224
|
+
*/
|
|
225
|
+
export const createMiniAppLink = (baseUrl, params = {}, { secret, expiresIn, audience, nonce, now = Date.now } = {}) => {
|
|
226
|
+
let u;
|
|
227
|
+
try {
|
|
228
|
+
u = new URL(baseUrl);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
throw new Boom(`miniApp.url is not a valid URL: ${baseUrl}`, { statusCode: 400 });
|
|
232
|
+
}
|
|
233
|
+
for (const [k, v] of Object.entries(params || {})) {
|
|
234
|
+
u.searchParams.set(k, String(v));
|
|
235
|
+
}
|
|
236
|
+
if (expiresIn != null) {
|
|
237
|
+
const secs = Number(expiresIn);
|
|
238
|
+
if (!Number.isFinite(secs) || secs <= 0) {
|
|
239
|
+
throw new Boom('miniApp.expiresIn must be a positive number of seconds', { statusCode: 400 });
|
|
240
|
+
}
|
|
241
|
+
u.searchParams.set('exp', String(Math.floor(now() / 1000) + Math.floor(secs)));
|
|
242
|
+
}
|
|
243
|
+
// Bind the link to a single opener (e.g. the recipient JID) so a shared/leaked
|
|
244
|
+
// link is rejected for anyone else — only meaningful when signed with `secret`.
|
|
245
|
+
if (audience != null && audience !== '') {
|
|
246
|
+
u.searchParams.set('aud', String(audience));
|
|
247
|
+
}
|
|
248
|
+
// One-time token: pair with a nonce store on the verify side to reject replays.
|
|
249
|
+
if (nonce != null && nonce !== '') {
|
|
250
|
+
u.searchParams.set('nonce', String(nonce));
|
|
251
|
+
}
|
|
252
|
+
if (secret) {
|
|
253
|
+
u.searchParams.set('sig', createHmac('sha256', secret).update(canonicalPayload(u.searchParams)).digest('hex'));
|
|
254
|
+
}
|
|
255
|
+
return u.toString();
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* JAP@Add --- single-use nonce store for one-time mini-app / webview links.
|
|
260
|
+
* `issue()` mints a nonce you embed in a signed link (via `createMiniAppLink`'s
|
|
261
|
+
* `nonce` option); `consume(nonce)` returns `true` exactly once per issued nonce
|
|
262
|
+
* and `false` for unknown, already-used, or expired nonces — so a captured link
|
|
263
|
+
* can't be replayed. Purely in-memory; inject `now` for testing.
|
|
264
|
+
*
|
|
265
|
+
* @param {object} [opts]
|
|
266
|
+
* @param {number} [opts.ttlMs=600000] how long an issued nonce stays valid (10 min)
|
|
267
|
+
* @param {number} [opts.max=10000] cap on tracked nonces (oldest pruned)
|
|
268
|
+
* @param {() => number} [opts.now=Date.now]
|
|
269
|
+
*/
|
|
270
|
+
export const createNonceStore = ({ ttlMs = 10 * 60 * 1000, max = 10000, now = Date.now } = {}) => {
|
|
271
|
+
const entries = new Map(); // nonce -> { issuedAt, consumed }
|
|
272
|
+
const prune = () => {
|
|
273
|
+
const cutoff = now() - ttlMs;
|
|
274
|
+
for (const [n, e] of entries) {
|
|
275
|
+
if (e.issuedAt < cutoff) entries.delete(n);
|
|
276
|
+
}
|
|
277
|
+
while (entries.size > max) {
|
|
278
|
+
const oldest = entries.keys().next().value;
|
|
279
|
+
if (oldest === undefined) break;
|
|
280
|
+
entries.delete(oldest);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
return {
|
|
284
|
+
issue(size = 16) {
|
|
285
|
+
prune();
|
|
286
|
+
const bytes = Math.max(8, Math.floor(size));
|
|
287
|
+
let n;
|
|
288
|
+
do {
|
|
289
|
+
n = createHmac('sha256', String(Math.random())).update(String(now()) + Math.random()).digest('hex').slice(0, bytes * 2);
|
|
290
|
+
} while (entries.has(n));
|
|
291
|
+
entries.set(n, { issuedAt: now(), consumed: false });
|
|
292
|
+
return n;
|
|
293
|
+
},
|
|
294
|
+
consume(nonce) {
|
|
295
|
+
if (typeof nonce !== 'string' || !nonce) return false;
|
|
296
|
+
const e = entries.get(nonce);
|
|
297
|
+
if (!e) return false; // never issued (or already pruned)
|
|
298
|
+
if (e.consumed) return false; // replay
|
|
299
|
+
if (e.issuedAt < now() - ttlMs) { // expired
|
|
300
|
+
entries.delete(nonce);
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
e.consumed = true;
|
|
304
|
+
return true;
|
|
305
|
+
},
|
|
306
|
+
has(nonce) { return entries.has(nonce); },
|
|
307
|
+
clear() { entries.clear(); },
|
|
308
|
+
get size() { return entries.size; }
|
|
309
|
+
};
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* JAP@Add --- parse + (optionally) verify a mini-app link's params.
|
|
314
|
+
* Throws `Boom(403)` when `secret` is given and the signature is missing/invalid,
|
|
315
|
+
* or when a signed `exp` timestamp is in the past. `exp` is only tamper-proof
|
|
316
|
+
* when the link was signed with a `secret`.
|
|
317
|
+
*
|
|
318
|
+
* @param {string} link
|
|
319
|
+
* @param {object} [opts]
|
|
320
|
+
* @param {string} [opts.secret]
|
|
321
|
+
* @param {() => number} [opts.now=Date.now]
|
|
322
|
+
*/
|
|
323
|
+
export const parseMiniAppParams = (link, { secret, now = Date.now, audience, nonceStore } = {}) => {
|
|
324
|
+
let u;
|
|
325
|
+
try {
|
|
326
|
+
u = new URL(link);
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
throw new Boom(`miniApp.url is not a valid URL: ${link}`, { statusCode: 400 });
|
|
330
|
+
}
|
|
331
|
+
const out = {};
|
|
332
|
+
for (const [k, v] of u.searchParams.entries()) {
|
|
333
|
+
if (k !== 'sig') {
|
|
334
|
+
out[k] = v;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (secret) {
|
|
338
|
+
const sig = u.searchParams.get('sig') || '';
|
|
339
|
+
const expect = createHmac('sha256', secret).update(canonicalPayload(u.searchParams)).digest('hex');
|
|
340
|
+
const ok = sig.length === expect.length && (() => { try { return timingSafeEqual(Buffer.from(sig), Buffer.from(expect)); } catch { return false; } })();
|
|
341
|
+
if (!ok) {
|
|
342
|
+
throw new Boom('miniApp.params: invalid signature', { statusCode: 403 });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (out.exp !== undefined) {
|
|
346
|
+
const exp = Number(out.exp);
|
|
347
|
+
if (!Number.isFinite(exp) || Math.floor(now() / 1000) > exp) {
|
|
348
|
+
throw new Boom('miniApp.params: link expired', { statusCode: 403 });
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// Audience binding: the link was minted for one opener; reject anyone else.
|
|
352
|
+
if (audience != null && audience !== '') {
|
|
353
|
+
if (String(out.aud ?? '') !== String(audience)) {
|
|
354
|
+
throw new Boom('miniApp.params: audience mismatch', { statusCode: 403 });
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
// One-time nonce: reject unknown / already-used / expired tokens (replay guard).
|
|
358
|
+
if (nonceStore) {
|
|
359
|
+
if (!out.nonce || !nonceStore.consume(out.nonce)) {
|
|
360
|
+
throw new Boom('miniApp.params: nonce invalid or already used', { statusCode: 403 });
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return out;
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* JAP@Add --- server-side convenience: verify a request that arrived from a
|
|
368
|
+
* mini-app opener. Accepts a full URL, a raw query string (`'uid=1&sig=…'`, with
|
|
369
|
+
* or without a leading `?`), or a params object (e.g. Express `req.query`).
|
|
370
|
+
* Returns the clean params (minus `sig`) or throws `Boom(403)` like
|
|
371
|
+
* `parseMiniAppParams`.
|
|
372
|
+
*/
|
|
373
|
+
export const verifyMiniAppRequest = (input, opts = {}) => {
|
|
374
|
+
if (typeof input === 'string') {
|
|
375
|
+
const s = input.trim();
|
|
376
|
+
const link = /^https?:\/\//i.test(s) ? s : `https://mini.app/?${s.replace(/^[?&]+/, '')}`;
|
|
377
|
+
return parseMiniAppParams(link, opts);
|
|
378
|
+
}
|
|
379
|
+
if (input && typeof input === 'object') {
|
|
380
|
+
const u = new URL('https://mini.app/');
|
|
381
|
+
for (const [k, v] of Object.entries(input)) {
|
|
382
|
+
if (v != null) u.searchParams.set(k, Array.isArray(v) ? String(v[0]) : String(v));
|
|
383
|
+
}
|
|
384
|
+
return parseMiniAppParams(u.toString(), opts);
|
|
385
|
+
}
|
|
386
|
+
throw new Boom('verifyMiniAppRequest: expected a URL, query string, or params object', { statusCode: 400 });
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* JAP@Add --- read a mini-app / WhatsApp Flow submission coming back IN chat
|
|
391
|
+
* (an `interactiveResponseMessage.nativeFlowResponseMessage`). Accepts a full
|
|
392
|
+
* WAMessage, its `.message`, or the inner message object. Returns
|
|
393
|
+
* `{ name, version, params, flowToken, body }` or `null` when the message isn't
|
|
394
|
+
* a flow response. `params` is always an object (invalid JSON → `{}`).
|
|
395
|
+
*/
|
|
396
|
+
export const parseMiniAppResponse = (message) => {
|
|
397
|
+
const inner = message?.message ?? message;
|
|
398
|
+
const interactive = inner?.interactiveResponseMessage
|
|
399
|
+
?? inner?.viewOnceMessage?.message?.interactiveResponseMessage
|
|
400
|
+
?? inner?.ephemeralMessage?.message?.interactiveResponseMessage;
|
|
401
|
+
const native = interactive?.nativeFlowResponseMessage;
|
|
402
|
+
if (!native) {
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
let params = {};
|
|
406
|
+
try {
|
|
407
|
+
params = native.paramsJson ? JSON.parse(native.paramsJson) : {};
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
params = {};
|
|
411
|
+
}
|
|
412
|
+
if (!params || typeof params !== 'object') {
|
|
413
|
+
params = {};
|
|
414
|
+
}
|
|
415
|
+
return {
|
|
416
|
+
name: native.name || undefined,
|
|
417
|
+
version: native.version,
|
|
418
|
+
params,
|
|
419
|
+
flowToken: params.flow_token,
|
|
420
|
+
body: interactive?.body?.text
|
|
421
|
+
};
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* JAP@Add --- build a WhatsApp Flows `data_exchange` action payload
|
|
427
|
+
* (`{ version, action, data, token? }`) for the `flow.actionPayload` shortcut.
|
|
428
|
+
*/
|
|
429
|
+
export const buildFlowDataExchange = (action, data = {}, { version = '3.0', token } = {}) => {
|
|
430
|
+
if (!action || typeof action !== 'string') {
|
|
431
|
+
throw new Boom('flow action is required (e.g. navigate, data_exchange)', { statusCode: 400 });
|
|
432
|
+
}
|
|
433
|
+
return { version, action, data, ...(token ? { token } : {}) };
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* JAP@Add --- build a WhatsApp Flows `navigate` action payload targeting a
|
|
438
|
+
* specific screen: `{ version, action:'navigate', data: { screen, ...data } }`.
|
|
439
|
+
* The screen name goes INSIDE `data` (where the Flows runtime expects it), so
|
|
440
|
+
* this is the correct shape to drop straight into `flow.actionPayload`.
|
|
441
|
+
*/
|
|
442
|
+
export const buildFlowNavigate = (screen, data = {}, { version = '3.0', token } = {}) => {
|
|
443
|
+
if (!screen || typeof screen !== 'string') {
|
|
444
|
+
throw new Boom('flow navigate: a target screen name is required', { statusCode: 400 });
|
|
445
|
+
}
|
|
446
|
+
return buildFlowDataExchange('navigate', { screen, ...data }, { version, token });
|
|
447
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { proto } from '../../WAProto/index.js';
|
|
2
|
+
import type { AnyMessageContent, MiscMessageGenerationOptions } from '../Types/index.js';
|
|
3
|
+
/** One captured outgoing message. */
|
|
4
|
+
export type MockOutboxEntry = {
|
|
5
|
+
jid: string;
|
|
6
|
+
content: AnyMessageContent | Record<string, unknown>;
|
|
7
|
+
options: MiscMessageGenerationOptions | Record<string, unknown>;
|
|
8
|
+
/** The real proto.WebMessageInfo built through generateWAMessage. */
|
|
9
|
+
message: proto.IWebMessageInfo;
|
|
10
|
+
};
|
|
11
|
+
export type MockSocketOptions = {
|
|
12
|
+
/** Own jid (default '628000000000@s.whatsapp.net'). */
|
|
13
|
+
me?: string;
|
|
14
|
+
/** Own display name on outgoing messages (default 'MockBot'). */
|
|
15
|
+
pushName?: string;
|
|
16
|
+
/** Emit connection.update open on creation (default true). */
|
|
17
|
+
autoConnect?: boolean;
|
|
18
|
+
};
|
|
19
|
+
export type ReceiveTextOptions = {
|
|
20
|
+
/** Deliver as a group message: fromJid becomes the participant. */
|
|
21
|
+
groupJid?: string;
|
|
22
|
+
/** Sender display name (default 'Tester'). */
|
|
23
|
+
pushName?: string;
|
|
24
|
+
/** Make the injected message quote this earlier message. */
|
|
25
|
+
quoted?: proto.IWebMessageInfo;
|
|
26
|
+
};
|
|
27
|
+
export type MockWASocket = {
|
|
28
|
+
/** The mock sock — hand to bot code in place of makeWASocket(). */
|
|
29
|
+
sock: any;
|
|
30
|
+
/** Every message the bot "sent", in order. */
|
|
31
|
+
outbox: MockOutboxEntry[];
|
|
32
|
+
/** Every event emitted, in order: full audit trail. */
|
|
33
|
+
eventLog: Array<{ event: string; data: unknown }>;
|
|
34
|
+
/** Keys passed to readMessages(). */
|
|
35
|
+
readReceipts: proto.IMessageKey[];
|
|
36
|
+
/** Presence updates sent via sendPresenceUpdate(). */
|
|
37
|
+
presenceLog: Array<{ type: string; toJid: string | null }>;
|
|
38
|
+
/** Inject an incoming text message; resolves after handlers get a turn. */
|
|
39
|
+
receiveText: (fromJid: string, text: string, opts?: ReceiveTextOptions) => Promise<proto.IWebMessageInfo>;
|
|
40
|
+
/** Inject any raw incoming WAMessage. */
|
|
41
|
+
receiveMessage: (msg: proto.IWebMessageInfo) => Promise<proto.IWebMessageInfo>;
|
|
42
|
+
/** Wait for the next outgoing message (optionally filtered). Rejects on timeout. */
|
|
43
|
+
waitForReply: (filter?: (entry: MockOutboxEntry) => boolean, timeoutMs?: number) => Promise<MockOutboxEntry>;
|
|
44
|
+
/** Emit connection.update open. */
|
|
45
|
+
connect: () => void;
|
|
46
|
+
/** Emit connection.update close (optionally with an error). */
|
|
47
|
+
disconnect: (error?: Error) => void;
|
|
48
|
+
/** Clear outbox/logs and reject pending waiters; listeners stay attached. */
|
|
49
|
+
reset: () => void;
|
|
50
|
+
readonly connectionState: 'open' | 'close';
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Offline mock WhatsApp socket for testing bot logic — same `ev` surface and
|
|
54
|
+
* `sendMessage()` signature as the live socket, producing real
|
|
55
|
+
* proto.WebMessageInfo objects. No network, CI-safe.
|
|
56
|
+
*
|
|
57
|
+
* NOT a server emulator: WhatsApp-side behaviour (rate limits, sessions,
|
|
58
|
+
* encryption) is out of scope; media builds use a stub uploader.
|
|
59
|
+
*/
|
|
60
|
+
export declare const createMockSocket: (options?: MockSocketOptions) => MockWASocket;
|