@rakku-kun/baileys 2.0.20 → 2.0.22

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 (155) hide show
  1. package/WAProto/fix-imports.js +18 -22
  2. package/WAProto/index.js +18 -22
  3. package/lib/Defaults/index.d.ts +7 -8
  4. package/lib/Defaults/index.d.ts.map +1 -1
  5. package/lib/Defaults/index.js +17 -11
  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 +59 -52
  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 +3 -18
  13. package/lib/Socket/business.d.ts.map +1 -1
  14. package/lib/Socket/chats.d.ts +2 -16
  15. package/lib/Socket/chats.d.ts.map +1 -1
  16. package/lib/Socket/chats.js +173 -238
  17. package/lib/Socket/chats.js.map +1 -1
  18. package/lib/Socket/communities.d.ts +3 -18
  19. package/lib/Socket/communities.d.ts.map +1 -1
  20. package/lib/Socket/groups.d.ts +2 -13
  21. package/lib/Socket/groups.d.ts.map +1 -1
  22. package/lib/Socket/groups.js +138 -26
  23. package/lib/Socket/groups.js.map +1 -1
  24. package/lib/Socket/index.d.ts +3 -18
  25. package/lib/Socket/index.d.ts.map +1 -1
  26. package/lib/Socket/messages-recv.d.ts +6 -22
  27. package/lib/Socket/messages-recv.d.ts.map +1 -1
  28. package/lib/Socket/messages-recv.js +645 -736
  29. package/lib/Socket/messages-recv.js.map +1 -1
  30. package/lib/Socket/messages-send.d.ts +2 -18
  31. package/lib/Socket/messages-send.d.ts.map +1 -1
  32. package/lib/Socket/messages-send.js +642 -152
  33. package/lib/Socket/messages-send.js.map +1 -1
  34. package/lib/Socket/newsletter.d.ts +1 -11
  35. package/lib/Socket/newsletter.d.ts.map +1 -1
  36. package/lib/Socket/newsletter.js +92 -3
  37. package/lib/Socket/newsletter.js.map +1 -1
  38. package/lib/Socket/socket.d.ts +2 -6
  39. package/lib/Socket/socket.d.ts.map +1 -1
  40. package/lib/Socket/socket.js +35 -61
  41. package/lib/Socket/socket.js.map +1 -1
  42. package/lib/Types/Auth.d.ts +0 -1
  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 +0 -1
  47. package/lib/Types/Chat.d.ts.map +1 -1
  48. package/lib/Types/Contact.d.ts +0 -2
  49. package/lib/Types/Contact.d.ts.map +1 -1
  50. package/lib/Types/Events.d.ts +1 -20
  51. package/lib/Types/Events.d.ts.map +1 -1
  52. package/lib/Types/GroupMetadata.d.ts +0 -4
  53. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  54. package/lib/Types/Message.d.ts +200 -25
  55. package/lib/Types/Message.d.ts.map +1 -1
  56. package/lib/Types/Message.js.map +1 -1
  57. package/lib/Types/Signal.d.ts +1 -12
  58. package/lib/Types/Signal.d.ts.map +1 -1
  59. package/lib/Types/Socket.d.ts +0 -3
  60. package/lib/Types/Socket.d.ts.map +1 -1
  61. package/lib/Types/State.d.ts +0 -58
  62. package/lib/Types/State.d.ts.map +1 -1
  63. package/lib/Types/State.js +0 -43
  64. package/lib/Types/State.js.map +1 -1
  65. package/lib/Types/index.d.ts +1 -2
  66. package/lib/Types/index.d.ts.map +1 -1
  67. package/lib/Types/index.js +2 -1
  68. package/lib/Types/index.js.map +1 -1
  69. package/lib/Utils/auth-utils.d.ts +0 -5
  70. package/lib/Utils/auth-utils.d.ts.map +1 -1
  71. package/lib/Utils/auth-utils.js +0 -12
  72. package/lib/Utils/auth-utils.js.map +1 -1
  73. package/lib/Utils/browser-utils.d.ts.map +1 -1
  74. package/lib/Utils/browser-utils.js +33 -21
  75. package/lib/Utils/browser-utils.js.map +1 -1
  76. package/lib/Utils/chat-utils.d.ts +1 -31
  77. package/lib/Utils/chat-utils.d.ts.map +1 -1
  78. package/lib/Utils/chat-utils.js +20 -80
  79. package/lib/Utils/chat-utils.js.map +1 -1
  80. package/lib/Utils/decode-wa-message.d.ts +0 -18
  81. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  82. package/lib/Utils/decode-wa-message.js +0 -34
  83. package/lib/Utils/decode-wa-message.js.map +1 -1
  84. package/lib/Utils/event-buffer.d.ts +0 -2
  85. package/lib/Utils/event-buffer.d.ts.map +1 -1
  86. package/lib/Utils/event-buffer.js +1 -49
  87. package/lib/Utils/event-buffer.js.map +1 -1
  88. package/lib/Utils/generics.d.ts +0 -1
  89. package/lib/Utils/generics.d.ts.map +1 -1
  90. package/lib/Utils/generics.js +28 -10
  91. package/lib/Utils/generics.js.map +1 -1
  92. package/lib/Utils/history.d.ts +0 -2
  93. package/lib/Utils/history.d.ts.map +1 -1
  94. package/lib/Utils/history.js +9 -12
  95. package/lib/Utils/history.js.map +1 -1
  96. package/lib/Utils/identity-change-handler.d.ts +0 -7
  97. package/lib/Utils/identity-change-handler.d.ts.map +1 -1
  98. package/lib/Utils/identity-change-handler.js +0 -1
  99. package/lib/Utils/identity-change-handler.js.map +1 -1
  100. package/lib/Utils/index.d.ts +2 -2
  101. package/lib/Utils/index.d.ts.map +1 -1
  102. package/lib/Utils/index.js +7 -2
  103. package/lib/Utils/index.js.map +1 -1
  104. package/lib/Utils/link-preview.js +2 -2
  105. package/lib/Utils/link-preview.js.map +1 -1
  106. package/lib/Utils/message-retry-manager.d.ts +0 -5
  107. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  108. package/lib/Utils/message-retry-manager.js +0 -40
  109. package/lib/Utils/message-retry-manager.js.map +1 -1
  110. package/lib/Utils/messages-media.d.ts +1 -4
  111. package/lib/Utils/messages-media.d.ts.map +1 -1
  112. package/lib/Utils/messages-media.js +173 -131
  113. package/lib/Utils/messages-media.js.map +1 -1
  114. package/lib/Utils/messages.d.ts +1 -0
  115. package/lib/Utils/messages.d.ts.map +1 -1
  116. package/lib/Utils/messages.js +906 -100
  117. package/lib/Utils/messages.js.map +1 -1
  118. package/lib/Utils/process-message.d.ts.map +1 -1
  119. package/lib/Utils/process-message.js +1 -103
  120. package/lib/Utils/process-message.js.map +1 -1
  121. package/lib/Utils/signal.d.ts +0 -13
  122. package/lib/Utils/signal.d.ts.map +1 -1
  123. package/lib/Utils/signal.js +0 -42
  124. package/lib/Utils/signal.js.map +1 -1
  125. package/lib/Utils/sync-action-utils.d.ts.map +1 -1
  126. package/lib/Utils/sync-action-utils.js +0 -1
  127. package/lib/Utils/sync-action-utils.js.map +1 -1
  128. package/lib/Utils/tc-token-utils.d.ts +1 -26
  129. package/lib/Utils/tc-token-utils.d.ts.map +1 -1
  130. package/lib/Utils/tc-token-utils.js +5 -151
  131. package/lib/Utils/tc-token-utils.js.map +1 -1
  132. package/lib/Utils/validate-connection.d.ts.map +1 -1
  133. package/lib/Utils/validate-connection.js +2 -12
  134. package/lib/Utils/validate-connection.js.map +1 -1
  135. package/lib/WABinary/generic-utils.js +15 -0
  136. package/lib/WABinary/index.js +1 -0
  137. package/lib/WABinary/jid-utils.js +2 -0
  138. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  139. package/lib/WAUSync/Protocols/USyncContactProtocol.js +3 -26
  140. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  141. package/lib/WAUSync/Protocols/index.d.ts +0 -1
  142. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  143. package/lib/WAUSync/Protocols/index.js +2 -2
  144. package/lib/WAUSync/Protocols/index.js.map +1 -1
  145. package/lib/WAUSync/USyncQuery.d.ts +0 -1
  146. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  147. package/lib/WAUSync/USyncQuery.js +2 -6
  148. package/lib/WAUSync/USyncQuery.js.map +1 -1
  149. package/lib/WAUSync/USyncUser.d.ts +0 -4
  150. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  151. package/lib/WAUSync/USyncUser.js +0 -8
  152. package/lib/WAUSync/USyncUser.js.map +1 -1
  153. package/lib/index.d.ts +1 -1
  154. package/lib/index.js +24 -10
  155. package/package.json +1 -1
@@ -4,24 +4,17 @@ 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 { 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';
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';
9
9
  import { makeMutex } from '../Utils/make-mutex.js';
10
- import { makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
11
- import { buildAckStanza } from '../Utils/stanza-ack.js';
12
- import { buildMergedTcTokenIndexWrite, isTcTokenExpired, readTcTokenIndex, resolveIssuanceJid, resolveTcTokenJid, storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY } from '../Utils/tc-token-utils.js';
13
- import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, getBinaryNodeChildUInt, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
10
+ import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
14
11
  import { extractGroupMetadata } from './groups.js';
15
12
  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
- }
13
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
20
14
  export const makeMessagesRecvSocket = (config) => {
21
15
  const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
22
16
  const sock = makeMessagesSocket(config);
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);
17
+ const { ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
25
18
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
26
19
  const retryMutex = makeMutex();
27
20
  const msgRetryCache = config.msgRetryCounterCache ||
@@ -34,6 +27,11 @@ export const makeMessagesRecvSocket = (config) => {
34
27
  stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
35
28
  useClones: false
36
29
  });
30
+ const placeholderResendCache = config.placeholderResendCache ||
31
+ new NodeCache({
32
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
33
+ useClones: false
34
+ });
37
35
  // Debounce identity-change session refreshes per JID to avoid bursts
38
36
  const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
39
37
  let sendActiveReceipts = false;
@@ -87,140 +85,25 @@ export const makeMessagesRecvSocket = (config) => {
87
85
  }, 8000);
88
86
  return sendPeerDataOperationMessage(pdoMessage);
89
87
  };
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) => {
88
+ // Handles mex newsletter notifications
89
+ const handleMexNewsletterNotification = async (node) => {
193
90
  const mexNode = getBinaryNodeChild(node, 'mex');
194
- const updateNode = mexNode?.content ? null : getBinaryNodeChild(node, 'update') || getAllBinaryNodeChildren(node)[0];
195
- const payloadNode = mexNode?.content ? mexNode : updateNode;
196
- if (!payloadNode?.content) {
197
- logger.warn({ node: binaryNodeToString(node) }, 'invalid mex newsletter notification');
91
+ if (!mexNode?.content) {
92
+ logger.warn({ node }, 'Invalid mex newsletter notification');
198
93
  return;
199
94
  }
200
95
  let data;
201
96
  try {
202
- const payloadContent = payloadNode.content;
203
- if (Array.isArray(payloadContent)) {
204
- logger.warn({ payloadNode }, 'invalid mex newsletter notification payload format');
205
- return;
206
- }
207
- const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent);
208
- data = JSON.parse(contentBuf.toString());
97
+ data = JSON.parse(mexNode.content.toString());
209
98
  }
210
99
  catch (error) {
211
- logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification');
100
+ logger.error({ err: error, node }, 'Failed to parse mex newsletter notification');
212
101
  return;
213
102
  }
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
- }
103
+ const operation = data?.operation;
104
+ const updates = data?.updates;
222
105
  if (!updates || !operation) {
223
- logger.warn({ data }, 'invalid mex newsletter notification content');
106
+ logger.warn({ data }, 'Invalid mex newsletter notification content');
224
107
  return;
225
108
  }
226
109
  logger.info({ operation, updates }, 'got mex newsletter notification');
@@ -248,119 +131,119 @@ export const makeMessagesRecvSocket = (config) => {
248
131
  }
249
132
  }
250
133
  break;
251
- case 'NotificationLinkedProfilesUpdates':
252
- for (const update of updates) {
253
- const lid = update?.jid;
254
- const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : [];
255
- const mappings = [];
256
- for (const profile of addedProfiles) {
257
- const pn = typeof profile === 'string' ? profile : (profile?.pn ?? profile?.jid ?? null);
258
- if (lid && pn) {
259
- const mapping = { lid, pn };
260
- ev.emit('lid-mapping.update', mapping);
261
- mappings.push(mapping);
262
- }
263
- }
264
- await signalRepository.lidMapping.storeLIDPNMappings(mappings);
265
- }
266
- break;
267
134
  default:
268
- logger.info({ operation, data }, 'unhandled mex newsletter notification');
135
+ logger.info({ operation, data }, 'Unhandled mex newsletter notification');
269
136
  break;
270
137
  }
271
138
  };
272
139
  // Handles newsletter notifications
273
140
  const handleNewsletterNotification = async (node) => {
274
141
  const from = node.attrs.from;
275
- const children = getAllBinaryNodeChildren(node);
142
+ const child = getAllBinaryNodeChildren(node)[0];
276
143
  const author = node.attrs.participant;
277
- for (const child of children) {
278
- logger.debug({ from, child }, 'got newsletter notification');
279
- switch (child.tag) {
280
- case 'reaction': {
281
- const reactionUpdate = {
282
- id: from,
283
- server_id: child.attrs.message_id,
284
- reaction: {
285
- code: getBinaryNodeChildString(child, 'reaction'),
286
- count: 1
287
- }
288
- };
289
- ev.emit('newsletter.reaction', reactionUpdate);
290
- break;
291
- }
292
- case 'view': {
293
- const viewUpdate = {
294
- id: from,
295
- server_id: child.attrs.message_id,
296
- count: parseInt(child.content?.toString() || '0', 10)
297
- };
298
- ev.emit('newsletter.view', viewUpdate);
299
- break;
300
- }
301
- case 'participant': {
302
- const participantUpdate = {
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', {
303
186
  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;
187
+ update
188
+ });
311
189
  }
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
- });
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');
326
210
  }
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
- }
211
+ catch (error) {
212
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
352
213
  }
353
- break;
354
214
  }
355
- default:
356
- logger.warn({ node, child }, 'Unknown newsletter notification child');
357
- break;
358
- }
215
+ break;
216
+ default:
217
+ logger.warn({ node }, 'Unknown newsletter notification');
218
+ break;
359
219
  }
360
220
  };
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');
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
228
+ }
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
+ }
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');
364
247
  await sendNode(stanza);
365
248
  };
366
249
  const rejectCall = async (callId, callFrom) => {
@@ -515,58 +398,15 @@ export const makeMessagesRecvSocket = (config) => {
515
398
  logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
516
399
  }, authState?.creds?.me?.id || 'sendRetryRequest');
517
400
  };
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
- };
549
401
  const handleEncryptNotification = async (node) => {
550
402
  const from = node.attrs.from;
551
403
  if (from === S_WHATSAPP_NET) {
552
- const stanzaId = node.attrs.id;
553
- if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
554
- return;
555
- }
556
404
  const countChild = getBinaryNodeChild(node, 'count');
557
405
  const count = +countChild.attrs.value;
558
406
  const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
559
407
  logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
560
408
  if (shouldUploadMorePreKeys) {
561
- if (stanzaId)
562
- inFlightPreKeyLow.add(stanzaId);
563
- try {
564
- await uploadPreKeys();
565
- }
566
- finally {
567
- if (stanzaId)
568
- inFlightPreKeyLow.delete(stanzaId);
569
- }
409
+ await uploadPreKeys();
570
410
  }
571
411
  }
572
412
  else {
@@ -576,8 +416,7 @@ export const makeMessagesRecvSocket = (config) => {
576
416
  validateSession: signalRepository.validateSession,
577
417
  assertSessions,
578
418
  debounceCache: identityAssertDebounce,
579
- logger,
580
- onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
419
+ logger
581
420
  });
582
421
  if (result.action === 'no_identity_node') {
583
422
  logger.info({ node }, 'unknown encrypt notification');
@@ -588,7 +427,6 @@ export const makeMessagesRecvSocket = (config) => {
588
427
  // TODO: Support PN/LID (Here is only LID now)
589
428
  const actingParticipantLid = fullNode.attrs.participant;
590
429
  const actingParticipantPn = fullNode.attrs.participant_pn;
591
- const actingParticipantUsername = fullNode.attrs.participant_username;
592
430
  const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
593
431
  const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
594
432
  switch (child?.tag) {
@@ -608,8 +446,7 @@ export const makeMessagesRecvSocket = (config) => {
608
446
  {
609
447
  ...metadata,
610
448
  author: actingParticipantLid,
611
- authorPn: actingParticipantPn,
612
- authorUsername: actingParticipantUsername
449
+ authorPn: actingParticipantPn
613
450
  }
614
451
  ]);
615
452
  break;
@@ -640,7 +477,6 @@ export const makeMessagesRecvSocket = (config) => {
640
477
  id: attrs.jid,
641
478
  phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
642
479
  lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
643
- username: attrs.participant_username || attrs.username || undefined,
644
480
  admin: (attrs.type || null)
645
481
  };
646
482
  });
@@ -710,89 +546,6 @@ export const makeMessagesRecvSocket = (config) => {
710
546
  break;
711
547
  }
712
548
  };
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
- };
796
549
  const processNotification = async (node) => {
797
550
  const result = {};
798
551
  const [child] = getAllBinaryNodeChildren(node);
@@ -803,7 +556,7 @@ export const makeMessagesRecvSocket = (config) => {
803
556
  await handleNewsletterNotification(node);
804
557
  break;
805
558
  case 'mex':
806
- await handleMexNotification(node);
559
+ await handleMexNewsletterNotification(node);
807
560
  break;
808
561
  case 'w:gp2':
809
562
  // TODO: HANDLE PARTICIPANT_PN
@@ -817,12 +570,13 @@ export const makeMessagesRecvSocket = (config) => {
817
570
  await handleEncryptNotification(node);
818
571
  break;
819
572
  case 'devices':
820
- try {
821
- await handleDevicesNotification(node);
822
- }
823
- catch (error) {
824
- logger.error({ error, node }, 'failed to handle devices notification');
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');
825
578
  }
579
+ //TODO: drop a new event, add hashes
826
580
  break;
827
581
  case 'server_sync':
828
582
  const update = getBinaryNodeChild(node, 'collection');
@@ -948,70 +702,27 @@ export const makeMessagesRecvSocket = (config) => {
948
702
  return result;
949
703
  }
950
704
  };
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
- }
996
705
  const handlePrivacyTokenNotification = async (node) => {
997
706
  const tokensNode = getBinaryNodeChild(node, 'tokens');
707
+ const from = jidNormalizedUser(node.attrs.from);
998
708
  if (!tokensNode)
999
709
  return;
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
- });
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
+ }
1015
726
  };
1016
727
  async function decipherLinkPublicKey(data) {
1017
728
  const buffer = toRequiredBuffer(data);
@@ -1037,11 +748,10 @@ export const makeMessagesRecvSocket = (config) => {
1037
748
  const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
1038
749
  await msgRetryCache.set(key, newValue);
1039
750
  };
1040
- const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
751
+ const sendMessagesAgain = async (key, ids, retryNode) => {
1041
752
  const remoteJid = key.remoteJid;
1042
753
  const participant = key.participant || remoteJid;
1043
754
  const retryCount = +retryNode.attrs.count || 1;
1044
- const msgId = ids[0];
1045
755
  // Try to get messages from cache first, then fallback to getMessage
1046
756
  const msgs = [];
1047
757
  for (const id of ids) {
@@ -1073,49 +783,12 @@ export const makeMessagesRecvSocket = (config) => {
1073
783
  // just re-send the message to everyone
1074
784
  // prevents the first message decryption failure
1075
785
  const sendToAll = !jidDecode(participant)?.device;
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
- }
786
+ // Check if we should recreate session for this retry
1115
787
  let shouldRecreateSession = false;
1116
788
  let recreateReason = '';
1117
- if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
789
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
1118
790
  try {
791
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
1119
792
  const hasSession = await signalRepository.validateSession(participant);
1120
793
  const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
1121
794
  shouldRecreateSession = result.recreate;
@@ -1129,13 +802,11 @@ export const makeMessagesRecvSocket = (config) => {
1129
802
  logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
1130
803
  }
1131
804
  }
1132
- if (!injectedFromBundle) {
1133
- await assertSessions([participant], true);
1134
- }
805
+ await assertSessions([participant], true);
1135
806
  if (isJidGroup(remoteJid)) {
1136
807
  await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
1137
808
  }
1138
- logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
809
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp');
1139
810
  for (const [i, msg] of msgs.entries()) {
1140
811
  if (!ids[i])
1141
812
  continue;
@@ -1170,6 +841,11 @@ export const makeMessagesRecvSocket = (config) => {
1170
841
  fromMe,
1171
842
  participant: attrs.participant
1172
843
  };
844
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
845
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
846
+ await sendMessageAck(node);
847
+ return;
848
+ }
1173
849
  const ids = [attrs.id];
1174
850
  if (Array.isArray(content)) {
1175
851
  const items = getBinaryNodeChildren(content[0], 'item');
@@ -1211,7 +887,7 @@ export const makeMessagesRecvSocket = (config) => {
1211
887
  try {
1212
888
  await updateSendMessageAgainCount(ids[0], key.participant);
1213
889
  logger.debug({ attrs, key }, 'recv retry request');
1214
- await sendMessagesAgain(key, ids, retryNode, node);
890
+ await sendMessagesAgain(key, ids, retryNode);
1215
891
  }
1216
892
  catch (error) {
1217
893
  logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
@@ -1229,11 +905,16 @@ export const makeMessagesRecvSocket = (config) => {
1229
905
  ]);
1230
906
  }
1231
907
  finally {
1232
- await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
908
+ await sendMessageAck(node);
1233
909
  }
1234
910
  };
1235
911
  const handleNotification = async (node) => {
1236
912
  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
+ }
1237
918
  try {
1238
919
  await Promise.all([
1239
920
  notificationMutex.mutex(async () => {
@@ -1246,7 +927,6 @@ export const makeMessagesRecvSocket = (config) => {
1246
927
  fromMe,
1247
928
  participant: node.attrs.participant,
1248
929
  participantAlt,
1249
- participantUsername: node.attrs.participant_username,
1250
930
  addressingMode,
1251
931
  id: node.attrs.id,
1252
932
  ...(msg.key || {})
@@ -1260,10 +940,253 @@ export const makeMessagesRecvSocket = (config) => {
1260
940
  ]);
1261
941
  }
1262
942
  finally {
1263
- await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
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;
1264
1182
  }
1265
1183
  };
1266
1184
  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
+ }
1267
1190
  const encNode = getBinaryNodeChild(node, 'enc');
1268
1191
  // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
1269
1192
  if (encNode?.attrs.type === 'msmsg') {
@@ -1271,34 +1194,36 @@ export const makeMessagesRecvSocket = (config) => {
1271
1194
  await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
1272
1195
  return;
1273
1196
  }
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);
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);
1291
1207
  }
1292
1208
  }
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 {
1293
1222
  await messageMutex.mutex(async () => {
1294
1223
  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
- }
1298
1224
  // message failed to decrypt
1299
1225
  if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
1300
1226
  if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
1301
- acked = true;
1302
1227
  return sendMessageAck(node, NACK_REASONS.ParsingError);
1303
1228
  }
1304
1229
  if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
@@ -1310,13 +1235,11 @@ export const makeMessagesRecvSocket = (config) => {
1310
1235
  unavailableType === 'hosted_unavailable_fanout' ||
1311
1236
  unavailableType === 'view_once_unavailable_fanout') {
1312
1237
  logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
1313
- acked = true;
1314
1238
  return sendMessageAck(node);
1315
1239
  }
1316
1240
  const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1317
1241
  if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
1318
1242
  logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
1319
- acked = true;
1320
1243
  return sendMessageAck(node);
1321
1244
  }
1322
1245
  // Request the real content from the phone via placeholder resend PDO.
@@ -1353,7 +1276,6 @@ export const makeMessagesRecvSocket = (config) => {
1353
1276
  .catch(err => {
1354
1277
  logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
1355
1278
  });
1356
- acked = true;
1357
1279
  await sendMessageAck(node);
1358
1280
  // Don't return — fall through to upsertMessage so the stub is emitted
1359
1281
  }
@@ -1363,18 +1285,32 @@ export const makeMessagesRecvSocket = (config) => {
1363
1285
  const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1364
1286
  if (messageAge > STATUS_EXPIRY_SECONDS) {
1365
1287
  logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message');
1366
- acked = true;
1367
1288
  return sendMessageAck(node);
1368
1289
  }
1369
1290
  }
1370
- logger.debug('[handleMessage] Attempting retry request for failed decryption');
1371
- // WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
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
1372
1295
  await retryMutex.mutex(async () => {
1373
1296
  try {
1374
1297
  if (!ws.isOpen) {
1375
1298
  logger.debug({ node }, 'Connection closed, skipping retry');
1376
1299
  return;
1377
1300
  }
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
+ }
1378
1314
  const encNode = getBinaryNodeChild(node, 'enc');
1379
1315
  await sendRetryRequest(node, !encNode);
1380
1316
  if (retryRequestDelayMs) {
@@ -1382,9 +1318,16 @@ export const makeMessagesRecvSocket = (config) => {
1382
1318
  }
1383
1319
  }
1384
1320
  catch (err) {
1385
- logger.error({ err }, 'Failed to send retry');
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
+ }
1386
1330
  }
1387
- acked = true;
1388
1331
  await sendMessageAck(node, NACK_REASONS.UnhandledError);
1389
1332
  });
1390
1333
  }
@@ -1413,7 +1356,6 @@ export const makeMessagesRecvSocket = (config) => {
1413
1356
  else if (!sendActiveReceipts) {
1414
1357
  type = 'inactive';
1415
1358
  }
1416
- acked = true;
1417
1359
  await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1418
1360
  // send ack for history message
1419
1361
  const isAnyHistoryMsg = getHistoryMsg(msg.message);
@@ -1423,73 +1365,147 @@ export const makeMessagesRecvSocket = (config) => {
1423
1365
  }
1424
1366
  }
1425
1367
  else {
1426
- acked = true;
1427
1368
  await sendMessageAck(node);
1428
1369
  logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
1429
1370
  }
1430
1371
  }
1431
1372
  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 ──────────────────────────────────────────────
1432
1465
  await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1433
1466
  });
1434
1467
  }
1435
1468
  catch (error) {
1436
1469
  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
- }
1440
1470
  }
1441
1471
  };
1442
1472
  const handleCall = async (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
- }
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);
1493
1509
  };
1494
1510
  const handleBadAck = async ({ attrs }) => {
1495
1511
  const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
@@ -1509,61 +1525,29 @@ export const makeMessagesRecvSocket = (config) => {
1509
1525
  // error in acknowledgement,
1510
1526
  // device could not display the message
1511
1527
  if (attrs.error) {
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
- }
1528
+ logger.warn({ attrs }, 'received error in ack');
1558
1529
  ev.emit('messages.update', [
1559
1530
  {
1560
1531
  key,
1561
1532
  update: {
1562
1533
  status: WAMessageStatus.ERROR,
1563
- messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
1534
+ messageStubParameters: [attrs.error]
1564
1535
  }
1565
1536
  }
1566
1537
  ]);
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
+ // }
1567
1551
  }
1568
1552
  };
1569
1553
  /// processes a node with the given function
@@ -1576,30 +1560,53 @@ export const makeMessagesRecvSocket = (config) => {
1576
1560
  return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1577
1561
  }
1578
1562
  };
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
- });
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();
1589
1609
  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
- }
1603
1610
  const isOffline = !!node.attrs.offline;
1604
1611
  if (isOffline) {
1605
1612
  offlineNodeProcessor.enqueue(type, node);
@@ -1655,110 +1662,12 @@ export const makeMessagesRecvSocket = (config) => {
1655
1662
  await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1656
1663
  }
1657
1664
  });
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 }) => {
1665
+ ev.on('connection.update', ({ isOnline }) => {
1663
1666
  if (typeof isOnline !== 'undefined') {
1664
1667
  sendActiveReceipts = isOnline;
1665
1668
  logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1666
1669
  }
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
- }
1690
1670
  });
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
- }
1762
1671
  return {
1763
1672
  ...sock,
1764
1673
  sendMessageAck,