@ikyyjee/ikyysinggle 1.7.7

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