@codexverified/baileys 2.7.5

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