@vanzxy/baileys 1.4.0 → 1.4.2

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