torbaileys 8.0.0

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