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
@@ -766,7 +766,8 @@ const makeMessagesRecvSocket = (config) => {
766
766
  const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
767
767
  // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
768
768
  if (encNode && encNode.attrs.type === 'msmsg') {
769
- logger.debug({ key: node.attrs.key }, 'ignored msmsg');
769
+ logger.warn({ id: node.attrs.id, from: node.attrs.from }, 'msmsg no compatible: contenido cifrado no procesado');
770
+ ev.emit('kage.unsupported-message', { id: node.attrs.id, chat: node.attrs.from, encryption: 'msmsg', reason: 'UNSUPPORTED_ENCRYPTION' });
770
771
  await sendMessageAck(node);
771
772
  return;
772
773
  }
@@ -822,7 +823,9 @@ const makeMessagesRecvSocket = (config) => {
822
823
  // no type in the receipt => message delivered
823
824
  let type = undefined;
824
825
  if ((_b = msg.key.participant) === null || _b === void 0 ? void 0 : _b.endsWith('@lid')) {
825
- msg.key.participant = node.attrs.participant_pn || authState.creds.me.id;
826
+ const originalLid = msg.key.participant;
827
+ const mapped = node.attrs.participant_pn || await Promise.resolve(signalRepository.lidMapping?.getPNForLID?.(originalLid)).catch(() => undefined);
828
+ if (mapped) { msg.key.participantAlt = originalLid; msg.key.participant = mapped; }
826
829
  }
827
830
  if ((0, WABinary_1.isJidGroup)(msg.key.remoteJid) && ((_f = (_e = (_d = (_c = msg.message) === null || _c === void 0 ? void 0 : _c.extendedTextMessage) === null || _d === void 0 ? void 0 : _d.contextInfo) === null || _e === void 0 ? void 0 : _e.participant) === null || _f === void 0 ? void 0 : _f.endsWith('@lid'))) {
828
831
  if (msg.message.extendedTextMessage.contextInfo) {
@@ -835,9 +838,10 @@ const makeMessagesRecvSocket = (config) => {
835
838
  void warmupGroupParticipants(msg.key.remoteJid);
836
839
  }
837
840
  if (!(0, WABinary_1.isJidGroup)(msg.key.remoteJid) && (0, WABinary_1.isLidUser)(msg.key.remoteJid)) {
838
- msg.key.remoteJid = node.attrs.sender_pn
839
- || node.attrs.peer_recipient_pn
840
- || (0, WABinary_1.lidToJid)(msg.key.remoteJid);
841
+ const originalLid = msg.key.remoteJid;
842
+ const mapped = node.attrs.sender_pn || node.attrs.peer_recipient_pn
843
+ || await Promise.resolve(signalRepository.lidMapping?.getPNForLID?.(originalLid)).catch(() => undefined);
844
+ if (mapped) { msg.key.remoteJidAlt = originalLid; msg.key.remoteJid = mapped; }
841
845
  }
842
846
  let participant = msg.key.participant;
843
847
  if (category === 'peer') { // special peer message
@@ -1104,3 +1108,3444 @@ const makeMessagesRecvSocket = (config) => {
1104
1108
  };
1105
1109
  };
1106
1110
  exports.makeMessagesRecvSocket = makeMessagesRecvSocket;
1111
+
1112
+ // Kage: compatibilidad de API.
1113
+ const __kageModule29 = (() => {
1114
+ const module = { exports: {} }; const exports = module.exports;
1115
+ "use strict"
1116
+
1117
+ Object.defineProperty(exports, "__esModule", { value: true })
1118
+
1119
+ const { default: NodeCache } = require("@cacheable/node-cache")
1120
+ const { Boom } = require("@hapi/boom")
1121
+ const { randomBytes } = require("crypto")
1122
+ const { proto } = require("../../WAProto")
1123
+ const {
1124
+ KEY_BUNDLE_TYPE,
1125
+ MIN_PREKEY_COUNT,
1126
+ DEFAULT_CACHE_TTLS
1127
+ } = require("../Defaults/constants")
1128
+ const {
1129
+ XWAPaths,
1130
+ XWAPathsMexUpdates,
1131
+ MexOperations,
1132
+ MexUpdatesOperations,
1133
+ WAMessageStubType,
1134
+ WAMessageStatus
1135
+ } = require("../Types")
1136
+ const {
1137
+ aesDecryptCTR,
1138
+ aesEncryptGCM,
1139
+ cleanMessage,
1140
+ Curve,
1141
+ decodeMediaRetryNode,
1142
+ decodeMessageNode,
1143
+ decryptMessageNode,
1144
+ delay,
1145
+ derivePairingCodeKey,
1146
+ encodeBigEndian,
1147
+ encodeSignedDeviceIdentity,
1148
+ extractAddressingContext,
1149
+ getCallStatusFromNode,
1150
+ getHistoryMsg,
1151
+ getNextPreKeys,
1152
+ getStatusFromReceiptType,
1153
+ hkdf,
1154
+ NO_MESSAGE_FOUND_ERROR_TEXT,
1155
+ MISSING_KEYS_ERROR_TEXT,
1156
+ NACK_REASONS,
1157
+ unixTimestampSeconds,
1158
+ xmppPreKey,
1159
+ xmppSignedPreKey,
1160
+ generateMessageID
1161
+ } = require("../Utils")
1162
+ const {
1163
+ areJidsSameUser,
1164
+ binaryNodeToString,
1165
+ getAllBinaryNodeChildren,
1166
+ getBinaryNodeChild,
1167
+ getBinaryNodeChildBuffer,
1168
+ getBinaryNodeChildren,
1169
+ getBinaryNodeChildString,
1170
+ isJidGroup,
1171
+ isJidNewsletter,
1172
+ isJidStatusBroadcast,
1173
+ isLidUser,
1174
+ isPnUser,
1175
+ jidDecode,
1176
+ jidNormalizedUser,
1177
+ S_WHATSAPP_NET
1178
+ } = require("../WABinary")
1179
+ const { extractGroupMetadata } = require("./groups")
1180
+ const { makeMutex } = require("../Utils/make-mutex")
1181
+ const { makeMessagesSocket } = require("./messages-send")
1182
+
1183
+ const makeMessagesRecvSocket = (config) => {
1184
+ const {
1185
+ logger,
1186
+ retryRequestDelayMs,
1187
+ maxMsgRetryCount,
1188
+ getMessage,
1189
+ shouldIgnoreJid,
1190
+ enableAutoSessionRecreation
1191
+ } = config
1192
+
1193
+ const suki = makeMessagesSocket(config)
1194
+
1195
+ const {
1196
+ ev,
1197
+ authState,
1198
+ ws,
1199
+ messageMutex,
1200
+ notificationMutex,
1201
+ receiptMutex,
1202
+ signalRepository,
1203
+ query,
1204
+ upsertMessage,
1205
+ resyncAppState,
1206
+ onUnexpectedError,
1207
+ assertSessions,
1208
+ sendNode,
1209
+ relayMessage,
1210
+ sendReceipt,
1211
+ uploadPreKeys,
1212
+ groupMetadata,
1213
+ getUSyncDevices,
1214
+ createParticipantNodes,
1215
+ messageRetryManager,
1216
+ sendPeerDataOperationMessage
1217
+ } = suki
1218
+
1219
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
1220
+ const retryMutex = makeMutex()
1221
+
1222
+ const msgRetryCache = config.msgRetryCounterCache || new NodeCache({
1223
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
1224
+ useClones: false
1225
+ })
1226
+
1227
+ const callOfferCache = config.callOfferCache || new NodeCache({
1228
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER,
1229
+ useClones: false
1230
+ })
1231
+
1232
+ const placeholderResendCache = config.placeholderResendCache || new NodeCache({
1233
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
1234
+ useClones: false
1235
+ })
1236
+
1237
+ // Debounce identity-change session refreshes per JID to avoid bursts
1238
+ const identityAssertDebounce = new NodeCache({
1239
+ stdTTL: 5,
1240
+ useClones: false
1241
+ })
1242
+
1243
+ let sendActiveReceipts = false
1244
+
1245
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
1246
+ if (!authState.creds.me?.id) {
1247
+ throw new Boom('Not authenticated')
1248
+ }
1249
+
1250
+ const pdoMessage = {
1251
+ historySyncOnDemandRequest: {
1252
+ chatJid: oldestMsgKey.remoteJid,
1253
+ oldestMsgFromMe: oldestMsgKey.fromMe,
1254
+ oldestMsgId: oldestMsgKey.id,
1255
+ oldestMsgTimestampMs: oldestMsgTimestamp,
1256
+ onDemandMsgCount: count
1257
+ },
1258
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
1259
+ }
1260
+
1261
+ return sendPeerDataOperationMessage(pdoMessage)
1262
+ }
1263
+
1264
+ const requestPlaceholderResend = async (messageKey) => {
1265
+ if (!authState.creds.me?.id) {
1266
+ throw new Boom('Not authenticated')
1267
+ }
1268
+
1269
+ if (await placeholderResendCache.get(messageKey?.id)) {
1270
+ logger.debug({ messageKey }, 'already requested resend')
1271
+ return
1272
+ }
1273
+
1274
+ else {
1275
+ await placeholderResendCache.set(messageKey?.id, true)
1276
+ }
1277
+
1278
+ await delay(5000)
1279
+
1280
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
1281
+ logger.debug({ messageKey }, 'message received while resend requested')
1282
+ return 'RESOLVED'
1283
+ }
1284
+
1285
+ const pdoMessage = {
1286
+ placeholderMessageResendRequest: [
1287
+ {
1288
+ messageKey
1289
+ }
1290
+ ],
1291
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
1292
+ }
1293
+
1294
+ setTimeout(async () => {
1295
+ if (await placeholderResendCache.get(messageKey?.id)) {
1296
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline')
1297
+ await placeholderResendCache.del(messageKey?.id)
1298
+ }
1299
+ }, 15000)
1300
+
1301
+ return sendPeerDataOperationMessage(pdoMessage)
1302
+ }
1303
+
1304
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
1305
+ const stanza = {
1306
+ tag: 'ack',
1307
+ attrs: {
1308
+ id: attrs.id,
1309
+ to: attrs.from,
1310
+ class: tag
1311
+ }
1312
+ }
1313
+
1314
+ if (!!errorCode) {
1315
+ stanza.attrs.error = errorCode.toString()
1316
+ }
1317
+
1318
+ if (!!attrs.participant) {
1319
+ stanza.attrs.participant = attrs.participant
1320
+ }
1321
+
1322
+ if (!!attrs.recipient) {
1323
+ stanza.attrs.recipient = attrs.recipient
1324
+ }
1325
+
1326
+ if (!!attrs.type && (tag !== 'message' || getBinaryNodeChild({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
1327
+ stanza.attrs.type = attrs.type
1328
+ }
1329
+
1330
+ if (tag === 'message' && getBinaryNodeChild({ tag, attrs, content }, 'unavailable')) {
1331
+ stanza.attrs.from = authState.creds.me.id
1332
+ }
1333
+
1334
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack')
1335
+ await sendNode(stanza)
1336
+ }
1337
+
1338
+ const offerCall = async (toJid, isVideo = false) => {
1339
+ const callId = randomBytes(16).toString('hex').toUpperCase().substring(0, 64)
1340
+ const offerContent = []
1341
+ offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '16000' }, content: undefined })
1342
+ offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '8000' }, content: undefined })
1343
+
1344
+ if (isVideo) {
1345
+ offerContent.push({
1346
+ tag: 'video',
1347
+ attrs: { enc: 'vp8', dec: 'vp8', orientation: '0', 'screen_width': '1920', 'screen_height': '1080', 'device_orientation': '0' },
1348
+ content: undefined
1349
+ })
1350
+ }
1351
+ offerContent.push({ tag: 'net', attrs: { medium: '3' }, content: undefined })
1352
+ offerContent.push({ tag: 'capability', attrs: { ver: '1' }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) })
1353
+ offerContent.push({ tag: 'encopt', attrs: { keygen: '2' }, content: undefined })
1354
+
1355
+ const encKey = randomBytes(32)
1356
+ const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => jidEncode(user, 's.whatsapp.net', device))
1357
+ await assertSessions(devices, true)
1358
+
1359
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
1360
+ call: {
1361
+ callKey: new Uint8Array(encKey)
1362
+ }
1363
+ }, { count: '0' })
1364
+ offerContent.push({ tag: 'destination', attrs: {}, content: destinations })
1365
+
1366
+ if (shouldIncludeDeviceIdentity) {
1367
+ offerContent.push({
1368
+ tag: 'device-identity',
1369
+ attrs: {},
1370
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
1371
+ })
1372
+ }
1373
+
1374
+ const stanza = ({
1375
+ tag: 'call',
1376
+ attrs: {
1377
+ id: generateMessageID(),
1378
+ to: toJid,
1379
+ },
1380
+ content: [{
1381
+ tag: 'offer',
1382
+ attrs: {
1383
+ 'call-id': callId,
1384
+ 'call-creator': authState.creds.me.id,
1385
+ },
1386
+ content: offerContent,
1387
+ }],
1388
+ })
1389
+
1390
+ await query(stanza)
1391
+
1392
+ return {
1393
+ id: callId,
1394
+ to: toJid
1395
+ }
1396
+ }
1397
+
1398
+ const rejectCall = async (callId, callFrom) => {
1399
+ const stanza = ({
1400
+ tag: 'call',
1401
+ attrs: {
1402
+ from: authState.creds.me.id,
1403
+ to: callFrom,
1404
+ },
1405
+ content: [{
1406
+ tag: 'reject',
1407
+ attrs: {
1408
+ 'call-id': callId,
1409
+ 'call-creator': callFrom,
1410
+ count: '0',
1411
+ },
1412
+ content: undefined,
1413
+ }],
1414
+ })
1415
+
1416
+ await query(stanza)
1417
+ }
1418
+
1419
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
1420
+ const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '')
1421
+ const { key: msgKey } = fullMessage
1422
+ const msgId = msgKey.id
1423
+
1424
+ if (messageRetryManager) {
1425
+ // Check if we've exceeded max retries using the new system
1426
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
1427
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing')
1428
+ messageRetryManager.markRetryFailed(msgId)
1429
+ return
1430
+ }
1431
+
1432
+ // Increment retry count using new system
1433
+ const retryCount = messageRetryManager.incrementRetryCount(msgId)
1434
+
1435
+ // Use the new retry count for the rest of the logic
1436
+ const key = `${msgId}:${msgKey?.participant}`
1437
+ await msgRetryCache.set(key, retryCount)
1438
+ }
1439
+
1440
+ else {
1441
+ // Fallback to old system
1442
+ const key = `${msgId}:${msgKey?.participant}`
1443
+
1444
+ let retryCount = (await msgRetryCache.get(key)) || 0
1445
+
1446
+ if (retryCount >= maxMsgRetryCount) {
1447
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing')
1448
+
1449
+ await msgRetryCache.del(key)
1450
+
1451
+ return
1452
+ }
1453
+
1454
+ retryCount += 1
1455
+
1456
+ await msgRetryCache.set(key, retryCount)
1457
+ }
1458
+
1459
+ const key = `${msgId}:${msgKey?.participant}`
1460
+ const retryCount = (await msgRetryCache.get(key)) || 1
1461
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
1462
+ const fromJid = node.attrs.from
1463
+
1464
+ // Check if we should recreate the session
1465
+ let shouldRecreateSession = false
1466
+ let recreateReason = ''
1467
+
1468
+ if (enableAutoSessionRecreation && messageRetryManager) {
1469
+ try {
1470
+ // Check if we have a session with this JID
1471
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid)
1472
+ const hasSession = await signalRepository.validateSession(fromJid)
1473
+ const result = messageRetryManager.shouldRecreateSession(fromJid, retryCount, hasSession.exists)
1474
+
1475
+ shouldRecreateSession = result.recreate
1476
+ recreateReason = result.reason
1477
+
1478
+ if (shouldRecreateSession) {
1479
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry')
1480
+
1481
+ // Delete existing session to force recreation
1482
+ await authState.keys.set({ session: { [sessionId]: null } })
1483
+
1484
+ forceIncludeKeys = true
1485
+ }
1486
+ }
1487
+
1488
+ catch (error) {
1489
+ logger.warn({ error, fromJid }, 'failed to check session recreation')
1490
+ }
1491
+ }
1492
+
1493
+ if (retryCount <= 2) {
1494
+ // Use new retry manager for phone requests if available
1495
+ if (messageRetryManager) {
1496
+ // Schedule phone request with delay (like whatsmeow)
1497
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
1498
+ try {
1499
+ const requestId = await requestPlaceholderResend(msgKey)
1500
+
1501
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`)
1502
+ }
1503
+
1504
+ catch (error) {
1505
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request')
1506
+ }
1507
+ })
1508
+ }
1509
+
1510
+ else {
1511
+ // Fallback to immediate request
1512
+ const msgId = await requestPlaceholderResend(msgKey)
1513
+
1514
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`)
1515
+ }
1516
+ }
1517
+
1518
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true)
1519
+
1520
+ await authState.keys.transaction(async () => {
1521
+ const receipt = {
1522
+ tag: 'receipt',
1523
+ attrs: {
1524
+ id: msgId,
1525
+ type: 'retry',
1526
+ to: node.attrs.from
1527
+ },
1528
+ content: [
1529
+ {
1530
+ tag: 'retry',
1531
+ attrs: {
1532
+ count: retryCount.toString(),
1533
+ id: node.attrs.id,
1534
+ t: node.attrs.t,
1535
+ v: '1',
1536
+ // ADD ERROR FIELD
1537
+ error: '0'
1538
+ }
1539
+ },
1540
+ {
1541
+ tag: 'registration',
1542
+ attrs: {},
1543
+ content: encodeBigEndian(authState.creds.registrationId)
1544
+ }
1545
+ ]
1546
+ }
1547
+
1548
+ if (node.attrs.recipient) {
1549
+ receipt.attrs.recipient = node.attrs.recipient
1550
+ }
1551
+
1552
+ if (node.attrs.participant) {
1553
+ receipt.attrs.participant = node.attrs.participant
1554
+ }
1555
+
1556
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
1557
+ const { update, preKeys } = await getNextPreKeys(authState, 1)
1558
+ const [keyId] = Object.keys(preKeys)
1559
+ const key = preKeys[+keyId]
1560
+ const content = receipt.content
1561
+
1562
+ content.push({
1563
+ tag: 'keys',
1564
+ attrs: {},
1565
+ content: [
1566
+ { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
1567
+ { tag: 'identity', attrs: {}, content: identityKey.public },
1568
+ xmppPreKey(key, +keyId),
1569
+ xmppSignedPreKey(signedPreKey),
1570
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
1571
+ ]
1572
+ })
1573
+
1574
+ ev.emit('creds.update', update)
1575
+ }
1576
+
1577
+ await sendNode(receipt)
1578
+
1579
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt')
1580
+ }, authState?.creds?.me?.id || 'sendRetryRequest')
1581
+ }
1582
+
1583
+ const handleEncryptNotification = async (node) => {
1584
+ const from = node.attrs.from
1585
+
1586
+ if (from === S_WHATSAPP_NET) {
1587
+ const countChild = getBinaryNodeChild(node, 'count')
1588
+ const count = +countChild.attrs.value
1589
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT
1590
+
1591
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count')
1592
+
1593
+ if (shouldUploadMorePreKeys) {
1594
+ await uploadPreKeys()
1595
+ }
1596
+ }
1597
+
1598
+ else {
1599
+ const identityNode = getBinaryNodeChild(node, 'identity')
1600
+
1601
+ if (identityNode) {
1602
+ logger.info({ jid: from }, 'identity changed')
1603
+
1604
+ if (identityAssertDebounce.get(from)) {
1605
+ logger.debug({ jid: from }, 'skipping identity assert (debounced)')
1606
+ return
1607
+ }
1608
+
1609
+ identityAssertDebounce.set(from, true)
1610
+
1611
+ try {
1612
+ await assertSessions([from], true)
1613
+ }
1614
+
1615
+ catch (error) {
1616
+ logger.warn({ error, jid: from }, 'failed to assert sessions after identity change')
1617
+ }
1618
+ }
1619
+
1620
+ else {
1621
+ logger.info({ node }, 'unknown encrypt notification')
1622
+ }
1623
+ }
1624
+ }
1625
+
1626
+ const handleGroupNotification = (fullNode, child, msg) => {
1627
+ // TODO: Support PN/LID (Here is only LID now)
1628
+ const actingParticipantLid = fullNode.attrs.participant
1629
+ const actingParticipantPn = fullNode.attrs.participant_pn
1630
+ const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid
1631
+ const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn
1632
+
1633
+ switch (child?.tag) {
1634
+ case 'create':
1635
+ const metadata = extractGroupMetadata(child)
1636
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE
1637
+ msg.messageStubParameters = [metadata.subject]
1638
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn }
1639
+
1640
+ ev.emit('chats.upsert', [
1641
+ {
1642
+ id: metadata.id,
1643
+ name: metadata.subject,
1644
+ conversationTimestamp: metadata.creation
1645
+ }
1646
+ ])
1647
+
1648
+ ev.emit('groups.upsert', [
1649
+ {
1650
+ ...metadata,
1651
+ author: actingParticipantLid,
1652
+ authorPn: actingParticipantPn
1653
+ }
1654
+ ])
1655
+ break
1656
+ case 'ephemeral':
1657
+ case 'not_ephemeral':
1658
+ msg.message = {
1659
+ protocolMessage: {
1660
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
1661
+ ephemeralExpiration: +(child.attrs.expiration || 0)
1662
+ }
1663
+ }
1664
+ break
1665
+ case 'modify':
1666
+ const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid)
1667
+ msg.messageStubParameters = oldNumber || []
1668
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER
1669
+ break
1670
+ case 'promote':
1671
+ case 'demote':
1672
+ case 'remove':
1673
+ case 'add':
1674
+ case 'leave':
1675
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`
1676
+ msg.messageStubType = WAMessageStubType[stubType]
1677
+ const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
1678
+ // TODO: Store LID MAPPINGS
1679
+ return {
1680
+ id: attrs.jid,
1681
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
1682
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
1683
+ admin: (attrs.type || null)
1684
+ }
1685
+ })
1686
+
1687
+ if (participants.length === 1 &&
1688
+ // if recv. "remove" message and sender removed themselves
1689
+ // mark as left
1690
+ (areJidsSameUser(participants[0].id, actingParticipantLid) ||
1691
+ areJidsSameUser(participants[0].id, actingParticipantPn)) &&
1692
+ child.tag === 'remove') {
1693
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE
1694
+ }
1695
+
1696
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a))
1697
+ break
1698
+ case 'subject':
1699
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT
1700
+ msg.messageStubParameters = [child.attrs.subject]
1701
+ break
1702
+ case 'description':
1703
+ const description = getBinaryNodeChild(child, 'body')?.content?.toString()
1704
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION
1705
+ msg.messageStubParameters = description ? [description] : undefined
1706
+ break
1707
+ case 'announcement':
1708
+ case 'not_announcement':
1709
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE
1710
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off']
1711
+ break
1712
+ case 'locked':
1713
+ case 'unlocked':
1714
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT
1715
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off']
1716
+ break
1717
+ case 'invite':
1718
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK
1719
+ msg.messageStubParameters = [child.attrs.code]
1720
+ break
1721
+ case 'member_add_mode':
1722
+ const addMode = child.content;
1723
+ if (addMode) {
1724
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE
1725
+ msg.messageStubParameters = [addMode.toString()]
1726
+ }
1727
+ break
1728
+ case 'membership_approval_mode':
1729
+ const approvalMode = getBinaryNodeChild(child, 'group_join')
1730
+ if (approvalMode) {
1731
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE
1732
+ msg.messageStubParameters = [approvalMode.attrs.state]
1733
+ }
1734
+ break
1735
+ case 'created_membership_requests':
1736
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
1737
+ msg.messageStubParameters = [
1738
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
1739
+ 'created',
1740
+ child.attrs.request_method
1741
+ ]
1742
+ break
1743
+ case 'revoked_membership_requests':
1744
+ const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid)
1745
+ // TODO: LIDMAPPING SUPPORT
1746
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
1747
+ msg.messageStubParameters = [
1748
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
1749
+ isDenied ? 'revoked' : 'rejected'
1750
+ ]
1751
+ break
1752
+ }
1753
+ }
1754
+
1755
+ const handleNewsletterNotification = (id, node) => {
1756
+ const messages = getBinaryNodeChild(node, 'messages')
1757
+ const message = getBinaryNodeChild(node, 'message')
1758
+ const serverId = node.attrs.server_id
1759
+
1760
+ const reactionsList = getBinaryNodeChild(node, 'reactions')
1761
+ const viewsList = getBinaryNodeChild(node, 'views_count')
1762
+
1763
+ if (reactionsList) {
1764
+ const reactions = getBinaryNodeChild(reactionsList, 'reaction')
1765
+
1766
+ if (reactions.length === 0) {
1767
+ ev.emit('newsletter.reaction', {
1768
+ id,
1769
+ newsletter_server_id: serverId,
1770
+ reaction: {
1771
+ removed: true
1772
+ }
1773
+ })
1774
+ }
1775
+
1776
+ reactions.forEach(item => {
1777
+ ev.emit('newsletter.reaction', {
1778
+ id,
1779
+ newsletter_server_id: serverId,
1780
+ reaction: {
1781
+ code: item.attrs?.code,
1782
+ count: +item.attrs.count
1783
+ }
1784
+ })
1785
+ })
1786
+ }
1787
+
1788
+ if (viewsList.length) {
1789
+ viewsList.forEach(item => {
1790
+ ev.emit('newsletter.view', {
1791
+ id,
1792
+ newsletter_server_id: serverId,
1793
+ count: +item.attrs.count
1794
+ })
1795
+ })
1796
+ }
1797
+ }
1798
+
1799
+ const handleMexNotification = (id, node) => {
1800
+ const operation = node?.attrs?.op_name
1801
+ const content = JSON.parse(node?.content)
1802
+
1803
+ let contentPath
1804
+ let action
1805
+
1806
+ if (operation === MexOperations.UPDATE) {
1807
+ contentPath = content.data[XWAPaths.METADATA_UPDATE]
1808
+
1809
+ ev.emit('newsletter-settings.update', {
1810
+ id,
1811
+ update: contentPath.thread_metadata.settings
1812
+ })
1813
+ } else if (operation === MexUpdatesOperations.GROUP_MEMBER_LINK) {
1814
+ contentPath = content.data[XWAPathsMexUpdates.GROUP_SHARING_CHANGE]
1815
+
1816
+ ev.emit('groups.update', [{
1817
+ id,
1818
+ author: contentPath.updated_by.id,
1819
+ member_link_mode: contentPath.properties.member_link_mode
1820
+ }])
1821
+ } else if (operation === MexUpdatesOperations.GROUP_LIMIT_SHARING) {
1822
+ contentPath = content.data[XWAPathsMexUpdates.GROUP_SHARING_CHANGE]
1823
+
1824
+ ev.emit('limit-sharing.update', {
1825
+ id,
1826
+ author: contentPath.updated_by?.pn ? contentPath.updated_by.pn : contentPath.updated_by.id,
1827
+ action: `${contentPath.properties.limit_sharing.limit_sharing_enabled ? 'on' : 'off'}`,
1828
+ trigger: contentPath.properties.limit_sharing.limit_sharing_trigger,
1829
+ update_time: contentPath.update_time
1830
+ })
1831
+ } else if (operation === MexUpdatesOperations.OWNER_COMMUNITY) {
1832
+ contentPath = content.data[XWAPathsMexUpdates.COMMUNITY_OWNER_CHANGE]
1833
+
1834
+ ev.emit('community-owner.update', {
1835
+ id,
1836
+ author: contentPath.updated_by?.pn ? contentPath.updated_by.pn : contentPath.updated_by.id,
1837
+ user: contentPath.role_updates[0].user?.pn ? contentPath.role_updates[0].user.pn : contentPath.role_updates[0].user.jid,
1838
+ new_role: contentPath.role_updates[0].new_role,
1839
+ update_time: contentPath.update_time
1840
+ })
1841
+ } else {
1842
+
1843
+ if (operation === MexOperations.PROMOTE) {
1844
+ action = 'promote'
1845
+ contentPath = content.data[XWAPaths.PROMOTE]
1846
+ } else {
1847
+ action = 'demote'
1848
+ contentPath = content.data[XWAPaths.DEMOTE]
1849
+ }
1850
+
1851
+ ev.emit('newsletter-participants.update', {
1852
+ id,
1853
+ author: contentPath.actor.pn,
1854
+ user: contentPath.user.pn,
1855
+ new_role: contentPath.user_new_role,
1856
+ action
1857
+ })
1858
+ }
1859
+ }
1860
+
1861
+ const processNotification = async (node) => {
1862
+ const result = {}
1863
+ const [child] = getAllBinaryNodeChildren(node)
1864
+ const nodeType = node.attrs.type
1865
+ const from = jidNormalizedUser(node.attrs.from)
1866
+
1867
+ switch (nodeType) {
1868
+ case 'w:gp2':
1869
+ // TODO: HANDLE PARTICIPANT_PN
1870
+ handleGroupNotification(node, child, result)
1871
+ break
1872
+ case 'newsletter':
1873
+ handleNewsletterNotification(node.attrs.from, child)
1874
+ break
1875
+ case 'mex':
1876
+ handleMexNotification(node.attrs.from, child, result)
1877
+ break
1878
+ case 'mediaretry':
1879
+ const event = decodeMediaRetryNode(node)
1880
+ ev.emit('messages.media-update', [event])
1881
+ break
1882
+ case 'encrypt':
1883
+ await handleEncryptNotification(node)
1884
+ break
1885
+ case 'devices':
1886
+ const devices = getBinaryNodeChildren(child, 'device')
1887
+ if (areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
1888
+ areJidsSameUser(child.attrs.lid, authState.creds.me.lid)) {
1889
+ const deviceData = devices.map(d => ({ id: d.attrs.jid, lid: d.attrs.lid }))
1890
+ logger.info({ deviceData }, 'my own devices changed')
1891
+ }
1892
+ //TODO: drop a new event, add hashes
1893
+ break
1894
+ case 'server_sync':
1895
+ const update = getBinaryNodeChild(node, 'collection')
1896
+ if (update) {
1897
+ const name = update.attrs.name
1898
+ await resyncAppState([name], false)
1899
+ }
1900
+ break
1901
+ case 'picture':
1902
+ const setPicture = getBinaryNodeChild(node, 'set')
1903
+ const delPicture = getBinaryNodeChild(node, 'delete')
1904
+
1905
+ ev.emit('contacts.update', [
1906
+ {
1907
+ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
1908
+ imgUrl: setPicture ? 'changed' : 'removed'
1909
+ }
1910
+ ])
1911
+
1912
+ if (isJidGroup(from)) {
1913
+ const node = setPicture || delPicture
1914
+
1915
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON
1916
+
1917
+ if (setPicture) {
1918
+ result.messageStubParameters = [setPicture.attrs.id]
1919
+ }
1920
+
1921
+ result.participant = node?.attrs.author
1922
+ result.key = {
1923
+ ...(result.key || {}),
1924
+ participant: setPicture?.attrs.author
1925
+ }
1926
+ }
1927
+ break
1928
+ case 'account_sync':
1929
+ if (child.tag === 'disappearing_mode') {
1930
+ const newDuration = +child.attrs.duration
1931
+ const timestamp = +child.attrs.t
1932
+ logger.info({ newDuration }, 'updated account disappearing mode')
1933
+ ev.emit('creds.update', {
1934
+ accountSettings: {
1935
+ ...authState.creds.accountSettings,
1936
+ defaultDisappearingMode: {
1937
+ ephemeralExpiration: newDuration,
1938
+ ephemeralSettingTimestamp: timestamp
1939
+ }
1940
+ }
1941
+ })
1942
+ }
1943
+
1944
+ else if (child.tag === 'blocklist') {
1945
+ const blocklists = getBinaryNodeChildren(child, 'item')
1946
+ for (const { attrs } of blocklists) {
1947
+ const blocklist = [attrs.jid]
1948
+ const type = attrs.action === 'block' ? 'add' : 'remove'
1949
+ ev.emit('blocklist.update', { blocklist, type })
1950
+ }
1951
+ }
1952
+ break
1953
+ case 'link_code_companion_reg':
1954
+ const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg')
1955
+ const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'))
1956
+ const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'))
1957
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'))
1958
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped)
1959
+ const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey)
1960
+ const random = randomBytes(32)
1961
+ const linkCodeSalt = randomBytes(32)
1962
+ const linkCodePairingExpanded = await hkdf(companionSharedKey, 32, {
1963
+ salt: linkCodeSalt,
1964
+ info: 'link_code_pairing_key_bundle_encryption_key'
1965
+ })
1966
+ const encryptPayload = Buffer.concat([
1967
+ Buffer.from(authState.creds.signedIdentityKey.public),
1968
+ primaryIdentityPublicKey,
1969
+ random
1970
+ ])
1971
+ const encryptIv = randomBytes(12)
1972
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0))
1973
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted])
1974
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey)
1975
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random])
1976
+
1977
+ authState.creds.advSecretKey = (await hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64')
1978
+
1979
+ await query({
1980
+ tag: 'iq',
1981
+ attrs: {
1982
+ to: S_WHATSAPP_NET,
1983
+ type: 'set',
1984
+ id: suki.generateMessageTag(),
1985
+ xmlns: 'md'
1986
+ },
1987
+ content: [
1988
+ {
1989
+ tag: 'link_code_companion_reg',
1990
+ attrs: {
1991
+ jid: authState.creds.me.id,
1992
+ stage: 'companion_finish'
1993
+ },
1994
+ content: [
1995
+ {
1996
+ tag: 'link_code_pairing_wrapped_key_bundle',
1997
+ attrs: {},
1998
+ content: encryptedPayload
1999
+ },
2000
+ {
2001
+ tag: 'companion_identity_public',
2002
+ attrs: {},
2003
+ content: authState.creds.signedIdentityKey.public
2004
+ },
2005
+ {
2006
+ tag: 'link_code_pairing_ref',
2007
+ attrs: {},
2008
+ content: ref
2009
+ }
2010
+ ]
2011
+ }
2012
+ ]
2013
+ })
2014
+
2015
+ authState.creds.registered = true
2016
+ ev.emit('creds.update', authState.creds)
2017
+ break
2018
+ case 'privacy_token':
2019
+ await handlePrivacyTokenNotification(node)
2020
+ break
2021
+ }
2022
+
2023
+ if (Object.keys(result).length) {
2024
+ return result
2025
+ }
2026
+ }
2027
+
2028
+ const handlePrivacyTokenNotification = async (node) => {
2029
+ const tokensNode = getBinaryNodeChild(node, 'tokens')
2030
+ const from = jidNormalizedUser(node.attrs.from)
2031
+
2032
+ if (!tokensNode) return
2033
+
2034
+ const tokenNodes = getBinaryNodeChildren(tokensNode, 'token')
2035
+
2036
+ for (const tokenNode of tokenNodes) {
2037
+ const { attrs, content } = tokenNode
2038
+ const type = attrs.type
2039
+ const timestamp = attrs.t
2040
+
2041
+ if (type === 'trusted_contact' && content instanceof Buffer) {
2042
+ logger.debug({
2043
+ from,
2044
+ timestamp,
2045
+ tcToken: content
2046
+ }, 'received trusted contact token')
2047
+
2048
+ await authState.keys.set({
2049
+ tctoken: { [from]: { token: content, timestamp } }
2050
+ })
2051
+ }
2052
+ }
2053
+ }
2054
+
2055
+ async function decipherLinkPublicKey(data) {
2056
+ const buffer = toRequiredBuffer(data)
2057
+ const salt = buffer.slice(0, 32)
2058
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt)
2059
+ const iv = buffer.slice(32, 48)
2060
+ const payload = buffer.slice(48, 80)
2061
+ return aesDecryptCTR(payload, secretKey, iv)
2062
+ }
2063
+
2064
+ function toRequiredBuffer(data) {
2065
+ if (data === undefined) {
2066
+ throw new Boom('Invalid buffer', { statusCode: 400 })
2067
+ }
2068
+ return data instanceof Buffer ? data : Buffer.from(data)
2069
+ }
2070
+
2071
+ const willSendMessageAgain = async (id, participant) => {
2072
+ const key = `${id}:${participant}`
2073
+ const retryCount = (await msgRetryCache.get(key)) || 0
2074
+ return retryCount < maxMsgRetryCount
2075
+ }
2076
+
2077
+ const updateSendMessageAgainCount = async (id, participant) => {
2078
+ const key = `${id}:${participant}`
2079
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1
2080
+ await msgRetryCache.set(key, newValue)
2081
+ }
2082
+
2083
+ const sendMessagesAgain = async (key, ids, retryNode) => {
2084
+ const remoteJid = key.remoteJid
2085
+ const participant = key.participant || remoteJid
2086
+ const retryCount = +retryNode.attrs.count || 1
2087
+
2088
+ // Try to get messages from cache first, then fallback to getMessage
2089
+ const msgs = []
2090
+
2091
+ for (const id of ids) {
2092
+ let msg
2093
+
2094
+ // Try to get from retry cache first if enabled
2095
+ if (messageRetryManager) {
2096
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id)
2097
+
2098
+ if (cachedMsg) {
2099
+ msg = cachedMsg.message
2100
+ logger.debug({ jid: remoteJid, id }, 'found message in retry cache')
2101
+
2102
+ // Mark retry as successful since we found the message
2103
+ messageRetryManager.markRetrySuccess(id)
2104
+ }
2105
+ }
2106
+
2107
+ // Fallback to getMessage if not found in cache
2108
+ if (!msg) {
2109
+ msg = await getMessage({ ...key, id })
2110
+
2111
+ if (msg) {
2112
+ logger.debug({ jid: remoteJid, id }, 'found message via getMessage')
2113
+
2114
+ // Also mark as successful if found via getMessage
2115
+ if (messageRetryManager) {
2116
+ messageRetryManager.markRetrySuccess(id)
2117
+ }
2118
+ }
2119
+ }
2120
+
2121
+ msgs.push(msg)
2122
+ }
2123
+
2124
+ // if it's the primary jid sending the request
2125
+ // just re-send the message to everyone
2126
+ // prevents the first message decryption failure
2127
+ const sendToAll = !jidDecode(participant)?.device
2128
+
2129
+ // Check if we should recreate session for this retry
2130
+ let shouldRecreateSession = false
2131
+ let recreateReason = ''
2132
+
2133
+ if (enableAutoSessionRecreation && messageRetryManager) {
2134
+ try {
2135
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant)
2136
+ const hasSession = await signalRepository.validateSession(participant)
2137
+ const result = messageRetryManager.shouldRecreateSession(participant, retryCount, hasSession.exists)
2138
+
2139
+ shouldRecreateSession = result.recreate
2140
+ recreateReason = result.reason
2141
+
2142
+ if (shouldRecreateSession) {
2143
+ logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry')
2144
+ await authState.keys.set({ session: { [sessionId]: null } })
2145
+ }
2146
+ }
2147
+
2148
+ catch (error) {
2149
+ logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry')
2150
+ }
2151
+ }
2152
+
2153
+ await assertSessions([participant], true)
2154
+
2155
+ if (isJidGroup(remoteJid)) {
2156
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } })
2157
+ }
2158
+
2159
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp')
2160
+
2161
+ for (const [i, msg] of msgs.entries()) {
2162
+ if (!ids[i]) continue
2163
+
2164
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
2165
+ await updateSendMessageAgainCount(ids[i], participant)
2166
+ const msgRelayOpts = { messageId: ids[i] }
2167
+
2168
+ if (sendToAll) {
2169
+ msgRelayOpts.useUserDevicesCache = false
2170
+ }
2171
+
2172
+ else {
2173
+ msgRelayOpts.participant = {
2174
+ jid: participant,
2175
+ count: +retryNode.attrs.count
2176
+ }
2177
+ }
2178
+
2179
+ await relayMessage(key.remoteJid, msg, msgRelayOpts)
2180
+ }
2181
+
2182
+ else {
2183
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available')
2184
+ }
2185
+ }
2186
+ }
2187
+
2188
+ const handleReceipt = async (node) => {
2189
+ const { attrs, content } = node
2190
+ const isLid = attrs.from.includes('lid')
2191
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id)
2192
+ const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient
2193
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe)
2194
+ const key = {
2195
+ remoteJid,
2196
+ id: '',
2197
+ fromMe,
2198
+ participant: attrs.participant
2199
+ }
2200
+
2201
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
2202
+ logger.debug({ remoteJid }, 'ignoring receipt from jid')
2203
+ await sendMessageAck(node)
2204
+ return
2205
+ }
2206
+
2207
+ const ids = [attrs.id]
2208
+
2209
+ if (Array.isArray(content)) {
2210
+ const items = getBinaryNodeChildren(content[0], 'item')
2211
+ ids.push(...items.map(i => i.attrs.id))
2212
+ }
2213
+
2214
+ try {
2215
+ await Promise.all([
2216
+ receiptMutex.mutex(async () => {
2217
+ const status = getStatusFromReceiptType(attrs.type)
2218
+
2219
+ if (typeof status !== 'undefined' &&
2220
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
2221
+ // or another device of ours has read some messages
2222
+ (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
2223
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
2224
+ if (attrs.participant) {
2225
+ const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp'
2226
+
2227
+ ev.emit('message-receipt.update', ids.map(id => ({
2228
+ key: { ...key, id },
2229
+ receipt: {
2230
+ userJid: jidNormalizedUser(attrs.participant),
2231
+ [updateKey]: +attrs.t
2232
+ }
2233
+ })))
2234
+ }
2235
+ }
2236
+
2237
+ else {
2238
+ ev.emit('messages.update', ids.map(id => ({
2239
+ key: { ...key, id },
2240
+ update: { status }
2241
+ })))
2242
+ }
2243
+ }
2244
+
2245
+ if (attrs.type === 'retry') {
2246
+ // correctly set who is asking for the retry
2247
+ key.participant = key.participant || attrs.from
2248
+
2249
+ const retryNode = getBinaryNodeChild(node, 'retry')
2250
+
2251
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
2252
+ if (key.fromMe) {
2253
+ try {
2254
+ await updateSendMessageAgainCount(ids[0], key.participant)
2255
+
2256
+ logger.debug({ attrs, key }, 'recv retry request')
2257
+
2258
+ await sendMessagesAgain(key, ids, retryNode)
2259
+ }
2260
+
2261
+ catch (error) {
2262
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again')
2263
+ }
2264
+ }
2265
+
2266
+ else {
2267
+ logger.info({ attrs, key }, 'recv retry for not fromMe message')
2268
+ }
2269
+ }
2270
+
2271
+ else {
2272
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times')
2273
+ }
2274
+ }
2275
+ })
2276
+ ])
2277
+ }
2278
+
2279
+ finally {
2280
+ await sendMessageAck(node)
2281
+ }
2282
+ }
2283
+
2284
+ const handleNotification = async (node) => {
2285
+ const remoteJid = node.attrs.from
2286
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
2287
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification')
2288
+ await sendMessageAck(node)
2289
+ return
2290
+ }
2291
+
2292
+ try {
2293
+ await Promise.all([
2294
+ notificationMutex.mutex(async () => {
2295
+ const msg = await processNotification(node)
2296
+
2297
+ if (msg) {
2298
+ const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id)
2299
+ const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node)
2300
+
2301
+ msg.key = {
2302
+ remoteJid,
2303
+ fromMe,
2304
+ participant: node.attrs.participant,
2305
+ participantAlt,
2306
+ addressingMode,
2307
+ id: node.attrs.id,
2308
+ ...(msg.key || {})
2309
+ }
2310
+
2311
+ msg.participant ?? (msg.participant = node.attrs.participant)
2312
+ msg.messageTimestamp = +node.attrs.t
2313
+
2314
+ const fullMsg = proto.WebMessageInfo.fromObject(msg)
2315
+
2316
+ await upsertMessage(fullMsg, 'append')
2317
+ }
2318
+ })
2319
+ ])
2320
+ }
2321
+
2322
+ finally {
2323
+ await sendMessageAck(node)
2324
+ }
2325
+ }
2326
+
2327
+ const handleMessage = async (node) => {
2328
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
2329
+ logger.debug({ key: node.attrs.key }, 'ignored message')
2330
+ await sendMessageAck(node, NACK_REASONS.UnhandledError)
2331
+ return
2332
+ }
2333
+
2334
+ const encNode = getBinaryNodeChild(node, 'enc')
2335
+
2336
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
2337
+ if (encNode && encNode.attrs.type === 'msmsg') {
2338
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg')
2339
+ await sendMessageAck(node, NACK_REASONS.MissingMessageSecret)
2340
+ return
2341
+ }
2342
+
2343
+ const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
2344
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
2345
+ // store new mappings we didn't have before
2346
+ if (!!alt) {
2347
+ const altServer = jidDecode(alt)?.server
2348
+ const primaryJid = msg.key.participant || msg.key.remoteJid
2349
+
2350
+ if (altServer === 'lid') {
2351
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
2352
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }])
2353
+ await signalRepository.migrateSession(primaryJid, alt)
2354
+ }
2355
+ }
2356
+
2357
+ else {
2358
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }])
2359
+ await signalRepository.migrateSession(alt, primaryJid)
2360
+ }
2361
+ }
2362
+
2363
+ if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
2364
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message)
2365
+ logger.debug({
2366
+ jid: msg.key.remoteJid,
2367
+ id: msg.key.id
2368
+ }, 'Added message to recent cache for retry receipts')
2369
+ }
2370
+
2371
+ try {
2372
+ await messageMutex.mutex(async () => {
2373
+ await decrypt()
2374
+
2375
+ // message failed to decrypt
2376
+ if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
2377
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT ||
2378
+ msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
2379
+ return sendMessageAck(node)
2380
+ }
2381
+
2382
+ const errorMessage = msg?.messageStubParameters?.[0] || ''
2383
+ const isPreKeyError = errorMessage.includes('PreKey')
2384
+
2385
+ logger.debug(`[handleMessage] Attempting retry request for failed decryption`)
2386
+
2387
+ // Handle both pre-key and normal retries in single mutex
2388
+ await retryMutex.mutex(async () => {
2389
+ try {
2390
+ if (!ws.isOpen) {
2391
+ logger.debug({ node }, 'Connection closed, skipping retry')
2392
+ return
2393
+ }
2394
+
2395
+ // Handle pre-key errors with upload and delay
2396
+ if (isPreKeyError) {
2397
+ logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying')
2398
+
2399
+ try {
2400
+ logger.debug('Uploading pre-keys for error recovery')
2401
+ await uploadPreKeys(5)
2402
+ logger.debug('Waiting for server to process new pre-keys')
2403
+ await delay(1000)
2404
+ }
2405
+
2406
+ catch (uploadErr) {
2407
+ logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway')
2408
+ }
2409
+ }
2410
+
2411
+ const encNode = getBinaryNodeChild(node, 'enc')
2412
+
2413
+ await sendRetryRequest(node, !encNode)
2414
+
2415
+ if (retryRequestDelayMs) {
2416
+ await delay(retryRequestDelayMs)
2417
+ }
2418
+ }
2419
+
2420
+ catch (err) {
2421
+ logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry')
2422
+
2423
+ // Still attempt retry even if pre-key upload failed
2424
+ try {
2425
+ const encNode = getBinaryNodeChild(node, 'enc')
2426
+
2427
+ await sendRetryRequest(node, !encNode)
2428
+ }
2429
+
2430
+ catch (retryErr) {
2431
+ logger.error({ retryErr }, 'Failed to send retry after error handling')
2432
+ }
2433
+ }
2434
+
2435
+ await sendMessageAck(node, NACK_REASONS.UnhandledError)
2436
+ })
2437
+ }
2438
+
2439
+ else {
2440
+ if (messageRetryManager && msg.key.id) {
2441
+ messageRetryManager.cancelPendingPhoneRequest(msg.key.id)
2442
+ }
2443
+
2444
+ const isNewsletter = isJidNewsletter(msg.key.remoteJid)
2445
+
2446
+ if (!isNewsletter) {
2447
+ // no type in the receipt => message delivered
2448
+ let type = undefined
2449
+ let participant = msg.key.participant
2450
+
2451
+ if (category === 'peer') {
2452
+ // special peer message
2453
+ type = 'peer_msg'
2454
+ }
2455
+
2456
+ else if (msg.key.fromMe) {
2457
+ // message was sent by us from a different device
2458
+ type = 'sender'
2459
+
2460
+ // need to specially handle this case
2461
+ if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
2462
+ participant = author // TODO: investigate sending receipts to LIDs and not PNs
2463
+ }
2464
+ }
2465
+
2466
+ else if (!sendActiveReceipts) {
2467
+ type = 'inactive'
2468
+ }
2469
+
2470
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type)
2471
+
2472
+ // send ack for history message
2473
+ const isAnyHistoryMsg = getHistoryMsg(msg.message)
2474
+
2475
+ if (isAnyHistoryMsg) {
2476
+ const jid = jidNormalizedUser(msg.key.remoteJid)
2477
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync') // TODO: investigate
2478
+ }
2479
+ }
2480
+
2481
+ else {
2482
+ await sendMessageAck(node)
2483
+ logger.debug({ key: msg.key }, 'processed newsletter message without receipts')
2484
+ }
2485
+ }
2486
+
2487
+ cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid)
2488
+
2489
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify')
2490
+ })
2491
+ }
2492
+
2493
+ catch (error) {
2494
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message')
2495
+ }
2496
+ }
2497
+
2498
+ const handleCall = async (node) => {
2499
+ const { attrs } = node
2500
+ const [infoChild] = getAllBinaryNodeChildren(node)
2501
+ const status = getCallStatusFromNode(infoChild)
2502
+
2503
+ if (!infoChild) {
2504
+ throw new Boom('Missing call info in call node')
2505
+ }
2506
+
2507
+ const callId = infoChild.attrs['call-id']
2508
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator']
2509
+ const call = {
2510
+ chatId: attrs.from,
2511
+ from,
2512
+ id: callId,
2513
+ date: new Date(+attrs.t * 1000),
2514
+ offline: !!attrs.offline,
2515
+ status
2516
+ }
2517
+
2518
+ if (status === 'offer') {
2519
+ call.isVideo = !!getBinaryNodeChild(infoChild, 'video')
2520
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid']
2521
+ call.groupJid = infoChild.attrs['group-jid']
2522
+
2523
+ await callOfferCache.set(call.id, call)
2524
+ }
2525
+
2526
+ const existingCall = await callOfferCache.get(call.id)
2527
+
2528
+ // use existing call info to populate this event
2529
+ if (existingCall) {
2530
+ call.isVideo = existingCall.isVideo
2531
+ call.isGroup = existingCall.isGroup
2532
+ }
2533
+
2534
+ // delete data once call has ended
2535
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
2536
+ await callOfferCache.del(call.id)
2537
+ }
2538
+
2539
+ ev.emit('call', [call])
2540
+
2541
+ await sendMessageAck(node)
2542
+ }
2543
+
2544
+ const handleBadAck = async ({ attrs }) => {
2545
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id }
2546
+
2547
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
2548
+ // // current hypothesis is that if pash is sent in the ack
2549
+ // // it means -- the message hasn't reached all devices yet
2550
+ // // we'll retry sending the message here
2551
+ // if(attrs.phash) {
2552
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
2553
+ // const msg = await getMessage(key)
2554
+ // if(msg) {
2555
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
2556
+ // } else {
2557
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
2558
+ // }
2559
+ // }
2560
+ // error in acknowledgement,
2561
+ // device could not display the message
2562
+ if (attrs.error) {
2563
+ logger.warn({ attrs }, 'received error in ack')
2564
+ ev.emit('messages.update', [
2565
+ {
2566
+ key,
2567
+ update: {
2568
+ status: WAMessageStatus.ERROR,
2569
+ messageStubParameters: [attrs.error]
2570
+ }
2571
+ }
2572
+ ])
2573
+
2574
+ // resend the message with device_fanout=false, use at your own risk
2575
+ // if (attrs.error === '475') {
2576
+ // const msg = await getMessage(key)
2577
+ // if (msg) {
2578
+ // await relayMessage(key.remoteJid!, msg, {
2579
+ // messageId: key.id!,
2580
+ // useUserDevicesCache: false,
2581
+ // additionalAttributes: {
2582
+ // device_fanout: 'false'
2583
+ // }
2584
+ // })
2585
+ // }
2586
+ // }
2587
+ }
2588
+ }
2589
+
2590
+ /// processes a node with the given function
2591
+ /// and adds the task to the existing buffer if we're buffering events
2592
+ const processNodeWithBuffer = async (node, identifier, exec) => {
2593
+ ev.buffer()
2594
+ await execTask()
2595
+ ev.flush()
2596
+
2597
+ function execTask() {
2598
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier))
2599
+ }
2600
+ }
2601
+
2602
+ /** Yields control to the event loop to prevent blocking */
2603
+ const yieldToEventLoop = () => {
2604
+ return new Promise(resolve => setImmediate(resolve))
2605
+ }
2606
+
2607
+ const makeOfflineNodeProcessor = () => {
2608
+ const nodeProcessorMap = new Map([
2609
+ ['message', handleMessage],
2610
+ ['call', handleCall],
2611
+ ['receipt', handleReceipt],
2612
+ ['notification', handleNotification]
2613
+ ])
2614
+
2615
+ const nodes = []
2616
+
2617
+ let isProcessing = false
2618
+
2619
+ // Number of nodes to process before yielding to event loop
2620
+ const BATCH_SIZE = 10
2621
+
2622
+ const enqueue = (type, node) => {
2623
+ nodes.push({ type, node })
2624
+
2625
+ if (isProcessing) {
2626
+ return
2627
+ }
2628
+
2629
+ isProcessing = true
2630
+
2631
+ const promise = async () => {
2632
+ let processedInBatch = 0
2633
+
2634
+ while (nodes.length && ws.isOpen) {
2635
+ const { type, node } = nodes.shift()
2636
+ const nodeProcessor = nodeProcessorMap.get(type)
2637
+
2638
+ if (!nodeProcessor) {
2639
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node')
2640
+ continue
2641
+ }
2642
+
2643
+ await nodeProcessor(node)
2644
+
2645
+ processedInBatch++
2646
+
2647
+ // Yield to event loop after processing a batch
2648
+ // This prevents blocking the event loop for too long when there are many offline nodes
2649
+ if (processedInBatch >= BATCH_SIZE) {
2650
+ processedInBatch = 0
2651
+ await yieldToEventLoop()
2652
+ }
2653
+ }
2654
+
2655
+ isProcessing = false
2656
+ }
2657
+
2658
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'))
2659
+ }
2660
+
2661
+ return { enqueue }
2662
+ }
2663
+
2664
+ const offlineNodeProcessor = makeOfflineNodeProcessor()
2665
+
2666
+ const processNode = async (type, node, identifier, exec) => {
2667
+ const isOffline = !!node.attrs.offline
2668
+
2669
+ if (isOffline) {
2670
+ offlineNodeProcessor.enqueue(type, node)
2671
+ }
2672
+
2673
+ else {
2674
+ await processNodeWithBuffer(node, identifier, exec)
2675
+ }
2676
+ }
2677
+
2678
+ // recv a message
2679
+ ws.on('CB:message', async (node) => {
2680
+ await processNode('message', node, 'processing message', handleMessage)
2681
+ })
2682
+
2683
+ ws.on('CB:call', async (node) => {
2684
+ await processNode('call', node, 'handling call', handleCall)
2685
+ })
2686
+
2687
+ ws.on('CB:receipt', async (node) => {
2688
+ await processNode('receipt', node, 'handling receipt', handleReceipt)
2689
+ })
2690
+
2691
+ ws.on('CB:notification', async (node) => {
2692
+ await processNode('notification', node, 'handling notification', handleNotification)
2693
+ })
2694
+
2695
+ ws.on('CB:ack,class:message', (node) => {
2696
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'))
2697
+ })
2698
+
2699
+ ev.on('call', async ([call]) => {
2700
+ if (!call) {
2701
+ return;
2702
+ }
2703
+
2704
+ // missed call + group call notification message generation
2705
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
2706
+ const msg = {
2707
+ key: {
2708
+ remoteJid: call.chatId,
2709
+ id: call.id,
2710
+ fromMe: false
2711
+ },
2712
+ messageTimestamp: unixTimestampSeconds(call.date)
2713
+ }
2714
+
2715
+ if (call.status === 'timeout') {
2716
+ if (call.isGroup) {
2717
+ msg.messageStubType = call.isVideo
2718
+ ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
2719
+ : WAMessageStubType.CALL_MISSED_GROUP_VOICE
2720
+ }
2721
+
2722
+ else {
2723
+ msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE
2724
+ }
2725
+ }
2726
+
2727
+ else {
2728
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
2729
+ }
2730
+
2731
+ const protoMsg = proto.WebMessageInfo.fromObject(msg)
2732
+
2733
+ await upsertMessage(protoMsg, call.offline ? 'append' : 'notify')
2734
+ }
2735
+ })
2736
+
2737
+ ev.on('connection.update', ({ isOnline }) => {
2738
+ if (typeof isOnline !== 'undefined') {
2739
+ sendActiveReceipts = isOnline
2740
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`)
2741
+ }
2742
+ })
2743
+
2744
+ return {
2745
+ ...suki,
2746
+ sendMessageAck,
2747
+ sendRetryRequest,
2748
+ offerCall,
2749
+ rejectCall,
2750
+ fetchMessageHistory,
2751
+ requestPlaceholderResend,
2752
+ messageRetryManager
2753
+ }
2754
+ }
2755
+
2756
+ module.exports = {
2757
+ makeMessagesRecvSocket
2758
+ }
2759
+ return module.exports;
2760
+ })();
2761
+ for (const key of Object.keys(__kageModule29)) {
2762
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule29[key]});
2763
+ }
2764
+
2765
+ // Kage: funciones avanzadas.
2766
+ const __kageModule135 = (() => {
2767
+ const module = { exports: {} }; const exports = module.exports;
2768
+ "use strict";
2769
+ Object.defineProperty(exports, "__esModule", { value: true });
2770
+ exports.makeMessagesRecvSocket = void 0;
2771
+ const node_crypto_1 = require("node:crypto");
2772
+ const index_js_1 = require("../../WAProto/index.js");
2773
+ const index_js_2 = require("../Addon/index.js");
2774
+ const index_js_3 = require("../Defaults/index.js");
2775
+ const index_js_4 = require("../Types/index.js");
2776
+ const index_js_5 = require("../Utils/index.js");
2777
+ const make_mutex_js_1 = require("../Utils/make-mutex.js");
2778
+ const offline_node_processor_js_1 = require("../Utils/offline-node-processor.js");
2779
+ const stanza_ack_js_1 = require("../Utils/stanza-ack.js");
2780
+ const tc_token_utils_js_1 = require("../Utils/tc-token-utils.js");
2781
+ const index_js_6 = require("../WABinary/index.js");
2782
+ const groups_js_1 = require("./groups.js");
2783
+ const messages_send_js_1 = require("./messages-send.js");
2784
+ const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(index_js_4.ReachoutTimelockEnforcementType));
2785
+ function isValidEnforcementType(value) {
2786
+ return typeof value === 'string' && ENFORCEMENT_TYPE_VALUES.has(value);
2787
+ }
2788
+ const makeMessagesRecvSocket = (config) => {
2789
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
2790
+ const sock = (0, messages_send_js_1.makeMessagesSocket)(config);
2791
+ 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;
2792
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
2793
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
2794
+ const retryMutex = (0, make_mutex_js_1.makeMutex)();
2795
+ const msgRetryCache = config.msgRetryCounterCache ||
2796
+ (0, index_js_2.createCache)({
2797
+ ttl: index_js_3.DEFAULT_CACHE_TTLS.MSG_RETRY // 1 hour
2798
+ });
2799
+ const callOfferCache = config.callOfferCache ||
2800
+ (0, index_js_2.createCache)({
2801
+ ttl: index_js_3.DEFAULT_CACHE_TTLS.CALL_OFFER // 5 mins
2802
+ });
2803
+ // Debounce identity-change session refreshes per JID to avoid bursts
2804
+ const identityAssertDebounce = (0, index_js_2.createCache)({ ttl: 5 });
2805
+ let sendActiveReceipts = false;
2806
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
2807
+ if (!authState.creds.me?.id) {
2808
+ throw new index_js_2.HttpError('Not authenticated');
2809
+ }
2810
+ const pdoMessage = {
2811
+ historySyncOnDemandRequest: {
2812
+ chatJid: oldestMsgKey.remoteJid,
2813
+ oldestMsgFromMe: oldestMsgKey.fromMe,
2814
+ oldestMsgId: oldestMsgKey.id,
2815
+ oldestMsgTimestampMs: oldestMsgTimestamp,
2816
+ onDemandMsgCount: count
2817
+ },
2818
+ peerDataOperationRequestType: index_js_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
2819
+ };
2820
+ return sendPeerDataOperationMessage(pdoMessage);
2821
+ };
2822
+ const requestPlaceholderResend = async (messageKey, msgData) => {
2823
+ if (!authState.creds.me?.id) {
2824
+ throw new index_js_2.HttpError('Not authenticated');
2825
+ }
2826
+ if (await placeholderResendCache.get(messageKey?.id)) {
2827
+ logger.debug({ messageKey }, 'already requested resend');
2828
+ return;
2829
+ }
2830
+ else {
2831
+ // Store original message data so PDO response handler can preserve
2832
+ // metadata (LID details, timestamps, etc.) that the phone may omit
2833
+ await placeholderResendCache.set(messageKey?.id, msgData || true);
2834
+ }
2835
+ await (0, index_js_5.delay)(2000);
2836
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
2837
+ logger.debug({ messageKey }, 'message received while resend requested');
2838
+ return 'RESOLVED';
2839
+ }
2840
+ const pdoMessage = {
2841
+ placeholderMessageResendRequest: [
2842
+ {
2843
+ messageKey
2844
+ }
2845
+ ],
2846
+ peerDataOperationRequestType: index_js_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
2847
+ };
2848
+ setTimeout(async () => {
2849
+ if (await placeholderResendCache.get(messageKey?.id)) {
2850
+ logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline');
2851
+ await placeholderResendCache.del(messageKey?.id);
2852
+ }
2853
+ }, 8000);
2854
+ return sendPeerDataOperationMessage(pdoMessage);
2855
+ };
2856
+ const handleMexNotification = async (node) => {
2857
+ const updateNode = (0, index_js_6.getBinaryNodeChild)(node, 'update');
2858
+ if (updateNode) {
2859
+ const opName = updateNode.attrs?.op_name;
2860
+ if (!opName) {
2861
+ logger.warn({ node: (0, index_js_6.binaryNodeToString)(node) }, 'mex notification missing op_name, fallback to legacy');
2862
+ await handleLegacyMexNewsletterNotification(node);
2863
+ return;
2864
+ }
2865
+ let mexResponse;
2866
+ try {
2867
+ mexResponse = JSON.parse(updateNode.content.toString());
2868
+ }
2869
+ catch (error) {
2870
+ logger.error({ err: error, opName }, 'failed to parse mex notification JSON');
2871
+ return;
2872
+ }
2873
+ if (mexResponse.errors?.length) {
2874
+ logger.warn({ errors: mexResponse.errors, opName }, 'mex notification has GQL errors');
2875
+ return;
2876
+ }
2877
+ const data = mexResponse.data;
2878
+ if (!data) {
2879
+ logger.warn({ opName }, 'mex notification has null data');
2880
+ return;
2881
+ }
2882
+ logger.debug({ opName }, 'processing mex notification');
2883
+ switch (opName) {
2884
+ case 'NotificationUserReachoutTimelockUpdate':
2885
+ handleReachoutTimelockNotification(data);
2886
+ break;
2887
+ case 'MessageCappingInfoNotification':
2888
+ handleMessageCappingNotification(data);
2889
+ break;
2890
+ // newsletter ops still use the legacy <mex> child structure
2891
+ case 'NotificationNewsletterUpdate':
2892
+ case 'NotificationLinkedProfilesUpdates':
2893
+ case 'NotificationNewsletterAdminPromote':
2894
+ case 'NotificationNewsletterAdminDemote':
2895
+ case 'NotificationNewsletterUserSettingChange':
2896
+ case 'NotificationNewsletterJoin':
2897
+ case 'NotificationNewsletterLeave':
2898
+ case 'NotificationNewsletterStateChange':
2899
+ case 'NotificationNewsletterAdminMetadataUpdate':
2900
+ case 'NotificationNewsletterOwnerUpdate':
2901
+ case 'NotificationNewsletterAdminInviteRevoke':
2902
+ case 'NotificationNewsletterWamoSubStatusChange':
2903
+ case 'NotificationNewsletterBlockUser':
2904
+ case 'NotificationNewsletterPaidPartnership':
2905
+ case 'NotificationNewsletterMilestone':
2906
+ case 'NewsletterResponseStateUpdate':
2907
+ await handleLegacyMexNewsletterNotification(node);
2908
+ break;
2909
+ default:
2910
+ logger.debug({ opName }, 'unhandled mex notification');
2911
+ break;
2912
+ }
2913
+ return;
2914
+ }
2915
+ await handleLegacyMexNewsletterNotification(node);
2916
+ };
2917
+ const handleReachoutTimelockNotification = (data) => {
2918
+ const payload = data.xwa2_notify_account_reachout_timelock;
2919
+ if (!payload) {
2920
+ logger.warn('reachout timelock notification missing payload');
2921
+ return;
2922
+ }
2923
+ if (!payload.is_active) {
2924
+ logger.info('reachout timelock restriction lifted');
2925
+ ev.emit('connection.update', {
2926
+ reachoutTimeLock: {
2927
+ isActive: false,
2928
+ enforcementType: index_js_4.ReachoutTimelockEnforcementType.DEFAULT
2929
+ }
2930
+ });
2931
+ return;
2932
+ }
2933
+ // WA Web defaults to now+60s when the server omits the expiry
2934
+ const timeEnforcementEnds = payload.time_enforcement_ends
2935
+ ? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000)
2936
+ : new Date(Date.now() + 60000);
2937
+ const enforcementType = isValidEnforcementType(payload.enforcement_type)
2938
+ ? payload.enforcement_type
2939
+ : index_js_4.ReachoutTimelockEnforcementType.DEFAULT;
2940
+ logger.info({ enforcementType, timeEnforcementEnds }, 'reachout timelock restriction set');
2941
+ ev.emit('connection.update', {
2942
+ reachoutTimeLock: {
2943
+ isActive: true,
2944
+ timeEnforcementEnds,
2945
+ enforcementType
2946
+ }
2947
+ });
2948
+ };
2949
+ const handleMessageCappingNotification = (data) => {
2950
+ const payload = data.xwa2_notify_new_chat_messages_capping_info_update;
2951
+ if (!payload) {
2952
+ logger.warn('message capping notification missing payload');
2953
+ return;
2954
+ }
2955
+ logger.info({ payload }, 'received message capping update');
2956
+ ev.emit('message-capping.update', payload);
2957
+ };
2958
+ const handleLegacyMexNewsletterNotification = async (node) => {
2959
+ const mexNode = (0, index_js_6.getBinaryNodeChild)(node, 'mex');
2960
+ const updateNode = mexNode?.content ? null : (0, index_js_6.getBinaryNodeChild)(node, 'update') || (0, index_js_6.getAllBinaryNodeChildren)(node)[0];
2961
+ const payloadNode = mexNode?.content ? mexNode : updateNode;
2962
+ if (!payloadNode?.content) {
2963
+ logger.warn({ node: (0, index_js_6.binaryNodeToString)(node) }, 'invalid mex newsletter notification');
2964
+ return;
2965
+ }
2966
+ let data;
2967
+ try {
2968
+ const payloadContent = payloadNode.content;
2969
+ if (Array.isArray(payloadContent)) {
2970
+ logger.warn({ payloadNode }, 'invalid mex newsletter notification payload format');
2971
+ return;
2972
+ }
2973
+ const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent);
2974
+ data = JSON.parse(contentBuf.toString());
2975
+ }
2976
+ catch (error) {
2977
+ logger.error({ err: error, node: (0, index_js_6.binaryNodeToString)(node) }, 'failed to parse mex newsletter notification');
2978
+ return;
2979
+ }
2980
+ const operation = data?.operation ?? payloadNode?.attrs?.op_name;
2981
+ let updates = data?.updates;
2982
+ if (!updates) {
2983
+ const linkedProfiles = data?.data?.xwa2_notify_linked_profiles;
2984
+ if (linkedProfiles) {
2985
+ updates = [linkedProfiles];
2986
+ }
2987
+ }
2988
+ if (!updates || !operation) {
2989
+ logger.warn({ data }, 'invalid mex newsletter notification content');
2990
+ return;
2991
+ }
2992
+ logger.info({ operation, updates }, 'got mex newsletter notification');
2993
+ switch (operation) {
2994
+ case 'NotificationNewsletterUpdate':
2995
+ for (const update of updates) {
2996
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
2997
+ ev.emit('newsletter-settings.update', {
2998
+ id: update.jid,
2999
+ update: update.settings
3000
+ });
3001
+ }
3002
+ }
3003
+ break;
3004
+ case 'NotificationNewsletterAdminPromote':
3005
+ for (const update of updates) {
3006
+ if (update.jid && update.user) {
3007
+ ev.emit('newsletter-participants.update', {
3008
+ id: update.jid,
3009
+ author: node.attrs.from,
3010
+ user: update.user,
3011
+ new_role: 'ADMIN',
3012
+ action: 'promote'
3013
+ });
3014
+ }
3015
+ }
3016
+ break;
3017
+ case 'NotificationLinkedProfilesUpdates':
3018
+ for (const update of updates) {
3019
+ const lid = update?.jid;
3020
+ const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : [];
3021
+ const mappings = [];
3022
+ for (const profile of addedProfiles) {
3023
+ const pn = typeof profile === 'string' ? profile : (profile?.pn ?? profile?.jid ?? null);
3024
+ if (lid && pn) {
3025
+ const mapping = { lid, pn };
3026
+ ev.emit('lid-mapping.update', mapping);
3027
+ mappings.push(mapping);
3028
+ }
3029
+ }
3030
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
3031
+ }
3032
+ break;
3033
+ default:
3034
+ logger.info({ operation, data }, 'unhandled mex newsletter notification');
3035
+ break;
3036
+ }
3037
+ };
3038
+ // Handles newsletter notifications
3039
+ const handleNewsletterNotification = async (node) => {
3040
+ const from = node.attrs.from;
3041
+ const children = (0, index_js_6.getAllBinaryNodeChildren)(node);
3042
+ const author = node.attrs.participant;
3043
+ for (const child of children) {
3044
+ logger.debug({ from, child }, 'got newsletter notification');
3045
+ switch (child.tag) {
3046
+ case 'reaction': {
3047
+ const reactionUpdate = {
3048
+ id: from,
3049
+ server_id: child.attrs.message_id,
3050
+ reaction: {
3051
+ code: (0, index_js_6.getBinaryNodeChildString)(child, 'reaction'),
3052
+ count: 1
3053
+ }
3054
+ };
3055
+ ev.emit('newsletter.reaction', reactionUpdate);
3056
+ break;
3057
+ }
3058
+ case 'view': {
3059
+ const viewUpdate = {
3060
+ id: from,
3061
+ server_id: child.attrs.message_id,
3062
+ count: parseInt(child.content?.toString() || '0', 10)
3063
+ };
3064
+ ev.emit('newsletter.view', viewUpdate);
3065
+ break;
3066
+ }
3067
+ case 'participant': {
3068
+ const participantUpdate = {
3069
+ id: from,
3070
+ author,
3071
+ user: child.attrs.jid,
3072
+ action: child.attrs.action,
3073
+ new_role: child.attrs.role
3074
+ };
3075
+ ev.emit('newsletter-participants.update', participantUpdate);
3076
+ break;
3077
+ }
3078
+ case 'update': {
3079
+ const settingsNode = (0, index_js_6.getBinaryNodeChild)(child, 'settings');
3080
+ if (settingsNode) {
3081
+ const update = {};
3082
+ const nameNode = (0, index_js_6.getBinaryNodeChild)(settingsNode, 'name');
3083
+ if (nameNode?.content)
3084
+ update.name = nameNode.content.toString();
3085
+ const descriptionNode = (0, index_js_6.getBinaryNodeChild)(settingsNode, 'description');
3086
+ if (descriptionNode?.content)
3087
+ update.description = descriptionNode.content.toString();
3088
+ ev.emit('newsletter-settings.update', {
3089
+ id: from,
3090
+ update
3091
+ });
3092
+ }
3093
+ break;
3094
+ }
3095
+ case 'message': {
3096
+ const plaintextNode = (0, index_js_6.getBinaryNodeChild)(child, 'plaintext');
3097
+ if (plaintextNode?.content) {
3098
+ try {
3099
+ const contentBuf = typeof plaintextNode.content === 'string'
3100
+ ? Buffer.from(plaintextNode.content, 'binary')
3101
+ : Buffer.from(plaintextNode.content);
3102
+ const messageProto = index_js_1.proto.Message.decode(contentBuf).toJSON();
3103
+ const fullMessage = index_js_1.proto.WebMessageInfo.fromObject({
3104
+ key: {
3105
+ remoteJid: from,
3106
+ id: child.attrs.message_id || child.attrs.server_id,
3107
+ fromMe: false // TODO: is this really true though
3108
+ },
3109
+ message: messageProto,
3110
+ messageTimestamp: +child.attrs.t
3111
+ }).toJSON();
3112
+ await upsertMessage(fullMessage, 'append');
3113
+ logger.debug('Processed plaintext newsletter message');
3114
+ }
3115
+ catch (error) {
3116
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
3117
+ }
3118
+ }
3119
+ break;
3120
+ }
3121
+ default:
3122
+ logger.warn({ node, child }, 'Unknown newsletter notification child');
3123
+ break;
3124
+ }
3125
+ }
3126
+ };
3127
+ const sendMessageAck = async (node, errorCode) => {
3128
+ const stanza = (0, stanza_ack_js_1.buildAckStanza)(node, errorCode, authState.creds.me.id);
3129
+ logger.debug({ recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs }, 'sent ack');
3130
+ await sendNode(stanza);
3131
+ };
3132
+ const rejectCall = async (callId, callFrom) => {
3133
+ const stanza = {
3134
+ tag: 'call',
3135
+ attrs: {
3136
+ from: authState.creds.me.id,
3137
+ to: callFrom
3138
+ },
3139
+ content: [
3140
+ {
3141
+ tag: 'reject',
3142
+ attrs: {
3143
+ 'call-id': callId,
3144
+ 'call-creator': callFrom,
3145
+ count: '0'
3146
+ },
3147
+ content: undefined
3148
+ }
3149
+ ]
3150
+ };
3151
+ await query(stanza);
3152
+ };
3153
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
3154
+ const { fullMessage } = (0, index_js_5.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
3155
+ const { key: msgKey } = fullMessage;
3156
+ const msgId = msgKey.id;
3157
+ if (messageRetryManager) {
3158
+ // Check if we've exceeded max retries using the new system
3159
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
3160
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
3161
+ messageRetryManager.markRetryFailed(msgId);
3162
+ return;
3163
+ }
3164
+ // Increment retry count using new system
3165
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
3166
+ // Use the new retry count for the rest of the logic
3167
+ const key = `${msgId}:${msgKey?.participant}`;
3168
+ await msgRetryCache.set(key, retryCount);
3169
+ }
3170
+ else {
3171
+ // Fallback to old system
3172
+ const key = `${msgId}:${msgKey?.participant}`;
3173
+ let retryCount = (await msgRetryCache.get(key)) || 0;
3174
+ if (retryCount >= maxMsgRetryCount) {
3175
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
3176
+ await msgRetryCache.del(key);
3177
+ return;
3178
+ }
3179
+ retryCount += 1;
3180
+ await msgRetryCache.set(key, retryCount);
3181
+ }
3182
+ const key = `${msgId}:${msgKey?.participant}`;
3183
+ const retryCount = (await msgRetryCache.get(key)) || 1;
3184
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
3185
+ const fromJid = node.attrs.from;
3186
+ // Check if we should recreate the session
3187
+ let shouldRecreateSession = false;
3188
+ let recreateReason = '';
3189
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
3190
+ try {
3191
+ // Check if we have a session with this JID
3192
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
3193
+ const hasSession = await signalRepository.validateSession(fromJid);
3194
+ const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
3195
+ shouldRecreateSession = result.recreate;
3196
+ recreateReason = result.reason;
3197
+ if (shouldRecreateSession) {
3198
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
3199
+ // Delete existing session to force recreation
3200
+ await authState.keys.set({ session: { [sessionId]: null } });
3201
+ forceIncludeKeys = true;
3202
+ }
3203
+ }
3204
+ catch (error) {
3205
+ logger.warn({ error, fromJid }, 'failed to check session recreation');
3206
+ }
3207
+ }
3208
+ if (retryCount <= 2) {
3209
+ // Use new retry manager for phone requests if available
3210
+ if (messageRetryManager) {
3211
+ // Schedule phone request with delay (like whatsmeow)
3212
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
3213
+ try {
3214
+ const requestId = await requestPlaceholderResend(msgKey);
3215
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
3216
+ }
3217
+ catch (error) {
3218
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request');
3219
+ }
3220
+ });
3221
+ }
3222
+ else {
3223
+ // Fallback to immediate request
3224
+ const msgId = await requestPlaceholderResend(msgKey);
3225
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
3226
+ }
3227
+ }
3228
+ const deviceIdentity = (0, index_js_5.encodeSignedDeviceIdentity)(account, true);
3229
+ await authState.keys.transaction(async () => {
3230
+ const receipt = {
3231
+ tag: 'receipt',
3232
+ attrs: {
3233
+ id: msgId,
3234
+ type: 'retry',
3235
+ to: node.attrs.from
3236
+ },
3237
+ content: [
3238
+ {
3239
+ tag: 'retry',
3240
+ attrs: {
3241
+ count: retryCount.toString(),
3242
+ id: node.attrs.id,
3243
+ t: node.attrs.t,
3244
+ v: '1',
3245
+ // ADD ERROR FIELD
3246
+ error: '0'
3247
+ }
3248
+ },
3249
+ {
3250
+ tag: 'registration',
3251
+ attrs: {},
3252
+ content: (0, index_js_5.encodeBigEndian)(authState.creds.registrationId)
3253
+ }
3254
+ ]
3255
+ };
3256
+ if (node.attrs.recipient) {
3257
+ receipt.attrs.recipient = node.attrs.recipient;
3258
+ }
3259
+ if (node.attrs.participant) {
3260
+ receipt.attrs.participant = node.attrs.participant;
3261
+ }
3262
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
3263
+ const { update, preKeys } = await (0, index_js_5.getNextPreKeys)(authState, 1);
3264
+ const [keyId] = Object.keys(preKeys);
3265
+ const key = preKeys[+keyId];
3266
+ const content = receipt.content;
3267
+ content.push({
3268
+ tag: 'keys',
3269
+ attrs: {},
3270
+ content: [
3271
+ { tag: 'type', attrs: {}, content: Buffer.from(index_js_3.KEY_BUNDLE_TYPE) },
3272
+ { tag: 'identity', attrs: {}, content: identityKey.public },
3273
+ (0, index_js_5.xmppPreKey)(key, +keyId),
3274
+ (0, index_js_5.xmppSignedPreKey)(signedPreKey),
3275
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
3276
+ ]
3277
+ });
3278
+ ev.emit('creds.update', update);
3279
+ }
3280
+ await sendNode(receipt);
3281
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
3282
+ }, authState?.creds?.me?.id || 'sendRetryRequest');
3283
+ };
3284
+ // Mirrors WAWeb/Handle/PreKeyLow.js: skip a re-issued notification with the same stanza id.
3285
+ const inFlightPreKeyLow = new Set();
3286
+ /**
3287
+ * Fire-and-forget tctoken re-issuance after a peer's device identity changed.
3288
+ * Mirrors WAWebSendTcTokenWhenDeviceIdentityChange — runs in parallel with
3289
+ * the session refresh (not after it).
3290
+ */
3291
+ const reissueTcTokenAfterIdentityChange = (from) => {
3292
+ void (async () => {
3293
+ const normalizedJid = (0, index_js_6.jidNormalizedUser)(from);
3294
+ const tcJid = await (0, tc_token_utils_js_1.resolveTcTokenJid)(normalizedJid, getLIDForPN);
3295
+ const tcTokenData = await authState.keys.get('tctoken', [tcJid]);
3296
+ const senderTs = tcTokenData?.[tcJid]?.senderTimestamp;
3297
+ if (senderTs === null || senderTs === undefined || (0, tc_token_utils_js_1.isTcTokenExpired)(senderTs)) {
3298
+ return;
3299
+ }
3300
+ logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken');
3301
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
3302
+ const issueJid = await (0, tc_token_utils_js_1.resolveIssuanceJid)(normalizedJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
3303
+ const result = await issuePrivacyTokens([issueJid], senderTs);
3304
+ await (0, tc_token_utils_js_1.storeTcTokensFromIqResult)({
3305
+ result,
3306
+ fallbackJid: tcJid,
3307
+ keys: authState.keys,
3308
+ getLIDForPN,
3309
+ onNewJidStored: trackTcTokenJid
3310
+ });
3311
+ })().catch(err => {
3312
+ logger.debug({ jid: from, err: err?.message }, 'failed to re-issue tctoken after identity change');
3313
+ });
3314
+ };
3315
+ const handleEncryptNotification = async (node) => {
3316
+ const from = node.attrs.from;
3317
+ if (from === index_js_6.S_WHATSAPP_NET) {
3318
+ const stanzaId = node.attrs.id;
3319
+ if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
3320
+ return;
3321
+ }
3322
+ const countChild = (0, index_js_6.getBinaryNodeChild)(node, 'count');
3323
+ const count = +countChild.attrs.value;
3324
+ const shouldUploadMorePreKeys = count < index_js_3.MIN_PREKEY_COUNT;
3325
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
3326
+ if (shouldUploadMorePreKeys) {
3327
+ if (stanzaId)
3328
+ inFlightPreKeyLow.add(stanzaId);
3329
+ try {
3330
+ await uploadPreKeys();
3331
+ }
3332
+ finally {
3333
+ if (stanzaId)
3334
+ inFlightPreKeyLow.delete(stanzaId);
3335
+ }
3336
+ }
3337
+ }
3338
+ else {
3339
+ const result = await (0, index_js_5.handleIdentityChange)(node, {
3340
+ meId: authState.creds.me?.id,
3341
+ meLid: authState.creds.me?.lid,
3342
+ validateSession: signalRepository.validateSession,
3343
+ assertSessions,
3344
+ debounceCache: identityAssertDebounce,
3345
+ logger,
3346
+ onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
3347
+ });
3348
+ if (result.action === 'no_identity_node') {
3349
+ logger.info({ node }, 'unknown encrypt notification');
3350
+ }
3351
+ }
3352
+ };
3353
+ const handleGroupNotification = (fullNode, child, msg) => {
3354
+ // TODO: Support PN/LID (Here is only LID now)
3355
+ const actingParticipantLid = fullNode.attrs.participant;
3356
+ const actingParticipantPn = fullNode.attrs.participant_pn;
3357
+ const actingParticipantUsername = fullNode.attrs.participant_username;
3358
+ const affectedParticipantLid = (0, index_js_6.getBinaryNodeChild)(child, 'participant')?.attrs?.jid || actingParticipantLid;
3359
+ const affectedParticipantPn = (0, index_js_6.getBinaryNodeChild)(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
3360
+ switch (child?.tag) {
3361
+ case 'create':
3362
+ const metadata = (0, groups_js_1.extractGroupMetadata)(child);
3363
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_CREATE;
3364
+ msg.messageStubParameters = [metadata.subject];
3365
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
3366
+ ev.emit('chats.upsert', [
3367
+ {
3368
+ id: metadata.id,
3369
+ name: metadata.subject,
3370
+ conversationTimestamp: metadata.creation
3371
+ }
3372
+ ]);
3373
+ ev.emit('groups.upsert', [
3374
+ {
3375
+ ...metadata,
3376
+ author: actingParticipantLid,
3377
+ authorPn: actingParticipantPn,
3378
+ authorUsername: actingParticipantUsername
3379
+ }
3380
+ ]);
3381
+ break;
3382
+ case 'ephemeral':
3383
+ case 'not_ephemeral':
3384
+ msg.message = {
3385
+ protocolMessage: {
3386
+ type: index_js_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
3387
+ ephemeralExpiration: +(child.attrs.expiration || 0)
3388
+ }
3389
+ };
3390
+ break;
3391
+ case 'modify':
3392
+ const oldNumber = (0, index_js_6.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
3393
+ msg.messageStubParameters = oldNumber || [];
3394
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
3395
+ break;
3396
+ case 'promote':
3397
+ case 'demote':
3398
+ case 'remove':
3399
+ case 'add':
3400
+ case 'leave':
3401
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
3402
+ msg.messageStubType = index_js_4.WAMessageStubType[stubType];
3403
+ const participants = (0, index_js_6.getBinaryNodeChildren)(child, 'participant').map(({ attrs }) => {
3404
+ // TODO: Store LID MAPPINGS
3405
+ return {
3406
+ id: attrs.jid,
3407
+ phoneNumber: (0, index_js_6.isLidUser)(attrs.jid) && (0, index_js_6.isPnUser)(attrs.phone_number) ? attrs.phone_number : undefined,
3408
+ lid: (0, index_js_6.isPnUser)(attrs.jid) && (0, index_js_6.isLidUser)(attrs.lid) ? attrs.lid : undefined,
3409
+ username: attrs.participant_username || attrs.username || undefined,
3410
+ admin: (attrs.type || null)
3411
+ };
3412
+ });
3413
+ if (participants.length === 1 &&
3414
+ // if recv. "remove" message and sender removed themselves
3415
+ // mark as left
3416
+ ((0, index_js_6.areJidsSameUser)(participants[0].id, actingParticipantLid) ||
3417
+ (0, index_js_6.areJidsSameUser)(participants[0].id, actingParticipantPn)) &&
3418
+ child.tag === 'remove') {
3419
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
3420
+ }
3421
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a));
3422
+ break;
3423
+ case 'subject':
3424
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_CHANGE_SUBJECT;
3425
+ msg.messageStubParameters = [child.attrs.subject];
3426
+ break;
3427
+ case 'description':
3428
+ const description = (0, index_js_6.getBinaryNodeChild)(child, 'body')?.content?.toString();
3429
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
3430
+ msg.messageStubParameters = description ? [description] : undefined;
3431
+ break;
3432
+ case 'announcement':
3433
+ case 'not_announcement':
3434
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
3435
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
3436
+ break;
3437
+ case 'locked':
3438
+ case 'unlocked':
3439
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_CHANGE_RESTRICT;
3440
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
3441
+ break;
3442
+ case 'invite':
3443
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
3444
+ msg.messageStubParameters = [child.attrs.code];
3445
+ break;
3446
+ case 'member_add_mode':
3447
+ const addMode = child.content;
3448
+ if (addMode) {
3449
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
3450
+ msg.messageStubParameters = [addMode.toString()];
3451
+ }
3452
+ break;
3453
+ case 'membership_approval_mode':
3454
+ const approvalMode = (0, index_js_6.getBinaryNodeChild)(child, 'group_join');
3455
+ if (approvalMode) {
3456
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
3457
+ msg.messageStubParameters = [approvalMode.attrs.state];
3458
+ }
3459
+ break;
3460
+ case 'created_membership_requests':
3461
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
3462
+ msg.messageStubParameters = [
3463
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
3464
+ 'created',
3465
+ child.attrs.request_method
3466
+ ];
3467
+ break;
3468
+ case 'revoked_membership_requests':
3469
+ const isDenied = (0, index_js_6.areJidsSameUser)(affectedParticipantLid, actingParticipantLid);
3470
+ // TODO: LIDMAPPING SUPPORT
3471
+ msg.messageStubType = index_js_4.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
3472
+ msg.messageStubParameters = [
3473
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
3474
+ isDenied ? 'revoked' : 'rejected'
3475
+ ];
3476
+ break;
3477
+ }
3478
+ };
3479
+ const handleDevicesNotification = async (node) => {
3480
+ const [child] = (0, index_js_6.getAllBinaryNodeChildren)(node);
3481
+ const from = (0, index_js_6.jidNormalizedUser)(node.attrs.from);
3482
+ if (!child) {
3483
+ logger.debug({ from }, 'devices notification missing child, skipping');
3484
+ return;
3485
+ }
3486
+ const tag = child.tag;
3487
+ const deviceHash = child.attrs.device_hash;
3488
+ const devices = (0, index_js_6.getBinaryNodeChildren)(child, 'device');
3489
+ if ((0, index_js_6.areJidsSameUser)(from, authState.creds.me.id) || (0, index_js_6.areJidsSameUser)(from, authState.creds.me.lid)) {
3490
+ const deviceJids = devices.map(d => d.attrs.jid);
3491
+ logger.info({ deviceJids }, 'got my own devices');
3492
+ }
3493
+ if (!devices.length) {
3494
+ logger.debug({ from, tag }, 'no devices in notification, skipping');
3495
+ return;
3496
+ }
3497
+ const decoded = [];
3498
+ for (const d of devices) {
3499
+ const jid = d.attrs.jid;
3500
+ if (!jid)
3501
+ continue;
3502
+ const parts = (0, index_js_6.jidDecode)(jid);
3503
+ if (!parts) {
3504
+ logger.debug({ jid }, 'failed to decode device jid, skipping');
3505
+ continue;
3506
+ }
3507
+ decoded.push({ jid, user: parts.user, server: parts.server, device: parts.device });
3508
+ }
3509
+ if (!decoded.length)
3510
+ return;
3511
+ await devicesMutex.mutex(async () => {
3512
+ const byUser = new Map();
3513
+ for (const d of decoded) {
3514
+ const list = byUser.get(d.user) || [];
3515
+ list.push(d);
3516
+ byUser.set(d.user, list);
3517
+ }
3518
+ for (const [user, entries] of byUser) {
3519
+ if (tag === 'update') {
3520
+ logger.debug({ user }, `${user}'s device list updated, dropping cached devices`);
3521
+ await userDevicesCache?.del(user);
3522
+ continue;
3523
+ }
3524
+ if (tag === 'remove') {
3525
+ await signalRepository.deleteSession(entries.map(e => e.jid));
3526
+ }
3527
+ const existingCache = (await userDevicesCache?.get(user)) || [];
3528
+ if (!existingCache.length) {
3529
+ // No baseline yet; skip applying the delta so getUSyncDevices can
3530
+ // later fetch the full device list. Caching just the notification
3531
+ // entries would make a partial list look authoritative.
3532
+ logger.debug({ user, tag }, 'device list not cached, deferring to USync refresh');
3533
+ continue;
3534
+ }
3535
+ const affected = new Set(entries.map(e => e.device));
3536
+ let updatedDevices;
3537
+ switch (tag) {
3538
+ case 'add':
3539
+ logger.info({ deviceHash, count: entries.length }, 'devices added');
3540
+ updatedDevices = [
3541
+ ...existingCache.filter(d => !affected.has(d.device)),
3542
+ ...entries.map(e => ({ user: e.user, server: e.server, device: e.device }))
3543
+ ];
3544
+ break;
3545
+ case 'remove':
3546
+ logger.info({ deviceHash, count: entries.length }, 'devices removed');
3547
+ updatedDevices = existingCache.filter(d => !affected.has(d.device));
3548
+ break;
3549
+ default:
3550
+ logger.debug({ tag }, 'Unknown device list change tag');
3551
+ continue;
3552
+ }
3553
+ if (updatedDevices.length === 0) {
3554
+ await userDevicesCache?.del(user);
3555
+ }
3556
+ else {
3557
+ await userDevicesCache?.set(user, updatedDevices);
3558
+ }
3559
+ }
3560
+ });
3561
+ };
3562
+ const processNotification = async (node) => {
3563
+ const result = {};
3564
+ const [child] = (0, index_js_6.getAllBinaryNodeChildren)(node);
3565
+ const nodeType = node.attrs.type;
3566
+ const from = (0, index_js_6.jidNormalizedUser)(node.attrs.from);
3567
+ switch (nodeType) {
3568
+ case 'newsletter':
3569
+ await handleNewsletterNotification(node);
3570
+ break;
3571
+ case 'mex':
3572
+ await handleMexNotification(node);
3573
+ break;
3574
+ case 'w:gp2':
3575
+ // TODO: HANDLE PARTICIPANT_PN
3576
+ handleGroupNotification(node, child, result);
3577
+ break;
3578
+ case 'mediaretry':
3579
+ const event = (0, index_js_5.decodeMediaRetryNode)(node);
3580
+ ev.emit('messages.media-update', [event]);
3581
+ break;
3582
+ case 'encrypt':
3583
+ await handleEncryptNotification(node);
3584
+ break;
3585
+ case 'devices':
3586
+ try {
3587
+ await handleDevicesNotification(node);
3588
+ }
3589
+ catch (error) {
3590
+ logger.error({ error, node }, 'failed to handle devices notification');
3591
+ }
3592
+ break;
3593
+ case 'server_sync':
3594
+ const update = (0, index_js_6.getBinaryNodeChild)(node, 'collection');
3595
+ if (update) {
3596
+ const name = update.attrs.name;
3597
+ await resyncAppState([name], false);
3598
+ }
3599
+ break;
3600
+ case 'picture':
3601
+ const setPicture = (0, index_js_6.getBinaryNodeChild)(node, 'set');
3602
+ const delPicture = (0, index_js_6.getBinaryNodeChild)(node, 'delete');
3603
+ // TODO: WAJIDHASH stuff proper support inhouse
3604
+ ev.emit('contacts.update', [
3605
+ {
3606
+ id: (0, index_js_6.jidNormalizedUser)(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
3607
+ imgUrl: setPicture ? 'changed' : 'removed'
3608
+ }
3609
+ ]);
3610
+ if ((0, index_js_6.isJidGroup)(from)) {
3611
+ const node = setPicture || delPicture;
3612
+ result.messageStubType = index_js_4.WAMessageStubType.GROUP_CHANGE_ICON;
3613
+ if (setPicture) {
3614
+ result.messageStubParameters = [setPicture.attrs.id];
3615
+ }
3616
+ result.participant = node?.attrs.author;
3617
+ result.key = {
3618
+ ...(result.key || {}),
3619
+ participant: setPicture?.attrs.author
3620
+ };
3621
+ }
3622
+ break;
3623
+ case 'account_sync':
3624
+ if (child.tag === 'disappearing_mode') {
3625
+ const newDuration = +child.attrs.duration;
3626
+ const timestamp = +child.attrs.t;
3627
+ logger.info({ newDuration }, 'updated account disappearing mode');
3628
+ ev.emit('creds.update', {
3629
+ accountSettings: {
3630
+ ...authState.creds.accountSettings,
3631
+ defaultDisappearingMode: {
3632
+ ephemeralExpiration: newDuration,
3633
+ ephemeralSettingTimestamp: timestamp
3634
+ }
3635
+ }
3636
+ });
3637
+ }
3638
+ else if (child.tag === 'blocklist') {
3639
+ const blocklists = (0, index_js_6.getBinaryNodeChildren)(child, 'item');
3640
+ for (const { attrs } of blocklists) {
3641
+ const blocklist = [attrs.jid];
3642
+ const type = attrs.action === 'block' ? 'add' : 'remove';
3643
+ ev.emit('blocklist.update', { blocklist, type });
3644
+ }
3645
+ }
3646
+ break;
3647
+ case 'link_code_companion_reg': {
3648
+ const linkCodeCompanionReg = (0, index_js_6.getBinaryNodeChild)(node, 'link_code_companion_reg');
3649
+ // Server sends two notifications: immediately after companion_hello (stage=undefined,
3650
+ // only link_code_pairing_ref) and after phone enters code (stage="primary_hello",
3651
+ // all 3 crypto fields). Only process the latter.
3652
+ if (linkCodeCompanionReg?.attrs?.stage !== 'primary_hello')
3653
+ break;
3654
+ const ref = toRequiredBuffer((0, index_js_6.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
3655
+ const primaryIdentityPublicKey = toRequiredBuffer((0, index_js_6.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
3656
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, index_js_6.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
3657
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
3658
+ const companionSharedKey = index_js_5.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
3659
+ const random = (0, node_crypto_1.randomBytes)(32);
3660
+ const linkCodeSalt = (0, node_crypto_1.randomBytes)(32);
3661
+ const linkCodePairingExpanded = (0, index_js_5.hkdf)(companionSharedKey, 32, {
3662
+ salt: linkCodeSalt,
3663
+ info: 'link_code_pairing_key_bundle_encryption_key'
3664
+ });
3665
+ const encryptPayload = Buffer.concat([
3666
+ Buffer.from(authState.creds.signedIdentityKey.public),
3667
+ primaryIdentityPublicKey,
3668
+ random
3669
+ ]);
3670
+ const encryptIv = (0, node_crypto_1.randomBytes)(12);
3671
+ const encrypted = (0, index_js_5.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
3672
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
3673
+ const identitySharedKey = index_js_5.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
3674
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
3675
+ authState.creds.advSecretKey = Buffer.from((0, index_js_5.hkdf)(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
3676
+ await query({
3677
+ tag: 'iq',
3678
+ attrs: {
3679
+ to: index_js_6.S_WHATSAPP_NET,
3680
+ type: 'set',
3681
+ id: sock.generateMessageTag(),
3682
+ xmlns: 'md'
3683
+ },
3684
+ content: [
3685
+ {
3686
+ tag: 'link_code_companion_reg',
3687
+ attrs: {
3688
+ jid: authState.creds.me.id,
3689
+ stage: 'companion_finish'
3690
+ },
3691
+ content: [
3692
+ {
3693
+ tag: 'link_code_pairing_wrapped_key_bundle',
3694
+ attrs: {},
3695
+ content: encryptedPayload
3696
+ },
3697
+ {
3698
+ tag: 'companion_identity_public',
3699
+ attrs: {},
3700
+ content: authState.creds.signedIdentityKey.public
3701
+ },
3702
+ {
3703
+ tag: 'link_code_pairing_ref',
3704
+ attrs: {},
3705
+ content: ref
3706
+ }
3707
+ ]
3708
+ }
3709
+ ]
3710
+ });
3711
+ authState.creds.registered = true;
3712
+ ev.emit('creds.update', authState.creds);
3713
+ break;
3714
+ }
3715
+ case 'privacy_token':
3716
+ await handlePrivacyTokenNotification(node);
3717
+ break;
3718
+ }
3719
+ if (Object.keys(result).length) {
3720
+ return result;
3721
+ }
3722
+ };
3723
+ /**
3724
+ * In-memory cache of storage JIDs with stored tctokens, seeded from the persisted index.
3725
+ * Used to coalesce writes during a session; pruning always re-reads the persisted index
3726
+ * to cover writes made by other layers (e.g. history sync).
3727
+ */
3728
+ const tcTokenKnownJids = new Set();
3729
+ const tcTokenIndexLoaded = (async () => {
3730
+ try {
3731
+ const jids = await (0, tc_token_utils_js_1.readTcTokenIndex)(authState.keys);
3732
+ for (const jid of jids)
3733
+ tcTokenKnownJids.add(jid);
3734
+ logger.debug({ count: tcTokenKnownJids.size }, 'loaded tctoken index');
3735
+ }
3736
+ catch (err) {
3737
+ logger.warn({ err: err?.message }, 'failed to load tctoken index');
3738
+ }
3739
+ })();
3740
+ let tcTokenIndexTimer;
3741
+ async function flushTcTokenIndex() {
3742
+ if (tcTokenIndexTimer) {
3743
+ clearTimeout(tcTokenIndexTimer);
3744
+ tcTokenIndexTimer = undefined;
3745
+ }
3746
+ // Merge with whatever is already persisted so we don't clobber writes from other
3747
+ // paths (history sync, concurrent sessions on the same store).
3748
+ const write = await (0, tc_token_utils_js_1.buildMergedTcTokenIndexWrite)(authState.keys, tcTokenKnownJids);
3749
+ return authState.keys.set({ tctoken: write });
3750
+ }
3751
+ function scheduleTcTokenIndexSave() {
3752
+ if (tcTokenIndexTimer) {
3753
+ clearTimeout(tcTokenIndexTimer);
3754
+ }
3755
+ tcTokenIndexTimer = setTimeout(() => {
3756
+ tcTokenIndexTimer = undefined;
3757
+ flushTcTokenIndex().catch(err => {
3758
+ logger.warn({ err: err?.message }, 'failed to save tctoken index');
3759
+ });
3760
+ }, 5000);
3761
+ }
3762
+ function trackTcTokenJid(jid) {
3763
+ if (jid && jid !== tc_token_utils_js_1.TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
3764
+ tcTokenKnownJids.add(jid);
3765
+ scheduleTcTokenIndexSave();
3766
+ }
3767
+ }
3768
+ const handlePrivacyTokenNotification = async (node) => {
3769
+ const tokensNode = (0, index_js_6.getBinaryNodeChild)(node, 'tokens');
3770
+ if (!tokensNode)
3771
+ return;
3772
+ const from = (0, index_js_6.jidNormalizedUser)(node.attrs.from);
3773
+ // WA Web uses: senderLid ?? toLid(from) for the storage key
3774
+ // The sender_lid attribute provides the LID directly when available
3775
+ const senderLid = node.attrs.sender_lid && (0, index_js_6.isLidUser)((0, index_js_6.jidNormalizedUser)(node.attrs.sender_lid))
3776
+ ? (0, index_js_6.jidNormalizedUser)(node.attrs.sender_lid)
3777
+ : undefined;
3778
+ const fallbackJid = senderLid ?? (await (0, tc_token_utils_js_1.resolveTcTokenJid)(from, getLIDForPN));
3779
+ logger.debug({ from, storageJid: fallbackJid }, 'processing privacy token notification');
3780
+ await (0, tc_token_utils_js_1.storeTcTokensFromIqResult)({
3781
+ result: node,
3782
+ fallbackJid,
3783
+ keys: authState.keys,
3784
+ getLIDForPN,
3785
+ onNewJidStored: trackTcTokenJid
3786
+ });
3787
+ };
3788
+ async function decipherLinkPublicKey(data) {
3789
+ const buffer = toRequiredBuffer(data);
3790
+ const salt = buffer.slice(0, 32);
3791
+ const secretKey = await (0, index_js_5.derivePairingCodeKey)(authState.creds.pairingCode, salt);
3792
+ const iv = buffer.slice(32, 48);
3793
+ const payload = buffer.slice(48, 80);
3794
+ return (0, index_js_5.aesDecryptCTR)(payload, secretKey, iv);
3795
+ }
3796
+ function toRequiredBuffer(data) {
3797
+ if (data === undefined) {
3798
+ throw new index_js_2.HttpError('Invalid buffer', { statusCode: 400 });
3799
+ }
3800
+ return data instanceof Buffer ? data : Buffer.from(data);
3801
+ }
3802
+ const willSendMessageAgain = async (id, participant) => {
3803
+ const key = `${id}:${participant}`;
3804
+ const retryCount = (await msgRetryCache.get(key)) || 0;
3805
+ return retryCount < maxMsgRetryCount;
3806
+ };
3807
+ const updateSendMessageAgainCount = async (id, participant) => {
3808
+ const key = `${id}:${participant}`;
3809
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
3810
+ await msgRetryCache.set(key, newValue);
3811
+ };
3812
+ const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
3813
+ const remoteJid = key.remoteJid;
3814
+ const participant = key.participant || remoteJid;
3815
+ const retryCount = +retryNode.attrs.count || 1;
3816
+ const msgId = ids[0];
3817
+ // Try to get messages from cache first, then fallback to getMessage
3818
+ const msgs = [];
3819
+ for (const id of ids) {
3820
+ let msg;
3821
+ // Try to get from retry cache first if enabled
3822
+ if (messageRetryManager) {
3823
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
3824
+ if (cachedMsg) {
3825
+ msg = cachedMsg.message;
3826
+ logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
3827
+ // Mark retry as successful since we found the message
3828
+ messageRetryManager.markRetrySuccess(id);
3829
+ }
3830
+ }
3831
+ // Fallback to getMessage if not found in cache
3832
+ if (!msg) {
3833
+ msg = await getMessage({ ...key, id });
3834
+ if (msg) {
3835
+ logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
3836
+ // Also mark as successful if found via getMessage
3837
+ if (messageRetryManager) {
3838
+ messageRetryManager.markRetrySuccess(id);
3839
+ }
3840
+ }
3841
+ }
3842
+ msgs.push(msg);
3843
+ }
3844
+ // if it's the primary jid sending the request
3845
+ // just re-send the message to everyone
3846
+ // prevents the first message decryption failure
3847
+ const sendToAll = !(0, index_js_6.jidDecode)(participant)?.device;
3848
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
3849
+ let injectedFromBundle = false;
3850
+ const bundle = (0, index_js_5.extractE2ESessionFromRetryReceipt)(receiptNode);
3851
+ if (bundle) {
3852
+ try {
3853
+ await signalRepository.injectE2ESession({ jid: participant, session: bundle });
3854
+ injectedFromBundle = true;
3855
+ logger.debug({ participant, retryCount }, 'injected session from retry receipt key bundle');
3856
+ }
3857
+ catch (error) {
3858
+ logger.warn({ error, participant }, 'failed to inject session from retry receipt');
3859
+ }
3860
+ }
3861
+ if (!injectedFromBundle) {
3862
+ const receivedRegId = (0, index_js_6.getBinaryNodeChildUInt)(receiptNode, 'registration', 4);
3863
+ if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
3864
+ const info = await signalRepository.getSessionInfo(participant);
3865
+ if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) {
3866
+ logger.info({ participant, stored: info.registrationId, received: receivedRegId }, 'reg id mismatch on retry without bundle, deleting session');
3867
+ await authState.keys.set({ session: { [sessionId]: null } });
3868
+ }
3869
+ }
3870
+ }
3871
+ const BASE_KEY_CHECK_RETRY = 2;
3872
+ if (msgId && messageRetryManager) {
3873
+ const info = await signalRepository.getSessionInfo(participant);
3874
+ if (info) {
3875
+ if (retryCount === BASE_KEY_CHECK_RETRY) {
3876
+ messageRetryManager.saveBaseKey(sessionId, msgId, info.baseKey);
3877
+ }
3878
+ else if (retryCount > BASE_KEY_CHECK_RETRY) {
3879
+ if (messageRetryManager.hasSameBaseKey(sessionId, msgId, info.baseKey)) {
3880
+ logger.warn({ participant, retryCount }, 'base key collision on retry, forcing fresh session');
3881
+ await authState.keys.set({ session: { [sessionId]: null } });
3882
+ }
3883
+ messageRetryManager.deleteBaseKey(sessionId, msgId);
3884
+ }
3885
+ }
3886
+ }
3887
+ let shouldRecreateSession = false;
3888
+ let recreateReason = '';
3889
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
3890
+ try {
3891
+ const hasSession = await signalRepository.validateSession(participant);
3892
+ const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
3893
+ shouldRecreateSession = result.recreate;
3894
+ recreateReason = result.reason;
3895
+ if (shouldRecreateSession) {
3896
+ logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry');
3897
+ await authState.keys.set({ session: { [sessionId]: null } });
3898
+ }
3899
+ }
3900
+ catch (error) {
3901
+ logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
3902
+ }
3903
+ }
3904
+ if (!injectedFromBundle) {
3905
+ await assertSessions([participant], true);
3906
+ }
3907
+ if ((0, index_js_6.isJidGroup)(remoteJid)) {
3908
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
3909
+ }
3910
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
3911
+ for (const [i, msg] of msgs.entries()) {
3912
+ if (!ids[i])
3913
+ continue;
3914
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
3915
+ await updateSendMessageAgainCount(ids[i], participant);
3916
+ const msgRelayOpts = { messageId: ids[i] };
3917
+ if (sendToAll) {
3918
+ msgRelayOpts.useUserDevicesCache = false;
3919
+ }
3920
+ else {
3921
+ msgRelayOpts.participant = {
3922
+ jid: participant,
3923
+ count: +retryNode.attrs.count
3924
+ };
3925
+ }
3926
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
3927
+ }
3928
+ else {
3929
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
3930
+ }
3931
+ }
3932
+ };
3933
+ const handleReceipt = async (node) => {
3934
+ const { attrs, content } = node;
3935
+ const isLid = attrs.from.includes('lid');
3936
+ const isNodeFromMe = (0, index_js_6.areJidsSameUser)(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
3937
+ const remoteJid = !isNodeFromMe || (0, index_js_6.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
3938
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
3939
+ const key = {
3940
+ remoteJid,
3941
+ id: '',
3942
+ fromMe,
3943
+ participant: attrs.participant
3944
+ };
3945
+ const ids = [attrs.id];
3946
+ if (Array.isArray(content)) {
3947
+ const items = (0, index_js_6.getBinaryNodeChildren)(content[0], 'item');
3948
+ ids.push(...items.map(i => i.attrs.id));
3949
+ }
3950
+ try {
3951
+ await Promise.all([
3952
+ receiptMutex.mutex(async () => {
3953
+ const status = (0, index_js_5.getStatusFromReceiptType)(attrs.type);
3954
+ if (typeof status !== 'undefined' &&
3955
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
3956
+ // or another device of ours has read some messages
3957
+ (status >= index_js_1.proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
3958
+ if ((0, index_js_6.isJidGroup)(remoteJid) || (0, index_js_6.isJidStatusBroadcast)(remoteJid)) {
3959
+ if (attrs.participant) {
3960
+ const updateKey = status === index_js_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
3961
+ ev.emit('message-receipt.update', ids.map(id => ({
3962
+ key: { ...key, id },
3963
+ receipt: {
3964
+ userJid: (0, index_js_6.jidNormalizedUser)(attrs.participant),
3965
+ [updateKey]: +attrs.t
3966
+ }
3967
+ })));
3968
+ }
3969
+ }
3970
+ else {
3971
+ ev.emit('messages.update', ids.map(id => ({
3972
+ key: { ...key, id },
3973
+ update: { status, messageTimestamp: (0, index_js_5.toNumber)(+(attrs.t ?? 0)) }
3974
+ })));
3975
+ }
3976
+ }
3977
+ if (attrs.type === 'retry') {
3978
+ // correctly set who is asking for the retry
3979
+ key.participant = key.participant || attrs.from;
3980
+ const retryNode = (0, index_js_6.getBinaryNodeChild)(node, 'retry');
3981
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
3982
+ if (key.fromMe) {
3983
+ try {
3984
+ await updateSendMessageAgainCount(ids[0], key.participant);
3985
+ logger.debug({ attrs, key }, 'recv retry request');
3986
+ await sendMessagesAgain(key, ids, retryNode, node);
3987
+ }
3988
+ catch (error) {
3989
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
3990
+ }
3991
+ }
3992
+ else {
3993
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
3994
+ }
3995
+ }
3996
+ else {
3997
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
3998
+ }
3999
+ }
4000
+ })
4001
+ ]);
4002
+ }
4003
+ finally {
4004
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
4005
+ }
4006
+ };
4007
+ const handleNotification = async (node) => {
4008
+ const remoteJid = node.attrs.from;
4009
+ try {
4010
+ await Promise.all([
4011
+ notificationMutex.mutex(async () => {
4012
+ const msg = await processNotification(node);
4013
+ if (msg) {
4014
+ const fromMe = (0, index_js_6.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
4015
+ const { senderAlt: participantAlt, addressingMode } = (0, index_js_5.extractAddressingContext)(node);
4016
+ msg.key = {
4017
+ remoteJid,
4018
+ fromMe,
4019
+ participant: node.attrs.participant,
4020
+ participantAlt,
4021
+ participantUsername: node.attrs.participant_username,
4022
+ addressingMode,
4023
+ id: node.attrs.id,
4024
+ ...(msg.key || {})
4025
+ };
4026
+ msg.participant ?? (msg.participant = node.attrs.participant);
4027
+ msg.messageTimestamp = +node.attrs.t;
4028
+ const fullMsg = index_js_1.proto.WebMessageInfo.fromObject(msg);
4029
+ await upsertMessage(fullMsg, 'append');
4030
+ }
4031
+ })
4032
+ ]);
4033
+ }
4034
+ finally {
4035
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
4036
+ }
4037
+ };
4038
+ const handleMessage = async (node) => {
4039
+ const encNode = (0, index_js_6.getBinaryNodeChild)(node, 'enc');
4040
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
4041
+ if (encNode?.attrs.type === 'msmsg') {
4042
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
4043
+ await sendMessageAck(node, index_js_5.NACK_REASONS.MissingMessageSecret);
4044
+ return;
4045
+ }
4046
+ let acked = false;
4047
+ try {
4048
+ const { fullMessage: msg, category, author, decrypt } = (0, index_js_5.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
4049
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
4050
+ // store new mappings we didn't have before
4051
+ if (!!alt) {
4052
+ const altServer = (0, index_js_6.jidDecode)(alt)?.server;
4053
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
4054
+ if (altServer === 'lid') {
4055
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
4056
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
4057
+ await signalRepository.migrateSession(primaryJid, alt);
4058
+ }
4059
+ }
4060
+ else {
4061
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
4062
+ await signalRepository.migrateSession(alt, primaryJid);
4063
+ }
4064
+ }
4065
+ await messageMutex.mutex(async () => {
4066
+ await decrypt();
4067
+ if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
4068
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
4069
+ }
4070
+ // message failed to decrypt
4071
+ if (msg.messageStubType === index_js_1.proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
4072
+ if (msg?.messageStubParameters?.[0] === index_js_5.MISSING_KEYS_ERROR_TEXT) {
4073
+ acked = true;
4074
+ return sendMessageAck(node, index_js_5.NACK_REASONS.ParsingError);
4075
+ }
4076
+ if (msg.messageStubParameters?.[0] === index_js_5.NO_MESSAGE_FOUND_ERROR_TEXT) {
4077
+ // Message arrived without encryption (e.g. CTWA ads messages).
4078
+ // Check if this is eligible for placeholder resend (matching WA Web filters).
4079
+ const unavailableNode = (0, index_js_6.getBinaryNodeChild)(node, 'unavailable');
4080
+ const unavailableType = unavailableNode?.attrs?.type;
4081
+ if (unavailableType === 'bot_unavailable_fanout' ||
4082
+ unavailableType === 'hosted_unavailable_fanout' ||
4083
+ unavailableType === 'view_once_unavailable_fanout') {
4084
+ logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
4085
+ acked = true;
4086
+ return sendMessageAck(node);
4087
+ }
4088
+ const messageAge = (0, index_js_5.unixTimestampSeconds)() - (0, index_js_5.toNumber)(msg.messageTimestamp);
4089
+ if (messageAge > index_js_3.PLACEHOLDER_MAX_AGE_SECONDS) {
4090
+ logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
4091
+ acked = true;
4092
+ return sendMessageAck(node);
4093
+ }
4094
+ // Request the real content from the phone via placeholder resend PDO.
4095
+ // Upsert the CIPHERTEXT stub as a placeholder (like WA Web's processPlaceholderMsg),
4096
+ // and store the requestId in stubParameters[1] so users can correlate
4097
+ // with the incoming PDO response event.
4098
+ const cleanKey = {
4099
+ remoteJid: msg.key.remoteJid,
4100
+ fromMe: msg.key.fromMe,
4101
+ id: msg.key.id,
4102
+ participant: msg.key.participant
4103
+ };
4104
+ // Cache the original message metadata so the PDO response handler
4105
+ // can preserve key fields (LID details etc.) that the phone may omit
4106
+ const msgData = {
4107
+ key: msg.key,
4108
+ messageTimestamp: msg.messageTimestamp,
4109
+ pushName: msg.pushName,
4110
+ participant: msg.participant,
4111
+ verifiedBizName: msg.verifiedBizName
4112
+ };
4113
+ requestPlaceholderResend(cleanKey, msgData)
4114
+ .then(requestId => {
4115
+ if (requestId && requestId !== 'RESOLVED') {
4116
+ logger.debug({ msgId: msg.key.id, requestId }, 'requested placeholder resend for unavailable message');
4117
+ ev.emit('messages.update', [
4118
+ {
4119
+ key: msg.key,
4120
+ update: { messageStubParameters: [index_js_5.NO_MESSAGE_FOUND_ERROR_TEXT, requestId] }
4121
+ }
4122
+ ]);
4123
+ }
4124
+ })
4125
+ .catch(err => {
4126
+ logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
4127
+ });
4128
+ acked = true;
4129
+ await sendMessageAck(node);
4130
+ // Don't return — fall through to upsertMessage so the stub is emitted
4131
+ }
4132
+ else {
4133
+ // Skip retry for expired status messages (>24h old)
4134
+ if ((0, index_js_6.isJidStatusBroadcast)(msg.key.remoteJid)) {
4135
+ const messageAge = (0, index_js_5.unixTimestampSeconds)() - (0, index_js_5.toNumber)(msg.messageTimestamp);
4136
+ if (messageAge > index_js_3.STATUS_EXPIRY_SECONDS) {
4137
+ logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message');
4138
+ acked = true;
4139
+ return sendMessageAck(node);
4140
+ }
4141
+ }
4142
+ logger.debug('[handleMessage] Attempting retry request for failed decryption');
4143
+ // WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
4144
+ await retryMutex.mutex(async () => {
4145
+ try {
4146
+ if (!ws.isOpen) {
4147
+ logger.debug({ node }, 'Connection closed, skipping retry');
4148
+ return;
4149
+ }
4150
+ const encNode = (0, index_js_6.getBinaryNodeChild)(node, 'enc');
4151
+ await sendRetryRequest(node, !encNode);
4152
+ if (retryRequestDelayMs) {
4153
+ await (0, index_js_5.delay)(retryRequestDelayMs);
4154
+ }
4155
+ }
4156
+ catch (err) {
4157
+ logger.error({ err }, 'Failed to send retry');
4158
+ }
4159
+ acked = true;
4160
+ await sendMessageAck(node, index_js_5.NACK_REASONS.UnhandledError);
4161
+ });
4162
+ }
4163
+ }
4164
+ else {
4165
+ if (messageRetryManager && msg.key.id) {
4166
+ messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
4167
+ }
4168
+ const isNewsletter = (0, index_js_6.isJidNewsletter)(msg.key.remoteJid);
4169
+ if (!isNewsletter) {
4170
+ // no type in the receipt => message delivered
4171
+ let type = undefined;
4172
+ let participant = msg.key.participant;
4173
+ if (category === 'peer') {
4174
+ // special peer message
4175
+ type = 'peer_msg';
4176
+ }
4177
+ else if (msg.key.fromMe) {
4178
+ // message was sent by us from a different device
4179
+ type = 'sender';
4180
+ // need to specially handle this case
4181
+ if ((0, index_js_6.isLidUser)(msg.key.remoteJid) || (0, index_js_6.isLidUser)(msg.key.remoteJidAlt)) {
4182
+ participant = author; // TODO: investigate sending receipts to LIDs and not PNs
4183
+ }
4184
+ }
4185
+ else if (!sendActiveReceipts) {
4186
+ type = 'inactive';
4187
+ }
4188
+ acked = true;
4189
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
4190
+ // send ack for history message
4191
+ const isAnyHistoryMsg = (0, index_js_5.getHistoryMsg)(msg.message);
4192
+ if (isAnyHistoryMsg) {
4193
+ const jid = (0, index_js_6.jidNormalizedUser)(msg.key.remoteJid);
4194
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync'); // TODO: investigate
4195
+ }
4196
+ }
4197
+ else {
4198
+ acked = true;
4199
+ await sendMessageAck(node);
4200
+ logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
4201
+ }
4202
+ }
4203
+ (0, index_js_5.cleanMessage)(msg, authState.creds.me.id, authState.creds.me.lid);
4204
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
4205
+ });
4206
+ }
4207
+ catch (error) {
4208
+ logger.error({ error, node: (0, index_js_6.binaryNodeToString)(node) }, 'error in handling message');
4209
+ if (!acked) {
4210
+ await sendMessageAck(node, index_js_5.NACK_REASONS.UnhandledError).catch(ackErr => logger.error({ ackErr }, 'failed to ack message after error'));
4211
+ }
4212
+ }
4213
+ };
4214
+ const handleCall = async (node) => {
4215
+ try {
4216
+ const { attrs } = node;
4217
+ const [infoChild] = (0, index_js_6.getAllBinaryNodeChildren)(node);
4218
+ if (!infoChild) {
4219
+ throw new index_js_2.HttpError('Missing call info in call node');
4220
+ }
4221
+ const status = (0, index_js_5.getCallStatusFromNode)(infoChild);
4222
+ const callId = infoChild.attrs['call-id'];
4223
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
4224
+ const call = {
4225
+ chatId: attrs.from,
4226
+ from,
4227
+ callerPn: infoChild.attrs['caller_pn'],
4228
+ id: callId,
4229
+ date: new Date(+attrs.t * 1000),
4230
+ offline: !!attrs.offline,
4231
+ status
4232
+ };
4233
+ if (status === 'relaylatency') {
4234
+ const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms'];
4235
+ const latencyMs = latencyValue ? Number(latencyValue) : undefined;
4236
+ if (Number.isFinite(latencyMs)) {
4237
+ call.latencyMs = latencyMs;
4238
+ }
4239
+ }
4240
+ if (status === 'offer') {
4241
+ call.isVideo = !!(0, index_js_6.getBinaryNodeChild)(infoChild, 'video');
4242
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
4243
+ call.groupJid = infoChild.attrs['group-jid'];
4244
+ await callOfferCache.set(call.id, call);
4245
+ }
4246
+ const existingCall = await callOfferCache.get(call.id);
4247
+ // use existing call info to populate this event
4248
+ if (existingCall) {
4249
+ call.isVideo = existingCall.isVideo;
4250
+ call.isGroup = existingCall.isGroup;
4251
+ call.callerPn = call.callerPn || existingCall.callerPn;
4252
+ }
4253
+ // delete data once call has ended
4254
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
4255
+ await callOfferCache.del(call.id);
4256
+ }
4257
+ ev.emit('call', [call]);
4258
+ }
4259
+ catch (error) {
4260
+ logger.error({ error, node: (0, index_js_6.binaryNodeToString)(node) }, 'error in handling call');
4261
+ }
4262
+ finally {
4263
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'));
4264
+ }
4265
+ };
4266
+ const handleBadAck = async ({ attrs }) => {
4267
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
4268
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
4269
+ // // current hypothesis is that if pash is sent in the ack
4270
+ // // it means -- the message hasn't reached all devices yet
4271
+ // // we'll retry sending the message here
4272
+ // if(attrs.phash) {
4273
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
4274
+ // const msg = await getMessage(key)
4275
+ // if(msg) {
4276
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
4277
+ // } else {
4278
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
4279
+ // }
4280
+ // }
4281
+ // error in acknowledgement,
4282
+ // device could not display the message
4283
+ if (attrs.error) {
4284
+ const isReachoutTimelocked = attrs.error === String(index_js_5.NACK_REASONS.SenderReachoutTimelocked);
4285
+ if (attrs.error === index_js_5.SERVER_ERROR_CODES.MessageAccountRestriction) {
4286
+ // 463 = 1:1 message missing privacy token (tctoken). Usually means the
4287
+ // account is restricted: WhatsApp blocks starting new chats but preserves
4288
+ // existing ones, since established chats already carry a tctoken.
4289
+ // WA Web prevents this client-side (disables the compose bar).
4290
+ // No retry — retrying counts as another "reach out" and worsens the restriction.
4291
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'error 463: account restricted or missing tctoken for contact');
4292
+ const ackFrom = attrs.from;
4293
+ if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
4294
+ inFlight463Recoveries.add(ackFrom);
4295
+ void (async () => {
4296
+ try {
4297
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
4298
+ const tcStorageJid = await (0, tc_token_utils_js_1.resolveTcTokenJid)(ackFrom, getLIDForPN);
4299
+ const issueJid = await (0, tc_token_utils_js_1.resolveIssuanceJid)(ackFrom, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
4300
+ const result = await issuePrivacyTokens([issueJid], (0, index_js_5.unixTimestampSeconds)());
4301
+ await (0, tc_token_utils_js_1.storeTcTokensFromIqResult)({
4302
+ result,
4303
+ fallbackJid: tcStorageJid,
4304
+ keys: authState.keys,
4305
+ getLIDForPN,
4306
+ onNewJidStored: trackTcTokenJid
4307
+ });
4308
+ logger.debug({ from: ackFrom }, 'completed 463 token recovery issuance');
4309
+ }
4310
+ catch (err) {
4311
+ logger.debug({ from: ackFrom, err: err?.message }, 'failed 463 token recovery issuance');
4312
+ }
4313
+ finally {
4314
+ inFlight463Recoveries.delete(ackFrom);
4315
+ }
4316
+ })();
4317
+ }
4318
+ }
4319
+ else if (attrs.error === index_js_5.SERVER_ERROR_CODES.SmaxInvalid) {
4320
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing');
4321
+ }
4322
+ else if (isReachoutTimelocked) {
4323
+ // user is temporarily restricted, fetch current restriction details
4324
+ await fetchAccountReachoutTimelock().catch(err => logger.warn({ err }, 'failed to fetch reachout timelock'));
4325
+ logger.warn({ attrs }, 'received error in ack');
4326
+ }
4327
+ else {
4328
+ logger.warn({ attrs }, 'received error in ack');
4329
+ }
4330
+ ev.emit('messages.update', [
4331
+ {
4332
+ key,
4333
+ update: {
4334
+ status: index_js_4.WAMessageStatus.ERROR,
4335
+ messageStubParameters: isReachoutTimelocked ? [attrs.error, index_js_5.ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
4336
+ }
4337
+ }
4338
+ ]);
4339
+ }
4340
+ };
4341
+ /// processes a node with the given function
4342
+ /// and adds the task to the existing buffer if we're buffering events
4343
+ const processNodeWithBuffer = async (node, identifier, exec) => {
4344
+ ev.buffer();
4345
+ await execTask();
4346
+ ev.flush();
4347
+ function execTask() {
4348
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
4349
+ }
4350
+ };
4351
+ const offlineNodeProcessor = (0, offline_node_processor_js_1.makeOfflineNodeProcessor)(new Map([
4352
+ ['message', handleMessage],
4353
+ ['call', handleCall],
4354
+ ['receipt', handleReceipt],
4355
+ ['notification', handleNotification]
4356
+ ]), {
4357
+ isWsOpen: () => ws.isOpen,
4358
+ onUnexpectedError,
4359
+ yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
4360
+ });
4361
+ const processNode = async (type, node, identifier, exec) => {
4362
+ // Fast path: ack and drop ignored JIDs before entering the buffer/queue
4363
+ const from = node.attrs.from;
4364
+ let ignoreJid = from;
4365
+ if (type === 'receipt' && from) {
4366
+ const attrs = node.attrs;
4367
+ const isLid = attrs.from.includes('lid');
4368
+ const isNodeFromMe = (0, index_js_6.areJidsSameUser)(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
4369
+ ignoreJid = !isNodeFromMe || (0, index_js_6.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
4370
+ }
4371
+ if (ignoreJid && ignoreJid !== index_js_6.S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
4372
+ await sendMessageAck(node, type === 'message' ? index_js_5.NACK_REASONS.UnhandledError : undefined);
4373
+ return;
4374
+ }
4375
+ const isOffline = !!node.attrs.offline;
4376
+ if (isOffline) {
4377
+ offlineNodeProcessor.enqueue(type, node);
4378
+ }
4379
+ else {
4380
+ await processNodeWithBuffer(node, identifier, exec);
4381
+ }
4382
+ };
4383
+ // recv a message
4384
+ ws.on('CB:message', async (node) => {
4385
+ await processNode('message', node, 'processing message', handleMessage);
4386
+ });
4387
+ ws.on('CB:call', async (node) => {
4388
+ await processNode('call', node, 'handling call', handleCall);
4389
+ });
4390
+ ws.on('CB:receipt', async (node) => {
4391
+ await processNode('receipt', node, 'handling receipt', handleReceipt);
4392
+ });
4393
+ ws.on('CB:notification', async (node) => {
4394
+ await processNode('notification', node, 'handling notification', handleNotification);
4395
+ });
4396
+ ws.on('CB:ack,class:message', (node) => {
4397
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
4398
+ });
4399
+ ev.on('call', async ([call]) => {
4400
+ if (!call) {
4401
+ return;
4402
+ }
4403
+ // missed call + group call notification message generation
4404
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
4405
+ const msg = {
4406
+ key: {
4407
+ remoteJid: call.chatId,
4408
+ id: call.id,
4409
+ fromMe: false
4410
+ },
4411
+ messageTimestamp: (0, index_js_5.unixTimestampSeconds)(call.date)
4412
+ };
4413
+ if (call.status === 'timeout') {
4414
+ if (call.isGroup) {
4415
+ msg.messageStubType = call.isVideo
4416
+ ? index_js_4.WAMessageStubType.CALL_MISSED_GROUP_VIDEO
4417
+ : index_js_4.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
4418
+ }
4419
+ else {
4420
+ msg.messageStubType = call.isVideo ? index_js_4.WAMessageStubType.CALL_MISSED_VIDEO : index_js_4.WAMessageStubType.CALL_MISSED_VOICE;
4421
+ }
4422
+ }
4423
+ else {
4424
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
4425
+ }
4426
+ const protoMsg = index_js_1.proto.WebMessageInfo.fromObject(msg);
4427
+ await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
4428
+ }
4429
+ });
4430
+ /** timestamp of last tctoken prune run — throttles to once per 24h */
4431
+ let lastTcTokenPruneTs = 0;
4432
+ /** dedupe in-flight 463 recovery token issuance by target JID */
4433
+ const inFlight463Recoveries = new Set();
4434
+ ev.on('connection.update', ({ isOnline, connection }) => {
4435
+ if (typeof isOnline !== 'undefined') {
4436
+ sendActiveReceipts = isOnline;
4437
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
4438
+ }
4439
+ // Flush pending tctoken index save on disconnect to avoid writing after close
4440
+ if (connection === 'close' && tcTokenIndexTimer) {
4441
+ clearTimeout(tcTokenIndexTimer);
4442
+ tcTokenIndexTimer = undefined;
4443
+ // Best-effort flush — may fail if store is already closed
4444
+ try {
4445
+ void Promise.resolve(flushTcTokenIndex()).catch(() => { });
4446
+ }
4447
+ catch {
4448
+ /* ignore sync errors */
4449
+ }
4450
+ }
4451
+ // Prune expired tctokens when coming online, at most once per 24 hours
4452
+ // Matches WA Web's CLEAN_TC_TOKENS task
4453
+ // Note: don't gate on tcTokenKnownJids.size — the index may still be loading
4454
+ if (isOnline) {
4455
+ const now = Date.now();
4456
+ const DAY_MS = 24 * 60 * 60 * 1000;
4457
+ if (now - lastTcTokenPruneTs >= DAY_MS) {
4458
+ lastTcTokenPruneTs = now;
4459
+ void pruneExpiredTcTokens();
4460
+ }
4461
+ }
4462
+ });
4463
+ registerSocketEndHandler(() => {
4464
+ if (!config.msgRetryCounterCache && msgRetryCache.close) {
4465
+ msgRetryCache.close();
4466
+ }
4467
+ if (!config.callOfferCache && callOfferCache.close) {
4468
+ callOfferCache.close();
4469
+ }
4470
+ identityAssertDebounce.flushAll();
4471
+ sendActiveReceipts = false;
4472
+ });
4473
+ async function pruneExpiredTcTokens() {
4474
+ try {
4475
+ await tcTokenIndexLoaded;
4476
+ // Union with the persisted index picks up JIDs added by other layers
4477
+ // (history sync) without needing inter-module wiring.
4478
+ const persisted = await (0, tc_token_utils_js_1.readTcTokenIndex)(authState.keys);
4479
+ const allJids = new Set(tcTokenKnownJids);
4480
+ for (const jid of persisted)
4481
+ allJids.add(jid);
4482
+ if (!allJids.size)
4483
+ return;
4484
+ const jids = [...allJids];
4485
+ const allTokens = await authState.keys.get('tctoken', jids);
4486
+ const writes = {};
4487
+ const survivors = new Set();
4488
+ let mutated = 0;
4489
+ for (const jid of jids) {
4490
+ const entry = allTokens[jid];
4491
+ if (!entry) {
4492
+ // Tracked but nothing in store — drop from index.
4493
+ mutated++;
4494
+ continue;
4495
+ }
4496
+ const hasPeerToken = !!entry.token?.length;
4497
+ const peerTokenExpired = hasPeerToken && (0, tc_token_utils_js_1.isTcTokenExpired)(entry.timestamp);
4498
+ const hasSenderTs = entry.senderTimestamp !== undefined;
4499
+ const senderTsExpired = hasSenderTs && (0, tc_token_utils_js_1.isTcTokenExpired)(entry.senderTimestamp);
4500
+ const keepPeerToken = hasPeerToken && !peerTokenExpired;
4501
+ const keepSenderTs = hasSenderTs && !senderTsExpired;
4502
+ if (!keepPeerToken && !keepSenderTs) {
4503
+ writes[jid] = null;
4504
+ mutated++;
4505
+ }
4506
+ else if (peerTokenExpired && keepSenderTs) {
4507
+ writes[jid] = { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp };
4508
+ survivors.add(jid);
4509
+ mutated++;
4510
+ }
4511
+ else {
4512
+ survivors.add(jid);
4513
+ }
4514
+ }
4515
+ if (mutated === 0)
4516
+ return;
4517
+ await authState.keys.set({
4518
+ tctoken: {
4519
+ ...writes,
4520
+ [tc_token_utils_js_1.TC_TOKEN_INDEX_KEY]: {
4521
+ token: Buffer.from(JSON.stringify([...survivors]))
4522
+ }
4523
+ }
4524
+ });
4525
+ tcTokenKnownJids.clear();
4526
+ for (const jid of survivors)
4527
+ tcTokenKnownJids.add(jid);
4528
+ logger.debug({ mutated, remaining: survivors.size }, 'pruned expired tctokens');
4529
+ }
4530
+ catch (err) {
4531
+ logger.warn({ err: err?.message }, 'failed to prune expired tctokens');
4532
+ }
4533
+ }
4534
+ return {
4535
+ ...sock,
4536
+ sendMessageAck,
4537
+ sendRetryRequest,
4538
+ rejectCall,
4539
+ fetchMessageHistory,
4540
+ requestPlaceholderResend,
4541
+ messageRetryManager
4542
+ };
4543
+ };
4544
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;
4545
+
4546
+ return module.exports;
4547
+ })();
4548
+ for (const key of Object.keys(__kageModule135)) {
4549
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule135[key]});
4550
+ }
4551
+ Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule135, configurable:true});