@nexustechpro/baileys 1.0.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 +1573 -0
- package/WAProto/fix-imports.js +29 -0
- package/WAProto/index.js +169659 -0
- package/lib/Defaults/index.js +115 -0
- package/lib/Signal/Group/ciphertext-message.js +12 -0
- package/lib/Signal/Group/group-session-builder.js +30 -0
- package/lib/Signal/Group/group_cipher.js +82 -0
- package/lib/Signal/Group/index.js +12 -0
- package/lib/Signal/Group/keyhelper.js +18 -0
- package/lib/Signal/Group/sender-chain-key.js +26 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
- package/lib/Signal/Group/sender-key-message.js +66 -0
- package/lib/Signal/Group/sender-key-name.js +48 -0
- package/lib/Signal/Group/sender-key-record.js +41 -0
- package/lib/Signal/Group/sender-key-state.js +84 -0
- package/lib/Signal/Group/sender-message-key.js +26 -0
- package/lib/Signal/libsignal.js +342 -0
- package/lib/Signal/lid-mapping.js +171 -0
- package/lib/Socket/Client/index.js +3 -0
- package/lib/Socket/Client/types.js +11 -0
- package/lib/Socket/Client/websocket.js +91 -0
- package/lib/Socket/business.js +376 -0
- package/lib/Socket/chats.js +963 -0
- package/lib/Socket/communities.js +431 -0
- package/lib/Socket/groups.js +328 -0
- package/lib/Socket/index.js +19 -0
- package/lib/Socket/messages-recv.js +1240 -0
- package/lib/Socket/messages-send.js +1370 -0
- package/lib/Socket/mex.js +42 -0
- package/lib/Socket/newsletter.js +202 -0
- package/lib/Socket/nexus-handler.js +667 -0
- package/lib/Socket/socket.js +871 -0
- package/lib/Store/index.js +4 -0
- package/lib/Store/make-cache-manager-store.js +81 -0
- package/lib/Store/make-in-memory-store.js +416 -0
- package/lib/Store/make-ordered-dictionary.js +82 -0
- package/lib/Store/object-repository.js +31 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Bussines.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +8 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.js +25 -0
- package/lib/Types/LabelAssociation.js +7 -0
- package/lib/Types/Message.js +11 -0
- package/lib/Types/Newsletter.js +31 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.js +3 -0
- package/lib/Types/State.js +13 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +26 -0
- package/lib/Utils/auth-utils.js +257 -0
- package/lib/Utils/baileys-event-stream.js +56 -0
- package/lib/Utils/browser-utils.js +28 -0
- package/lib/Utils/business.js +231 -0
- package/lib/Utils/chat-utils.js +763 -0
- package/lib/Utils/crypto.js +142 -0
- package/lib/Utils/decode-wa-message.js +279 -0
- package/lib/Utils/event-buffer.js +548 -0
- package/lib/Utils/generics.js +381 -0
- package/lib/Utils/history.js +84 -0
- package/lib/Utils/index.js +20 -0
- package/lib/Utils/link-preview.js +85 -0
- package/lib/Utils/logger.js +3 -0
- package/lib/Utils/lt-hash.js +48 -0
- package/lib/Utils/make-mutex.js +40 -0
- package/lib/Utils/message-retry-manager.js +149 -0
- package/lib/Utils/messages-media.js +685 -0
- package/lib/Utils/messages.js +820 -0
- package/lib/Utils/noise-handler.js +147 -0
- package/lib/Utils/pre-key-manager.js +106 -0
- package/lib/Utils/process-message.js +413 -0
- package/lib/Utils/signal.js +159 -0
- package/lib/Utils/use-multi-file-auth-state.js +121 -0
- package/lib/Utils/validate-connection.js +195 -0
- package/lib/WABinary/constants.js +1301 -0
- package/lib/WABinary/decode.js +238 -0
- package/lib/WABinary/encode.js +216 -0
- package/lib/WABinary/generic-utils.js +111 -0
- package/lib/WABinary/index.js +6 -0
- package/lib/WABinary/jid-utils.js +96 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.js +10 -0
- package/lib/WAM/constants.js +22853 -0
- package/lib/WAM/encode.js +150 -0
- package/lib/WAM/index.js +4 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
- package/lib/WAUSync/Protocols/index.js +5 -0
- package/lib/WAUSync/USyncQuery.js +94 -0
- package/lib/WAUSync/USyncUser.js +23 -0
- package/lib/WAUSync/index.js +4 -0
- package/lib/index.js +24 -0
- package/package.json +113 -0
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import { Boom } from '@hapi/boom';
|
|
2
|
+
import { createHash, randomBytes } from 'crypto';
|
|
3
|
+
import { proto } from '../../WAProto/index.js';
|
|
4
|
+
const baileysVersion = [2, 3000, 1027934701];
|
|
5
|
+
import { DisconnectReason } from '../Types/index.js';
|
|
6
|
+
import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
|
|
7
|
+
import { sha256 } from './crypto.js';
|
|
8
|
+
export const BufferJSON = {
|
|
9
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
10
|
+
replacer: (k, value) => {
|
|
11
|
+
if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
|
|
12
|
+
return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
|
|
13
|
+
}
|
|
14
|
+
return value;
|
|
15
|
+
},
|
|
16
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
17
|
+
reviver: (_, value) => {
|
|
18
|
+
if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
|
|
19
|
+
return Buffer.from(value.data, 'base64');
|
|
20
|
+
}
|
|
21
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
|
22
|
+
const keys = Object.keys(value);
|
|
23
|
+
if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
|
|
24
|
+
const values = Object.values(value);
|
|
25
|
+
if (values.every(v => typeof v === 'number')) {
|
|
26
|
+
return Buffer.from(values);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participant || key?.remoteJid) || '';
|
|
34
|
+
export const writeRandomPadMax16 = (msg) => {
|
|
35
|
+
const pad = randomBytes(1);
|
|
36
|
+
const padLength = (pad[0] & 0x0f) + 1;
|
|
37
|
+
return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
|
|
38
|
+
};
|
|
39
|
+
export const unpadRandomMax16 = (e) => {
|
|
40
|
+
const t = new Uint8Array(e);
|
|
41
|
+
if (0 === t.length) {
|
|
42
|
+
throw new Error('unpadPkcs7 given empty bytes');
|
|
43
|
+
}
|
|
44
|
+
var r = t[t.length - 1];
|
|
45
|
+
if (r > t.length) {
|
|
46
|
+
throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
|
|
47
|
+
}
|
|
48
|
+
return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
|
|
49
|
+
};
|
|
50
|
+
// code is inspired by whatsmeow
|
|
51
|
+
export const generateParticipantHashV2 = (participants) => {
|
|
52
|
+
participants.sort();
|
|
53
|
+
const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
|
|
54
|
+
return '2:' + sha256Hash.slice(0, 6);
|
|
55
|
+
};
|
|
56
|
+
export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
|
|
57
|
+
export const generateRegistrationId = () => {
|
|
58
|
+
return Uint16Array.from(randomBytes(2))[0] & 16383;
|
|
59
|
+
};
|
|
60
|
+
export const encodeBigEndian = (e, t = 4) => {
|
|
61
|
+
let r = e;
|
|
62
|
+
const a = new Uint8Array(t);
|
|
63
|
+
for (let i = t - 1; i >= 0; i--) {
|
|
64
|
+
a[i] = 255 & r;
|
|
65
|
+
r >>>= 8;
|
|
66
|
+
}
|
|
67
|
+
return a;
|
|
68
|
+
};
|
|
69
|
+
export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
|
|
70
|
+
/** unix timestamp of a date in seconds */
|
|
71
|
+
export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
|
|
72
|
+
export const debouncedTimeout = (intervalMs = 1000, task) => {
|
|
73
|
+
let timeout;
|
|
74
|
+
return {
|
|
75
|
+
start: (newIntervalMs, newTask) => {
|
|
76
|
+
task = newTask || task;
|
|
77
|
+
intervalMs = newIntervalMs || intervalMs;
|
|
78
|
+
timeout && clearTimeout(timeout);
|
|
79
|
+
timeout = setTimeout(() => task?.(), intervalMs);
|
|
80
|
+
},
|
|
81
|
+
cancel: () => {
|
|
82
|
+
timeout && clearTimeout(timeout);
|
|
83
|
+
timeout = undefined;
|
|
84
|
+
},
|
|
85
|
+
setTask: (newTask) => (task = newTask),
|
|
86
|
+
setInterval: (newInterval) => (intervalMs = newInterval)
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
export const delay = (ms) => delayCancellable(ms).delay;
|
|
90
|
+
export const delayCancellable = (ms) => {
|
|
91
|
+
const stack = new Error().stack;
|
|
92
|
+
let timeout;
|
|
93
|
+
let reject;
|
|
94
|
+
const delay = new Promise((resolve, _reject) => {
|
|
95
|
+
timeout = setTimeout(resolve, ms);
|
|
96
|
+
reject = _reject;
|
|
97
|
+
});
|
|
98
|
+
const cancel = () => {
|
|
99
|
+
clearTimeout(timeout);
|
|
100
|
+
reject(new Boom('Cancelled', {
|
|
101
|
+
statusCode: 500,
|
|
102
|
+
data: {
|
|
103
|
+
stack
|
|
104
|
+
}
|
|
105
|
+
}));
|
|
106
|
+
};
|
|
107
|
+
return { delay, cancel };
|
|
108
|
+
};
|
|
109
|
+
export async function promiseTimeout(ms, promise) {
|
|
110
|
+
if (!ms) {
|
|
111
|
+
return new Promise(promise);
|
|
112
|
+
}
|
|
113
|
+
const stack = new Error().stack;
|
|
114
|
+
// Create a promise that rejects in <ms> milliseconds
|
|
115
|
+
const { delay, cancel } = delayCancellable(ms);
|
|
116
|
+
const p = new Promise((resolve, reject) => {
|
|
117
|
+
delay
|
|
118
|
+
.then(() => reject(new Boom('Timed Out', {
|
|
119
|
+
statusCode: DisconnectReason.timedOut,
|
|
120
|
+
data: {
|
|
121
|
+
stack
|
|
122
|
+
}
|
|
123
|
+
})))
|
|
124
|
+
.catch(err => reject(err));
|
|
125
|
+
promise(resolve, reject);
|
|
126
|
+
}).finally(cancel);
|
|
127
|
+
return p;
|
|
128
|
+
}
|
|
129
|
+
// inspired from whatsmeow code
|
|
130
|
+
// https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
|
|
131
|
+
export const generateMessageIDV2 = (userId) => {
|
|
132
|
+
const data = Buffer.alloc(8 + 20 + 16);
|
|
133
|
+
data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
|
|
134
|
+
if (userId) {
|
|
135
|
+
const id = jidDecode(userId);
|
|
136
|
+
if (id?.user) {
|
|
137
|
+
data.write(id.user, 8);
|
|
138
|
+
data.write('@c.us', 8 + id.user.length);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const random = randomBytes(16);
|
|
142
|
+
random.copy(data, 28);
|
|
143
|
+
const hash = createHash('sha256').update(data).digest();
|
|
144
|
+
return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
|
|
145
|
+
};
|
|
146
|
+
// generate a random ID to attach to a message
|
|
147
|
+
export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase();
|
|
148
|
+
export function bindWaitForEvent(ev, event) {
|
|
149
|
+
return async (check, timeoutMs) => {
|
|
150
|
+
let listener;
|
|
151
|
+
let closeListener;
|
|
152
|
+
await promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
153
|
+
closeListener = ({ connection, lastDisconnect }) => {
|
|
154
|
+
if (connection === 'close') {
|
|
155
|
+
reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
ev.on('connection.update', closeListener);
|
|
159
|
+
listener = async (update) => {
|
|
160
|
+
if (await check(update)) {
|
|
161
|
+
resolve();
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
ev.on(event, listener);
|
|
165
|
+
}).finally(() => {
|
|
166
|
+
ev.off(event, listener);
|
|
167
|
+
ev.off('connection.update', closeListener);
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
|
|
172
|
+
/**
|
|
173
|
+
* utility that fetches latest baileys version from the master branch.
|
|
174
|
+
* Use to ensure your WA connection is always on the latest version
|
|
175
|
+
*/
|
|
176
|
+
export const fetchLatestBaileysVersion = async (options = {}) => {
|
|
177
|
+
const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
|
|
178
|
+
try {
|
|
179
|
+
const response = await fetch(URL, {
|
|
180
|
+
dispatcher: options.dispatcher,
|
|
181
|
+
method: 'GET',
|
|
182
|
+
headers: options.headers
|
|
183
|
+
});
|
|
184
|
+
if (!response.ok) {
|
|
185
|
+
throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
|
|
186
|
+
}
|
|
187
|
+
const text = await response.text();
|
|
188
|
+
// Extract version from line 7 (const version = [...])
|
|
189
|
+
const lines = text.split('\n');
|
|
190
|
+
const versionLine = lines[6]; // Line 7 (0-indexed)
|
|
191
|
+
const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
|
|
192
|
+
if (versionMatch) {
|
|
193
|
+
const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
|
|
194
|
+
return {
|
|
195
|
+
version,
|
|
196
|
+
isLatest: true
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
throw new Error('Could not parse version from Defaults/index.ts');
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
return {
|
|
205
|
+
version: baileysVersion,
|
|
206
|
+
isLatest: false,
|
|
207
|
+
error
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
/**
|
|
212
|
+
* A utility that fetches the latest web version of whatsapp.
|
|
213
|
+
* Use to ensure your WA connection is always on the latest version
|
|
214
|
+
*/
|
|
215
|
+
export const fetchLatestWaWebVersion = async (options = {}) => {
|
|
216
|
+
try {
|
|
217
|
+
// Absolute minimal headers required to bypass anti-bot detection
|
|
218
|
+
const defaultHeaders = {
|
|
219
|
+
'sec-fetch-site': 'none',
|
|
220
|
+
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
|
|
221
|
+
};
|
|
222
|
+
const headers = { ...defaultHeaders, ...options.headers };
|
|
223
|
+
const response = await fetch('https://web.whatsapp.com/sw.js', {
|
|
224
|
+
...options,
|
|
225
|
+
method: 'GET',
|
|
226
|
+
headers
|
|
227
|
+
});
|
|
228
|
+
if (!response.ok) {
|
|
229
|
+
throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
|
|
230
|
+
}
|
|
231
|
+
const data = await response.text();
|
|
232
|
+
const regex = /\\?"client_revision\\?":\s*(\d+)/;
|
|
233
|
+
const match = data.match(regex);
|
|
234
|
+
if (!match?.[1]) {
|
|
235
|
+
return {
|
|
236
|
+
version: baileysVersion,
|
|
237
|
+
isLatest: false,
|
|
238
|
+
error: {
|
|
239
|
+
message: 'Could not find client revision in the fetched content'
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
const clientRevision = match[1];
|
|
244
|
+
return {
|
|
245
|
+
version: [2, 3000, +clientRevision],
|
|
246
|
+
isLatest: true
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
return {
|
|
251
|
+
version: baileysVersion,
|
|
252
|
+
isLatest: false,
|
|
253
|
+
error
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
/** unique message tag prefix for MD clients */
|
|
258
|
+
export const generateMdTagPrefix = () => {
|
|
259
|
+
const bytes = randomBytes(4);
|
|
260
|
+
return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
|
|
261
|
+
};
|
|
262
|
+
const STATUS_MAP = {
|
|
263
|
+
sender: proto.WebMessageInfo.Status.SERVER_ACK,
|
|
264
|
+
played: proto.WebMessageInfo.Status.PLAYED,
|
|
265
|
+
read: proto.WebMessageInfo.Status.READ,
|
|
266
|
+
'read-self': proto.WebMessageInfo.Status.READ
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* Given a type of receipt, returns what the new status of the message should be
|
|
270
|
+
* @param type type from receipt
|
|
271
|
+
*/
|
|
272
|
+
export const getStatusFromReceiptType = (type) => {
|
|
273
|
+
const status = STATUS_MAP[type];
|
|
274
|
+
if (typeof type === 'undefined') {
|
|
275
|
+
return proto.WebMessageInfo.Status.DELIVERY_ACK;
|
|
276
|
+
}
|
|
277
|
+
return status;
|
|
278
|
+
};
|
|
279
|
+
const CODE_MAP = {
|
|
280
|
+
conflict: DisconnectReason.connectionReplaced
|
|
281
|
+
};
|
|
282
|
+
/**
|
|
283
|
+
* Stream errors generally provide a reason, map that to a baileys DisconnectReason
|
|
284
|
+
* @param reason the string reason given, eg. "conflict"
|
|
285
|
+
*/
|
|
286
|
+
export const getErrorCodeFromStreamError = (node) => {
|
|
287
|
+
const [reasonNode] = getAllBinaryNodeChildren(node);
|
|
288
|
+
let reason = reasonNode?.tag || 'unknown';
|
|
289
|
+
const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
|
|
290
|
+
if (statusCode === DisconnectReason.restartRequired) {
|
|
291
|
+
reason = 'restart required';
|
|
292
|
+
}
|
|
293
|
+
return {
|
|
294
|
+
reason,
|
|
295
|
+
statusCode
|
|
296
|
+
};
|
|
297
|
+
};
|
|
298
|
+
export const getCallStatusFromNode = ({ tag, attrs }) => {
|
|
299
|
+
let status;
|
|
300
|
+
switch (tag) {
|
|
301
|
+
case 'offer':
|
|
302
|
+
case 'offer_notice':
|
|
303
|
+
status = 'offer';
|
|
304
|
+
break;
|
|
305
|
+
case 'terminate':
|
|
306
|
+
if (attrs.reason === 'timeout') {
|
|
307
|
+
status = 'timeout';
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
//fired when accepted/rejected/timeout/caller hangs up
|
|
311
|
+
status = 'terminate';
|
|
312
|
+
}
|
|
313
|
+
break;
|
|
314
|
+
case 'reject':
|
|
315
|
+
status = 'reject';
|
|
316
|
+
break;
|
|
317
|
+
case 'accept':
|
|
318
|
+
status = 'accept';
|
|
319
|
+
break;
|
|
320
|
+
default:
|
|
321
|
+
status = 'ringing';
|
|
322
|
+
break;
|
|
323
|
+
}
|
|
324
|
+
return status;
|
|
325
|
+
};
|
|
326
|
+
const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
|
|
327
|
+
export const getCodeFromWSError = (error) => {
|
|
328
|
+
let statusCode = 500;
|
|
329
|
+
if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
|
|
330
|
+
const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
|
|
331
|
+
if (!Number.isNaN(code) && code >= 400) {
|
|
332
|
+
statusCode = code;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
else if (
|
|
336
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
337
|
+
error?.code?.startsWith('E') ||
|
|
338
|
+
error?.message?.includes('timed out')) {
|
|
339
|
+
// handle ETIMEOUT, ENOTFOUND etc
|
|
340
|
+
statusCode = 408;
|
|
341
|
+
}
|
|
342
|
+
return statusCode;
|
|
343
|
+
};
|
|
344
|
+
/**
|
|
345
|
+
* Is the given platform WA business
|
|
346
|
+
* @param platform AuthenticationCreds.platform
|
|
347
|
+
*/
|
|
348
|
+
export const isWABusinessPlatform = (platform) => {
|
|
349
|
+
return platform === 'smbi' || platform === 'smba';
|
|
350
|
+
};
|
|
351
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
352
|
+
export function trimUndefined(obj) {
|
|
353
|
+
for (const key in obj) {
|
|
354
|
+
if (typeof obj[key] === 'undefined') {
|
|
355
|
+
delete obj[key];
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return obj;
|
|
359
|
+
}
|
|
360
|
+
const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
|
|
361
|
+
export function bytesToCrockford(buffer) {
|
|
362
|
+
let value = 0;
|
|
363
|
+
let bitCount = 0;
|
|
364
|
+
const crockford = [];
|
|
365
|
+
for (const element of buffer) {
|
|
366
|
+
value = (value << 8) | (element & 0xff);
|
|
367
|
+
bitCount += 8;
|
|
368
|
+
while (bitCount >= 5) {
|
|
369
|
+
crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
|
|
370
|
+
bitCount -= 5;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (bitCount > 0) {
|
|
374
|
+
crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
|
|
375
|
+
}
|
|
376
|
+
return crockford.join('');
|
|
377
|
+
}
|
|
378
|
+
export function encodeNewsletterMessage(message) {
|
|
379
|
+
return proto.Message.encode(message).finish();
|
|
380
|
+
}
|
|
381
|
+
//# sourceMappingURL=generics.js.map
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { promisify } from 'util';
|
|
2
|
+
import { inflate } from 'zlib';
|
|
3
|
+
import { proto } from '../../WAProto/index.js';
|
|
4
|
+
import { WAMessageStubType } from '../Types/index.js';
|
|
5
|
+
import { toNumber } from './generics.js';
|
|
6
|
+
import { normalizeMessageContent } from './messages.js';
|
|
7
|
+
import { downloadContentFromMessage } from './messages-media.js';
|
|
8
|
+
const inflatePromise = promisify(inflate);
|
|
9
|
+
export const downloadHistory = async (msg, options) => {
|
|
10
|
+
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
|
|
11
|
+
const bufferArray = [];
|
|
12
|
+
for await (const chunk of stream) {
|
|
13
|
+
bufferArray.push(chunk);
|
|
14
|
+
}
|
|
15
|
+
let buffer = Buffer.concat(bufferArray);
|
|
16
|
+
// decompress buffer
|
|
17
|
+
buffer = await inflatePromise(buffer);
|
|
18
|
+
const syncData = proto.HistorySync.decode(buffer);
|
|
19
|
+
return syncData;
|
|
20
|
+
};
|
|
21
|
+
export const processHistoryMessage = (item) => {
|
|
22
|
+
const messages = [];
|
|
23
|
+
const contacts = [];
|
|
24
|
+
const chats = [];
|
|
25
|
+
switch (item.syncType) {
|
|
26
|
+
case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
|
|
27
|
+
case proto.HistorySync.HistorySyncType.RECENT:
|
|
28
|
+
case proto.HistorySync.HistorySyncType.FULL:
|
|
29
|
+
case proto.HistorySync.HistorySyncType.ON_DEMAND:
|
|
30
|
+
for (const chat of item.conversations) {
|
|
31
|
+
contacts.push({
|
|
32
|
+
id: chat.id,
|
|
33
|
+
name: chat.name || undefined,
|
|
34
|
+
lid: chat.lidJid || undefined,
|
|
35
|
+
phoneNumber: chat.pnJid || undefined
|
|
36
|
+
});
|
|
37
|
+
const msgs = chat.messages || [];
|
|
38
|
+
delete chat.messages;
|
|
39
|
+
for (const item of msgs) {
|
|
40
|
+
const message = item.message;
|
|
41
|
+
messages.push(message);
|
|
42
|
+
if (!chat.messages?.length) {
|
|
43
|
+
// keep only the most recent message in the chat array
|
|
44
|
+
chat.messages = [{ message }];
|
|
45
|
+
}
|
|
46
|
+
if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
|
|
47
|
+
chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
|
|
48
|
+
}
|
|
49
|
+
if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
|
|
50
|
+
message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
|
|
51
|
+
message.messageStubParameters?.[0]) {
|
|
52
|
+
contacts.push({
|
|
53
|
+
id: message.key.participant || message.key.remoteJid,
|
|
54
|
+
verifiedName: message.messageStubParameters?.[0]
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
chats.push({ ...chat });
|
|
59
|
+
}
|
|
60
|
+
break;
|
|
61
|
+
case proto.HistorySync.HistorySyncType.PUSH_NAME:
|
|
62
|
+
for (const c of item.pushnames) {
|
|
63
|
+
contacts.push({ id: c.id, notify: c.pushname });
|
|
64
|
+
}
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
chats,
|
|
69
|
+
contacts,
|
|
70
|
+
messages,
|
|
71
|
+
syncType: item.syncType,
|
|
72
|
+
progress: item.progress
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
export const downloadAndProcessHistorySyncNotification = async (msg, options) => {
|
|
76
|
+
const historyMsg = await downloadHistory(msg, options);
|
|
77
|
+
return processHistoryMessage(historyMsg);
|
|
78
|
+
};
|
|
79
|
+
export const getHistoryMsg = (message) => {
|
|
80
|
+
const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
|
|
81
|
+
const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
|
|
82
|
+
return anyHistoryMsg;
|
|
83
|
+
};
|
|
84
|
+
//# sourceMappingURL=history.js.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export * from './generics.js';
|
|
2
|
+
export * from './decode-wa-message.js';
|
|
3
|
+
export * from './messages.js';
|
|
4
|
+
export * from './messages-media.js';
|
|
5
|
+
export * from './validate-connection.js';
|
|
6
|
+
export * from './crypto.js';
|
|
7
|
+
export * from './signal.js';
|
|
8
|
+
export * from './noise-handler.js';
|
|
9
|
+
export * from './history.js';
|
|
10
|
+
export * from './chat-utils.js';
|
|
11
|
+
export * from './lt-hash.js';
|
|
12
|
+
export * from './auth-utils.js';
|
|
13
|
+
export * from './baileys-event-stream.js';
|
|
14
|
+
export * from './use-multi-file-auth-state.js';
|
|
15
|
+
export * from './link-preview.js';
|
|
16
|
+
export * from './event-buffer.js';
|
|
17
|
+
export * from './process-message.js';
|
|
18
|
+
export * from './message-retry-manager.js';
|
|
19
|
+
export * from './browser-utils.js';
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { prepareWAMessageMedia } from './messages.js';
|
|
2
|
+
import { extractImageThumb, getHttpStream } from './messages-media.js';
|
|
3
|
+
const THUMBNAIL_WIDTH_PX = 192;
|
|
4
|
+
/** Fetches an image and generates a thumbnail for it */
|
|
5
|
+
const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
|
|
6
|
+
const stream = await getHttpStream(url, fetchOpts);
|
|
7
|
+
const result = await extractImageThumb(stream, thumbnailWidth);
|
|
8
|
+
return result;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Given a piece of text, checks for any URL present, generates link preview for the same and returns it
|
|
12
|
+
* Return undefined if the fetch failed or no URL was found
|
|
13
|
+
* @param text first matched URL in text
|
|
14
|
+
* @returns the URL info required to generate link preview
|
|
15
|
+
*/
|
|
16
|
+
export const getUrlInfo = async (text, opts = {
|
|
17
|
+
thumbnailWidth: THUMBNAIL_WIDTH_PX,
|
|
18
|
+
fetchOpts: { timeout: 3000 }
|
|
19
|
+
}) => {
|
|
20
|
+
try {
|
|
21
|
+
// retries
|
|
22
|
+
const retries = 0;
|
|
23
|
+
const maxRetry = 5;
|
|
24
|
+
const { getLinkPreview } = await import('link-preview-js');
|
|
25
|
+
let previewLink = text;
|
|
26
|
+
if (!text.startsWith('https://') && !text.startsWith('http://')) {
|
|
27
|
+
previewLink = 'https://' + previewLink;
|
|
28
|
+
}
|
|
29
|
+
const info = await getLinkPreview(previewLink, {
|
|
30
|
+
...opts.fetchOpts,
|
|
31
|
+
followRedirects: 'follow',
|
|
32
|
+
handleRedirects: (baseURL, forwardedURL) => {
|
|
33
|
+
const urlObj = new URL(baseURL);
|
|
34
|
+
const forwardedURLObj = new URL(forwardedURL);
|
|
35
|
+
if (retries >= maxRetry) {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
if (forwardedURLObj.hostname === urlObj.hostname ||
|
|
39
|
+
forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
|
|
40
|
+
'www.' + forwardedURLObj.hostname === urlObj.hostname) {
|
|
41
|
+
retries + 1;
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
headers: opts.fetchOpts?.headers
|
|
49
|
+
});
|
|
50
|
+
if (info && 'title' in info && info.title) {
|
|
51
|
+
const [image] = info.images;
|
|
52
|
+
const urlInfo = {
|
|
53
|
+
'canonical-url': info.url,
|
|
54
|
+
'matched-text': text,
|
|
55
|
+
title: info.title,
|
|
56
|
+
description: info.description,
|
|
57
|
+
originalThumbnailUrl: image
|
|
58
|
+
};
|
|
59
|
+
if (opts.uploadImage) {
|
|
60
|
+
const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, {
|
|
61
|
+
upload: opts.uploadImage,
|
|
62
|
+
mediaTypeOverride: 'thumbnail-link',
|
|
63
|
+
options: opts.fetchOpts
|
|
64
|
+
});
|
|
65
|
+
urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined;
|
|
66
|
+
urlInfo.highQualityThumbnail = imageMessage || undefined;
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
try {
|
|
70
|
+
urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined;
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return urlInfo;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (!error.message.includes('receive a valid')) {
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
//# sourceMappingURL=link-preview.js.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { hkdf } from './crypto.js';
|
|
2
|
+
/**
|
|
3
|
+
* LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
|
|
4
|
+
* over a series of mutations. You can add/remove mutations and it'll return a hash equal to
|
|
5
|
+
* if the same series of mutations was made sequentially.
|
|
6
|
+
*/
|
|
7
|
+
const o = 128;
|
|
8
|
+
class LTHash {
|
|
9
|
+
constructor(e) {
|
|
10
|
+
this.salt = e;
|
|
11
|
+
}
|
|
12
|
+
async add(e, t) {
|
|
13
|
+
for (const item of t) {
|
|
14
|
+
e = await this._addSingle(e, item);
|
|
15
|
+
}
|
|
16
|
+
return e;
|
|
17
|
+
}
|
|
18
|
+
async subtract(e, t) {
|
|
19
|
+
for (const item of t) {
|
|
20
|
+
e = await this._subtractSingle(e, item);
|
|
21
|
+
}
|
|
22
|
+
return e;
|
|
23
|
+
}
|
|
24
|
+
async subtractThenAdd(e, addList, subtractList) {
|
|
25
|
+
const subtracted = await this.subtract(e, subtractList);
|
|
26
|
+
return this.add(subtracted, addList);
|
|
27
|
+
}
|
|
28
|
+
async _addSingle(e, t) {
|
|
29
|
+
const derived = new Uint8Array(await hkdf(Buffer.from(t), o, { info: this.salt })).buffer;
|
|
30
|
+
return this.performPointwiseWithOverflow(e, derived, (a, b) => a + b);
|
|
31
|
+
}
|
|
32
|
+
async _subtractSingle(e, t) {
|
|
33
|
+
const derived = new Uint8Array(await hkdf(Buffer.from(t), o, { info: this.salt })).buffer;
|
|
34
|
+
return this.performPointwiseWithOverflow(e, derived, (a, b) => a - b);
|
|
35
|
+
}
|
|
36
|
+
performPointwiseWithOverflow(e, t, op) {
|
|
37
|
+
const n = new DataView(e);
|
|
38
|
+
const i = new DataView(t);
|
|
39
|
+
const out = new ArrayBuffer(n.byteLength);
|
|
40
|
+
const s = new DataView(out);
|
|
41
|
+
for (let offset = 0; offset < n.byteLength; offset += 2) {
|
|
42
|
+
s.setUint16(offset, op(n.getUint16(offset, true), i.getUint16(offset, true)), true);
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export const LT_HASH_ANTI_TAMPERING = new LTHash('WhatsApp Patch Integrity');
|
|
48
|
+
//# sourceMappingURL=lt-hash.js.map
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const makeMutex = () => {
|
|
2
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3
|
+
let task = Promise.resolve();
|
|
4
|
+
let taskTimeout;
|
|
5
|
+
return {
|
|
6
|
+
mutex(code) {
|
|
7
|
+
task = (async () => {
|
|
8
|
+
// wait for the previous task to complete
|
|
9
|
+
// if there is an error, we swallow so as to not block the queue
|
|
10
|
+
try {
|
|
11
|
+
await task;
|
|
12
|
+
}
|
|
13
|
+
catch { }
|
|
14
|
+
try {
|
|
15
|
+
// execute the current task
|
|
16
|
+
const result = await code();
|
|
17
|
+
return result;
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
clearTimeout(taskTimeout);
|
|
21
|
+
}
|
|
22
|
+
})();
|
|
23
|
+
// we replace the existing task, appending the new piece of execution to it
|
|
24
|
+
// so the next task will have to wait for this one to finish
|
|
25
|
+
return task;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
export const makeKeyedMutex = () => {
|
|
30
|
+
const map = {};
|
|
31
|
+
return {
|
|
32
|
+
mutex(key, task) {
|
|
33
|
+
if (!map[key]) {
|
|
34
|
+
map[key] = makeMutex();
|
|
35
|
+
}
|
|
36
|
+
return map[key].mutex(task);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
//# sourceMappingURL=make-mutex.js.map
|