@rakku-kun/baileys 2.0.14 → 2.0.16

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 (175) hide show
  1. package/WAProto/fix-imports.js +22 -18
  2. package/WAProto/index.js +22 -18
  3. package/lib/Defaults/index.d.ts +8 -7
  4. package/lib/Defaults/index.d.ts.map +1 -1
  5. package/lib/Defaults/index.js +11 -17
  6. package/lib/Defaults/index.js.map +1 -1
  7. package/lib/Signal/libsignal.d.ts.map +1 -1
  8. package/lib/Signal/libsignal.js +52 -59
  9. package/lib/Signal/libsignal.js.map +1 -1
  10. package/lib/Signal/lid-mapping.d.ts.map +1 -1
  11. package/lib/Signal/lid-mapping.js.map +1 -1
  12. package/lib/Socket/business.d.ts +18 -3
  13. package/lib/Socket/business.d.ts.map +1 -1
  14. package/lib/Socket/chats.d.ts +16 -2
  15. package/lib/Socket/chats.d.ts.map +1 -1
  16. package/lib/Socket/chats.js +238 -173
  17. package/lib/Socket/chats.js.map +1 -1
  18. package/lib/Socket/communities.d.ts +18 -3
  19. package/lib/Socket/communities.d.ts.map +1 -1
  20. package/lib/Socket/groups.d.ts +13 -2
  21. package/lib/Socket/groups.d.ts.map +1 -1
  22. package/lib/Socket/groups.js +26 -138
  23. package/lib/Socket/groups.js.map +1 -1
  24. package/lib/Socket/index.d.ts +18 -3
  25. package/lib/Socket/index.d.ts.map +1 -1
  26. package/lib/Socket/messages-recv.d.ts +22 -6
  27. package/lib/Socket/messages-recv.d.ts.map +1 -1
  28. package/lib/Socket/messages-recv.js +736 -645
  29. package/lib/Socket/messages-recv.js.map +1 -1
  30. package/lib/Socket/messages-send.d.ts +18 -2
  31. package/lib/Socket/messages-send.d.ts.map +1 -1
  32. package/lib/Socket/messages-send.js +152 -642
  33. package/lib/Socket/messages-send.js.map +1 -1
  34. package/lib/Socket/newsletter.d.ts +11 -1
  35. package/lib/Socket/newsletter.d.ts.map +1 -1
  36. package/lib/Socket/newsletter.js +3 -92
  37. package/lib/Socket/newsletter.js.map +1 -1
  38. package/lib/Socket/socket.d.ts +6 -2
  39. package/lib/Socket/socket.d.ts.map +1 -1
  40. package/lib/Socket/socket.js +61 -35
  41. package/lib/Socket/socket.js.map +1 -1
  42. package/lib/Types/Auth.d.ts +1 -0
  43. package/lib/Types/Auth.d.ts.map +1 -1
  44. package/lib/Types/Call.d.ts +1 -1
  45. package/lib/Types/Call.d.ts.map +1 -1
  46. package/lib/Types/Chat.d.ts +1 -0
  47. package/lib/Types/Chat.d.ts.map +1 -1
  48. package/lib/Types/Contact.d.ts +2 -0
  49. package/lib/Types/Contact.d.ts.map +1 -1
  50. package/lib/Types/Events.d.ts +20 -1
  51. package/lib/Types/Events.d.ts.map +1 -1
  52. package/lib/Types/GroupMetadata.d.ts +4 -0
  53. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  54. package/lib/Types/Message.d.ts +25 -200
  55. package/lib/Types/Message.d.ts.map +1 -1
  56. package/lib/Types/Message.js.map +1 -1
  57. package/lib/Types/Mex.d.ts +141 -0
  58. package/lib/Types/Mex.d.ts.map +1 -0
  59. package/lib/Types/Mex.js +37 -0
  60. package/lib/Types/Mex.js.map +1 -0
  61. package/lib/Types/Signal.d.ts +12 -1
  62. package/lib/Types/Signal.d.ts.map +1 -1
  63. package/lib/Types/Socket.d.ts +3 -0
  64. package/lib/Types/Socket.d.ts.map +1 -1
  65. package/lib/Types/State.d.ts +58 -0
  66. package/lib/Types/State.d.ts.map +1 -1
  67. package/lib/Types/State.js +43 -0
  68. package/lib/Types/State.js.map +1 -1
  69. package/lib/Types/index.d.ts +2 -1
  70. package/lib/Types/index.d.ts.map +1 -1
  71. package/lib/Types/index.js +1 -2
  72. package/lib/Types/index.js.map +1 -1
  73. package/lib/Utils/auth-utils.d.ts +5 -0
  74. package/lib/Utils/auth-utils.d.ts.map +1 -1
  75. package/lib/Utils/auth-utils.js +12 -0
  76. package/lib/Utils/auth-utils.js.map +1 -1
  77. package/lib/Utils/browser-utils.d.ts.map +1 -1
  78. package/lib/Utils/browser-utils.js +21 -33
  79. package/lib/Utils/browser-utils.js.map +1 -1
  80. package/lib/Utils/chat-utils.d.ts +31 -1
  81. package/lib/Utils/chat-utils.d.ts.map +1 -1
  82. package/lib/Utils/chat-utils.js +80 -20
  83. package/lib/Utils/chat-utils.js.map +1 -1
  84. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  85. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  86. package/lib/Utils/companion-reg-client-utils.js +35 -0
  87. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  88. package/lib/Utils/decode-wa-message.d.ts +18 -0
  89. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  90. package/lib/Utils/decode-wa-message.js +34 -0
  91. package/lib/Utils/decode-wa-message.js.map +1 -1
  92. package/lib/Utils/event-buffer.d.ts +2 -0
  93. package/lib/Utils/event-buffer.d.ts.map +1 -1
  94. package/lib/Utils/event-buffer.js +49 -1
  95. package/lib/Utils/event-buffer.js.map +1 -1
  96. package/lib/Utils/generics.d.ts +1 -0
  97. package/lib/Utils/generics.d.ts.map +1 -1
  98. package/lib/Utils/generics.js +10 -28
  99. package/lib/Utils/generics.js.map +1 -1
  100. package/lib/Utils/history.d.ts +2 -0
  101. package/lib/Utils/history.d.ts.map +1 -1
  102. package/lib/Utils/history.js +12 -9
  103. package/lib/Utils/history.js.map +1 -1
  104. package/lib/Utils/identity-change-handler.d.ts +7 -0
  105. package/lib/Utils/identity-change-handler.d.ts.map +1 -1
  106. package/lib/Utils/identity-change-handler.js +1 -0
  107. package/lib/Utils/identity-change-handler.js.map +1 -1
  108. package/lib/Utils/index.d.ts +2 -2
  109. package/lib/Utils/index.d.ts.map +1 -1
  110. package/lib/Utils/index.js +2 -7
  111. package/lib/Utils/index.js.map +1 -1
  112. package/lib/Utils/link-preview.js +2 -2
  113. package/lib/Utils/link-preview.js.map +1 -1
  114. package/lib/Utils/message-retry-manager.d.ts +5 -0
  115. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  116. package/lib/Utils/message-retry-manager.js +40 -0
  117. package/lib/Utils/message-retry-manager.js.map +1 -1
  118. package/lib/Utils/messages-media.d.ts +4 -1
  119. package/lib/Utils/messages-media.d.ts.map +1 -1
  120. package/lib/Utils/messages-media.js +131 -173
  121. package/lib/Utils/messages-media.js.map +1 -1
  122. package/lib/Utils/messages.d.ts +0 -1
  123. package/lib/Utils/messages.d.ts.map +1 -1
  124. package/lib/Utils/messages.js +100 -906
  125. package/lib/Utils/messages.js.map +1 -1
  126. package/lib/Utils/offline-node-processor.d.ts +17 -0
  127. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  128. package/lib/Utils/offline-node-processor.js +40 -0
  129. package/lib/Utils/offline-node-processor.js.map +1 -0
  130. package/lib/Utils/process-message.d.ts.map +1 -1
  131. package/lib/Utils/process-message.js +103 -1
  132. package/lib/Utils/process-message.js.map +1 -1
  133. package/lib/Utils/signal.d.ts +13 -0
  134. package/lib/Utils/signal.d.ts.map +1 -1
  135. package/lib/Utils/signal.js +42 -0
  136. package/lib/Utils/signal.js.map +1 -1
  137. package/lib/Utils/stanza-ack.d.ts +11 -0
  138. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  139. package/lib/Utils/stanza-ack.js +38 -0
  140. package/lib/Utils/stanza-ack.js.map +1 -0
  141. package/lib/Utils/sync-action-utils.d.ts.map +1 -1
  142. package/lib/Utils/sync-action-utils.js +1 -0
  143. package/lib/Utils/sync-action-utils.js.map +1 -1
  144. package/lib/Utils/tc-token-utils.d.ts +26 -1
  145. package/lib/Utils/tc-token-utils.d.ts.map +1 -1
  146. package/lib/Utils/tc-token-utils.js +151 -5
  147. package/lib/Utils/tc-token-utils.js.map +1 -1
  148. package/lib/Utils/validate-connection.d.ts.map +1 -1
  149. package/lib/Utils/validate-connection.js +12 -2
  150. package/lib/Utils/validate-connection.js.map +1 -1
  151. package/lib/WABinary/generic-utils.js +0 -15
  152. package/lib/WABinary/index.js +0 -1
  153. package/lib/WABinary/jid-utils.js +0 -2
  154. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  155. package/lib/WAUSync/Protocols/USyncContactProtocol.js +26 -3
  156. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  157. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  158. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  159. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  160. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  161. package/lib/WAUSync/Protocols/index.d.ts +1 -0
  162. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  163. package/lib/WAUSync/Protocols/index.js +2 -2
  164. package/lib/WAUSync/Protocols/index.js.map +1 -1
  165. package/lib/WAUSync/USyncQuery.d.ts +1 -0
  166. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  167. package/lib/WAUSync/USyncQuery.js +6 -2
  168. package/lib/WAUSync/USyncQuery.js.map +1 -1
  169. package/lib/WAUSync/USyncUser.d.ts +4 -0
  170. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  171. package/lib/WAUSync/USyncUser.js +8 -0
  172. package/lib/WAUSync/USyncUser.js.map +1 -1
  173. package/lib/index.d.ts +1 -1
  174. package/lib/index.js +10 -24
  175. package/package.json +2 -2
@@ -4,17 +4,24 @@ import { randomBytes } from 'crypto';
4
4
  import Long from 'long';
5
5
  import { proto } from '../../WAProto/index.js';
6
6
  import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/index.js';
7
- import { WAMessageStatus, WAMessageStubType } from '../Types/index.js';
8
- import { aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, NO_MESSAGE_FOUND_ERROR_TEXT, toNumber, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/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, 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
9
  import { makeMutex } from '../Utils/make-mutex.js';
10
- import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.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';
11
14
  import { extractGroupMetadata } from './groups.js';
12
15
  import { makeMessagesSocket } from './messages-send.js';
13
- import { USyncQuery, USyncUser } from '../WAUSync/index.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
+ }
14
20
  export const makeMessagesRecvSocket = (config) => {
15
21
  const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
16
22
  const sock = makeMessagesSocket(config);
17
- const { ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
23
+ 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 } = sock;
24
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
18
25
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
19
26
  const retryMutex = makeMutex();
20
27
  const msgRetryCache = config.msgRetryCounterCache ||
@@ -27,11 +34,6 @@ export const makeMessagesRecvSocket = (config) => {
27
34
  stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
28
35
  useClones: false
29
36
  });
30
- const placeholderResendCache = config.placeholderResendCache ||
31
- new NodeCache({
32
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
33
- useClones: false
34
- });
35
37
  // Debounce identity-change session refreshes per JID to avoid bursts
36
38
  const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
37
39
  let sendActiveReceipts = false;
@@ -85,25 +87,140 @@ export const makeMessagesRecvSocket = (config) => {
85
87
  }, 8000);
86
88
  return sendPeerDataOperationMessage(pdoMessage);
87
89
  };
88
- // Handles mex newsletter notifications
89
- const handleMexNewsletterNotification = async (node) => {
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) => {
90
193
  const mexNode = getBinaryNodeChild(node, 'mex');
91
- if (!mexNode?.content) {
92
- logger.warn({ node }, 'Invalid mex newsletter notification');
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');
93
198
  return;
94
199
  }
95
200
  let data;
96
201
  try {
97
- data = JSON.parse(mexNode.content.toString());
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());
98
209
  }
99
210
  catch (error) {
100
- logger.error({ err: error, node }, 'Failed to parse mex newsletter notification');
211
+ logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification');
101
212
  return;
102
213
  }
103
- const operation = data?.operation;
104
- const updates = data?.updates;
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
+ }
105
222
  if (!updates || !operation) {
106
- logger.warn({ data }, 'Invalid mex newsletter notification content');
223
+ logger.warn({ data }, 'invalid mex newsletter notification content');
107
224
  return;
108
225
  }
109
226
  logger.info({ operation, updates }, 'got mex newsletter notification');
@@ -131,119 +248,119 @@ export const makeMessagesRecvSocket = (config) => {
131
248
  }
132
249
  }
133
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;
134
267
  default:
135
- logger.info({ operation, data }, 'Unhandled mex newsletter notification');
268
+ logger.info({ operation, data }, 'unhandled mex newsletter notification');
136
269
  break;
137
270
  }
138
271
  };
139
272
  // Handles newsletter notifications
140
273
  const handleNewsletterNotification = async (node) => {
141
274
  const from = node.attrs.from;
142
- const child = getAllBinaryNodeChildren(node)[0];
275
+ const children = getAllBinaryNodeChildren(node);
143
276
  const author = node.attrs.participant;
144
- logger.info({ from, child }, 'got newsletter notification');
145
- switch (child.tag) {
146
- case 'reaction':
147
- const reactionUpdate = {
148
- id: from,
149
- server_id: child.attrs.message_id,
150
- reaction: {
151
- code: getBinaryNodeChildString(child, 'reaction'),
152
- count: 1
153
- }
154
- };
155
- ev.emit('newsletter.reaction', reactionUpdate);
156
- break;
157
- case 'view':
158
- const viewUpdate = {
159
- id: from,
160
- server_id: child.attrs.message_id,
161
- count: parseInt(child.content?.toString() || '0', 10)
162
- };
163
- ev.emit('newsletter.view', viewUpdate);
164
- break;
165
- case 'participant':
166
- const participantUpdate = {
167
- id: from,
168
- author,
169
- user: child.attrs.jid,
170
- action: child.attrs.action,
171
- new_role: child.attrs.role
172
- };
173
- ev.emit('newsletter-participants.update', participantUpdate);
174
- break;
175
- case 'update':
176
- const settingsNode = getBinaryNodeChild(child, 'settings');
177
- if (settingsNode) {
178
- const update = {};
179
- const nameNode = getBinaryNodeChild(settingsNode, 'name');
180
- if (nameNode?.content)
181
- update.name = nameNode.content.toString();
182
- const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
183
- if (descriptionNode?.content)
184
- update.description = descriptionNode.content.toString();
185
- ev.emit('newsletter-settings.update', {
277
+ for (const child of children) {
278
+ logger.debug({ from, child }, 'got newsletter notification');
279
+ switch (child.tag) {
280
+ case 'reaction': {
281
+ const reactionUpdate = {
186
282
  id: from,
187
- update
188
- });
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;
189
291
  }
190
- break;
191
- case 'message':
192
- const plaintextNode = getBinaryNodeChild(child, 'plaintext');
193
- if (plaintextNode?.content) {
194
- try {
195
- const contentBuf = typeof plaintextNode.content === 'string'
196
- ? Buffer.from(plaintextNode.content, 'binary')
197
- : Buffer.from(plaintextNode.content);
198
- const messageProto = proto.Message.decode(contentBuf).toJSON();
199
- const fullMessage = proto.WebMessageInfo.fromObject({
200
- key: {
201
- remoteJid: from,
202
- id: child.attrs.message_id || child.attrs.server_id,
203
- fromMe: false // TODO: is this really true though
204
- },
205
- message: messageProto,
206
- messageTimestamp: +child.attrs.t
207
- }).toJSON();
208
- await upsertMessage(fullMessage, 'notify');
209
- logger.info('Processed plaintext newsletter message');
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
+ });
210
326
  }
211
- catch (error) {
212
- logger.error({ error }, 'Failed to decode plaintext newsletter message');
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
+ }
213
352
  }
353
+ break;
214
354
  }
215
- break;
216
- default:
217
- logger.warn({ node }, 'Unknown newsletter notification');
218
- break;
219
- }
220
- };
221
- const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
222
- const stanza = {
223
- tag: 'ack',
224
- attrs: {
225
- id: attrs.id,
226
- to: attrs.from,
227
- class: tag
355
+ default:
356
+ logger.warn({ node, child }, 'Unknown newsletter notification child');
357
+ break;
228
358
  }
229
- };
230
- if (!!errorCode) {
231
- stanza.attrs.error = errorCode.toString();
232
- }
233
- if (!!attrs.participant) {
234
- stanza.attrs.participant = attrs.participant;
235
- }
236
- if (!!attrs.recipient) {
237
- stanza.attrs.recipient = attrs.recipient;
238
- }
239
- if (!!attrs.type &&
240
- (tag !== 'message' || getBinaryNodeChild({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
241
- stanza.attrs.type = attrs.type;
242
359
  }
243
- if (tag === 'message' && getBinaryNodeChild({ tag, attrs, content }, 'unavailable')) {
244
- stanza.attrs.from = authState.creds.me.id;
245
- }
246
- logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
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');
247
364
  await sendNode(stanza);
248
365
  };
249
366
  const rejectCall = async (callId, callFrom) => {
@@ -398,15 +515,58 @@ export const makeMessagesRecvSocket = (config) => {
398
515
  logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
399
516
  }, authState?.creds?.me?.id || 'sendRetryRequest');
400
517
  };
518
+ // Mirrors WAWeb/Handle/PreKeyLow.js: skip a re-issued notification with the same stanza id.
519
+ const inFlightPreKeyLow = new Set();
520
+ /**
521
+ * Fire-and-forget tctoken re-issuance after a peer's device identity changed.
522
+ * Mirrors WAWebSendTcTokenWhenDeviceIdentityChange — runs in parallel with
523
+ * the session refresh (not after it).
524
+ */
525
+ const reissueTcTokenAfterIdentityChange = (from) => {
526
+ void (async () => {
527
+ const normalizedJid = jidNormalizedUser(from);
528
+ const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN);
529
+ const tcTokenData = await authState.keys.get('tctoken', [tcJid]);
530
+ const senderTs = tcTokenData?.[tcJid]?.senderTimestamp;
531
+ if (senderTs === null || senderTs === undefined || isTcTokenExpired(senderTs)) {
532
+ return;
533
+ }
534
+ logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken');
535
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
536
+ const issueJid = await resolveIssuanceJid(normalizedJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
537
+ const result = await issuePrivacyTokens([issueJid], senderTs);
538
+ await storeTcTokensFromIqResult({
539
+ result,
540
+ fallbackJid: tcJid,
541
+ keys: authState.keys,
542
+ getLIDForPN,
543
+ onNewJidStored: trackTcTokenJid
544
+ });
545
+ })().catch(err => {
546
+ logger.debug({ jid: from, err: err?.message }, 'failed to re-issue tctoken after identity change');
547
+ });
548
+ };
401
549
  const handleEncryptNotification = async (node) => {
402
550
  const from = node.attrs.from;
403
551
  if (from === S_WHATSAPP_NET) {
552
+ const stanzaId = node.attrs.id;
553
+ if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
554
+ return;
555
+ }
404
556
  const countChild = getBinaryNodeChild(node, 'count');
405
557
  const count = +countChild.attrs.value;
406
558
  const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
407
559
  logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
408
560
  if (shouldUploadMorePreKeys) {
409
- await uploadPreKeys();
561
+ if (stanzaId)
562
+ inFlightPreKeyLow.add(stanzaId);
563
+ try {
564
+ await uploadPreKeys();
565
+ }
566
+ finally {
567
+ if (stanzaId)
568
+ inFlightPreKeyLow.delete(stanzaId);
569
+ }
410
570
  }
411
571
  }
412
572
  else {
@@ -416,7 +576,8 @@ export const makeMessagesRecvSocket = (config) => {
416
576
  validateSession: signalRepository.validateSession,
417
577
  assertSessions,
418
578
  debounceCache: identityAssertDebounce,
419
- logger
579
+ logger,
580
+ onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
420
581
  });
421
582
  if (result.action === 'no_identity_node') {
422
583
  logger.info({ node }, 'unknown encrypt notification');
@@ -427,6 +588,7 @@ export const makeMessagesRecvSocket = (config) => {
427
588
  // TODO: Support PN/LID (Here is only LID now)
428
589
  const actingParticipantLid = fullNode.attrs.participant;
429
590
  const actingParticipantPn = fullNode.attrs.participant_pn;
591
+ const actingParticipantUsername = fullNode.attrs.participant_username;
430
592
  const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
431
593
  const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
432
594
  switch (child?.tag) {
@@ -446,7 +608,8 @@ export const makeMessagesRecvSocket = (config) => {
446
608
  {
447
609
  ...metadata,
448
610
  author: actingParticipantLid,
449
- authorPn: actingParticipantPn
611
+ authorPn: actingParticipantPn,
612
+ authorUsername: actingParticipantUsername
450
613
  }
451
614
  ]);
452
615
  break;
@@ -477,6 +640,7 @@ export const makeMessagesRecvSocket = (config) => {
477
640
  id: attrs.jid,
478
641
  phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
479
642
  lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
643
+ username: attrs.participant_username || attrs.username || undefined,
480
644
  admin: (attrs.type || null)
481
645
  };
482
646
  });
@@ -546,6 +710,89 @@ export const makeMessagesRecvSocket = (config) => {
546
710
  break;
547
711
  }
548
712
  };
713
+ const handleDevicesNotification = async (node) => {
714
+ const [child] = getAllBinaryNodeChildren(node);
715
+ const from = jidNormalizedUser(node.attrs.from);
716
+ if (!child) {
717
+ logger.debug({ from }, 'devices notification missing child, skipping');
718
+ return;
719
+ }
720
+ const tag = child.tag;
721
+ const deviceHash = child.attrs.device_hash;
722
+ const devices = getBinaryNodeChildren(child, 'device');
723
+ if (areJidsSameUser(from, authState.creds.me.id) || areJidsSameUser(from, authState.creds.me.lid)) {
724
+ const deviceJids = devices.map(d => d.attrs.jid);
725
+ logger.info({ deviceJids }, 'got my own devices');
726
+ }
727
+ if (!devices.length) {
728
+ logger.debug({ from, tag }, 'no devices in notification, skipping');
729
+ return;
730
+ }
731
+ const decoded = [];
732
+ for (const d of devices) {
733
+ const jid = d.attrs.jid;
734
+ if (!jid)
735
+ continue;
736
+ const parts = jidDecode(jid);
737
+ if (!parts) {
738
+ logger.debug({ jid }, 'failed to decode device jid, skipping');
739
+ continue;
740
+ }
741
+ decoded.push({ jid, user: parts.user, server: parts.server, device: parts.device });
742
+ }
743
+ if (!decoded.length)
744
+ return;
745
+ await devicesMutex.mutex(async () => {
746
+ const byUser = new Map();
747
+ for (const d of decoded) {
748
+ const list = byUser.get(d.user) || [];
749
+ list.push(d);
750
+ byUser.set(d.user, list);
751
+ }
752
+ for (const [user, entries] of byUser) {
753
+ if (tag === 'update') {
754
+ logger.debug({ user }, `${user}'s device list updated, dropping cached devices`);
755
+ await userDevicesCache?.del(user);
756
+ continue;
757
+ }
758
+ if (tag === 'remove') {
759
+ await signalRepository.deleteSession(entries.map(e => e.jid));
760
+ }
761
+ const existingCache = (await userDevicesCache?.get(user)) || [];
762
+ if (!existingCache.length) {
763
+ // No baseline yet; skip applying the delta so getUSyncDevices can
764
+ // later fetch the full device list. Caching just the notification
765
+ // entries would make a partial list look authoritative.
766
+ logger.debug({ user, tag }, 'device list not cached, deferring to USync refresh');
767
+ continue;
768
+ }
769
+ const affected = new Set(entries.map(e => e.device));
770
+ let updatedDevices;
771
+ switch (tag) {
772
+ case 'add':
773
+ logger.info({ deviceHash, count: entries.length }, 'devices added');
774
+ updatedDevices = [
775
+ ...existingCache.filter(d => !affected.has(d.device)),
776
+ ...entries.map(e => ({ user: e.user, server: e.server, device: e.device }))
777
+ ];
778
+ break;
779
+ case 'remove':
780
+ logger.info({ deviceHash, count: entries.length }, 'devices removed');
781
+ updatedDevices = existingCache.filter(d => !affected.has(d.device));
782
+ break;
783
+ default:
784
+ logger.debug({ tag }, 'Unknown device list change tag');
785
+ continue;
786
+ }
787
+ if (updatedDevices.length === 0) {
788
+ await userDevicesCache?.del(user);
789
+ }
790
+ else {
791
+ await userDevicesCache?.set(user, updatedDevices);
792
+ }
793
+ }
794
+ });
795
+ };
549
796
  const processNotification = async (node) => {
550
797
  const result = {};
551
798
  const [child] = getAllBinaryNodeChildren(node);
@@ -556,7 +803,7 @@ export const makeMessagesRecvSocket = (config) => {
556
803
  await handleNewsletterNotification(node);
557
804
  break;
558
805
  case 'mex':
559
- await handleMexNewsletterNotification(node);
806
+ await handleMexNotification(node);
560
807
  break;
561
808
  case 'w:gp2':
562
809
  // TODO: HANDLE PARTICIPANT_PN
@@ -570,13 +817,12 @@ export const makeMessagesRecvSocket = (config) => {
570
817
  await handleEncryptNotification(node);
571
818
  break;
572
819
  case 'devices':
573
- const devices = getBinaryNodeChildren(child, 'device');
574
- if (areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
575
- areJidsSameUser(child.attrs.lid, authState.creds.me.lid)) {
576
- const deviceData = devices.map(d => ({ id: d.attrs.jid, lid: d.attrs.lid }));
577
- logger.info({ deviceData }, 'my own devices changed');
820
+ try {
821
+ await handleDevicesNotification(node);
822
+ }
823
+ catch (error) {
824
+ logger.error({ error, node }, 'failed to handle devices notification');
578
825
  }
579
- //TODO: drop a new event, add hashes
580
826
  break;
581
827
  case 'server_sync':
582
828
  const update = getBinaryNodeChild(node, 'collection');
@@ -702,27 +948,70 @@ export const makeMessagesRecvSocket = (config) => {
702
948
  return result;
703
949
  }
704
950
  };
951
+ /**
952
+ * In-memory cache of storage JIDs with stored tctokens, seeded from the persisted index.
953
+ * Used to coalesce writes during a session; pruning always re-reads the persisted index
954
+ * to cover writes made by other layers (e.g. history sync).
955
+ */
956
+ const tcTokenKnownJids = new Set();
957
+ const tcTokenIndexLoaded = (async () => {
958
+ try {
959
+ const jids = await readTcTokenIndex(authState.keys);
960
+ for (const jid of jids)
961
+ tcTokenKnownJids.add(jid);
962
+ logger.debug({ count: tcTokenKnownJids.size }, 'loaded tctoken index');
963
+ }
964
+ catch (err) {
965
+ logger.warn({ err: err?.message }, 'failed to load tctoken index');
966
+ }
967
+ })();
968
+ let tcTokenIndexTimer;
969
+ async function flushTcTokenIndex() {
970
+ if (tcTokenIndexTimer) {
971
+ clearTimeout(tcTokenIndexTimer);
972
+ tcTokenIndexTimer = undefined;
973
+ }
974
+ // Merge with whatever is already persisted so we don't clobber writes from other
975
+ // paths (history sync, concurrent sessions on the same store).
976
+ const write = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids);
977
+ return authState.keys.set({ tctoken: write });
978
+ }
979
+ function scheduleTcTokenIndexSave() {
980
+ if (tcTokenIndexTimer) {
981
+ clearTimeout(tcTokenIndexTimer);
982
+ }
983
+ tcTokenIndexTimer = setTimeout(() => {
984
+ tcTokenIndexTimer = undefined;
985
+ flushTcTokenIndex().catch(err => {
986
+ logger.warn({ err: err?.message }, 'failed to save tctoken index');
987
+ });
988
+ }, 5000);
989
+ }
990
+ function trackTcTokenJid(jid) {
991
+ if (jid && jid !== TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
992
+ tcTokenKnownJids.add(jid);
993
+ scheduleTcTokenIndexSave();
994
+ }
995
+ }
705
996
  const handlePrivacyTokenNotification = async (node) => {
706
997
  const tokensNode = getBinaryNodeChild(node, 'tokens');
707
- const from = jidNormalizedUser(node.attrs.from);
708
998
  if (!tokensNode)
709
999
  return;
710
- const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
711
- for (const tokenNode of tokenNodes) {
712
- const { attrs, content } = tokenNode;
713
- const type = attrs.type;
714
- const timestamp = attrs.t;
715
- if (type === 'trusted_contact' && content instanceof Buffer) {
716
- logger.debug({
717
- from,
718
- timestamp,
719
- tcToken: content
720
- }, 'received trusted contact token');
721
- await authState.keys.set({
722
- tctoken: { [from]: { token: content, timestamp } }
723
- });
724
- }
725
- }
1000
+ const from = jidNormalizedUser(node.attrs.from);
1001
+ // WA Web uses: senderLid ?? toLid(from) for the storage key
1002
+ // The sender_lid attribute provides the LID directly when available
1003
+ const senderLid = node.attrs.sender_lid && isLidUser(jidNormalizedUser(node.attrs.sender_lid))
1004
+ ? jidNormalizedUser(node.attrs.sender_lid)
1005
+ : undefined;
1006
+ const fallbackJid = senderLid ?? (await resolveTcTokenJid(from, getLIDForPN));
1007
+ logger.debug({ from, storageJid: fallbackJid }, 'processing privacy token notification');
1008
+ await storeTcTokensFromIqResult({
1009
+ result: node,
1010
+ fallbackJid,
1011
+ keys: authState.keys,
1012
+ getLIDForPN,
1013
+ onNewJidStored: trackTcTokenJid
1014
+ });
726
1015
  };
727
1016
  async function decipherLinkPublicKey(data) {
728
1017
  const buffer = toRequiredBuffer(data);
@@ -748,10 +1037,11 @@ export const makeMessagesRecvSocket = (config) => {
748
1037
  const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
749
1038
  await msgRetryCache.set(key, newValue);
750
1039
  };
751
- const sendMessagesAgain = async (key, ids, retryNode) => {
1040
+ const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
752
1041
  const remoteJid = key.remoteJid;
753
1042
  const participant = key.participant || remoteJid;
754
1043
  const retryCount = +retryNode.attrs.count || 1;
1044
+ const msgId = ids[0];
755
1045
  // Try to get messages from cache first, then fallback to getMessage
756
1046
  const msgs = [];
757
1047
  for (const id of ids) {
@@ -783,12 +1073,49 @@ export const makeMessagesRecvSocket = (config) => {
783
1073
  // just re-send the message to everyone
784
1074
  // prevents the first message decryption failure
785
1075
  const sendToAll = !jidDecode(participant)?.device;
786
- // Check if we should recreate session for this retry
1076
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
1077
+ let injectedFromBundle = false;
1078
+ const bundle = extractE2ESessionFromRetryReceipt(receiptNode);
1079
+ if (bundle) {
1080
+ try {
1081
+ await signalRepository.injectE2ESession({ jid: participant, session: bundle });
1082
+ injectedFromBundle = true;
1083
+ logger.debug({ participant, retryCount }, 'injected session from retry receipt key bundle');
1084
+ }
1085
+ catch (error) {
1086
+ logger.warn({ error, participant }, 'failed to inject session from retry receipt');
1087
+ }
1088
+ }
1089
+ if (!injectedFromBundle) {
1090
+ const receivedRegId = getBinaryNodeChildUInt(receiptNode, 'registration', 4);
1091
+ if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
1092
+ const info = await signalRepository.getSessionInfo(participant);
1093
+ if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) {
1094
+ logger.info({ participant, stored: info.registrationId, received: receivedRegId }, 'reg id mismatch on retry without bundle, deleting session');
1095
+ await authState.keys.set({ session: { [sessionId]: null } });
1096
+ }
1097
+ }
1098
+ }
1099
+ const BASE_KEY_CHECK_RETRY = 2;
1100
+ if (msgId && messageRetryManager) {
1101
+ const info = await signalRepository.getSessionInfo(participant);
1102
+ if (info) {
1103
+ if (retryCount === BASE_KEY_CHECK_RETRY) {
1104
+ messageRetryManager.saveBaseKey(sessionId, msgId, info.baseKey);
1105
+ }
1106
+ else if (retryCount > BASE_KEY_CHECK_RETRY) {
1107
+ if (messageRetryManager.hasSameBaseKey(sessionId, msgId, info.baseKey)) {
1108
+ logger.warn({ participant, retryCount }, 'base key collision on retry, forcing fresh session');
1109
+ await authState.keys.set({ session: { [sessionId]: null } });
1110
+ }
1111
+ messageRetryManager.deleteBaseKey(sessionId, msgId);
1112
+ }
1113
+ }
1114
+ }
787
1115
  let shouldRecreateSession = false;
788
1116
  let recreateReason = '';
789
- if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
1117
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
790
1118
  try {
791
- const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
792
1119
  const hasSession = await signalRepository.validateSession(participant);
793
1120
  const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
794
1121
  shouldRecreateSession = result.recreate;
@@ -802,11 +1129,13 @@ export const makeMessagesRecvSocket = (config) => {
802
1129
  logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
803
1130
  }
804
1131
  }
805
- await assertSessions([participant], true);
1132
+ if (!injectedFromBundle) {
1133
+ await assertSessions([participant], true);
1134
+ }
806
1135
  if (isJidGroup(remoteJid)) {
807
1136
  await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
808
1137
  }
809
- logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp');
1138
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
810
1139
  for (const [i, msg] of msgs.entries()) {
811
1140
  if (!ids[i])
812
1141
  continue;
@@ -841,11 +1170,6 @@ export const makeMessagesRecvSocket = (config) => {
841
1170
  fromMe,
842
1171
  participant: attrs.participant
843
1172
  };
844
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
845
- logger.debug({ remoteJid }, 'ignoring receipt from jid');
846
- await sendMessageAck(node);
847
- return;
848
- }
849
1173
  const ids = [attrs.id];
850
1174
  if (Array.isArray(content)) {
851
1175
  const items = getBinaryNodeChildren(content[0], 'item');
@@ -887,7 +1211,7 @@ export const makeMessagesRecvSocket = (config) => {
887
1211
  try {
888
1212
  await updateSendMessageAgainCount(ids[0], key.participant);
889
1213
  logger.debug({ attrs, key }, 'recv retry request');
890
- await sendMessagesAgain(key, ids, retryNode);
1214
+ await sendMessagesAgain(key, ids, retryNode, node);
891
1215
  }
892
1216
  catch (error) {
893
1217
  logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
@@ -905,16 +1229,11 @@ export const makeMessagesRecvSocket = (config) => {
905
1229
  ]);
906
1230
  }
907
1231
  finally {
908
- await sendMessageAck(node);
1232
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
909
1233
  }
910
1234
  };
911
1235
  const handleNotification = async (node) => {
912
1236
  const remoteJid = node.attrs.from;
913
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
914
- logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
915
- await sendMessageAck(node);
916
- return;
917
- }
918
1237
  try {
919
1238
  await Promise.all([
920
1239
  notificationMutex.mutex(async () => {
@@ -927,6 +1246,7 @@ export const makeMessagesRecvSocket = (config) => {
927
1246
  fromMe,
928
1247
  participant: node.attrs.participant,
929
1248
  participantAlt,
1249
+ participantUsername: node.attrs.participant_username,
930
1250
  addressingMode,
931
1251
  id: node.attrs.id,
932
1252
  ...(msg.key || {})
@@ -940,253 +1260,10 @@ export const makeMessagesRecvSocket = (config) => {
940
1260
  ]);
941
1261
  }
942
1262
  finally {
943
- await sendMessageAck(node);
944
- }
945
- };
946
- const resolveMentionedLIDs = async (msg, lidMapping) => {
947
- if (msg.key?.participant?.endsWith('@lid')) {
948
- try {
949
- const pn = await lidMapping.getPNForLID(msg.key.participant);
950
- if (pn) {
951
- logger.debug({ lid: msg.key.participant, pn }, 'resolved key.participant LID → PN');
952
- msg.key.participant = pn;
953
- }
954
- }
955
- catch { }
956
- }
957
- if (msg.key?.remoteJid?.endsWith('@lid')) {
958
- try {
959
- const pn = await lidMapping.getPNForLID(msg.key.remoteJid);
960
- if (pn) {
961
- logger.debug({ lid: msg.key.remoteJid, pn }, 'resolved key.remoteJid LID → PN');
962
- msg.key.remoteJid = pn;
963
- }
964
- }
965
- catch { }
966
- }
967
- const msgContent = msg.message;
968
- if (!msgContent)
969
- return;
970
- const getContextInfo = (content) => {
971
- if (!content || typeof content !== 'object')
972
- return null;
973
- if (content.contextInfo)
974
- return content.contextInfo;
975
- for (const val of Object.values(content)) {
976
- const found = getContextInfo(val);
977
- if (found)
978
- return found;
979
- }
980
- return null;
981
- };
982
- const getTextField = (content) => {
983
- if (!content || typeof content !== 'object')
984
- return null;
985
- for (const key of ['text', 'caption', 'conversation']) {
986
- if (typeof content[key] === 'string')
987
- return { obj: content, key };
988
- }
989
- for (const val of Object.values(content)) {
990
- const found = getTextField(val);
991
- if (found)
992
- return found;
993
- }
994
- return null;
995
- };
996
- // Resolve semua contextInfo termasuk yang ada di dalam quotedMessage
997
- const getAllContextInfos = (content, results = []) => {
998
- if (!content || typeof content !== 'object') return results;
999
- if (content.contextInfo) {
1000
- results.push(content.contextInfo);
1001
- // Juga cari di dalam quotedMessage secara rekursif
1002
- if (content.contextInfo.quotedMessage) {
1003
- getAllContextInfos(content.contextInfo.quotedMessage, results);
1004
- }
1005
- }
1006
- for (const val of Object.values(content)) {
1007
- if (val && typeof val === 'object' && !results.includes(val)) {
1008
- getAllContextInfos(val, results);
1009
- }
1010
- }
1011
- return results;
1012
- };
1013
- const contextInfo = getContextInfo(msgContent);
1014
- // Resolve participant LID di semua contextInfo (termasuk quotedMessage)
1015
- const allContextInfos = getAllContextInfos(msgContent);
1016
- for (const ctx of allContextInfos) {
1017
- if (ctx?.participant?.endsWith('@lid')) {
1018
- try {
1019
- const pn = await lidMapping.getPNForLID(ctx.participant);
1020
- if (pn) {
1021
- logger.debug({ lid: ctx.participant, pn }, 'resolved nested contextInfo.participant LID → PN');
1022
- ctx.participant = pn;
1023
- }
1024
- } catch { }
1025
- }
1026
- // Resolve mentionedJid di quotedMessage contextInfo juga
1027
- if (ctx !== contextInfo && ctx?.mentionedJid?.length) {
1028
- const lids = ctx.mentionedJid.filter(j => j?.endsWith('@lid'));
1029
- for (const lid of lids) {
1030
- try {
1031
- const pn = await lidMapping.getPNForLID(lid);
1032
- if (pn) ctx.mentionedJid = ctx.mentionedJid.map(j => j === lid ? pn : j);
1033
- } catch { }
1034
- }
1035
- }
1036
- }
1037
- // resolve contextInfo.participant (sender of quoted message) jika masih LID
1038
- if (contextInfo?.participant?.endsWith('@lid')) {
1039
- try {
1040
- const pn = await lidMapping.getPNForLID(contextInfo.participant);
1041
- if (pn) {
1042
- logger.debug({ lid: contextInfo.participant, pn }, 'resolved contextInfo.participant LID → PN');
1043
- contextInfo.participant = pn;
1044
- }
1045
- }
1046
- catch { }
1047
- }
1048
- if (!contextInfo?.mentionedJid?.length)
1049
- return;
1050
- // Fix text yang masih mengandung LID number meskipun mentionedJid sudah resolved ke PN
1051
- // Kasus: mentionedJid sudah jadi @s.whatsapp.net tapi text masih "@165159209271535" (LID num)
1052
- const textFieldEarly = getTextField(msgContent);
1053
- if (textFieldEarly) {
1054
- let earlyText = textFieldEarly.obj[textFieldEarly.key] || '';
1055
- // Cek apakah text mengandung @angka panjang (>12 digit = kemungkinan LID number bukan nomor HP)
1056
- const lidNumPattern = /@(\d{13,20})/g;
1057
- const lidNumMatches = [...earlyText.matchAll(lidNumPattern)];
1058
- if (lidNumMatches.length > 0) {
1059
- // Untuk setiap mentionedJid yang sudah resolved, cek apakah ada LID number di text
1060
- for (const resolvedJid of contextInfo.mentionedJid) {
1061
- if (resolvedJid?.endsWith('@lid')) continue; // belum resolved, skip dulu
1062
- const pnNum = resolvedJid.split('@')[0].split(':')[0];
1063
- if (!pnNum) continue;
1064
- // Cari LID number di text yang paling mungkin match (berdasarkan urutan)
1065
- for (const match of lidNumMatches) {
1066
- const lidNum = match[1];
1067
- if (earlyText.includes(`@${lidNum}`)) {
1068
- earlyText = earlyText.split(`@${lidNum}`).join(`@${pnNum}`);
1069
- logger.debug({ lidNum, pnNum }, 'replaced LID number in text with PN number');
1070
- break;
1071
- }
1072
- }
1073
- }
1074
- textFieldEarly.obj[textFieldEarly.key] = earlyText;
1075
- }
1076
- }
1077
- const hasLid = contextInfo.mentionedJid.some((j) => j?.endsWith('@lid'));
1078
- if (!hasLid)
1079
- return;
1080
- const lidJids = contextInfo.mentionedJid.filter((j) => j?.endsWith('@lid'));
1081
- const resolveMap = new Map();
1082
- const stillUnresolved = [];
1083
- for (const lidJid of lidJids) {
1084
- try {
1085
- const pn = await lidMapping.getPNForLID(lidJid);
1086
- if (pn) {
1087
- resolveMap.set(lidJid, pn);
1088
- }
1089
- else {
1090
- stillUnresolved.push(lidJid);
1091
- }
1092
- }
1093
- catch {
1094
- stillUnresolved.push(lidJid);
1095
- }
1096
- }
1097
- if (stillUnresolved.length > 0) {
1098
- try {
1099
- const usyncQ = new USyncQuery()
1100
- .withContactProtocol()
1101
- .withContext('background');
1102
- for (const lidJid of stillUnresolved) {
1103
- usyncQ.withUser(new USyncUser().withId(lidJid));
1104
- }
1105
- const result = await sock.executeUSyncQuery(usyncQ);
1106
- if (result?.list) {
1107
- const mappings = [];
1108
- for (const item of result.list) {
1109
- // item.id bisa berupa PN (@s.whatsapp.net) atau LID (@lid)
1110
- // stillUnresolved berisi LID. Match berdasarkan numeric prefix
1111
- const itemNum = (item.id ?? '').split('@')[0].split(':')[0];
1112
- const lidJid = stillUnresolved.find(l => {
1113
- if (l === item.id) return true;
1114
- const lNum = l.split('@')[0].split(':')[0];
1115
- return itemNum && lNum && itemNum === lNum;
1116
- });
1117
- if (lidJid && item.id && !item.id.endsWith('@lid')) {
1118
- resolveMap.set(lidJid, item.id);
1119
- mappings.push({ lid: lidJid, pn: item.id });
1120
- logger.debug({ lid: lidJid, pn: item.id }, 'USync resolved LID → PN');
1121
- }
1122
- }
1123
- if (mappings.length > 0) {
1124
- lidMapping.storeLIDPNMappings(mappings).catch(() => { });
1125
- }
1126
- }
1127
- }
1128
- catch (e) {
1129
- logger.debug({ err: e }, 'USync LID resolve failed, using cache only');
1130
- }
1131
- }
1132
- // ── Text-based PN extraction ─────────────────────────────────────────────
1133
- // WA kadang sudah resolve nomor HP di text (@6285133801810) tapi mentionedJid
1134
- // masih berisi LID. Kita ekstrak semua @nomor dari text lalu matching ke LID
1135
- // yang masih unresolved berdasarkan urutan kemunculan di mentionedJid.
1136
- const textField = getTextField(msgContent);
1137
- const stillUnresolvedAfterUSync = lidJids.filter(l => !resolveMap.has(l));
1138
- if (stillUnresolvedAfterUSync.length > 0 && textField) {
1139
- const rawText = textField.obj[textField.key] || '';
1140
- // Ekstrak semua mention @nomor dari text (hanya angka, min 7 digit)
1141
- const mentionMatches = [...rawText.matchAll(/@(\d{7,15})/g)].map(m => m[1]);
1142
- if (mentionMatches.length > 0) {
1143
- // Match LID ke nomor berdasarkan urutan index di mentionedJid
1144
- const lidOrder = contextInfo.mentionedJid
1145
- .map((jid, idx) => ({ jid, idx }))
1146
- .filter(({ jid }) => stillUnresolvedAfterUSync.includes(jid));
1147
- for (let i = 0; i < lidOrder.length && i < mentionMatches.length; i++) {
1148
- const lidJid = lidOrder[i].jid;
1149
- const phoneNum = mentionMatches[i];
1150
- const pnJid = `${phoneNum}@s.whatsapp.net`;
1151
- resolveMap.set(lidJid, pnJid);
1152
- // Simpan mapping baru ini ke store untuk request berikutnya
1153
- lidMapping.storeLIDPNMappings([{ lid: lidJid, pn: pnJid }]).catch(() => {});
1154
- logger.debug({ lid: lidJid, pn: pnJid }, 'text-extracted PN for LID → PN');
1155
- }
1156
- }
1157
- }
1158
- // ── End text-based PN extraction ─────────────────────────────────────────
1159
-
1160
- contextInfo.mentionedJid = contextInfo.mentionedJid.map((jid) => {
1161
- if (!jid?.endsWith('@lid'))
1162
- return jid;
1163
- const resolved = resolveMap.get(jid);
1164
- if (resolved) {
1165
- logger.debug({ lid: jid, pn: resolved }, 'resolved mentionedJid LID → PN');
1166
- return resolved;
1167
- }
1168
- // Tetap kembalikan LID jika benar-benar tidak bisa di-resolve
1169
- return jid;
1170
- });
1171
- if (textField) {
1172
- let text = textField.obj[textField.key];
1173
- // Replace LID number di text dengan PN number yang sudah di-resolve
1174
- for (const [lidJid, pnJid] of resolveMap) {
1175
- const lidNum = lidJid.split('@')[0].split(':')[0] ?? '';
1176
- const pnNum = pnJid.replace('@s.whatsapp.net', '').split(':')[0] ?? '';
1177
- if (lidNum && pnNum && text.includes(lidNum)) {
1178
- text = text.split(lidNum).join(pnNum);
1179
- }
1180
- }
1181
- textField.obj[textField.key] = text;
1263
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
1182
1264
  }
1183
1265
  };
1184
1266
  const handleMessage = async (node) => {
1185
- if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
1186
- logger.debug({ key: node.attrs.key }, 'ignored message');
1187
- await sendMessageAck(node, NACK_REASONS.UnhandledError);
1188
- return;
1189
- }
1190
1267
  const encNode = getBinaryNodeChild(node, 'enc');
1191
1268
  // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
1192
1269
  if (encNode?.attrs.type === 'msmsg') {
@@ -1194,36 +1271,34 @@ export const makeMessagesRecvSocket = (config) => {
1194
1271
  await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
1195
1272
  return;
1196
1273
  }
1197
- const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
1198
- const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
1199
- // store new mappings we didn't have before
1200
- if (!!alt) {
1201
- const altServer = jidDecode(alt)?.server;
1202
- const primaryJid = msg.key.participant || msg.key.remoteJid;
1203
- if (altServer === 'lid') {
1204
- if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
1205
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
1206
- await signalRepository.migrateSession(primaryJid, alt);
1274
+ let acked = false;
1275
+ try {
1276
+ const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
1277
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
1278
+ // store new mappings we didn't have before
1279
+ if (!!alt) {
1280
+ const altServer = jidDecode(alt)?.server;
1281
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
1282
+ if (altServer === 'lid') {
1283
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
1284
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
1285
+ await signalRepository.migrateSession(primaryJid, alt);
1286
+ }
1287
+ }
1288
+ else {
1289
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
1290
+ await signalRepository.migrateSession(alt, primaryJid);
1207
1291
  }
1208
1292
  }
1209
- else {
1210
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
1211
- await signalRepository.migrateSession(alt, primaryJid);
1212
- }
1213
- }
1214
- if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
1215
- messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
1216
- logger.debug({
1217
- jid: msg.key.remoteJid,
1218
- id: msg.key.id
1219
- }, 'Added message to recent cache for retry receipts');
1220
- }
1221
- try {
1222
1293
  await messageMutex.mutex(async () => {
1223
1294
  await decrypt();
1295
+ if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
1296
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
1297
+ }
1224
1298
  // message failed to decrypt
1225
1299
  if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
1226
1300
  if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
1301
+ acked = true;
1227
1302
  return sendMessageAck(node, NACK_REASONS.ParsingError);
1228
1303
  }
1229
1304
  if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
@@ -1235,11 +1310,13 @@ export const makeMessagesRecvSocket = (config) => {
1235
1310
  unavailableType === 'hosted_unavailable_fanout' ||
1236
1311
  unavailableType === 'view_once_unavailable_fanout') {
1237
1312
  logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
1313
+ acked = true;
1238
1314
  return sendMessageAck(node);
1239
1315
  }
1240
1316
  const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1241
1317
  if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
1242
1318
  logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
1319
+ acked = true;
1243
1320
  return sendMessageAck(node);
1244
1321
  }
1245
1322
  // Request the real content from the phone via placeholder resend PDO.
@@ -1276,6 +1353,7 @@ export const makeMessagesRecvSocket = (config) => {
1276
1353
  .catch(err => {
1277
1354
  logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
1278
1355
  });
1356
+ acked = true;
1279
1357
  await sendMessageAck(node);
1280
1358
  // Don't return — fall through to upsertMessage so the stub is emitted
1281
1359
  }
@@ -1285,32 +1363,18 @@ export const makeMessagesRecvSocket = (config) => {
1285
1363
  const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1286
1364
  if (messageAge > STATUS_EXPIRY_SECONDS) {
1287
1365
  logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message');
1366
+ acked = true;
1288
1367
  return sendMessageAck(node);
1289
1368
  }
1290
1369
  }
1291
- const errorMessage = msg?.messageStubParameters?.[0] || '';
1292
- const isPreKeyError = errorMessage.includes('PreKey');
1293
- logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
1294
- // Handle both pre-key and normal retries in single mutex
1370
+ logger.debug('[handleMessage] Attempting retry request for failed decryption');
1371
+ // WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
1295
1372
  await retryMutex.mutex(async () => {
1296
1373
  try {
1297
1374
  if (!ws.isOpen) {
1298
1375
  logger.debug({ node }, 'Connection closed, skipping retry');
1299
1376
  return;
1300
1377
  }
1301
- // Handle pre-key errors with upload and delay
1302
- if (isPreKeyError) {
1303
- logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
1304
- try {
1305
- logger.debug('Uploading pre-keys for error recovery');
1306
- await uploadPreKeys(5);
1307
- logger.debug('Waiting for server to process new pre-keys');
1308
- await delay(1000);
1309
- }
1310
- catch (uploadErr) {
1311
- logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
1312
- }
1313
- }
1314
1378
  const encNode = getBinaryNodeChild(node, 'enc');
1315
1379
  await sendRetryRequest(node, !encNode);
1316
1380
  if (retryRequestDelayMs) {
@@ -1318,16 +1382,9 @@ export const makeMessagesRecvSocket = (config) => {
1318
1382
  }
1319
1383
  }
1320
1384
  catch (err) {
1321
- logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry');
1322
- // Still attempt retry even if pre-key upload failed
1323
- try {
1324
- const encNode = getBinaryNodeChild(node, 'enc');
1325
- await sendRetryRequest(node, !encNode);
1326
- }
1327
- catch (retryErr) {
1328
- logger.error({ retryErr }, 'Failed to send retry after error handling');
1329
- }
1385
+ logger.error({ err }, 'Failed to send retry');
1330
1386
  }
1387
+ acked = true;
1331
1388
  await sendMessageAck(node, NACK_REASONS.UnhandledError);
1332
1389
  });
1333
1390
  }
@@ -1356,6 +1413,7 @@ export const makeMessagesRecvSocket = (config) => {
1356
1413
  else if (!sendActiveReceipts) {
1357
1414
  type = 'inactive';
1358
1415
  }
1416
+ acked = true;
1359
1417
  await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1360
1418
  // send ack for history message
1361
1419
  const isAnyHistoryMsg = getHistoryMsg(msg.message);
@@ -1365,147 +1423,73 @@ export const makeMessagesRecvSocket = (config) => {
1365
1423
  }
1366
1424
  }
1367
1425
  else {
1426
+ acked = true;
1368
1427
  await sendMessageAck(node);
1369
1428
  logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
1370
1429
  }
1371
1430
  }
1372
1431
  cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1373
- await resolveMentionedLIDs(msg, signalRepository.lidMapping);
1374
- // ── Post-resolve: fix semua LID yang tersisa di message object ────────
1375
- // Setelah resolveMentionedLIDs:
1376
- // 1. Fix text yang masih "@LIDnum" → "@PNnum"
1377
- // 2. Fix contextInfo.participant yang masih @lid (sender quoted)
1378
- // 3. Fix mentionedJid & text di dalam quotedMessage
1379
- try {
1380
- const _safeSet = (obj, key, val) => {
1381
- try { obj[key] = val; } catch (_) {
1382
- // proto readonly fallback
1383
- const proto = Object.getPrototypeOf(obj);
1384
- const fresh = Object.assign(Object.create(proto), obj, { [key]: val });
1385
- // replace reference di parent jika bisa — caller handles
1386
- return fresh;
1387
- }
1388
- return obj;
1389
- };
1390
- const _fixTextLid = (innerMsg, mentionedJids, msgTypeLabel) => {
1391
- const pnNumbers = (mentionedJids || [])
1392
- .filter(j => j && !j.endsWith('@lid'))
1393
- .map(j => j.split('@')[0].split(':')[0])
1394
- .filter(Boolean);
1395
- if (!pnNumbers.length) return;
1396
- for (const textKey of ['text', 'caption', 'conversation']) {
1397
- const originalText = innerMsg[textKey];
1398
- if (typeof originalText !== 'string') continue;
1399
- const lidPattern = /@(\d{13,20})/g;
1400
- let newText = originalText;
1401
- let match;
1402
- let pnIdx = 0;
1403
- while ((match = lidPattern.exec(originalText)) !== null) {
1404
- if (pnIdx >= pnNumbers.length) break;
1405
- const lidNum = match[1];
1406
- const pnNum = pnNumbers[pnIdx++];
1407
- newText = newText.split(`@${lidNum}`).join(`@${pnNum}`);
1408
- logger.debug({ lidNum, pnNum, type: msgTypeLabel, textKey }, 'post-resolve: replaced LID num in text');
1409
- }
1410
- if (newText !== originalText) _safeSet(innerMsg, textKey, newText);
1411
- }
1412
- };
1413
- const msgObj = msg.message;
1414
- if (msgObj) {
1415
- for (const msgType of Object.keys(msgObj)) {
1416
- const innerMsg = msgObj[msgType];
1417
- if (!innerMsg || typeof innerMsg !== 'object') continue;
1418
- const ctxInfo = innerMsg.contextInfo;
1419
- if (!ctxInfo) continue;
1420
- // 1. Fix text LID → PN (pesan utama)
1421
- if (ctxInfo.mentionedJid?.length) {
1422
- _fixTextLid(innerMsg, ctxInfo.mentionedJid, msgType);
1423
- }
1424
- // 2. Fix contextInfo.participant (sender quoted) jika masih LID
1425
- if (ctxInfo.participant?.endsWith('@lid')) {
1426
- try {
1427
- const pn = await signalRepository.lidMapping.getPNForLID(ctxInfo.participant);
1428
- if (pn) {
1429
- _safeSet(ctxInfo, 'participant', pn);
1430
- logger.debug({ lid: ctxInfo.participant, pn }, 'post-resolve: fixed contextInfo.participant LID');
1431
- }
1432
- } catch (_) {}
1433
- }
1434
- // 3. Fix mentionedJid & text di dalam quotedMessage
1435
- if (ctxInfo.quotedMessage) {
1436
- for (const qType of Object.keys(ctxInfo.quotedMessage)) {
1437
- const qInner = ctxInfo.quotedMessage[qType];
1438
- if (!qInner || typeof qInner !== 'object') continue;
1439
- const qCtx = qInner.contextInfo;
1440
- if (!qCtx?.mentionedJid?.length) continue;
1441
- // Resolve LID di mentionedJid quoted
1442
- const resolvedQ = await Promise.all(
1443
- qCtx.mentionedJid.map(async (jid) => {
1444
- if (!jid?.endsWith('@lid')) return jid;
1445
- try {
1446
- const pn = await signalRepository.lidMapping.getPNForLID(jid);
1447
- return pn || jid;
1448
- } catch (_) { return jid; }
1449
- })
1450
- );
1451
- if (resolvedQ.some((j, i) => j !== qCtx.mentionedJid[i])) {
1452
- _safeSet(qCtx, 'mentionedJid', resolvedQ);
1453
- logger.debug({ resolvedQ }, 'post-resolve: fixed quotedMessage mentionedJid');
1454
- }
1455
- // Fix text LID → PN di quoted
1456
- _fixTextLid(qInner, resolvedQ, `quoted.${qType}`);
1457
- }
1458
- }
1459
- }
1460
- }
1461
- } catch (lidFixErr) {
1462
- logger.debug({ err: lidFixErr }, 'post-resolve LID fix failed (non-critical)');
1463
- }
1464
- // ── End post-resolve fix ──────────────────────────────────────────────
1465
1432
  await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1466
1433
  });
1467
1434
  }
1468
1435
  catch (error) {
1469
1436
  logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
1437
+ if (!acked) {
1438
+ await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(ackErr => logger.error({ ackErr }, 'failed to ack message after error'));
1439
+ }
1470
1440
  }
1471
1441
  };
1472
1442
  const handleCall = async (node) => {
1473
- const { attrs } = node;
1474
- const [infoChild] = getAllBinaryNodeChildren(node);
1475
- const status = getCallStatusFromNode(infoChild);
1476
- if (!infoChild) {
1477
- throw new Boom('Missing call info in call node');
1478
- }
1479
- const callId = infoChild.attrs['call-id'];
1480
- const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1481
- const call = {
1482
- chatId: attrs.from,
1483
- from,
1484
- callerPn: infoChild.attrs['caller_pn'],
1485
- id: callId,
1486
- date: new Date(+attrs.t * 1000),
1487
- offline: !!attrs.offline,
1488
- status
1489
- };
1490
- if (status === 'offer') {
1491
- call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1492
- call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1493
- call.groupJid = infoChild.attrs['group-jid'];
1494
- await callOfferCache.set(call.id, call);
1495
- }
1496
- const existingCall = await callOfferCache.get(call.id);
1497
- // use existing call info to populate this event
1498
- if (existingCall) {
1499
- call.isVideo = existingCall.isVideo;
1500
- call.isGroup = existingCall.isGroup;
1501
- call.callerPn = call.callerPn || existingCall.callerPn;
1502
- }
1503
- // delete data once call has ended
1504
- if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1505
- await callOfferCache.del(call.id);
1506
- }
1507
- ev.emit('call', [call]);
1508
- await sendMessageAck(node);
1443
+ try {
1444
+ const { attrs } = node;
1445
+ const [infoChild] = getAllBinaryNodeChildren(node);
1446
+ if (!infoChild) {
1447
+ throw new Boom('Missing call info in call node');
1448
+ }
1449
+ const status = getCallStatusFromNode(infoChild);
1450
+ const callId = infoChild.attrs['call-id'];
1451
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1452
+ const call = {
1453
+ chatId: attrs.from,
1454
+ from,
1455
+ callerPn: infoChild.attrs['caller_pn'],
1456
+ id: callId,
1457
+ date: new Date(+attrs.t * 1000),
1458
+ offline: !!attrs.offline,
1459
+ status
1460
+ };
1461
+ if (status === 'relaylatency') {
1462
+ const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms'];
1463
+ const latencyMs = latencyValue ? Number(latencyValue) : undefined;
1464
+ if (Number.isFinite(latencyMs)) {
1465
+ call.latencyMs = latencyMs;
1466
+ }
1467
+ }
1468
+ if (status === 'offer') {
1469
+ call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1470
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1471
+ call.groupJid = infoChild.attrs['group-jid'];
1472
+ await callOfferCache.set(call.id, call);
1473
+ }
1474
+ const existingCall = await callOfferCache.get(call.id);
1475
+ // use existing call info to populate this event
1476
+ if (existingCall) {
1477
+ call.isVideo = existingCall.isVideo;
1478
+ call.isGroup = existingCall.isGroup;
1479
+ call.callerPn = call.callerPn || existingCall.callerPn;
1480
+ }
1481
+ // delete data once call has ended
1482
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1483
+ await callOfferCache.del(call.id);
1484
+ }
1485
+ ev.emit('call', [call]);
1486
+ }
1487
+ catch (error) {
1488
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling call');
1489
+ }
1490
+ finally {
1491
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'));
1492
+ }
1509
1493
  };
1510
1494
  const handleBadAck = async ({ attrs }) => {
1511
1495
  const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
@@ -1525,29 +1509,61 @@ export const makeMessagesRecvSocket = (config) => {
1525
1509
  // error in acknowledgement,
1526
1510
  // device could not display the message
1527
1511
  if (attrs.error) {
1528
- logger.warn({ attrs }, 'received error in ack');
1512
+ const isReachoutTimelocked = attrs.error === String(NACK_REASONS.SenderReachoutTimelocked);
1513
+ if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
1514
+ // 463 = 1:1 message missing privacy token (tctoken). Usually means the
1515
+ // account is restricted: WhatsApp blocks starting new chats but preserves
1516
+ // existing ones, since established chats already carry a tctoken.
1517
+ // WA Web prevents this client-side (disables the compose bar).
1518
+ // No retry — retrying counts as another "reach out" and worsens the restriction.
1519
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'error 463: account restricted or missing tctoken for contact');
1520
+ const ackFrom = attrs.from;
1521
+ if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
1522
+ inFlight463Recoveries.add(ackFrom);
1523
+ void (async () => {
1524
+ try {
1525
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1526
+ const tcStorageJid = await resolveTcTokenJid(ackFrom, getLIDForPN);
1527
+ const issueJid = await resolveIssuanceJid(ackFrom, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
1528
+ const result = await issuePrivacyTokens([issueJid], unixTimestampSeconds());
1529
+ await storeTcTokensFromIqResult({
1530
+ result,
1531
+ fallbackJid: tcStorageJid,
1532
+ keys: authState.keys,
1533
+ getLIDForPN,
1534
+ onNewJidStored: trackTcTokenJid
1535
+ });
1536
+ logger.debug({ from: ackFrom }, 'completed 463 token recovery issuance');
1537
+ }
1538
+ catch (err) {
1539
+ logger.debug({ from: ackFrom, err: err?.message }, 'failed 463 token recovery issuance');
1540
+ }
1541
+ finally {
1542
+ inFlight463Recoveries.delete(ackFrom);
1543
+ }
1544
+ })();
1545
+ }
1546
+ }
1547
+ else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
1548
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing');
1549
+ }
1550
+ else if (isReachoutTimelocked) {
1551
+ // user is temporarily restricted, fetch current restriction details
1552
+ await fetchAccountReachoutTimelock().catch(err => logger.warn({ err }, 'failed to fetch reachout timelock'));
1553
+ logger.warn({ attrs }, 'received error in ack');
1554
+ }
1555
+ else {
1556
+ logger.warn({ attrs }, 'received error in ack');
1557
+ }
1529
1558
  ev.emit('messages.update', [
1530
1559
  {
1531
1560
  key,
1532
1561
  update: {
1533
1562
  status: WAMessageStatus.ERROR,
1534
- messageStubParameters: [attrs.error]
1563
+ messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
1535
1564
  }
1536
1565
  }
1537
1566
  ]);
1538
- // resend the message with device_fanout=false, use at your own risk
1539
- // if (attrs.error === '475') {
1540
- // const msg = await getMessage(key)
1541
- // if (msg) {
1542
- // await relayMessage(key.remoteJid!, msg, {
1543
- // messageId: key.id!,
1544
- // useUserDevicesCache: false,
1545
- // additionalAttributes: {
1546
- // device_fanout: 'false'
1547
- // }
1548
- // })
1549
- // }
1550
- // }
1551
1567
  }
1552
1568
  };
1553
1569
  /// processes a node with the given function
@@ -1560,53 +1576,30 @@ export const makeMessagesRecvSocket = (config) => {
1560
1576
  return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1561
1577
  }
1562
1578
  };
1563
- /** Yields control to the event loop to prevent blocking */
1564
- const yieldToEventLoop = () => {
1565
- return new Promise(resolve => setImmediate(resolve));
1566
- };
1567
- const makeOfflineNodeProcessor = () => {
1568
- const nodeProcessorMap = new Map([
1569
- ['message', handleMessage],
1570
- ['call', handleCall],
1571
- ['receipt', handleReceipt],
1572
- ['notification', handleNotification]
1573
- ]);
1574
- const nodes = [];
1575
- let isProcessing = false;
1576
- // Number of nodes to process before yielding to event loop
1577
- const BATCH_SIZE = 10;
1578
- const enqueue = (type, node) => {
1579
- nodes.push({ type, node });
1580
- if (isProcessing) {
1581
- return;
1582
- }
1583
- isProcessing = true;
1584
- const promise = async () => {
1585
- let processedInBatch = 0;
1586
- while (nodes.length && ws.isOpen) {
1587
- const { type, node } = nodes.shift();
1588
- const nodeProcessor = nodeProcessorMap.get(type);
1589
- if (!nodeProcessor) {
1590
- onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1591
- continue;
1592
- }
1593
- await nodeProcessor(node);
1594
- processedInBatch++;
1595
- // Yield to event loop after processing a batch
1596
- // This prevents blocking the event loop for too long when there are many offline nodes
1597
- if (processedInBatch >= BATCH_SIZE) {
1598
- processedInBatch = 0;
1599
- await yieldToEventLoop();
1600
- }
1601
- }
1602
- isProcessing = false;
1603
- };
1604
- promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1605
- };
1606
- return { enqueue };
1607
- };
1608
- const offlineNodeProcessor = makeOfflineNodeProcessor();
1579
+ const offlineNodeProcessor = makeOfflineNodeProcessor(new Map([
1580
+ ['message', handleMessage],
1581
+ ['call', handleCall],
1582
+ ['receipt', handleReceipt],
1583
+ ['notification', handleNotification]
1584
+ ]), {
1585
+ isWsOpen: () => ws.isOpen,
1586
+ onUnexpectedError,
1587
+ yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
1588
+ });
1609
1589
  const processNode = async (type, node, identifier, exec) => {
1590
+ // Fast path: ack and drop ignored JIDs before entering the buffer/queue
1591
+ const from = node.attrs.from;
1592
+ let ignoreJid = from;
1593
+ if (type === 'receipt' && from) {
1594
+ const attrs = node.attrs;
1595
+ const isLid = attrs.from.includes('lid');
1596
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
1597
+ ignoreJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
1598
+ }
1599
+ if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
1600
+ await sendMessageAck(node, type === 'message' ? NACK_REASONS.UnhandledError : undefined);
1601
+ return;
1602
+ }
1610
1603
  const isOffline = !!node.attrs.offline;
1611
1604
  if (isOffline) {
1612
1605
  offlineNodeProcessor.enqueue(type, node);
@@ -1662,12 +1655,110 @@ export const makeMessagesRecvSocket = (config) => {
1662
1655
  await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1663
1656
  }
1664
1657
  });
1665
- ev.on('connection.update', ({ isOnline }) => {
1658
+ /** timestamp of last tctoken prune run — throttles to once per 24h */
1659
+ let lastTcTokenPruneTs = 0;
1660
+ /** dedupe in-flight 463 recovery token issuance by target JID */
1661
+ const inFlight463Recoveries = new Set();
1662
+ ev.on('connection.update', ({ isOnline, connection }) => {
1666
1663
  if (typeof isOnline !== 'undefined') {
1667
1664
  sendActiveReceipts = isOnline;
1668
1665
  logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1669
1666
  }
1667
+ // Flush pending tctoken index save on disconnect to avoid writing after close
1668
+ if (connection === 'close' && tcTokenIndexTimer) {
1669
+ clearTimeout(tcTokenIndexTimer);
1670
+ tcTokenIndexTimer = undefined;
1671
+ // Best-effort flush — may fail if store is already closed
1672
+ try {
1673
+ void Promise.resolve(flushTcTokenIndex()).catch(() => { });
1674
+ }
1675
+ catch {
1676
+ /* ignore sync errors */
1677
+ }
1678
+ }
1679
+ // Prune expired tctokens when coming online, at most once per 24 hours
1680
+ // Matches WA Web's CLEAN_TC_TOKENS task
1681
+ // Note: don't gate on tcTokenKnownJids.size — the index may still be loading
1682
+ if (isOnline) {
1683
+ const now = Date.now();
1684
+ const DAY_MS = 24 * 60 * 60 * 1000;
1685
+ if (now - lastTcTokenPruneTs >= DAY_MS) {
1686
+ lastTcTokenPruneTs = now;
1687
+ void pruneExpiredTcTokens();
1688
+ }
1689
+ }
1670
1690
  });
1691
+ registerSocketEndHandler(() => {
1692
+ if (!config.msgRetryCounterCache && msgRetryCache.close) {
1693
+ msgRetryCache.close();
1694
+ }
1695
+ if (!config.callOfferCache && callOfferCache.close) {
1696
+ callOfferCache.close();
1697
+ }
1698
+ identityAssertDebounce.close();
1699
+ sendActiveReceipts = false;
1700
+ });
1701
+ async function pruneExpiredTcTokens() {
1702
+ try {
1703
+ await tcTokenIndexLoaded;
1704
+ // Union with the persisted index picks up JIDs added by other layers
1705
+ // (history sync) without needing inter-module wiring.
1706
+ const persisted = await readTcTokenIndex(authState.keys);
1707
+ const allJids = new Set(tcTokenKnownJids);
1708
+ for (const jid of persisted)
1709
+ allJids.add(jid);
1710
+ if (!allJids.size)
1711
+ return;
1712
+ const jids = [...allJids];
1713
+ const allTokens = await authState.keys.get('tctoken', jids);
1714
+ const writes = {};
1715
+ const survivors = new Set();
1716
+ let mutated = 0;
1717
+ for (const jid of jids) {
1718
+ const entry = allTokens[jid];
1719
+ if (!entry) {
1720
+ // Tracked but nothing in store — drop from index.
1721
+ mutated++;
1722
+ continue;
1723
+ }
1724
+ const hasPeerToken = !!entry.token?.length;
1725
+ const peerTokenExpired = hasPeerToken && isTcTokenExpired(entry.timestamp);
1726
+ const hasSenderTs = entry.senderTimestamp !== undefined;
1727
+ const senderTsExpired = hasSenderTs && isTcTokenExpired(entry.senderTimestamp);
1728
+ const keepPeerToken = hasPeerToken && !peerTokenExpired;
1729
+ const keepSenderTs = hasSenderTs && !senderTsExpired;
1730
+ if (!keepPeerToken && !keepSenderTs) {
1731
+ writes[jid] = null;
1732
+ mutated++;
1733
+ }
1734
+ else if (peerTokenExpired && keepSenderTs) {
1735
+ writes[jid] = { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp };
1736
+ survivors.add(jid);
1737
+ mutated++;
1738
+ }
1739
+ else {
1740
+ survivors.add(jid);
1741
+ }
1742
+ }
1743
+ if (mutated === 0)
1744
+ return;
1745
+ await authState.keys.set({
1746
+ tctoken: {
1747
+ ...writes,
1748
+ [TC_TOKEN_INDEX_KEY]: {
1749
+ token: Buffer.from(JSON.stringify([...survivors]))
1750
+ }
1751
+ }
1752
+ });
1753
+ tcTokenKnownJids.clear();
1754
+ for (const jid of survivors)
1755
+ tcTokenKnownJids.add(jid);
1756
+ logger.debug({ mutated, remaining: survivors.size }, 'pruned expired tctokens');
1757
+ }
1758
+ catch (err) {
1759
+ logger.warn({ err: err?.message }, 'failed to prune expired tctokens');
1760
+ }
1761
+ }
1671
1762
  return {
1672
1763
  ...sock,
1673
1764
  sendMessageAck,