@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.
Files changed (101) hide show
  1. package/README.md +1573 -0
  2. package/WAProto/fix-imports.js +29 -0
  3. package/WAProto/index.js +169659 -0
  4. package/lib/Defaults/index.js +115 -0
  5. package/lib/Signal/Group/ciphertext-message.js +12 -0
  6. package/lib/Signal/Group/group-session-builder.js +30 -0
  7. package/lib/Signal/Group/group_cipher.js +82 -0
  8. package/lib/Signal/Group/index.js +12 -0
  9. package/lib/Signal/Group/keyhelper.js +18 -0
  10. package/lib/Signal/Group/sender-chain-key.js +26 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  12. package/lib/Signal/Group/sender-key-message.js +66 -0
  13. package/lib/Signal/Group/sender-key-name.js +48 -0
  14. package/lib/Signal/Group/sender-key-record.js +41 -0
  15. package/lib/Signal/Group/sender-key-state.js +84 -0
  16. package/lib/Signal/Group/sender-message-key.js +26 -0
  17. package/lib/Signal/libsignal.js +342 -0
  18. package/lib/Signal/lid-mapping.js +171 -0
  19. package/lib/Socket/Client/index.js +3 -0
  20. package/lib/Socket/Client/types.js +11 -0
  21. package/lib/Socket/Client/websocket.js +91 -0
  22. package/lib/Socket/business.js +376 -0
  23. package/lib/Socket/chats.js +963 -0
  24. package/lib/Socket/communities.js +431 -0
  25. package/lib/Socket/groups.js +328 -0
  26. package/lib/Socket/index.js +19 -0
  27. package/lib/Socket/messages-recv.js +1240 -0
  28. package/lib/Socket/messages-send.js +1370 -0
  29. package/lib/Socket/mex.js +42 -0
  30. package/lib/Socket/newsletter.js +202 -0
  31. package/lib/Socket/nexus-handler.js +667 -0
  32. package/lib/Socket/socket.js +871 -0
  33. package/lib/Store/index.js +4 -0
  34. package/lib/Store/make-cache-manager-store.js +81 -0
  35. package/lib/Store/make-in-memory-store.js +416 -0
  36. package/lib/Store/make-ordered-dictionary.js +82 -0
  37. package/lib/Store/object-repository.js +31 -0
  38. package/lib/Types/Auth.js +2 -0
  39. package/lib/Types/Bussines.js +2 -0
  40. package/lib/Types/Call.js +2 -0
  41. package/lib/Types/Chat.js +8 -0
  42. package/lib/Types/Contact.js +2 -0
  43. package/lib/Types/Events.js +2 -0
  44. package/lib/Types/GroupMetadata.js +2 -0
  45. package/lib/Types/Label.js +25 -0
  46. package/lib/Types/LabelAssociation.js +7 -0
  47. package/lib/Types/Message.js +11 -0
  48. package/lib/Types/Newsletter.js +31 -0
  49. package/lib/Types/Product.js +2 -0
  50. package/lib/Types/Signal.js +2 -0
  51. package/lib/Types/Socket.js +3 -0
  52. package/lib/Types/State.js +13 -0
  53. package/lib/Types/USync.js +2 -0
  54. package/lib/Types/index.js +26 -0
  55. package/lib/Utils/auth-utils.js +257 -0
  56. package/lib/Utils/baileys-event-stream.js +56 -0
  57. package/lib/Utils/browser-utils.js +28 -0
  58. package/lib/Utils/business.js +231 -0
  59. package/lib/Utils/chat-utils.js +763 -0
  60. package/lib/Utils/crypto.js +142 -0
  61. package/lib/Utils/decode-wa-message.js +279 -0
  62. package/lib/Utils/event-buffer.js +548 -0
  63. package/lib/Utils/generics.js +381 -0
  64. package/lib/Utils/history.js +84 -0
  65. package/lib/Utils/index.js +20 -0
  66. package/lib/Utils/link-preview.js +85 -0
  67. package/lib/Utils/logger.js +3 -0
  68. package/lib/Utils/lt-hash.js +48 -0
  69. package/lib/Utils/make-mutex.js +40 -0
  70. package/lib/Utils/message-retry-manager.js +149 -0
  71. package/lib/Utils/messages-media.js +685 -0
  72. package/lib/Utils/messages.js +820 -0
  73. package/lib/Utils/noise-handler.js +147 -0
  74. package/lib/Utils/pre-key-manager.js +106 -0
  75. package/lib/Utils/process-message.js +413 -0
  76. package/lib/Utils/signal.js +159 -0
  77. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  78. package/lib/Utils/validate-connection.js +195 -0
  79. package/lib/WABinary/constants.js +1301 -0
  80. package/lib/WABinary/decode.js +238 -0
  81. package/lib/WABinary/encode.js +216 -0
  82. package/lib/WABinary/generic-utils.js +111 -0
  83. package/lib/WABinary/index.js +6 -0
  84. package/lib/WABinary/jid-utils.js +96 -0
  85. package/lib/WABinary/types.js +2 -0
  86. package/lib/WAM/BinaryInfo.js +10 -0
  87. package/lib/WAM/constants.js +22853 -0
  88. package/lib/WAM/encode.js +150 -0
  89. package/lib/WAM/index.js +4 -0
  90. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  91. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  92. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  93. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  94. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  95. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  96. package/lib/WAUSync/Protocols/index.js +5 -0
  97. package/lib/WAUSync/USyncQuery.js +94 -0
  98. package/lib/WAUSync/USyncUser.js +23 -0
  99. package/lib/WAUSync/index.js +4 -0
  100. package/lib/index.js +24 -0
  101. package/package.json +113 -0
@@ -0,0 +1,1240 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import Long from 'long';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT } from '../Defaults/index.js';
7
+ import { WAMessageStatus, WAMessageStubType } from '../Types/index.js';
8
+ import { aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
9
+ import { makeMutex } from '../Utils/make-mutex.js';
10
+ import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { extractGroupMetadata } from './groups.js';
12
+ import { makeMessagesSocket } from './messages-send.js';
13
+ export const makeMessagesRecvSocket = (config) => {
14
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
15
+ const sock = makeMessagesSocket(config);
16
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
17
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
18
+ const retryMutex = makeMutex();
19
+ const msgRetryCache = config.msgRetryCounterCache ||
20
+ new NodeCache({
21
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
22
+ useClones: false
23
+ });
24
+ const callOfferCache = config.callOfferCache ||
25
+ new NodeCache({
26
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
27
+ useClones: false
28
+ });
29
+ const placeholderResendCache = config.placeholderResendCache ||
30
+ new NodeCache({
31
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
32
+ useClones: false
33
+ });
34
+ let sendActiveReceipts = false;
35
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
36
+ if (!authState.creds.me?.id) {
37
+ throw new Boom('Not authenticated');
38
+ }
39
+ const pdoMessage = {
40
+ historySyncOnDemandRequest: {
41
+ chatJid: oldestMsgKey.remoteJid,
42
+ oldestMsgFromMe: oldestMsgKey.fromMe,
43
+ oldestMsgId: oldestMsgKey.id,
44
+ oldestMsgTimestampMs: oldestMsgTimestamp,
45
+ onDemandMsgCount: count
46
+ },
47
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
48
+ };
49
+ return sendPeerDataOperationMessage(pdoMessage);
50
+ };
51
+ const requestPlaceholderResend = async (messageKey) => {
52
+ if (!authState.creds.me?.id) {
53
+ throw new Boom('Not authenticated');
54
+ }
55
+ if (placeholderResendCache.get(messageKey?.id)) {
56
+ logger.debug({ messageKey }, 'already requested resend');
57
+ return;
58
+ }
59
+ else {
60
+ placeholderResendCache.set(messageKey?.id, true);
61
+ }
62
+ await delay(5000);
63
+ if (!placeholderResendCache.get(messageKey?.id)) {
64
+ logger.debug({ messageKey }, 'message received while resend requested');
65
+ return 'RESOLVED';
66
+ }
67
+ const pdoMessage = {
68
+ placeholderMessageResendRequest: [
69
+ {
70
+ messageKey
71
+ }
72
+ ],
73
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
74
+ };
75
+ setTimeout(() => {
76
+ if (placeholderResendCache.get(messageKey?.id)) {
77
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
78
+ placeholderResendCache.del(messageKey?.id);
79
+ }
80
+ }, 15000);
81
+ return sendPeerDataOperationMessage(pdoMessage);
82
+ };
83
+ // Handles mex newsletter notifications
84
+ const handleMexNewsletterNotification = async (node) => {
85
+ const mexNode = getBinaryNodeChild(node, 'mex');
86
+ if (!mexNode?.content) {
87
+ logger.warn({ node }, 'Invalid mex newsletter notification');
88
+ return;
89
+ }
90
+ let data;
91
+ try {
92
+ data = JSON.parse(mexNode.content.toString());
93
+ }
94
+ catch (error) {
95
+ logger.error({ err: error, node }, 'Failed to parse mex newsletter notification');
96
+ return;
97
+ }
98
+ const operation = data?.operation;
99
+ const updates = data?.updates;
100
+ if (!updates || !operation) {
101
+ logger.warn({ data }, 'Invalid mex newsletter notification content');
102
+ return;
103
+ }
104
+ logger.info({ operation, updates }, 'got mex newsletter notification');
105
+ switch (operation) {
106
+ case 'NotificationNewsletterUpdate':
107
+ for (const update of updates) {
108
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
109
+ ev.emit('newsletter-settings.update', {
110
+ id: update.jid,
111
+ update: update.settings
112
+ });
113
+ }
114
+ }
115
+ break;
116
+ case 'NotificationNewsletterAdminPromote':
117
+ for (const update of updates) {
118
+ if (update.jid && update.user) {
119
+ ev.emit('newsletter-participants.update', {
120
+ id: update.jid,
121
+ author: node.attrs.from,
122
+ user: update.user,
123
+ new_role: 'ADMIN',
124
+ action: 'promote'
125
+ });
126
+ }
127
+ }
128
+ break;
129
+ default:
130
+ logger.info({ operation, data }, 'Unhandled mex newsletter notification');
131
+ break;
132
+ }
133
+ };
134
+ // Handles newsletter notifications
135
+ const handleNewsletterNotification = async (node) => {
136
+ const from = node.attrs.from;
137
+ const child = getAllBinaryNodeChildren(node)[0];
138
+ const author = node.attrs.participant;
139
+ logger.info({ from, child }, 'got newsletter notification');
140
+ switch (child.tag) {
141
+ case 'reaction':
142
+ const reactionUpdate = {
143
+ id: from,
144
+ server_id: child.attrs.message_id,
145
+ reaction: {
146
+ code: getBinaryNodeChildString(child, 'reaction'),
147
+ count: 1
148
+ }
149
+ };
150
+ ev.emit('newsletter.reaction', reactionUpdate);
151
+ break;
152
+ case 'view':
153
+ const viewUpdate = {
154
+ id: from,
155
+ server_id: child.attrs.message_id,
156
+ count: parseInt(child.content?.toString() || '0', 10)
157
+ };
158
+ ev.emit('newsletter.view', viewUpdate);
159
+ break;
160
+ case 'participant':
161
+ const participantUpdate = {
162
+ id: from,
163
+ author,
164
+ user: child.attrs.jid,
165
+ action: child.attrs.action,
166
+ new_role: child.attrs.role
167
+ };
168
+ ev.emit('newsletter-participants.update', participantUpdate);
169
+ break;
170
+ case 'update':
171
+ const settingsNode = getBinaryNodeChild(child, 'settings');
172
+ if (settingsNode) {
173
+ const update = {};
174
+ const nameNode = getBinaryNodeChild(settingsNode, 'name');
175
+ if (nameNode?.content)
176
+ update.name = nameNode.content.toString();
177
+ const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
178
+ if (descriptionNode?.content)
179
+ update.description = descriptionNode.content.toString();
180
+ ev.emit('newsletter-settings.update', {
181
+ id: from,
182
+ update
183
+ });
184
+ }
185
+ break;
186
+ case 'message':
187
+ const plaintextNode = getBinaryNodeChild(child, 'plaintext');
188
+ if (plaintextNode?.content) {
189
+ try {
190
+ const contentBuf = typeof plaintextNode.content === 'string'
191
+ ? Buffer.from(plaintextNode.content, 'binary')
192
+ : Buffer.from(plaintextNode.content);
193
+ const messageProto = proto.Message.decode(contentBuf).toJSON();
194
+ const fullMessage = proto.WebMessageInfo.fromObject({
195
+ key: {
196
+ remoteJid: from,
197
+ id: child.attrs.message_id || child.attrs.server_id,
198
+ fromMe: false // TODO: is this really true though
199
+ },
200
+ message: messageProto,
201
+ messageTimestamp: +child.attrs.t
202
+ }).toJSON();
203
+ await upsertMessage(fullMessage, 'append');
204
+ logger.info('Processed plaintext newsletter message');
205
+ }
206
+ catch (error) {
207
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
208
+ }
209
+ }
210
+ break;
211
+ default:
212
+ logger.warn({ node }, 'Unknown newsletter notification');
213
+ break;
214
+ }
215
+ };
216
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
217
+ const stanza = {
218
+ tag: 'ack',
219
+ attrs: {
220
+ id: attrs.id,
221
+ to: attrs.from,
222
+ class: tag
223
+ }
224
+ };
225
+ if (!!errorCode) {
226
+ stanza.attrs.error = errorCode.toString();
227
+ }
228
+ if (!!attrs.participant) {
229
+ stanza.attrs.participant = attrs.participant;
230
+ }
231
+ if (!!attrs.recipient) {
232
+ stanza.attrs.recipient = attrs.recipient;
233
+ }
234
+ if (!!attrs.type &&
235
+ (tag !== 'message' || getBinaryNodeChild({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
236
+ stanza.attrs.type = attrs.type;
237
+ }
238
+ if (tag === 'message' && getBinaryNodeChild({ tag, attrs, content }, 'unavailable')) {
239
+ stanza.attrs.from = authState.creds.me.id;
240
+ }
241
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
242
+ try {
243
+ await sendNode(stanza);
244
+ } catch (error) {
245
+ // Handle connection closed errors gracefully
246
+ // Don't crash if ACK fails - the message was already received
247
+ if (error?.output?.statusCode === 428 || error?.message?.includes('Connection')) {
248
+ logger.warn({ id: attrs.id, error: error?.message }, 'Failed to send ACK (connection closed) - message already received');
249
+ // Silently continue instead of throwing
250
+ } else {
251
+ // Re-throw other errors
252
+ throw error;
253
+ }
254
+ }
255
+ };
256
+ const rejectCall = async (callId, callFrom) => {
257
+ const stanza = {
258
+ tag: 'call',
259
+ attrs: {
260
+ from: authState.creds.me.id,
261
+ to: callFrom
262
+ },
263
+ content: [
264
+ {
265
+ tag: 'reject',
266
+ attrs: {
267
+ 'call-id': callId,
268
+ 'call-creator': callFrom,
269
+ count: '0'
270
+ },
271
+ content: undefined
272
+ }
273
+ ]
274
+ };
275
+ await query(stanza);
276
+ };
277
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
278
+ const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
279
+ const { key: msgKey } = fullMessage;
280
+ const msgId = msgKey.id;
281
+ if (messageRetryManager) {
282
+ // Check if we've exceeded max retries using the new system
283
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
284
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
285
+ messageRetryManager.markRetryFailed(msgId);
286
+ return;
287
+ }
288
+ // Increment retry count using new system
289
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
290
+ // Use the new retry count for the rest of the logic
291
+ const key = `${msgId}:${msgKey?.participant}`;
292
+ msgRetryCache.set(key, retryCount);
293
+ }
294
+ else {
295
+ // Fallback to old system
296
+ const key = `${msgId}:${msgKey?.participant}`;
297
+ let retryCount = (await msgRetryCache.get(key)) || 0;
298
+ if (retryCount >= maxMsgRetryCount) {
299
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
300
+ msgRetryCache.del(key);
301
+ return;
302
+ }
303
+ retryCount += 1;
304
+ await msgRetryCache.set(key, retryCount);
305
+ }
306
+ const key = `${msgId}:${msgKey?.participant}`;
307
+ const retryCount = (await msgRetryCache.get(key)) || 1;
308
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
309
+ const fromJid = node.attrs.from;
310
+ // Check if we should recreate the session
311
+ let shouldRecreateSession = false;
312
+ let recreateReason = '';
313
+ if (enableAutoSessionRecreation && messageRetryManager) {
314
+ try {
315
+ // Check if we have a session with this JID
316
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
317
+ const hasSession = await signalRepository.validateSession(fromJid);
318
+ const result = messageRetryManager.shouldRecreateSession(fromJid, retryCount, hasSession.exists);
319
+ shouldRecreateSession = result.recreate;
320
+ recreateReason = result.reason;
321
+ if (shouldRecreateSession) {
322
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
323
+ // Delete existing session to force recreation
324
+ await authState.keys.set({ session: { [sessionId]: null } });
325
+ forceIncludeKeys = true;
326
+ }
327
+ }
328
+ catch (error) {
329
+ logger.warn({ error, fromJid }, 'failed to check session recreation');
330
+ }
331
+ }
332
+ if (retryCount <= 2) {
333
+ // Use new retry manager for phone requests if available
334
+ if (messageRetryManager) {
335
+ // Schedule phone request with delay (like whatsmeow)
336
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
337
+ try {
338
+ const requestId = await requestPlaceholderResend(msgKey);
339
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
340
+ }
341
+ catch (error) {
342
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request');
343
+ }
344
+ });
345
+ }
346
+ else {
347
+ // Fallback to immediate request
348
+ const msgId = await requestPlaceholderResend(msgKey);
349
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
350
+ }
351
+ }
352
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true);
353
+ await authState.keys.transaction(async () => {
354
+ const receipt = {
355
+ tag: 'receipt',
356
+ attrs: {
357
+ id: msgId,
358
+ type: 'retry',
359
+ to: node.attrs.from
360
+ },
361
+ content: [
362
+ {
363
+ tag: 'retry',
364
+ attrs: {
365
+ count: retryCount.toString(),
366
+ id: node.attrs.id,
367
+ t: node.attrs.t,
368
+ v: '1',
369
+ // ADD ERROR FIELD
370
+ error: '0'
371
+ }
372
+ },
373
+ {
374
+ tag: 'registration',
375
+ attrs: {},
376
+ content: encodeBigEndian(authState.creds.registrationId)
377
+ }
378
+ ]
379
+ };
380
+ if (node.attrs.recipient) {
381
+ receipt.attrs.recipient = node.attrs.recipient;
382
+ }
383
+ if (node.attrs.participant) {
384
+ receipt.attrs.participant = node.attrs.participant;
385
+ }
386
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
387
+ const { update, preKeys } = await getNextPreKeys(authState, 1);
388
+ const [keyId] = Object.keys(preKeys);
389
+ const key = preKeys[+keyId];
390
+ const content = receipt.content;
391
+ content.push({
392
+ tag: 'keys',
393
+ attrs: {},
394
+ content: [
395
+ { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
396
+ { tag: 'identity', attrs: {}, content: identityKey.public },
397
+ xmppPreKey(key, +keyId),
398
+ xmppSignedPreKey(signedPreKey),
399
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
400
+ ]
401
+ });
402
+ ev.emit('creds.update', update);
403
+ }
404
+ await sendNode(receipt);
405
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
406
+ }, authState?.creds?.me?.id || 'sendRetryRequest');
407
+ };
408
+ const handleEncryptNotification = async (node) => {
409
+ const from = node.attrs.from;
410
+ if (from === S_WHATSAPP_NET) {
411
+ const countChild = getBinaryNodeChild(node, 'count');
412
+ const count = +countChild.attrs.value;
413
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
414
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
415
+ if (shouldUploadMorePreKeys) {
416
+ await uploadPreKeys();
417
+ }
418
+ }
419
+ else {
420
+ const identityNode = getBinaryNodeChild(node, 'identity');
421
+ if (identityNode) {
422
+ logger.info({ jid: from }, 'identity changed');
423
+ // not handling right now
424
+ // signal will override new identity anyway
425
+ }
426
+ else {
427
+ logger.info({ node }, 'unknown encrypt notification');
428
+ }
429
+ }
430
+ };
431
+ const handleGroupNotification = (fullNode, child, msg) => {
432
+ // TODO: Support PN/LID (Here is only LID now)
433
+ const actingParticipantLid = fullNode.attrs.participant;
434
+ const actingParticipantPn = fullNode.attrs.participant_pn;
435
+ const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
436
+ const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
437
+ switch (child?.tag) {
438
+ case 'create':
439
+ const metadata = extractGroupMetadata(child);
440
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE;
441
+ msg.messageStubParameters = [metadata.subject];
442
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
443
+ ev.emit('chats.upsert', [
444
+ {
445
+ id: metadata.id,
446
+ name: metadata.subject,
447
+ conversationTimestamp: metadata.creation
448
+ }
449
+ ]);
450
+ ev.emit('groups.upsert', [
451
+ {
452
+ ...metadata,
453
+ author: actingParticipantLid,
454
+ authorPn: actingParticipantPn
455
+ }
456
+ ]);
457
+ break;
458
+ case 'ephemeral':
459
+ case 'not_ephemeral':
460
+ msg.message = {
461
+ protocolMessage: {
462
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
463
+ ephemeralExpiration: +(child.attrs.expiration || 0)
464
+ }
465
+ };
466
+ break;
467
+ case 'modify':
468
+ const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
469
+ msg.messageStubParameters = oldNumber || [];
470
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
471
+ break;
472
+ case 'promote':
473
+ case 'demote':
474
+ case 'remove':
475
+ case 'add':
476
+ case 'leave':
477
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
478
+ msg.messageStubType = WAMessageStubType[stubType];
479
+ const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
480
+ // TODO: Store LID MAPPINGS
481
+ return {
482
+ id: attrs.jid,
483
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
484
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
485
+ admin: (attrs.type || null)
486
+ };
487
+ });
488
+ if (participants.length === 1 &&
489
+ // if recv. "remove" message and sender removed themselves
490
+ // mark as left
491
+ (areJidsSameUser(participants[0].id, actingParticipantLid) ||
492
+ areJidsSameUser(participants[0].id, actingParticipantPn)) &&
493
+ child.tag === 'remove') {
494
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
495
+ }
496
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a));
497
+ break;
498
+ case 'subject':
499
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
500
+ msg.messageStubParameters = [child.attrs.subject];
501
+ break;
502
+ case 'description':
503
+ const description = getBinaryNodeChild(child, 'body')?.content?.toString();
504
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
505
+ msg.messageStubParameters = description ? [description] : undefined;
506
+ break;
507
+ case 'announcement':
508
+ case 'not_announcement':
509
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
510
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
511
+ break;
512
+ case 'locked':
513
+ case 'unlocked':
514
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
515
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
516
+ break;
517
+ case 'invite':
518
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
519
+ msg.messageStubParameters = [child.attrs.code];
520
+ break;
521
+ case 'member_add_mode':
522
+ const addMode = child.content;
523
+ if (addMode) {
524
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
525
+ msg.messageStubParameters = [addMode.toString()];
526
+ }
527
+ break;
528
+ case 'membership_approval_mode':
529
+ const approvalMode = getBinaryNodeChild(child, 'group_join');
530
+ if (approvalMode) {
531
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
532
+ msg.messageStubParameters = [approvalMode.attrs.state];
533
+ }
534
+ break;
535
+ case 'created_membership_requests':
536
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
537
+ msg.messageStubParameters = [
538
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
539
+ 'created',
540
+ child.attrs.request_method
541
+ ];
542
+ break;
543
+ case 'revoked_membership_requests':
544
+ const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
545
+ // TODO: LIDMAPPING SUPPORT
546
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
547
+ msg.messageStubParameters = [
548
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
549
+ isDenied ? 'revoked' : 'rejected'
550
+ ];
551
+ break;
552
+ }
553
+ };
554
+ const processNotification = async (node) => {
555
+ const result = {};
556
+ const [child] = getAllBinaryNodeChildren(node);
557
+ const nodeType = node.attrs.type;
558
+ const from = jidNormalizedUser(node.attrs.from);
559
+ switch (nodeType) {
560
+ case 'privacy_token':
561
+ const tokenList = getBinaryNodeChildren(child, 'token');
562
+ for (const { attrs, content } of tokenList) {
563
+ const jid = attrs.jid;
564
+ ev.emit('chats.update', [
565
+ {
566
+ id: jid,
567
+ tcToken: content
568
+ }
569
+ ]);
570
+ logger.debug({ jid }, 'got privacy token update');
571
+ }
572
+ break;
573
+ case 'newsletter':
574
+ await handleNewsletterNotification(node);
575
+ break;
576
+ case 'mex':
577
+ await handleMexNewsletterNotification(node);
578
+ break;
579
+ case 'w:gp2':
580
+ // TODO: HANDLE PARTICIPANT_PN
581
+ handleGroupNotification(node, child, result);
582
+ break;
583
+ case 'mediaretry':
584
+ const event = decodeMediaRetryNode(node);
585
+ ev.emit('messages.media-update', [event]);
586
+ break;
587
+ case 'encrypt':
588
+ await handleEncryptNotification(node);
589
+ break;
590
+ case 'devices':
591
+ const devices = getBinaryNodeChildren(child, 'device');
592
+ if (areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
593
+ areJidsSameUser(child.attrs.lid, authState.creds.me.lid)) {
594
+ const deviceData = devices.map(d => ({ id: d.attrs.jid, lid: d.attrs.lid }));
595
+ logger.info({ deviceData }, 'my own devices changed');
596
+ }
597
+ //TODO: drop a new event, add hashes
598
+ break;
599
+ case 'server_sync':
600
+ const update = getBinaryNodeChild(node, 'collection');
601
+ if (update) {
602
+ const name = update.attrs.name;
603
+ await resyncAppState([name], false);
604
+ }
605
+ break;
606
+ case 'picture':
607
+ const setPicture = getBinaryNodeChild(node, 'set');
608
+ const delPicture = getBinaryNodeChild(node, 'delete');
609
+ ev.emit('contacts.update', [
610
+ {
611
+ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
612
+ imgUrl: setPicture ? 'changed' : 'removed'
613
+ }
614
+ ]);
615
+ if (isJidGroup(from)) {
616
+ const node = setPicture || delPicture;
617
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
618
+ if (setPicture) {
619
+ result.messageStubParameters = [setPicture.attrs.id];
620
+ }
621
+ result.participant = node?.attrs.author;
622
+ result.key = {
623
+ ...(result.key || {}),
624
+ participant: setPicture?.attrs.author
625
+ };
626
+ }
627
+ break;
628
+ case 'account_sync':
629
+ if (child.tag === 'disappearing_mode') {
630
+ const newDuration = +child.attrs.duration;
631
+ const timestamp = +child.attrs.t;
632
+ logger.info({ newDuration }, 'updated account disappearing mode');
633
+ ev.emit('creds.update', {
634
+ accountSettings: {
635
+ ...authState.creds.accountSettings,
636
+ defaultDisappearingMode: {
637
+ ephemeralExpiration: newDuration,
638
+ ephemeralSettingTimestamp: timestamp
639
+ }
640
+ }
641
+ });
642
+ }
643
+ else if (child.tag === 'blocklist') {
644
+ const blocklists = getBinaryNodeChildren(child, 'item');
645
+ for (const { attrs } of blocklists) {
646
+ const blocklist = [attrs.jid];
647
+ const type = attrs.action === 'block' ? 'add' : 'remove';
648
+ ev.emit('blocklist.update', { blocklist, type });
649
+ }
650
+ }
651
+ break;
652
+ case 'link_code_companion_reg':
653
+ const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
654
+ const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
655
+ const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
656
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
657
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
658
+ const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
659
+ const random = randomBytes(32);
660
+ const linkCodeSalt = randomBytes(32);
661
+ const linkCodePairingExpanded = await hkdf(companionSharedKey, 32, {
662
+ salt: linkCodeSalt,
663
+ info: 'link_code_pairing_key_bundle_encryption_key'
664
+ });
665
+ const encryptPayload = Buffer.concat([
666
+ Buffer.from(authState.creds.signedIdentityKey.public),
667
+ primaryIdentityPublicKey,
668
+ random
669
+ ]);
670
+ const encryptIv = randomBytes(12);
671
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
672
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
673
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
674
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
675
+ authState.creds.advSecretKey = (await hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
676
+ await query({
677
+ tag: 'iq',
678
+ attrs: {
679
+ to: S_WHATSAPP_NET,
680
+ type: 'set',
681
+ id: sock.generateMessageTag(),
682
+ xmlns: 'md'
683
+ },
684
+ content: [
685
+ {
686
+ tag: 'link_code_companion_reg',
687
+ attrs: {
688
+ jid: authState.creds.me.id,
689
+ stage: 'companion_finish'
690
+ },
691
+ content: [
692
+ {
693
+ tag: 'link_code_pairing_wrapped_key_bundle',
694
+ attrs: {},
695
+ content: encryptedPayload
696
+ },
697
+ {
698
+ tag: 'companion_identity_public',
699
+ attrs: {},
700
+ content: authState.creds.signedIdentityKey.public
701
+ },
702
+ {
703
+ tag: 'link_code_pairing_ref',
704
+ attrs: {},
705
+ content: ref
706
+ }
707
+ ]
708
+ }
709
+ ]
710
+ });
711
+ authState.creds.registered = true;
712
+ ev.emit('creds.update', authState.creds);
713
+ }
714
+ if (Object.keys(result).length) {
715
+ return result;
716
+ }
717
+ };
718
+ async function decipherLinkPublicKey(data) {
719
+ const buffer = toRequiredBuffer(data);
720
+ const salt = buffer.slice(0, 32);
721
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
722
+ const iv = buffer.slice(32, 48);
723
+ const payload = buffer.slice(48, 80);
724
+ return aesDecryptCTR(payload, secretKey, iv);
725
+ }
726
+ function toRequiredBuffer(data) {
727
+ if (data === undefined) {
728
+ throw new Boom('Invalid buffer', { statusCode: 400 });
729
+ }
730
+ return data instanceof Buffer ? data : Buffer.from(data);
731
+ }
732
+ const willSendMessageAgain = async (id, participant) => {
733
+ const key = `${id}:${participant}`;
734
+ const retryCount = (await msgRetryCache.get(key)) || 0;
735
+ return retryCount < maxMsgRetryCount;
736
+ };
737
+ const updateSendMessageAgainCount = async (id, participant) => {
738
+ const key = `${id}:${participant}`;
739
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
740
+ await msgRetryCache.set(key, newValue);
741
+ };
742
+ const sendMessagesAgain = async (key, ids, retryNode) => {
743
+ const remoteJid = key.remoteJid;
744
+ const participant = key.participant || remoteJid;
745
+ const retryCount = +retryNode.attrs.count || 1;
746
+ // Try to get messages from cache first, then fallback to getMessage
747
+ const msgs = [];
748
+ for (const id of ids) {
749
+ let msg;
750
+ // Try to get from retry cache first if enabled
751
+ if (messageRetryManager) {
752
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
753
+ if (cachedMsg) {
754
+ msg = cachedMsg.message;
755
+ logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
756
+ // Mark retry as successful since we found the message
757
+ messageRetryManager.markRetrySuccess(id);
758
+ }
759
+ }
760
+ // Fallback to getMessage if not found in cache
761
+ if (!msg) {
762
+ msg = await getMessage({ ...key, id });
763
+ if (msg) {
764
+ logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
765
+ // Also mark as successful if found via getMessage
766
+ if (messageRetryManager) {
767
+ messageRetryManager.markRetrySuccess(id);
768
+ }
769
+ }
770
+ }
771
+ msgs.push(msg);
772
+ }
773
+ // if it's the primary jid sending the request
774
+ // just re-send the message to everyone
775
+ // prevents the first message decryption failure
776
+ const sendToAll = !jidDecode(participant)?.device;
777
+ // Check if we should recreate session for this retry
778
+ let shouldRecreateSession = false;
779
+ let recreateReason = '';
780
+ if (enableAutoSessionRecreation && messageRetryManager) {
781
+ try {
782
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
783
+ const hasSession = await signalRepository.validateSession(participant);
784
+ const result = messageRetryManager.shouldRecreateSession(participant, retryCount, hasSession.exists);
785
+ shouldRecreateSession = result.recreate;
786
+ recreateReason = result.reason;
787
+ if (shouldRecreateSession) {
788
+ logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry');
789
+ await authState.keys.set({ session: { [sessionId]: null } });
790
+ }
791
+ }
792
+ catch (error) {
793
+ logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
794
+ }
795
+ }
796
+ await assertSessions([participant]);
797
+ if (isJidGroup(remoteJid)) {
798
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
799
+ }
800
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp');
801
+ for (const [i, msg] of msgs.entries()) {
802
+ if (!ids[i])
803
+ continue;
804
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
805
+ updateSendMessageAgainCount(ids[i], participant);
806
+ const msgRelayOpts = { messageId: ids[i] };
807
+ if (sendToAll) {
808
+ msgRelayOpts.useUserDevicesCache = false;
809
+ }
810
+ else {
811
+ msgRelayOpts.participant = {
812
+ jid: participant,
813
+ count: +retryNode.attrs.count
814
+ };
815
+ }
816
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
817
+ }
818
+ else {
819
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
820
+ }
821
+ }
822
+ };
823
+ const handleReceipt = async (node) => {
824
+ const { attrs, content } = node;
825
+ const isLid = attrs.from.includes('lid');
826
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
827
+ const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
828
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
829
+ const key = {
830
+ remoteJid,
831
+ id: '',
832
+ fromMe,
833
+ participant: attrs.participant
834
+ };
835
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
836
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
837
+ await sendMessageAck(node);
838
+ return;
839
+ }
840
+ const ids = [attrs.id];
841
+ if (Array.isArray(content)) {
842
+ const items = getBinaryNodeChildren(content[0], 'item');
843
+ ids.push(...items.map(i => i.attrs.id));
844
+ }
845
+ try {
846
+ await Promise.all([
847
+ processingMutex.mutex(async () => {
848
+ const status = getStatusFromReceiptType(attrs.type);
849
+ if (typeof status !== 'undefined' &&
850
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
851
+ // or another device of ours has read some messages
852
+ (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
853
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
854
+ if (attrs.participant) {
855
+ const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
856
+ ev.emit('message-receipt.update', ids.map(id => ({
857
+ key: { ...key, id },
858
+ receipt: {
859
+ userJid: jidNormalizedUser(attrs.participant),
860
+ [updateKey]: +attrs.t
861
+ }
862
+ })));
863
+ }
864
+ }
865
+ else {
866
+ ev.emit('messages.update', ids.map(id => ({
867
+ key: { ...key, id },
868
+ update: { status }
869
+ })));
870
+ }
871
+ }
872
+ if (attrs.type === 'retry') {
873
+ // correctly set who is asking for the retry
874
+ key.participant = key.participant || attrs.from;
875
+ const retryNode = getBinaryNodeChild(node, 'retry');
876
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
877
+ if (key.fromMe) {
878
+ try {
879
+ updateSendMessageAgainCount(ids[0], key.participant);
880
+ logger.debug({ attrs, key }, 'recv retry request');
881
+ await sendMessagesAgain(key, ids, retryNode);
882
+ }
883
+ catch (error) {
884
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
885
+ }
886
+ }
887
+ else {
888
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
889
+ }
890
+ }
891
+ else {
892
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
893
+ }
894
+ }
895
+ })
896
+ ]);
897
+ }
898
+ finally {
899
+ await sendMessageAck(node);
900
+ }
901
+ };
902
+ const handleNotification = async (node) => {
903
+ const remoteJid = node.attrs.from;
904
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
905
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
906
+ await sendMessageAck(node);
907
+ return;
908
+ }
909
+ try {
910
+ await Promise.all([
911
+ processingMutex.mutex(async () => {
912
+ const msg = await processNotification(node);
913
+ if (msg) {
914
+ const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
915
+ const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node);
916
+ msg.key = {
917
+ remoteJid,
918
+ fromMe,
919
+ participant: node.attrs.participant,
920
+ participantAlt,
921
+ addressingMode,
922
+ id: node.attrs.id,
923
+ ...(msg.key || {})
924
+ };
925
+ msg.participant ?? (msg.participant = node.attrs.participant);
926
+ msg.messageTimestamp = +node.attrs.t;
927
+ const fullMsg = proto.WebMessageInfo.fromObject(msg);
928
+ await upsertMessage(fullMsg, 'append');
929
+ }
930
+ })
931
+ ]);
932
+ }
933
+ finally {
934
+ await sendMessageAck(node);
935
+ }
936
+ };
937
+ const handleMessage = async (node) => {
938
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
939
+ logger.debug({ key: node.attrs.key }, 'ignored message');
940
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
941
+ return;
942
+ }
943
+ const encNode = getBinaryNodeChild(node, 'enc');
944
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
945
+ if (encNode && encNode.attrs.type === 'msmsg') {
946
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
947
+ await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
948
+ return;
949
+ }
950
+ const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
951
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
952
+ // store new mappings we didn't have before
953
+ if (!!alt) {
954
+ const altServer = jidDecode(alt)?.server;
955
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
956
+ if (altServer === 'lid') {
957
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
958
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
959
+ await signalRepository.migrateSession(primaryJid, alt);
960
+ }
961
+ }
962
+ else {
963
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
964
+ await signalRepository.migrateSession(alt, primaryJid);
965
+ }
966
+ }
967
+ if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
968
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
969
+ logger.debug({
970
+ jid: msg.key.remoteJid,
971
+ id: msg.key.id
972
+ }, 'Added message to recent cache for retry receipts');
973
+ }
974
+ try {
975
+ await processingMutex.mutex(async () => {
976
+ await decrypt();
977
+ // message failed to decrypt
978
+ if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT) {
979
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
980
+ return sendMessageAck(node, NACK_REASONS.ParsingError);
981
+ }
982
+ const errorMessage = msg?.messageStubParameters?.[0] || '';
983
+ const isPreKeyError = errorMessage.includes('PreKey');
984
+ logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
985
+ // Handle both pre-key and normal retries in single mutex
986
+ retryMutex.mutex(async () => {
987
+ try {
988
+ if (!ws.isOpen) {
989
+ logger.debug({ node }, 'Connection closed, skipping retry');
990
+ return;
991
+ }
992
+ // Handle pre-key errors with upload and delay
993
+ if (isPreKeyError) {
994
+ logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
995
+ try {
996
+ logger.debug('Uploading pre-keys for error recovery');
997
+ await uploadPreKeys(5);
998
+ logger.debug('Waiting for server to process new pre-keys');
999
+ await delay(1000);
1000
+ }
1001
+ catch (uploadErr) {
1002
+ logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
1003
+ }
1004
+ }
1005
+ const encNode = getBinaryNodeChild(node, 'enc');
1006
+ await sendRetryRequest(node, !encNode);
1007
+ if (retryRequestDelayMs) {
1008
+ await delay(retryRequestDelayMs);
1009
+ }
1010
+ }
1011
+ catch (err) {
1012
+ logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry');
1013
+ // Still attempt retry even if pre-key upload failed
1014
+ try {
1015
+ const encNode = getBinaryNodeChild(node, 'enc');
1016
+ await sendRetryRequest(node, !encNode);
1017
+ }
1018
+ catch (retryErr) {
1019
+ logger.error({ retryErr }, 'Failed to send retry after error handling');
1020
+ }
1021
+ }
1022
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
1023
+ });
1024
+ }
1025
+ else {
1026
+ // no type in the receipt => message delivered
1027
+ let type = undefined;
1028
+ let participant = msg.key.participant;
1029
+ if (category === 'peer') {
1030
+ // special peer message
1031
+ type = 'peer_msg';
1032
+ }
1033
+ else if (msg.key.fromMe) {
1034
+ // message was sent by us from a different device
1035
+ type = 'sender';
1036
+ // need to specially handle this case
1037
+ if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1038
+ participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1039
+ }
1040
+ }
1041
+ else if (!sendActiveReceipts) {
1042
+ type = 'inactive';
1043
+ }
1044
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1045
+ // send ack for history message
1046
+ const isAnyHistoryMsg = getHistoryMsg(msg.message);
1047
+ if (isAnyHistoryMsg) {
1048
+ const jid = jidNormalizedUser(msg.key.remoteJid);
1049
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
1050
+ }
1051
+ }
1052
+ cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1053
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1054
+ });
1055
+ }
1056
+ catch (error) {
1057
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
1058
+ }
1059
+ };
1060
+ const handleCall = async (node) => {
1061
+ const { attrs } = node;
1062
+ const [infoChild] = getAllBinaryNodeChildren(node);
1063
+ const status = getCallStatusFromNode(infoChild);
1064
+ if (!infoChild) {
1065
+ throw new Boom('Missing call info in call node');
1066
+ }
1067
+ const callId = infoChild.attrs['call-id'];
1068
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1069
+ const call = {
1070
+ chatId: attrs.from,
1071
+ from,
1072
+ id: callId,
1073
+ date: new Date(+attrs.t * 1000),
1074
+ offline: !!attrs.offline,
1075
+ status
1076
+ };
1077
+ if (status === 'offer') {
1078
+ call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1079
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1080
+ call.groupJid = infoChild.attrs['group-jid'];
1081
+ await callOfferCache.set(call.id, call);
1082
+ }
1083
+ const existingCall = await callOfferCache.get(call.id);
1084
+ // use existing call info to populate this event
1085
+ if (existingCall) {
1086
+ call.isVideo = existingCall.isVideo;
1087
+ call.isGroup = existingCall.isGroup;
1088
+ }
1089
+ // delete data once call has ended
1090
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1091
+ await callOfferCache.del(call.id);
1092
+ }
1093
+ ev.emit('call', [call]);
1094
+ await sendMessageAck(node);
1095
+ };
1096
+ const handleBadAck = async ({ attrs }) => {
1097
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1098
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1099
+ // // current hypothesis is that if pash is sent in the ack
1100
+ // // it means -- the message hasn't reached all devices yet
1101
+ // // we'll retry sending the message here
1102
+ // if(attrs.phash) {
1103
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
1104
+ // const msg = await getMessage(key)
1105
+ // if(msg) {
1106
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1107
+ // } else {
1108
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
1109
+ // }
1110
+ // }
1111
+ // error in acknowledgement,
1112
+ // device could not display the message
1113
+ if (attrs.error) {
1114
+ logger.warn({ attrs }, 'received error in ack');
1115
+ ev.emit('messages.update', [
1116
+ {
1117
+ key,
1118
+ update: {
1119
+ status: WAMessageStatus.ERROR,
1120
+ messageStubParameters: [attrs.error]
1121
+ }
1122
+ }
1123
+ ]);
1124
+ }
1125
+ };
1126
+ /// processes a node with the given function
1127
+ /// and adds the task to the existing buffer if we're buffering events
1128
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1129
+ ev.buffer();
1130
+ await execTask();
1131
+ ev.flush();
1132
+ function execTask() {
1133
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1134
+ }
1135
+ };
1136
+ const makeOfflineNodeProcessor = () => {
1137
+ const nodeProcessorMap = new Map([
1138
+ ['message', handleMessage],
1139
+ ['call', handleCall],
1140
+ ['receipt', handleReceipt],
1141
+ ['notification', handleNotification]
1142
+ ]);
1143
+ const nodes = [];
1144
+ let isProcessing = false;
1145
+ const enqueue = (type, node) => {
1146
+ nodes.push({ type, node });
1147
+ if (isProcessing) {
1148
+ return;
1149
+ }
1150
+ isProcessing = true;
1151
+ const promise = async () => {
1152
+ while (nodes.length && ws.isOpen) {
1153
+ const { type, node } = nodes.shift();
1154
+ const nodeProcessor = nodeProcessorMap.get(type);
1155
+ if (!nodeProcessor) {
1156
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1157
+ continue;
1158
+ }
1159
+ await nodeProcessor(node);
1160
+ }
1161
+ isProcessing = false;
1162
+ };
1163
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1164
+ };
1165
+ return { enqueue };
1166
+ };
1167
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
1168
+ const processNode = (type, node, identifier, exec) => {
1169
+ const isOffline = !!node.attrs.offline;
1170
+ if (isOffline) {
1171
+ offlineNodeProcessor.enqueue(type, node);
1172
+ }
1173
+ else {
1174
+ processNodeWithBuffer(node, identifier, exec);
1175
+ }
1176
+ };
1177
+ // recv a message
1178
+ ws.on('CB:message', (node) => {
1179
+ processNode('message', node, 'processing message', handleMessage);
1180
+ });
1181
+ ws.on('CB:call', async (node) => {
1182
+ processNode('call', node, 'handling call', handleCall);
1183
+ });
1184
+ ws.on('CB:receipt', node => {
1185
+ processNode('receipt', node, 'handling receipt', handleReceipt);
1186
+ });
1187
+ ws.on('CB:notification', async (node) => {
1188
+ processNode('notification', node, 'handling notification', handleNotification);
1189
+ });
1190
+ ws.on('CB:ack,class:message', (node) => {
1191
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1192
+ });
1193
+ ev.on('call', ([call]) => {
1194
+ if (!call) {
1195
+ return;
1196
+ }
1197
+ // missed call + group call notification message generation
1198
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1199
+ const msg = {
1200
+ key: {
1201
+ remoteJid: call.chatId,
1202
+ id: call.id,
1203
+ fromMe: false
1204
+ },
1205
+ messageTimestamp: unixTimestampSeconds(call.date)
1206
+ };
1207
+ if (call.status === 'timeout') {
1208
+ if (call.isGroup) {
1209
+ msg.messageStubType = call.isVideo
1210
+ ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1211
+ : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1212
+ }
1213
+ else {
1214
+ msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
1215
+ }
1216
+ }
1217
+ else {
1218
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1219
+ }
1220
+ const protoMsg = proto.WebMessageInfo.fromObject(msg);
1221
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1222
+ }
1223
+ });
1224
+ ev.on('connection.update', ({ isOnline }) => {
1225
+ if (typeof isOnline !== 'undefined') {
1226
+ sendActiveReceipts = isOnline;
1227
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1228
+ }
1229
+ });
1230
+ return {
1231
+ ...sock,
1232
+ sendMessageAck,
1233
+ sendRetryRequest,
1234
+ rejectCall,
1235
+ fetchMessageHistory,
1236
+ requestPlaceholderResend,
1237
+ messageRetryManager
1238
+ };
1239
+ };
1240
+ //# sourceMappingURL=messages-recv.js.map