@gara31/void-baileys 7.0.0-rc.10

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