kage-baileys 3.0.6 → 3.2.3

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