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