@itsliaaa/baileys 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.
Files changed (103) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1078 -0
  3. package/WAProto/index.js +100441 -0
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/index.js +144 -0
  6. package/lib/Signal/Group/ciphertext-message.js +11 -0
  7. package/lib/Signal/Group/group-session-builder.js +29 -0
  8. package/lib/Signal/Group/group_cipher.js +81 -0
  9. package/lib/Signal/Group/index.js +11 -0
  10. package/lib/Signal/Group/keyhelper.js +17 -0
  11. package/lib/Signal/Group/sender-chain-key.js +25 -0
  12. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  13. package/lib/Signal/Group/sender-key-message.js +65 -0
  14. package/lib/Signal/Group/sender-key-name.js +47 -0
  15. package/lib/Signal/Group/sender-key-record.js +40 -0
  16. package/lib/Signal/Group/sender-key-state.js +83 -0
  17. package/lib/Signal/Group/sender-message-key.js +25 -0
  18. package/lib/Signal/libsignal.js +402 -0
  19. package/lib/Signal/lid-mapping.js +270 -0
  20. package/lib/Socket/Client/index.js +2 -0
  21. package/lib/Socket/Client/types.js +10 -0
  22. package/lib/Socket/Client/websocket.js +53 -0
  23. package/lib/Socket/business.js +378 -0
  24. package/lib/Socket/chats.js +1048 -0
  25. package/lib/Socket/communities.js +430 -0
  26. package/lib/Socket/groups.js +328 -0
  27. package/lib/Socket/index.js +11 -0
  28. package/lib/Socket/messages-recv.js +1442 -0
  29. package/lib/Socket/messages-send.js +1153 -0
  30. package/lib/Socket/mex.js +41 -0
  31. package/lib/Socket/newsletter.js +227 -0
  32. package/lib/Socket/socket.js +936 -0
  33. package/lib/Store/index.js +3 -0
  34. package/lib/Store/make-in-memory-store.js +421 -0
  35. package/lib/Store/make-ordered-dictionary.js +78 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Types/Auth.js +1 -0
  38. package/lib/Types/Bussines.js +1 -0
  39. package/lib/Types/Call.js +1 -0
  40. package/lib/Types/Chat.js +7 -0
  41. package/lib/Types/Contact.js +1 -0
  42. package/lib/Types/Events.js +1 -0
  43. package/lib/Types/GroupMetadata.js +1 -0
  44. package/lib/Types/Label.js +24 -0
  45. package/lib/Types/LabelAssociation.js +6 -0
  46. package/lib/Types/Message.js +17 -0
  47. package/lib/Types/Newsletter.js +33 -0
  48. package/lib/Types/Product.js +1 -0
  49. package/lib/Types/Signal.js +1 -0
  50. package/lib/Types/Socket.js +2 -0
  51. package/lib/Types/State.js +12 -0
  52. package/lib/Types/USync.js +1 -0
  53. package/lib/Types/index.js +25 -0
  54. package/lib/Utils/auth-utils.js +289 -0
  55. package/lib/Utils/browser-utils.js +28 -0
  56. package/lib/Utils/business.js +230 -0
  57. package/lib/Utils/chat-utils.js +811 -0
  58. package/lib/Utils/crypto.js +117 -0
  59. package/lib/Utils/decode-wa-message.js +282 -0
  60. package/lib/Utils/event-buffer.js +573 -0
  61. package/lib/Utils/generics.js +385 -0
  62. package/lib/Utils/history.js +130 -0
  63. package/lib/Utils/identity-change-handler.js +48 -0
  64. package/lib/Utils/index.js +19 -0
  65. package/lib/Utils/link-preview.js +84 -0
  66. package/lib/Utils/logger.js +2 -0
  67. package/lib/Utils/lt-hash.js +7 -0
  68. package/lib/Utils/make-mutex.js +32 -0
  69. package/lib/Utils/message-retry-manager.js +224 -0
  70. package/lib/Utils/messages-media.js +789 -0
  71. package/lib/Utils/messages.js +1832 -0
  72. package/lib/Utils/noise-handler.js +200 -0
  73. package/lib/Utils/pre-key-manager.js +105 -0
  74. package/lib/Utils/process-message.js +527 -0
  75. package/lib/Utils/reporting-utils.js +257 -0
  76. package/lib/Utils/signal.js +158 -0
  77. package/lib/Utils/sync-action-utils.js +47 -0
  78. package/lib/Utils/tc-token-utils.js +17 -0
  79. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  80. package/lib/Utils/validate-connection.js +206 -0
  81. package/lib/WABinary/constants.js +1300 -0
  82. package/lib/WABinary/decode.js +261 -0
  83. package/lib/WABinary/encode.js +219 -0
  84. package/lib/WABinary/generic-utils.js +197 -0
  85. package/lib/WABinary/index.js +5 -0
  86. package/lib/WABinary/jid-utils.js +95 -0
  87. package/lib/WABinary/types.js +1 -0
  88. package/lib/WAM/BinaryInfo.js +9 -0
  89. package/lib/WAM/constants.js +22852 -0
  90. package/lib/WAM/encode.js +149 -0
  91. package/lib/WAM/index.js +3 -0
  92. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  93. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  94. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  95. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  96. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  97. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  98. package/lib/WAUSync/Protocols/index.js +4 -0
  99. package/lib/WAUSync/USyncQuery.js +93 -0
  100. package/lib/WAUSync/USyncUser.js +22 -0
  101. package/lib/WAUSync/index.js +3 -0
  102. package/lib/index.js +11 -0
  103. package/package.json +72 -0
@@ -0,0 +1,385 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash, randomBytes } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ const baileysVersion = [2, 3000, 1034143497];
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?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
34
+ export const isStringNullOrEmpty = (value) =>
35
+ // eslint-disable-next-line eqeqeq
36
+ value == null || value === '';
37
+ export const writeRandomPadMax16 = (msg) => {
38
+ const pad = randomBytes(1);
39
+ const padLength = (pad[0] & 0x0f) + 1;
40
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
41
+ };
42
+ export const unpadRandomMax16 = (e) => {
43
+ const t = new Uint8Array(e);
44
+ if (0 === t.length) {
45
+ throw new Error('unpadPkcs7 given empty bytes');
46
+ }
47
+ var r = t[t.length - 1];
48
+ if (r > t.length) {
49
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
50
+ }
51
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
52
+ };
53
+ // code is inspired by whatsmeow
54
+ export const generateParticipantHashV2 = (participants) => {
55
+ participants.sort();
56
+ const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
57
+ return '2:' + sha256Hash.slice(0, 6);
58
+ };
59
+ export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
60
+ export const generateRegistrationId = () => {
61
+ return Uint16Array.from(randomBytes(2))[0] & 16383;
62
+ };
63
+ export const encodeBigEndian = (e, t = 4) => {
64
+ let r = e;
65
+ const a = new Uint8Array(t);
66
+ for (let i = t - 1; i >= 0; i--) {
67
+ a[i] = 255 & r;
68
+ r >>>= 8;
69
+ }
70
+ return a;
71
+ };
72
+ export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
73
+ /** unix timestamp of a date in seconds */
74
+ export const unixTimestampSeconds = (date = Date.now()) => date / 1000 | 0; // Changed from new Date → Date.now for faster operation
75
+ export const debouncedTimeout = (intervalMs = 1000, task) => {
76
+ let timeout;
77
+ return {
78
+ start: (newIntervalMs, newTask) => {
79
+ task = newTask || task;
80
+ intervalMs = newIntervalMs || intervalMs;
81
+ timeout && clearTimeout(timeout);
82
+ timeout = setTimeout(() => task?.(), intervalMs);
83
+ },
84
+ cancel: () => {
85
+ timeout && clearTimeout(timeout);
86
+ timeout = undefined;
87
+ },
88
+ setTask: (newTask) => (task = newTask),
89
+ setInterval: (newInterval) => (intervalMs = newInterval)
90
+ };
91
+ };
92
+ export const delay = (ms) => delayCancellable(ms).delay;
93
+ export const delayCancellable = (ms) => {
94
+ const stack = new Error().stack;
95
+ let timeout;
96
+ let reject;
97
+ const delay = new Promise((resolve, _reject) => {
98
+ timeout = setTimeout(resolve, ms);
99
+ reject = _reject;
100
+ });
101
+ const cancel = () => {
102
+ clearTimeout(timeout);
103
+ reject(new Boom('Cancelled', {
104
+ statusCode: 500,
105
+ data: {
106
+ stack
107
+ }
108
+ }));
109
+ };
110
+ return { delay, cancel };
111
+ };
112
+ export async function promiseTimeout(ms, promise) {
113
+ if (!ms) {
114
+ return new Promise(promise);
115
+ }
116
+ const stack = new Error().stack;
117
+ // Create a promise that rejects in <ms> milliseconds
118
+ const { delay, cancel } = delayCancellable(ms);
119
+ const p = new Promise((resolve, reject) => {
120
+ delay
121
+ .then(() => reject(new Boom('Timed Out', {
122
+ statusCode: DisconnectReason.timedOut,
123
+ data: {
124
+ stack
125
+ }
126
+ })))
127
+ .catch(err => reject(err));
128
+ promise(resolve, reject);
129
+ }).finally(cancel);
130
+ return p;
131
+ }
132
+ // inspired from whatsmeow code
133
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
134
+ export const generateMessageIDV2 = (userId) => {
135
+ const data = Buffer.allocUnsafe(8 + 20 + 16);
136
+ data.writeBigUInt64BE(BigInt(unixTimestampSeconds()));
137
+ if (userId) {
138
+ const id = jidDecode(userId);
139
+ if (id?.user) {
140
+ const len = data.write(id.user, 8);
141
+ data.write('@c.us', 8 + len);
142
+ }
143
+ }
144
+ randomBytes(16).copy(data, 28);
145
+ const hash = createHash('sha256').update(data).digest();
146
+ const hex = hash.toString('hex').toUpperCase();
147
+ const baseId = '3EB0' + hex.substring(0, 18);
148
+ const pos = 4 + (hash[0] & 15);
149
+ return baseId.slice(0, pos) + 'STARFALL' + baseId.slice(pos);
150
+ };
151
+ // generate a random ID to attach to a message
152
+ export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase();
153
+ export function bindWaitForEvent(ev, event) {
154
+ return async (check, timeoutMs) => {
155
+ let listener;
156
+ let closeListener;
157
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
158
+ closeListener = ({ connection, lastDisconnect }) => {
159
+ if (connection === 'close') {
160
+ reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
161
+ }
162
+ };
163
+ ev.on('connection.update', closeListener);
164
+ listener = async (update) => {
165
+ if (await check(update)) {
166
+ resolve();
167
+ }
168
+ };
169
+ ev.on(event, listener);
170
+ }).finally(() => {
171
+ ev.off(event, listener);
172
+ ev.off('connection.update', closeListener);
173
+ });
174
+ };
175
+ }
176
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
177
+ /**
178
+ * utility that fetches latest baileys version from the master branch.
179
+ * Use to ensure your WA connection is always on the latest version
180
+ */
181
+ export const fetchLatestBaileysVersion = async (options = {}) => {
182
+ const URL = 'https://raw.githubusercontent.com/itsliaaa/baileys/main/lib/Defaults/index.js';
183
+ try {
184
+ const response = await fetch(URL, {
185
+ dispatcher: options.dispatcher,
186
+ method: 'GET',
187
+ headers: options.headers
188
+ });
189
+ if (!response.ok) {
190
+ throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
191
+ }
192
+ const text = await response.text();
193
+ // Extract version from line 5 (const version = [...])
194
+ const lines = text.split('\n');
195
+ const versionLine = lines[4]; // Line 5 (0-indexed)
196
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
197
+ if (versionMatch) {
198
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
199
+ return {
200
+ version,
201
+ isLatest: true
202
+ };
203
+ }
204
+ else {
205
+ throw new Error('Could not parse version from Defaults/index.ts');
206
+ }
207
+ }
208
+ catch (error) {
209
+ return {
210
+ version: baileysVersion,
211
+ isLatest: false,
212
+ error
213
+ };
214
+ }
215
+ };
216
+ /**
217
+ * A utility that fetches the latest web version of whatsapp.
218
+ * Use to ensure your WA connection is always on the latest version
219
+ */
220
+ export const fetchLatestWaWebVersion = async (options = {}) => {
221
+ try {
222
+ // Absolute minimal headers required to bypass anti-bot detection
223
+ const defaultHeaders = {
224
+ 'sec-fetch-site': 'none',
225
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
226
+ };
227
+ const headers = { ...defaultHeaders, ...options.headers };
228
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
229
+ ...options,
230
+ method: 'GET',
231
+ headers
232
+ });
233
+ if (!response.ok) {
234
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
235
+ }
236
+ const data = await response.text();
237
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
238
+ const match = data.match(regex);
239
+ if (!match?.[1]) {
240
+ return {
241
+ version: baileysVersion,
242
+ isLatest: false,
243
+ error: {
244
+ message: 'Could not find client revision in the fetched content'
245
+ }
246
+ };
247
+ }
248
+ const clientRevision = match[1];
249
+ return {
250
+ version: [2, 3000, +clientRevision],
251
+ isLatest: true
252
+ };
253
+ }
254
+ catch (error) {
255
+ return {
256
+ version: baileysVersion,
257
+ isLatest: false,
258
+ error
259
+ };
260
+ }
261
+ };
262
+ /** unique message tag prefix for MD clients */
263
+ export const generateMdTagPrefix = () => {
264
+ const bytes = randomBytes(4);
265
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
266
+ };
267
+ const STATUS_MAP = {
268
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
269
+ played: proto.WebMessageInfo.Status.PLAYED,
270
+ read: proto.WebMessageInfo.Status.READ,
271
+ 'read-self': proto.WebMessageInfo.Status.READ
272
+ };
273
+ /**
274
+ * Given a type of receipt, returns what the new status of the message should be
275
+ * @param type type from receipt
276
+ */
277
+ export const getStatusFromReceiptType = (type) => {
278
+ const status = STATUS_MAP[type];
279
+ if (typeof type === 'undefined') {
280
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
281
+ }
282
+ return status;
283
+ };
284
+ const CODE_MAP = {
285
+ conflict: DisconnectReason.connectionReplaced
286
+ };
287
+ /**
288
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
289
+ * @param reason the string reason given, eg. "conflict"
290
+ */
291
+ export const getErrorCodeFromStreamError = (node) => {
292
+ const [reasonNode] = getAllBinaryNodeChildren(node);
293
+ let reason = reasonNode?.tag || 'unknown';
294
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
295
+ if (statusCode === DisconnectReason.restartRequired) {
296
+ reason = 'restart required';
297
+ }
298
+ return {
299
+ reason,
300
+ statusCode
301
+ };
302
+ };
303
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
304
+ let status;
305
+ switch (tag) {
306
+ case 'offer':
307
+ case 'offer_notice':
308
+ status = 'offer';
309
+ break;
310
+ case 'terminate':
311
+ if (attrs.reason === 'timeout') {
312
+ status = 'timeout';
313
+ }
314
+ else {
315
+ //fired when accepted/rejected/timeout/caller hangs up
316
+ status = 'terminate';
317
+ }
318
+ break;
319
+ case 'reject':
320
+ status = 'reject';
321
+ break;
322
+ case 'accept':
323
+ status = 'accept';
324
+ break;
325
+ default:
326
+ status = 'ringing';
327
+ break;
328
+ }
329
+ return status;
330
+ };
331
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
332
+ export const getCodeFromWSError = (error) => {
333
+ let statusCode = 500;
334
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
335
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
336
+ if (!Number.isNaN(code) && code >= 400) {
337
+ statusCode = code;
338
+ }
339
+ }
340
+ else if (
341
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
342
+ error?.code?.startsWith('E') ||
343
+ error?.message?.includes('timed out')) {
344
+ // handle ETIMEOUT, ENOTFOUND etc
345
+ statusCode = 408;
346
+ }
347
+ return statusCode;
348
+ };
349
+ /**
350
+ * Is the given platform WA business
351
+ * @param platform AuthenticationCreds.platform
352
+ */
353
+ export const isWABusinessPlatform = (platform) => {
354
+ return platform === 'smbi' || platform === 'smba';
355
+ };
356
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
357
+ export function trimUndefined(obj) {
358
+ for (const key in obj) {
359
+ if (typeof obj[key] === 'undefined') {
360
+ delete obj[key];
361
+ }
362
+ }
363
+ return obj;
364
+ }
365
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
366
+ export function bytesToCrockford(buffer) {
367
+ let value = 0;
368
+ let bitCount = 0;
369
+ const crockford = [];
370
+ for (const element of buffer) {
371
+ value = (value << 8) | (element & 0xff);
372
+ bitCount += 8;
373
+ while (bitCount >= 5) {
374
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
375
+ bitCount -= 5;
376
+ }
377
+ }
378
+ if (bitCount > 0) {
379
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
380
+ }
381
+ return crockford.join('');
382
+ }
383
+ export function encodeNewsletterMessage(message) {
384
+ return proto.Message.encode(message).finish();
385
+ }
@@ -0,0 +1,130 @@
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 { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/index.js';
6
+ import { toNumber } from './generics.js';
7
+ import { normalizeMessageContent } from './messages.js';
8
+ import { downloadContentFromMessage } from './messages-media.js';
9
+ const inflatePromise = promisify(inflate);
10
+ const extractPnFromMessages = (messages) => {
11
+ for (const msgItem of messages) {
12
+ const message = msgItem.message;
13
+ // Only extract from outgoing messages (fromMe: true) in 1:1 chats
14
+ // because userReceipt.userJid is the recipient's JID
15
+ if (!message?.key?.fromMe || !message.userReceipt?.length) {
16
+ continue;
17
+ }
18
+ const userJid = message.userReceipt[0]?.userJid;
19
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
20
+ return userJid;
21
+ }
22
+ }
23
+ return undefined;
24
+ };
25
+ export const downloadHistory = async (msg, options) => {
26
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
27
+ const bufferArray = [];
28
+ for await (const chunk of stream) {
29
+ bufferArray.push(chunk);
30
+ }
31
+ let buffer = Buffer.concat(bufferArray);
32
+ // decompress buffer
33
+ buffer = await inflatePromise(buffer);
34
+ const syncData = proto.HistorySync.decode(buffer);
35
+ return syncData;
36
+ };
37
+ export const processHistoryMessage = (item, logger) => {
38
+ const messages = [];
39
+ const contacts = [];
40
+ const chats = [];
41
+ const lidPnMappings = [];
42
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
43
+ // Extract LID-PN mappings for all sync types
44
+ for (const m of item.phoneNumberToLidMappings || []) {
45
+ if (m.lidJid && m.pnJid) {
46
+ lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
47
+ }
48
+ }
49
+ switch (item.syncType) {
50
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
51
+ case proto.HistorySync.HistorySyncType.RECENT:
52
+ case proto.HistorySync.HistorySyncType.FULL:
53
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
54
+ for (const chat of item.conversations) {
55
+ contacts.push({
56
+ id: chat.id,
57
+ name: chat.displayName || chat.name || chat.username || undefined,
58
+ lid: chat.lidJid || chat.accountLid || undefined,
59
+ phoneNumber: chat.pnJid || undefined
60
+ });
61
+ const chatId = chat.id;
62
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
63
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
64
+ if (isLid && chat.pnJid) {
65
+ lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
66
+ }
67
+ else if (isPn && chat.lidJid) {
68
+ lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
69
+ }
70
+ else if (isLid && !chat.pnJid) {
71
+ // Fallback: extract PN from userReceipt in messages when pnJid is missing
72
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
73
+ if (pnFromReceipt) {
74
+ lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
75
+ }
76
+ }
77
+ const msgs = chat.messages || [];
78
+ delete chat.messages;
79
+ for (const item of msgs) {
80
+ const message = item.message;
81
+ messages.push(message);
82
+ if (!chat.messages?.length) {
83
+ // keep only the most recent message in the chat array
84
+ chat.messages = [{ message }];
85
+ }
86
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
87
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
88
+ }
89
+ if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
90
+ message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
91
+ message.messageStubParameters?.[0]) {
92
+ contacts.push({
93
+ id: message.key.participant || message.key.remoteJid,
94
+ verifiedName: message.messageStubParameters?.[0]
95
+ });
96
+ }
97
+ }
98
+ chats.push({ ...chat });
99
+ }
100
+ break;
101
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
102
+ for (const c of item.pushnames) {
103
+ contacts.push({ id: c.id, notify: c.pushname });
104
+ }
105
+ break;
106
+ }
107
+ return {
108
+ chats,
109
+ contacts,
110
+ messages,
111
+ lidPnMappings,
112
+ syncType: item.syncType,
113
+ progress: item.progress
114
+ };
115
+ };
116
+ export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
117
+ let historyMsg;
118
+ if (msg.initialHistBootstrapInlinePayload) {
119
+ historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
120
+ }
121
+ else {
122
+ historyMsg = await downloadHistory(msg, options);
123
+ }
124
+ return processHistoryMessage(historyMsg, logger);
125
+ };
126
+ export const getHistoryMsg = (message) => {
127
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
128
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
129
+ return anyHistoryMsg;
130
+ };
@@ -0,0 +1,48 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { areJidsSameUser, getBinaryNodeChild, jidDecode } from '../WABinary/index.js';
3
+ import { isStringNullOrEmpty } from './generics.js';
4
+ export async function handleIdentityChange(node, ctx) {
5
+ const from = node.attrs.from;
6
+ if (!from) {
7
+ return { action: 'invalid_notification' };
8
+ }
9
+ const identityNode = getBinaryNodeChild(node, 'identity');
10
+ if (!identityNode) {
11
+ return { action: 'no_identity_node' };
12
+ }
13
+ ctx.logger.info({ jid: from }, 'identity changed');
14
+ const decoded = jidDecode(from);
15
+ if (decoded?.device && decoded.device !== 0) {
16
+ ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device');
17
+ return { action: 'skipped_companion_device', device: decoded.device };
18
+ }
19
+ const isSelfPrimary = ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)));
20
+ if (isSelfPrimary) {
21
+ ctx.logger.info({ jid: from }, 'self primary identity changed');
22
+ return { action: 'skipped_self_primary' };
23
+ }
24
+ if (ctx.debounceCache.get(from)) {
25
+ ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)');
26
+ return { action: 'debounced' };
27
+ }
28
+ ctx.debounceCache.set(from, true);
29
+ const isOfflineNotification = !isStringNullOrEmpty(node.attrs.offline);
30
+ const hasExistingSession = await ctx.validateSession(from);
31
+ if (!hasExistingSession.exists) {
32
+ ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh');
33
+ return { action: 'skipped_no_session' };
34
+ }
35
+ ctx.logger.debug({ jid: from }, 'old session exists, will refresh session');
36
+ if (isOfflineNotification) {
37
+ ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing');
38
+ return { action: 'skipped_offline' };
39
+ }
40
+ try {
41
+ await ctx.assertSessions([from], true);
42
+ return { action: 'session_refreshed' };
43
+ }
44
+ catch (error) {
45
+ ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change');
46
+ return { action: 'session_refresh_failed', error };
47
+ }
48
+ }
@@ -0,0 +1,19 @@
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 './use-multi-file-auth-state.js';
14
+ export * from './link-preview.js';
15
+ export * from './event-buffer.js';
16
+ export * from './process-message.js';
17
+ export * from './message-retry-manager.js';
18
+ export * from './browser-utils.js';
19
+ export * from './identity-change-handler.js';
@@ -0,0 +1,84 @@
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
+ };
@@ -0,0 +1,2 @@
1
+ import P from 'pino';
2
+ export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
@@ -0,0 +1,7 @@
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
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
+ export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();