@badzz88/baileys 8.4.6 → 8.4.9

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 (250) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/WAProto.proto +850 -32
  4. package/WAProto/index.d.ts +4913 -25
  5. package/WAProto/index.js +14074 -98
  6. package/package.json +96 -131
  7. package/src/Defaults/index.js +201 -0
  8. package/src/Defaults/phonenumber-mcc.json +223 -0
  9. package/src/Signal/Group/ciphertext-message.js +15 -0
  10. package/src/Signal/Group/group-session-builder.js +92 -0
  11. package/src/Signal/Group/group_cipher.js +89 -0
  12. package/src/Signal/Group/index.js +136 -0
  13. package/src/Signal/Group/keyhelper.js +73 -0
  14. package/src/Signal/Group/sender-chain-key.js +32 -0
  15. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/src/Signal/Group/sender-key-message.js +69 -0
  17. package/src/Signal/Group/sender-key-name.js +50 -0
  18. package/src/Signal/Group/sender-key-record.js +44 -0
  19. package/src/Signal/Group/sender-key-state.js +97 -0
  20. package/src/Signal/Group/sender-message-key.js +30 -0
  21. package/src/Signal/libsignal.js +470 -0
  22. package/src/Signal/lid-mapping.js +262 -0
  23. package/src/Socket/Client/index.js +30 -0
  24. package/src/Socket/Client/types.js +13 -0
  25. package/src/Socket/Client/websocket.js +62 -0
  26. package/src/Socket/aigroups.js +240 -0
  27. package/src/Socket/business.js +422 -0
  28. package/src/Socket/chats.js +2374 -0
  29. package/src/Socket/communities.js +580 -0
  30. package/src/Socket/graphql.js +915 -0
  31. package/src/Socket/groups.js +812 -0
  32. package/src/Socket/index.js +37 -0
  33. package/src/Socket/interactive-handler.js +579 -0
  34. package/src/Socket/interop.js +566 -0
  35. package/src/Socket/managed-account.js +214 -0
  36. package/src/Socket/messages-recv.js +3012 -0
  37. package/src/Socket/messages-send.js +2163 -0
  38. package/{lib → src}/Socket/mex.js +11 -5
  39. package/src/Socket/newsletter.js +1057 -0
  40. package/src/Socket/privacy.js +452 -0
  41. package/src/Socket/registration.js +434 -0
  42. package/src/Socket/socket.js +1079 -0
  43. package/src/Socket/text-router.js +67 -0
  44. package/src/Socket/username.js +234 -0
  45. package/src/Store/index.js +36 -0
  46. package/src/Store/make-cache-manager-store.js +90 -0
  47. package/src/Store/make-in-memory-store.js +506 -0
  48. package/src/Store/make-ordered-dictionary.js +81 -0
  49. package/src/Store/object-repository.js +29 -0
  50. package/src/Types/Auth.js +38 -0
  51. package/src/Types/Bussines.js +2 -0
  52. package/src/Types/Call.js +2 -0
  53. package/src/Types/Chat.js +4 -0
  54. package/src/Types/Contact.js +2 -0
  55. package/src/Types/Events.js +2 -0
  56. package/src/Types/GroupMetadata.js +2 -0
  57. package/src/Types/Label.js +27 -0
  58. package/src/Types/LabelAssociation.js +9 -0
  59. package/src/Types/Message.js +95 -0
  60. package/src/Types/Newsletter.js +152 -0
  61. package/src/Types/Product.js +2 -0
  62. package/src/Types/Signal.js +2 -0
  63. package/src/Types/Socket.js +2 -0
  64. package/src/Types/State.js +70 -0
  65. package/src/Types/USync.js +2 -0
  66. package/src/Types/index.js +54 -0
  67. package/src/Utils/auth-utils.js +306 -0
  68. package/src/Utils/browser-utils.js +114 -0
  69. package/src/Utils/business.js +247 -0
  70. package/src/Utils/chat-utils.js +1272 -0
  71. package/src/Utils/consumer-application.js +107 -0
  72. package/src/Utils/crypto.js +125 -0
  73. package/src/Utils/decode-wa-message.js +808 -0
  74. package/src/Utils/event-buffer.js +586 -0
  75. package/src/Utils/generics.js +640 -0
  76. package/src/Utils/group-history.js +60 -0
  77. package/src/Utils/history.js +244 -0
  78. package/src/Utils/identity-change-handler.js +52 -0
  79. package/src/Utils/index.js +53 -0
  80. package/src/Utils/jid-display-normalization.js +218 -0
  81. package/src/Utils/link-preview.js +143 -0
  82. package/src/Utils/logger.js +9 -0
  83. package/src/Utils/lt-hash.js +10 -0
  84. package/src/Utils/make-mutex.js +36 -0
  85. package/src/Utils/message-composer.js +479 -0
  86. package/src/Utils/message-inspect.js +400 -0
  87. package/src/Utils/message-retry-manager.js +231 -0
  88. package/src/Utils/messages-media.js +943 -0
  89. package/src/Utils/messages.js +2490 -0
  90. package/src/Utils/meta-ai-msmsg.js +133 -0
  91. package/src/Utils/noise-handler.js +194 -0
  92. package/src/Utils/offline-node-processor.js +42 -0
  93. package/src/Utils/pre-key-manager.js +107 -0
  94. package/src/Utils/process-message.js +1047 -0
  95. package/src/Utils/reporting-utils.js +262 -0
  96. package/src/Utils/signal.js +192 -0
  97. package/src/Utils/stanza-ack.js +74 -0
  98. package/src/Utils/sync-action-utils.js +54 -0
  99. package/src/Utils/tc-token-utils.js +161 -0
  100. package/src/Utils/use-multi-file-auth-state.js +121 -0
  101. package/src/Utils/validate-connection.js +248 -0
  102. package/src/Utils/voip-rekey.js +22 -0
  103. package/src/WABinary/constants.js +1304 -0
  104. package/src/WABinary/decode.js +377 -0
  105. package/src/WABinary/encode.js +58 -0
  106. package/src/WABinary/generic-utils.js +148 -0
  107. package/src/WABinary/index.js +33 -0
  108. package/src/WABinary/jid-utils.js +374 -0
  109. package/src/WABinary/types.js +2 -0
  110. package/src/WAM/BinaryInfo.js +13 -0
  111. package/src/WAM/constants.js +39486 -0
  112. package/src/WAM/encode.js +142 -0
  113. package/src/WAM/index.js +31 -0
  114. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  115. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +100 -0
  116. package/src/WAUSync/Protocols/USyncContactProtocol.js +60 -0
  117. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  118. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  119. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +74 -0
  120. package/src/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  121. package/src/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  122. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  123. package/src/WAUSync/Protocols/USyncStatusProtocol.js +44 -0
  124. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  125. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  126. package/src/WAUSync/Protocols/index.js +40 -0
  127. package/src/WAUSync/USyncBackoff.js +31 -0
  128. package/src/WAUSync/USyncQuery.js +204 -0
  129. package/src/WAUSync/USyncUser.js +58 -0
  130. package/src/WAUSync/index.js +32 -0
  131. package/src/antiban.js +4726 -0
  132. package/{lib → src}/index.js +48 -16
  133. package/lib/Defaults/baileys-version.json +0 -3
  134. package/lib/Defaults/index.js +0 -137
  135. package/lib/Defaults/phonenumber-mcc.json +0 -223
  136. package/lib/Signal/Group/Protocols.js +0 -269
  137. package/lib/Signal/Group/ciphertext-message.js +0 -12
  138. package/lib/Signal/Group/group-session-builder.js +0 -30
  139. package/lib/Signal/Group/group_cipher.js +0 -82
  140. package/lib/Signal/Group/index.js +0 -12
  141. package/lib/Signal/Group/keyhelper.js +0 -18
  142. package/lib/Signal/Group/queue-job.js +0 -57
  143. package/lib/Signal/Group/sender-chain-key.js +0 -26
  144. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  145. package/lib/Signal/Group/sender-key-message.js +0 -66
  146. package/lib/Signal/Group/sender-key-name.js +0 -48
  147. package/lib/Signal/Group/sender-key-record.js +0 -41
  148. package/lib/Signal/Group/sender-key-state.js +0 -84
  149. package/lib/Signal/Group/sender-message-key.js +0 -26
  150. package/lib/Signal/libsignal.js +0 -432
  151. package/lib/Signal/lid-mapping.js +0 -277
  152. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  153. package/lib/Socket/Client/index.js +0 -3
  154. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  155. package/lib/Socket/Client/types.js +0 -11
  156. package/lib/Socket/Client/web-socket-client.js +0 -62
  157. package/lib/Socket/Client/websocket.js +0 -54
  158. package/lib/Socket/business.js +0 -379
  159. package/lib/Socket/chats.js +0 -1193
  160. package/lib/Socket/communities.js +0 -431
  161. package/lib/Socket/community.js +0 -392
  162. package/lib/Socket/dugong.js +0 -637
  163. package/lib/Socket/groups.js +0 -374
  164. package/lib/Socket/index.js +0 -12
  165. package/lib/Socket/luxu.js +0 -387
  166. package/lib/Socket/messages-recv.js +0 -1916
  167. package/lib/Socket/messages-send.js +0 -1459
  168. package/lib/Socket/newsletter.js +0 -253
  169. package/lib/Socket/registration.js +0 -167
  170. package/lib/Socket/socket.js +0 -950
  171. package/lib/Socket/username.js +0 -146
  172. package/lib/Socket/usync.js +0 -69
  173. package/lib/Store/index.js +0 -10
  174. package/lib/Store/keyed-db.js +0 -108
  175. package/lib/Store/make-cache-manager-store.js +0 -85
  176. package/lib/Store/make-in-memory-store.js +0 -198
  177. package/lib/Store/make-ordered-dictionary.js +0 -75
  178. package/lib/Store/object-repository.js +0 -32
  179. package/lib/Types/Auth.js +0 -2
  180. package/lib/Types/Bussines.js +0 -2
  181. package/lib/Types/Call.js +0 -2
  182. package/lib/Types/Chat.js +0 -8
  183. package/lib/Types/Contact.js +0 -2
  184. package/lib/Types/Events.js +0 -2
  185. package/lib/Types/GroupMetadata.js +0 -2
  186. package/lib/Types/Label.js +0 -25
  187. package/lib/Types/LabelAssociation.js +0 -7
  188. package/lib/Types/Message.js +0 -11
  189. package/lib/Types/Mex.js +0 -37
  190. package/lib/Types/Newsletter.js +0 -38
  191. package/lib/Types/Product.js +0 -2
  192. package/lib/Types/Signal.js +0 -2
  193. package/lib/Types/Socket.js +0 -3
  194. package/lib/Types/State.js +0 -56
  195. package/lib/Types/USync.js +0 -2
  196. package/lib/Types/index.js +0 -26
  197. package/lib/Utils/auth-utils.js +0 -302
  198. package/lib/Utils/baileys-event-stream.js +0 -63
  199. package/lib/Utils/browser-utils.js +0 -48
  200. package/lib/Utils/business.js +0 -231
  201. package/lib/Utils/chat-utils.js +0 -873
  202. package/lib/Utils/companion-reg-client-utils.js +0 -35
  203. package/lib/Utils/crypto.js +0 -118
  204. package/lib/Utils/decode-wa-message.js +0 -350
  205. package/lib/Utils/event-buffer.js +0 -622
  206. package/lib/Utils/generics.js +0 -399
  207. package/lib/Utils/history.js +0 -134
  208. package/lib/Utils/identity-change-handler.js +0 -50
  209. package/lib/Utils/index.js +0 -23
  210. package/lib/Utils/link-preview.js +0 -85
  211. package/lib/Utils/logger.js +0 -3
  212. package/lib/Utils/lt-hash.js +0 -8
  213. package/lib/Utils/make-mutex.js +0 -33
  214. package/lib/Utils/message-composer.js +0 -273
  215. package/lib/Utils/message-retry-manager.js +0 -265
  216. package/lib/Utils/messages-media.js +0 -788
  217. package/lib/Utils/messages.js +0 -1260
  218. package/lib/Utils/noise-handler.js +0 -201
  219. package/lib/Utils/offline-node-processor.js +0 -40
  220. package/lib/Utils/pre-key-manager.js +0 -106
  221. package/lib/Utils/process-message.js +0 -630
  222. package/lib/Utils/reporting-utils.js +0 -258
  223. package/lib/Utils/signal.js +0 -202
  224. package/lib/Utils/stanza-ack.js +0 -38
  225. package/lib/Utils/sync-action-utils.js +0 -49
  226. package/lib/Utils/tc-token-utils.js +0 -163
  227. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  228. package/lib/Utils/validate-connection.js +0 -204
  229. package/lib/WABinary/constants.js +0 -1301
  230. package/lib/WABinary/decode.js +0 -262
  231. package/lib/WABinary/encode.js +0 -220
  232. package/lib/WABinary/generic-utils.js +0 -204
  233. package/lib/WABinary/index.js +0 -6
  234. package/lib/WABinary/jid-utils.js +0 -98
  235. package/lib/WABinary/types.js +0 -2
  236. package/lib/WAM/BinaryInfo.js +0 -10
  237. package/lib/WAM/constants.js +0 -22853
  238. package/lib/WAM/encode.js +0 -150
  239. package/lib/WAM/index.js +0 -4
  240. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  241. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  242. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  243. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  244. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  245. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  247. package/lib/WAUSync/Protocols/index.js +0 -6
  248. package/lib/WAUSync/USyncQuery.js +0 -98
  249. package/lib/WAUSync/USyncUser.js +0 -31
  250. package/lib/WAUSync/index.js +0 -4
@@ -0,0 +1,3012 @@
1
+ 'use strict'
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod }
6
+ }
7
+ Object.defineProperty(exports, '__esModule', { value: true })
8
+ exports.makeMessagesRecvSocket = void 0
9
+ const node_cache_1 = __importDefault(require('@cacheable/node-cache'))
10
+ const boom_1 = require('@hapi/boom')
11
+ const crypto_1 = require('crypto')
12
+ const index_js_1 = require('../../WAProto/index.js')
13
+ const Defaults_1 = require('../Defaults')
14
+ const Types_1 = require('../Types')
15
+ const Utils_1 = require('../Utils')
16
+ const jid_display_normalization_1 = require('../Utils/jid-display-normalization')
17
+ const make_mutex_1 = require('../Utils/make-mutex')
18
+ const offline_node_processor_1 = require('../Utils/offline-node-processor')
19
+ const stanza_ack_1 = require('../Utils/stanza-ack')
20
+ const tc_token_utils_1 = require('../Utils/tc-token-utils')
21
+ const WABinary_1 = require('../WABinary')
22
+ const groups_1 = require('./groups')
23
+ const aigroup_1 = require('./aigroups')
24
+ const messages_send_1 = require('./messages-send')
25
+
26
+ const makeMessagesRecvSocket = config => {
27
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } =
28
+ config
29
+ const sock = (0, messages_send_1.makeMessagesSocket)(config)
30
+ const {
31
+ ev,
32
+ authState,
33
+ ws,
34
+ messageMutex,
35
+ notificationMutex,
36
+ receiptMutex,
37
+ signalRepository,
38
+ query,
39
+ upsertMessage,
40
+ resyncAppState,
41
+ onUnexpectedError,
42
+ assertSessions,
43
+ sendNode,
44
+ relayMessage,
45
+ sendReceipt,
46
+ uploadPreKeys,
47
+ sendPeerDataOperationMessage,
48
+ messageRetryManager,
49
+ issuePrivacyTokens,
50
+ getUSyncDevices,
51
+ createParticipantNodes,
52
+ newsletterServerIdCache
53
+ } = sock
54
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
55
+ // Track when the socket fully opens so pending pre-connect messages are treated as history
56
+ const socketCreatedAt = Math.floor(Date.now() / 1000)
57
+ let isConnected = false
58
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
59
+ const retryMutex = (0, make_mutex_1.makeMutex)()
60
+ const msgRetryCache =
61
+ config.msgRetryCounterCache ||
62
+ new node_cache_1.default({
63
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
64
+ useClones: false
65
+ })
66
+ const callOfferCache =
67
+ config.callOfferCache ||
68
+ new node_cache_1.default({
69
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
70
+ useClones: false
71
+ })
72
+ const placeholderResendCache =
73
+ config.placeholderResendCache ||
74
+ new node_cache_1.default({
75
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
76
+ useClones: false
77
+ })
78
+ // Debounce identity-change session refreshes per JID to avoid bursts
79
+ const identityAssertDebounce = new node_cache_1.default({ stdTTL: 5, useClones: false })
80
+ let sendActiveReceipts = false
81
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
82
+ if (!authState.creds.me?.id) {
83
+ throw new boom_1.Boom('Not authenticated')
84
+ }
85
+ const pdoMessage = {
86
+ historySyncOnDemandRequest: {
87
+ chatJid: oldestMsgKey.remoteJid,
88
+ oldestMsgFromMe: oldestMsgKey.fromMe,
89
+ oldestMsgId: oldestMsgKey.id,
90
+ oldestMsgTimestampMs: oldestMsgTimestamp,
91
+ onDemandMsgCount: count
92
+ },
93
+ peerDataOperationRequestType: index_js_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
94
+ }
95
+ return sendPeerDataOperationMessage(pdoMessage)
96
+ }
97
+ const requestPlaceholderResend = async (messageKey, msgData) => {
98
+ if (!authState.creds.me?.id) {
99
+ throw new boom_1.Boom('Not authenticated')
100
+ }
101
+ if (await placeholderResendCache.get(messageKey?.id)) {
102
+ logger.debug({ messageKey }, 'already requested resend')
103
+ return
104
+ } else {
105
+ // Store original message data so PDO response handler can preserve
106
+ // metadata (LID details, timestamps, etc.) that the phone may omit
107
+ await placeholderResendCache.set(messageKey?.id, msgData || true)
108
+ }
109
+ await (0, Utils_1.delay)(2000)
110
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
111
+ logger.debug({ messageKey }, 'message received while resend requested')
112
+ return 'RESOLVED'
113
+ }
114
+ const pdoMessage = {
115
+ placeholderMessageResendRequest: [
116
+ {
117
+ messageKey
118
+ }
119
+ ],
120
+ peerDataOperationRequestType: index_js_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
121
+ }
122
+ setTimeout(async () => {
123
+ if (await placeholderResendCache.get(messageKey?.id)) {
124
+ logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline')
125
+ await placeholderResendCache.del(messageKey?.id)
126
+ }
127
+ }, 8000)
128
+ return sendPeerDataOperationMessage(pdoMessage)
129
+ }
130
+ /**
131
+ * Request a Waffle (Meta-account) linking nonce from the paired phone.
132
+ * The phone responds via a PeerDataOperationRequestResponseMessage containing
133
+ * a WaffleNonceFetchResponse with the nonce needed for Meta account linking.
134
+ */
135
+ const requestWaffleNonce = async () => {
136
+ if (!authState.creds.me?.id) {
137
+ throw new boom_1.Boom('Not authenticated')
138
+ }
139
+ return sendPeerDataOperationMessage({
140
+ peerDataOperationRequestType: index_js_1.proto.Message.PeerDataOperationRequestType.WAFFLE_LINKING_NONCE_FETCH
141
+ })
142
+ }
143
+ /**
144
+ * Request a Companion Canonical User nonce from the paired phone.
145
+ * Used during companion linking to canonicalize the user identity across devices.
146
+ * The phone responds with a CompanionCanonicalUserNonceFetchResponse (nonce + waFbid).
147
+ *
148
+ * @param {string} [registrationTraceId] - Optional trace ID for this registration attempt.
149
+ */
150
+ const requestCompanionCanonicalNonce = async registrationTraceId => {
151
+ if (!authState.creds.me?.id) {
152
+ throw new boom_1.Boom('Not authenticated')
153
+ }
154
+ return sendPeerDataOperationMessage({
155
+ companionCanonicalUserNonceFetchRequest: registrationTraceId ? { registrationTraceId } : {},
156
+ peerDataOperationRequestType:
157
+ index_js_1.proto.Message.PeerDataOperationRequestType.COMPANION_CANONICAL_USER_NONCE_FETCH
158
+ })
159
+ }
160
+ /**
161
+ * Request a Companion Meta nonce from the paired phone.
162
+ * Used during Meta-account companion linking flow.
163
+ * The phone responds with a CompanionMetaNonceFetchResponse (nonce).
164
+ */
165
+ const requestCompanionMetaNonce = async () => {
166
+ if (!authState.creds.me?.id) {
167
+ throw new boom_1.Boom('Not authenticated')
168
+ }
169
+ return sendPeerDataOperationMessage({
170
+ peerDataOperationRequestType: index_js_1.proto.Message.PeerDataOperationRequestType.COMPANION_META_NONCE_FETCH
171
+ })
172
+ }
173
+ // Handles mex notifications (newsletter and group XWA2 property updates).
174
+ // Wire format: notification[type=mex] → <update op_name="..."> → JSON payload in content bytes.
175
+ const handleMexNotification = async node => {
176
+ const updateNodes = (0, WABinary_1.getBinaryNodeChildren)(node, 'update')
177
+ if (!updateNodes.length) {
178
+ logger.debug({ node }, 'mex notification with no update children')
179
+ return
180
+ }
181
+ for (const updateNode of updateNodes) {
182
+ const opName = updateNode.attrs?.op_name
183
+ if (!opName) continue
184
+ let payload
185
+ try {
186
+ const raw = updateNode.content?.text ?? updateNode.content?.toString?.()
187
+ payload = raw ? JSON.parse(raw) : null
188
+ } catch (e) {
189
+ logger.error({ err: e, opName }, 'failed to parse mex update payload')
190
+ continue
191
+ }
192
+ if (!payload?.data) {
193
+ logger.debug({ opName }, 'mex update with no data field')
194
+ continue
195
+ }
196
+ const d = payload.data
197
+ switch (opName) {
198
+ case 'NotificationNewsletterUpdate': {
199
+ // d.xwa2_notify_newsletter_on_metadata_update: { id, thread_metadata: { settings } }
200
+ const upd = d.xwa2_notify_newsletter_on_metadata_update
201
+ if (upd?.id) {
202
+ ev.emit('newsletter-settings.update', {
203
+ id: upd.id,
204
+ update: upd.thread_metadata?.settings ?? {}
205
+ })
206
+ }
207
+ break
208
+ }
209
+ case 'NotificationNewsletterJoin': {
210
+ // d.xwa2_notify_newsletter_on_join: full newsletter metadata on subscribe
211
+ const upd = d.xwa2_notify_newsletter_on_join
212
+ if (upd?.id) {
213
+ ev.emit('newsletter-participants.update', {
214
+ id: upd.id,
215
+ author: node.attrs.from,
216
+ user: (0, WABinary_1.jidNormalizedUser)(node.attrs.from),
217
+ new_role: upd.viewer_metadata?.role ?? 'SUBSCRIBER',
218
+ action: 'join',
219
+ metadata: upd.thread_metadata
220
+ })
221
+ }
222
+ break
223
+ }
224
+ case 'NotificationNewsletterMuteChange': {
225
+ // d.xwa2_notify_newsletter_on_mute_change: { id, mute: "ON"|"OFF" }
226
+ const upd = d.xwa2_notify_newsletter_on_mute_change
227
+ if (upd?.id) {
228
+ ev.emit('newsletter-settings.update', {
229
+ id: upd.id,
230
+ update: { mute: upd.mute }
231
+ })
232
+ }
233
+ break
234
+ }
235
+ case 'NotificationNewsletterUserSettingChange': {
236
+ // d.xwa2_notify_newsletter_on_user_setting_change: { id, setting: { type, value } }
237
+ const upd = d.xwa2_notify_newsletter_on_user_setting_change
238
+ if (upd?.id && upd.setting) {
239
+ ev.emit('newsletter-settings.update', {
240
+ id: upd.id,
241
+ update: { userSetting: upd.setting }
242
+ })
243
+ }
244
+ break
245
+ }
246
+ case 'NotificationNewsletterAdminPromote': {
247
+ // legacy format kept for compat
248
+ const upd = d.xwa2_notify_newsletter_on_admin_promote
249
+ if (upd?.id) {
250
+ ev.emit('newsletter-participants.update', {
251
+ id: upd.id,
252
+ author: node.attrs.from,
253
+ user: upd.user,
254
+ new_role: 'ADMIN',
255
+ action: 'promote'
256
+ })
257
+ }
258
+ break
259
+ }
260
+ case 'NotificationGroupMemberLinkPropertyUpdate': {
261
+ // d.xwa2_notify_group_on_prop_change: { id, properties: { member_link_mode } }
262
+ const upd = d.xwa2_notify_group_on_prop_change
263
+ if (upd?.id && upd.properties?.member_link_mode !== undefined) {
264
+ ev.emit('groups.update', [
265
+ {
266
+ id: upd.id,
267
+ memberAddMode: upd.properties.member_link_mode
268
+ }
269
+ ])
270
+ }
271
+ break
272
+ }
273
+ case 'NotificationGroupLimitSharingPropertyUpdate': {
274
+ // d.xwa2_notify_group_on_prop_change: { id, properties: { limit_sharing } }
275
+ const upd = d.xwa2_notify_group_on_prop_change
276
+ if (upd?.id && upd.properties?.limit_sharing !== undefined) {
277
+ ev.emit('groups.update', [
278
+ {
279
+ id: upd.id,
280
+ limitSharing: upd.properties.limit_sharing
281
+ }
282
+ ])
283
+ }
284
+ break
285
+ }
286
+ case 'NotificationGroupMemberShareGroupHistoryModePropertyUpdate': {
287
+ // d.xwa2_notify_group_on_prop_change: { id, properties: { member_share_group_history_mode } }
288
+ const upd = d.xwa2_notify_group_on_prop_change
289
+ if (upd?.id && upd.properties?.member_share_group_history_mode !== undefined) {
290
+ ev.emit('groups.update', [
291
+ {
292
+ id: upd.id,
293
+ memberShareHistoryMode: upd.properties.member_share_group_history_mode
294
+ }
295
+ ])
296
+ }
297
+ break
298
+ }
299
+ default:
300
+ logger.debug({ opName, from: node.attrs.from }, 'unhandled mex op')
301
+ }
302
+ }
303
+ }
304
+ // Handles newsletter notifications
305
+ const handleNewsletterNotification = async node => {
306
+ const from = node.attrs.from
307
+ const child = (0, WABinary_1.getAllBinaryNodeChildren)(node)[0]
308
+ const author = node.attrs.participant
309
+ logger.info({ from, child }, 'got newsletter notification')
310
+ switch (child.tag) {
311
+ case 'reaction':
312
+ const reactionUpdate = {
313
+ id: from,
314
+ server_id: child.attrs.message_id,
315
+ reaction: {
316
+ code: (0, WABinary_1.getBinaryNodeChildString)(child, 'reaction'),
317
+ count: 1
318
+ }
319
+ }
320
+ ev.emit('newsletter.reaction', reactionUpdate)
321
+ break
322
+ case 'view':
323
+ const viewUpdate = {
324
+ id: from,
325
+ server_id: child.attrs.message_id,
326
+ count: parseInt(child.content?.toString() || '0', 10)
327
+ }
328
+ ev.emit('newsletter.view', viewUpdate)
329
+ break
330
+ case 'participant':
331
+ const participantUpdate = {
332
+ id: from,
333
+ author,
334
+ user: child.attrs.jid,
335
+ action: child.attrs.action,
336
+ new_role: child.attrs.role
337
+ }
338
+ ev.emit('newsletter-participants.update', participantUpdate)
339
+ break
340
+ case 'update':
341
+ const settingsNode = (0, WABinary_1.getBinaryNodeChild)(child, 'settings')
342
+ if (settingsNode) {
343
+ const update = {}
344
+ const nameNode = (0, WABinary_1.getBinaryNodeChild)(settingsNode, 'name')
345
+ if (nameNode?.content) update.name = nameNode.content.toString()
346
+ const descriptionNode = (0, WABinary_1.getBinaryNodeChild)(settingsNode, 'description')
347
+ if (descriptionNode?.content) update.description = descriptionNode.content.toString()
348
+ ev.emit('newsletter-settings.update', {
349
+ id: from,
350
+ update
351
+ })
352
+ }
353
+ break
354
+ case 'message': {
355
+ const viewCount = child.attrs.view_count !== undefined ? +child.attrs.view_count : undefined
356
+ const impressionCount = child.attrs.impression_count !== undefined ? +child.attrs.impression_count : undefined
357
+ const plaintextNode = (0, WABinary_1.getBinaryNodeChild)(child, 'plaintext')
358
+ if (plaintextNode?.content) {
359
+ try {
360
+ const contentBuf =
361
+ typeof plaintextNode.content === 'string'
362
+ ? Buffer.from(plaintextNode.content, 'binary')
363
+ : Buffer.from(plaintextNode.content)
364
+ const messageProto = index_js_1.proto.Message.decode(contentBuf).toJSON()
365
+ const fullMessage = index_js_1.proto.WebMessageInfo.fromObject({
366
+ key: {
367
+ remoteJid: from,
368
+ id: child.attrs.message_id || child.attrs.server_id,
369
+ // always false: this branch only runs for inbound plaintext newsletter posts,
370
+ // which always originate from the channel, never from us
371
+ fromMe: false
372
+ },
373
+ message: messageProto,
374
+ messageTimestamp: +child.attrs.t
375
+ }).toJSON()
376
+ // Attach insight counters when the server includes them
377
+ if (viewCount !== undefined) fullMessage.views = viewCount
378
+ if (impressionCount !== undefined) fullMessage.impressions = impressionCount
379
+ await upsertMessage(fullMessage, 'append')
380
+ logger.info('Processed plaintext newsletter message')
381
+ } catch (error) {
382
+ logger.error({ error }, 'Failed to decode plaintext newsletter message')
383
+ }
384
+ }
385
+ break
386
+ }
387
+ case 'live_updates': {
388
+ // Live engagement updates: reactions + forwards per message.
389
+ // Wire: <live_updates> → <messages t="..."> → <message server_id="...">
390
+ // → <forwards_count count="N">, <reactions> → <reaction code="X" count="N">
391
+ const messagesNode = (0, WABinary_1.getBinaryNodeChild)(child, 'messages')
392
+ const msgTs = messagesNode?.attrs?.t ? +messagesNode.attrs.t : undefined
393
+ for (const msgNode of (0, WABinary_1.getBinaryNodeChildren)(messagesNode ?? child, 'message')) {
394
+ const serverId = msgNode.attrs.server_id
395
+ const fwdNode = (0, WABinary_1.getBinaryNodeChild)(msgNode, 'forwards_count')
396
+ const forwardsCount = fwdNode?.attrs?.count !== undefined ? +fwdNode.attrs.count : undefined
397
+ const reactionsNode = (0, WABinary_1.getBinaryNodeChild)(msgNode, 'reactions')
398
+ const reactions = (0, WABinary_1.getBinaryNodeChildren)(reactionsNode ?? msgNode, 'reaction').map(r => ({
399
+ code: r.attrs.code,
400
+ count: +r.attrs.count
401
+ }))
402
+ ev.emit('newsletter.live-update', {
403
+ id: from,
404
+ server_id: serverId,
405
+ timestamp: msgTs,
406
+ forwardsCount,
407
+ reactions
408
+ })
409
+ }
410
+ break
411
+ }
412
+ case 'pin': {
413
+ const pinnedServerId = child.attrs.message_id || child.attrs.server_id
414
+ const isPinned = child.attrs.action !== 'unpin'
415
+ ev.emit('newsletter.pin', {
416
+ id: from,
417
+ server_id: pinnedServerId,
418
+ pinned: isPinned
419
+ })
420
+ // Sync the pinnedMessage field on the newsletter metadata object
421
+ ev.emit('newsletters.update', [{ id: from, pinnedMessage: isPinned ? pinnedServerId : null }])
422
+ break
423
+ }
424
+ case 'category':
425
+ ev.emit('newsletter-settings.update', {
426
+ id: from,
427
+ update: { category: child.attrs.value || child.content?.toString() }
428
+ })
429
+ break
430
+ case 'invite':
431
+ ev.emit('newsletter.invite', {
432
+ id: from,
433
+ inviteCode: child.attrs.code,
434
+ inviter: child.attrs.jid || author,
435
+ role: child.attrs.role || 'SUBSCRIBER'
436
+ })
437
+ break
438
+ default:
439
+ logger.warn({ node }, 'Unknown newsletter notification')
440
+ break
441
+ }
442
+ }
443
+ // Handles incoming <status> stanzas pushed by the server for newsletter posts.
444
+ // These arrive on the CB:status channel (AB-gated by status_e2ee_recv_over_status_stanza).
445
+ const handleNewsletterStatus = async node => {
446
+ const { id, from, server_id, t, is_sender, offline, type, edit } = node.attrs
447
+ const serverId = server_id ? +server_id : undefined
448
+ const timestamp = t ? +t : undefined
449
+ const isSender = is_sender === 'true'
450
+ const offlineIndex = offline !== undefined ? +offline : undefined
451
+ // Cache messageId → serverId so the bot can look up server_id when a message is quoted
452
+ if (id && serverId != null) {
453
+ newsletterServerIdCache?.set(id, serverId)
454
+ }
455
+
456
+ // Parse optional <meta> child: edit timestamps, interaction type, admin profile
457
+ const metaNode = (0, WABinary_1.getBinaryNodeChild)(node, 'meta')
458
+ const meta = metaNode
459
+ ? {
460
+ ...(metaNode.attrs.msg_edit_t ? { editedAt: +metaNode.attrs.msg_edit_t } : {}),
461
+ ...(metaNode.attrs.original_msg_t ? { originalTimestamp: +metaNode.attrs.original_msg_t } : {}),
462
+ ...(metaNode.attrs.interaction_type ? { interactionType: metaNode.attrs.interaction_type } : {}),
463
+ ...(metaNode.attrs.parent_server_id ? { parentServerId: +metaNode.attrs.parent_server_id } : {}),
464
+ ...(metaNode.attrs.response_server_id ? { responseServerId: +metaNode.attrs.response_server_id } : {})
465
+ }
466
+ : undefined
467
+
468
+ // Parse engagement counters
469
+ const viewsNode = (0, WABinary_1.getBinaryNodeChild)(node, 'views_count')
470
+ const viewsCount = viewsNode?.attrs?.count !== undefined ? +viewsNode.attrs.count : undefined
471
+ const responsesNode = (0, WABinary_1.getBinaryNodeChild)(node, 'responses_count')
472
+ const responsesCount = responsesNode?.attrs?.count !== undefined ? +responsesNode.attrs.count : undefined
473
+ const reactionsNode = (0, WABinary_1.getBinaryNodeChild)(node, 'reactions')
474
+ const reactionCounts = (0, WABinary_1.getBinaryNodeChildren)(reactionsNode ?? { content: [] }, 'reaction').map(
475
+ r => ({ code: r.attrs.code, count: +r.attrs.count })
476
+ )
477
+
478
+ let content = null
479
+ let mediaType = undefined
480
+
481
+ if (type === 'reaction') {
482
+ const reactionNode = (0, WABinary_1.getBinaryNodeChild)(node, 'reaction')
483
+ content = { type: 'reaction', code: reactionNode?.attrs?.code }
484
+ } else if (type === 'text' || type === 'media') {
485
+ const plaintextNode = (0, WABinary_1.getBinaryNodeChild)(node, 'plaintext')
486
+ if (type === 'media') mediaType = plaintextNode?.attrs?.mediatype
487
+ if (edit === '7' || edit === '8') {
488
+ content = { type: 'revoke', edit }
489
+ } else if (plaintextNode?.content) {
490
+ try {
491
+ const buf = Buffer.isBuffer(plaintextNode.content)
492
+ ? plaintextNode.content
493
+ : Buffer.from(plaintextNode.content)
494
+ const message = index_js_1.proto.Message.decode(buf).toJSON()
495
+ content = { type, message, ...(mediaType ? { mediaType } : {}) }
496
+ } catch (err) {
497
+ logger.error({ err }, 'Failed to decode newsletter status plaintext')
498
+ content = { type, raw: true, ...(mediaType ? { mediaType } : {}) }
499
+ }
500
+ }
501
+ }
502
+
503
+ // Send ACK back to server
504
+ const ackType = type === 'reaction' ? 'reaction' : edit ? 'revoke' : type
505
+ await sendNode({
506
+ tag: 'ack',
507
+ attrs: { id, to: from, class: 'status', type: ackType || 'text' },
508
+ content: undefined
509
+ })
510
+
511
+ ev.emit('newsletter.status', {
512
+ id: from,
513
+ messageId: id,
514
+ serverId,
515
+ timestamp,
516
+ isSender,
517
+ ...(offlineIndex !== undefined ? { offlineIndex } : {}),
518
+ ...(meta ? { meta } : {}),
519
+ ...(viewsCount !== undefined ? { viewsCount } : {}),
520
+ ...(responsesCount !== undefined ? { responsesCount } : {}),
521
+ ...(reactionCounts.length ? { reactionCounts } : {}),
522
+ content
523
+ })
524
+ }
525
+ const sendMessageAck = async (node, errorCode) => {
526
+ const stanza = (0, stanza_ack_1.buildAckStanza)(node, errorCode, authState.creds.me.id)
527
+ logger.debug({ recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs }, 'sent ack')
528
+ await sendNode(stanza)
529
+ }
530
+
531
+ const offerCall = async (toJid, isVideo = false) => {
532
+ const callId = crypto_1.randomBytes(16).toString('hex').toUpperCase().substring(0, 64)
533
+ const offerContent = []
534
+ offerContent.push({
535
+ tag: 'audio',
536
+ attrs: { enc: 'opus', rate: '16000' },
537
+ content: undefined
538
+ })
539
+ offerContent.push({
540
+ tag: 'audio',
541
+ attrs: { enc: 'opus', rate: '8000' },
542
+ content: undefined
543
+ })
544
+
545
+ if (isVideo) {
546
+ offerContent.push({
547
+ tag: 'video',
548
+ attrs: {
549
+ enc: 'vp8',
550
+ dec: 'vp8',
551
+ orientation: '0',
552
+ screen_width: '1920',
553
+ screen_height: '1080',
554
+ device_orientation: '0'
555
+ },
556
+ content: undefined
557
+ })
558
+ }
559
+ offerContent.push({
560
+ tag: 'net',
561
+ attrs: { medium: '3' },
562
+ content: undefined
563
+ })
564
+ offerContent.push({
565
+ tag: 'capability',
566
+ attrs: { ver: '1' },
567
+ content: new Uint8Array([1, 4, 255, 131, 207, 4])
568
+ })
569
+ offerContent.push({
570
+ tag: 'encopt',
571
+ attrs: { keygen: '2' },
572
+ content: undefined
573
+ })
574
+
575
+ const encKey = crypto_1.randomBytes(32)
576
+ const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) =>
577
+ WABinary_1.jidEncode(user, 's.whatsapp.net', device)
578
+ )
579
+ await assertSessions(devices, true)
580
+
581
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(
582
+ devices,
583
+ {
584
+ call: {
585
+ callKey: new Uint8Array(encKey)
586
+ }
587
+ },
588
+ { count: '0' }
589
+ )
590
+ offerContent.push({ tag: 'destination', attrs: {}, content: destinations })
591
+
592
+ if (shouldIncludeDeviceIdentity) {
593
+ offerContent.push({
594
+ tag: 'device-identity',
595
+ attrs: {},
596
+ content: Utils_1.encodeSignedDeviceIdentity(authState.creds.account, true)
597
+ })
598
+ }
599
+
600
+ const stanza = {
601
+ tag: 'call',
602
+ attrs: {
603
+ id: Utils_1.generateMessageID(),
604
+ to: toJid
605
+ },
606
+ content: [
607
+ {
608
+ tag: 'offer',
609
+ attrs: {
610
+ 'call-id': callId,
611
+ 'call-creator': authState.creds.me.id
612
+ },
613
+ content: offerContent
614
+ }
615
+ ]
616
+ }
617
+
618
+ await query(stanza)
619
+
620
+ return {
621
+ id: callId,
622
+ to: toJid
623
+ }
624
+ }
625
+
626
+ const rejectCall = async (callId, callFrom) => {
627
+ const stanza = {
628
+ tag: 'call',
629
+ attrs: {
630
+ from: authState.creds.me.id,
631
+ to: callFrom
632
+ },
633
+ content: [
634
+ {
635
+ tag: 'reject',
636
+ attrs: {
637
+ 'call-id': callId,
638
+ 'call-creator': callFrom,
639
+ count: '0'
640
+ },
641
+ content: undefined
642
+ }
643
+ ]
644
+ }
645
+ await query(stanza)
646
+ }
647
+
648
+ const acceptCall = async (callId, callFrom) => {
649
+ const stanza = {
650
+ tag: 'call',
651
+ attrs: {
652
+ from: authState.creds.me.id,
653
+ to: callFrom
654
+ },
655
+ content: [
656
+ {
657
+ tag: 'accept',
658
+ attrs: {
659
+ 'call-id': callId,
660
+ 'call-creator': callFrom,
661
+ count: '0'
662
+ },
663
+ content: undefined
664
+ }
665
+ ]
666
+ }
667
+ await query(stanza)
668
+ }
669
+
670
+ const terminateCall = async (callId, callFrom) => {
671
+ const stanza = {
672
+ tag: 'call',
673
+ attrs: {
674
+ from: authState.creds.me.id,
675
+ to: callFrom
676
+ },
677
+ content: [
678
+ {
679
+ tag: 'terminate',
680
+ attrs: {
681
+ 'call-id': callId,
682
+ 'call-creator': callFrom,
683
+ reason: 'user-terminated',
684
+ count: '0'
685
+ },
686
+ content: undefined
687
+ }
688
+ ]
689
+ }
690
+ await query(stanza)
691
+ }
692
+
693
+ /**
694
+ * Re-encrypt call key for a device that reconnected mid-call.
695
+ * Source: OutgoingSignalingHandler.java enc_rekey / rekeyEncryptionTask
696
+ *
697
+ * @param {string} callId - Active call ID
698
+ * @param {string} callFrom - JID of the call creator
699
+ * @param {Buffer} encryptedKeyBytes - Re-encrypted call session key bytes
700
+ * @param {number} [count=0] - Retry counter (0–4)
701
+ */
702
+ const rekeyCall = async (callId, callFrom, encryptedKeyBytes, count = 0) => {
703
+ const stanza = {
704
+ tag: 'call',
705
+ attrs: {
706
+ from: authState.creds.me.id,
707
+ to: callFrom
708
+ },
709
+ content: [
710
+ {
711
+ tag: 'enc_rekey',
712
+ attrs: {
713
+ 'call-id': callId,
714
+ 'call-creator': callFrom,
715
+ count: count.toString()
716
+ },
717
+ content: [
718
+ {
719
+ tag: 'enc',
720
+ attrs: { v: '2', type: 'msg' },
721
+ content: encryptedKeyBytes
722
+ }
723
+ ]
724
+ }
725
+ ]
726
+ }
727
+ await query(stanza)
728
+ }
729
+
730
+ /**
731
+ * Join a call via an invite link.
732
+ * Source: OutgoingSignalingHandler.java link_join tag
733
+ *
734
+ * @param {string} callId - Call ID from the link
735
+ * @param {string} callCreator - JID of the call creator
736
+ * @param {string} linkToken - Token from the call link
737
+ */
738
+ const joinCallLink = async (callId, callCreator, linkToken) => {
739
+ const stanza = {
740
+ tag: 'call',
741
+ attrs: {
742
+ from: authState.creds.me.id,
743
+ to: callCreator
744
+ },
745
+ content: [
746
+ {
747
+ tag: 'link_join',
748
+ attrs: {
749
+ 'call-id': callId,
750
+ 'call-creator': callCreator,
751
+ token: linkToken
752
+ },
753
+ content: undefined
754
+ }
755
+ ]
756
+ }
757
+ await query(stanza)
758
+ }
759
+
760
+ /**
761
+ * Query info about a call link before joining.
762
+ * Source: OutgoingSignalingHandler.java link_query tag
763
+ *
764
+ * @param {string} callLinkCode - The call link code to query
765
+ * @param {string} to - JID to send the query to
766
+ */
767
+ const queryCallLink = async (callLinkCode, to) => {
768
+ const stanza = {
769
+ tag: 'call',
770
+ attrs: {
771
+ from: authState.creds.me.id,
772
+ to
773
+ },
774
+ content: [
775
+ {
776
+ tag: 'link_query',
777
+ attrs: { code: callLinkCode },
778
+ content: undefined
779
+ }
780
+ ]
781
+ }
782
+ return query(stanza)
783
+ }
784
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
785
+ const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '')
786
+ const { key: msgKey } = fullMessage
787
+ const msgId = msgKey.id
788
+ if (messageRetryManager) {
789
+ // Check if we've exceeded max retries using the new system
790
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
791
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing')
792
+ messageRetryManager.markRetryFailed(msgId)
793
+ return
794
+ }
795
+ // Increment retry count using new system
796
+ const retryCount = messageRetryManager.incrementRetryCount(msgId)
797
+ // Use the new retry count for the rest of the logic
798
+ const key = `${msgId}:${msgKey?.participant}`
799
+ await msgRetryCache.set(key, retryCount)
800
+ } else {
801
+ // Fallback to old system
802
+ const key = `${msgId}:${msgKey?.participant}`
803
+ let retryCount = (await msgRetryCache.get(key)) || 0
804
+ if (retryCount >= maxMsgRetryCount) {
805
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing')
806
+ await msgRetryCache.del(key)
807
+ return
808
+ }
809
+ retryCount += 1
810
+ await msgRetryCache.set(key, retryCount)
811
+ }
812
+ const key = `${msgId}:${msgKey?.participant}`
813
+ const retryCount = (await msgRetryCache.get(key)) || 1
814
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
815
+ const fromJid = node.attrs.from
816
+ // Check if we should recreate the session
817
+ let shouldRecreateSession = false
818
+ let recreateReason = ''
819
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
820
+ try {
821
+ // Check if we have a session with this JID
822
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid)
823
+ const hasSession = await signalRepository.validateSession(fromJid)
824
+ const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists)
825
+ shouldRecreateSession = result.recreate
826
+ recreateReason = result.reason
827
+ if (shouldRecreateSession) {
828
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry')
829
+ // Delete existing session to force recreation
830
+ await authState.keys.set({ session: { [sessionId]: null } })
831
+ forceIncludeKeys = true
832
+ }
833
+ } catch (error) {
834
+ logger.warn({ error, fromJid }, 'failed to check session recreation')
835
+ }
836
+ }
837
+ if (retryCount <= 2) {
838
+ // Use new retry manager for phone requests if available
839
+ if (messageRetryManager) {
840
+ // Schedule phone request with delay (like whatsmeow)
841
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
842
+ try {
843
+ const requestId = await requestPlaceholderResend(msgKey)
844
+ logger.debug(
845
+ `sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`
846
+ )
847
+ } catch (error) {
848
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request')
849
+ }
850
+ })
851
+ } else {
852
+ // Fallback to immediate request
853
+ const msgId = await requestPlaceholderResend(msgKey)
854
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`)
855
+ }
856
+ }
857
+ const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true)
858
+ await authState.keys.transaction(async () => {
859
+ const receipt = {
860
+ tag: 'receipt',
861
+ attrs: {
862
+ id: msgId,
863
+ type: 'retry',
864
+ to: node.attrs.from
865
+ },
866
+ content: [
867
+ {
868
+ tag: 'retry',
869
+ attrs: {
870
+ count: retryCount.toString(),
871
+ id: node.attrs.id,
872
+ t: node.attrs.t,
873
+ v: '1',
874
+ // Confirmed from live capture: real retry receipts carry error="1"
875
+ // in the overwhelming majority of samples (1270/1273); "0" never observed.
876
+ error: '1'
877
+ }
878
+ },
879
+ {
880
+ tag: 'registration',
881
+ attrs: {},
882
+ content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
883
+ }
884
+ ]
885
+ }
886
+ if (node.attrs.recipient) {
887
+ receipt.attrs.recipient = node.attrs.recipient
888
+ }
889
+ if (node.attrs.participant) {
890
+ receipt.attrs.participant = node.attrs.participant
891
+ }
892
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
893
+ const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1)
894
+ const [keyId] = Object.keys(preKeys)
895
+ const key = preKeys[+keyId]
896
+ const content = receipt.content
897
+ content.push({
898
+ tag: 'keys',
899
+ attrs: {},
900
+ content: [
901
+ { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
902
+ { tag: 'identity', attrs: {}, content: identityKey.public },
903
+ (0, Utils_1.xmppPreKey)(key, +keyId),
904
+ (0, Utils_1.xmppSignedPreKey)(signedPreKey),
905
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
906
+ ]
907
+ })
908
+ ev.emit('creds.update', update)
909
+ }
910
+ await sendNode(receipt)
911
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt')
912
+ }, authState?.creds?.me?.id || 'sendRetryRequest')
913
+ }
914
+ /**
915
+ * Fire-and-forget tctoken re-issuance after a peer's device identity changed.
916
+ * Runs in parallel with the session refresh (not after it).
917
+ */
918
+ const reissueTcTokenAfterIdentityChange = from => {
919
+ void (async () => {
920
+ const normalizedJid = (0, WABinary_1.jidNormalizedUser)(from)
921
+ const tcJid = await (0, tc_token_utils_1.resolveTcTokenJid)(normalizedJid, getLIDForPN)
922
+ const tcTokenData = await authState.keys.get('tctoken', [tcJid])
923
+ const senderTs = tcTokenData?.[tcJid]?.senderTimestamp
924
+ if (senderTs == null || (0, tc_token_utils_1.isTcTokenExpired)(senderTs)) {
925
+ return
926
+ }
927
+ logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken')
928
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
929
+ const issueJid = await (0, tc_token_utils_1.resolveIssuanceJid)(
930
+ normalizedJid,
931
+ sock.serverProps.lidTrustedTokenIssueToLid,
932
+ getLIDForPN,
933
+ getPNForLID
934
+ )
935
+ const result = await issuePrivacyTokens([issueJid], senderTs)
936
+ await (0, tc_token_utils_1.storeTcTokensFromIqResult)({
937
+ result,
938
+ fallbackJid: tcJid,
939
+ keys: authState.keys,
940
+ getLIDForPN,
941
+ onNewJidStored: trackTcTokenJid
942
+ })
943
+ })().catch(err => {
944
+ logger.debug({ jid: from, err: err?.message }, 'failed to re-issue tctoken after identity change')
945
+ })
946
+ }
947
+ const handleEncryptNotification = async node => {
948
+ const from = node.attrs.from
949
+ if (from === WABinary_1.S_WHATSAPP_NET) {
950
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count')
951
+ const count = +countChild.attrs.value
952
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT
953
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count')
954
+ if (shouldUploadMorePreKeys) {
955
+ await uploadPreKeys()
956
+ }
957
+ } else {
958
+ const result = await (0, Utils_1.handleIdentityChange)(node, {
959
+ meId: authState.creds.me?.id,
960
+ meLid: authState.creds.me?.lid,
961
+ validateSession: signalRepository.validateSession,
962
+ assertSessions,
963
+ debounceCache: identityAssertDebounce,
964
+ logger,
965
+ onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
966
+ })
967
+ if (result.action === 'no_identity_node') {
968
+ logger.info({ node }, 'unknown encrypt notification')
969
+ }
970
+ }
971
+ }
972
+ // Group participant nodes carry authoritative LID<->PN pairs (jid + phone_number/lid
973
+ // attrs). Persist them so PN<->LID resolution elsewhere doesn't need a usync round trip.
974
+ const storeParticipantLidPairs = participants => {
975
+ const pairs = []
976
+ for (const p of participants || []) {
977
+ if (p.phoneNumber) pairs.push({ lid: p.id, pn: p.phoneNumber })
978
+ else if (p.lid) pairs.push({ lid: p.lid, pn: p.id })
979
+ }
980
+ if (!pairs.length) return
981
+ signalRepository.lidMapping
982
+ .storeLIDPNMappings(pairs)
983
+ .catch(error => logger.debug({ error }, 'failed to store LID/PN mappings from group notification'))
984
+ }
985
+ const handleGroupNotification = (fullNode, child, msg) => {
986
+ // PN/LID: acting + affected participant already resolved below via participant_pn/lid attrs
987
+ const actingParticipantLid = fullNode.attrs.participant
988
+ const actingParticipantPn = fullNode.attrs.participant_pn
989
+ const actingParticipantUsername = fullNode.attrs.participant_username
990
+ const affectedParticipantLid =
991
+ (0, WABinary_1.getBinaryNodeChild)(child, 'participant')?.attrs?.jid || actingParticipantLid
992
+ const affectedParticipantPn =
993
+ (0, WABinary_1.getBinaryNodeChild)(child, 'participant')?.attrs?.phone_number || actingParticipantPn
994
+ switch (child?.tag) {
995
+ case 'create':
996
+ const metadata = (0, groups_1.extractGroupMetadata)(child)
997
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE
998
+ msg.messageStubParameters = [metadata.subject]
999
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn }
1000
+ storeParticipantLidPairs(metadata.participants)
1001
+ ev.emit('chats.upsert', [
1002
+ {
1003
+ id: metadata.id,
1004
+ name: metadata.subject,
1005
+ conversationTimestamp: metadata.creation
1006
+ }
1007
+ ])
1008
+ ev.emit('groups.upsert', [
1009
+ {
1010
+ ...metadata,
1011
+ author: actingParticipantLid,
1012
+ authorPn: actingParticipantPn,
1013
+ authorUsername: actingParticipantUsername
1014
+ }
1015
+ ])
1016
+ break
1017
+ case 'ephemeral':
1018
+ case 'not_ephemeral':
1019
+ msg.message = {
1020
+ protocolMessage: {
1021
+ type: index_js_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
1022
+ ephemeralExpiration: +(child.attrs.expiration || 0)
1023
+ }
1024
+ }
1025
+ break
1026
+ case 'modify':
1027
+ const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid)
1028
+ msg.messageStubParameters = oldNumber || []
1029
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER
1030
+ break
1031
+ case 'promote':
1032
+ case 'demote':
1033
+ case 'remove':
1034
+ case 'add':
1035
+ case 'leave':
1036
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`
1037
+ msg.messageStubType = Types_1.WAMessageStubType[stubType]
1038
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(({ attrs }) => {
1039
+ return {
1040
+ id: attrs.jid,
1041
+ phoneNumber:
1042
+ (0, WABinary_1.isLidUser)(attrs.jid) && (0, WABinary_1.isPnUser)(attrs.phone_number)
1043
+ ? attrs.phone_number
1044
+ : undefined,
1045
+ lid: (0, WABinary_1.isPnUser)(attrs.jid) && (0, WABinary_1.isLidUser)(attrs.lid) ? attrs.lid : undefined,
1046
+ username: attrs.participant_username || attrs.username || undefined,
1047
+ admin: attrs.type || null,
1048
+ uuid: attrs.uuid || attrs.participant_uuid || undefined
1049
+ }
1050
+ })
1051
+ if (
1052
+ participants.length === 1 &&
1053
+ // if recv. "remove" message and sender removed themselves
1054
+ // mark as left
1055
+ ((0, WABinary_1.areJidsSameUser)(participants[0].id, actingParticipantLid) ||
1056
+ (0, WABinary_1.areJidsSameUser)(participants[0].id, actingParticipantPn)) &&
1057
+ child.tag === 'remove'
1058
+ ) {
1059
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE
1060
+ }
1061
+ storeParticipantLidPairs(participants)
1062
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a))
1063
+ break
1064
+ case 'subject':
1065
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT
1066
+ msg.messageStubParameters = [child.attrs.subject]
1067
+ break
1068
+ case 'description':
1069
+ const description = (0, WABinary_1.getBinaryNodeChild)(child, 'body')?.content?.toString()
1070
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION
1071
+ msg.messageStubParameters = description ? [description] : undefined
1072
+ break
1073
+ case 'announcement':
1074
+ case 'not_announcement':
1075
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE
1076
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off']
1077
+ break
1078
+ case 'locked':
1079
+ case 'unlocked':
1080
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT
1081
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off']
1082
+ break
1083
+ case 'invite':
1084
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK
1085
+ msg.messageStubParameters = [child.attrs.code]
1086
+ break
1087
+ case 'member_add_mode':
1088
+ const addMode = child.content
1089
+ if (addMode) {
1090
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE
1091
+ msg.messageStubParameters = [addMode.toString()]
1092
+ }
1093
+ break
1094
+ case 'membership_approval_mode':
1095
+ const approvalMode = (0, WABinary_1.getBinaryNodeChild)(child, 'group_join')
1096
+ if (approvalMode) {
1097
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE
1098
+ msg.messageStubParameters = [approvalMode.attrs.state]
1099
+ }
1100
+ break
1101
+ case 'created_membership_requests':
1102
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
1103
+ msg.messageStubParameters = [
1104
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
1105
+ 'created',
1106
+ child.attrs.request_method
1107
+ ]
1108
+ break
1109
+ case 'revoked_membership_requests':
1110
+ const isDenied = (0, WABinary_1.areJidsSameUser)(affectedParticipantLid, actingParticipantLid)
1111
+ if ((0, WABinary_1.isLidUser)(affectedParticipantLid) && (0, WABinary_1.isPnUser)(affectedParticipantPn)) {
1112
+ storeParticipantLidPairs([{ id: affectedParticipantLid, phoneNumber: affectedParticipantPn }])
1113
+ }
1114
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
1115
+ msg.messageStubParameters = [
1116
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
1117
+ isDenied ? 'revoked' : 'rejected'
1118
+ ]
1119
+ break
1120
+ case 'sibling_link': {
1121
+ const linkedGroupJid = (0, WABinary_1.getBinaryNodeChild)(child, 'group')?.attrs?.jid || child.attrs?.jid
1122
+ ev.emit('groups.update', [
1123
+ {
1124
+ id: fullNode.attrs.from,
1125
+ siblingGroupLinked: linkedGroupJid || true,
1126
+ author: actingParticipantLid,
1127
+ authorPn: actingParticipantPn
1128
+ }
1129
+ ])
1130
+ break
1131
+ }
1132
+ case 'sibling_unlink': {
1133
+ const unlinkedGroupJid = (0, WABinary_1.getBinaryNodeChild)(child, 'group')?.attrs?.jid || child.attrs?.jid
1134
+ ev.emit('groups.update', [
1135
+ {
1136
+ id: fullNode.attrs.from,
1137
+ siblingGroupUnlinked: unlinkedGroupJid || true,
1138
+ author: actingParticipantLid,
1139
+ authorPn: actingParticipantPn
1140
+ }
1141
+ ])
1142
+ break
1143
+ }
1144
+ case 'clear_history': {
1145
+ const historyClearTimestamp = child.attrs?.t ? +child.attrs.t : (0, Date)()
1146
+ ev.emit('groups.update', [
1147
+ {
1148
+ id: fullNode.attrs.from,
1149
+ historyClearTimestamp,
1150
+ author: actingParticipantLid,
1151
+ authorPn: actingParticipantPn
1152
+ }
1153
+ ])
1154
+ break
1155
+ }
1156
+ }
1157
+ }
1158
+ const normalizeNotificationParticipant = async (jid, groupData) => {
1159
+ if (!jid || typeof jid !== 'string') {
1160
+ return jid
1161
+ }
1162
+ if (!(0, WABinary_1.isLidUser)(jid) && !(0, WABinary_1.isHostedLidUser)(jid)) {
1163
+ return jid
1164
+ }
1165
+ const normalized = await (0, jid_display_normalization_1.normalizeMentionedJidsForSend)(
1166
+ [jid],
1167
+ groupData,
1168
+ signalRepository,
1169
+ logger
1170
+ )
1171
+ return normalized?.[0] || jid
1172
+ }
1173
+ const normalizeNotificationParticipantsArray = async (participants, groupData) => {
1174
+ if (!Array.isArray(participants)) {
1175
+ return participants
1176
+ }
1177
+ return Promise.all(participants.map(jid => normalizeNotificationParticipant(jid, groupData)))
1178
+ }
1179
+ const getNotificationGroupData = async node => {
1180
+ const groupJid = (0, WABinary_1.jidNormalizedUser)(node?.attrs?.from)
1181
+ if (!(0, WABinary_1.isJidGroup)(groupJid)) {
1182
+ return undefined
1183
+ }
1184
+ try {
1185
+ return (
1186
+ (config.useCachedGroupMetadata && config.cachedGroupMetadata
1187
+ ? await config.cachedGroupMetadata(groupJid)
1188
+ : undefined) || (await sock.groupMetadata(groupJid))
1189
+ )
1190
+ } catch (error) {
1191
+ logger.debug({ error, groupJid }, 'failed to fetch group metadata for notification normalization')
1192
+ return undefined
1193
+ }
1194
+ }
1195
+ const normalizeNotificationStubParameters = async (stubParameters, groupData) => {
1196
+ if (!Array.isArray(stubParameters)) {
1197
+ return stubParameters
1198
+ }
1199
+ const normalized = []
1200
+ for (const entry of stubParameters) {
1201
+ if (typeof entry !== 'string') {
1202
+ normalized.push(entry)
1203
+ continue
1204
+ }
1205
+ if ((0, WABinary_1.isLidUser)(entry) || (0, WABinary_1.isHostedLidUser)(entry)) {
1206
+ normalized.push(await normalizeNotificationParticipant(entry, groupData))
1207
+ continue
1208
+ }
1209
+ if (entry.startsWith('{') && entry.includes('"id"')) {
1210
+ try {
1211
+ const parsed = JSON.parse(entry)
1212
+ const explicitPn =
1213
+ typeof parsed?.phoneNumber === 'string'
1214
+ ? parsed.phoneNumber
1215
+ : typeof parsed?.pn === 'string'
1216
+ ? parsed.pn
1217
+ : undefined
1218
+ if ((0, WABinary_1.isPnUser)(explicitPn) || (0, WABinary_1.isHostedPnUser)(explicitPn)) {
1219
+ parsed.id = explicitPn
1220
+ parsed.pn = explicitPn
1221
+ normalized.push(JSON.stringify(parsed))
1222
+ continue
1223
+ }
1224
+ if (parsed?.id) {
1225
+ parsed.id = await normalizeNotificationParticipant(parsed.id, groupData)
1226
+ }
1227
+ if (parsed?.lid && !parsed?.pn) {
1228
+ parsed.pn = await normalizeNotificationParticipant(parsed.lid, groupData)
1229
+ }
1230
+ normalized.push(JSON.stringify(parsed))
1231
+ continue
1232
+ } catch (err) {
1233
+ logger.debug({ err, entry }, 'failed to normalize stub parameter JSON')
1234
+ }
1235
+ }
1236
+ normalized.push(entry)
1237
+ }
1238
+ return normalized
1239
+ }
1240
+ const normalizeCallEventJids = async (call, infoChild) => {
1241
+ if (!call) {
1242
+ return call
1243
+ }
1244
+ const callContextGroupJid = call.groupJid || ((0, WABinary_1.isJidGroup)(call.chatId) ? call.chatId : undefined)
1245
+ let groupData
1246
+ if (callContextGroupJid) {
1247
+ try {
1248
+ groupData =
1249
+ (config.useCachedGroupMetadata && config.cachedGroupMetadata
1250
+ ? await config.cachedGroupMetadata(callContextGroupJid)
1251
+ : undefined) || (await sock.groupMetadata(callContextGroupJid))
1252
+ } catch (error) {
1253
+ logger.debug({ error, groupJid: callContextGroupJid }, 'failed to fetch group metadata for call normalization')
1254
+ }
1255
+ }
1256
+ if (call.chatId && !call.isGroup) {
1257
+ call.chatId = await normalizeNotificationParticipant(call.chatId, groupData)
1258
+ }
1259
+ if (call.from) {
1260
+ call.from = await normalizeNotificationParticipant(call.from, groupData)
1261
+ }
1262
+ if (call.groupJid) {
1263
+ call.groupJid = await normalizeNotificationParticipant(call.groupJid, groupData)
1264
+ }
1265
+ if (!call.callerPn && infoChild?.attrs?.caller_lid) {
1266
+ call.callerPn = await normalizeNotificationParticipant(infoChild.attrs.caller_lid, groupData)
1267
+ }
1268
+ if (!call.callerPn && call.from) {
1269
+ call.callerPn = call.from
1270
+ }
1271
+ return call
1272
+ }
1273
+ const normalizeNotificationResult = async (node, result, groupData) => {
1274
+ const groupJid = (0, WABinary_1.jidNormalizedUser)(node?.attrs?.from)
1275
+ if (!(0, WABinary_1.isJidGroup)(groupJid)) {
1276
+ return
1277
+ }
1278
+ if (result?.key?.participant) {
1279
+ result.key.participant = await normalizeNotificationParticipant(result.key.participant, groupData)
1280
+ }
1281
+ if (result?.participant) {
1282
+ result.participant = await normalizeNotificationParticipant(result.participant, groupData)
1283
+ }
1284
+ if (Array.isArray(result?.messageStubParameters)) {
1285
+ result.messageStubParameters = await normalizeNotificationStubParameters(result.messageStubParameters, groupData)
1286
+ }
1287
+ }
1288
+
1289
+ /**
1290
+ * Handle incoming interop notifications (type="interop").
1291
+ *
1292
+ * The APK emits these for:
1293
+ * - stella_interop_enabled / stella_ios_enabled → feature-flag toggles
1294
+ * - ig_professional / ig_handle / followers → Instagram profile data updates
1295
+ * - fbid:thread / fbid:devices → Meta thread/device association
1296
+ * - peer_device_presence → interop contact online/offline
1297
+ * - group membership changes in interop groups → add/remove/promote events
1298
+ */
1299
+ const handleInteropNotification = (node, child) => {
1300
+ const childTag = child?.tag
1301
+ const attrs = child?.attrs || {}
1302
+
1303
+ // Feature flag: server toggled stella_interop_enabled or stella_ios_enabled
1304
+ if (childTag === 'feature') {
1305
+ const feature = attrs.name
1306
+ const enabled = attrs.value === 'true' || attrs.value === '1'
1307
+ logger.info({ feature, enabled }, '[interop] feature flag update')
1308
+ ev.emit('interop.feature-update', { feature, enabled })
1309
+ return
1310
+ }
1311
+
1312
+ // Instagram profile data pushed for an interop contact
1313
+ if (childTag === 'ig_profile') {
1314
+ const contactUpdate = {
1315
+ id: (0, WABinary_1.jidNormalizedUser)(node.attrs.from),
1316
+ ...(attrs.ig_handle ? { igHandle: attrs.ig_handle } : {}),
1317
+ ...(attrs.ig_professional !== undefined ? { igProfessional: attrs.ig_professional === 'true' } : {}),
1318
+ ...(attrs.followers !== undefined ? { igFollowers: parseInt(attrs.followers, 10) } : {})
1319
+ }
1320
+ logger.debug({ contactUpdate }, '[interop] ig_profile update')
1321
+ ev.emit('contacts.update', [contactUpdate])
1322
+ return
1323
+ }
1324
+
1325
+ // peer_device_presence — interop contact came online or went offline
1326
+ if (childTag === 'peer_device_presence') {
1327
+ const jid = attrs.jid || (0, WABinary_1.jidNormalizedUser)(node.attrs.from)
1328
+ const presence = attrs.type === 'unavailable' ? 'unavailable' : 'available'
1329
+ const isIosInterop = !!authState.creds.interopIosEnabled
1330
+ logger.debug({ jid, presence, isIosInterop }, '[interop] peer_device_presence')
1331
+ ev.emit('presence.update', { id: jid, presences: { [jid]: { lastKnownPresence: presence } }, isIosInterop })
1332
+ return
1333
+ }
1334
+
1335
+ // fbid:thread / fbid:devices — Meta thread or device list association
1336
+ if (childTag === 'fbid_thread' || childTag === 'fbid_devices') {
1337
+ const isIosInterop = !!authState.creds.interopIosEnabled
1338
+ logger.debug({ childTag, attrs, from: node.attrs.from, isIosInterop }, '[interop] fbid association update')
1339
+ ev.emit('interop.fbid-update', { type: childTag, jid: node.attrs.from, attrs, isIosInterop })
1340
+ return
1341
+ }
1342
+
1343
+ // Interop group membership changes (add / remove / promote / demote)
1344
+ if (childTag === 'participants') {
1345
+ const groupJid = node.attrs.from
1346
+ const action = attrs.type // 'add' | 'remove' | 'promote' | 'demote'
1347
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid)
1348
+ logger.info({ groupJid, action, participants }, '[interop] group participants update')
1349
+ ev.emit('group-participants.update', { id: groupJid, participants, action })
1350
+ return
1351
+ }
1352
+
1353
+ logger.debug({ childTag, from: node.attrs.from }, '[interop] unhandled interop notification subtype')
1354
+ }
1355
+
1356
+ const processNotification = async node => {
1357
+ const result = {}
1358
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node)
1359
+ const nodeType = node.attrs.type
1360
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from)
1361
+ switch (nodeType) {
1362
+ case 'newsletter':
1363
+ await handleNewsletterNotification(node)
1364
+ break
1365
+ case 'mex':
1366
+ await handleMexNotification(node)
1367
+ break
1368
+ case 'w:gp2':
1369
+ if (child?.tag === 'groups_dirty') {
1370
+ // Bulk "these groups are stale, refetch" signal — not a per-group stub message,
1371
+ // so it doesn't go through handleGroupNotification (which assumes a single group).
1372
+ const dirtyGroupJids = (0, WABinary_1.getBinaryNodeChildren)(child, 'group')
1373
+ .map(g => g.attrs.jid)
1374
+ .filter(Boolean)
1375
+ if (dirtyGroupJids.length) {
1376
+ ev.emit(
1377
+ 'groups.update',
1378
+ dirtyGroupJids.map(jid => ({ id: jid }))
1379
+ )
1380
+ }
1381
+ break
1382
+ }
1383
+ // PN/LID resolution for participant fields happens below via normalizeNotificationResult
1384
+ const groupData = await getNotificationGroupData(node)
1385
+ handleGroupNotification(node, child, result)
1386
+
1387
+ await normalizeNotificationResult(node, result, groupData)
1388
+ break
1389
+ case 'mediaretry':
1390
+ const event = (0, Utils_1.decodeMediaRetryNode)(node)
1391
+ ev.emit('messages.media-update', [event])
1392
+ break
1393
+ case 'encrypt':
1394
+ await handleEncryptNotification(node)
1395
+ break
1396
+ case 'devices': {
1397
+ // child = <add> or <remove> — neither carries jid/lid, owner is node.attrs.from.
1398
+ // A third variant, <update hash="..."/>, carries no device list at all (just a
1399
+ // device-list hash refresh) — don't misreport it as "removed nothing".
1400
+ const addNode = (0, WABinary_1.getBinaryNodeChild)(node, 'add')
1401
+ const removeNode = (0, WABinary_1.getBinaryNodeChild)(node, 'remove')
1402
+ const changedNode = addNode || removeNode
1403
+ if (!changedNode) {
1404
+ logger.debug({ node }, 'devices hash refresh, no add/remove list to report')
1405
+ break
1406
+ }
1407
+ const isAdded = !!addNode
1408
+ const devices = (0, WABinary_1.getBinaryNodeChildren)(changedNode, 'device')
1409
+ const deviceOwnerJid = from
1410
+ const deviceData = devices.map(d => ({
1411
+ id: d.attrs.jid,
1412
+ lid: d.attrs.lid,
1413
+ // wire attr is "key-index" (hyphen), not "key_index"
1414
+ keyIndex: d.attrs['key-index'] ? +d.attrs['key-index'] : undefined,
1415
+ platform: d.attrs.platform || undefined,
1416
+ isCompanion: d.attrs.companion === 'true' || undefined
1417
+ }))
1418
+ const isSelf =
1419
+ (0, WABinary_1.areJidsSameUser)(from, authState.creds.me?.id) ||
1420
+ (0, WABinary_1.areJidsSameUser)(from, authState.creds.me?.lid)
1421
+ if (isSelf) {
1422
+ logger.info({ deviceData, isAdded }, 'my own devices changed')
1423
+ }
1424
+ if (deviceOwnerJid) {
1425
+ ev.emit('devices.update', { id: deviceOwnerJid, devices: deviceData, isSelf, added: isAdded })
1426
+ }
1427
+ break
1428
+ }
1429
+ case 'server_sync':
1430
+ const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection')
1431
+ if (update) {
1432
+ const name = update.attrs.name
1433
+ await resyncAppState([name], false)
1434
+ }
1435
+ break
1436
+ case 'picture': {
1437
+ const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set')
1438
+ const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete')
1439
+ const pictureOwnerJid = (0, WABinary_1.jidNormalizedUser)(node?.attrs?.from)
1440
+ if (!pictureOwnerJid) {
1441
+ // a picture content hash is not a valid contact id — nothing usable to emit without "from"
1442
+ logger.debug({ node }, 'picture notification missing "from", skipping contacts.update')
1443
+ break
1444
+ }
1445
+ ev.emit('contacts.update', [
1446
+ {
1447
+ id: pictureOwnerJid,
1448
+ imgUrl: setPicture ? 'changed' : 'removed'
1449
+ }
1450
+ ])
1451
+ if ((0, WABinary_1.isJidGroup)(from)) {
1452
+ const node = setPicture || delPicture
1453
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON
1454
+ if (setPicture) {
1455
+ result.messageStubParameters = [setPicture.attrs.id]
1456
+ }
1457
+ result.participant = node?.attrs.author
1458
+ result.key = {
1459
+ ...(result.key || {}),
1460
+ participant: setPicture?.attrs.author
1461
+ }
1462
+ }
1463
+ break
1464
+ }
1465
+ case 'account_sync':
1466
+ if (child.tag === 'disappearing_mode') {
1467
+ const newDuration = +child.attrs.duration
1468
+ const timestamp = +child.attrs.t
1469
+ logger.info({ newDuration }, 'updated account disappearing mode')
1470
+ ev.emit('creds.update', {
1471
+ accountSettings: {
1472
+ ...authState.creds.accountSettings,
1473
+ defaultDisappearingMode: {
1474
+ ephemeralExpiration: newDuration,
1475
+ ephemeralSettingTimestamp: timestamp
1476
+ }
1477
+ }
1478
+ })
1479
+ } else if (child.tag === 'blocklist') {
1480
+ // Real wire shape is <blocklist action="modify" addressing_mode="lid"/> with
1481
+ // no per-entry children — it's a "your blocklist changed, go refetch it" signal,
1482
+ // not an inline diff. Re-fetch and let fetchBlocklist emit the refreshed list.
1483
+ sock.fetchBlocklist().catch(error => logger.warn({ error }, 'failed to refresh blocklist after account_sync'))
1484
+ } else if (child.tag === 'devices') {
1485
+ // Full device-list sync: all linked devices + signed key-index-list.
1486
+ // Sent when a device is added, removed, or key index changes.
1487
+ const dhash = child.attrs.dhash
1488
+ const deviceNodes = (0, WABinary_1.getBinaryNodeChildren)(child, 'device')
1489
+ const keyIndexListNode = (0, WABinary_1.getBinaryNodeChild)(child, 'key-index-list')
1490
+ const devices = deviceNodes.map(d => ({
1491
+ jid: d.attrs.jid ? String(d.attrs.jid) : undefined,
1492
+ keyIndex: d.attrs['key-index'] ? +d.attrs['key-index'] : undefined
1493
+ }))
1494
+ logger.info({ dhash, deviceCount: devices.length }, 'account devices list synced')
1495
+ ev.emit('account.devices-synced', {
1496
+ dhash,
1497
+ devices,
1498
+ keyIndexListTimestamp: keyIndexListNode?.attrs?.ts ? +keyIndexListNode.attrs.ts : undefined,
1499
+ keyIndexList: keyIndexListNode?.content ? Buffer.from(keyIndexListNode.content) : undefined
1500
+ })
1501
+ }
1502
+ break
1503
+ case 'disappearing_mode': {
1504
+ // Same payload as the account_sync-nested variant above, but WhatsApp also
1505
+ // pushes it as its own top-level notification type on some accounts.
1506
+ const newDuration = +child.attrs.duration
1507
+ const timestamp = +child.attrs.t
1508
+ logger.info({ newDuration }, 'updated account disappearing mode')
1509
+ ev.emit('creds.update', {
1510
+ accountSettings: {
1511
+ ...authState.creds.accountSettings,
1512
+ defaultDisappearingMode: {
1513
+ ephemeralExpiration: newDuration,
1514
+ ephemeralSettingTimestamp: timestamp
1515
+ }
1516
+ }
1517
+ })
1518
+ break
1519
+ }
1520
+ case 'contacts': {
1521
+ // <update jid="..."/> = single contact touched; <update hash="..."/> or a
1522
+ // sibling <sync after="..."/> = list-level signal with no actionable jid.
1523
+ const updateChild = (0, WABinary_1.getBinaryNodeChild)(node, 'update')
1524
+ if (updateChild?.attrs?.jid) {
1525
+ ev.emit('contacts.update', [{ id: (0, WABinary_1.jidNormalizedUser)(updateChild.attrs.jid) }])
1526
+ } else {
1527
+ logger.debug({ node }, 'contacts list changed (hash/sync signal), no per-contact jid to update')
1528
+ }
1529
+ break
1530
+ }
1531
+ case 'business':
1532
+ if (child?.tag === 'privacy') {
1533
+ // SMB privacy / data-sharing settings sync push
1534
+ ev.emit('business.privacy-settings-sync', {
1535
+ jid: from,
1536
+ categories: (0, WABinary_1.getBinaryNodeChildren)(child, 'category').map(c => ({
1537
+ name: c.attrs.name,
1538
+ value: c.attrs.value
1539
+ })),
1540
+ attrs: child.attrs
1541
+ })
1542
+ } else if (child?.tag === 'profile') {
1543
+ // Business profile updated for a contact (tag = profile version hash)
1544
+ ev.emit('contacts.update', [
1545
+ {
1546
+ id: (0, WABinary_1.jidNormalizedUser)(child.attrs.jid || from),
1547
+ businessProfileTag: child.attrs.tag
1548
+ }
1549
+ ])
1550
+ } else if (child?.tag === 'verified_name') {
1551
+ // Verified business name changed — content is a proto payload
1552
+ ev.emit('contacts.update', [
1553
+ {
1554
+ id: (0, WABinary_1.jidNormalizedUser)(child.attrs.jid || from),
1555
+ verifiedName: {
1556
+ verifiedLevel: child.attrs.verified_level,
1557
+ serial: child.attrs.serial,
1558
+ version: child.attrs.v
1559
+ }
1560
+ }
1561
+ ])
1562
+ } else if (child?.tag === 'remove') {
1563
+ // Business account downgraded/removed. <remove jid="..."/> names the account;
1564
+ // <remove hash="..."/> is a list-level signal with no actionable jid.
1565
+ if (child.attrs.jid) {
1566
+ ev.emit('contacts.update', [{ id: (0, WABinary_1.jidNormalizedUser)(child.attrs.jid), isBusiness: false }])
1567
+ }
1568
+ }
1569
+ break
1570
+ case 'hosted':
1571
+ // Coexistence (WhatsApp <-> Messenger/Instagram) onboarding/offboarding push
1572
+ // (WhatsApp Web: WASmaxInCoexistenceOnboarding/OffboardingNotification)
1573
+ if (child?.tag === 'onboarding_status') {
1574
+ ev.emit('coexistence.update', {
1575
+ jid: from,
1576
+ kind: 'onboarding',
1577
+ status: child.attrs.status,
1578
+ productSurface: child.attrs['product_surface']
1579
+ })
1580
+ } else if (child?.tag === 'offboarding') {
1581
+ ev.emit('coexistence.update', {
1582
+ jid: from,
1583
+ kind: 'offboarding',
1584
+ productSurface: child.attrs['product_surface']
1585
+ })
1586
+ }
1587
+ break
1588
+ case 'link_code_companion_reg':
1589
+ const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg')
1590
+ const ref = toRequiredBuffer(
1591
+ (0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref')
1592
+ )
1593
+ const primaryIdentityPublicKey = toRequiredBuffer(
1594
+ (0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub')
1595
+ )
1596
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(
1597
+ (0, WABinary_1.getBinaryNodeChildBuffer)(
1598
+ linkCodeCompanionReg,
1599
+ 'link_code_pairing_wrapped_primary_ephemeral_pub'
1600
+ )
1601
+ )
1602
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped)
1603
+ const companionSharedKey = Utils_1.Curve.sharedKey(
1604
+ authState.creds.pairingEphemeralKeyPair.private,
1605
+ codePairingPublicKey
1606
+ )
1607
+ const random = (0, crypto_1.randomBytes)(32)
1608
+ const linkCodeSalt = (0, crypto_1.randomBytes)(32)
1609
+ const linkCodePairingExpanded = (0, Utils_1.hkdf)(companionSharedKey, 32, {
1610
+ salt: linkCodeSalt,
1611
+ info: 'link_code_pairing_key_bundle_encryption_key'
1612
+ })
1613
+ const encryptPayload = Buffer.concat([
1614
+ Buffer.from(authState.creds.signedIdentityKey.public),
1615
+ primaryIdentityPublicKey,
1616
+ random
1617
+ ])
1618
+ const encryptIv = (0, crypto_1.randomBytes)(12)
1619
+ const encrypted = (0, Utils_1.aesEncryptGCM)(
1620
+ encryptPayload,
1621
+ linkCodePairingExpanded,
1622
+ encryptIv,
1623
+ Buffer.alloc(0)
1624
+ )
1625
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted])
1626
+ const identitySharedKey = Utils_1.Curve.sharedKey(
1627
+ authState.creds.signedIdentityKey.private,
1628
+ primaryIdentityPublicKey
1629
+ )
1630
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random])
1631
+ authState.creds.advSecretKey = Buffer.from(
1632
+ (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' })
1633
+ ).toString('base64')
1634
+ await query({
1635
+ tag: 'iq',
1636
+ attrs: {
1637
+ to: WABinary_1.S_WHATSAPP_NET,
1638
+ type: 'set',
1639
+ id: sock.generateMessageTag(),
1640
+ xmlns: 'md'
1641
+ },
1642
+ content: [
1643
+ {
1644
+ tag: 'link_code_companion_reg',
1645
+ attrs: {
1646
+ jid: authState.creds.me.id,
1647
+ stage: 'companion_finish'
1648
+ },
1649
+ content: [
1650
+ {
1651
+ tag: 'link_code_pairing_wrapped_key_bundle',
1652
+ attrs: {},
1653
+ content: encryptedPayload
1654
+ },
1655
+ {
1656
+ tag: 'companion_identity_public',
1657
+ attrs: {},
1658
+ content: authState.creds.signedIdentityKey.public
1659
+ },
1660
+ {
1661
+ tag: 'link_code_pairing_ref',
1662
+ attrs: {},
1663
+ content: ref
1664
+ }
1665
+ ]
1666
+ }
1667
+ ]
1668
+ })
1669
+ authState.creds.registered = true
1670
+ ev.emit('creds.update', authState.creds)
1671
+ break
1672
+ case 'privacy_token':
1673
+ await handlePrivacyTokenNotification(node)
1674
+ break
1675
+ case 'security':
1676
+ // Security notifications (compromised session, location change alerts)
1677
+ const securityType = child?.tag || node.attrs.type
1678
+ const securityData = {
1679
+ type: securityType,
1680
+ jid: from,
1681
+ timestamp: node.attrs.t ? +node.attrs.t : Math.floor(Date.now() / 1000),
1682
+ details: child?.attrs || {}
1683
+ }
1684
+ logger.warn({ securityData }, 'received security notification')
1685
+ ev.emit('security.alert', securityData)
1686
+ break
1687
+ case 'identity':
1688
+ // Identity change notifications — peer changed their identity key
1689
+ const identityJid = node.attrs.from
1690
+ const identityNewKey = child?.content ? Buffer.from(child.content) : undefined
1691
+ ev.emit('identity.update', {
1692
+ jid: (0, WABinary_1.jidNormalizedUser)(identityJid),
1693
+ newIdentityKey: identityNewKey,
1694
+ timestamp: node.attrs.t ? +node.attrs.t : Math.floor(Date.now() / 1000)
1695
+ })
1696
+ break
1697
+ case 'server':
1698
+ // Server-issued notifications (config changes, client config refresh)
1699
+ const serverTag = child?.tag
1700
+ if (serverTag === 'config') {
1701
+ const configData = {}
1702
+ for (const attr of Object.keys(child?.attrs || {})) {
1703
+ configData[attr] = child.attrs[attr]
1704
+ }
1705
+ ev.emit('server.config', configData)
1706
+ } else if (serverTag === 'app_state_key') {
1707
+ // Server pushed a new app-state key — trigger resync
1708
+ logger.info('server pushed app state key update')
1709
+ await resyncAppState(['critical_block', 'regular_high', 'regular_low'], false)
1710
+ } else {
1711
+ logger.debug({ node }, 'unhandled server notification')
1712
+ }
1713
+ break
1714
+ case 'status':
1715
+ // Contact status (about) change notification
1716
+ const statusOwner = node.attrs.from
1717
+ const statusText = child?.content ? child.content.toString() : undefined
1718
+ if (statusOwner && statusText !== undefined) {
1719
+ ev.emit('contacts.update', [
1720
+ {
1721
+ id: (0, WABinary_1.jidNormalizedUser)(statusOwner),
1722
+ status: statusText
1723
+ }
1724
+ ])
1725
+ }
1726
+ break
1727
+ case 'usync':
1728
+ // USync result push from server
1729
+ const usyncResults = (0, WABinary_1.getBinaryNodeChildren)(child || node, 'user')
1730
+ if (usyncResults.length) {
1731
+ const updates = usyncResults
1732
+ .map(u => ({
1733
+ id: (0, WABinary_1.jidNormalizedUser)(u.attrs.jid),
1734
+ ...(u.attrs.lid ? { lid: u.attrs.lid } : {}),
1735
+ ...(u.attrs.username ? { username: u.attrs.username } : {}),
1736
+ ...(u.attrs.status ? { status: u.attrs.status } : {})
1737
+ }))
1738
+ .filter(u => u.id)
1739
+ if (updates.length) {
1740
+ ev.emit('contacts.update', updates)
1741
+ }
1742
+ }
1743
+ break
1744
+ case 'interop':
1745
+ // Interop-related server notifications — covers:
1746
+ // stella_interop_enabled / stella_ios_enabled feature flags
1747
+ // ig_professional / ig_handle / followers (Instagram account data)
1748
+ // fbid:thread / fbid:devices (Meta thread/device references)
1749
+ // peer_device_presence updates
1750
+ // group membership changes in interop groups
1751
+ handleInteropNotification(node, child)
1752
+ break
1753
+ }
1754
+ if (Object.keys(result).length) {
1755
+ return result
1756
+ }
1757
+ }
1758
+ /**
1759
+ * In-memory cache of storage JIDs with stored tctokens, seeded from the persisted index.
1760
+ * Used to coalesce writes during a session; pruning always re-reads the persisted index.
1761
+ */
1762
+ const tcTokenKnownJids = new Set()
1763
+ const tcTokenIndexLoaded = (async () => {
1764
+ try {
1765
+ const jids = await (0, tc_token_utils_1.readTcTokenIndex)(authState.keys)
1766
+ for (const jid of jids) tcTokenKnownJids.add(jid)
1767
+ logger.debug({ count: tcTokenKnownJids.size }, 'loaded tctoken index')
1768
+ } catch (err) {
1769
+ logger.warn({ err: err?.message }, 'failed to load tctoken index')
1770
+ }
1771
+ })()
1772
+ let tcTokenIndexTimer
1773
+ async function flushTcTokenIndex() {
1774
+ if (tcTokenIndexTimer) {
1775
+ clearTimeout(tcTokenIndexTimer)
1776
+ tcTokenIndexTimer = undefined
1777
+ }
1778
+ const write = await (0, tc_token_utils_1.buildMergedTcTokenIndexWrite)(authState.keys, tcTokenKnownJids)
1779
+ return authState.keys.set({ tctoken: write })
1780
+ }
1781
+ function scheduleTcTokenIndexSave() {
1782
+ if (tcTokenIndexTimer) {
1783
+ clearTimeout(tcTokenIndexTimer)
1784
+ }
1785
+ tcTokenIndexTimer = setTimeout(() => {
1786
+ tcTokenIndexTimer = undefined
1787
+ flushTcTokenIndex().catch(err => {
1788
+ logger.warn({ err: err?.message }, 'failed to save tctoken index')
1789
+ })
1790
+ }, 5000)
1791
+ }
1792
+ function trackTcTokenJid(jid) {
1793
+ if (jid && jid !== tc_token_utils_1.TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
1794
+ tcTokenKnownJids.add(jid)
1795
+ scheduleTcTokenIndexSave()
1796
+ }
1797
+ }
1798
+ const handlePrivacyTokenNotification = async node => {
1799
+ const tokensNode = (0, WABinary_1.getBinaryNodeChild)(node, 'tokens')
1800
+ if (!tokensNode) return
1801
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from)
1802
+ // WA Web uses: senderLid ?? toLid(from) for the storage key
1803
+ const senderLid =
1804
+ node.attrs.sender_lid && (0, WABinary_1.isLidUser)((0, WABinary_1.jidNormalizedUser)(node.attrs.sender_lid))
1805
+ ? (0, WABinary_1.jidNormalizedUser)(node.attrs.sender_lid)
1806
+ : undefined
1807
+ const fallbackJid = senderLid ?? (await (0, tc_token_utils_1.resolveTcTokenJid)(from, getLIDForPN))
1808
+ logger.debug({ from, storageJid: fallbackJid }, 'processing privacy token notification')
1809
+ await (0, tc_token_utils_1.storeTcTokensFromIqResult)({
1810
+ result: node,
1811
+ fallbackJid,
1812
+ keys: authState.keys,
1813
+ getLIDForPN,
1814
+ onNewJidStored: trackTcTokenJid
1815
+ })
1816
+ }
1817
+ async function decipherLinkPublicKey(data) {
1818
+ const buffer = toRequiredBuffer(data)
1819
+ const salt = buffer.slice(0, 32)
1820
+ const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt)
1821
+ const iv = buffer.slice(32, 48)
1822
+ const payload = buffer.slice(48, 80)
1823
+ return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv)
1824
+ }
1825
+ function toRequiredBuffer(data) {
1826
+ if (data === undefined) {
1827
+ throw new boom_1.Boom('Invalid buffer', { statusCode: 400 })
1828
+ }
1829
+ return data instanceof Buffer ? data : Buffer.from(data)
1830
+ }
1831
+ const willSendMessageAgain = async (id, participant) => {
1832
+ const key = `${id}:${participant}`
1833
+ const retryCount = (await msgRetryCache.get(key)) || 0
1834
+ return retryCount < maxMsgRetryCount
1835
+ }
1836
+ const updateSendMessageAgainCount = async (id, participant) => {
1837
+ const key = `${id}:${participant}`
1838
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1
1839
+ await msgRetryCache.set(key, newValue)
1840
+ }
1841
+ const sendMessagesAgain = async (key, ids, retryNode) => {
1842
+ const remoteJid = key.remoteJid
1843
+ const participant = key.participant || remoteJid
1844
+ const retryCount = +retryNode.attrs.count || 1
1845
+ // Try to get messages from cache first, then fallback to getMessage
1846
+ const msgs = []
1847
+ for (const id of ids) {
1848
+ let msg
1849
+ // Try to get from retry cache first if enabled
1850
+ if (messageRetryManager) {
1851
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id)
1852
+ if (cachedMsg) {
1853
+ msg = cachedMsg.message
1854
+ logger.debug({ jid: remoteJid, id }, 'found message in retry cache')
1855
+ // Mark retry as successful since we found the message
1856
+ messageRetryManager.markRetrySuccess(id)
1857
+ }
1858
+ }
1859
+ // Fallback to getMessage if not found in cache
1860
+ if (!msg) {
1861
+ msg = await getMessage({ ...key, id })
1862
+ if (msg) {
1863
+ logger.debug({ jid: remoteJid, id }, 'found message via getMessage')
1864
+ // Also mark as successful if found via getMessage
1865
+ if (messageRetryManager) {
1866
+ messageRetryManager.markRetrySuccess(id)
1867
+ }
1868
+ }
1869
+ }
1870
+ msgs.push(msg)
1871
+ }
1872
+ // if it's the primary jid sending the request
1873
+ // just re-send the message to everyone
1874
+ // prevents the first message decryption failure
1875
+ const sendToAll = !(0, WABinary_1.jidDecode)(participant)?.device
1876
+ // Check if we should recreate session for this retry
1877
+ let shouldRecreateSession = false
1878
+ let recreateReason = ''
1879
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
1880
+ try {
1881
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant)
1882
+ const hasSession = await signalRepository.validateSession(participant)
1883
+ const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists)
1884
+ shouldRecreateSession = result.recreate
1885
+ recreateReason = result.reason
1886
+ if (shouldRecreateSession) {
1887
+ logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry')
1888
+ await authState.keys.set({ session: { [sessionId]: null } })
1889
+ }
1890
+ } catch (error) {
1891
+ logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry')
1892
+ }
1893
+ }
1894
+ await assertSessions([participant], true)
1895
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
1896
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } })
1897
+ }
1898
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp')
1899
+ for (const [i, msg] of msgs.entries()) {
1900
+ if (!ids[i]) continue
1901
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
1902
+ await updateSendMessageAgainCount(ids[i], participant)
1903
+ const msgRelayOpts = { messageId: ids[i] }
1904
+ if (sendToAll) {
1905
+ msgRelayOpts.useUserDevicesCache = false
1906
+ } else {
1907
+ msgRelayOpts.participant = {
1908
+ jid: participant,
1909
+ count: +retryNode.attrs.count
1910
+ }
1911
+ }
1912
+ await relayMessage(key.remoteJid, msg, msgRelayOpts)
1913
+ } else {
1914
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available')
1915
+ }
1916
+ }
1917
+ }
1918
+ const handleReceipt = async node => {
1919
+ const { attrs, content } = node
1920
+ const isLid = attrs.from.includes('lid')
1921
+ const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(
1922
+ attrs.participant || attrs.from,
1923
+ isLid ? authState.creds.me?.lid : authState.creds.me?.id
1924
+ )
1925
+ const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient
1926
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe)
1927
+ const key = {
1928
+ remoteJid,
1929
+ id: '',
1930
+ fromMe,
1931
+ participant: attrs.participant
1932
+ }
1933
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== WABinary_1.S_WHATSAPP_NET) {
1934
+ logger.debug({ remoteJid }, 'ignoring receipt from jid')
1935
+ await sendMessageAck(node)
1936
+ return
1937
+ }
1938
+ const ids = [attrs.id]
1939
+ if (Array.isArray(content)) {
1940
+ const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item')
1941
+ ids.push(...items.map(i => i.attrs.id))
1942
+ }
1943
+ // E. Media Retry Notification Receipt
1944
+ // Server tells us a specific message's media should be re-fetched
1945
+ if (attrs.type === 'media-retry') {
1946
+ const mediaRetryNode =
1947
+ (0, WABinary_1.getBinaryNodeChild)(node, 'media-retry') ||
1948
+ (0, WABinary_1.getBinaryNodeChild)(node, 'media_retry')
1949
+ ev.emit('messages.media-retry', {
1950
+ ids,
1951
+ from: attrs.from,
1952
+ participant: attrs.participant,
1953
+ t: attrs.t,
1954
+ retryAttrs: mediaRetryNode?.attrs
1955
+ })
1956
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack media-retry receipt'))
1957
+ return
1958
+ }
1959
+ // F. Server Error Receipt
1960
+ // Server signals a delivery error for one or more messages
1961
+ if (attrs.type === 'server-error') {
1962
+ const errorNode = (0, WABinary_1.getBinaryNodeChild)(node, 'error')
1963
+ ev.emit('messages.server-error', {
1964
+ ids,
1965
+ from: attrs.from,
1966
+ participant: attrs.participant,
1967
+ t: attrs.t,
1968
+ errorCode: errorNode?.attrs?.code || attrs.error_code,
1969
+ errorText: errorNode?.attrs?.text || errorNode?.content?.toString?.()
1970
+ })
1971
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack server-error receipt'))
1972
+ return
1973
+ }
1974
+ // D. Receipt aggregation
1975
+ // Server sent a batched-receipt (receipt_agg attr) — emit dedicated event AND fall through
1976
+ // to the normal status-update pipeline so all IDs in the batch get their status updated.
1977
+ if (attrs.receipt_agg) {
1978
+ ev.emit('receipt.batched', {
1979
+ ids,
1980
+ from: attrs.from,
1981
+ participant: attrs.participant,
1982
+ type: attrs.type,
1983
+ t: attrs.t,
1984
+ receiptAgg: attrs.receipt_agg
1985
+ })
1986
+ // Do not return — let all IDs be processed by the normal receipt path below.
1987
+ }
1988
+ try {
1989
+ await Promise.all([
1990
+ receiptMutex.mutex(async () => {
1991
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type)
1992
+ if (
1993
+ typeof status !== 'undefined' &&
1994
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
1995
+ // or another device of ours has read some messages
1996
+ (status >= index_js_1.proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)
1997
+ ) {
1998
+ if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
1999
+ if (attrs.participant) {
2000
+ const updateKey =
2001
+ status === index_js_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp'
2002
+ ev.emit(
2003
+ 'message-receipt.update',
2004
+ ids.map(id => ({
2005
+ key: { ...key, id },
2006
+ receipt: {
2007
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
2008
+ [updateKey]: +attrs.t
2009
+ }
2010
+ }))
2011
+ )
2012
+ }
2013
+ } else {
2014
+ ev.emit(
2015
+ 'messages.update',
2016
+ ids.map(id => ({
2017
+ key: { ...key, id },
2018
+ update: { status, messageTimestamp: (0, Utils_1.toNumber)(+(attrs.t ?? 0)) }
2019
+ }))
2020
+ )
2021
+ }
2022
+ }
2023
+ if (attrs.type === 'retry') {
2024
+ // correctly set who is asking for the retry
2025
+ key.participant = key.participant || attrs.from
2026
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry')
2027
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
2028
+ if (key.fromMe) {
2029
+ try {
2030
+ await updateSendMessageAgainCount(ids[0], key.participant)
2031
+ logger.debug({ attrs, key }, 'recv retry request')
2032
+ await sendMessagesAgain(key, ids, retryNode)
2033
+ } catch (error) {
2034
+ logger.error(
2035
+ { key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' },
2036
+ 'error in sending message again'
2037
+ )
2038
+ }
2039
+ } else {
2040
+ logger.info({ attrs, key }, 'recv retry for not fromMe message')
2041
+ }
2042
+ } else {
2043
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times')
2044
+ }
2045
+ }
2046
+ })
2047
+ ])
2048
+ } finally {
2049
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'))
2050
+ }
2051
+ }
2052
+ const handleNotification = async node => {
2053
+ const remoteJid = node.attrs.from
2054
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== WABinary_1.S_WHATSAPP_NET) {
2055
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification')
2056
+ await sendMessageAck(node)
2057
+ return
2058
+ }
2059
+ try {
2060
+ await Promise.all([
2061
+ notificationMutex.mutex(async () => {
2062
+ const msg = await processNotification(node)
2063
+ if (msg) {
2064
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id)
2065
+ const { senderAlt: participantAlt, addressingMode } = (0, Utils_1.extractAddressingContext)(node)
2066
+ msg.key = {
2067
+ remoteJid,
2068
+ fromMe,
2069
+ participant: node.attrs.participant,
2070
+ participantAlt,
2071
+ participantUsername: node.attrs.participant_username,
2072
+ addressingMode,
2073
+ id: node.attrs.id,
2074
+ ...(msg.key || {})
2075
+ }
2076
+ msg.participant ?? (msg.participant = node.attrs.participant)
2077
+ msg.messageTimestamp = +node.attrs.t
2078
+ let groupDataForNormalization
2079
+ if ((0, WABinary_1.isJidGroup)(msg?.key?.remoteJid)) {
2080
+ try {
2081
+ groupDataForNormalization =
2082
+ (config.useCachedGroupMetadata && config.cachedGroupMetadata
2083
+ ? await config.cachedGroupMetadata(msg.key.remoteJid)
2084
+ : undefined) || (await sock.groupMetadata(msg.key.remoteJid))
2085
+ } catch (error) {
2086
+ logger.debug(
2087
+ { error, jid: msg.key.remoteJid },
2088
+ 'failed to fetch group metadata for recv jid normalization'
2089
+ )
2090
+ }
2091
+ }
2092
+ await (0, jid_display_normalization_1.normalizeMessageForDisplayJids)(
2093
+ msg,
2094
+ signalRepository,
2095
+ logger,
2096
+ groupDataForNormalization
2097
+ )
2098
+ const fullMsg = index_js_1.proto.WebMessageInfo.fromObject(msg)
2099
+ await upsertMessage(fullMsg, 'append')
2100
+ }
2101
+ })
2102
+ ])
2103
+ } finally {
2104
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'))
2105
+ }
2106
+ }
2107
+ const handleMessage = async node => {
2108
+ const isInteropNode = (0, WABinary_1.isInteropUser)(node.attrs.from)
2109
+ if (isInteropNode) {
2110
+ logger.info(
2111
+ {
2112
+ from: node.attrs.from,
2113
+ id: node.attrs.id,
2114
+ type: node.attrs.type,
2115
+ sts: node.attrs.sts,
2116
+ display_name: node.attrs.display_name,
2117
+ encType: (0, WABinary_1.getBinaryNodeChild)(node, 'enc')?.attrs?.type
2118
+ },
2119
+ '[interop] node arrived'
2120
+ )
2121
+ }
2122
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== WABinary_1.S_WHATSAPP_NET) {
2123
+ if (isInteropNode) logger.warn({ from: node.attrs.from }, '[interop] node dropped by shouldIgnoreJid')
2124
+ logger.debug({ key: node.attrs.key }, 'ignored message')
2125
+ await sendMessageAck(node, Utils_1.NACK_REASONS.UnhandledError)
2126
+ return
2127
+ }
2128
+ const groupJid = node.attrs.from
2129
+ const communityJid = linkedParentMap[groupJid]
2130
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc')
2131
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
2132
+ if (encNode?.attrs.type === 'msmsg') {
2133
+ // await sendMessageAck(node, Utils_1.NACK_REASONS.MissingMessageSecret)
2134
+ // return
2135
+ // Pre-populate botMessageSecrets from store so msmsg can be decrypted after restart
2136
+ if (getMessage) {
2137
+ const metaNode = (0, WABinary_1.getBinaryNodeChild)(node, 'meta')
2138
+ const targetId = metaNode?.attrs?.target_id
2139
+ if (targetId) {
2140
+ try {
2141
+ const targetMsg = await getMessage({ remoteJid: node.attrs.from, id: targetId, fromMe: true })
2142
+ const secret = targetMsg?.messageContextInfo?.messageSecret
2143
+ if (secret) {
2144
+ ;(0, Utils_1.setBotMessageSecret)(targetId, secret)
2145
+ }
2146
+ } catch (err) {
2147
+ logger.debug({ err, targetId }, 'failed to retrieve message secret for msmsg')
2148
+ }
2149
+ }
2150
+ }
2151
+ }
2152
+ let acked = false
2153
+ try {
2154
+ const {
2155
+ fullMessage: msg,
2156
+ category,
2157
+ author,
2158
+ decrypt
2159
+ } = (0, Utils_1.decryptMessageNode)(
2160
+ node,
2161
+ authState.creds.me.id,
2162
+ authState.creds.me.lid || '',
2163
+ signalRepository,
2164
+ logger
2165
+ )
2166
+ if (isInteropNode) {
2167
+ logger.info(
2168
+ { remoteJid: msg.key.remoteJid, id: msg.key.id, fromMe: msg.key.fromMe, pushName: msg.pushName },
2169
+ '[interop] decodeMessageNode OK'
2170
+ )
2171
+ }
2172
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt
2173
+ // store new mappings we didn't have before
2174
+ if (!!alt) {
2175
+ const altServer = (0, WABinary_1.jidDecode)(alt)?.server
2176
+ const primaryJid = msg.key.participant || msg.key.remoteJid
2177
+ if (altServer === 'lid') {
2178
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
2179
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }])
2180
+ await signalRepository.migrateSession(primaryJid, alt)
2181
+ }
2182
+ } else {
2183
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }])
2184
+ await signalRepository.migrateSession(alt, primaryJid)
2185
+ }
2186
+ }
2187
+ await messageMutex.mutex(async () => {
2188
+ await decrypt()
2189
+ if (isInteropNode) {
2190
+ const stubType = msg.messageStubType
2191
+ const stubText = msg.messageStubParameters?.[0]
2192
+ logger.info(
2193
+ {
2194
+ id: msg.key.id,
2195
+ hasMessage: !!msg.message,
2196
+ messageKeys: msg.message ? Object.keys(msg.message) : [],
2197
+ stubType,
2198
+ stubText
2199
+ },
2200
+ '[interop] decrypt() done'
2201
+ )
2202
+ }
2203
+ if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
2204
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message)
2205
+ }
2206
+ // message failed to decrypt
2207
+ if (msg.messageStubType === index_js_1.proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
2208
+ if (msg?.messageStubParameters?.[0] === Utils_1.MISSING_KEYS_ERROR_TEXT) {
2209
+ if (isInteropNode) logger.warn({ id: msg.key.id }, '[interop] decrypt failed: MISSING_KEYS')
2210
+ acked = true
2211
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError)
2212
+ }
2213
+ if (msg.messageStubParameters?.[0] === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT) {
2214
+ // Message arrived without encryption (e.g. CTWA ads messages).
2215
+ // Check if this is eligible for placeholder resend (matching WA Web filters).
2216
+ const unavailableNode = (0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')
2217
+ const unavailableType = unavailableNode?.attrs?.type
2218
+ if (
2219
+ unavailableType === 'bot_unavailable_fanout' ||
2220
+ unavailableType === 'hosted_unavailable_fanout' ||
2221
+ unavailableType === 'view_once_unavailable_fanout'
2222
+ ) {
2223
+ logger.debug(
2224
+ { msgId: msg.key.id, unavailableType },
2225
+ 'skipping placeholder resend for excluded unavailable type'
2226
+ )
2227
+ acked = true
2228
+ return sendMessageAck(node)
2229
+ }
2230
+ const messageAge = (0, Utils_1.unixTimestampSeconds)() - (0, Utils_1.toNumber)(msg.messageTimestamp)
2231
+ if (messageAge > Defaults_1.PLACEHOLDER_MAX_AGE_SECONDS) {
2232
+ logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message')
2233
+ acked = true
2234
+ return sendMessageAck(node)
2235
+ }
2236
+ // Request the real content from the phone via placeholder resend PDO.
2237
+ // Upsert the CIPHERTEXT stub as a placeholder (like WA Web's processPlaceholderMsg),
2238
+ // and store the requestId in stubParameters[1] so users can correlate
2239
+ // with the incoming PDO response event.
2240
+ const cleanKey = {
2241
+ remoteJid: msg.key.remoteJid,
2242
+ fromMe: msg.key.fromMe,
2243
+ id: msg.key.id,
2244
+ participant: msg.key.participant
2245
+ }
2246
+ // Cache the original message metadata so the PDO response handler
2247
+ // can preserve key fields (LID details etc.) that the phone may omit
2248
+ const msgData = {
2249
+ key: msg.key,
2250
+ messageTimestamp: msg.messageTimestamp,
2251
+ pushName: msg.pushName,
2252
+ participant: msg.participant,
2253
+ verifiedBizName: msg.verifiedBizName
2254
+ }
2255
+ requestPlaceholderResend(cleanKey, msgData)
2256
+ .then(requestId => {
2257
+ if (requestId && requestId !== 'RESOLVED') {
2258
+ logger.debug({ msgId: msg.key.id, requestId }, 'requested placeholder resend for unavailable message')
2259
+ ev.emit('messages.update', [
2260
+ {
2261
+ key: msg.key,
2262
+ update: { messageStubParameters: [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, requestId] }
2263
+ }
2264
+ ])
2265
+ }
2266
+ })
2267
+ .catch(err => {
2268
+ logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message')
2269
+ })
2270
+ acked = true
2271
+ await sendMessageAck(node)
2272
+ // Don't return — fall through to upsertMessage so the stub is emitted
2273
+ } else {
2274
+ // Skip retry for expired status messages (>24h old)
2275
+ if ((0, WABinary_1.isJidStatusBroadcast)(msg.key.remoteJid)) {
2276
+ const messageAge = (0, Utils_1.unixTimestampSeconds)() - (0, Utils_1.toNumber)(msg.messageTimestamp)
2277
+ if (messageAge > Defaults_1.STATUS_EXPIRY_SECONDS) {
2278
+ logger.debug(
2279
+ { msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid },
2280
+ 'skipping retry for expired status message'
2281
+ )
2282
+ acked = true
2283
+ return sendMessageAck(node)
2284
+ }
2285
+ }
2286
+ const errorMessage = msg?.messageStubParameters?.[0] || ''
2287
+ const isPreKeyError = errorMessage.includes('PreKey')
2288
+ logger.debug(`[handleMessage] Attempting retry request for failed decryption`)
2289
+ // Handle both pre-key and normal retries in single mutex
2290
+ await retryMutex.mutex(async () => {
2291
+ try {
2292
+ if (!ws.isOpen) {
2293
+ logger.debug({ node }, 'Connection closed, skipping retry')
2294
+ return
2295
+ }
2296
+ // Handle pre-key errors with upload and delay
2297
+ if (isPreKeyError) {
2298
+ logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying')
2299
+ try {
2300
+ logger.debug('Uploading pre-keys for error recovery')
2301
+ await uploadPreKeys(5)
2302
+ logger.debug('Waiting for server to process new pre-keys')
2303
+ await (0, Utils_1.delay)(1000)
2304
+ } catch (uploadErr) {
2305
+ logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway')
2306
+ }
2307
+ }
2308
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc')
2309
+ await sendRetryRequest(node, !encNode)
2310
+ if (retryRequestDelayMs) {
2311
+ await (0, Utils_1.delay)(retryRequestDelayMs)
2312
+ }
2313
+ } catch (err) {
2314
+ logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry')
2315
+ // Still attempt retry even if pre-key upload failed
2316
+ try {
2317
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc')
2318
+ await sendRetryRequest(node, !encNode)
2319
+ } catch (retryErr) {
2320
+ logger.error({ retryErr }, 'Failed to send retry after error handling')
2321
+ }
2322
+ }
2323
+ acked = true
2324
+ await sendMessageAck(node, Utils_1.NACK_REASONS.UnhandledError)
2325
+ })
2326
+ }
2327
+ } else {
2328
+ if (messageRetryManager && msg.key.id) {
2329
+ messageRetryManager.cancelPendingPhoneRequest(msg.key.id)
2330
+ }
2331
+ const isNewsletter = (0, WABinary_1.isJidNewsletter)(msg.key.remoteJid)
2332
+ if (!isNewsletter) {
2333
+ // no type in the receipt => message delivered
2334
+ let type = undefined
2335
+ let participant = msg.key.participant
2336
+ if (communityJid) {
2337
+ msg.communityJid = communityJid
2338
+ }
2339
+ if (category === 'peer') {
2340
+ // special peer message
2341
+ type = 'peer_msg'
2342
+ } else if (msg.key.fromMe) {
2343
+ // message was sent by us from a different device
2344
+ type = 'sender'
2345
+ // need to specially handle this case
2346
+ if ((0, WABinary_1.isLidUser)(msg.key.remoteJid) || (0, WABinary_1.isLidUser)(msg.key.remoteJidAlt)) {
2347
+ participant = author // TODO: investigate sending receipts to LIDs and not PNs
2348
+ }
2349
+ } else if (!sendActiveReceipts) {
2350
+ type = 'inactive'
2351
+ }
2352
+ acked = true
2353
+ // Pass sts from the original stanza for interop contacts (BirdyChat/Haiket)
2354
+ const interopSts = (0, WABinary_1.isInteropUser)(msg.key.remoteJid) ? node.attrs.sts : undefined
2355
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type, interopSts)
2356
+ // send ack for history message
2357
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message)
2358
+ if (isAnyHistoryMsg) {
2359
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid)
2360
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync') // TODO: investigate
2361
+ }
2362
+ } else {
2363
+ acked = true
2364
+ await sendMessageAck(node)
2365
+ logger.debug({ key: msg.key }, 'processed newsletter message without receipts')
2366
+ }
2367
+ }
2368
+ ;(0, Utils_1.cleanMessage)(msg, authState.creds.me.id, authState.creds.me.lid)
2369
+ const msgTs = (0, Utils_1.toNumber)(msg.messageTimestamp)
2370
+ const isPending = !isConnected || node.attrs.offline || msgTs < socketCreatedAt
2371
+ if (isInteropNode) {
2372
+ logger.info(
2373
+ {
2374
+ id: msg.key.id,
2375
+ isPending,
2376
+ isConnected,
2377
+ offline: node.attrs.offline,
2378
+ msgTs,
2379
+ socketCreatedAt
2380
+ },
2381
+ isPending ? '[interop] upsert as append (pending/offline)' : '[interop] upsert as notify'
2382
+ )
2383
+ }
2384
+ if (isPending) {
2385
+ await upsertMessage(msg, 'append')
2386
+ return
2387
+ }
2388
+ let groupDataForNormalization
2389
+ if ((0, WABinary_1.isJidGroup)(msg?.key?.remoteJid)) {
2390
+ try {
2391
+ groupDataForNormalization =
2392
+ (config.useCachedGroupMetadata && config.cachedGroupMetadata
2393
+ ? await config.cachedGroupMetadata(msg.key.remoteJid)
2394
+ : undefined) || (await sock.groupMetadata(msg.key.remoteJid))
2395
+ } catch (error) {
2396
+ logger.debug({ error, jid: msg.key.remoteJid }, 'failed to fetch group metadata for recv jid normalization')
2397
+ }
2398
+ }
2399
+ await (0, jid_display_normalization_1.normalizeMessageForDisplayJids)(
2400
+ msg,
2401
+ signalRepository,
2402
+ logger,
2403
+ groupDataForNormalization
2404
+ )
2405
+ await upsertMessage(msg, 'notify')
2406
+ })
2407
+ } catch (error) {
2408
+ if (isInteropNode) {
2409
+ logger.error(
2410
+ { error: error?.message, stack: error?.stack, from: node.attrs.from, id: node.attrs.id },
2411
+ '[interop] unhandled error in handleMessage'
2412
+ )
2413
+ }
2414
+ logger.error({ error, node: (0, WABinary_1.binaryNodeToString)(node) }, 'error in handling message')
2415
+ if (!acked) {
2416
+ await sendMessageAck(node, Utils_1.NACK_REASONS.UnhandledError).catch(ackErr =>
2417
+ logger.error({ ackErr }, 'failed to ack message after error')
2418
+ )
2419
+ }
2420
+ }
2421
+ }
2422
+ // group_info roster: <group_info><user jid=.. state=.. user_pn=..><device jid=..
2423
+ // platform=..><capability ver=../></device></user>...</group_info>. Baileys previously
2424
+ // only kept the flat group_info-level attrs (call.payload), dropping the roster entirely.
2425
+ const parseGroupCallRoster = groupInfoNode =>
2426
+ (0, WABinary_1.getBinaryNodeChildren)(groupInfoNode, 'user').map(userNode => ({
2427
+ jid: userNode.attrs.jid,
2428
+ state: userNode.attrs.state,
2429
+ userPn: userNode.attrs.user_pn,
2430
+ devices: (0, WABinary_1.getBinaryNodeChildren)(userNode, 'device').map(d => ({
2431
+ jid: d.attrs.jid,
2432
+ platform: d.attrs.platform
2433
+ }))
2434
+ }))
2435
+ const handleCall = async node => {
2436
+ try {
2437
+ const { attrs } = node
2438
+ const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node)
2439
+ if (!infoChild) {
2440
+ throw new boom_1.Boom('Missing call info in call node')
2441
+ }
2442
+ const status = (0, Utils_1.getCallStatusFromNode)(infoChild)
2443
+ const callId = infoChild.attrs['call-id']
2444
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator']
2445
+ const call = {
2446
+ chatId: attrs.from,
2447
+ from,
2448
+ callerPn: infoChild.attrs['caller_pn'],
2449
+ id: callId,
2450
+ date: new Date(+attrs.t * 1000),
2451
+ offline: !!attrs.offline,
2452
+ status
2453
+ }
2454
+ if (status === 'relaylatency') {
2455
+ const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms']
2456
+ const latencyMs = latencyValue ? Number(latencyValue) : undefined
2457
+ if (Number.isFinite(latencyMs)) {
2458
+ call.latencyMs = latencyMs
2459
+ }
2460
+ }
2461
+ if (status === 'offer') {
2462
+ const videoNode = (0, WABinary_1.getBinaryNodeChild)(infoChild, 'video')
2463
+ const audioNodes = (0, WABinary_1.getBinaryNodeChildren)(infoChild, 'audio')
2464
+ const silenceNode = (0, WABinary_1.getBinaryNodeChild)(infoChild, 'silence')
2465
+ call.isVideo = !!videoNode
2466
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid']
2467
+ call.groupJid = infoChild.attrs['group-jid']
2468
+ // lightweight=1 marks a silent/wave-style group ring (no full ringing UX expected)
2469
+ call.isLightweight = infoChild.attrs.lightweight === '1'
2470
+ if (silenceNode?.attrs?.reason) {
2471
+ call.silenceReason = silenceNode.attrs.reason
2472
+ }
2473
+ // Wire attrs are "enc"/"rate" (audio) and "dec" (video) — not "codec".
2474
+ // <audio> can repeat once per supported sample rate.
2475
+ if (audioNodes.length) {
2476
+ call.audioCodecs = audioNodes.map(n => ({ enc: n.attrs.enc, rate: n.attrs.rate ? +n.attrs.rate : undefined }))
2477
+ call.audioCodec = audioNodes[0].attrs.enc
2478
+ }
2479
+ if (videoNode?.attrs?.dec) {
2480
+ call.videoCodec = videoNode.attrs.dec
2481
+ }
2482
+ // Decrypt Signal-encrypted callKey from <enc> child
2483
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(infoChild, 'enc')
2484
+ if (encNode?.content) {
2485
+ try {
2486
+ const encType = encNode.attrs.type || 'msg'
2487
+ const ciphertext = Buffer.isBuffer(encNode.content) ? encNode.content : Buffer.from(encNode.content)
2488
+ const decrypted = await signalRepository.decryptMessage({ jid: attrs.from, type: encType, ciphertext })
2489
+ const unpadded = (0, Utils_1.unpadRandomMax16)(decrypted)
2490
+ const callMsg = index_js_1.proto.Message.decode(unpadded)
2491
+ if (callMsg?.call?.callKey?.length) {
2492
+ call.callKey = Buffer.from(callMsg.call.callKey)
2493
+ }
2494
+ } catch (e) {
2495
+ logger.debug({ e }, 'failed to decrypt call enc')
2496
+ }
2497
+ }
2498
+ await callOfferCache.set(call.id, call)
2499
+ } else if (status === 'waiting_room_request') {
2500
+ call.peerJid = infoChild.attrs.from || infoChild.attrs['peer-jid'] || infoChild.attrs['user-jid']
2501
+ }
2502
+ const existingCall = await callOfferCache.get(call.id)
2503
+ // use existing call info to populate this event
2504
+ if (existingCall) {
2505
+ call.isVideo = existingCall.isVideo
2506
+ call.isGroup = existingCall.isGroup
2507
+ call.callerPn = call.callerPn || existingCall.callerPn
2508
+ }
2509
+ // Enrich event payload for signalling-only statuses
2510
+ if (status === 'peer_state') {
2511
+ const stateChild = (0, WABinary_1.getBinaryNodeChild)(infoChild, 'peer_state')
2512
+ call.state = stateChild?.attrs?.state || infoChild.attrs?.state
2513
+ } else if (status === 'group_info') {
2514
+ call.payload = infoChild.attrs
2515
+ call.participants = parseGroupCallRoster(infoChild)
2516
+ } else if (status === 'video_state') {
2517
+ const vsChild = (0, WABinary_1.getBinaryNodeChild)(infoChild, 'video_state')
2518
+ const enabledRaw = vsChild?.attrs?.enabled ?? infoChild.attrs?.enabled
2519
+ call.enabled = enabledRaw === 'true' || enabledRaw === '1'
2520
+ } else if (status === 'enc_rekey') {
2521
+ const rekeyChild =
2522
+ (0, WABinary_1.getBinaryNodeChild)(infoChild, 'enc-rekey') ||
2523
+ (0, WABinary_1.getBinaryNodeChild)(infoChild, 'enc_rekey')
2524
+ if (rekeyChild?.content && Buffer.isBuffer(rekeyChild.content)) {
2525
+ try {
2526
+ call.rekeyPayload = (0, Utils_1.decodeE2eRekeyPayload)(rekeyChild.content)
2527
+ } catch (e) {
2528
+ logger.debug({ e }, 'failed to decode enc-rekey payload in handleCall')
2529
+ }
2530
+ }
2531
+ }
2532
+ // delete data once call has ended
2533
+ if (
2534
+ status === 'reject' ||
2535
+ status === 'accept' ||
2536
+ status === 'timeout' ||
2537
+ status === 'terminate' ||
2538
+ status === 'reject_do_not_disturb' ||
2539
+ status === 'mic_permission_denied' ||
2540
+ status === 'camera_permission_denied' ||
2541
+ status === 'remote_busy' ||
2542
+ status === 'remote_offline'
2543
+ ) {
2544
+ await callOfferCache.del(call.id)
2545
+ }
2546
+ await normalizeCallEventJids(call, infoChild)
2547
+ ev.emit('call', [call])
2548
+ } catch (error) {
2549
+ logger.error({ error, node: (0, WABinary_1.binaryNodeToString)(node) }, 'error in handling call')
2550
+ } finally {
2551
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'))
2552
+ }
2553
+ }
2554
+ // Some accounts receive call signalling as TOP-LEVEL stanzas (<offer>, <terminate>,
2555
+ // <mute_v2>, <transport>, … each with a call-id) instead of wrapped in <call>.
2556
+ // This additively handles those: emit a 'call' event for state stanzas and ack ALL
2557
+ // of them (otherwise WhatsApp keeps redelivering). The <call> path above is untouched.
2558
+ const CALL_STATE_TAGS = new Set([
2559
+ 'offer',
2560
+ 'offer_notice',
2561
+ 'terminate',
2562
+ 'accept',
2563
+ 'reject',
2564
+ 'preaccept',
2565
+ 'accept_ack',
2566
+ 'enc-rekey',
2567
+ 'enc_rekey',
2568
+ 'peer_state',
2569
+ 'group_info',
2570
+ 'video_state',
2571
+ 'video_state_ack',
2572
+ 'flow_control',
2573
+ 'mute_v2',
2574
+ 'waiting_room_request'
2575
+ ])
2576
+ const handleStandaloneCallStanza = async node => {
2577
+ try {
2578
+ if (!CALL_STATE_TAGS.has(node.tag)) {
2579
+ return // media/relay signalling (transport, video, duration, mute_v2, lobby, …): ack only
2580
+ }
2581
+ const { attrs } = node
2582
+ const status = (0, Utils_1.getCallStatusFromNode)(node)
2583
+ const callId = attrs['call-id']
2584
+ const from = attrs.from || attrs['call-creator']
2585
+ const call = {
2586
+ chatId: attrs.from || from,
2587
+ from,
2588
+ callerPn: attrs['caller_pn'],
2589
+ id: callId,
2590
+ date: attrs.t ? new Date(+attrs.t * 1000) : new Date(),
2591
+ offline: !!attrs.offline,
2592
+ status
2593
+ }
2594
+ if (status === 'offer') {
2595
+ const videoNode = (0, WABinary_1.getBinaryNodeChild)(node, 'video')
2596
+ const audioNodes = (0, WABinary_1.getBinaryNodeChildren)(node, 'audio')
2597
+ const silenceNode = (0, WABinary_1.getBinaryNodeChild)(node, 'silence')
2598
+ call.isVideo = !!videoNode
2599
+ call.isGroup = attrs.type === 'group' || !!attrs['group-jid']
2600
+ call.groupJid = attrs['group-jid']
2601
+ call.isLightweight = attrs.lightweight === '1'
2602
+ if (silenceNode?.attrs?.reason) {
2603
+ call.silenceReason = silenceNode.attrs.reason
2604
+ }
2605
+ // Wire attrs are "enc"/"rate" (audio) and "dec" (video) — not "codec".
2606
+ if (audioNodes.length) {
2607
+ call.audioCodecs = audioNodes.map(n => ({ enc: n.attrs.enc, rate: n.attrs.rate ? +n.attrs.rate : undefined }))
2608
+ call.audioCodec = audioNodes[0].attrs.enc
2609
+ }
2610
+ if (videoNode?.attrs?.dec) {
2611
+ call.videoCodec = videoNode.attrs.dec
2612
+ }
2613
+ if (callId) {
2614
+ await callOfferCache.set(callId, call)
2615
+ }
2616
+ }
2617
+ const existingCall = callId ? await callOfferCache.get(callId) : undefined
2618
+ if (existingCall) {
2619
+ call.isVideo = existingCall.isVideo
2620
+ call.isGroup = existingCall.isGroup
2621
+ call.callerPn = call.callerPn || existingCall.callerPn
2622
+ }
2623
+ // Enrich event payload for signalling-only statuses
2624
+ if (status === 'peer_state') {
2625
+ const stateChild = (0, WABinary_1.getBinaryNodeChild)(node, 'peer_state')
2626
+ call.state = stateChild?.attrs?.state || attrs?.state
2627
+ } else if (status === 'group_info') {
2628
+ call.payload = attrs
2629
+ call.participants = parseGroupCallRoster(node)
2630
+ } else if (status === 'video_state') {
2631
+ const vsChild = (0, WABinary_1.getBinaryNodeChild)(node, 'video_state')
2632
+ const enabledRaw = vsChild?.attrs?.enabled ?? attrs?.enabled
2633
+ call.enabled = enabledRaw === 'true' || enabledRaw === '1'
2634
+ } else if (status === 'enc_rekey') {
2635
+ const rekeyChild =
2636
+ (0, WABinary_1.getBinaryNodeChild)(node, 'enc-rekey') || (0, WABinary_1.getBinaryNodeChild)(node, 'enc_rekey')
2637
+ if (rekeyChild?.content && Buffer.isBuffer(rekeyChild.content)) {
2638
+ try {
2639
+ call.rekeyPayload = (0, Utils_1.decodeE2eRekeyPayload)(rekeyChild.content)
2640
+ } catch (e) {
2641
+ logger.debug({ e }, 'failed to decode enc-rekey payload in standalone call stanza')
2642
+ }
2643
+ }
2644
+ } else if (status === 'mute') {
2645
+ // mute_v2 IS the top-level tag on real traffic (no wrapping/nested child) —
2646
+ // attrs are { call-id, call-creator, mute-state: "0"|"1" }, never
2647
+ // muted/audio_muted, and there's no nested <audio> child.
2648
+ call.muted = node.attrs['mute-state'] === '1'
2649
+ }
2650
+ if (
2651
+ callId &&
2652
+ (status === 'reject' ||
2653
+ status === 'accept' ||
2654
+ status === 'timeout' ||
2655
+ status === 'terminate' ||
2656
+ status === 'reject_do_not_disturb' ||
2657
+ status === 'mic_permission_denied' ||
2658
+ status === 'camera_permission_denied' ||
2659
+ status === 'remote_busy' ||
2660
+ status === 'remote_offline')
2661
+ ) {
2662
+ await callOfferCache.del(callId)
2663
+ }
2664
+ await normalizeCallEventJids(call, node)
2665
+ ev.emit('call', [call])
2666
+ } catch (error) {
2667
+ logger.error({ error, node: (0, WABinary_1.binaryNodeToString)(node) }, 'error handling standalone call stanza')
2668
+ } finally {
2669
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack standalone call'))
2670
+ }
2671
+ }
2672
+ const handleBadAck = async ({ attrs }) => {
2673
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id }
2674
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
2675
+ // // current hypothesis is that if pash is sent in the ack
2676
+ // // it means -- the message hasn't reached all devices yet
2677
+ // // we'll retry sending the message here
2678
+ // if(attrs.phash) {
2679
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
2680
+ // const msg = await getMessage(key)
2681
+ // if(msg) {
2682
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
2683
+ // } else {
2684
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
2685
+ // }
2686
+ // }
2687
+ // error in acknowledgement,
2688
+ // device could not display the message
2689
+ if (attrs.error) {
2690
+ if (attrs.error === Utils_1.SERVER_ERROR_CODES.MissingTcToken) {
2691
+ // 463 = account restricted + no tctoken for this contact.
2692
+ // WA Web prevents this client-side (disables compose bar).
2693
+ // No retry — retrying worsens the restriction by counting as another "reach out" to an unknown contact.
2694
+ logger.warn(
2695
+ { msgId: attrs.id, from: attrs.from },
2696
+ 'error 463: account restricted or missing tctoken for contact'
2697
+ )
2698
+ } else if (attrs.error === Utils_1.SERVER_ERROR_CODES.SmaxInvalid) {
2699
+ logger.warn(
2700
+ { msgId: attrs.id, from: attrs.from },
2701
+ 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing'
2702
+ )
2703
+ } else {
2704
+ logger.warn({ attrs }, 'received error in ack')
2705
+ }
2706
+ ev.emit('messages.update', [
2707
+ {
2708
+ key,
2709
+ update: {
2710
+ status: Types_1.WAMessageStatus.ERROR,
2711
+ messageStubParameters: [attrs.error]
2712
+ }
2713
+ }
2714
+ ])
2715
+ // resend the message with device_fanout=false, use at your own risk
2716
+ // if (attrs.error === '475') {
2717
+ // const msg = await getMessage(key)
2718
+ // if (msg) {
2719
+ // await relayMessage(key.remoteJid!, msg, {
2720
+ // messageId: key.id!,
2721
+ // useUserDevicesCache: false,
2722
+ // additionalAttributes: {
2723
+ // device_fanout: 'false'
2724
+ // }
2725
+ // })
2726
+ // }
2727
+ // }
2728
+ }
2729
+ }
2730
+ const handleChatstate = async node => {
2731
+ const { from, state } = node.attrs
2732
+ if (!from) return
2733
+ const isTyping = state === 'typing'
2734
+ ev.emit('presence.update', [
2735
+ {
2736
+ id: from,
2737
+ presences: {
2738
+ [from]: isTyping ? 'composing' : 'paused'
2739
+ }
2740
+ }
2741
+ ])
2742
+ }
2743
+ const handlePresence = async node => {
2744
+ const { from, type } = node.attrs
2745
+ if (!from || !type) return
2746
+ const presenceMap = {
2747
+ available: 'available',
2748
+ unavailable: 'unavailable'
2749
+ }
2750
+ const presence = presenceMap[type] || type
2751
+ ev.emit('presence.update', [
2752
+ {
2753
+ id: from,
2754
+ presences: {
2755
+ [from]: presence
2756
+ },
2757
+ lastSeen: node.attrs.t ? Number(node.attrs.t) * 1000 : undefined
2758
+ }
2759
+ ])
2760
+ }
2761
+ /// processes a node with the given function
2762
+ /// and adds the task to the existing buffer if we're buffering events
2763
+ const processNodeWithBuffer = async (node, identifier, exec) => {
2764
+ ev.buffer()
2765
+ await execTask()
2766
+ ev.flush()
2767
+ function execTask() {
2768
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier))
2769
+ }
2770
+ }
2771
+ const offlineNodeProcessor = (0, offline_node_processor_1.makeOfflineNodeProcessor)(
2772
+ new Map([
2773
+ ['message', handleMessage],
2774
+ ['call', handleCall],
2775
+ ['receipt', handleReceipt],
2776
+ ['notification', handleNotification]
2777
+ ]),
2778
+ {
2779
+ isWsOpen: () => ws.isOpen,
2780
+ onUnexpectedError,
2781
+ yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
2782
+ }
2783
+ )
2784
+ const processNode = async (type, node, identifier, exec) => {
2785
+ const isOffline = !!node.attrs.offline
2786
+ if (isOffline) {
2787
+ offlineNodeProcessor.enqueue(type, node)
2788
+ } else {
2789
+ await processNodeWithBuffer(node, identifier, exec)
2790
+ }
2791
+ }
2792
+ let latestNodeInMemory = null
2793
+ const nodelogger = node => {
2794
+ if (!node) return null
2795
+ latestNodeInMemory = node
2796
+ return latestNodeInMemory
2797
+ }
2798
+ const setNodeLoggerListener = () => {
2799
+ return latestNodeInMemory
2800
+ }
2801
+ // recv a message
2802
+ ws.on('CB:message', async node => {
2803
+ nodelogger(node)
2804
+ await processNode('message', node, 'processing message', handleMessage)
2805
+ })
2806
+ ws.on('CB:call', async node => {
2807
+ nodelogger(node)
2808
+ await processNode('call', node, 'handling call', handleCall)
2809
+ })
2810
+ // additive: top-level call-signalling stanzas (some accounts send these instead of <call>)
2811
+ for (const callTag of [
2812
+ 'offer',
2813
+ 'offer_notice',
2814
+ 'terminate',
2815
+ 'accept',
2816
+ 'reject',
2817
+ 'preaccept',
2818
+ 'accept_ack',
2819
+ 'enc-rekey',
2820
+ 'enc_rekey',
2821
+ 'peer_state',
2822
+ 'group_info',
2823
+ 'video_state',
2824
+ 'video_state_ack',
2825
+ 'flow_control',
2826
+ 'transport',
2827
+ 'video',
2828
+ 'duration',
2829
+ 'mute_v2',
2830
+ 'lobby',
2831
+ 'heartbeat',
2832
+ 'relaylatency',
2833
+ 'link_query',
2834
+ 'waiting_room_request',
2835
+ // Present in Utils/stanza-ack.js's CALL_STANZA_TAGS (ack builder already treats it as a
2836
+ // call stanza) but was missing here — meant it was never routed/acked, so real traffic
2837
+ // (confirmed via live capture) would just get redelivered forever.
2838
+ 'group_update'
2839
+ ]) {
2840
+ ws.on('CB:' + callTag, node => {
2841
+ nodelogger(node)
2842
+ handleStandaloneCallStanza(node).catch(error => onUnexpectedError(error, 'handling standalone call stanza'))
2843
+ })
2844
+ }
2845
+ ws.on('CB:receipt', async node => {
2846
+ nodelogger(node)
2847
+ await processNode('receipt', node, 'handling receipt', handleReceipt)
2848
+ })
2849
+ ws.on('CB:notification', async node => {
2850
+ nodelogger(node)
2851
+ await processNode('notification', node, 'handling notification', handleNotification)
2852
+ })
2853
+ ws.on('CB:status', async node => {
2854
+ nodelogger(node)
2855
+ await handleNewsletterStatus(node).catch(error => onUnexpectedError(error, 'handling newsletter status'))
2856
+ })
2857
+ ws.on('CB:chatstate', async node => {
2858
+ nodelogger(node)
2859
+ await handleChatstate(node).catch(error => onUnexpectedError(error, 'handling chatstate'))
2860
+ })
2861
+ ws.on('CB:presence', async node => {
2862
+ nodelogger(node)
2863
+ await handlePresence(node).catch(error => onUnexpectedError(error, 'handling presence'))
2864
+ })
2865
+ ws.on('CB:ack,class:message', node => {
2866
+ nodelogger(node)
2867
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'))
2868
+ })
2869
+ const linkedParentMap = {}
2870
+ ws.on('CB:iq', node => {
2871
+ if (node && node.tag === 'iq' && node.attrs.type === 'result') {
2872
+ const groups = node.content
2873
+
2874
+ if (Array.isArray(groups)) {
2875
+ for (const group of groups) {
2876
+ const groupId = group.attrs.id + '@g.us'
2877
+
2878
+ if (group && Array.isArray(group.content)) {
2879
+ for (const item of group.content) {
2880
+ if (item.tag === 'linked_parent' && item.attrs && item.attrs.jid) {
2881
+ linkedParentMap[groupId] = item.attrs.jid
2882
+ }
2883
+ }
2884
+ }
2885
+ }
2886
+ }
2887
+ }
2888
+ })
2889
+ ev.on('call', async ([call]) => {
2890
+ if (!call) {
2891
+ return
2892
+ }
2893
+ nodelogger(call)
2894
+ // missed call + group call notification message generation
2895
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
2896
+ const msg = {
2897
+ key: {
2898
+ remoteJid: call.chatId,
2899
+ id: call.id,
2900
+ fromMe: false
2901
+ },
2902
+ messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date)
2903
+ }
2904
+ if (call.status === 'timeout') {
2905
+ if (call.isGroup) {
2906
+ msg.messageStubType = call.isVideo
2907
+ ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO
2908
+ : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE
2909
+ } else {
2910
+ msg.messageStubType = call.isVideo
2911
+ ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO
2912
+ : Types_1.WAMessageStubType.CALL_MISSED_VOICE
2913
+ }
2914
+ } else {
2915
+ msg.message = { call: { callKey: Buffer.from(call.id) } }
2916
+ }
2917
+ const protoMsg = index_js_1.proto.WebMessageInfo.fromObject(msg)
2918
+ await upsertMessage(protoMsg, call.offline ? 'append' : 'notify')
2919
+ }
2920
+ })
2921
+ let lastTcTokenPruneTs = 0
2922
+ ev.on('connection.update', ({ isOnline, connection }) => {
2923
+ if (connection === 'open') {
2924
+ isConnected = true
2925
+ }
2926
+ if (typeof isOnline !== 'undefined') {
2927
+ sendActiveReceipts = isOnline
2928
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`)
2929
+ }
2930
+ // Daily cleanup of expired tctokens (mirrors WA Web's CLEAN_TC_TOKENS task)
2931
+ if (isOnline) {
2932
+ const now = Date.now()
2933
+ const DAY_MS = 24 * 60 * 60 * 1000
2934
+ if (now - lastTcTokenPruneTs >= DAY_MS) {
2935
+ lastTcTokenPruneTs = now
2936
+ void pruneExpiredTcTokens()
2937
+ }
2938
+ }
2939
+ })
2940
+ async function pruneExpiredTcTokens() {
2941
+ try {
2942
+ await tcTokenIndexLoaded
2943
+ const persisted = await (0, tc_token_utils_1.readTcTokenIndex)(authState.keys)
2944
+ const allJids = new Set(tcTokenKnownJids)
2945
+ for (const jid of persisted) allJids.add(jid)
2946
+ if (!allJids.size) return
2947
+ const jids = [...allJids]
2948
+ const allTokens = await authState.keys.get('tctoken', jids)
2949
+ const writes = {}
2950
+ const survivors = new Set()
2951
+ let mutated = 0
2952
+ for (const jid of jids) {
2953
+ const entry = allTokens[jid]
2954
+ if (!entry) {
2955
+ mutated++
2956
+ continue
2957
+ }
2958
+ const hasPeerToken = !!entry.token?.length
2959
+ const peerTokenExpired = hasPeerToken && (0, tc_token_utils_1.isTcTokenExpired)(entry.timestamp)
2960
+ const hasSenderTs = entry.senderTimestamp !== undefined
2961
+ const senderTsExpired = hasSenderTs && (0, tc_token_utils_1.isTcTokenExpired)(entry.senderTimestamp)
2962
+ const keepPeerToken = hasPeerToken && !peerTokenExpired
2963
+ const keepSenderTs = hasSenderTs && !senderTsExpired
2964
+ if (!keepPeerToken && !keepSenderTs) {
2965
+ writes[jid] = null
2966
+ mutated++
2967
+ } else if (peerTokenExpired && keepSenderTs) {
2968
+ writes[jid] = { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
2969
+ survivors.add(jid)
2970
+ mutated++
2971
+ } else {
2972
+ survivors.add(jid)
2973
+ }
2974
+ }
2975
+ if (mutated === 0) return
2976
+ await authState.keys.set({
2977
+ tctoken: {
2978
+ ...writes,
2979
+ [tc_token_utils_1.TC_TOKEN_INDEX_KEY]: {
2980
+ token: Buffer.from(JSON.stringify([...survivors]))
2981
+ }
2982
+ }
2983
+ })
2984
+ tcTokenKnownJids.clear()
2985
+ for (const jid of survivors) tcTokenKnownJids.add(jid)
2986
+ logger.debug({ mutated, remaining: survivors.size }, 'pruned expired tctokens')
2987
+ } catch (err) {
2988
+ logger.warn({ err: err?.message }, 'failed to prune expired tctokens')
2989
+ }
2990
+ }
2991
+ return {
2992
+ ...sock,
2993
+ sendMessageAck,
2994
+ sendRetryRequest,
2995
+ offerCall,
2996
+ rejectCall,
2997
+ acceptCall,
2998
+ terminateCall,
2999
+ rekeyCall,
3000
+ joinCallLink,
3001
+ queryCallLink,
3002
+ nodelogger,
3003
+ setNodeLoggerListener,
3004
+ fetchMessageHistory,
3005
+ requestPlaceholderResend,
3006
+ requestWaffleNonce,
3007
+ requestCompanionCanonicalNonce,
3008
+ requestCompanionMetaNonce,
3009
+ messageRetryManager
3010
+ }
3011
+ }
3012
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket