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