@prototypevip/baileys 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/LICENSE +23 -0
  2. package/WAProto/index.js +131118 -0
  3. package/engine-requirements.js +1 -0
  4. package/lib/Defaults/index.js +187 -0
  5. package/lib/Signal/Group/ciphertext-message.js +11 -0
  6. package/lib/Signal/Group/group-session-builder.js +41 -0
  7. package/lib/Signal/Group/group_cipher.js +108 -0
  8. package/lib/Signal/Group/index.js +11 -0
  9. package/lib/Signal/Group/keyhelper.js +14 -0
  10. package/lib/Signal/Group/sender-chain-key.js +31 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  12. package/lib/Signal/Group/sender-key-message.js +79 -0
  13. package/lib/Signal/Group/sender-key-name.js +49 -0
  14. package/lib/Signal/Group/sender-key-record.js +46 -0
  15. package/lib/Signal/Group/sender-key-state.js +104 -0
  16. package/lib/Signal/Group/sender-message-key.js +29 -0
  17. package/lib/Signal/libsignal.js +532 -0
  18. package/lib/Signal/lid-mapping.js +312 -0
  19. package/lib/Socket/Client/index.js +2 -0
  20. package/lib/Socket/Client/types.js +10 -0
  21. package/lib/Socket/Client/websocket.js +64 -0
  22. package/lib/Socket/business.js +293 -0
  23. package/lib/Socket/chats.js +1124 -0
  24. package/lib/Socket/communities.js +528 -0
  25. package/lib/Socket/groups.js +465 -0
  26. package/lib/Socket/index.js +14 -0
  27. package/lib/Socket/messages-recv.js +2325 -0
  28. package/lib/Socket/messages-send.js +1746 -0
  29. package/lib/Socket/mex.js +55 -0
  30. package/lib/Socket/newsletter.js +317 -0
  31. package/lib/Socket/socket.js +1185 -0
  32. package/lib/Store/cache-factory.js +20 -0
  33. package/lib/Store/index.js +5 -0
  34. package/lib/Store/make-in-memory-store.js +523 -0
  35. package/lib/Store/make-ordered-dictionary.js +203 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Store/prototype-store.js +958 -0
  38. package/lib/Types/Auth.js +1 -0
  39. package/lib/Types/Bussines.js +1 -0
  40. package/lib/Types/Call.js +1 -0
  41. package/lib/Types/Chat.js +7 -0
  42. package/lib/Types/Contact.js +1 -0
  43. package/lib/Types/Events.js +1 -0
  44. package/lib/Types/GroupMetadata.js +1 -0
  45. package/lib/Types/Label.js +24 -0
  46. package/lib/Types/LabelAssociation.js +6 -0
  47. package/lib/Types/Message.js +18 -0
  48. package/lib/Types/Mex.js +37 -0
  49. package/lib/Types/Newsletter.js +36 -0
  50. package/lib/Types/Product.js +1 -0
  51. package/lib/Types/RichType.js +25 -0
  52. package/lib/Types/Signal.js +1 -0
  53. package/lib/Types/Socket.js +2 -0
  54. package/lib/Types/State.js +78 -0
  55. package/lib/Types/USync.js +1 -0
  56. package/lib/Types/index.js +33 -0
  57. package/lib/Utils/auth-utils.js +303 -0
  58. package/lib/Utils/browser-utils.js +32 -0
  59. package/lib/Utils/business.js +245 -0
  60. package/lib/Utils/chat-utils.js +971 -0
  61. package/lib/Utils/companion-reg-client-utils.js +54 -0
  62. package/lib/Utils/constants.js +24 -0
  63. package/lib/Utils/crypto.js +133 -0
  64. package/lib/Utils/cstoken-utils.js +41 -0
  65. package/lib/Utils/decode-wa-message.js +406 -0
  66. package/lib/Utils/event-buffer.js +616 -0
  67. package/lib/Utils/generics.js +438 -0
  68. package/lib/Utils/history.js +147 -0
  69. package/lib/Utils/identity-change-handler.js +63 -0
  70. package/lib/Utils/index.js +29 -0
  71. package/lib/Utils/interactive-message-handler.js +478 -0
  72. package/lib/Utils/link-preview.js +91 -0
  73. package/lib/Utils/logger.js +2 -0
  74. package/lib/Utils/lt-hash.js +6 -0
  75. package/lib/Utils/make-mutex.js +31 -0
  76. package/lib/Utils/message-retry-manager.js +291 -0
  77. package/lib/Utils/messages-media.js +881 -0
  78. package/lib/Utils/messages.js +1434 -0
  79. package/lib/Utils/noise-handler.js +229 -0
  80. package/lib/Utils/normalize-message-identity.js +73 -0
  81. package/lib/Utils/offline-node-processor.js +50 -0
  82. package/lib/Utils/pre-key-manager.js +119 -0
  83. package/lib/Utils/process-message.js +648 -0
  84. package/lib/Utils/reporting-utils.js +355 -0
  85. package/lib/Utils/rich-message-utils.js +264 -0
  86. package/lib/Utils/signal.js +233 -0
  87. package/lib/Utils/stanza-ack.js +33 -0
  88. package/lib/Utils/sticker-utils.js +221 -0
  89. package/lib/Utils/sync-action-utils.js +53 -0
  90. package/lib/Utils/tc-token-utils.js +182 -0
  91. package/lib/Utils/use-multi-file-auth-state.js +118 -0
  92. package/lib/Utils/use-prototype-auth-state.js +217 -0
  93. package/lib/Utils/use-single-file-auth-state.js +94 -0
  94. package/lib/Utils/validate-connection.js +235 -0
  95. package/lib/WABinary/constants.js +1468 -0
  96. package/lib/WABinary/decode.js +258 -0
  97. package/lib/WABinary/encode.js +219 -0
  98. package/lib/WABinary/generic-utils.js +202 -0
  99. package/lib/WABinary/index.js +5 -0
  100. package/lib/WABinary/jid-utils.js +94 -0
  101. package/lib/WABinary/types.js +1 -0
  102. package/lib/WAM/BinaryInfo.js +9 -0
  103. package/lib/WAM/constants.js +20669 -0
  104. package/lib/WAM/encode.js +151 -0
  105. package/lib/WAM/index.js +3 -0
  106. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  107. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -0
  108. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -0
  109. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +29 -0
  110. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  111. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +59 -0
  112. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +21 -0
  113. package/lib/WAUSync/Protocols/index.js +4 -0
  114. package/lib/WAUSync/USyncQuery.js +133 -0
  115. package/lib/WAUSync/USyncUser.js +22 -0
  116. package/lib/WAUSync/index.js +3 -0
  117. package/lib/index.js +12 -0
  118. package/package.json +78 -0
@@ -0,0 +1,2325 @@
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
+ PLACEHOLDER_MAX_AGE_SECONDS,
11
+ STATUS_EXPIRY_SECONDS,
12
+ } from "../Defaults/index.js";
13
+ import {
14
+ ReachoutTimelockEnforcementType,
15
+ WAMessageStatus,
16
+ WAMessageStubType,
17
+ } from "../Types/index.js";
18
+ import {
19
+ ACCOUNT_RESTRICTED_TEXT,
20
+ aesDecryptCTR,
21
+ aesEncryptGCM,
22
+ cleanMessage,
23
+ Curve,
24
+ decodeMediaRetryNode,
25
+ decodeMessageNode,
26
+ decryptMessageNode,
27
+ delay,
28
+ derivePairingCodeKey,
29
+ encodeBigEndian,
30
+ encodeSignedDeviceIdentity,
31
+ extractAddressingContext,
32
+ extractE2ESessionFromRetryReceipt,
33
+ getCallStatusFromNode,
34
+ getHistoryMsg,
35
+ getNextPreKeys,
36
+ getStatusFromReceiptType,
37
+ handleIdentityChange,
38
+ hkdf,
39
+ MISSING_KEYS_ERROR_TEXT,
40
+ NACK_REASONS,
41
+ NO_MESSAGE_FOUND_ERROR_TEXT,
42
+ SERVER_ERROR_CODES,
43
+ toNumber,
44
+ unixTimestampSeconds,
45
+ xmppPreKey,
46
+ xmppSignedPreKey,
47
+ } from "../Utils/index.js";
48
+ import { makeMutex } from "../Utils/make-mutex.js";
49
+ import { makeOfflineNodeProcessor } from "../Utils/offline-node-processor.js";
50
+ import { buildAckStanza } from "../Utils/stanza-ack.js";
51
+ import {
52
+ buildMergedTcTokenIndexWrite,
53
+ isTcTokenExpired,
54
+ readTcTokenIndex,
55
+ resolveIssuanceJid,
56
+ resolveTcTokenJid,
57
+ storeTcTokensFromIqResult,
58
+ TC_TOKEN_INDEX_KEY,
59
+ } from "../Utils/tc-token-utils.js";
60
+ import {
61
+ areJidsSameUser,
62
+ binaryNodeToString,
63
+ getAllBinaryNodeChildren,
64
+ getBinaryNodeChild,
65
+ getBinaryNodeChildBuffer,
66
+ getBinaryNodeChildren,
67
+ getBinaryNodeChildString,
68
+ getBinaryNodeChildUInt,
69
+ isJidGroup,
70
+ isJidNewsletter,
71
+ isJidStatusBroadcast,
72
+ isLidUser,
73
+ isPnUser,
74
+ jidDecode,
75
+ jidNormalizedUser,
76
+ S_WHATSAPP_NET,
77
+ } from "../WABinary/index.js";
78
+ import { extractGroupMetadata } from "./groups.js";
79
+ import { makeMessagesSocket } from "./messages-send.js";
80
+ const ENFORCEMENT_TYPE_VALUES = new Set(
81
+ Object.values(ReachoutTimelockEnforcementType),
82
+ );
83
+ function isValidEnforcementType(value) {
84
+ return typeof value === "string" && ENFORCEMENT_TYPE_VALUES.has(value);
85
+ }
86
+ export const makeMessagesRecvSocket = (config) => {
87
+ const {
88
+ logger,
89
+ retryRequestDelayMs,
90
+ maxMsgRetryCount,
91
+ getMessage,
92
+ shouldIgnoreJid,
93
+ enableAutoSessionRecreation,
94
+ } = config;
95
+ const sock = makeMessagesSocket(config);
96
+ const {
97
+ userDevicesCache,
98
+ devicesMutex,
99
+ ev,
100
+ authState,
101
+ ws,
102
+ messageMutex,
103
+ notificationMutex,
104
+ receiptMutex,
105
+ signalRepository,
106
+ query,
107
+ upsertMessage,
108
+ resyncAppState,
109
+ onUnexpectedError,
110
+ assertSessions,
111
+ sendNode,
112
+ relayMessage,
113
+ sendReceipt,
114
+ uploadPreKeys,
115
+ sendPeerDataOperationMessage,
116
+ messageRetryManager,
117
+ registerSocketEndHandler,
118
+ issuePrivacyTokens,
119
+ fetchAccountReachoutTimelock,
120
+ placeholderResendCache,
121
+ } = sock;
122
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(
123
+ signalRepository.lidMapping,
124
+ );
125
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
126
+ const retryMutex = makeMutex();
127
+ const msgRetryCache =
128
+ config.msgRetryCounterCache ||
129
+ new NodeCache({
130
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
131
+ useClones: false,
132
+ });
133
+ const callOfferCache =
134
+ config.callOfferCache ||
135
+ new NodeCache({
136
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
137
+ useClones: false,
138
+ });
139
+ // Debounce identity-change session refreshes per JID to avoid bursts
140
+ const identityAssertDebounce = new NodeCache({
141
+ stdTTL: 5,
142
+ useClones: false,
143
+ });
144
+ let sendActiveReceipts = false;
145
+ const fetchMessageHistory = async (
146
+ count,
147
+ oldestMsgKey,
148
+ oldestMsgTimestamp,
149
+ ) => {
150
+ if (!authState.creds.me?.id) {
151
+ throw new Boom("Not authenticated");
152
+ }
153
+ const pdoMessage = {
154
+ historySyncOnDemandRequest: {
155
+ chatJid: oldestMsgKey.remoteJid,
156
+ oldestMsgFromMe: oldestMsgKey.fromMe,
157
+ oldestMsgId: oldestMsgKey.id,
158
+ oldestMsgTimestampMs: oldestMsgTimestamp,
159
+ onDemandMsgCount: count,
160
+ },
161
+ peerDataOperationRequestType:
162
+ proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND,
163
+ };
164
+ return sendPeerDataOperationMessage(pdoMessage);
165
+ };
166
+ const requestPlaceholderResend = async (messageKey, msgData) => {
167
+ if (!authState.creds.me?.id) {
168
+ throw new Boom("Not authenticated");
169
+ }
170
+ if (await placeholderResendCache.get(messageKey?.id)) {
171
+ logger.debug({ messageKey }, "already requested resend");
172
+ return;
173
+ } else {
174
+ // Store original message data so PDO response handler can preserve
175
+ // metadata (LID details, timestamps, etc.) that the phone may omit
176
+ await placeholderResendCache.set(messageKey?.id, msgData || true);
177
+ }
178
+ await delay(2000);
179
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
180
+ logger.debug({ messageKey }, "message received while resend requested");
181
+ return "RESOLVED";
182
+ }
183
+ const pdoMessage = {
184
+ placeholderMessageResendRequest: [
185
+ {
186
+ messageKey,
187
+ },
188
+ ],
189
+ peerDataOperationRequestType:
190
+ proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND,
191
+ };
192
+ setTimeout(async () => {
193
+ if (await placeholderResendCache.get(messageKey?.id)) {
194
+ logger.debug(
195
+ { messageKey },
196
+ "PDO message without response after 8 seconds. Phone possibly offline",
197
+ );
198
+ await placeholderResendCache.del(messageKey?.id);
199
+ }
200
+ }, 8000);
201
+ return sendPeerDataOperationMessage(pdoMessage);
202
+ };
203
+ const handleMexNotification = async (node) => {
204
+ const updateNode = getBinaryNodeChild(node, "update");
205
+ if (updateNode) {
206
+ const opName = updateNode.attrs?.op_name;
207
+ if (!opName) {
208
+ logger.warn(
209
+ { node: binaryNodeToString(node) },
210
+ "mex notification missing op_name, fallback to legacy",
211
+ );
212
+ await handleLegacyMexNewsletterNotification(node);
213
+ return;
214
+ }
215
+ let mexResponse;
216
+ try {
217
+ mexResponse = JSON.parse(updateNode.content.toString());
218
+ } catch (error) {
219
+ logger.error(
220
+ { err: error, opName },
221
+ "failed to parse mex notification JSON",
222
+ );
223
+ return;
224
+ }
225
+ if (mexResponse.errors?.length) {
226
+ logger.warn(
227
+ { errors: mexResponse.errors, opName },
228
+ "mex notification has GQL errors",
229
+ );
230
+ return;
231
+ }
232
+ const data = mexResponse.data;
233
+ if (!data) {
234
+ logger.warn({ opName }, "mex notification has null data");
235
+ return;
236
+ }
237
+ logger.debug({ opName }, "processing mex notification");
238
+ switch (opName) {
239
+ case "NotificationUserReachoutTimelockUpdate":
240
+ handleReachoutTimelockNotification(data);
241
+ break;
242
+ case "MessageCappingInfoNotification":
243
+ handleMessageCappingNotification(data);
244
+ break;
245
+ // newsletter ops still use the legacy <mex> child structure
246
+ case "NotificationNewsletterUpdate":
247
+ case "NotificationLinkedProfilesUpdates":
248
+ case "NotificationNewsletterAdminPromote":
249
+ case "NotificationNewsletterAdminDemote":
250
+ case "NotificationNewsletterUserSettingChange":
251
+ case "NotificationNewsletterJoin":
252
+ case "NotificationNewsletterLeave":
253
+ case "NotificationNewsletterStateChange":
254
+ case "NotificationNewsletterAdminMetadataUpdate":
255
+ case "NotificationNewsletterOwnerUpdate":
256
+ case "NotificationNewsletterAdminInviteRevoke":
257
+ case "NotificationNewsletterWamoSubStatusChange":
258
+ case "NotificationNewsletterBlockUser":
259
+ case "NotificationNewsletterPaidPartnership":
260
+ case "NotificationNewsletterMilestone":
261
+ case "NewsletterResponseStateUpdate":
262
+ await handleLegacyMexNewsletterNotification(node);
263
+ break;
264
+ default:
265
+ logger.debug({ opName }, "unhandled mex notification");
266
+ break;
267
+ }
268
+ return;
269
+ }
270
+ await handleLegacyMexNewsletterNotification(node);
271
+ };
272
+ const handleReachoutTimelockNotification = (data) => {
273
+ const payload = data.xwa2_notify_account_reachout_timelock;
274
+ if (!payload) {
275
+ logger.warn("reachout timelock notification missing payload");
276
+ return;
277
+ }
278
+ if (!payload.is_active) {
279
+ logger.info("reachout timelock restriction lifted");
280
+ ev.emit("connection.update", {
281
+ reachoutTimeLock: {
282
+ isActive: false,
283
+ enforcementType: ReachoutTimelockEnforcementType.DEFAULT,
284
+ },
285
+ });
286
+ return;
287
+ }
288
+ // WA Web defaults to now+60s when the server omits the expiry
289
+ const timeEnforcementEnds = payload.time_enforcement_ends
290
+ ? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000)
291
+ : new Date(Date.now() + 60000);
292
+ const enforcementType = isValidEnforcementType(payload.enforcement_type)
293
+ ? payload.enforcement_type
294
+ : ReachoutTimelockEnforcementType.DEFAULT;
295
+ logger.info(
296
+ { enforcementType, timeEnforcementEnds },
297
+ "reachout timelock restriction set",
298
+ );
299
+ ev.emit("connection.update", {
300
+ reachoutTimeLock: {
301
+ isActive: true,
302
+ timeEnforcementEnds,
303
+ enforcementType,
304
+ },
305
+ });
306
+ };
307
+ const handleMessageCappingNotification = (data) => {
308
+ const payload = data.xwa2_notify_new_chat_messages_capping_info_update;
309
+ if (!payload) {
310
+ logger.warn("message capping notification missing payload");
311
+ return;
312
+ }
313
+ logger.info({ payload }, "received message capping update");
314
+ ev.emit("message-capping.update", payload);
315
+ };
316
+ const handleLegacyMexNewsletterNotification = async (node) => {
317
+ const mexNode = getBinaryNodeChild(node, "mex");
318
+ const updateNode = mexNode?.content
319
+ ? null
320
+ : getBinaryNodeChild(node, "update") || getAllBinaryNodeChildren(node)[0];
321
+ const payloadNode = mexNode?.content ? mexNode : updateNode;
322
+ if (!payloadNode?.content) {
323
+ logger.warn(
324
+ { node: binaryNodeToString(node) },
325
+ "invalid mex newsletter notification",
326
+ );
327
+ return;
328
+ }
329
+ let data;
330
+ try {
331
+ const payloadContent = payloadNode.content;
332
+ if (Array.isArray(payloadContent)) {
333
+ logger.warn(
334
+ { payloadNode },
335
+ "invalid mex newsletter notification payload format",
336
+ );
337
+ return;
338
+ }
339
+ const contentBuf =
340
+ typeof payloadContent === "string"
341
+ ? Buffer.from(payloadContent, "binary")
342
+ : Buffer.from(payloadContent);
343
+ data = JSON.parse(contentBuf.toString());
344
+ } catch (error) {
345
+ logger.error(
346
+ { err: error, node: binaryNodeToString(node) },
347
+ "failed to parse mex newsletter notification",
348
+ );
349
+ return;
350
+ }
351
+ const operation = data?.operation ?? payloadNode?.attrs?.op_name;
352
+ let updates = data?.updates;
353
+ if (!updates) {
354
+ const linkedProfiles = data?.data?.xwa2_notify_linked_profiles;
355
+ if (linkedProfiles) {
356
+ updates = [linkedProfiles];
357
+ }
358
+ }
359
+ if (!updates || !operation) {
360
+ logger.warn({ data }, "invalid mex newsletter notification content");
361
+ return;
362
+ }
363
+ logger.info({ operation, updates }, "got mex newsletter notification");
364
+ switch (operation) {
365
+ case "NotificationNewsletterUpdate":
366
+ for (const update of updates) {
367
+ if (
368
+ update.jid &&
369
+ update.settings &&
370
+ Object.keys(update.settings).length > 0
371
+ ) {
372
+ ev.emit("newsletter-settings.update", {
373
+ id: update.jid,
374
+ update: update.settings,
375
+ });
376
+ }
377
+ }
378
+ break;
379
+ case "NotificationNewsletterAdminPromote":
380
+ for (const update of updates) {
381
+ if (update.jid && update.user) {
382
+ ev.emit("newsletter-participants.update", {
383
+ id: update.jid,
384
+ author: node.attrs.from,
385
+ user: update.user,
386
+ new_role: "ADMIN",
387
+ action: "promote",
388
+ });
389
+ }
390
+ }
391
+ break;
392
+ case "NotificationLinkedProfilesUpdates":
393
+ for (const update of updates) {
394
+ const lid = update?.jid;
395
+ const addedProfiles = Array.isArray(update?.added_profiles)
396
+ ? update.added_profiles
397
+ : [];
398
+ const mappings = [];
399
+ for (const profile of addedProfiles) {
400
+ const pn =
401
+ typeof profile === "string"
402
+ ? profile
403
+ : (profile?.pn ?? profile?.jid ?? null);
404
+ if (lid && pn) {
405
+ const mapping = { lid, pn };
406
+ ev.emit("lid-mapping.update", mapping);
407
+ mappings.push(mapping);
408
+ }
409
+ }
410
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
411
+ }
412
+ break;
413
+ default:
414
+ logger.info(
415
+ { operation, data },
416
+ "unhandled mex newsletter notification",
417
+ );
418
+ break;
419
+ }
420
+ };
421
+ // Handles newsletter notifications
422
+ const handleNewsletterNotification = async (node) => {
423
+ const from = node.attrs.from;
424
+ const children = getAllBinaryNodeChildren(node);
425
+ const author = node.attrs.participant;
426
+ for (const child of children) {
427
+ logger.debug({ from, child }, "got newsletter notification");
428
+ switch (child.tag) {
429
+ case "reaction": {
430
+ const reactionUpdate = {
431
+ id: from,
432
+ server_id: child.attrs.message_id,
433
+ reaction: {
434
+ code: getBinaryNodeChildString(child, "reaction"),
435
+ count: 1,
436
+ },
437
+ };
438
+ ev.emit("newsletter.reaction", reactionUpdate);
439
+ break;
440
+ }
441
+ case "view": {
442
+ const viewUpdate = {
443
+ id: from,
444
+ server_id: child.attrs.message_id,
445
+ count: parseInt(child.content?.toString() || "0", 10),
446
+ };
447
+ ev.emit("newsletter.view", viewUpdate);
448
+ break;
449
+ }
450
+ case "participant": {
451
+ const participantUpdate = {
452
+ id: from,
453
+ author,
454
+ user: child.attrs.jid,
455
+ action: child.attrs.action,
456
+ new_role: child.attrs.role,
457
+ };
458
+ ev.emit("newsletter-participants.update", participantUpdate);
459
+ break;
460
+ }
461
+ case "update": {
462
+ const settingsNode = getBinaryNodeChild(child, "settings");
463
+ if (settingsNode) {
464
+ const update = {};
465
+ const nameNode = getBinaryNodeChild(settingsNode, "name");
466
+ if (nameNode?.content) update.name = nameNode.content.toString();
467
+ const descriptionNode = getBinaryNodeChild(
468
+ settingsNode,
469
+ "description",
470
+ );
471
+ if (descriptionNode?.content)
472
+ update.description = descriptionNode.content.toString();
473
+ ev.emit("newsletter-settings.update", {
474
+ id: from,
475
+ update,
476
+ });
477
+ }
478
+ break;
479
+ }
480
+ case "message": {
481
+ const plaintextNode = getBinaryNodeChild(child, "plaintext");
482
+ if (plaintextNode?.content) {
483
+ try {
484
+ const contentBuf =
485
+ typeof plaintextNode.content === "string"
486
+ ? Buffer.from(plaintextNode.content, "binary")
487
+ : Buffer.from(plaintextNode.content);
488
+ const messageProto = proto.Message.decode(contentBuf).toJSON();
489
+ const fullMessage = proto.WebMessageInfo.fromObject({
490
+ key: {
491
+ remoteJid: from,
492
+ id: child.attrs.message_id || child.attrs.server_id,
493
+ fromMe: false, // TODO: is this really true though
494
+ },
495
+ message: messageProto,
496
+ messageTimestamp: +child.attrs.t,
497
+ }).toJSON();
498
+ await upsertMessage(fullMessage, "append");
499
+ logger.debug("Processed plaintext newsletter message");
500
+ } catch (error) {
501
+ logger.error(
502
+ { error },
503
+ "Failed to decode plaintext newsletter message",
504
+ );
505
+ }
506
+ }
507
+ break;
508
+ }
509
+ default:
510
+ logger.warn({ node, child }, "Unknown newsletter notification child");
511
+ break;
512
+ }
513
+ }
514
+ };
515
+ const sendMessageAck = async (node, errorCode) => {
516
+ const stanza = buildAckStanza(node, errorCode, authState.creds.me.id);
517
+ logger.debug(
518
+ { recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs },
519
+ "sent ack",
520
+ );
521
+ await sendNode(stanza);
522
+ };
523
+ const rejectCall = async (callId, callFrom) => {
524
+ const stanza = {
525
+ tag: "call",
526
+ attrs: {
527
+ from: authState.creds.me.id,
528
+ to: callFrom,
529
+ },
530
+ content: [
531
+ {
532
+ tag: "reject",
533
+ attrs: {
534
+ "call-id": callId,
535
+ "call-creator": callFrom,
536
+ count: "0",
537
+ },
538
+ content: undefined,
539
+ },
540
+ ],
541
+ };
542
+ await query(stanza);
543
+ };
544
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
545
+ const { fullMessage } = decodeMessageNode(
546
+ node,
547
+ authState.creds.me.id,
548
+ authState.creds.me.lid || "",
549
+ );
550
+ const { key: msgKey } = fullMessage;
551
+ const msgId = msgKey.id;
552
+ if (messageRetryManager) {
553
+ // Check if we've exceeded max retries using the new system
554
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
555
+ logger.debug(
556
+ { msgId },
557
+ "reached retry limit with new retry manager, clearing",
558
+ );
559
+ messageRetryManager.markRetryFailed(msgId);
560
+ return;
561
+ }
562
+ // Increment retry count using new system
563
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
564
+ // Use the new retry count for the rest of the logic
565
+ const key = `${msgId}:${msgKey?.participant}`;
566
+ await msgRetryCache.set(key, retryCount);
567
+ } else {
568
+ // Fallback to old system
569
+ const key = `${msgId}:${msgKey?.participant}`;
570
+ let retryCount = (await msgRetryCache.get(key)) || 0;
571
+ if (retryCount >= maxMsgRetryCount) {
572
+ logger.debug({ retryCount, msgId }, "reached retry limit, clearing");
573
+ await msgRetryCache.del(key);
574
+ return;
575
+ }
576
+ retryCount += 1;
577
+ await msgRetryCache.set(key, retryCount);
578
+ }
579
+ const key = `${msgId}:${msgKey?.participant}`;
580
+ const retryCount = (await msgRetryCache.get(key)) || 1;
581
+ const {
582
+ account,
583
+ signedPreKey,
584
+ signedIdentityKey: identityKey,
585
+ } = authState.creds;
586
+ const fromJid = node.attrs.from;
587
+ // Check if we should recreate the session
588
+ let shouldRecreateSession = false;
589
+ let recreateReason = "";
590
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
591
+ try {
592
+ // Check if we have a session with this JID
593
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
594
+ const hasSession = await signalRepository.validateSession(fromJid);
595
+ const result = messageRetryManager.shouldRecreateSession(
596
+ fromJid,
597
+ hasSession.exists,
598
+ );
599
+ shouldRecreateSession = result.recreate;
600
+ recreateReason = result.reason;
601
+ if (shouldRecreateSession) {
602
+ logger.debug(
603
+ { fromJid, retryCount, reason: recreateReason },
604
+ "recreating session for retry",
605
+ );
606
+ // Delete existing session to force recreation
607
+ await authState.keys.set({
608
+ session: { [sessionId]: null },
609
+ });
610
+ forceIncludeKeys = true;
611
+ }
612
+ } catch (error) {
613
+ logger.warn({ error, fromJid }, "failed to check session recreation");
614
+ }
615
+ }
616
+ if (retryCount <= 2) {
617
+ // Use new retry manager for phone requests if available
618
+ if (messageRetryManager) {
619
+ // Schedule phone request with delay (like whatsmeow)
620
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
621
+ try {
622
+ const requestId = await requestPlaceholderResend(msgKey);
623
+ logger.debug(
624
+ `sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`,
625
+ );
626
+ } catch (error) {
627
+ logger.warn(
628
+ { error, msgId },
629
+ "failed to send scheduled phone request",
630
+ );
631
+ }
632
+ });
633
+ } else {
634
+ // Fallback to immediate request
635
+ const msgId = await requestPlaceholderResend(msgKey);
636
+ logger.debug(
637
+ `sendRetryRequest: requested placeholder resend for message ${msgId}`,
638
+ );
639
+ }
640
+ }
641
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true);
642
+ await authState.keys.transaction(async () => {
643
+ const receipt = {
644
+ tag: "receipt",
645
+ attrs: {
646
+ id: msgId,
647
+ type: "retry",
648
+ to: node.attrs.from,
649
+ },
650
+ content: [
651
+ {
652
+ tag: "retry",
653
+ attrs: {
654
+ count: retryCount.toString(),
655
+ id: node.attrs.id,
656
+ t: node.attrs.t,
657
+ v: "1",
658
+ // ADD ERROR FIELD
659
+ error: "0",
660
+ },
661
+ },
662
+ {
663
+ tag: "registration",
664
+ attrs: {},
665
+ content: encodeBigEndian(authState.creds.registrationId),
666
+ },
667
+ ],
668
+ };
669
+ if (node.attrs.recipient) {
670
+ receipt.attrs.recipient = node.attrs.recipient;
671
+ }
672
+ if (node.attrs.participant) {
673
+ receipt.attrs.participant = node.attrs.participant;
674
+ }
675
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
676
+ const { update, preKeys } = await getNextPreKeys(authState, 1);
677
+ const [keyId] = Object.keys(preKeys);
678
+ const key = preKeys[+keyId];
679
+ const content = receipt.content;
680
+ content.push({
681
+ tag: "keys",
682
+ attrs: {},
683
+ content: [
684
+ {
685
+ tag: "type",
686
+ attrs: {},
687
+ content: Buffer.from(KEY_BUNDLE_TYPE),
688
+ },
689
+ {
690
+ tag: "identity",
691
+ attrs: {},
692
+ content: identityKey.public,
693
+ },
694
+ xmppPreKey(key, +keyId),
695
+ xmppSignedPreKey(signedPreKey),
696
+ {
697
+ tag: "device-identity",
698
+ attrs: {},
699
+ content: deviceIdentity,
700
+ },
701
+ ],
702
+ });
703
+ ev.emit("creds.update", update);
704
+ }
705
+ await sendNode(receipt);
706
+ logger.info({ msgAttrs: node.attrs, retryCount }, "sent retry receipt");
707
+ }, authState?.creds?.me?.id || "sendRetryRequest");
708
+ };
709
+ // Mirrors WAWeb/Handle/PreKeyLow.js: skip a re-issued notification with the same stanza id.
710
+ const inFlightPreKeyLow = new Set();
711
+ /**
712
+ * Fire-and-forget tctoken re-issuance after a peer's device identity changed.
713
+ * Mirrors WAWebSendTcTokenWhenDeviceIdentityChange — runs in parallel with
714
+ * the session refresh (not after it).
715
+ */
716
+ const reissueTcTokenAfterIdentityChange = (from) => {
717
+ void (async () => {
718
+ const normalizedJid = jidNormalizedUser(from);
719
+ const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN);
720
+ const tcTokenData = await authState.keys.get("tctoken", [tcJid]);
721
+ const senderTs = tcTokenData?.[tcJid]?.senderTimestamp;
722
+ if (
723
+ senderTs === null ||
724
+ senderTs === undefined ||
725
+ isTcTokenExpired(senderTs)
726
+ ) {
727
+ return;
728
+ }
729
+ logger.debug(
730
+ { jid: normalizedJid, senderTimestamp: senderTs },
731
+ "identity changed, re-issuing tctoken",
732
+ );
733
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(
734
+ signalRepository.lidMapping,
735
+ );
736
+ const issueJid = await resolveIssuanceJid(
737
+ normalizedJid,
738
+ sock.serverProps.lidTrustedTokenIssueToLid,
739
+ getLIDForPN,
740
+ getPNForLID,
741
+ );
742
+ const result = await issuePrivacyTokens([issueJid], senderTs);
743
+ await storeTcTokensFromIqResult({
744
+ result,
745
+ fallbackJid: tcJid,
746
+ keys: authState.keys,
747
+ getLIDForPN,
748
+ onNewJidStored: trackTcTokenJid,
749
+ });
750
+ })().catch((err) => {
751
+ logger.debug(
752
+ { jid: from, err: err?.message },
753
+ "failed to re-issue tctoken after identity change",
754
+ );
755
+ });
756
+ };
757
+ const handleEncryptNotification = async (node) => {
758
+ const from = node.attrs.from;
759
+ if (from === S_WHATSAPP_NET) {
760
+ const stanzaId = node.attrs.id;
761
+ if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
762
+ return;
763
+ }
764
+ const countChild = getBinaryNodeChild(node, "count");
765
+ const count = +countChild.attrs.value;
766
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
767
+ logger.debug({ count, shouldUploadMorePreKeys }, "recv pre-key count");
768
+ if (shouldUploadMorePreKeys) {
769
+ if (stanzaId) inFlightPreKeyLow.add(stanzaId);
770
+ try {
771
+ await uploadPreKeys();
772
+ } finally {
773
+ if (stanzaId) inFlightPreKeyLow.delete(stanzaId);
774
+ }
775
+ }
776
+ } else {
777
+ const result = await handleIdentityChange(node, {
778
+ meId: authState.creds.me?.id,
779
+ meLid: authState.creds.me?.lid,
780
+ validateSession: signalRepository.validateSession,
781
+ assertSessions,
782
+ debounceCache: identityAssertDebounce,
783
+ logger,
784
+ onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange,
785
+ });
786
+ if (result.action === "no_identity_node") {
787
+ logger.info({ node }, "unknown encrypt notification");
788
+ }
789
+ }
790
+ };
791
+ const handleGroupNotification = (fullNode, child, msg) => {
792
+ // Handle both PN and LID for acting participant
793
+ const actingParticipantLid = fullNode.attrs.participant;
794
+ const actingParticipantPn = fullNode.attrs.participant_pn;
795
+ const actingParticipant = actingParticipantLid || actingParticipantPn;
796
+ const actingParticipantUsername = fullNode.attrs.participant_username;
797
+ const affectedParticipantLid =
798
+ getBinaryNodeChild(child, "participant")?.attrs?.jid || actingParticipant;
799
+ const affectedParticipantPn =
800
+ getBinaryNodeChild(child, "participant")?.attrs?.phone_number ||
801
+ actingParticipantPn;
802
+ switch (child?.tag) {
803
+ case "create":
804
+ const metadata = extractGroupMetadata(child);
805
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE;
806
+ msg.messageStubParameters = [metadata.subject];
807
+ msg.key = {
808
+ participant: metadata.owner,
809
+ participantAlt: metadata.ownerPn,
810
+ };
811
+ ev.emit("chats.upsert", [
812
+ {
813
+ id: metadata.id,
814
+ name: metadata.subject,
815
+ conversationTimestamp: metadata.creation,
816
+ },
817
+ ]);
818
+ ev.emit("groups.upsert", [
819
+ {
820
+ ...metadata,
821
+ author: actingParticipantLid,
822
+ authorPn: actingParticipantPn,
823
+ authorUsername: actingParticipantUsername,
824
+ },
825
+ ]);
826
+ break;
827
+ case "ephemeral":
828
+ case "not_ephemeral":
829
+ msg.message = {
830
+ protocolMessage: {
831
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
832
+ ephemeralExpiration: +(child.attrs.expiration || 0),
833
+ },
834
+ };
835
+ break;
836
+ case "modify":
837
+ const oldNumber = getBinaryNodeChildren(child, "participant").map(
838
+ (p) => p.attrs.jid,
839
+ );
840
+ msg.messageStubParameters = oldNumber || [];
841
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
842
+ break;
843
+ case "promote":
844
+ case "demote":
845
+ case "remove":
846
+ case "add":
847
+ case "leave":
848
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
849
+ msg.messageStubType = WAMessageStubType[stubType];
850
+ const participants = getBinaryNodeChildren(child, "participant").map(
851
+ ({ attrs }) => {
852
+ // TODO: Store LID MAPPINGS
853
+ return {
854
+ id: attrs.jid,
855
+ phoneNumber:
856
+ isLidUser(attrs.jid) && isPnUser(attrs.phone_number)
857
+ ? attrs.phone_number
858
+ : undefined,
859
+ lid:
860
+ isPnUser(attrs.jid) && isLidUser(attrs.lid)
861
+ ? attrs.lid
862
+ : undefined,
863
+ username:
864
+ attrs.participant_username || attrs.username || undefined,
865
+ admin: attrs.type || null,
866
+ };
867
+ },
868
+ );
869
+ if (
870
+ participants.length === 1 &&
871
+ // if recv. "remove" message and sender removed themselves
872
+ // mark as left
873
+ (areJidsSameUser(participants[0].id, actingParticipantLid) ||
874
+ areJidsSameUser(participants[0].id, actingParticipantPn)) &&
875
+ child.tag === "remove"
876
+ ) {
877
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
878
+ }
879
+ msg.messageStubParameters = participants.map((a) => JSON.stringify(a));
880
+ break;
881
+ case "subject":
882
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
883
+ msg.messageStubParameters = [child.attrs.subject];
884
+ break;
885
+ case "description":
886
+ const description = getBinaryNodeChild(
887
+ child,
888
+ "body",
889
+ )?.content?.toString();
890
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
891
+ msg.messageStubParameters = description ? [description] : undefined;
892
+ break;
893
+ case "announcement":
894
+ case "not_announcement":
895
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
896
+ msg.messageStubParameters = [
897
+ child.tag === "announcement" ? "on" : "off",
898
+ ];
899
+ break;
900
+ case "locked":
901
+ case "unlocked":
902
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
903
+ msg.messageStubParameters = [child.tag === "locked" ? "on" : "off"];
904
+ break;
905
+ case "invite":
906
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
907
+ msg.messageStubParameters = [child.attrs.code];
908
+ break;
909
+ case "member_add_mode":
910
+ const addMode = child.content;
911
+ if (addMode) {
912
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
913
+ msg.messageStubParameters = [addMode.toString()];
914
+ }
915
+ break;
916
+ case "membership_approval_mode":
917
+ const approvalMode = getBinaryNodeChild(child, "group_join");
918
+ if (approvalMode) {
919
+ msg.messageStubType =
920
+ WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
921
+ msg.messageStubParameters = [approvalMode.attrs.state];
922
+ }
923
+ break;
924
+ case "created_membership_requests":
925
+ msg.messageStubType =
926
+ WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
927
+ msg.messageStubParameters = [
928
+ JSON.stringify({
929
+ lid: affectedParticipantLid,
930
+ pn: affectedParticipantPn,
931
+ }),
932
+ "created",
933
+ child.attrs.request_method,
934
+ ];
935
+ break;
936
+ case "revoked_membership_requests":
937
+ const isDenied = areJidsSameUser(
938
+ affectedParticipantLid,
939
+ actingParticipantLid,
940
+ );
941
+ // TODO: LIDMAPPING SUPPORT
942
+ msg.messageStubType =
943
+ WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
944
+ msg.messageStubParameters = [
945
+ JSON.stringify({
946
+ lid: affectedParticipantLid,
947
+ pn: affectedParticipantPn,
948
+ }),
949
+ isDenied ? "revoked" : "rejected",
950
+ ];
951
+ break;
952
+ }
953
+ };
954
+ const handleDevicesNotification = async (node) => {
955
+ const [child] = getAllBinaryNodeChildren(node);
956
+ const from = jidNormalizedUser(node.attrs.from);
957
+ if (!child) {
958
+ logger.debug({ from }, "devices notification missing child, skipping");
959
+ return;
960
+ }
961
+ const tag = child.tag;
962
+ const deviceHash = child.attrs.device_hash;
963
+ const devices = getBinaryNodeChildren(child, "device");
964
+ if (
965
+ areJidsSameUser(from, authState.creds.me.id) ||
966
+ areJidsSameUser(from, authState.creds.me.lid)
967
+ ) {
968
+ const deviceJids = devices.map((d) => d.attrs.jid);
969
+ logger.info({ deviceJids }, "got my own devices");
970
+ }
971
+ if (!devices.length) {
972
+ logger.debug({ from, tag }, "no devices in notification, skipping");
973
+ return;
974
+ }
975
+ const decoded = [];
976
+ for (const d of devices) {
977
+ const jid = d.attrs.jid;
978
+ if (!jid) continue;
979
+ const parts = jidDecode(jid);
980
+ if (!parts) {
981
+ logger.debug({ jid }, "failed to decode device jid, skipping");
982
+ continue;
983
+ }
984
+ decoded.push({
985
+ jid,
986
+ user: parts.user,
987
+ server: parts.server,
988
+ device: parts.device,
989
+ });
990
+ }
991
+ if (!decoded.length) return;
992
+ await devicesMutex.mutex(async () => {
993
+ const byUser = new Map();
994
+ for (const d of decoded) {
995
+ const list = byUser.get(d.user) || [];
996
+ list.push(d);
997
+ byUser.set(d.user, list);
998
+ }
999
+ for (const [user, entries] of byUser) {
1000
+ if (tag === "update") {
1001
+ logger.debug(
1002
+ { user },
1003
+ `${user}'s device list updated, dropping cached devices`,
1004
+ );
1005
+ await userDevicesCache?.del(user);
1006
+ continue;
1007
+ }
1008
+ if (tag === "remove") {
1009
+ await signalRepository.deleteSession(entries.map((e) => e.jid));
1010
+ }
1011
+ const existingCache = (await userDevicesCache?.get(user)) || [];
1012
+ if (!existingCache.length) {
1013
+ // No baseline yet; skip applying the delta so getUSyncDevices can
1014
+ // later fetch the full device list. Caching just the notification
1015
+ // entries would make a partial list look authoritative.
1016
+ logger.debug(
1017
+ { user, tag },
1018
+ "device list not cached, deferring to USync refresh",
1019
+ );
1020
+ continue;
1021
+ }
1022
+ const affected = new Set(entries.map((e) => e.device));
1023
+ let updatedDevices;
1024
+ switch (tag) {
1025
+ case "add":
1026
+ logger.info({ deviceHash, count: entries.length }, "devices added");
1027
+ updatedDevices = [
1028
+ ...existingCache.filter((d) => !affected.has(d.device)),
1029
+ ...entries.map((e) => ({
1030
+ user: e.user,
1031
+ server: e.server,
1032
+ device: e.device,
1033
+ })),
1034
+ ];
1035
+ break;
1036
+ case "remove":
1037
+ logger.info(
1038
+ { deviceHash, count: entries.length },
1039
+ "devices removed",
1040
+ );
1041
+ updatedDevices = existingCache.filter(
1042
+ (d) => !affected.has(d.device),
1043
+ );
1044
+ break;
1045
+ default:
1046
+ logger.debug({ tag }, "Unknown device list change tag");
1047
+ continue;
1048
+ }
1049
+ if (updatedDevices.length === 0) {
1050
+ await userDevicesCache?.del(user);
1051
+ } else {
1052
+ await userDevicesCache?.set(user, updatedDevices);
1053
+ }
1054
+ }
1055
+ });
1056
+ };
1057
+ const processNotification = async (node) => {
1058
+ const result = {};
1059
+ const [child] = getAllBinaryNodeChildren(node);
1060
+ const nodeType = node.attrs.type;
1061
+ const from = jidNormalizedUser(node.attrs.from);
1062
+ switch (nodeType) {
1063
+ case "newsletter":
1064
+ await handleNewsletterNotification(node);
1065
+ break;
1066
+ case "mex":
1067
+ await handleMexNotification(node);
1068
+ break;
1069
+ case "w:gp2":
1070
+ // TODO: HANDLE PARTICIPANT_PN
1071
+ handleGroupNotification(node, child, result);
1072
+ break;
1073
+ case "mediaretry":
1074
+ const event = decodeMediaRetryNode(node);
1075
+ ev.emit("messages.media-update", [event]);
1076
+ break;
1077
+ case "encrypt":
1078
+ await handleEncryptNotification(node);
1079
+ break;
1080
+ case "devices":
1081
+ try {
1082
+ await handleDevicesNotification(node);
1083
+ } catch (error) {
1084
+ logger.error(
1085
+ { error, node },
1086
+ "failed to handle devices notification",
1087
+ );
1088
+ }
1089
+ break;
1090
+ case "server_sync":
1091
+ const update = getBinaryNodeChild(node, "collection");
1092
+ if (update) {
1093
+ const name = update.attrs.name;
1094
+ await resyncAppState([name], false);
1095
+ }
1096
+ break;
1097
+ case "picture":
1098
+ const setPicture = getBinaryNodeChild(node, "set");
1099
+ const delPicture = getBinaryNodeChild(node, "delete");
1100
+ // TODO: WAJIDHASH stuff proper support inhouse
1101
+ ev.emit("contacts.update", [
1102
+ {
1103
+ id:
1104
+ jidNormalizedUser(node?.attrs?.from) ||
1105
+ (setPicture || delPicture)?.attrs?.hash ||
1106
+ "",
1107
+ imgUrl: setPicture ? "changed" : "removed",
1108
+ },
1109
+ ]);
1110
+ if (isJidGroup(from)) {
1111
+ const node = setPicture || delPicture;
1112
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
1113
+ if (setPicture) {
1114
+ result.messageStubParameters = [setPicture.attrs.id];
1115
+ }
1116
+ result.participant = node?.attrs.author;
1117
+ result.key = {
1118
+ ...(result.key || {}),
1119
+ participant: setPicture?.attrs.author,
1120
+ };
1121
+ }
1122
+ break;
1123
+ case "account_sync":
1124
+ if (child.tag === "disappearing_mode") {
1125
+ const newDuration = +child.attrs.duration;
1126
+ const timestamp = +child.attrs.t;
1127
+ logger.info({ newDuration }, "updated account disappearing mode");
1128
+ ev.emit("creds.update", {
1129
+ accountSettings: {
1130
+ ...authState.creds.accountSettings,
1131
+ defaultDisappearingMode: {
1132
+ ephemeralExpiration: newDuration,
1133
+ ephemeralSettingTimestamp: timestamp,
1134
+ },
1135
+ },
1136
+ });
1137
+ } else if (child.tag === "blocklist") {
1138
+ const blocklists = getBinaryNodeChildren(child, "item");
1139
+ for (const { attrs } of blocklists) {
1140
+ const blocklist = [attrs.jid];
1141
+ const type = attrs.action === "block" ? "add" : "remove";
1142
+ ev.emit("blocklist.update", { blocklist, type });
1143
+ }
1144
+ }
1145
+ break;
1146
+ case "link_code_companion_reg":
1147
+ const linkCodeCompanionReg = getBinaryNodeChild(
1148
+ node,
1149
+ "link_code_companion_reg",
1150
+ );
1151
+ const ref = toRequiredBuffer(
1152
+ getBinaryNodeChildBuffer(
1153
+ linkCodeCompanionReg,
1154
+ "link_code_pairing_ref",
1155
+ ),
1156
+ );
1157
+ const primaryIdentityPublicKey = toRequiredBuffer(
1158
+ getBinaryNodeChildBuffer(
1159
+ linkCodeCompanionReg,
1160
+ "primary_identity_pub",
1161
+ ),
1162
+ );
1163
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(
1164
+ getBinaryNodeChildBuffer(
1165
+ linkCodeCompanionReg,
1166
+ "link_code_pairing_wrapped_primary_ephemeral_pub",
1167
+ ),
1168
+ );
1169
+ const codePairingPublicKey = await decipherLinkPublicKey(
1170
+ primaryEphemeralPublicKeyWrapped,
1171
+ );
1172
+ const companionSharedKey = Curve.sharedKey(
1173
+ authState.creds.pairingEphemeralKeyPair.private,
1174
+ codePairingPublicKey,
1175
+ );
1176
+ const random = randomBytes(32);
1177
+ const linkCodeSalt = randomBytes(32);
1178
+ const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
1179
+ salt: linkCodeSalt,
1180
+ info: "link_code_pairing_key_bundle_encryption_key",
1181
+ });
1182
+ const encryptPayload = Buffer.concat([
1183
+ Buffer.from(authState.creds.signedIdentityKey.public),
1184
+ primaryIdentityPublicKey,
1185
+ random,
1186
+ ]);
1187
+ const encryptIv = randomBytes(12);
1188
+ const encrypted = aesEncryptGCM(
1189
+ encryptPayload,
1190
+ linkCodePairingExpanded,
1191
+ encryptIv,
1192
+ Buffer.alloc(0),
1193
+ );
1194
+ const encryptedPayload = Buffer.concat([
1195
+ linkCodeSalt,
1196
+ encryptIv,
1197
+ encrypted,
1198
+ ]);
1199
+ const identitySharedKey = Curve.sharedKey(
1200
+ authState.creds.signedIdentityKey.private,
1201
+ primaryIdentityPublicKey,
1202
+ );
1203
+ const identityPayload = Buffer.concat([
1204
+ companionSharedKey,
1205
+ identitySharedKey,
1206
+ random,
1207
+ ]);
1208
+ authState.creds.advSecretKey = Buffer.from(
1209
+ hkdf(identityPayload, 32, { info: "adv_secret" }),
1210
+ ).toString("base64");
1211
+ await query({
1212
+ tag: "iq",
1213
+ attrs: {
1214
+ to: S_WHATSAPP_NET,
1215
+ type: "set",
1216
+ id: sock.generateMessageTag(),
1217
+ xmlns: "md",
1218
+ },
1219
+ content: [
1220
+ {
1221
+ tag: "link_code_companion_reg",
1222
+ attrs: {
1223
+ jid: authState.creds.me.id,
1224
+ stage: "companion_finish",
1225
+ },
1226
+ content: [
1227
+ {
1228
+ tag: "link_code_pairing_wrapped_key_bundle",
1229
+ attrs: {},
1230
+ content: encryptedPayload,
1231
+ },
1232
+ {
1233
+ tag: "companion_identity_public",
1234
+ attrs: {},
1235
+ content: authState.creds.signedIdentityKey.public,
1236
+ },
1237
+ {
1238
+ tag: "link_code_pairing_ref",
1239
+ attrs: {},
1240
+ content: ref,
1241
+ },
1242
+ ],
1243
+ },
1244
+ ],
1245
+ });
1246
+ authState.creds.registered = true;
1247
+ ev.emit("creds.update", authState.creds);
1248
+ break;
1249
+ case "privacy_token":
1250
+ await handlePrivacyTokenNotification(node);
1251
+ break;
1252
+ }
1253
+ if (Object.keys(result).length) {
1254
+ return result;
1255
+ }
1256
+ };
1257
+ /**
1258
+ * In-memory cache of storage JIDs with stored tctokens, seeded from the persisted index.
1259
+ * Used to coalesce writes during a session; pruning always re-reads the persisted index
1260
+ * to cover writes made by other layers (e.g. history sync).
1261
+ */
1262
+ const tcTokenKnownJids = new Set();
1263
+ const tcTokenIndexLoaded = (async () => {
1264
+ try {
1265
+ const jids = await readTcTokenIndex(authState.keys);
1266
+ for (const jid of jids) tcTokenKnownJids.add(jid);
1267
+ logger.debug({ count: tcTokenKnownJids.size }, "loaded tctoken index");
1268
+ } catch (err) {
1269
+ logger.warn({ err: err?.message }, "failed to load tctoken index");
1270
+ }
1271
+ })();
1272
+ let tcTokenIndexTimer;
1273
+ async function flushTcTokenIndex() {
1274
+ if (tcTokenIndexTimer) {
1275
+ clearTimeout(tcTokenIndexTimer);
1276
+ tcTokenIndexTimer = undefined;
1277
+ }
1278
+ // Merge with whatever is already persisted so we don't clobber writes from other
1279
+ // paths (history sync, concurrent sessions on the same store).
1280
+ const write = await buildMergedTcTokenIndexWrite(
1281
+ authState.keys,
1282
+ tcTokenKnownJids,
1283
+ );
1284
+ return authState.keys.set({ tctoken: write });
1285
+ }
1286
+ function scheduleTcTokenIndexSave() {
1287
+ if (tcTokenIndexTimer) {
1288
+ clearTimeout(tcTokenIndexTimer);
1289
+ }
1290
+ tcTokenIndexTimer = setTimeout(() => {
1291
+ tcTokenIndexTimer = undefined;
1292
+ flushTcTokenIndex().catch((err) => {
1293
+ logger.warn({ err: err?.message }, "failed to save tctoken index");
1294
+ });
1295
+ }, 5000);
1296
+ }
1297
+ function trackTcTokenJid(jid) {
1298
+ if (jid && jid !== TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
1299
+ tcTokenKnownJids.add(jid);
1300
+ scheduleTcTokenIndexSave();
1301
+ }
1302
+ }
1303
+ const handlePrivacyTokenNotification = async (node) => {
1304
+ const tokensNode = getBinaryNodeChild(node, "tokens");
1305
+ if (!tokensNode) return;
1306
+ const from = jidNormalizedUser(node.attrs.from);
1307
+ // WA Web uses: senderLid ?? toLid(from) for the storage key
1308
+ // The sender_lid attribute provides the LID directly when available
1309
+ const senderLid =
1310
+ node.attrs.sender_lid &&
1311
+ isLidUser(jidNormalizedUser(node.attrs.sender_lid))
1312
+ ? jidNormalizedUser(node.attrs.sender_lid)
1313
+ : undefined;
1314
+ const fallbackJid =
1315
+ senderLid ?? (await resolveTcTokenJid(from, getLIDForPN));
1316
+ logger.debug(
1317
+ { from, storageJid: fallbackJid },
1318
+ "processing privacy token notification",
1319
+ );
1320
+ await storeTcTokensFromIqResult({
1321
+ result: node,
1322
+ fallbackJid,
1323
+ keys: authState.keys,
1324
+ getLIDForPN,
1325
+ onNewJidStored: trackTcTokenJid,
1326
+ });
1327
+ };
1328
+ async function decipherLinkPublicKey(data) {
1329
+ const buffer = toRequiredBuffer(data);
1330
+ const salt = buffer.slice(0, 32);
1331
+ const secretKey = await derivePairingCodeKey(
1332
+ authState.creds.pairingCode,
1333
+ salt,
1334
+ );
1335
+ const iv = buffer.slice(32, 48);
1336
+ const payload = buffer.slice(48, 80);
1337
+ return aesDecryptCTR(payload, secretKey, iv);
1338
+ }
1339
+ function toRequiredBuffer(data) {
1340
+ if (data === undefined) {
1341
+ throw new Boom("Invalid buffer", { statusCode: 400 });
1342
+ }
1343
+ return data instanceof Buffer ? data : Buffer.from(data);
1344
+ }
1345
+ const willSendMessageAgain = async (id, participant) => {
1346
+ const key = `${id}:${participant}`;
1347
+ const retryCount = (await msgRetryCache.get(key)) || 0;
1348
+ return retryCount < maxMsgRetryCount;
1349
+ };
1350
+ const updateSendMessageAgainCount = async (id, participant) => {
1351
+ const key = `${id}:${participant}`;
1352
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
1353
+ await msgRetryCache.set(key, newValue);
1354
+ };
1355
+ const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
1356
+ const remoteJid = key.remoteJid;
1357
+ const participant = key.participant || remoteJid;
1358
+ const retryCount = +retryNode.attrs.count || 1;
1359
+ const msgId = ids[0];
1360
+ // Try to get messages from cache first, then fallback to getMessage
1361
+ const msgs = [];
1362
+ for (const id of ids) {
1363
+ let msg;
1364
+ // Try to get from retry cache first if enabled
1365
+ if (messageRetryManager) {
1366
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
1367
+ if (cachedMsg) {
1368
+ msg = cachedMsg.message;
1369
+ logger.debug({ jid: remoteJid, id }, "found message in retry cache");
1370
+ // Mark retry as successful since we found the message
1371
+ messageRetryManager.markRetrySuccess(id);
1372
+ }
1373
+ }
1374
+ // Fallback to getMessage if not found in cache
1375
+ if (!msg) {
1376
+ msg = await getMessage({ ...key, id });
1377
+ if (msg) {
1378
+ logger.debug({ jid: remoteJid, id }, "found message via getMessage");
1379
+ // Also mark as successful if found via getMessage
1380
+ if (messageRetryManager) {
1381
+ messageRetryManager.markRetrySuccess(id);
1382
+ }
1383
+ }
1384
+ }
1385
+ msgs.push(msg);
1386
+ }
1387
+ // if it's the primary jid sending the request
1388
+ // just re-send the message to everyone
1389
+ // prevents the first message decryption failure
1390
+ const sendToAll = !jidDecode(participant)?.device;
1391
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
1392
+ let injectedFromBundle = false;
1393
+ const bundle = extractE2ESessionFromRetryReceipt(receiptNode);
1394
+ if (bundle) {
1395
+ try {
1396
+ await signalRepository.injectE2ESession({
1397
+ jid: participant,
1398
+ session: bundle,
1399
+ });
1400
+ injectedFromBundle = true;
1401
+ logger.debug(
1402
+ { participant, retryCount },
1403
+ "injected session from retry receipt key bundle",
1404
+ );
1405
+ } catch (error) {
1406
+ logger.warn(
1407
+ { error, participant },
1408
+ "failed to inject session from retry receipt",
1409
+ );
1410
+ }
1411
+ }
1412
+ if (!injectedFromBundle) {
1413
+ const receivedRegId = getBinaryNodeChildUInt(
1414
+ receiptNode,
1415
+ "registration",
1416
+ 4,
1417
+ );
1418
+ if (
1419
+ typeof receivedRegId === "number" &&
1420
+ Number.isInteger(receivedRegId)
1421
+ ) {
1422
+ const info = await signalRepository.getSessionInfo(participant);
1423
+ if (
1424
+ info &&
1425
+ info.registrationId !== 0 &&
1426
+ info.registrationId !== receivedRegId
1427
+ ) {
1428
+ logger.info(
1429
+ {
1430
+ participant,
1431
+ stored: info.registrationId,
1432
+ received: receivedRegId,
1433
+ },
1434
+ "reg id mismatch on retry without bundle, deleting session",
1435
+ );
1436
+ await authState.keys.set({
1437
+ session: { [sessionId]: null },
1438
+ });
1439
+ }
1440
+ }
1441
+ }
1442
+ const BASE_KEY_CHECK_RETRY = 2;
1443
+ if (msgId && messageRetryManager) {
1444
+ const info = await signalRepository.getSessionInfo(participant);
1445
+ if (info) {
1446
+ if (retryCount === BASE_KEY_CHECK_RETRY) {
1447
+ messageRetryManager.saveBaseKey(sessionId, msgId, info.baseKey);
1448
+ } else if (retryCount > BASE_KEY_CHECK_RETRY) {
1449
+ if (
1450
+ messageRetryManager.hasSameBaseKey(sessionId, msgId, info.baseKey)
1451
+ ) {
1452
+ logger.warn(
1453
+ { participant, retryCount },
1454
+ "base key collision on retry, forcing fresh session",
1455
+ );
1456
+ await authState.keys.set({
1457
+ session: { [sessionId]: null },
1458
+ });
1459
+ }
1460
+ messageRetryManager.deleteBaseKey(sessionId, msgId);
1461
+ }
1462
+ }
1463
+ }
1464
+ let shouldRecreateSession = false;
1465
+ let recreateReason = "";
1466
+ if (
1467
+ enableAutoSessionRecreation &&
1468
+ messageRetryManager &&
1469
+ retryCount > 1 &&
1470
+ !injectedFromBundle
1471
+ ) {
1472
+ try {
1473
+ const hasSession = await signalRepository.validateSession(participant);
1474
+ const result = messageRetryManager.shouldRecreateSession(
1475
+ participant,
1476
+ hasSession.exists,
1477
+ );
1478
+ shouldRecreateSession = result.recreate;
1479
+ recreateReason = result.reason;
1480
+ if (shouldRecreateSession) {
1481
+ logger.debug(
1482
+ { participant, retryCount, reason: recreateReason },
1483
+ "recreating session for outgoing retry",
1484
+ );
1485
+ await authState.keys.set({
1486
+ session: { [sessionId]: null },
1487
+ });
1488
+ }
1489
+ } catch (error) {
1490
+ logger.warn(
1491
+ { error, participant },
1492
+ "failed to check session recreation for outgoing retry",
1493
+ );
1494
+ }
1495
+ }
1496
+ if (!injectedFromBundle) {
1497
+ await assertSessions([participant], true);
1498
+ }
1499
+ if (isJidGroup(remoteJid)) {
1500
+ await authState.keys.set({
1501
+ "sender-key-memory": { [remoteJid]: null },
1502
+ });
1503
+ }
1504
+ logger.debug(
1505
+ {
1506
+ participant,
1507
+ sendToAll,
1508
+ shouldRecreateSession,
1509
+ recreateReason,
1510
+ injectedFromBundle,
1511
+ },
1512
+ "prepared session for retry resend",
1513
+ );
1514
+ for (const [i, msg] of msgs.entries()) {
1515
+ if (!ids[i]) continue;
1516
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
1517
+ await updateSendMessageAgainCount(ids[i], participant);
1518
+ const msgRelayOpts = { messageId: ids[i] };
1519
+ if (sendToAll) {
1520
+ msgRelayOpts.useUserDevicesCache = false;
1521
+ } else {
1522
+ msgRelayOpts.participant = {
1523
+ jid: participant,
1524
+ count: +retryNode.attrs.count,
1525
+ };
1526
+ }
1527
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
1528
+ } else {
1529
+ logger.debug(
1530
+ { jid: key.remoteJid, id: ids[i] },
1531
+ "recv retry request, but message not available",
1532
+ );
1533
+ }
1534
+ }
1535
+ };
1536
+ const handleReceipt = async (node) => {
1537
+ const { attrs, content } = node;
1538
+ const isLid = attrs.from.includes("lid");
1539
+ const isNodeFromMe = areJidsSameUser(
1540
+ attrs.participant || attrs.from,
1541
+ isLid ? authState.creds.me?.lid : authState.creds.me?.id,
1542
+ );
1543
+ const remoteJid =
1544
+ !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
1545
+ const fromMe =
1546
+ !attrs.recipient ||
1547
+ ((attrs.type === "retry" || attrs.type === "sender") && isNodeFromMe);
1548
+ const key = {
1549
+ remoteJid,
1550
+ id: "",
1551
+ fromMe,
1552
+ participant: attrs.participant,
1553
+ };
1554
+ const ids = [attrs.id];
1555
+ if (Array.isArray(content)) {
1556
+ const items = getBinaryNodeChildren(content[0], "item");
1557
+ ids.push(...items.map((i) => i.attrs.id));
1558
+ }
1559
+ try {
1560
+ await Promise.all([
1561
+ receiptMutex.mutex(async () => {
1562
+ const status = getStatusFromReceiptType(attrs.type);
1563
+ if (
1564
+ typeof status !== "undefined" &&
1565
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
1566
+ // or another device of ours has read some messages
1567
+ (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)
1568
+ ) {
1569
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
1570
+ if (attrs.participant) {
1571
+ if (attrs.participant.endsWith("lid")) {
1572
+ let after = signalRepository.lidMapping.getPNForLIDSync(
1573
+ attrs.participant,
1574
+ );
1575
+ if (after && after.endsWith("net"))
1576
+ attrs.participant = jidNormalizedUser(after);
1577
+ }
1578
+ const updateKey =
1579
+ status === proto.WebMessageInfo.Status.DELIVERY_ACK
1580
+ ? "receiptTimestamp"
1581
+ : "readTimestamp";
1582
+ ev.emit(
1583
+ "message-receipt.update",
1584
+ ids.map((id) => ({
1585
+ key: { ...key, id },
1586
+ receipt: {
1587
+ userJid: jidNormalizedUser(attrs.participant),
1588
+ [updateKey]: +attrs.t,
1589
+ },
1590
+ })),
1591
+ );
1592
+ }
1593
+ } else {
1594
+ ev.emit(
1595
+ "messages.update",
1596
+ ids.map((id) => ({
1597
+ key: { ...key, id },
1598
+ update: {
1599
+ status,
1600
+ messageTimestamp: toNumber(+(attrs.t ?? 0)),
1601
+ },
1602
+ })),
1603
+ );
1604
+ }
1605
+ }
1606
+ if (attrs.type === "retry") {
1607
+ // correctly set who is asking for the retry
1608
+ key.participant = key.participant || attrs.from;
1609
+ const retryNode = getBinaryNodeChild(node, "retry");
1610
+ if (
1611
+ ids[0] &&
1612
+ key.participant &&
1613
+ (await willSendMessageAgain(ids[0], key.participant))
1614
+ ) {
1615
+ if (key.fromMe) {
1616
+ try {
1617
+ await updateSendMessageAgainCount(ids[0], key.participant);
1618
+ logger.debug({ attrs, key }, "recv retry request");
1619
+ await sendMessagesAgain(key, ids, retryNode, node);
1620
+ } catch (error) {
1621
+ logger.error(
1622
+ {
1623
+ key,
1624
+ ids,
1625
+ trace:
1626
+ error instanceof Error ? error.stack : "Unknown error",
1627
+ },
1628
+ "error in sending message again",
1629
+ );
1630
+ }
1631
+ } else {
1632
+ logger.info(
1633
+ { attrs, key },
1634
+ "recv retry for not fromMe message",
1635
+ );
1636
+ }
1637
+ } else {
1638
+ logger.info(
1639
+ { attrs, key },
1640
+ "will not send message again, as sent too many times",
1641
+ );
1642
+ }
1643
+ }
1644
+ }),
1645
+ ]);
1646
+ } finally {
1647
+ await sendMessageAck(node).catch((ackErr) =>
1648
+ logger.error({ ackErr }, "failed to ack receipt"),
1649
+ );
1650
+ }
1651
+ };
1652
+ const handleNotification = async (node) => {
1653
+ const remoteJid = node.attrs.from;
1654
+ try {
1655
+ await Promise.all([
1656
+ notificationMutex.mutex(async () => {
1657
+ const msg = await processNotification(node);
1658
+ if (msg) {
1659
+ const fromMe = areJidsSameUser(
1660
+ node.attrs.participant || remoteJid,
1661
+ authState.creds.me.id,
1662
+ );
1663
+ const { senderAlt: participantAlt, addressingMode } =
1664
+ extractAddressingContext(node);
1665
+ msg.key = {
1666
+ remoteJid,
1667
+ fromMe,
1668
+ participant: node.attrs.participant,
1669
+ participantAlt,
1670
+ participantUsername: node.attrs.participant_username,
1671
+ addressingMode,
1672
+ id: node.attrs.id,
1673
+ ...(msg.key || {}),
1674
+ };
1675
+ msg.participant ?? (msg.participant = node.attrs.participant);
1676
+ msg.messageTimestamp = +node.attrs.t;
1677
+ const fullMsg = proto.WebMessageInfo.fromObject(msg);
1678
+ await upsertMessage(fullMsg, "append");
1679
+ }
1680
+ }),
1681
+ ]);
1682
+ } finally {
1683
+ await sendMessageAck(node).catch((ackErr) =>
1684
+ logger.error({ ackErr }, "failed to ack notification"),
1685
+ );
1686
+ }
1687
+ };
1688
+ const handleMessage = async (node) => {
1689
+ const encNode = getBinaryNodeChild(node, "enc");
1690
+ // Improved handling for failed msmsg decryption
1691
+ if (encNode?.attrs.type === "msmsg") {
1692
+ logger.warn(
1693
+ { key: node.attrs.key, attrs: encNode.attrs },
1694
+ "msmsg decryption failed or not supported, ignoring",
1695
+ );
1696
+ await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
1697
+ return;
1698
+ }
1699
+ let acked = false;
1700
+ try {
1701
+ const {
1702
+ fullMessage: msg,
1703
+ category,
1704
+ author,
1705
+ decrypt,
1706
+ } = decryptMessageNode(
1707
+ node,
1708
+ authState.creds.me.id,
1709
+ authState.creds.me.lid || "",
1710
+ signalRepository,
1711
+ logger,
1712
+ );
1713
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
1714
+ // store new mappings we didn't have before
1715
+ if (!!alt) {
1716
+ const altServer = jidDecode(alt)?.server;
1717
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
1718
+ if (altServer === "lid") {
1719
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
1720
+ await signalRepository.lidMapping.storeLIDPNMappings([
1721
+ { lid: alt, pn: primaryJid },
1722
+ ]);
1723
+ await signalRepository.migrateSession(primaryJid, alt);
1724
+ }
1725
+ } else {
1726
+ await signalRepository.lidMapping.storeLIDPNMappings([
1727
+ { lid: primaryJid, pn: alt },
1728
+ ]);
1729
+ await signalRepository.migrateSession(alt, primaryJid);
1730
+ }
1731
+ }
1732
+ await messageMutex.mutex(async () => {
1733
+ await decrypt();
1734
+ if (
1735
+ msg.key?.remoteJid &&
1736
+ msg.key?.id &&
1737
+ msg.message &&
1738
+ messageRetryManager
1739
+ ) {
1740
+ messageRetryManager.addRecentMessage(
1741
+ msg.key.remoteJid,
1742
+ msg.key.id,
1743
+ msg.message,
1744
+ );
1745
+ }
1746
+ // message failed to decrypt
1747
+ if (
1748
+ msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT &&
1749
+ msg.category !== "peer"
1750
+ ) {
1751
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
1752
+ acked = true;
1753
+ return sendMessageAck(node, NACK_REASONS.ParsingError);
1754
+ }
1755
+ if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
1756
+ // Message arrived without encryption (e.g. CTWA ads messages).
1757
+ // Check if this is eligible for placeholder resend (matching WA Web filters).
1758
+ const unavailableNode = getBinaryNodeChild(node, "unavailable");
1759
+ const unavailableType = unavailableNode?.attrs?.type;
1760
+ if (
1761
+ unavailableType === "bot_unavailable_fanout" ||
1762
+ unavailableType === "hosted_unavailable_fanout" ||
1763
+ unavailableType === "view_once_unavailable_fanout"
1764
+ ) {
1765
+ logger.debug(
1766
+ { msgId: msg.key.id, unavailableType },
1767
+ "upserting unavailable stub for notification",
1768
+ );
1769
+ await upsertMessage(msg, "append");
1770
+ acked = true;
1771
+ return sendMessageAck(node);
1772
+ }
1773
+ const messageAge =
1774
+ unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1775
+ if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
1776
+ logger.debug(
1777
+ { msgId: msg.key.id, messageAge },
1778
+ "skipping placeholder resend for old message",
1779
+ );
1780
+ acked = true;
1781
+ return sendMessageAck(node);
1782
+ }
1783
+ // Request the real content from the phone via placeholder resend PDO.
1784
+ // Upsert the CIPHERTEXT stub as a placeholder (like WA Web's processPlaceholderMsg),
1785
+ // and store the requestId in stubParameters[1] so users can correlate
1786
+ // with the incoming PDO response event.
1787
+ const cleanKey = {
1788
+ remoteJid: msg.key.remoteJid,
1789
+ fromMe: msg.key.fromMe,
1790
+ id: msg.key.id,
1791
+ participant: msg.key.participant,
1792
+ };
1793
+ // Cache the original message metadata so the PDO response handler
1794
+ // can preserve key fields (LID details etc.) that the phone may omit
1795
+ const msgData = {
1796
+ key: msg.key,
1797
+ messageTimestamp: msg.messageTimestamp,
1798
+ pushName: msg.pushName,
1799
+ participant: msg.participant,
1800
+ verifiedBizName: msg.verifiedBizName,
1801
+ };
1802
+ requestPlaceholderResend(cleanKey, msgData)
1803
+ .then((requestId) => {
1804
+ if (requestId && requestId !== "RESOLVED") {
1805
+ logger.debug(
1806
+ { msgId: msg.key.id, requestId },
1807
+ "requested placeholder resend for unavailable message",
1808
+ );
1809
+ ev.emit("messages.update", [
1810
+ {
1811
+ key: msg.key,
1812
+ update: {
1813
+ messageStubParameters: [
1814
+ NO_MESSAGE_FOUND_ERROR_TEXT,
1815
+ requestId,
1816
+ ],
1817
+ },
1818
+ },
1819
+ ]);
1820
+ }
1821
+ })
1822
+ .catch((err) => {
1823
+ logger.warn(
1824
+ { err, msgId: msg.key.id },
1825
+ "failed to request placeholder resend for unavailable message",
1826
+ );
1827
+ });
1828
+ acked = true;
1829
+ await sendMessageAck(node);
1830
+ // Don't return — fall through to upsertMessage so the stub is emitted
1831
+ } else {
1832
+ // Skip retry for expired status messages (>24h old)
1833
+ if (isJidStatusBroadcast(msg.key.remoteJid)) {
1834
+ const messageAge =
1835
+ unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1836
+ if (messageAge > STATUS_EXPIRY_SECONDS) {
1837
+ logger.debug(
1838
+ {
1839
+ msgId: msg.key.id,
1840
+ messageAge,
1841
+ remoteJid: msg.key.remoteJid,
1842
+ },
1843
+ "skipping retry for expired status message",
1844
+ );
1845
+ acked = true;
1846
+ return sendMessageAck(node);
1847
+ }
1848
+ }
1849
+ logger.debug(
1850
+ "[handleMessage] Attempting retry request for failed decryption",
1851
+ );
1852
+ // WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
1853
+ await retryMutex.mutex(async () => {
1854
+ try {
1855
+ if (!ws.isOpen) {
1856
+ logger.debug({ node }, "Connection closed, skipping retry");
1857
+ return;
1858
+ }
1859
+ const encNode = getBinaryNodeChild(node, "enc");
1860
+ await sendRetryRequest(node, !encNode);
1861
+ if (retryRequestDelayMs) {
1862
+ await delay(retryRequestDelayMs);
1863
+ }
1864
+ } catch (err) {
1865
+ logger.error({ err }, "Failed to send retry");
1866
+ }
1867
+ acked = true;
1868
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
1869
+ });
1870
+ }
1871
+ } else {
1872
+ if (messageRetryManager && msg.key.id) {
1873
+ messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
1874
+ }
1875
+ const isNewsletter = isJidNewsletter(msg.key.remoteJid);
1876
+ if (!isNewsletter) {
1877
+ // no type in the receipt => message delivered
1878
+ let type = undefined;
1879
+ let participant = msg.key.participant;
1880
+ if (category === "peer") {
1881
+ // special peer message
1882
+ type = "peer_msg";
1883
+ } else if (msg.key.fromMe) {
1884
+ // message was sent by us from a different device
1885
+ type = "sender";
1886
+ // need to specially handle this case
1887
+ if (
1888
+ isLidUser(msg.key.remoteJid) ||
1889
+ isLidUser(msg.key.remoteJidAlt)
1890
+ ) {
1891
+ participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1892
+ }
1893
+ } else if (!sendActiveReceipts) {
1894
+ type = "inactive";
1895
+ }
1896
+ acked = true;
1897
+ await sendReceipt(
1898
+ msg.key.remoteJid,
1899
+ participant,
1900
+ [msg.key.id],
1901
+ type,
1902
+ );
1903
+ // send ack for history message
1904
+ const isAnyHistoryMsg = getHistoryMsg(msg.message);
1905
+ if (isAnyHistoryMsg) {
1906
+ const jid = jidNormalizedUser(msg.key.remoteJid);
1907
+ await sendReceipt(jid, undefined, [msg.key.id], "hist_sync"); // TODO: investigate
1908
+ }
1909
+ } else {
1910
+ acked = true;
1911
+ await sendMessageAck(node);
1912
+ logger.debug(
1913
+ { key: msg.key },
1914
+ "processed newsletter message without receipts",
1915
+ );
1916
+ }
1917
+ }
1918
+ cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1919
+ await upsertMessage(msg, node.attrs.offline ? "append" : "notify");
1920
+ });
1921
+ } catch (error) {
1922
+ logger.error(
1923
+ { error, node: binaryNodeToString(node) },
1924
+ "error in handling message",
1925
+ );
1926
+ if (!acked) {
1927
+ await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(
1928
+ (ackErr) =>
1929
+ logger.error({ ackErr }, "failed to ack message after error"),
1930
+ );
1931
+ }
1932
+ }
1933
+ };
1934
+ const handleCall = async (node) => {
1935
+ try {
1936
+ const { attrs } = node;
1937
+ const [infoChild] = getAllBinaryNodeChildren(node);
1938
+ if (!infoChild) {
1939
+ throw new Boom("Missing call info in call node");
1940
+ }
1941
+ const status = getCallStatusFromNode(infoChild);
1942
+ const callId = infoChild.attrs["call-id"];
1943
+ const from = infoChild.attrs.from || infoChild.attrs["call-creator"];
1944
+ const call = {
1945
+ chatId: attrs.from,
1946
+ from,
1947
+ callerPn: infoChild.attrs["caller_pn"],
1948
+ id: callId,
1949
+ date: new Date(+attrs.t * 1000),
1950
+ offline: !!attrs.offline,
1951
+ status,
1952
+ };
1953
+ if (status === "relaylatency") {
1954
+ const latencyValue =
1955
+ infoChild.attrs.latency ||
1956
+ infoChild.attrs["latency_ms"] ||
1957
+ infoChild.attrs["latency-ms"];
1958
+ const latencyMs = latencyValue ? Number(latencyValue) : undefined;
1959
+ if (Number.isFinite(latencyMs)) {
1960
+ call.latencyMs = latencyMs;
1961
+ }
1962
+ }
1963
+ if (status === "offer") {
1964
+ call.isVideo = !!getBinaryNodeChild(infoChild, "video");
1965
+ call.isGroup =
1966
+ infoChild.attrs.type === "group" || !!infoChild.attrs["group-jid"];
1967
+ call.groupJid = infoChild.attrs["group-jid"];
1968
+ await callOfferCache.set(call.id, call);
1969
+ }
1970
+ const existingCall = await callOfferCache.get(call.id);
1971
+ // use existing call info to populate this event
1972
+ if (existingCall) {
1973
+ call.isVideo = existingCall.isVideo;
1974
+ call.isGroup = existingCall.isGroup;
1975
+ call.callerPn = call.callerPn || existingCall.callerPn;
1976
+ }
1977
+ // delete data once call has ended
1978
+ if (
1979
+ status === "reject" ||
1980
+ status === "accept" ||
1981
+ status === "timeout" ||
1982
+ status === "terminate"
1983
+ ) {
1984
+ await callOfferCache.del(call.id);
1985
+ }
1986
+ ev.emit("call", [call]);
1987
+ } catch (error) {
1988
+ logger.error(
1989
+ { error, node: binaryNodeToString(node) },
1990
+ "error in handling call",
1991
+ );
1992
+ } finally {
1993
+ await sendMessageAck(node).catch((ackErr) =>
1994
+ logger.error({ ackErr }, "failed to ack call"),
1995
+ );
1996
+ }
1997
+ };
1998
+ const handleBadAck = async ({ attrs }) => {
1999
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
2000
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
2001
+ // // current hypothesis is that if pash is sent in the ack
2002
+ // // it means -- the message hasn't reached all devices yet
2003
+ // // we'll retry sending the message here
2004
+ // if(attrs.phash) {
2005
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
2006
+ // const msg = await getMessage(key)
2007
+ // if(msg) {
2008
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
2009
+ // } else {
2010
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
2011
+ // }
2012
+ // }
2013
+ // error in acknowledgement,
2014
+ // device could not display the message
2015
+ if (attrs.error) {
2016
+ const isReachoutTimelocked =
2017
+ attrs.error === String(NACK_REASONS.SenderReachoutTimelocked);
2018
+ if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
2019
+ // 463 = 1:1 message missing privacy token (tctoken). Usually means the
2020
+ // account is restricted: WhatsApp blocks starting new chats but preserves
2021
+ // existing ones, since established chats already carry a tctoken.
2022
+ // WA Web prevents this client-side (disables the compose bar).
2023
+ // No retry — retrying counts as another "reach out" and worsens the restriction.
2024
+ logger.warn(
2025
+ { msgId: attrs.id, from: attrs.from },
2026
+ "error 463: account restricted or missing tctoken for contact",
2027
+ );
2028
+ const ackFrom = attrs.from;
2029
+ if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
2030
+ inFlight463Recoveries.add(ackFrom);
2031
+ void (async () => {
2032
+ try {
2033
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(
2034
+ signalRepository.lidMapping,
2035
+ );
2036
+ const tcStorageJid = await resolveTcTokenJid(
2037
+ ackFrom,
2038
+ getLIDForPN,
2039
+ );
2040
+ const issueJid = await resolveIssuanceJid(
2041
+ ackFrom,
2042
+ sock.serverProps.lidTrustedTokenIssueToLid,
2043
+ getLIDForPN,
2044
+ getPNForLID,
2045
+ );
2046
+ const result = await issuePrivacyTokens(
2047
+ [issueJid],
2048
+ unixTimestampSeconds(),
2049
+ );
2050
+ await storeTcTokensFromIqResult({
2051
+ result,
2052
+ fallbackJid: tcStorageJid,
2053
+ keys: authState.keys,
2054
+ getLIDForPN,
2055
+ onNewJidStored: trackTcTokenJid,
2056
+ });
2057
+ logger.debug(
2058
+ { from: ackFrom },
2059
+ "completed 463 token recovery issuance",
2060
+ );
2061
+ } catch (err) {
2062
+ logger.debug(
2063
+ { from: ackFrom, err: err?.message },
2064
+ "failed 463 token recovery issuance",
2065
+ );
2066
+ } finally {
2067
+ inFlight463Recoveries.delete(ackFrom);
2068
+ }
2069
+ })();
2070
+ }
2071
+ } else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
2072
+ logger.warn(
2073
+ { msgId: attrs.id, from: attrs.from },
2074
+ "smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing",
2075
+ );
2076
+ } else if (isReachoutTimelocked) {
2077
+ // user is temporarily restricted, fetch current restriction details
2078
+ await fetchAccountReachoutTimelock().catch((err) =>
2079
+ logger.warn({ err }, "failed to fetch reachout timelock"),
2080
+ );
2081
+ logger.warn({ attrs }, "received error in ack");
2082
+ } else {
2083
+ logger.warn({ attrs }, "received error in ack");
2084
+ }
2085
+ ev.emit("messages.update", [
2086
+ {
2087
+ key,
2088
+ update: {
2089
+ status: WAMessageStatus.ERROR,
2090
+ messageStubParameters: isReachoutTimelocked
2091
+ ? [attrs.error, ACCOUNT_RESTRICTED_TEXT]
2092
+ : [attrs.error],
2093
+ },
2094
+ },
2095
+ ]);
2096
+ }
2097
+ };
2098
+ /// processes a node with the given function
2099
+ /// and adds the task to the existing buffer if we're buffering events
2100
+ const processNodeWithBuffer = async (node, identifier, exec) => {
2101
+ ev.buffer();
2102
+ await execTask();
2103
+ ev.flush();
2104
+ function execTask() {
2105
+ return exec(node, false).catch((err) =>
2106
+ onUnexpectedError(err, identifier),
2107
+ );
2108
+ }
2109
+ };
2110
+ const offlineNodeProcessor = makeOfflineNodeProcessor(
2111
+ new Map([
2112
+ ["message", handleMessage],
2113
+ ["call", handleCall],
2114
+ ["receipt", handleReceipt],
2115
+ ["notification", handleNotification],
2116
+ ]),
2117
+ {
2118
+ isWsOpen: () => ws.isOpen,
2119
+ onUnexpectedError,
2120
+ yieldToEventLoop: () => new Promise((resolve) => setImmediate(resolve)),
2121
+ },
2122
+ );
2123
+ const processNode = async (type, node, identifier, exec) => {
2124
+ // Fast path: ack and drop ignored JIDs before entering the buffer/queue
2125
+ const from = node.attrs.from;
2126
+ let ignoreJid = from;
2127
+ if (type === "receipt" && from) {
2128
+ const attrs = node.attrs;
2129
+ const isLid = attrs.from.includes("lid");
2130
+ const isNodeFromMe = areJidsSameUser(
2131
+ attrs.participant || attrs.from,
2132
+ isLid ? authState.creds.me?.lid : authState.creds.me?.id,
2133
+ );
2134
+ ignoreJid =
2135
+ !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
2136
+ }
2137
+ if (
2138
+ ignoreJid &&
2139
+ ignoreJid !== S_WHATSAPP_NET &&
2140
+ shouldIgnoreJid(ignoreJid)
2141
+ ) {
2142
+ await sendMessageAck(
2143
+ node,
2144
+ type === "message" ? NACK_REASONS.UnhandledError : undefined,
2145
+ );
2146
+ return;
2147
+ }
2148
+ const isOffline = !!node.attrs.offline;
2149
+ if (isOffline) {
2150
+ offlineNodeProcessor.enqueue(type, node);
2151
+ } else {
2152
+ await processNodeWithBuffer(node, identifier, exec);
2153
+ }
2154
+ };
2155
+ // recv a message
2156
+ ws.on("CB:message", async (node) => {
2157
+ await processNode("message", node, "processing message", handleMessage);
2158
+ });
2159
+ ws.on("CB:call", async (node) => {
2160
+ await processNode("call", node, "handling call", handleCall);
2161
+ });
2162
+ ws.on("CB:receipt", async (node) => {
2163
+ await processNode("receipt", node, "handling receipt", handleReceipt);
2164
+ });
2165
+ ws.on("CB:notification", async (node) => {
2166
+ await processNode(
2167
+ "notification",
2168
+ node,
2169
+ "handling notification",
2170
+ handleNotification,
2171
+ );
2172
+ });
2173
+ ws.on("CB:ack,class:message", (node) => {
2174
+ handleBadAck(node).catch((error) =>
2175
+ onUnexpectedError(error, "handling bad ack"),
2176
+ );
2177
+ });
2178
+ ev.on("call", async ([call]) => {
2179
+ if (!call) {
2180
+ return;
2181
+ }
2182
+ // missed call + group call notification message generation
2183
+ if (
2184
+ call.status === "timeout" ||
2185
+ (call.status === "offer" && call.isGroup)
2186
+ ) {
2187
+ const msg = {
2188
+ key: {
2189
+ remoteJid: call.chatId,
2190
+ id: call.id,
2191
+ fromMe: false,
2192
+ },
2193
+ messageTimestamp: unixTimestampSeconds(call.date),
2194
+ };
2195
+ if (call.status === "timeout") {
2196
+ if (call.isGroup) {
2197
+ msg.messageStubType = call.isVideo
2198
+ ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
2199
+ : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
2200
+ } else {
2201
+ msg.messageStubType = call.isVideo
2202
+ ? WAMessageStubType.CALL_MISSED_VIDEO
2203
+ : WAMessageStubType.CALL_MISSED_VOICE;
2204
+ }
2205
+ } else {
2206
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
2207
+ }
2208
+ const protoMsg = proto.WebMessageInfo.fromObject(msg);
2209
+ await upsertMessage(protoMsg, call.offline ? "append" : "notify");
2210
+ }
2211
+ });
2212
+ /** timestamp of last tctoken prune run — throttles to once per 24h */
2213
+ let lastTcTokenPruneTs = 0;
2214
+ /** dedupe in-flight 463 recovery token issuance by target JID */
2215
+ const inFlight463Recoveries = new Set();
2216
+ ev.on("connection.update", ({ isOnline, connection }) => {
2217
+ if (typeof isOnline !== "undefined") {
2218
+ sendActiveReceipts = isOnline;
2219
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
2220
+ }
2221
+ // Flush pending tctoken index save on disconnect to avoid writing after close
2222
+ if (connection === "close" && tcTokenIndexTimer) {
2223
+ clearTimeout(tcTokenIndexTimer);
2224
+ tcTokenIndexTimer = undefined;
2225
+ // Best-effort flush — may fail if store is already closed
2226
+ try {
2227
+ void Promise.resolve(flushTcTokenIndex()).catch(() => {});
2228
+ } catch {
2229
+ /* ignore sync errors */
2230
+ }
2231
+ }
2232
+ // Prune expired tctokens when coming online, at most once per 24 hours
2233
+ // Matches WA Web's CLEAN_TC_TOKENS task
2234
+ // Note: don't gate on tcTokenKnownJids.size — the index may still be loading
2235
+ if (isOnline) {
2236
+ const now = Date.now();
2237
+ const DAY_MS = 24 * 60 * 60 * 1000;
2238
+ if (now - lastTcTokenPruneTs >= DAY_MS) {
2239
+ lastTcTokenPruneTs = now;
2240
+ void pruneExpiredTcTokens();
2241
+ }
2242
+ }
2243
+ });
2244
+ registerSocketEndHandler(() => {
2245
+ if (!config.msgRetryCounterCache && msgRetryCache.close) {
2246
+ msgRetryCache.close();
2247
+ }
2248
+ if (!config.callOfferCache && callOfferCache.close) {
2249
+ callOfferCache.close();
2250
+ }
2251
+ identityAssertDebounce.close();
2252
+ sendActiveReceipts = false;
2253
+ });
2254
+ async function pruneExpiredTcTokens() {
2255
+ try {
2256
+ await tcTokenIndexLoaded;
2257
+ // Union with the persisted index picks up JIDs added by other layers
2258
+ // (history sync) without needing inter-module wiring.
2259
+ const persisted = await readTcTokenIndex(authState.keys);
2260
+ const allJids = new Set(tcTokenKnownJids);
2261
+ for (const jid of persisted) allJids.add(jid);
2262
+ if (!allJids.size) return;
2263
+ const jids = [...allJids];
2264
+ const allTokens = await authState.keys.get("tctoken", jids);
2265
+ const writes = {};
2266
+ const survivors = new Set();
2267
+ let mutated = 0;
2268
+ for (const jid of jids) {
2269
+ const entry = allTokens[jid];
2270
+ if (!entry) {
2271
+ // Tracked but nothing in store — drop from index.
2272
+ mutated++;
2273
+ continue;
2274
+ }
2275
+ const hasPeerToken = !!entry.token?.length;
2276
+ const peerTokenExpired =
2277
+ hasPeerToken && isTcTokenExpired(entry.timestamp);
2278
+ const hasSenderTs = entry.senderTimestamp !== undefined;
2279
+ const senderTsExpired =
2280
+ hasSenderTs && isTcTokenExpired(entry.senderTimestamp);
2281
+ const keepPeerToken = hasPeerToken && !peerTokenExpired;
2282
+ const keepSenderTs = hasSenderTs && !senderTsExpired;
2283
+ if (!keepPeerToken && !keepSenderTs) {
2284
+ writes[jid] = null;
2285
+ mutated++;
2286
+ } else if (peerTokenExpired && keepSenderTs) {
2287
+ writes[jid] = {
2288
+ token: Buffer.alloc(0),
2289
+ senderTimestamp: entry.senderTimestamp,
2290
+ };
2291
+ survivors.add(jid);
2292
+ mutated++;
2293
+ } else {
2294
+ survivors.add(jid);
2295
+ }
2296
+ }
2297
+ if (mutated === 0) return;
2298
+ await authState.keys.set({
2299
+ tctoken: {
2300
+ ...writes,
2301
+ [TC_TOKEN_INDEX_KEY]: {
2302
+ token: Buffer.from(JSON.stringify([...survivors])),
2303
+ },
2304
+ },
2305
+ });
2306
+ tcTokenKnownJids.clear();
2307
+ for (const jid of survivors) tcTokenKnownJids.add(jid);
2308
+ logger.debug(
2309
+ { mutated, remaining: survivors.size },
2310
+ "pruned expired tctokens",
2311
+ );
2312
+ } catch (err) {
2313
+ logger.warn({ err: err?.message }, "failed to prune expired tctokens");
2314
+ }
2315
+ }
2316
+ return {
2317
+ ...sock,
2318
+ sendMessageAck,
2319
+ sendRetryRequest,
2320
+ rejectCall,
2321
+ fetchMessageHistory,
2322
+ requestPlaceholderResend,
2323
+ messageRetryManager,
2324
+ };
2325
+ };