@vinzsocket/baileys 3.3.2 → 3.3.13

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 (212) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1337 -2685
  3. package/WAProto/WAProto.proto +916 -360
  4. package/WAProto/fix-imports.js +18 -22
  5. package/WAProto/index.d.ts +0 -14015
  6. package/WAProto/index.js +80576 -45941
  7. package/lib/Defaults/index.d.ts +14 -15
  8. package/lib/Defaults/index.d.ts.map +1 -1
  9. package/lib/Defaults/index.js +109 -98
  10. package/lib/Defaults/index.js.map +1 -1
  11. package/lib/Signal/Group/group_cipher.js.map +1 -1
  12. package/lib/Signal/Group/keyhelper.d.ts.map +1 -1
  13. package/lib/Signal/Group/keyhelper.js.map +1 -1
  14. package/lib/Signal/Group/sender-chain-key.js.map +1 -1
  15. package/lib/Signal/Group/sender-key-message.js.map +1 -1
  16. package/lib/Signal/Group/sender-message-key.js.map +1 -1
  17. package/lib/Signal/libsignal.d.ts.map +1 -1
  18. package/lib/Signal/libsignal.js +17 -45
  19. package/lib/Signal/libsignal.js.map +1 -1
  20. package/lib/Signal/lid-mapping.d.ts +0 -4
  21. package/lib/Signal/lid-mapping.d.ts.map +1 -1
  22. package/lib/Signal/lid-mapping.js +0 -6
  23. package/lib/Signal/lid-mapping.js.map +1 -1
  24. package/lib/Socket/business.d.ts +532 -213
  25. package/lib/Socket/business.d.ts.map +1 -1
  26. package/lib/Socket/business.js +401 -358
  27. package/lib/Socket/chats.d.ts +2 -15
  28. package/lib/Socket/chats.d.ts.map +1 -1
  29. package/lib/Socket/chats.js +40 -247
  30. package/lib/Socket/chats.js.map +1 -1
  31. package/lib/Socket/communities.d.ts +641 -269
  32. package/lib/Socket/communities.d.ts.map +1 -1
  33. package/lib/Socket/dugong.d.ts +127 -315
  34. package/lib/Socket/dugong.d.ts.map +1 -0
  35. package/lib/Socket/dugong.js +749 -653
  36. package/lib/Socket/dugong.js.map +1 -0
  37. package/lib/Socket/groups.d.ts +2 -13
  38. package/lib/Socket/groups.d.ts.map +1 -1
  39. package/lib/Socket/groups.js +1 -21
  40. package/lib/Socket/groups.js.map +1 -1
  41. package/lib/Socket/index.d.ts +631 -256
  42. package/lib/Socket/index.d.ts.map +1 -1
  43. package/lib/Socket/index.js +12 -9
  44. package/lib/Socket/index.js.map +1 -1
  45. package/lib/Socket/messages-recv.d.ts +58 -23
  46. package/lib/Socket/messages-recv.d.ts.map +1 -1
  47. package/lib/Socket/messages-recv.js +181 -645
  48. package/lib/Socket/messages-recv.js.map +1 -1
  49. package/lib/Socket/messages-send.d.ts +575 -201
  50. package/lib/Socket/messages-send.d.ts.map +1 -1
  51. package/lib/Socket/messages-send.js +1552 -1185
  52. package/lib/Socket/messages-send.js.map +1 -1
  53. package/lib/Socket/mex.d.ts.map +1 -1
  54. package/lib/Socket/mex.js +8 -2
  55. package/lib/Socket/mex.js.map +1 -1
  56. package/lib/Socket/newsletter.d.ts +18 -11
  57. package/lib/Socket/newsletter.d.ts.map +1 -1
  58. package/lib/Socket/newsletter.js +440 -165
  59. package/lib/Socket/newsletter.js.map +1 -1
  60. package/lib/Socket/socket.d.ts +2 -6
  61. package/lib/Socket/socket.d.ts.map +1 -1
  62. package/lib/Socket/socket.js +25 -59
  63. package/lib/Socket/socket.js.map +1 -1
  64. package/lib/Types/Auth.d.ts +0 -1
  65. package/lib/Types/Auth.d.ts.map +1 -1
  66. package/lib/Types/Bussines.d.ts +34 -22
  67. package/lib/Types/Call.d.ts +1 -1
  68. package/lib/Types/Call.d.ts.map +1 -1
  69. package/lib/Types/Chat.d.ts +0 -1
  70. package/lib/Types/Chat.d.ts.map +1 -1
  71. package/lib/Types/Contact.d.ts +0 -2
  72. package/lib/Types/Contact.d.ts.map +1 -1
  73. package/lib/Types/Events.d.ts +1 -20
  74. package/lib/Types/Events.d.ts.map +1 -1
  75. package/lib/Types/GroupMetadata.d.ts +1 -4
  76. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  77. package/lib/Types/Message.d.ts +348 -294
  78. package/lib/Types/Message.d.ts.map +1 -1
  79. package/lib/Types/Message.js.map +1 -1
  80. package/lib/Types/Newsletter.d.ts.map +1 -0
  81. package/lib/Types/Newsletter.js.map +1 -0
  82. package/lib/Types/Signal.d.ts +1 -12
  83. package/lib/Types/Signal.d.ts.map +1 -1
  84. package/lib/Types/Socket.d.ts +148 -126
  85. package/lib/Types/Socket.d.ts.map +1 -1
  86. package/lib/Types/State.d.ts +0 -58
  87. package/lib/Types/State.d.ts.map +1 -1
  88. package/lib/Types/State.js +0 -43
  89. package/lib/Types/State.js.map +1 -1
  90. package/lib/Types/index.d.ts +52 -52
  91. package/lib/Types/index.d.ts.map +1 -1
  92. package/lib/Types/index.js +30 -23
  93. package/lib/Types/index.js.map +1 -1
  94. package/lib/Utils/auth-utils.d.ts +0 -5
  95. package/lib/Utils/auth-utils.d.ts.map +1 -1
  96. package/lib/Utils/auth-utils.js +0 -12
  97. package/lib/Utils/auth-utils.js.map +1 -1
  98. package/lib/Utils/browser-utils.js +0 -1
  99. package/lib/Utils/chat-utils.d.ts +4 -34
  100. package/lib/Utils/chat-utils.d.ts.map +1 -1
  101. package/lib/Utils/chat-utils.js +20 -80
  102. package/lib/Utils/chat-utils.js.map +1 -1
  103. package/lib/Utils/crypto.d.ts +12 -12
  104. package/lib/Utils/crypto.d.ts.map +1 -1
  105. package/lib/Utils/crypto.js.map +1 -1
  106. package/lib/Utils/decode-wa-message.d.ts +0 -18
  107. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  108. package/lib/Utils/decode-wa-message.js +0 -34
  109. package/lib/Utils/decode-wa-message.js.map +1 -1
  110. package/lib/Utils/event-buffer.d.ts +0 -2
  111. package/lib/Utils/event-buffer.d.ts.map +1 -1
  112. package/lib/Utils/event-buffer.js +1 -49
  113. package/lib/Utils/event-buffer.js.map +1 -1
  114. package/lib/Utils/generics.d.ts +2 -2
  115. package/lib/Utils/generics.d.ts.map +1 -1
  116. package/lib/Utils/generics.js +1 -10
  117. package/lib/Utils/generics.js.map +1 -1
  118. package/lib/Utils/history.d.ts +0 -2
  119. package/lib/Utils/history.d.ts.map +1 -1
  120. package/lib/Utils/history.js +9 -12
  121. package/lib/Utils/history.js.map +1 -1
  122. package/lib/Utils/identity-change-handler.d.ts +0 -7
  123. package/lib/Utils/identity-change-handler.d.ts.map +1 -1
  124. package/lib/Utils/identity-change-handler.js +0 -1
  125. package/lib/Utils/identity-change-handler.js.map +1 -1
  126. package/lib/Utils/index.d.ts +23 -23
  127. package/lib/Utils/index.d.ts.map +1 -1
  128. package/lib/Utils/index.js +1 -4
  129. package/lib/Utils/index.js.map +1 -1
  130. package/lib/Utils/link-preview.js +2 -2
  131. package/lib/Utils/link-preview.js.map +1 -1
  132. package/lib/Utils/logger.d.ts +2 -1
  133. package/lib/Utils/logger.d.ts.map +1 -1
  134. package/lib/Utils/message-retry-manager.d.ts +0 -5
  135. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  136. package/lib/Utils/message-retry-manager.js +0 -40
  137. package/lib/Utils/message-retry-manager.js.map +1 -1
  138. package/lib/Utils/messages-media.d.ts +13 -16
  139. package/lib/Utils/messages-media.d.ts.map +1 -1
  140. package/lib/Utils/messages-media.js +79 -85
  141. package/lib/Utils/messages-media.js.map +1 -1
  142. package/lib/Utils/messages.d.ts +6 -16
  143. package/lib/Utils/messages.d.ts.map +1 -1
  144. package/lib/Utils/messages.js +1160 -1021
  145. package/lib/Utils/messages.js.map +1 -1
  146. package/lib/Utils/noise-handler.d.ts +1 -1
  147. package/lib/Utils/process-message.d.ts.map +1 -1
  148. package/lib/Utils/process-message.js +1 -103
  149. package/lib/Utils/process-message.js.map +1 -1
  150. package/lib/Utils/rich-messages.d.ts.map +1 -0
  151. package/lib/Utils/rich-messages.js.map +1 -0
  152. package/lib/Utils/signal.d.ts +0 -13
  153. package/lib/Utils/signal.d.ts.map +1 -1
  154. package/lib/Utils/signal.js +0 -42
  155. package/lib/Utils/signal.js.map +1 -1
  156. package/lib/Utils/sync-action-utils.d.ts.map +1 -1
  157. package/lib/Utils/sync-action-utils.js +0 -1
  158. package/lib/Utils/sync-action-utils.js.map +1 -1
  159. package/lib/Utils/tc-token-utils.d.ts +1 -26
  160. package/lib/Utils/tc-token-utils.d.ts.map +1 -1
  161. package/lib/Utils/tc-token-utils.js +5 -151
  162. package/lib/Utils/tc-token-utils.js.map +1 -1
  163. package/lib/Utils/validate-connection.d.ts.map +1 -1
  164. package/lib/Utils/validate-connection.js +2 -12
  165. package/lib/Utils/validate-connection.js.map +1 -1
  166. package/lib/VoIP/audio-feeder.js +8 -0
  167. package/lib/VoIP/relay-transport.js +15 -1
  168. package/lib/VoIP/worker-bootstrap.js +14 -2
  169. package/lib/WABinary/decode.d.ts +1 -1
  170. package/lib/WABinary/decode.d.ts.map +1 -1
  171. package/lib/WABinary/generic-utils.d.ts +3 -1
  172. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  173. package/lib/WABinary/generic-utils.js +78 -0
  174. package/lib/WABinary/generic-utils.js.map +1 -1
  175. package/lib/WAM/encode.d.ts +1 -1
  176. package/lib/WAM/encode.d.ts.map +1 -1
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  178. package/lib/WAUSync/Protocols/USyncContactProtocol.js +3 -26
  179. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  180. package/lib/WAUSync/Protocols/index.d.ts +0 -1
  181. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  182. package/lib/WAUSync/Protocols/index.js +0 -1
  183. package/lib/WAUSync/Protocols/index.js.map +1 -1
  184. package/lib/WAUSync/USyncQuery.d.ts +0 -1
  185. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  186. package/lib/WAUSync/USyncQuery.js +2 -6
  187. package/lib/WAUSync/USyncQuery.js.map +1 -1
  188. package/lib/WAUSync/USyncUser.d.ts +0 -4
  189. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  190. package/lib/WAUSync/USyncUser.js +0 -8
  191. package/lib/WAUSync/USyncUser.js.map +1 -1
  192. package/lib/index.d.ts +1 -0
  193. package/lib/index.d.ts.map +1 -1
  194. package/lib/index.js +1 -0
  195. package/lib/index.js.map +1 -1
  196. package/package.json +24 -91
  197. package/engine-requirements.js +0 -27
  198. package/lib/Types/Mex.d.ts +0 -141
  199. package/lib/Types/Mex.d.ts.map +0 -1
  200. package/lib/Types/Mex.js +0 -37
  201. package/lib/Types/Mex.js.map +0 -1
  202. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  203. package/lib/Utils/companion-reg-client-utils.d.ts.map +0 -1
  204. package/lib/Utils/companion-reg-client-utils.js +0 -35
  205. package/lib/Utils/companion-reg-client-utils.js.map +0 -1
  206. package/lib/Utils/mention.d.ts +0 -14
  207. package/lib/Utils/mention.js +0 -138
  208. package/lib/Utils/story-card.js +0 -107
  209. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  210. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +0 -1
  211. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  212. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +0 -1
@@ -4,24 +4,18 @@ 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
10
  import { makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
11
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';
12
+ import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
14
13
  import { extractGroupMetadata } from './groups.js';
15
14
  import { makeMessagesSocket } from './messages-send.js';
16
- const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(ReachoutTimelockEnforcementType));
17
- function isValidEnforcementType(value) {
18
- return typeof value === 'string' && ENFORCEMENT_TYPE_VALUES.has(value);
19
- }
20
15
  export const makeMessagesRecvSocket = (config) => {
21
16
  const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
22
17
  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);
18
+ const { ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
25
19
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
26
20
  const retryMutex = makeMutex();
27
21
  const msgRetryCache = config.msgRetryCounterCache ||
@@ -34,6 +28,11 @@ export const makeMessagesRecvSocket = (config) => {
34
28
  stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
35
29
  useClones: false
36
30
  });
31
+ const placeholderResendCache = config.placeholderResendCache ||
32
+ new NodeCache({
33
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
+ useClones: false
35
+ });
37
36
  // Debounce identity-change session refreshes per JID to avoid bursts
38
37
  const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
39
38
  let sendActiveReceipts = false;
@@ -87,140 +86,25 @@ export const makeMessagesRecvSocket = (config) => {
87
86
  }, 8000);
88
87
  return sendPeerDataOperationMessage(pdoMessage);
89
88
  };
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) => {
89
+ // Handles mex newsletter notifications
90
+ const handleMexNewsletterNotification = async (node) => {
193
91
  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');
92
+ if (!mexNode?.content) {
93
+ logger.warn({ node }, 'Invalid mex newsletter notification');
198
94
  return;
199
95
  }
200
96
  let data;
201
97
  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());
98
+ data = JSON.parse(mexNode.content.toString());
209
99
  }
210
100
  catch (error) {
211
- logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification');
101
+ logger.error({ err: error, node }, 'Failed to parse mex newsletter notification');
212
102
  return;
213
103
  }
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
- }
104
+ const operation = data?.operation;
105
+ const updates = data?.updates;
222
106
  if (!updates || !operation) {
223
- logger.warn({ data }, 'invalid mex newsletter notification content');
107
+ logger.warn({ data }, 'Invalid mex newsletter notification content');
224
108
  return;
225
109
  }
226
110
  logger.info({ operation, updates }, 'got mex newsletter notification');
@@ -248,114 +132,91 @@ export const makeMessagesRecvSocket = (config) => {
248
132
  }
249
133
  }
250
134
  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
135
  default:
268
- logger.info({ operation, data }, 'unhandled mex newsletter notification');
136
+ logger.info({ operation, data }, 'Unhandled mex newsletter notification');
269
137
  break;
270
138
  }
271
139
  };
272
140
  // Handles newsletter notifications
273
141
  const handleNewsletterNotification = async (node) => {
274
142
  const from = node.attrs.from;
275
- const children = getAllBinaryNodeChildren(node);
143
+ const child = getAllBinaryNodeChildren(node)[0];
276
144
  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 = {
145
+ logger.info({ from, child }, 'got newsletter notification');
146
+ switch (child.tag) {
147
+ case 'reaction':
148
+ const reactionUpdate = {
149
+ id: from,
150
+ server_id: child.attrs.message_id,
151
+ reaction: {
152
+ code: getBinaryNodeChildString(child, 'reaction'),
153
+ count: 1
154
+ }
155
+ };
156
+ ev.emit('newsletter.reaction', reactionUpdate);
157
+ break;
158
+ case 'view':
159
+ const viewUpdate = {
160
+ id: from,
161
+ server_id: child.attrs.message_id,
162
+ count: parseInt(child.content?.toString() || '0', 10)
163
+ };
164
+ ev.emit('newsletter.view', viewUpdate);
165
+ break;
166
+ case 'participant':
167
+ const participantUpdate = {
168
+ id: from,
169
+ author,
170
+ user: child.attrs.jid,
171
+ action: child.attrs.action,
172
+ new_role: child.attrs.role
173
+ };
174
+ ev.emit('newsletter-participants.update', participantUpdate);
175
+ break;
176
+ case 'update':
177
+ const settingsNode = getBinaryNodeChild(child, 'settings');
178
+ if (settingsNode) {
179
+ const update = {};
180
+ const nameNode = getBinaryNodeChild(settingsNode, 'name');
181
+ if (nameNode?.content)
182
+ update.name = nameNode.content.toString();
183
+ const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
184
+ if (descriptionNode?.content)
185
+ update.description = descriptionNode.content.toString();
186
+ ev.emit('newsletter-settings.update', {
303
187
  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;
188
+ update
189
+ });
311
190
  }
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
- });
191
+ break;
192
+ case 'message':
193
+ const plaintextNode = getBinaryNodeChild(child, 'plaintext');
194
+ if (plaintextNode?.content) {
195
+ try {
196
+ const contentBuf = typeof plaintextNode.content === 'string'
197
+ ? Buffer.from(plaintextNode.content, 'binary')
198
+ : Buffer.from(plaintextNode.content);
199
+ const messageProto = proto.Message.decode(contentBuf).toJSON();
200
+ const fullMessage = proto.WebMessageInfo.fromObject({
201
+ key: {
202
+ remoteJid: from,
203
+ id: child.attrs.message_id || child.attrs.server_id,
204
+ fromMe: false // TODO: is this really true though
205
+ },
206
+ message: messageProto,
207
+ messageTimestamp: +child.attrs.t
208
+ }).toJSON();
209
+ await upsertMessage(fullMessage, 'append');
210
+ logger.info('Processed plaintext newsletter message');
326
211
  }
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
- }
212
+ catch (error) {
213
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
352
214
  }
353
- break;
354
215
  }
355
- default:
356
- logger.warn({ node, child }, 'Unknown newsletter notification child');
357
- break;
358
- }
216
+ break;
217
+ default:
218
+ logger.warn({ node }, 'Unknown newsletter notification');
219
+ break;
359
220
  }
360
221
  };
361
222
  const sendMessageAck = async (node, errorCode) => {
@@ -515,58 +376,15 @@ export const makeMessagesRecvSocket = (config) => {
515
376
  logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
516
377
  }, authState?.creds?.me?.id || 'sendRetryRequest');
517
378
  };
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
379
  const handleEncryptNotification = async (node) => {
550
380
  const from = node.attrs.from;
551
381
  if (from === S_WHATSAPP_NET) {
552
- const stanzaId = node.attrs.id;
553
- if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
554
- return;
555
- }
556
382
  const countChild = getBinaryNodeChild(node, 'count');
557
383
  const count = +countChild.attrs.value;
558
384
  const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
559
385
  logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
560
386
  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
- }
387
+ await uploadPreKeys();
570
388
  }
571
389
  }
572
390
  else {
@@ -576,8 +394,7 @@ export const makeMessagesRecvSocket = (config) => {
576
394
  validateSession: signalRepository.validateSession,
577
395
  assertSessions,
578
396
  debounceCache: identityAssertDebounce,
579
- logger,
580
- onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
397
+ logger
581
398
  });
582
399
  if (result.action === 'no_identity_node') {
583
400
  logger.info({ node }, 'unknown encrypt notification');
@@ -588,7 +405,6 @@ export const makeMessagesRecvSocket = (config) => {
588
405
  // TODO: Support PN/LID (Here is only LID now)
589
406
  const actingParticipantLid = fullNode.attrs.participant;
590
407
  const actingParticipantPn = fullNode.attrs.participant_pn;
591
- const actingParticipantUsername = fullNode.attrs.participant_username;
592
408
  const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
593
409
  const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
594
410
  switch (child?.tag) {
@@ -608,8 +424,7 @@ export const makeMessagesRecvSocket = (config) => {
608
424
  {
609
425
  ...metadata,
610
426
  author: actingParticipantLid,
611
- authorPn: actingParticipantPn,
612
- authorUsername: actingParticipantUsername
427
+ authorPn: actingParticipantPn
613
428
  }
614
429
  ]);
615
430
  break;
@@ -640,7 +455,6 @@ export const makeMessagesRecvSocket = (config) => {
640
455
  id: attrs.jid,
641
456
  phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
642
457
  lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
643
- username: attrs.participant_username || attrs.username || undefined,
644
458
  admin: (attrs.type || null)
645
459
  };
646
460
  });
@@ -710,89 +524,6 @@ export const makeMessagesRecvSocket = (config) => {
710
524
  break;
711
525
  }
712
526
  };
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
527
  const processNotification = async (node) => {
797
528
  const result = {};
798
529
  const [child] = getAllBinaryNodeChildren(node);
@@ -803,7 +534,7 @@ export const makeMessagesRecvSocket = (config) => {
803
534
  await handleNewsletterNotification(node);
804
535
  break;
805
536
  case 'mex':
806
- await handleMexNotification(node);
537
+ await handleMexNewsletterNotification(node);
807
538
  break;
808
539
  case 'w:gp2':
809
540
  // TODO: HANDLE PARTICIPANT_PN
@@ -817,12 +548,13 @@ export const makeMessagesRecvSocket = (config) => {
817
548
  await handleEncryptNotification(node);
818
549
  break;
819
550
  case 'devices':
820
- try {
821
- await handleDevicesNotification(node);
822
- }
823
- catch (error) {
824
- logger.error({ error, node }, 'failed to handle devices notification');
551
+ const devices = getBinaryNodeChildren(child, 'device');
552
+ if (areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
553
+ areJidsSameUser(child.attrs.lid, authState.creds.me.lid)) {
554
+ const deviceData = devices.map(d => ({ id: d.attrs.jid, lid: d.attrs.lid }));
555
+ logger.info({ deviceData }, 'my own devices changed');
825
556
  }
557
+ //TODO: drop a new event, add hashes
826
558
  break;
827
559
  case 'server_sync':
828
560
  const update = getBinaryNodeChild(node, 'collection');
@@ -948,70 +680,27 @@ export const makeMessagesRecvSocket = (config) => {
948
680
  return result;
949
681
  }
950
682
  };
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
683
  const handlePrivacyTokenNotification = async (node) => {
997
684
  const tokensNode = getBinaryNodeChild(node, 'tokens');
685
+ const from = jidNormalizedUser(node.attrs.from);
998
686
  if (!tokensNode)
999
687
  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
- });
688
+ const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
689
+ for (const tokenNode of tokenNodes) {
690
+ const { attrs, content } = tokenNode;
691
+ const type = attrs.type;
692
+ const timestamp = attrs.t;
693
+ if (type === 'trusted_contact' && content instanceof Buffer) {
694
+ logger.debug({
695
+ from,
696
+ timestamp,
697
+ tcToken: content
698
+ }, 'received trusted contact token');
699
+ await authState.keys.set({
700
+ tctoken: { [from]: { token: content, timestamp } }
701
+ });
702
+ }
703
+ }
1015
704
  };
1016
705
  async function decipherLinkPublicKey(data) {
1017
706
  const buffer = toRequiredBuffer(data);
@@ -1037,11 +726,10 @@ export const makeMessagesRecvSocket = (config) => {
1037
726
  const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
1038
727
  await msgRetryCache.set(key, newValue);
1039
728
  };
1040
- const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
729
+ const sendMessagesAgain = async (key, ids, retryNode) => {
1041
730
  const remoteJid = key.remoteJid;
1042
731
  const participant = key.participant || remoteJid;
1043
732
  const retryCount = +retryNode.attrs.count || 1;
1044
- const msgId = ids[0];
1045
733
  // Try to get messages from cache first, then fallback to getMessage
1046
734
  const msgs = [];
1047
735
  for (const id of ids) {
@@ -1073,49 +761,12 @@ export const makeMessagesRecvSocket = (config) => {
1073
761
  // just re-send the message to everyone
1074
762
  // prevents the first message decryption failure
1075
763
  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
- }
764
+ // Check if we should recreate session for this retry
1115
765
  let shouldRecreateSession = false;
1116
766
  let recreateReason = '';
1117
- if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
767
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
1118
768
  try {
769
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
1119
770
  const hasSession = await signalRepository.validateSession(participant);
1120
771
  const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
1121
772
  shouldRecreateSession = result.recreate;
@@ -1129,13 +780,11 @@ export const makeMessagesRecvSocket = (config) => {
1129
780
  logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
1130
781
  }
1131
782
  }
1132
- if (!injectedFromBundle) {
1133
- await assertSessions([participant], true);
1134
- }
783
+ await assertSessions([participant], true);
1135
784
  if (isJidGroup(remoteJid)) {
1136
785
  await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
1137
786
  }
1138
- logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
787
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp');
1139
788
  for (const [i, msg] of msgs.entries()) {
1140
789
  if (!ids[i])
1141
790
  continue;
@@ -1170,6 +819,11 @@ export const makeMessagesRecvSocket = (config) => {
1170
819
  fromMe,
1171
820
  participant: attrs.participant
1172
821
  };
822
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
823
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
824
+ await sendMessageAck(node);
825
+ return;
826
+ }
1173
827
  const ids = [attrs.id];
1174
828
  if (Array.isArray(content)) {
1175
829
  const items = getBinaryNodeChildren(content[0], 'item');
@@ -1211,7 +865,7 @@ export const makeMessagesRecvSocket = (config) => {
1211
865
  try {
1212
866
  await updateSendMessageAgainCount(ids[0], key.participant);
1213
867
  logger.debug({ attrs, key }, 'recv retry request');
1214
- await sendMessagesAgain(key, ids, retryNode, node);
868
+ await sendMessagesAgain(key, ids, retryNode);
1215
869
  }
1216
870
  catch (error) {
1217
871
  logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
@@ -1234,6 +888,11 @@ export const makeMessagesRecvSocket = (config) => {
1234
888
  };
1235
889
  const handleNotification = async (node) => {
1236
890
  const remoteJid = node.attrs.from;
891
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
892
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
893
+ await sendMessageAck(node);
894
+ return;
895
+ }
1237
896
  try {
1238
897
  await Promise.all([
1239
898
  notificationMutex.mutex(async () => {
@@ -1246,7 +905,6 @@ export const makeMessagesRecvSocket = (config) => {
1246
905
  fromMe,
1247
906
  participant: node.attrs.participant,
1248
907
  participantAlt,
1249
- participantUsername: node.attrs.participant_username,
1250
908
  addressingMode,
1251
909
  id: node.attrs.id,
1252
910
  ...(msg.key || {})
@@ -1264,6 +922,11 @@ export const makeMessagesRecvSocket = (config) => {
1264
922
  }
1265
923
  };
1266
924
  const handleMessage = async (node) => {
925
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
926
+ logger.debug({ key: node.attrs.key }, 'ignored message');
927
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
928
+ return;
929
+ }
1267
930
  const encNode = getBinaryNodeChild(node, 'enc');
1268
931
  // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
1269
932
  if (encNode?.attrs.type === 'msmsg') {
@@ -1367,14 +1030,29 @@ export const makeMessagesRecvSocket = (config) => {
1367
1030
  return sendMessageAck(node);
1368
1031
  }
1369
1032
  }
1370
- logger.debug('[handleMessage] Attempting retry request for failed decryption');
1371
- // WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
1033
+ const errorMessage = msg?.messageStubParameters?.[0] || '';
1034
+ const isPreKeyError = errorMessage.includes('PreKey');
1035
+ logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
1036
+ // Handle both pre-key and normal retries in single mutex
1372
1037
  await retryMutex.mutex(async () => {
1373
1038
  try {
1374
1039
  if (!ws.isOpen) {
1375
1040
  logger.debug({ node }, 'Connection closed, skipping retry');
1376
1041
  return;
1377
1042
  }
1043
+ // Handle pre-key errors with upload and delay
1044
+ if (isPreKeyError) {
1045
+ logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
1046
+ try {
1047
+ logger.debug('Uploading pre-keys for error recovery');
1048
+ await uploadPreKeys(5);
1049
+ logger.debug('Waiting for server to process new pre-keys');
1050
+ await delay(1000);
1051
+ }
1052
+ catch (uploadErr) {
1053
+ logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
1054
+ }
1055
+ }
1378
1056
  const encNode = getBinaryNodeChild(node, 'enc');
1379
1057
  await sendRetryRequest(node, !encNode);
1380
1058
  if (retryRequestDelayMs) {
@@ -1382,7 +1060,15 @@ export const makeMessagesRecvSocket = (config) => {
1382
1060
  }
1383
1061
  }
1384
1062
  catch (err) {
1385
- logger.error({ err }, 'Failed to send retry');
1063
+ logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry');
1064
+ // Still attempt retry even if pre-key upload failed
1065
+ try {
1066
+ const encNode = getBinaryNodeChild(node, 'enc');
1067
+ await sendRetryRequest(node, !encNode);
1068
+ }
1069
+ catch (retryErr) {
1070
+ logger.error({ retryErr }, 'Failed to send retry after error handling');
1071
+ }
1386
1072
  }
1387
1073
  acked = true;
1388
1074
  await sendMessageAck(node, NACK_REASONS.UnhandledError);
@@ -1458,13 +1144,6 @@ export const makeMessagesRecvSocket = (config) => {
1458
1144
  offline: !!attrs.offline,
1459
1145
  status
1460
1146
  };
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
1147
  if (status === 'offer') {
1469
1148
  call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1470
1149
  call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
@@ -1509,61 +1188,29 @@ export const makeMessagesRecvSocket = (config) => {
1509
1188
  // error in acknowledgement,
1510
1189
  // device could not display the message
1511
1190
  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
- }
1191
+ logger.warn({ attrs }, 'received error in ack');
1558
1192
  ev.emit('messages.update', [
1559
1193
  {
1560
1194
  key,
1561
1195
  update: {
1562
1196
  status: WAMessageStatus.ERROR,
1563
- messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
1197
+ messageStubParameters: [attrs.error]
1564
1198
  }
1565
1199
  }
1566
1200
  ]);
1201
+ // resend the message with device_fanout=false, use at your own risk
1202
+ // if (attrs.error === '475') {
1203
+ // const msg = await getMessage(key)
1204
+ // if (msg) {
1205
+ // await relayMessage(key.remoteJid!, msg, {
1206
+ // messageId: key.id!,
1207
+ // useUserDevicesCache: false,
1208
+ // additionalAttributes: {
1209
+ // device_fanout: 'false'
1210
+ // }
1211
+ // })
1212
+ // }
1213
+ // }
1567
1214
  }
1568
1215
  };
1569
1216
  /// processes a node with the given function
@@ -1587,19 +1234,6 @@ export const makeMessagesRecvSocket = (config) => {
1587
1234
  yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
1588
1235
  });
1589
1236
  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
1237
  const isOffline = !!node.attrs.offline;
1604
1238
  if (isOffline) {
1605
1239
  offlineNodeProcessor.enqueue(type, node);
@@ -1655,110 +1289,12 @@ export const makeMessagesRecvSocket = (config) => {
1655
1289
  await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1656
1290
  }
1657
1291
  });
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 }) => {
1292
+ ev.on('connection.update', ({ isOnline }) => {
1663
1293
  if (typeof isOnline !== 'undefined') {
1664
1294
  sendActiveReceipts = isOnline;
1665
1295
  logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1666
1296
  }
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
- });
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
1297
  });
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
1298
  return {
1763
1299
  ...sock,
1764
1300
  sendMessageAck,