@zervonexx/baileys 5.0.0 → 5.0.1

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 (125) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4112 -4112
  3. package/WAProto/WAProtoCompile.js +322 -322
  4. package/WAProto/fetcher.js +67 -67
  5. package/WAProto/index.js +95 -95
  6. package/WAProto/parser.js +333 -333
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +248 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +14 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +194 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +2 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +942 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +191 -192
@@ -1,994 +1,994 @@
1
- import NodeCache from '@cacheable/node-cache'
2
- import { Boom } from '@hapi/boom'
3
- import { randomBytes } from 'crypto'
4
- import { proto } from '../../WAProto/index.js'
5
- import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/index.js'
6
- import { ReachoutTimelockEnforcementType, WAMessageStatus, WAMessageStubType } from '../Types/index.js'
7
- import {
8
- aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode,
9
- decodeMessageNode, makeMutex, decryptMessageNode, delay, derivePairingCodeKey,
10
- encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext,
11
- extractE2ESessionFromRetryReceipt, getCallStatusFromNode, getHistoryMsg,
12
- getNextPreKeys, getStatusFromReceiptType, extractMessageText,
13
- handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS,
14
- NO_MESSAGE_FOUND_ERROR_TEXT, SERVER_ERROR_CODES, toNumber, unixTimestampSeconds,
15
- xmppPreKey, xmppSignedPreKey, ACCOUNT_RESTRICTED_TEXT, buildMergedTcTokenIndexWrite,
16
- isTcTokenExpired, readTcTokenIndex, resolveTcTokenJid, resolveIssuanceJid,
17
- storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY, decryptMsmsgBotMessage,
18
- decodeDecryptedMsmsgMessage, extractReportingInfoFromStanza, getContentType,
19
- } from '../Utils/index.js'
20
- import {
21
- areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild,
22
- getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString,
23
- getBinaryNodeChildUInt, isJidGroup, isJidNewsletter, isJidStatusBroadcast,
24
- isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET, jidEncode,
25
- } from '../WABinary/index.js'
26
- import { extractGroupMetadata } from './groups.js'
27
- import { makeMessagesSocket } from './messages-send.js'
28
-
29
- // ─── Pure stanza builders ─────────────────────────────────────────────────────
30
-
31
- export const buildGroupCallStanza = ({ id, to, callId, callCreator, offerContent }) => ({
32
- tag: 'call',
33
- attrs: { id, to },
34
- content: [{ tag: 'offer', attrs: { 'call-id': callId, 'call-creator': callCreator, type: 'group', 'group-jid': to }, content: offerContent }]
35
- })
36
-
37
- export const buildGroupCallCancelStanza = ({ to, callId, callCreator }) => ({
38
- tag: 'call',
39
- attrs: { from: callCreator, to },
40
- content: [{ tag: 'terminate', attrs: { 'call-id': callId, 'call-creator': callCreator, reason: 'user-terminated', count: '0' }, content: undefined }]
41
- })
42
-
43
- const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(ReachoutTimelockEnforcementType))
44
- const isValidEnforcementType = (value) => typeof value === 'string' && ENFORCEMENT_TYPE_VALUES.has(value)
45
-
46
- // ─── Socket ───────────────────────────────────────────────────────────────────
47
-
48
- export const makeMessagesRecvSocket = (config) => {
49
- const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config
50
- const sock = makeMessagesSocket(config)
51
- const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager, registerSocketEndHandler, issuePrivacyTokens, fetchAccountReachoutTimelock, placeholderResendCache: sockPlaceholderResendCache } = sock
52
-
53
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
54
- const { messageMutex, notificationMutex, receiptMutex: _receiptMutex, placeholderResendCache } = sock
55
- const retryMutex = makeMutex()
56
- const msgRetryCache = config.msgRetryCounterCache || new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, useClones: false })
57
- const callOfferCache = config.callOfferCache || new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, useClones: false })
58
- const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false })
59
- const inFlightPreKeyLow = new Set()
60
- const inFlight463Recoveries = new Set()
61
-
62
- let sendActiveReceipts = false
63
-
64
- // ── PDO helpers ───────────────────────────────────────────────────────────
65
-
66
- const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
67
- if (!authState.creds.me?.id) throw new Boom('Not authenticated')
68
- return sendPeerDataOperationMessage({ historySyncOnDemandRequest: { chatJid: oldestMsgKey.remoteJid, oldestMsgFromMe: oldestMsgKey.fromMe, oldestMsgId: oldestMsgKey.id, oldestMsgTimestampMs: oldestMsgTimestamp, onDemandMsgCount: count }, peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND })
69
- }
70
-
71
- const requestPlaceholderResend = async (messageKey, msgData) => {
72
- if (!authState.creds.me?.id) throw new Boom('Not authenticated')
73
- if (await placeholderResendCache.get(messageKey?.id)) { logger.debug({ messageKey }, 'already requested resend'); return }
74
- await placeholderResendCache.set(messageKey?.id, msgData || true)
75
- await delay(2000)
76
- if (!(await placeholderResendCache.get(messageKey?.id))) { logger.debug({ messageKey }, 'message received while resend requested'); return 'RESOLVED' }
77
- setTimeout(async () => { if (await placeholderResendCache.get(messageKey?.id)) { logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline'); await placeholderResendCache.del(messageKey?.id) } }, 8000)
78
- return sendPeerDataOperationMessage({ placeholderMessageResendRequest: [{ messageKey }], peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND })
79
- }
80
-
81
- const requestContactRefresh = async (jids) => {
82
- if (!jids?.length) return
83
- return sendPeerDataOperationMessage({ contactRefreshRequest: { jids: Array.isArray(jids) ? jids : [jids] }, peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.CONTACT_REFRESH_REQUEST })
84
- }
85
-
86
- // ── Newsletter notifications ──────────────────────────────────────────────
87
-
88
- const handleReachoutTimelockNotification = (data) => {
89
- const payload = data.xwa2_notify_account_reachout_timelock
90
- if (!payload) { logger.warn('reachout timelock notification missing payload'); return }
91
- if (!payload.is_active) { ev.emit('connection.update', { reachoutTimeLock: { isActive: false, enforcementType: ReachoutTimelockEnforcementType.DEFAULT } }); return }
92
- const timeEnforcementEnds = payload.time_enforcement_ends ? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000) : new Date(Date.now() + 60000)
93
- const enforcementType = isValidEnforcementType(payload.enforcement_type) ? payload.enforcement_type : ReachoutTimelockEnforcementType.DEFAULT
94
- logger.info({ enforcementType, timeEnforcementEnds }, 'reachout timelock restriction set')
95
- ev.emit('connection.update', { reachoutTimeLock: { isActive: true, timeEnforcementEnds, enforcementType } })
96
- }
97
-
98
- const handleMessageCappingNotification = (data) => {
99
- const payload = data.xwa2_notify_new_chat_messages_capping_info_update
100
- if (!payload) { logger.warn('message capping notification missing payload'); return }
101
- logger.info({ payload }, 'received message capping update')
102
- ev.emit('message-capping.update', payload)
103
- }
104
-
105
- const handleLegacyMexNewsletterNotification = async (node) => {
106
- const mexNode = getBinaryNodeChild(node, 'mex')
107
- const updateNode = mexNode?.content ? null : getBinaryNodeChild(node, 'update') || getAllBinaryNodeChildren(node)[0]
108
- const payloadNode = mexNode?.content ? mexNode : updateNode
109
- if (!payloadNode?.content) { logger.warn({ node: binaryNodeToString(node) }, 'invalid mex newsletter notification'); return }
110
- let data
111
- try {
112
- const payloadContent = payloadNode.content
113
- if (Array.isArray(payloadContent)) { logger.warn({ payloadNode }, 'invalid mex newsletter notification payload format'); return }
114
- const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent)
115
- data = JSON.parse(contentBuf.toString())
116
- } catch (error) { logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification'); return }
117
- const operation = data?.operation ?? payloadNode?.attrs?.op_name
118
- let updates = data?.updates
119
- if (!updates) { const linkedProfiles = data?.data?.xwa2_notify_linked_profiles; if (linkedProfiles) updates = [linkedProfiles] }
120
- if (!updates || !operation) { logger.warn({ data }, 'invalid mex newsletter notification content'); return }
121
- logger.info({ operation, updates }, 'got mex newsletter notification')
122
- switch (operation) {
123
- case 'NotificationNewsletterUpdate':
124
- for (const update of updates) if (update.jid && update.settings && Object.keys(update.settings).length > 0) ev.emit('newsletter-settings.update', { id: update.jid, update: update.settings })
125
- break
126
- case 'NotificationNewsletterAdminPromote':
127
- for (const update of updates) if (update.jid && update.user) ev.emit('newsletter-participants.update', { id: update.jid, author: node.attrs.from, user: update.user, new_role: 'ADMIN', action: 'promote' })
128
- break
129
- case 'NotificationLinkedProfilesUpdates':
130
- for (const update of updates) {
131
- const lid = update?.jid
132
- const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : []
133
- const mappings = []
134
- for (const profile of addedProfiles) {
135
- const pn = typeof profile === 'string' ? profile : (profile?.pn ?? profile?.jid ?? null)
136
- if (lid && pn) { const mapping = { lid, pn }; ev.emit('lid-mapping.update', mapping); mappings.push(mapping) }
137
- }
138
- await signalRepository.lidMapping.storeLIDPNMappings(mappings)
139
- }
140
- break
141
- default:
142
- logger.info({ operation, data }, 'unhandled mex newsletter notification')
143
- }
144
- }
145
-
146
- const handleMexNotification = async (node) => {
147
- const updateNode = getBinaryNodeChild(node, 'update')
148
- if (!updateNode) { await handleLegacyMexNewsletterNotification(node); return }
149
- const opName = updateNode.attrs?.op_name
150
- if (!opName) { logger.warn({ node: binaryNodeToString(node) }, 'mex notification missing op_name, fallback to legacy'); await handleLegacyMexNewsletterNotification(node); return }
151
- let mexResponse
152
- try { mexResponse = JSON.parse(updateNode.content.toString()) } catch (error) { logger.error({ err: error, opName }, 'failed to parse mex notification JSON'); return }
153
- if (mexResponse.errors?.length) { logger.warn({ errors: mexResponse.errors, opName }, 'mex notification has GQL errors'); return }
154
- const data = mexResponse.data
155
- if (!data) { logger.warn({ opName }, 'mex notification has null data'); return }
156
- logger.debug({ opName }, 'processing mex notification')
157
- switch (opName) {
158
- case 'NotificationUserReachoutTimelockUpdate': handleReachoutTimelockNotification(data); break
159
- case 'MessageCappingInfoNotification': handleMessageCappingNotification(data); break
160
- case 'NotificationNewsletterJoin':
161
- ev.emit('newsletter.join', data?.xwa2_notify_newsletter_on_join); break
162
- case 'NotificationNewsletterUserSettingChange':
163
- ev.emit('newsletter.viewer-settings.update', data?.xwa2_notify_newsletter_on_user_setting_change); break
164
- default: {
165
- const xwa2Key = Object.keys(data).find(k => k.startsWith('xwa2_notify_'))
166
- if (xwa2Key) {
167
- ev.emit('newsletter.update', { type: opName, data: data[xwa2Key] })
168
- logger.debug({ opName, xwa2Key }, 'emitted newsletter update from xwa2 key')
169
- } else {
170
- await handleLegacyMexNewsletterNotification(node)
171
- }
172
- break
173
- }
174
- }
175
- }
176
-
177
- const handleNewsletterNotification = async (node) => {
178
- const from = node.attrs.from
179
- const children = getAllBinaryNodeChildren(node)
180
- const author = node.attrs.participant
181
- for (const child of children) {
182
- logger.debug({ from, child }, 'got newsletter notification')
183
- switch (child.tag) {
184
- case 'reaction':
185
- ev.emit('newsletter.reaction', { id: from, server_id: child.attrs.message_id, reaction: { code: getBinaryNodeChildString(child, 'reaction'), count: 1 } })
186
- break
187
- case 'view':
188
- ev.emit('newsletter.view', { id: from, server_id: child.attrs.message_id, count: parseInt(child.content?.toString() || '0', 10) })
189
- break
190
- case 'participant':
191
- ev.emit('newsletter-participants.update', { id: from, author, user: child.attrs.jid, action: child.attrs.action, new_role: child.attrs.role })
192
- break
193
- case 'update':
194
- const settingsNode = getBinaryNodeChild(child, 'settings')
195
- if (settingsNode) {
196
- const update = {}
197
- const nameNode = getBinaryNodeChild(settingsNode, 'name')
198
- if (nameNode?.content) update.name = nameNode.content.toString()
199
- const descNode = getBinaryNodeChild(settingsNode, 'description')
200
- if (descNode?.content) update.description = descNode.content.toString()
201
- ev.emit('newsletter-settings.update', { id: from, update })
202
- }
203
- break
204
- case 'message':
205
- const plaintextNode = getBinaryNodeChild(child, 'plaintext')
206
- if (plaintextNode?.content) {
207
- try {
208
- const buf = typeof plaintextNode.content === 'string' ? Buffer.from(plaintextNode.content, 'binary') : Buffer.from(plaintextNode.content)
209
- const messageProto = proto.Message.decode(buf).toJSON()
210
- const fullMessage = proto.WebMessageInfo.fromObject({ key: { remoteJid: from, id: child.attrs.message_id || child.attrs.server_id, fromMe: false }, message: messageProto, messageTimestamp: +child.attrs.t }).toJSON()
211
- await upsertMessage(fullMessage, 'append')
212
- } catch (error) { logger.error({ error }, 'Failed to decode plaintext newsletter message') }
213
- }
214
- break
215
- default:
216
- logger.warn({ node }, 'Unknown newsletter notification')
217
- }
218
- }
219
- }
220
-
221
- // ── ACK / call helpers ────────────────────────────────────────────────────
222
-
223
- const sendMessageAck = async (node, errorCode) => {
224
- const { tag, attrs, content } = node
225
- const hasUnavailable = !!getBinaryNodeChild({ tag, attrs, content }, 'unavailable')
226
- const stanza = { tag: 'ack', attrs: { id: attrs.id, to: attrs.from, class: tag } }
227
- if (errorCode) stanza.attrs.error = errorCode.toString()
228
- if (attrs.participant) stanza.attrs.participant = attrs.participant
229
- if (attrs.recipient) stanza.attrs.recipient = attrs.recipient
230
- if (attrs.type || hasUnavailable || errorCode) stanza.attrs.type = attrs.type
231
- if (tag === 'message' && authState.creds.me?.id) stanza.attrs.from = authState.creds.me.id
232
- logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack')
233
- try { await sendNode(stanza) } catch (error) {
234
- if (error?.output?.statusCode === 428 || error?.message?.includes('Connection')) logger.warn({ id: attrs.id, error: error?.message }, 'Failed to send ACK (connection closed) - message already received')
235
- else throw error
236
- }
237
- }
238
-
239
- const rejectCall = async (callId, callFrom) => {
240
- await query({ tag: 'call', attrs: { from: authState.creds.me.id, to: callFrom }, content: [{ tag: 'reject', attrs: { 'call-id': callId, 'call-creator': callFrom, count: '0' }, content: undefined }] })
241
- }
242
-
243
- const acceptCall = async (callId, callFrom) => {
244
- await query({ tag: 'call', attrs: { from: authState.creds.me.id, to: callFrom }, content: [{ tag: 'accept', attrs: { 'call-id': callId, 'call-creator': callFrom, count: '0' }, content: undefined }] })
245
- }
246
-
247
- const terminateCall = async (callId, callFrom) => {
248
- await query({ tag: 'call', attrs: { from: authState.creds.me.id, to: callFrom }, content: [{ tag: 'terminate', attrs: { 'call-id': callId, 'call-creator': callFrom, reason: 'user-terminated', count: '0' }, content: undefined }] })
249
- }
250
-
251
- const offerCall = async (toJid, isVideo = false) => {
252
- const callId = randomBytes(16).toString('hex').toUpperCase().substring(0, 64)
253
- const offerContent = []
254
- offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '16000' }, content: undefined })
255
- offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '8000' }, content: undefined })
256
- if (isVideo) offerContent.push({ tag: 'video', attrs: { orientation: '0', screen_width: '1920', screen_height: '1080', device_orientation: '0', enc: 'vp8', dec: 'vp8' } })
257
- offerContent.push({ tag: 'net', attrs: { medium: '3' }, content: undefined })
258
- offerContent.push({ tag: 'capability', attrs: { ver: '1' }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) })
259
- offerContent.push({ tag: 'encopt', attrs: { keygen: '2' }, content: undefined })
260
- const encKey = randomBytes(32)
261
- const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => jidEncode(user, 's.whatsapp.net', device))
262
- await assertSessions(devices, true)
263
- const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, { call: { callKey: encKey } }, {})
264
- offerContent.push({ tag: 'destination', attrs: {}, content: destinations })
265
- if (shouldIncludeDeviceIdentity) offerContent.push({ tag: 'device-identity', attrs: {}, content: encodeSignedDeviceIdentity(authState.creds.account, true) })
266
- await query({ tag: 'call', attrs: { to: toJid }, content: [{ tag: 'offer', attrs: { 'call-id': callId, 'call-creator': authState.creds.me.id }, content: offerContent }] })
267
- return { callId, toJid, isVideo }
268
- }
269
-
270
- // ── Retry logic ───────────────────────────────────────────────────────────
271
-
272
- const sendRetryRequest = async (node, forceIncludeKeys = false) => {
273
- const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '')
274
- const { key: msgKey } = fullMessage
275
- const msgId = msgKey.id
276
-
277
- if (messageRetryManager) {
278
- if (messageRetryManager.hasExceededMaxRetries(msgId)) { logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing'); messageRetryManager.markRetryFailed(msgId); return }
279
- const retryCount = messageRetryManager.incrementRetryCount(msgId)
280
- await msgRetryCache.set(`${msgId}:${msgKey?.participant}`, retryCount)
281
- } else {
282
- const key = `${msgId}:${msgKey?.participant}`
283
- let retryCount = (await msgRetryCache.get(key)) || 0
284
- if (retryCount >= maxMsgRetryCount) { logger.debug({ retryCount, msgId }, 'reached retry limit, clearing'); await msgRetryCache.del(key); return }
285
- await msgRetryCache.set(key, retryCount + 1)
286
- }
287
-
288
- const retryCount = (await msgRetryCache.get(`${msgId}:${msgKey?.participant}`)) || 1
289
- const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
290
- const fromJid = node.attrs.from
291
- let shouldRecreateSession = false, recreateReason = ''
292
-
293
- if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
294
- try {
295
- const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid)
296
- const hasSession = await signalRepository.validateSession(fromJid)
297
- let lidJid = null
298
- if (isPnUser(fromJid)) lidJid = await signalRepository.lidMapping.getLIDForPN(fromJid)
299
- const result = messageRetryManager.shouldRecreateSession(fromJid, retryCount, hasSession.exists)
300
- shouldRecreateSession = result.recreate; recreateReason = result.reason
301
- if (shouldRecreateSession) {
302
- logger.debug({ fromJid, lidJid, retryCount, reason: recreateReason }, 'recreating session for retry')
303
- await authState.keys.set({ session: { [sessionId]: null } })
304
- if (lidJid) await authState.keys.set({ session: { [signalRepository.jidToSignalProtocolAddress(lidJid)]: null } })
305
- forceIncludeKeys = true
306
- }
307
- } catch (error) { logger.warn({ error, fromJid }, 'failed to check session recreation') }
308
- }
309
-
310
- if (retryCount <= 2) {
311
- if (messageRetryManager) {
312
- messageRetryManager.schedulePhoneRequest(msgId, async () => {
313
- try { const requestId = await requestPlaceholderResend(msgKey); logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`) }
314
- catch (error) { logger.warn({ error, msgId }, 'failed to send scheduled phone request') }
315
- })
316
- } else {
317
- const id = await requestPlaceholderResend(msgKey)
318
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${id}`)
319
- }
320
- }
321
-
322
- const deviceIdentity = encodeSignedDeviceIdentity(account, true)
323
- await authState.keys.transaction(async () => {
324
- const receipt = { tag: 'receipt', attrs: { id: msgId, type: 'retry', to: node.attrs.from }, content: [{ tag: 'retry', attrs: { count: retryCount.toString(), id: node.attrs.id, t: node.attrs.t, v: '1', error: '0' } }, { tag: 'registration', attrs: {}, content: encodeBigEndian(authState.creds.registrationId) }] }
325
- if (node.attrs.recipient) receipt.attrs.recipient = node.attrs.recipient
326
- if (node.attrs.participant) receipt.attrs.participant = node.attrs.participant
327
- if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
328
- const { update, preKeys } = await getNextPreKeys(authState, 1)
329
- const [keyId] = Object.keys(preKeys)
330
- const key = preKeys[+keyId]
331
- receipt.content.push({ tag: 'keys', attrs: {}, content: [{ tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) }, { tag: 'identity', attrs: {}, content: identityKey.public }, xmppPreKey(key, +keyId), xmppSignedPreKey(signedPreKey), { tag: 'device-identity', attrs: {}, content: deviceIdentity }] })
332
- ev.emit('creds.update', update)
333
- }
334
- await sendNode(receipt)
335
- logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt')
336
- }, authState?.creds?.me?.id || 'sendRetryRequest')
337
- }
338
-
339
- // ── TC token helpers ──────────────────────────────────────────────────────
340
-
341
- const reissueTcTokenAfterIdentityChange = (from) => {
342
- void (async () => {
343
- const normalizedJid = jidNormalizedUser(from)
344
- const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN)
345
- const tcTokenData = await authState.keys.get('tctoken', [tcJid])
346
- const senderTs = tcTokenData?.[tcJid]?.senderTimestamp
347
- if (senderTs === null || senderTs === undefined || isTcTokenExpired(senderTs)) return
348
- logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken')
349
- const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
350
- const issueToLid = sock.serverProps?.lidTrustedTokenIssueToLid ?? false
351
- const issueJid = await resolveIssuanceJid(normalizedJid, issueToLid, getLIDForPN, getPNForLID)
352
- const result = await issuePrivacyTokens([issueJid], senderTs)
353
- await storeTcTokensFromIqResult({ result, fallbackJid: tcJid, keys: authState.keys, getLIDForPN, onNewJidStored: trackTcTokenJid })
354
- })().catch(err => logger.debug({ jid: from, err: err?.message }, 'failed to re-issue tctoken after identity change'))
355
- }
356
-
357
- const handlePrivacyTokenNotification = async (node) => {
358
- const tokensNode = getBinaryNodeChild(node, 'tokens')
359
- if (!tokensNode) return
360
- const from = jidNormalizedUser(node.attrs.from)
361
- const senderLid = node.attrs.sender_lid && isLidUser(jidNormalizedUser(node.attrs.sender_lid)) ? jidNormalizedUser(node.attrs.sender_lid) : undefined
362
- const fallbackJid = senderLid ?? (await resolveTcTokenJid(from, getLIDForPN))
363
- logger.debug({ from, storageJid: fallbackJid }, 'processing privacy token notification')
364
- await storeTcTokensFromIqResult({ result: node, fallbackJid, keys: authState.keys, getLIDForPN, onNewJidStored: trackTcTokenJid })
365
- }
366
-
367
- const tcTokenKnownJids = new Set()
368
- const tcTokenIndexLoaded = (async () => {
369
- try { const jids = await readTcTokenIndex(authState.keys); for (const jid of jids) tcTokenKnownJids.add(jid); if (tcTokenKnownJids.size > 0) logger.debug({ count: tcTokenKnownJids.size }, 'loaded tctoken index') }
370
- catch (err) { logger.warn({ err: err?.message }, 'failed to load tctoken index') }
371
- })()
372
-
373
- let tcTokenIndexTimer
374
- const flushTcTokenIndex = async () => {
375
- if (tcTokenIndexTimer) { clearTimeout(tcTokenIndexTimer); tcTokenIndexTimer = undefined }
376
- const write = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids)
377
- return authState.keys.set({ tctoken: write })
378
- }
379
- const scheduleTcTokenIndexSave = () => {
380
- if (tcTokenIndexTimer) clearTimeout(tcTokenIndexTimer)
381
- tcTokenIndexTimer = setTimeout(() => { tcTokenIndexTimer = undefined; flushTcTokenIndex().catch(err => logger.warn({ err: err?.message }, 'failed to save tctoken index')) }, 5000)
382
- }
383
- const trackTcTokenJid = (jid) => { if (jid && jid !== TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) { tcTokenKnownJids.add(jid); scheduleTcTokenIndexSave() } }
384
-
385
- // ── Encrypt notification ──────────────────────────────────────────────────
386
-
387
- const handleEncryptNotification = async (node) => {
388
- const from = node.attrs.from
389
- if (from === S_WHATSAPP_NET) {
390
- const stanzaId = node.attrs.id
391
- if (stanzaId && inFlightPreKeyLow.has(stanzaId)) return
392
- const count = +getBinaryNodeChild(node, 'count').attrs.value
393
- logger.debug({ count, shouldUploadMorePreKeys: count < MIN_PREKEY_COUNT }, 'recv pre-key count')
394
- if (count < MIN_PREKEY_COUNT) {
395
- if (stanzaId) inFlightPreKeyLow.add(stanzaId)
396
- try { await uploadPreKeys() } finally { if (stanzaId) inFlightPreKeyLow.delete(stanzaId) }
397
- }
398
- } else {
399
- const result = await handleIdentityChange(node, { meId: authState.creds.me?.id, meLid: authState.creds.me?.lid, validateSession: signalRepository.validateSession, assertSessions, debounceCache: identityAssertDebounce, logger, onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange })
400
- if (result.action === 'no_identity_node') logger.info({ node }, 'unknown encrypt notification')
401
- }
402
- }
403
-
404
- // ── Group notification ────────────────────────────────────────────────────
405
-
406
- const handleGroupNotification = (fullNode, child, msg) => {
407
- const actingParticipantLid = fullNode.attrs.participant
408
- const actingParticipantPn = fullNode.attrs.participant_pn
409
- const actingParticipantUsername = fullNode.attrs.participant_username
410
- const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid
411
- const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn
412
- switch (child?.tag) {
413
- case 'create':
414
- const metadata = extractGroupMetadata(child)
415
- msg.messageStubType = WAMessageStubType.GROUP_CREATE
416
- msg.messageStubParameters = [metadata.subject]
417
- msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn }
418
- ev.emit('chats.upsert', [{ id: metadata.id, name: metadata.subject, conversationTimestamp: metadata.creation }])
419
- ev.emit('groups.upsert', [{ ...metadata, author: actingParticipantLid, authorPn: actingParticipantPn, authorUsername: actingParticipantUsername }])
420
- break
421
- case 'ephemeral':
422
- case 'not_ephemeral':
423
- msg.message = { protocolMessage: { type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING, ephemeralExpiration: +(child.attrs.expiration || 0) } }
424
- break
425
- case 'modify':
426
- const modifiedParticipants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => ({ id: attrs.jid, phoneNumber: isPnUser(attrs.phone_number) ? attrs.phone_number : undefined, lid: isLidUser(attrs.lid) ? attrs.lid : undefined, admin: attrs.type || null }))
427
- msg.messageStubParameters = modifiedParticipants.map(a => JSON.stringify(a))
428
- msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER
429
- break
430
- case 'promote':
431
- case 'demote':
432
- case 'remove':
433
- case 'add':
434
- case 'leave':
435
- msg.messageStubType = WAMessageStubType[`GROUP_PARTICIPANT_${child.tag.toUpperCase()}`]
436
- const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => ({ id: attrs.jid, phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined, lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined, admin: attrs.type || null }))
437
- if (participants.length === 1 && (areJidsSameUser(participants[0].id, actingParticipantLid) || areJidsSameUser(participants[0].id, actingParticipantPn)) && child.tag === 'remove') msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE
438
- msg.messageStubParameters = participants.map(a => JSON.stringify(a))
439
- break
440
- case 'subject':
441
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT
442
- msg.messageStubParameters = [child.attrs.subject]
443
- break
444
- case 'description':
445
- const description = getBinaryNodeChild(child, 'body')?.content?.toString()
446
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION
447
- msg.messageStubParameters = description ? [description] : undefined
448
- break
449
- case 'announcement':
450
- case 'not_announcement':
451
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE
452
- msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off']
453
- break
454
- case 'locked':
455
- case 'unlocked':
456
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT
457
- msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off']
458
- break
459
- case 'invite':
460
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK
461
- msg.messageStubParameters = [child.attrs.code]
462
- break
463
- case 'member_add_mode':
464
- const addMode = child.content
465
- if (addMode) { msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE; msg.messageStubParameters = [addMode.toString()] }
466
- break
467
- case 'membership_approval_mode':
468
- const approvalMode = getBinaryNodeChild(child, 'group_join')
469
- if (approvalMode) { msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE; msg.messageStubParameters = [approvalMode?.attrs?.state] }
470
- break
471
- case 'created_membership_requests':
472
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
473
- msg.messageStubParameters = [JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }), 'created', child.attrs.request_method]
474
- break
475
- case 'revoked_membership_requests':
476
- const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid)
477
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
478
- msg.messageStubParameters = [JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }), isDenied ? 'revoked' : 'rejected']
479
- break
480
- }
481
- }
482
-
483
- // ── Devices notification ──────────────────────────────────────────────────
484
-
485
- const handleDevicesNotification = async (node) => {
486
- const [child] = getAllBinaryNodeChildren(node)
487
- const from = jidNormalizedUser(node.attrs.from)
488
- if (!child) { logger.debug({ from }, 'devices notification missing child, skipping'); return }
489
- const tag = child.tag
490
- const deviceHash = child.attrs.device_hash
491
- const devices = getBinaryNodeChildren(child, 'device')
492
- if (areJidsSameUser(from, authState.creds.me.id) || areJidsSameUser(from, authState.creds.me.lid)) logger.info({ deviceJids: devices.map(d => d.attrs.jid) }, 'got my own devices')
493
- if (!devices.length) { logger.debug({ from, tag }, 'no devices in notification, skipping'); return }
494
- const decoded = []
495
- for (const d of devices) { const jid = d.attrs.jid; if (!jid) continue; const parts = jidDecode(jid); if (!parts) { logger.debug({ jid }, 'failed to decode device jid, skipping'); continue }; decoded.push({ jid, user: parts.user, server: parts.server, device: parts.device }) }
496
- if (!decoded.length) return
497
- await sock.devicesMutex.mutex(async () => {
498
- const byUser = new Map()
499
- for (const d of decoded) { const list = byUser.get(d.user) || []; list.push(d); byUser.set(d.user, list) }
500
- for (const [user, entries] of byUser) {
501
- if (tag === 'update') { logger.debug({ user }, `${user}'s device list updated, dropping cached devices`); await sock.userDevicesCache?.del(user); continue }
502
- if (tag === 'remove') await signalRepository.deleteSession(entries.map(e => e.jid))
503
- const existingCache = (await sock.userDevicesCache?.get(user)) || []
504
- if (!existingCache.length) { logger.debug({ user, tag }, 'device list not cached, deferring to USync refresh'); continue }
505
- const affected = new Set(entries.map(e => e.device))
506
- let updatedDevices
507
- switch (tag) {
508
- case 'add': logger.info({ deviceHash, count: entries.length }, 'devices added'); updatedDevices = [...existingCache.filter(d => !affected.has(d.device)), ...entries.map(e => ({ user: e.user, server: e.server, device: e.device }))]; break
509
- case 'remove': logger.info({ deviceHash, count: entries.length }, 'devices removed'); updatedDevices = existingCache.filter(d => !affected.has(d.device)); break
510
- default: logger.debug({ tag }, 'unknown device list change tag'); continue
511
- }
512
- if (updatedDevices.length === 0) await sock.userDevicesCache?.del(user)
513
- else await sock.userDevicesCache?.set(user, updatedDevices)
514
- }
515
- })
516
- }
517
-
518
- // ── processNotification ───────────────────────────────────────────────────
519
-
520
- const processNotification = async (node) => {
521
- const result = {}
522
- const [child] = getAllBinaryNodeChildren(node)
523
- const nodeType = node.attrs.type
524
- const from = jidNormalizedUser(node.attrs.from)
525
- switch (nodeType) {
526
- case 'privacy_token': await handlePrivacyTokenNotification(node); break
527
- case 'newsletter': await handleNewsletterNotification(node); break
528
- case 'mex': await handleMexNotification(node); break
529
- case 'w:gp2': handleGroupNotification(node, child, result); break
530
- case 'mediaretry': ev.emit('messages.media-update', [decodeMediaRetryNode(node)]); break
531
- case 'encrypt': await handleEncryptNotification(node); break
532
- case 'devices':
533
- try { await handleDevicesNotification(node) } catch (error) { logger.error({ error, node }, 'failed to handle devices notification') }
534
- break
535
- case 'server_sync':
536
- const update = getBinaryNodeChild(node, 'collection')
537
- if (update) await resyncAppState([update.attrs.name], false)
538
- break
539
- case 'picture':
540
- const setPicture = getBinaryNodeChild(node, 'set')
541
- const delPicture = getBinaryNodeChild(node, 'delete')
542
- ev.emit('contacts.update', [{ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '', imgUrl: setPicture ? 'changed' : 'removed' }])
543
- if (isJidGroup(from)) {
544
- const pictureNode = setPicture || delPicture
545
- result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON
546
- if (setPicture) result.messageStubParameters = [setPicture.attrs.id]
547
- result.participant = pictureNode?.attrs.author
548
- result.key = { ...(result.key || {}), participant: setPicture?.attrs.author }
549
- }
550
- break
551
- case 'account_sync':
552
- if (child.tag === 'disappearing_mode') {
553
- const newDuration = +child.attrs.duration
554
- logger.info({ newDuration }, 'updated account disappearing mode')
555
- ev.emit('creds.update', { accountSettings: { ...authState.creds.accountSettings, defaultDisappearingMode: { ephemeralExpiration: newDuration, ephemeralSettingTimestamp: +child.attrs.t } } })
556
- } else if (child.tag === 'blocklist') {
557
- for (const { attrs } of getBinaryNodeChildren(child, 'item')) ev.emit('blocklist.update', { blocklist: [attrs.jid], type: attrs.action === 'block' ? 'add' : 'remove' })
558
- }
559
- break
560
- case 'link_code_companion_reg':
561
- const linkCodeNode = getBinaryNodeChild(node, 'link_code_companion_reg')
562
- const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeNode, 'link_code_pairing_ref'))
563
- const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeNode, 'primary_identity_pub'))
564
- const primaryEphemeralWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeNode, 'link_code_pairing_wrapped_primary_ephemeral_pub'))
565
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralWrapped)
566
- const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey)
567
- const random = randomBytes(32)
568
- const linkCodeSalt = randomBytes(32)
569
- const linkCodePairingExpanded = hkdf(companionSharedKey, 32, { salt: linkCodeSalt, info: 'link_code_pairing_key_bundle_encryption_key' })
570
- const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random])
571
- const encryptIv = randomBytes(12)
572
- const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0))
573
- const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted])
574
- const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey)
575
- const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random])
576
- authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64')
577
- await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'set', id: sock.generateMessageTag(), xmlns: 'md' }, content: [{ tag: 'link_code_companion_reg', attrs: { jid: authState.creds.me.id, stage: 'companion_finish' }, content: [{ tag: 'link_code_pairing_wrapped_key_bundle', attrs: {}, content: encryptedPayload }, { tag: 'companion_identity_public', attrs: {}, content: authState.creds.signedIdentityKey.public }, { tag: 'link_code_pairing_ref', attrs: {}, content: ref }] }] })
578
- authState.creds.registered = true
579
- ev.emit('creds.update', authState.creds)
580
- break
581
- }
582
- if (Object.keys(result).length) return result
583
- }
584
-
585
- // ── Link pairing helpers ──────────────────────────────────────────────────
586
-
587
- const decipherLinkPublicKey = async (data) => {
588
- const buffer = toRequiredBuffer(data)
589
- const salt = buffer.subarray(0, 32)
590
- const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt)
591
- const iv = buffer.subarray(32, 48)
592
- const payload = buffer.subarray(48, 80)
593
- return aesDecryptCTR(payload, secretKey, iv)
594
- }
595
-
596
- const toRequiredBuffer = (data) => {
597
- if (data === undefined) throw new Boom('Invalid buffer', { statusCode: 400 })
598
- return data instanceof Buffer ? data : Buffer.from(data)
599
- }
600
-
601
- // ── Retry helpers ─────────────────────────────────────────────────────────
602
-
603
- const willSendMessageAgain = async (id, participant) => { const retryCount = (await msgRetryCache.get(`${id}:${participant}`)) || 0; return retryCount < maxMsgRetryCount }
604
- const updateSendMessageAgainCount = async (id, participant) => { const key = `${id}:${participant}`; await msgRetryCache.set(key, ((await msgRetryCache.get(key)) || 0) + 1) }
605
-
606
- const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
607
- const remoteJid = key.remoteJid
608
- const participant = key.participant || remoteJid
609
- const retryCount = +retryNode.attrs.count || 1
610
- const msgs = []
611
-
612
- for (const id of ids) {
613
- let msg
614
- if (messageRetryManager) { const cached = messageRetryManager.getRecentMessage(remoteJid, id); if (cached) { msg = cached.message; logger.debug({ jid: remoteJid, id }, 'found message in retry cache'); messageRetryManager.markRetrySuccess(id) } }
615
- if (!msg) { msg = await getMessage({ ...key, id }); if (msg) { logger.debug({ jid: remoteJid, id }, 'found message via getMessage'); if (messageRetryManager) messageRetryManager.markRetrySuccess(id) } }
616
- msgs.push(msg)
617
- }
618
-
619
- const sendToAll = !jidDecode(participant)?.device
620
- const sessionId = signalRepository.jidToSignalProtocolAddress(participant)
621
- let injectedFromBundle = false
622
- const bundle = extractE2ESessionFromRetryReceipt(receiptNode)
623
-
624
- if (bundle) {
625
- try { await signalRepository.injectE2ESession({ jid: participant, session: bundle }); injectedFromBundle = true; logger.debug({ participant, retryCount }, 'injected session from retry receipt key bundle') }
626
- catch (error) { logger.warn({ error, participant }, 'failed to inject session from retry receipt') }
627
- }
628
-
629
- if (!injectedFromBundle && typeof signalRepository.getSessionInfo === 'function') {
630
- const receivedRegId = getBinaryNodeChildUInt(receiptNode, 'registration', 4)
631
- if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
632
- const info = await signalRepository.getSessionInfo(participant)
633
- if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) { logger.info({ participant, stored: info.registrationId, received: receivedRegId }, 'reg id mismatch on retry without bundle, deleting session'); await authState.keys.set({ session: { [sessionId]: null } }) }
634
- }
635
- }
636
-
637
- if (ids[0] && messageRetryManager && typeof messageRetryManager.saveBaseKey === 'function') {
638
- const info = typeof signalRepository.getSessionInfo === 'function' ? await signalRepository.getSessionInfo(participant) : undefined
639
- if (info) {
640
- if (retryCount === 2) messageRetryManager.saveBaseKey(sessionId, ids[0], info.baseKey)
641
- else if (retryCount > 2) {
642
- if (messageRetryManager.hasSameBaseKey(sessionId, ids[0], info.baseKey)) { logger.warn({ participant, retryCount }, 'base key collision on retry, forcing fresh session'); await authState.keys.set({ session: { [sessionId]: null } }) }
643
- messageRetryManager.deleteBaseKey(sessionId, ids[0])
644
- }
645
- }
646
- }
647
-
648
- let shouldRecreateSession = false, recreateReason = ''
649
- if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
650
- try {
651
- const hasSession = await signalRepository.validateSession(participant)
652
- const result = messageRetryManager.shouldRecreateSession(participant, retryCount, hasSession.exists)
653
- shouldRecreateSession = result.recreate; recreateReason = result.reason
654
- if (shouldRecreateSession) { logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry'); await authState.keys.set({ session: { [sessionId]: null } }) }
655
- } catch (error) { logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry') }
656
- }
657
-
658
- if (!injectedFromBundle) await assertSessions([participant], true)
659
- if (isJidGroup(remoteJid)) await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } })
660
- logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'preparing retry recp')
661
-
662
- for (const [i, msg] of msgs.entries()) {
663
- if (!ids[i]) continue
664
- if (msg && (await willSendMessageAgain(ids[i], participant))) {
665
- await updateSendMessageAgainCount(ids[i], participant)
666
- const msgRelayOpts = { messageId: ids[i] }
667
- if (sendToAll) msgRelayOpts.useUserDevicesCache = false
668
- else msgRelayOpts.participant = { jid: participant, count: +retryNode.attrs.count }
669
- await relayMessage(key.remoteJid, msg, msgRelayOpts)
670
- } else logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available')
671
- }
672
- }
673
-
674
- // ── handleReceipt ─────────────────────────────────────────────────────────
675
-
676
- const handleReceipt = async (node) => {
677
- const { attrs, content } = node
678
- const isLid = attrs.from.includes('lid')
679
- const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id)
680
- const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient
681
- const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe)
682
- const key = { remoteJid, id: '', fromMe, participant: attrs.participant }
683
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) { logger.debug({ remoteJid }, 'ignoring receipt from jid'); await sendMessageAck(node); return }
684
- const ids = [attrs.id]
685
- if (Array.isArray(content)) ids.push(...getBinaryNodeChildren(content[0], 'item').map(i => i.attrs.id))
686
- try {
687
- await Promise.all([processingMutex.mutex(async () => {
688
- const status = getStatusFromReceiptType(attrs.type)
689
- if (typeof status !== 'undefined' && (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
690
- if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
691
- if (attrs.participant) {
692
- const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp'
693
- ev.emit('message-receipt.update', ids.map(id => ({ key: { ...key, id }, receipt: { userJid: jidNormalizedUser(attrs.participant), [updateKey]: +attrs.t } })))
694
- }
695
- } else ev.emit('messages.update', ids.map(id => ({ key: { ...key, id }, update: { status, messageTimestamp: toNumber(+(attrs.t ?? 0)) } })))
696
- }
697
- if (attrs.type === 'retry') {
698
- key.participant = key.participant || attrs.from
699
- const retryNode = getBinaryNodeChild(node, 'retry')
700
- if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
701
- if (key.fromMe) {
702
- try { await updateSendMessageAgainCount(ids[0], key.participant); logger.debug({ attrs, key }, 'recv retry request'); await sendMessagesAgain(key, ids, retryNode, node) }
703
- catch (error) { logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again') }
704
- } else logger.info({ attrs, key }, 'recv retry for not fromMe message')
705
- } else {
706
- logger.info({ attrs, key, participant: key.participant }, 'retry limit exhausted - clearing broken session')
707
- try {
708
- await signalRepository.deleteSession([key.participant])
709
- await msgRetryCache.del(`${ids[0]}:${key.participant}`)
710
- } catch (err) { logger.error({ err, participant: key.participant }, 'failed to clear session/cache at retry exhaustion') }
711
- }
712
- }
713
- })])
714
- } finally { await sendMessageAck(node) }
715
- }
716
-
717
- // ── handleNotification ────────────────────────────────────────────────────
718
-
719
- const handleNotification = async (node) => {
720
- const remoteJid = node.attrs.from
721
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) { logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification'); await sendMessageAck(node); return }
722
- try {
723
- await Promise.all([notificationMutex.mutex(async () => {
724
- const msg = await processNotification(node)
725
- if (msg) {
726
- const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id)
727
- const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node)
728
- msg.key = { remoteJid, fromMe, participant: node.attrs.participant, participantAlt, participantUsername: node.attrs.participant_username, addressingMode, id: node.attrs.id, ...(msg.key || {}) }
729
- msg.participant ?? (msg.participant = node.attrs.participant)
730
- msg.messageTimestamp = +node.attrs.t
731
- await upsertMessage(proto.WebMessageInfo.fromObject(msg), 'append')
732
- }
733
- })])
734
- } finally { await sendMessageAck(node) }
735
- }
736
-
737
- // ── handleMessage ─────────────────────────────────────────────────────────
738
-
739
- const handleMessage = async (node) => {
740
- if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) { logger.debug({ key: node.attrs.key }, 'ignored message'); await sendMessageAck(node, NACK_REASONS.UnhandledError); return }
741
-
742
- const encNode = getBinaryNodeChild(node, 'enc')
743
- if (encNode && encNode.attrs.type === 'msmsg') {
744
- const encIv = getBinaryNodeChildBuffer(encNode, 'enc_iv')
745
- const encPayload = getBinaryNodeChildBuffer(encNode, 'enc_p') || encNode.content
746
- if (!encIv || !encPayload) { logger.debug({ id: node.attrs.id, from: node.attrs.from, hasIv: !!encIv, hasPayload: !!encPayload }, 'msmsg missing enc_iv or enc_p, cannot decrypt'); await sendMessageAck(node); return }
747
- try {
748
- const messageSecret = authState.creds.myAppStateKeyId ? Buffer.from(authState.creds.myAppStateKeyId, 'base64') : undefined
749
- if (!messageSecret) { logger.debug({ key: node.attrs.key }, 'no message secret for msmsg, skipping'); await sendMessageAck(node, NACK_REASONS.MissingMessageSecret); return }
750
- const messageKey = { participant: node.attrs.participant || node.attrs.from, meId: authState.creds.me.id, meLid: authState.creds.me.lid, conversationJid: node.attrs.from, senderJid: node.attrs.participant, stanzaId: node.attrs.id, targetId: node.attrs.id }
751
- const decrypted = await decryptMsmsgBotMessage(messageSecret, messageKey, { encPayload, encIv })
752
- node.attrs._msmsgDecrypted = decodeDecryptedMsmsgMessage(decrypted)
753
- logger.debug({ key: node.attrs.key }, 'decrypted msmsg bot message')
754
- } catch (err) { logger.warn({ err, id: node.attrs.id }, 'failed to decrypt msmsg, falling back to nack'); await sendMessageAck(node, NACK_REASONS.MissingMessageSecret); return }
755
- }
756
-
757
- const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger)
758
- const alt = msg.key.participantAlt || msg.key.remoteJidAlt
759
- if (!!alt) {
760
- const altServer = jidDecode(alt)?.server
761
- const primaryJid = msg.key.participant || msg.key.remoteJid
762
- if (altServer === 'lid') { if (!(await signalRepository.lidMapping.getPNForLID(alt))) { await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]); await signalRepository.migrateSession(primaryJid, alt) } }
763
- else { await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]); await signalRepository.migrateSession(alt, primaryJid) }
764
- }
765
-
766
- let acked = false
767
- try {
768
- await messageMutex.mutex(async () => {
769
- await decrypt()
770
- if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message)
771
-
772
- if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
773
- if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) { acked = true; return sendMessageAck(node, NACK_REASONS.ParsingError) }
774
- if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
775
- const unavailableNode = getBinaryNodeChild(node, 'unavailable')
776
- const unavailableType = unavailableNode?.attrs?.type
777
- if (['bot_unavailable_fanout', 'hosted_unavailable_fanout', 'view_once_unavailable_fanout'].includes(unavailableType)) { logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type'); acked = true; return sendMessageAck(node) }
778
- const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp)
779
- if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) { logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message'); acked = true; return sendMessageAck(node) }
780
- const cleanKey = { remoteJid: msg.key.remoteJid, fromMe: msg.key.fromMe, id: msg.key.id, participant: msg.key.participant }
781
- const msgData = { key: msg.key, messageTimestamp: msg.messageTimestamp, pushName: msg.pushName, participant: msg.participant, verifiedBizName: msg.verifiedBizName }
782
- requestPlaceholderResend(cleanKey, msgData).then(requestId => { if (requestId && requestId !== 'RESOLVED') { logger.debug({ msgId: msg.key.id, requestId }, 'requested placeholder resend for unavailable message'); ev.emit('messages.update', [{ key: msg.key, update: { messageStubParameters: [NO_MESSAGE_FOUND_ERROR_TEXT, requestId] } }]) } }).catch(err => logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message'))
783
- acked = true; await sendMessageAck(node)
784
- } else {
785
- if ((msg.messageStubParameters?.[0] || '').includes('InvalidPreKeyId')) { logger.debug({ msgId: msg.key.id, remoteJid: msg.key.remoteJid }, 'skipping retry for InvalidPreKeyId, sender must re-establish session'); acked = true; return sendMessageAck(node, NACK_REASONS.UnhandledError) }
786
- if (isJidStatusBroadcast(msg.key.remoteJid)) {
787
- const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp)
788
- if (messageAge > STATUS_EXPIRY_SECONDS) { logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message'); acked = true; return sendMessageAck(node) }
789
- }
790
- retryMutex.mutex(async () => {
791
- try { if (!ws.isOpen) { logger.debug({ node }, 'Connection closed, skipping retry'); return }; await sendRetryRequest(node, true); if (retryRequestDelayMs) await delay(retryRequestDelayMs) }
792
- catch (err) { logger.error({ err }, 'Retry mechanism failed'); try { await sendRetryRequest(node, !getBinaryNodeChild(node, 'enc')) } catch (retryErr) { logger.error({ retryErr }, 'Final retry attempt failed') } }
793
- acked = true; await sendMessageAck(node, NACK_REASONS.UnhandledError)
794
- })
795
- }
796
- } else {
797
- if (messageRetryManager && msg.key.id) messageRetryManager.cancelPendingPhoneRequest(msg.key.id)
798
- const isNewsletter = isJidNewsletter(msg.key.remoteJid)
799
- if (!isNewsletter) {
800
- let type = undefined, participant = msg.key.participant
801
- if (category === 'peer') type = 'peer_msg'
802
- else if (msg.key.fromMe) { type = 'sender'; if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) participant = author }
803
- else if (!sendActiveReceipts) type = 'inactive'
804
- acked = true; await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type)
805
- if (getHistoryMsg(msg.message)) await sendReceipt(jidNormalizedUser(msg.key.remoteJid), undefined, [msg.key.id], 'hist_sync')
806
- } else { acked = true; await sendMessageAck(node); logger.debug({ key: msg.key }, 'processed newsletter message without receipts') }
807
- }
808
-
809
- cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid)
810
-
811
- if (!msg.key.fromMe) {
812
- try {
813
- const info = extractReportingInfoFromStanza(node)
814
- if (info) {
815
- const senderJid = msg.key.participant || author || msg.key.remoteJid
816
- const contentType = msg.message ? getContentType(msg.message) : undefined
817
- config.reportingInfoStore?.add(senderJid, { stanzaId: info.stanzaId, timestamp: info.timestamp || Number(msg.messageTimestamp) || 0, reportingTag: info.reportingTag, reportingToken: info.reportingToken, tokenVersion: info.tokenVersion, validationPolicy: info.validationPolicy, text: extractMessageText(msg), pushName: msg.pushName || node.attrs?.notify || '', messageType: contentType === 'conversation' || contentType === 'extendedTextMessage' ? 'text' : contentType || 'text', fromJid: senderJid })
818
- }
819
- } catch (storeErr) { logger.warn({ err: storeErr, key: msg.key }, 'failed to store reporting_tag') }
820
- }
821
-
822
- await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify')
823
- })
824
- } catch (error) {
825
- const isClosed = error?.message?.includes('Connection Closed') || error?.output?.statusCode === 428
826
- if (isClosed) logger.debug({ msg: error?.message }, 'Connection closed while handling message')
827
- else logger.error({ error, stack: error?.stack, msg: error?.message || String(error), node: binaryNodeToString(node) }, 'error in handling message')
828
- if (!acked) await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(ackErr => logger.error({ ackErr }, 'failed to ack message after error'))
829
- }
830
- }
831
-
832
- // ── handleCall ────────────────────────────────────────────────────────────
833
-
834
- const handleCall = async (node) => {
835
- const { attrs } = node
836
- try {
837
- const [infoChild] = getAllBinaryNodeChildren(node)
838
- if (!infoChild) throw new Boom('Missing call info in call node')
839
- const status = getCallStatusFromNode(infoChild)
840
- const callId = infoChild.attrs['call-id']
841
- const from = infoChild.attrs.from || infoChild.attrs['call-creator']
842
- const call = { chatId: attrs.from, from, callerPn: infoChild.attrs['caller_pn'], id: callId, date: new Date(+attrs.t * 1000), offline: !!attrs.offline, status }
843
- if (status === 'relaylatency') { const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms']; const latencyMs = latencyValue ? Number(latencyValue) : undefined; if (Number.isFinite(latencyMs)) call.latencyMs = latencyMs }
844
- if (status === 'offer') { call.isVideo = !!getBinaryNodeChild(infoChild, 'video'); call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid']; call.groupJid = infoChild.attrs['group-jid']; await callOfferCache.set(call.id, call) }
845
- const existingCall = await callOfferCache.get(call.id)
846
- if (existingCall) { call.isVideo = existingCall.isVideo; call.isGroup = existingCall.isGroup; call.callerPn = call.callerPn || existingCall.callerPn }
847
- if (['reject', 'accept', 'timeout', 'terminate'].includes(status)) await callOfferCache.del(call.id)
848
- ev.emit('call', [call])
849
- } catch (error) { logger.error({ error, node: binaryNodeToString(node) }, 'error in handling call') }
850
- finally { await sendMessageAck(node) }
851
- }
852
-
853
- // ── handleBadAck ──────────────────────────────────────────────────────────
854
-
855
- const handleBadAck = async ({ attrs }) => {
856
- const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id }
857
- if (!attrs.error) return
858
- const isReachoutTimelocked = attrs.error === String(NACK_REASONS.SenderReachoutTimelocked)
859
- if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
860
- logger.warn({ msgId: attrs.id, from: attrs.from }, 'error 463: account restricted or missing tctoken for contact')
861
- const ackFrom = attrs.from
862
- if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
863
- inFlight463Recoveries.add(ackFrom)
864
- void (async () => {
865
- try {
866
- const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
867
- const tcStorageJid = await resolveTcTokenJid(ackFrom, getLIDForPN)
868
- const issueToLid = sock.serverProps?.lidTrustedTokenIssueToLid ?? false
869
- const issueJid = await resolveIssuanceJid(ackFrom, issueToLid, getLIDForPN, getPNForLID)
870
- const result = await issuePrivacyTokens([issueJid], unixTimestampSeconds())
871
- await storeTcTokensFromIqResult({ result, fallbackJid: tcStorageJid, keys: authState.keys, getLIDForPN, onNewJidStored: trackTcTokenJid })
872
- logger.debug({ from: ackFrom }, 'completed 463 token recovery issuance')
873
- ev.emit('messages.update', [{ key, update: { status: WAMessageStatus.PENDING } }])
874
- } catch (err) { logger.debug({ from: ackFrom, err: err?.message }, 'failed 463 token recovery issuance') }
875
- finally { inFlight463Recoveries.delete(ackFrom) }
876
- })()
877
- }
878
- } else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
879
- logger.warn({ msgId: attrs.id, from: attrs.from }, 'smax-invalid (479): stale device session or malformed addressing')
880
- } else if (isReachoutTimelocked) {
881
- await fetchAccountReachoutTimelock().catch(err => logger.warn({ err }, 'failed to fetch reachout timelock'))
882
- logger.warn({ attrs }, 'received error in ack')
883
- } else {
884
- logger.warn({ attrs }, 'received error in ack')
885
- }
886
- ev.emit('messages.update', [{ key, update: { status: WAMessageStatus.ERROR, messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error] } }])
887
- }
888
-
889
- // ── Offline node processor ────────────────────────────────────────────────
890
-
891
- const processNodeWithBuffer = async (node, identifier, exec) => { ev.buffer(); await exec(node, false).catch(err => onUnexpectedError(err, identifier)); ev.flush() }
892
- const yieldToEventLoop = () => new Promise(resolve => setImmediate(resolve))
893
-
894
- const makeOfflineNodeProcessor = () => {
895
- const nodeProcessorMap = new Map([['message', handleMessage], ['status', handleMessage], ['call', handleCall], ['receipt', handleReceipt], ['notification', handleNotification]])
896
- const nodes = []
897
- let isProcessing = false
898
- const enqueue = (type, node) => {
899
- nodes.push({ type, node })
900
- if (isProcessing) return
901
- isProcessing = true;
902
- (async () => {
903
- let processedInBatch = 0
904
- while (nodes.length && ws.isOpen) {
905
- const { type, node } = nodes.shift()
906
- const processor = nodeProcessorMap.get(type)
907
- if (!processor) { onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node'); continue }
908
- await processor(node).catch(err => onUnexpectedError(err, `processing offline ${type}`))
909
- if (++processedInBatch >= 10) { processedInBatch = 0; await yieldToEventLoop() }
910
- }
911
- isProcessing = false
912
- })().catch(error => onUnexpectedError(error, 'processing offline nodes'))
913
- }
914
- return { enqueue }
915
- }
916
-
917
- const offlineNodeProcessor = makeOfflineNodeProcessor()
918
-
919
- const processNode = async (type, node, identifier, exec) => {
920
- const from = node.attrs.from
921
- let ignoreJid = from
922
- if (type === 'receipt' && from) { const isLid = from.includes('lid'); const isNodeFromMe = areJidsSameUser(node.attrs.participant || from, isLid ? authState.creds.me?.lid : authState.creds.me?.id); ignoreJid = !isNodeFromMe || isJidGroup(from) ? from : node.attrs.recipient }
923
- if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) { await sendMessageAck(node, type === 'message' ? NACK_REASONS.UnhandledError : undefined); return }
924
- if (node.attrs.offline) offlineNodeProcessor.enqueue(type, node)
925
- else await processNodeWithBuffer(node, identifier, exec)
926
- }
927
-
928
- // ── WS event bindings ─────────────────────────────────────────────────────
929
-
930
- ws.on('CB:message', async (node) => { await processNode('message', node, 'processing message', handleMessage) })
931
- ws.on('CB:status', async (node) => { if (isJidNewsletter(node.attrs?.from)) return; await processNode('message', node, 'processing status', handleMessage) })
932
- ws.on('CB:call', async (node) => { await processNode('call', node, 'handling call', handleCall) })
933
- ws.on('CB:receipt', async (node) => { await processNode('receipt', node, 'handling receipt', handleReceipt) })
934
- ws.on('CB:notification', async (node) => { await processNode('notification', node, 'handling notification', handleNotification) })
935
- ws.on('CB:ack,class:message', (node) => { handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack')) })
936
-
937
- ev.on('call', async ([call]) => {
938
- if (!call) return
939
- if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
940
- const msg = { key: { remoteJid: call.chatId, id: call.id, fromMe: false }, messageTimestamp: unixTimestampSeconds(call.date) }
941
- if (call.status === 'timeout') msg.messageStubType = call.isGroup ? (call.isVideo ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO : WAMessageStubType.CALL_MISSED_GROUP_VOICE) : (call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE)
942
- else msg.message = { call: { callKey: Buffer.from(call.id) } }
943
- await upsertMessage(proto.WebMessageInfo.fromObject(msg), call.offline ? 'append' : 'notify')
944
- }
945
- })
946
-
947
- // ── TC token pruning ──────────────────────────────────────────────────────
948
-
949
- let lastTcTokenPruneTs = 0
950
- const pruneExpiredTcTokens = async () => {
951
- try {
952
- await tcTokenIndexLoaded
953
- const persisted = await readTcTokenIndex(authState.keys)
954
- const allJids = new Set([...tcTokenKnownJids, ...persisted])
955
- if (!allJids.size) return
956
- const jids = [...allJids]
957
- const allTokens = await authState.keys.get('tctoken', jids)
958
- const writes = {}, survivors = new Set()
959
- let mutated = 0
960
- for (const jid of jids) {
961
- const entry = allTokens[jid]
962
- if (!entry) { mutated++; continue }
963
- const hasPeerToken = !!entry.token?.length
964
- const peerTokenExpired = hasPeerToken && isTcTokenExpired(entry.timestamp)
965
- const hasSenderTs = entry.senderTimestamp !== undefined
966
- const senderTsExpired = hasSenderTs && isTcTokenExpired(entry.senderTimestamp)
967
- const keepPeer = hasPeerToken && !peerTokenExpired
968
- const keepSender = hasSenderTs && !senderTsExpired
969
- if (!keepPeer && !keepSender) { writes[jid] = null; mutated++ }
970
- else if (peerTokenExpired && keepSender) { writes[jid] = { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }; survivors.add(jid); mutated++ }
971
- else survivors.add(jid)
972
- }
973
- if (mutated === 0) return
974
- await authState.keys.set({ tctoken: { ...writes, [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...survivors])) } } })
975
- tcTokenKnownJids.clear(); for (const jid of survivors) tcTokenKnownJids.add(jid)
976
- logger.debug({ mutated, remaining: survivors.size }, 'pruned expired tctokens')
977
- } catch (err) { logger.warn({ err: err?.message }, 'failed to prune expired tctokens') }
978
- }
979
-
980
- ev.on('connection.update', ({ isOnline, connection }) => {
981
- if (typeof isOnline !== 'undefined') { sendActiveReceipts = isOnline; logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`) }
982
- if (connection === 'close' && tcTokenIndexTimer) { clearTimeout(tcTokenIndexTimer); tcTokenIndexTimer = undefined; try { void Promise.resolve(flushTcTokenIndex()).catch(() => { }) } catch { } }
983
- if (isOnline) { const now = Date.now(); if (now - lastTcTokenPruneTs >= 86_400_000) { lastTcTokenPruneTs = now; void pruneExpiredTcTokens() } }
984
- })
985
-
986
- registerSocketEndHandler(() => {
987
- if (!config.msgRetryCounterCache && msgRetryCache.close) msgRetryCache.close()
988
- if (!config.callOfferCache && callOfferCache.close) callOfferCache.close()
989
- identityAssertDebounce.close()
990
- sendActiveReceipts = false
991
- })
992
-
993
- return { ...sock, sendMessageAck, sendRetryRequest, rejectCall, acceptCall, terminateCall, offerCall, fetchMessageHistory, requestPlaceholderResend, requestContactRefresh, messageRetryManager, tcTokenIndexLoaded }
1
+ import NodeCache from '@cacheable/node-cache'
2
+ import { Boom } from '@hapi/boom'
3
+ import { randomBytes } from 'crypto'
4
+ import { proto } from '../../WAProto/index.js'
5
+ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/index.js'
6
+ import { ReachoutTimelockEnforcementType, WAMessageStatus, WAMessageStubType } from '../Types/index.js'
7
+ import {
8
+ aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode,
9
+ decodeMessageNode, makeMutex, decryptMessageNode, delay, derivePairingCodeKey,
10
+ encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext,
11
+ extractE2ESessionFromRetryReceipt, getCallStatusFromNode, getHistoryMsg,
12
+ getNextPreKeys, getStatusFromReceiptType, extractMessageText,
13
+ handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS,
14
+ NO_MESSAGE_FOUND_ERROR_TEXT, SERVER_ERROR_CODES, toNumber, unixTimestampSeconds,
15
+ xmppPreKey, xmppSignedPreKey, ACCOUNT_RESTRICTED_TEXT, buildMergedTcTokenIndexWrite,
16
+ isTcTokenExpired, readTcTokenIndex, resolveTcTokenJid, resolveIssuanceJid,
17
+ storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY, decryptMsmsgBotMessage,
18
+ decodeDecryptedMsmsgMessage, extractReportingInfoFromStanza, getContentType,
19
+ } from '../Utils/index.js'
20
+ import {
21
+ areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild,
22
+ getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString,
23
+ getBinaryNodeChildUInt, isJidGroup, isJidNewsletter, isJidStatusBroadcast,
24
+ isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET, jidEncode,
25
+ } from '../WABinary/index.js'
26
+ import { extractGroupMetadata } from './groups.js'
27
+ import { makeMessagesSocket } from './messages-send.js'
28
+
29
+ // ─── Pure stanza builders ─────────────────────────────────────────────────────
30
+
31
+ export const buildGroupCallStanza = ({ id, to, callId, callCreator, offerContent }) => ({
32
+ tag: 'call',
33
+ attrs: { id, to },
34
+ content: [{ tag: 'offer', attrs: { 'call-id': callId, 'call-creator': callCreator, type: 'group', 'group-jid': to }, content: offerContent }]
35
+ })
36
+
37
+ export const buildGroupCallCancelStanza = ({ to, callId, callCreator }) => ({
38
+ tag: 'call',
39
+ attrs: { from: callCreator, to },
40
+ content: [{ tag: 'terminate', attrs: { 'call-id': callId, 'call-creator': callCreator, reason: 'user-terminated', count: '0' }, content: undefined }]
41
+ })
42
+
43
+ const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(ReachoutTimelockEnforcementType))
44
+ const isValidEnforcementType = (value) => typeof value === 'string' && ENFORCEMENT_TYPE_VALUES.has(value)
45
+
46
+ // ─── Socket ───────────────────────────────────────────────────────────────────
47
+
48
+ export const makeMessagesRecvSocket = (config) => {
49
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config
50
+ const sock = makeMessagesSocket(config)
51
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager, registerSocketEndHandler, issuePrivacyTokens, fetchAccountReachoutTimelock, placeholderResendCache: sockPlaceholderResendCache } = sock
52
+
53
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
54
+ const { messageMutex, notificationMutex, receiptMutex: _receiptMutex, placeholderResendCache } = sock
55
+ const retryMutex = makeMutex()
56
+ const msgRetryCache = config.msgRetryCounterCache || new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, useClones: false })
57
+ const callOfferCache = config.callOfferCache || new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, useClones: false })
58
+ const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false })
59
+ const inFlightPreKeyLow = new Set()
60
+ const inFlight463Recoveries = new Set()
61
+
62
+ let sendActiveReceipts = false
63
+
64
+ // ── PDO helpers ───────────────────────────────────────────────────────────
65
+
66
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
67
+ if (!authState.creds.me?.id) throw new Boom('Not authenticated')
68
+ return sendPeerDataOperationMessage({ historySyncOnDemandRequest: { chatJid: oldestMsgKey.remoteJid, oldestMsgFromMe: oldestMsgKey.fromMe, oldestMsgId: oldestMsgKey.id, oldestMsgTimestampMs: oldestMsgTimestamp, onDemandMsgCount: count }, peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND })
69
+ }
70
+
71
+ const requestPlaceholderResend = async (messageKey, msgData) => {
72
+ if (!authState.creds.me?.id) throw new Boom('Not authenticated')
73
+ if (await placeholderResendCache.get(messageKey?.id)) { logger.debug({ messageKey }, 'already requested resend'); return }
74
+ await placeholderResendCache.set(messageKey?.id, msgData || true)
75
+ await delay(2000)
76
+ if (!(await placeholderResendCache.get(messageKey?.id))) { logger.debug({ messageKey }, 'message received while resend requested'); return 'RESOLVED' }
77
+ setTimeout(async () => { if (await placeholderResendCache.get(messageKey?.id)) { logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline'); await placeholderResendCache.del(messageKey?.id) } }, 8000)
78
+ return sendPeerDataOperationMessage({ placeholderMessageResendRequest: [{ messageKey }], peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND })
79
+ }
80
+
81
+ const requestContactRefresh = async (jids) => {
82
+ if (!jids?.length) return
83
+ return sendPeerDataOperationMessage({ contactRefreshRequest: { jids: Array.isArray(jids) ? jids : [jids] }, peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.CONTACT_REFRESH_REQUEST })
84
+ }
85
+
86
+ // ── Newsletter notifications ──────────────────────────────────────────────
87
+
88
+ const handleReachoutTimelockNotification = (data) => {
89
+ const payload = data.xwa2_notify_account_reachout_timelock
90
+ if (!payload) { logger.warn('reachout timelock notification missing payload'); return }
91
+ if (!payload.is_active) { ev.emit('connection.update', { reachoutTimeLock: { isActive: false, enforcementType: ReachoutTimelockEnforcementType.DEFAULT } }); return }
92
+ const timeEnforcementEnds = payload.time_enforcement_ends ? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000) : new Date(Date.now() + 60000)
93
+ const enforcementType = isValidEnforcementType(payload.enforcement_type) ? payload.enforcement_type : ReachoutTimelockEnforcementType.DEFAULT
94
+ logger.info({ enforcementType, timeEnforcementEnds }, 'reachout timelock restriction set')
95
+ ev.emit('connection.update', { reachoutTimeLock: { isActive: true, timeEnforcementEnds, enforcementType } })
96
+ }
97
+
98
+ const handleMessageCappingNotification = (data) => {
99
+ const payload = data.xwa2_notify_new_chat_messages_capping_info_update
100
+ if (!payload) { logger.warn('message capping notification missing payload'); return }
101
+ logger.info({ payload }, 'received message capping update')
102
+ ev.emit('message-capping.update', payload)
103
+ }
104
+
105
+ const handleLegacyMexNewsletterNotification = async (node) => {
106
+ const mexNode = getBinaryNodeChild(node, 'mex')
107
+ const updateNode = mexNode?.content ? null : getBinaryNodeChild(node, 'update') || getAllBinaryNodeChildren(node)[0]
108
+ const payloadNode = mexNode?.content ? mexNode : updateNode
109
+ if (!payloadNode?.content) { logger.warn({ node: binaryNodeToString(node) }, 'invalid mex newsletter notification'); return }
110
+ let data
111
+ try {
112
+ const payloadContent = payloadNode.content
113
+ if (Array.isArray(payloadContent)) { logger.warn({ payloadNode }, 'invalid mex newsletter notification payload format'); return }
114
+ const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent)
115
+ data = JSON.parse(contentBuf.toString())
116
+ } catch (error) { logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification'); return }
117
+ const operation = data?.operation ?? payloadNode?.attrs?.op_name
118
+ let updates = data?.updates
119
+ if (!updates) { const linkedProfiles = data?.data?.xwa2_notify_linked_profiles; if (linkedProfiles) updates = [linkedProfiles] }
120
+ if (!updates || !operation) { logger.warn({ data }, 'invalid mex newsletter notification content'); return }
121
+ logger.info({ operation, updates }, 'got mex newsletter notification')
122
+ switch (operation) {
123
+ case 'NotificationNewsletterUpdate':
124
+ for (const update of updates) if (update.jid && update.settings && Object.keys(update.settings).length > 0) ev.emit('newsletter-settings.update', { id: update.jid, update: update.settings })
125
+ break
126
+ case 'NotificationNewsletterAdminPromote':
127
+ for (const update of updates) if (update.jid && update.user) ev.emit('newsletter-participants.update', { id: update.jid, author: node.attrs.from, user: update.user, new_role: 'ADMIN', action: 'promote' })
128
+ break
129
+ case 'NotificationLinkedProfilesUpdates':
130
+ for (const update of updates) {
131
+ const lid = update?.jid
132
+ const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : []
133
+ const mappings = []
134
+ for (const profile of addedProfiles) {
135
+ const pn = typeof profile === 'string' ? profile : (profile?.pn ?? profile?.jid ?? null)
136
+ if (lid && pn) { const mapping = { lid, pn }; ev.emit('lid-mapping.update', mapping); mappings.push(mapping) }
137
+ }
138
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings)
139
+ }
140
+ break
141
+ default:
142
+ logger.info({ operation, data }, 'unhandled mex newsletter notification')
143
+ }
144
+ }
145
+
146
+ const handleMexNotification = async (node) => {
147
+ const updateNode = getBinaryNodeChild(node, 'update')
148
+ if (!updateNode) { await handleLegacyMexNewsletterNotification(node); return }
149
+ const opName = updateNode.attrs?.op_name
150
+ if (!opName) { logger.warn({ node: binaryNodeToString(node) }, 'mex notification missing op_name, fallback to legacy'); await handleLegacyMexNewsletterNotification(node); return }
151
+ let mexResponse
152
+ try { mexResponse = JSON.parse(updateNode.content.toString()) } catch (error) { logger.error({ err: error, opName }, 'failed to parse mex notification JSON'); return }
153
+ if (mexResponse.errors?.length) { logger.warn({ errors: mexResponse.errors, opName }, 'mex notification has GQL errors'); return }
154
+ const data = mexResponse.data
155
+ if (!data) { logger.warn({ opName }, 'mex notification has null data'); return }
156
+ logger.debug({ opName }, 'processing mex notification')
157
+ switch (opName) {
158
+ case 'NotificationUserReachoutTimelockUpdate': handleReachoutTimelockNotification(data); break
159
+ case 'MessageCappingInfoNotification': handleMessageCappingNotification(data); break
160
+ case 'NotificationNewsletterJoin':
161
+ ev.emit('newsletter.join', data?.xwa2_notify_newsletter_on_join); break
162
+ case 'NotificationNewsletterUserSettingChange':
163
+ ev.emit('newsletter.viewer-settings.update', data?.xwa2_notify_newsletter_on_user_setting_change); break
164
+ default: {
165
+ const xwa2Key = Object.keys(data).find(k => k.startsWith('xwa2_notify_'))
166
+ if (xwa2Key) {
167
+ ev.emit('newsletter.update', { type: opName, data: data[xwa2Key] })
168
+ logger.debug({ opName, xwa2Key }, 'emitted newsletter update from xwa2 key')
169
+ } else {
170
+ await handleLegacyMexNewsletterNotification(node)
171
+ }
172
+ break
173
+ }
174
+ }
175
+ }
176
+
177
+ const handleNewsletterNotification = async (node) => {
178
+ const from = node.attrs.from
179
+ const children = getAllBinaryNodeChildren(node)
180
+ const author = node.attrs.participant
181
+ for (const child of children) {
182
+ logger.debug({ from, child }, 'got newsletter notification')
183
+ switch (child.tag) {
184
+ case 'reaction':
185
+ ev.emit('newsletter.reaction', { id: from, server_id: child.attrs.message_id, reaction: { code: getBinaryNodeChildString(child, 'reaction'), count: 1 } })
186
+ break
187
+ case 'view':
188
+ ev.emit('newsletter.view', { id: from, server_id: child.attrs.message_id, count: parseInt(child.content?.toString() || '0', 10) })
189
+ break
190
+ case 'participant':
191
+ ev.emit('newsletter-participants.update', { id: from, author, user: child.attrs.jid, action: child.attrs.action, new_role: child.attrs.role })
192
+ break
193
+ case 'update':
194
+ const settingsNode = getBinaryNodeChild(child, 'settings')
195
+ if (settingsNode) {
196
+ const update = {}
197
+ const nameNode = getBinaryNodeChild(settingsNode, 'name')
198
+ if (nameNode?.content) update.name = nameNode.content.toString()
199
+ const descNode = getBinaryNodeChild(settingsNode, 'description')
200
+ if (descNode?.content) update.description = descNode.content.toString()
201
+ ev.emit('newsletter-settings.update', { id: from, update })
202
+ }
203
+ break
204
+ case 'message':
205
+ const plaintextNode = getBinaryNodeChild(child, 'plaintext')
206
+ if (plaintextNode?.content) {
207
+ try {
208
+ const buf = typeof plaintextNode.content === 'string' ? Buffer.from(plaintextNode.content, 'binary') : Buffer.from(plaintextNode.content)
209
+ const messageProto = proto.Message.decode(buf).toJSON()
210
+ const fullMessage = proto.WebMessageInfo.fromObject({ key: { remoteJid: from, id: child.attrs.message_id || child.attrs.server_id, fromMe: false }, message: messageProto, messageTimestamp: +child.attrs.t }).toJSON()
211
+ await upsertMessage(fullMessage, 'append')
212
+ } catch (error) { logger.error({ error }, 'Failed to decode plaintext newsletter message') }
213
+ }
214
+ break
215
+ default:
216
+ logger.warn({ node }, 'Unknown newsletter notification')
217
+ }
218
+ }
219
+ }
220
+
221
+ // ── ACK / call helpers ────────────────────────────────────────────────────
222
+
223
+ const sendMessageAck = async (node, errorCode) => {
224
+ const { tag, attrs, content } = node
225
+ const hasUnavailable = !!getBinaryNodeChild({ tag, attrs, content }, 'unavailable')
226
+ const stanza = { tag: 'ack', attrs: { id: attrs.id, to: attrs.from, class: tag } }
227
+ if (errorCode) stanza.attrs.error = errorCode.toString()
228
+ if (attrs.participant) stanza.attrs.participant = attrs.participant
229
+ if (attrs.recipient) stanza.attrs.recipient = attrs.recipient
230
+ if (attrs.type || hasUnavailable || errorCode) stanza.attrs.type = attrs.type
231
+ if (tag === 'message' && authState.creds.me?.id) stanza.attrs.from = authState.creds.me.id
232
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack')
233
+ try { await sendNode(stanza) } catch (error) {
234
+ if (error?.output?.statusCode === 428 || error?.message?.includes('Connection')) logger.warn({ id: attrs.id, error: error?.message }, 'Failed to send ACK (connection closed) - message already received')
235
+ else throw error
236
+ }
237
+ }
238
+
239
+ const rejectCall = async (callId, callFrom) => {
240
+ await query({ tag: 'call', attrs: { from: authState.creds.me.id, to: callFrom }, content: [{ tag: 'reject', attrs: { 'call-id': callId, 'call-creator': callFrom, count: '0' }, content: undefined }] })
241
+ }
242
+
243
+ const acceptCall = async (callId, callFrom) => {
244
+ await query({ tag: 'call', attrs: { from: authState.creds.me.id, to: callFrom }, content: [{ tag: 'accept', attrs: { 'call-id': callId, 'call-creator': callFrom, count: '0' }, content: undefined }] })
245
+ }
246
+
247
+ const terminateCall = async (callId, callFrom) => {
248
+ await query({ tag: 'call', attrs: { from: authState.creds.me.id, to: callFrom }, content: [{ tag: 'terminate', attrs: { 'call-id': callId, 'call-creator': callFrom, reason: 'user-terminated', count: '0' }, content: undefined }] })
249
+ }
250
+
251
+ const offerCall = async (toJid, isVideo = false) => {
252
+ const callId = randomBytes(16).toString('hex').toUpperCase().substring(0, 64)
253
+ const offerContent = []
254
+ offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '16000' }, content: undefined })
255
+ offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '8000' }, content: undefined })
256
+ if (isVideo) offerContent.push({ tag: 'video', attrs: { orientation: '0', screen_width: '1920', screen_height: '1080', device_orientation: '0', enc: 'vp8', dec: 'vp8' } })
257
+ offerContent.push({ tag: 'net', attrs: { medium: '3' }, content: undefined })
258
+ offerContent.push({ tag: 'capability', attrs: { ver: '1' }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) })
259
+ offerContent.push({ tag: 'encopt', attrs: { keygen: '2' }, content: undefined })
260
+ const encKey = randomBytes(32)
261
+ const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => jidEncode(user, 's.whatsapp.net', device))
262
+ await assertSessions(devices, true)
263
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, { call: { callKey: encKey } }, {})
264
+ offerContent.push({ tag: 'destination', attrs: {}, content: destinations })
265
+ if (shouldIncludeDeviceIdentity) offerContent.push({ tag: 'device-identity', attrs: {}, content: encodeSignedDeviceIdentity(authState.creds.account, true) })
266
+ await query({ tag: 'call', attrs: { to: toJid }, content: [{ tag: 'offer', attrs: { 'call-id': callId, 'call-creator': authState.creds.me.id }, content: offerContent }] })
267
+ return { callId, toJid, isVideo }
268
+ }
269
+
270
+ // ── Retry logic ───────────────────────────────────────────────────────────
271
+
272
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
273
+ const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '')
274
+ const { key: msgKey } = fullMessage
275
+ const msgId = msgKey.id
276
+
277
+ if (messageRetryManager) {
278
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) { logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing'); messageRetryManager.markRetryFailed(msgId); return }
279
+ const retryCount = messageRetryManager.incrementRetryCount(msgId)
280
+ await msgRetryCache.set(`${msgId}:${msgKey?.participant}`, retryCount)
281
+ } else {
282
+ const key = `${msgId}:${msgKey?.participant}`
283
+ let retryCount = (await msgRetryCache.get(key)) || 0
284
+ if (retryCount >= maxMsgRetryCount) { logger.debug({ retryCount, msgId }, 'reached retry limit, clearing'); await msgRetryCache.del(key); return }
285
+ await msgRetryCache.set(key, retryCount + 1)
286
+ }
287
+
288
+ const retryCount = (await msgRetryCache.get(`${msgId}:${msgKey?.participant}`)) || 1
289
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
290
+ const fromJid = node.attrs.from
291
+ let shouldRecreateSession = false, recreateReason = ''
292
+
293
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
294
+ try {
295
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid)
296
+ const hasSession = await signalRepository.validateSession(fromJid)
297
+ let lidJid = null
298
+ if (isPnUser(fromJid)) lidJid = await signalRepository.lidMapping.getLIDForPN(fromJid)
299
+ const result = messageRetryManager.shouldRecreateSession(fromJid, retryCount, hasSession.exists)
300
+ shouldRecreateSession = result.recreate; recreateReason = result.reason
301
+ if (shouldRecreateSession) {
302
+ logger.debug({ fromJid, lidJid, retryCount, reason: recreateReason }, 'recreating session for retry')
303
+ await authState.keys.set({ session: { [sessionId]: null } })
304
+ if (lidJid) await authState.keys.set({ session: { [signalRepository.jidToSignalProtocolAddress(lidJid)]: null } })
305
+ forceIncludeKeys = true
306
+ }
307
+ } catch (error) { logger.warn({ error, fromJid }, 'failed to check session recreation') }
308
+ }
309
+
310
+ if (retryCount <= 2) {
311
+ if (messageRetryManager) {
312
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
313
+ try { const requestId = await requestPlaceholderResend(msgKey); logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`) }
314
+ catch (error) { logger.warn({ error, msgId }, 'failed to send scheduled phone request') }
315
+ })
316
+ } else {
317
+ const id = await requestPlaceholderResend(msgKey)
318
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${id}`)
319
+ }
320
+ }
321
+
322
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true)
323
+ await authState.keys.transaction(async () => {
324
+ const receipt = { tag: 'receipt', attrs: { id: msgId, type: 'retry', to: node.attrs.from }, content: [{ tag: 'retry', attrs: { count: retryCount.toString(), id: node.attrs.id, t: node.attrs.t, v: '1', error: '0' } }, { tag: 'registration', attrs: {}, content: encodeBigEndian(authState.creds.registrationId) }] }
325
+ if (node.attrs.recipient) receipt.attrs.recipient = node.attrs.recipient
326
+ if (node.attrs.participant) receipt.attrs.participant = node.attrs.participant
327
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
328
+ const { update, preKeys } = await getNextPreKeys(authState, 1)
329
+ const [keyId] = Object.keys(preKeys)
330
+ const key = preKeys[+keyId]
331
+ receipt.content.push({ tag: 'keys', attrs: {}, content: [{ tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) }, { tag: 'identity', attrs: {}, content: identityKey.public }, xmppPreKey(key, +keyId), xmppSignedPreKey(signedPreKey), { tag: 'device-identity', attrs: {}, content: deviceIdentity }] })
332
+ ev.emit('creds.update', update)
333
+ }
334
+ await sendNode(receipt)
335
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt')
336
+ }, authState?.creds?.me?.id || 'sendRetryRequest')
337
+ }
338
+
339
+ // ── TC token helpers ──────────────────────────────────────────────────────
340
+
341
+ const reissueTcTokenAfterIdentityChange = (from) => {
342
+ void (async () => {
343
+ const normalizedJid = jidNormalizedUser(from)
344
+ const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN)
345
+ const tcTokenData = await authState.keys.get('tctoken', [tcJid])
346
+ const senderTs = tcTokenData?.[tcJid]?.senderTimestamp
347
+ if (senderTs === null || senderTs === undefined || isTcTokenExpired(senderTs)) return
348
+ logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken')
349
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
350
+ const issueToLid = sock.serverProps?.lidTrustedTokenIssueToLid ?? false
351
+ const issueJid = await resolveIssuanceJid(normalizedJid, issueToLid, getLIDForPN, getPNForLID)
352
+ const result = await issuePrivacyTokens([issueJid], senderTs)
353
+ await storeTcTokensFromIqResult({ result, fallbackJid: tcJid, keys: authState.keys, getLIDForPN, onNewJidStored: trackTcTokenJid })
354
+ })().catch(err => logger.debug({ jid: from, err: err?.message }, 'failed to re-issue tctoken after identity change'))
355
+ }
356
+
357
+ const handlePrivacyTokenNotification = async (node) => {
358
+ const tokensNode = getBinaryNodeChild(node, 'tokens')
359
+ if (!tokensNode) return
360
+ const from = jidNormalizedUser(node.attrs.from)
361
+ const senderLid = node.attrs.sender_lid && isLidUser(jidNormalizedUser(node.attrs.sender_lid)) ? jidNormalizedUser(node.attrs.sender_lid) : undefined
362
+ const fallbackJid = senderLid ?? (await resolveTcTokenJid(from, getLIDForPN))
363
+ logger.debug({ from, storageJid: fallbackJid }, 'processing privacy token notification')
364
+ await storeTcTokensFromIqResult({ result: node, fallbackJid, keys: authState.keys, getLIDForPN, onNewJidStored: trackTcTokenJid })
365
+ }
366
+
367
+ const tcTokenKnownJids = new Set()
368
+ const tcTokenIndexLoaded = (async () => {
369
+ try { const jids = await readTcTokenIndex(authState.keys); for (const jid of jids) tcTokenKnownJids.add(jid); if (tcTokenKnownJids.size > 0) logger.debug({ count: tcTokenKnownJids.size }, 'loaded tctoken index') }
370
+ catch (err) { logger.warn({ err: err?.message }, 'failed to load tctoken index') }
371
+ })()
372
+
373
+ let tcTokenIndexTimer
374
+ const flushTcTokenIndex = async () => {
375
+ if (tcTokenIndexTimer) { clearTimeout(tcTokenIndexTimer); tcTokenIndexTimer = undefined }
376
+ const write = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids)
377
+ return authState.keys.set({ tctoken: write })
378
+ }
379
+ const scheduleTcTokenIndexSave = () => {
380
+ if (tcTokenIndexTimer) clearTimeout(tcTokenIndexTimer)
381
+ tcTokenIndexTimer = setTimeout(() => { tcTokenIndexTimer = undefined; flushTcTokenIndex().catch(err => logger.warn({ err: err?.message }, 'failed to save tctoken index')) }, 5000)
382
+ }
383
+ const trackTcTokenJid = (jid) => { if (jid && jid !== TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) { tcTokenKnownJids.add(jid); scheduleTcTokenIndexSave() } }
384
+
385
+ // ── Encrypt notification ──────────────────────────────────────────────────
386
+
387
+ const handleEncryptNotification = async (node) => {
388
+ const from = node.attrs.from
389
+ if (from === S_WHATSAPP_NET) {
390
+ const stanzaId = node.attrs.id
391
+ if (stanzaId && inFlightPreKeyLow.has(stanzaId)) return
392
+ const count = +getBinaryNodeChild(node, 'count').attrs.value
393
+ logger.debug({ count, shouldUploadMorePreKeys: count < MIN_PREKEY_COUNT }, 'recv pre-key count')
394
+ if (count < MIN_PREKEY_COUNT) {
395
+ if (stanzaId) inFlightPreKeyLow.add(stanzaId)
396
+ try { await uploadPreKeys() } finally { if (stanzaId) inFlightPreKeyLow.delete(stanzaId) }
397
+ }
398
+ } else {
399
+ const result = await handleIdentityChange(node, { meId: authState.creds.me?.id, meLid: authState.creds.me?.lid, validateSession: signalRepository.validateSession, assertSessions, debounceCache: identityAssertDebounce, logger, onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange })
400
+ if (result.action === 'no_identity_node') logger.info({ node }, 'unknown encrypt notification')
401
+ }
402
+ }
403
+
404
+ // ── Group notification ────────────────────────────────────────────────────
405
+
406
+ const handleGroupNotification = (fullNode, child, msg) => {
407
+ const actingParticipantLid = fullNode.attrs.participant
408
+ const actingParticipantPn = fullNode.attrs.participant_pn
409
+ const actingParticipantUsername = fullNode.attrs.participant_username
410
+ const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid
411
+ const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn
412
+ switch (child?.tag) {
413
+ case 'create':
414
+ const metadata = extractGroupMetadata(child)
415
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE
416
+ msg.messageStubParameters = [metadata.subject]
417
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn }
418
+ ev.emit('chats.upsert', [{ id: metadata.id, name: metadata.subject, conversationTimestamp: metadata.creation }])
419
+ ev.emit('groups.upsert', [{ ...metadata, author: actingParticipantLid, authorPn: actingParticipantPn, authorUsername: actingParticipantUsername }])
420
+ break
421
+ case 'ephemeral':
422
+ case 'not_ephemeral':
423
+ msg.message = { protocolMessage: { type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING, ephemeralExpiration: +(child.attrs.expiration || 0) } }
424
+ break
425
+ case 'modify':
426
+ const modifiedParticipants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => ({ id: attrs.jid, phoneNumber: isPnUser(attrs.phone_number) ? attrs.phone_number : undefined, lid: isLidUser(attrs.lid) ? attrs.lid : undefined, admin: attrs.type || null }))
427
+ msg.messageStubParameters = modifiedParticipants.map(a => JSON.stringify(a))
428
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER
429
+ break
430
+ case 'promote':
431
+ case 'demote':
432
+ case 'remove':
433
+ case 'add':
434
+ case 'leave':
435
+ msg.messageStubType = WAMessageStubType[`GROUP_PARTICIPANT_${child.tag.toUpperCase()}`]
436
+ const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => ({ id: attrs.jid, phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined, lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined, admin: attrs.type || null }))
437
+ if (participants.length === 1 && (areJidsSameUser(participants[0].id, actingParticipantLid) || areJidsSameUser(participants[0].id, actingParticipantPn)) && child.tag === 'remove') msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE
438
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a))
439
+ break
440
+ case 'subject':
441
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT
442
+ msg.messageStubParameters = [child.attrs.subject]
443
+ break
444
+ case 'description':
445
+ const description = getBinaryNodeChild(child, 'body')?.content?.toString()
446
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION
447
+ msg.messageStubParameters = description ? [description] : undefined
448
+ break
449
+ case 'announcement':
450
+ case 'not_announcement':
451
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE
452
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off']
453
+ break
454
+ case 'locked':
455
+ case 'unlocked':
456
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT
457
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off']
458
+ break
459
+ case 'invite':
460
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK
461
+ msg.messageStubParameters = [child.attrs.code]
462
+ break
463
+ case 'member_add_mode':
464
+ const addMode = child.content
465
+ if (addMode) { msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE; msg.messageStubParameters = [addMode.toString()] }
466
+ break
467
+ case 'membership_approval_mode':
468
+ const approvalMode = getBinaryNodeChild(child, 'group_join')
469
+ if (approvalMode) { msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE; msg.messageStubParameters = [approvalMode?.attrs?.state] }
470
+ break
471
+ case 'created_membership_requests':
472
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
473
+ msg.messageStubParameters = [JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }), 'created', child.attrs.request_method]
474
+ break
475
+ case 'revoked_membership_requests':
476
+ const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid)
477
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
478
+ msg.messageStubParameters = [JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }), isDenied ? 'revoked' : 'rejected']
479
+ break
480
+ }
481
+ }
482
+
483
+ // ── Devices notification ──────────────────────────────────────────────────
484
+
485
+ const handleDevicesNotification = async (node) => {
486
+ const [child] = getAllBinaryNodeChildren(node)
487
+ const from = jidNormalizedUser(node.attrs.from)
488
+ if (!child) { logger.debug({ from }, 'devices notification missing child, skipping'); return }
489
+ const tag = child.tag
490
+ const deviceHash = child.attrs.device_hash
491
+ const devices = getBinaryNodeChildren(child, 'device')
492
+ if (areJidsSameUser(from, authState.creds.me.id) || areJidsSameUser(from, authState.creds.me.lid)) logger.info({ deviceJids: devices.map(d => d.attrs.jid) }, 'got my own devices')
493
+ if (!devices.length) { logger.debug({ from, tag }, 'no devices in notification, skipping'); return }
494
+ const decoded = []
495
+ for (const d of devices) { const jid = d.attrs.jid; if (!jid) continue; const parts = jidDecode(jid); if (!parts) { logger.debug({ jid }, 'failed to decode device jid, skipping'); continue }; decoded.push({ jid, user: parts.user, server: parts.server, device: parts.device }) }
496
+ if (!decoded.length) return
497
+ await sock.devicesMutex.mutex(async () => {
498
+ const byUser = new Map()
499
+ for (const d of decoded) { const list = byUser.get(d.user) || []; list.push(d); byUser.set(d.user, list) }
500
+ for (const [user, entries] of byUser) {
501
+ if (tag === 'update') { logger.debug({ user }, `${user}'s device list updated, dropping cached devices`); await sock.userDevicesCache?.del(user); continue }
502
+ if (tag === 'remove') await signalRepository.deleteSession(entries.map(e => e.jid))
503
+ const existingCache = (await sock.userDevicesCache?.get(user)) || []
504
+ if (!existingCache.length) { logger.debug({ user, tag }, 'device list not cached, deferring to USync refresh'); continue }
505
+ const affected = new Set(entries.map(e => e.device))
506
+ let updatedDevices
507
+ switch (tag) {
508
+ case 'add': logger.info({ deviceHash, count: entries.length }, 'devices added'); updatedDevices = [...existingCache.filter(d => !affected.has(d.device)), ...entries.map(e => ({ user: e.user, server: e.server, device: e.device }))]; break
509
+ case 'remove': logger.info({ deviceHash, count: entries.length }, 'devices removed'); updatedDevices = existingCache.filter(d => !affected.has(d.device)); break
510
+ default: logger.debug({ tag }, 'unknown device list change tag'); continue
511
+ }
512
+ if (updatedDevices.length === 0) await sock.userDevicesCache?.del(user)
513
+ else await sock.userDevicesCache?.set(user, updatedDevices)
514
+ }
515
+ })
516
+ }
517
+
518
+ // ── processNotification ───────────────────────────────────────────────────
519
+
520
+ const processNotification = async (node) => {
521
+ const result = {}
522
+ const [child] = getAllBinaryNodeChildren(node)
523
+ const nodeType = node.attrs.type
524
+ const from = jidNormalizedUser(node.attrs.from)
525
+ switch (nodeType) {
526
+ case 'privacy_token': await handlePrivacyTokenNotification(node); break
527
+ case 'newsletter': await handleNewsletterNotification(node); break
528
+ case 'mex': await handleMexNotification(node); break
529
+ case 'w:gp2': handleGroupNotification(node, child, result); break
530
+ case 'mediaretry': ev.emit('messages.media-update', [decodeMediaRetryNode(node)]); break
531
+ case 'encrypt': await handleEncryptNotification(node); break
532
+ case 'devices':
533
+ try { await handleDevicesNotification(node) } catch (error) { logger.error({ error, node }, 'failed to handle devices notification') }
534
+ break
535
+ case 'server_sync':
536
+ const update = getBinaryNodeChild(node, 'collection')
537
+ if (update) await resyncAppState([update.attrs.name], false)
538
+ break
539
+ case 'picture':
540
+ const setPicture = getBinaryNodeChild(node, 'set')
541
+ const delPicture = getBinaryNodeChild(node, 'delete')
542
+ ev.emit('contacts.update', [{ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '', imgUrl: setPicture ? 'changed' : 'removed' }])
543
+ if (isJidGroup(from)) {
544
+ const pictureNode = setPicture || delPicture
545
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON
546
+ if (setPicture) result.messageStubParameters = [setPicture.attrs.id]
547
+ result.participant = pictureNode?.attrs.author
548
+ result.key = { ...(result.key || {}), participant: setPicture?.attrs.author }
549
+ }
550
+ break
551
+ case 'account_sync':
552
+ if (child.tag === 'disappearing_mode') {
553
+ const newDuration = +child.attrs.duration
554
+ logger.info({ newDuration }, 'updated account disappearing mode')
555
+ ev.emit('creds.update', { accountSettings: { ...authState.creds.accountSettings, defaultDisappearingMode: { ephemeralExpiration: newDuration, ephemeralSettingTimestamp: +child.attrs.t } } })
556
+ } else if (child.tag === 'blocklist') {
557
+ for (const { attrs } of getBinaryNodeChildren(child, 'item')) ev.emit('blocklist.update', { blocklist: [attrs.jid], type: attrs.action === 'block' ? 'add' : 'remove' })
558
+ }
559
+ break
560
+ case 'link_code_companion_reg':
561
+ const linkCodeNode = getBinaryNodeChild(node, 'link_code_companion_reg')
562
+ const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeNode, 'link_code_pairing_ref'))
563
+ const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeNode, 'primary_identity_pub'))
564
+ const primaryEphemeralWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeNode, 'link_code_pairing_wrapped_primary_ephemeral_pub'))
565
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralWrapped)
566
+ const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey)
567
+ const random = randomBytes(32)
568
+ const linkCodeSalt = randomBytes(32)
569
+ const linkCodePairingExpanded = hkdf(companionSharedKey, 32, { salt: linkCodeSalt, info: 'link_code_pairing_key_bundle_encryption_key' })
570
+ const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random])
571
+ const encryptIv = randomBytes(12)
572
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0))
573
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted])
574
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey)
575
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random])
576
+ authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64')
577
+ await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'set', id: sock.generateMessageTag(), xmlns: 'md' }, content: [{ tag: 'link_code_companion_reg', attrs: { jid: authState.creds.me.id, stage: 'companion_finish' }, content: [{ tag: 'link_code_pairing_wrapped_key_bundle', attrs: {}, content: encryptedPayload }, { tag: 'companion_identity_public', attrs: {}, content: authState.creds.signedIdentityKey.public }, { tag: 'link_code_pairing_ref', attrs: {}, content: ref }] }] })
578
+ authState.creds.registered = true
579
+ ev.emit('creds.update', authState.creds)
580
+ break
581
+ }
582
+ if (Object.keys(result).length) return result
583
+ }
584
+
585
+ // ── Link pairing helpers ──────────────────────────────────────────────────
586
+
587
+ const decipherLinkPublicKey = async (data) => {
588
+ const buffer = toRequiredBuffer(data)
589
+ const salt = buffer.subarray(0, 32)
590
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt)
591
+ const iv = buffer.subarray(32, 48)
592
+ const payload = buffer.subarray(48, 80)
593
+ return aesDecryptCTR(payload, secretKey, iv)
594
+ }
595
+
596
+ const toRequiredBuffer = (data) => {
597
+ if (data === undefined) throw new Boom('Invalid buffer', { statusCode: 400 })
598
+ return data instanceof Buffer ? data : Buffer.from(data)
599
+ }
600
+
601
+ // ── Retry helpers ─────────────────────────────────────────────────────────
602
+
603
+ const willSendMessageAgain = async (id, participant) => { const retryCount = (await msgRetryCache.get(`${id}:${participant}`)) || 0; return retryCount < maxMsgRetryCount }
604
+ const updateSendMessageAgainCount = async (id, participant) => { const key = `${id}:${participant}`; await msgRetryCache.set(key, ((await msgRetryCache.get(key)) || 0) + 1) }
605
+
606
+ const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
607
+ const remoteJid = key.remoteJid
608
+ const participant = key.participant || remoteJid
609
+ const retryCount = +retryNode.attrs.count || 1
610
+ const msgs = []
611
+
612
+ for (const id of ids) {
613
+ let msg
614
+ if (messageRetryManager) { const cached = messageRetryManager.getRecentMessage(remoteJid, id); if (cached) { msg = cached.message; logger.debug({ jid: remoteJid, id }, 'found message in retry cache'); messageRetryManager.markRetrySuccess(id) } }
615
+ if (!msg) { msg = await getMessage({ ...key, id }); if (msg) { logger.debug({ jid: remoteJid, id }, 'found message via getMessage'); if (messageRetryManager) messageRetryManager.markRetrySuccess(id) } }
616
+ msgs.push(msg)
617
+ }
618
+
619
+ const sendToAll = !jidDecode(participant)?.device
620
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant)
621
+ let injectedFromBundle = false
622
+ const bundle = extractE2ESessionFromRetryReceipt(receiptNode)
623
+
624
+ if (bundle) {
625
+ try { await signalRepository.injectE2ESession({ jid: participant, session: bundle }); injectedFromBundle = true; logger.debug({ participant, retryCount }, 'injected session from retry receipt key bundle') }
626
+ catch (error) { logger.warn({ error, participant }, 'failed to inject session from retry receipt') }
627
+ }
628
+
629
+ if (!injectedFromBundle && typeof signalRepository.getSessionInfo === 'function') {
630
+ const receivedRegId = getBinaryNodeChildUInt(receiptNode, 'registration', 4)
631
+ if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
632
+ const info = await signalRepository.getSessionInfo(participant)
633
+ if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) { logger.info({ participant, stored: info.registrationId, received: receivedRegId }, 'reg id mismatch on retry without bundle, deleting session'); await authState.keys.set({ session: { [sessionId]: null } }) }
634
+ }
635
+ }
636
+
637
+ if (ids[0] && messageRetryManager && typeof messageRetryManager.saveBaseKey === 'function') {
638
+ const info = typeof signalRepository.getSessionInfo === 'function' ? await signalRepository.getSessionInfo(participant) : undefined
639
+ if (info) {
640
+ if (retryCount === 2) messageRetryManager.saveBaseKey(sessionId, ids[0], info.baseKey)
641
+ else if (retryCount > 2) {
642
+ if (messageRetryManager.hasSameBaseKey(sessionId, ids[0], info.baseKey)) { logger.warn({ participant, retryCount }, 'base key collision on retry, forcing fresh session'); await authState.keys.set({ session: { [sessionId]: null } }) }
643
+ messageRetryManager.deleteBaseKey(sessionId, ids[0])
644
+ }
645
+ }
646
+ }
647
+
648
+ let shouldRecreateSession = false, recreateReason = ''
649
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
650
+ try {
651
+ const hasSession = await signalRepository.validateSession(participant)
652
+ const result = messageRetryManager.shouldRecreateSession(participant, retryCount, hasSession.exists)
653
+ shouldRecreateSession = result.recreate; recreateReason = result.reason
654
+ if (shouldRecreateSession) { logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry'); await authState.keys.set({ session: { [sessionId]: null } }) }
655
+ } catch (error) { logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry') }
656
+ }
657
+
658
+ if (!injectedFromBundle) await assertSessions([participant], true)
659
+ if (isJidGroup(remoteJid)) await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } })
660
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'preparing retry recp')
661
+
662
+ for (const [i, msg] of msgs.entries()) {
663
+ if (!ids[i]) continue
664
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
665
+ await updateSendMessageAgainCount(ids[i], participant)
666
+ const msgRelayOpts = { messageId: ids[i] }
667
+ if (sendToAll) msgRelayOpts.useUserDevicesCache = false
668
+ else msgRelayOpts.participant = { jid: participant, count: +retryNode.attrs.count }
669
+ await relayMessage(key.remoteJid, msg, msgRelayOpts)
670
+ } else logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available')
671
+ }
672
+ }
673
+
674
+ // ── handleReceipt ─────────────────────────────────────────────────────────
675
+
676
+ const handleReceipt = async (node) => {
677
+ const { attrs, content } = node
678
+ const isLid = attrs.from.includes('lid')
679
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id)
680
+ const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient
681
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe)
682
+ const key = { remoteJid, id: '', fromMe, participant: attrs.participant }
683
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) { logger.debug({ remoteJid }, 'ignoring receipt from jid'); await sendMessageAck(node); return }
684
+ const ids = [attrs.id]
685
+ if (Array.isArray(content)) ids.push(...getBinaryNodeChildren(content[0], 'item').map(i => i.attrs.id))
686
+ try {
687
+ await Promise.all([processingMutex.mutex(async () => {
688
+ const status = getStatusFromReceiptType(attrs.type)
689
+ if (typeof status !== 'undefined' && (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
690
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
691
+ if (attrs.participant) {
692
+ const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp'
693
+ ev.emit('message-receipt.update', ids.map(id => ({ key: { ...key, id }, receipt: { userJid: jidNormalizedUser(attrs.participant), [updateKey]: +attrs.t } })))
694
+ }
695
+ } else ev.emit('messages.update', ids.map(id => ({ key: { ...key, id }, update: { status, messageTimestamp: toNumber(+(attrs.t ?? 0)) } })))
696
+ }
697
+ if (attrs.type === 'retry') {
698
+ key.participant = key.participant || attrs.from
699
+ const retryNode = getBinaryNodeChild(node, 'retry')
700
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
701
+ if (key.fromMe) {
702
+ try { await updateSendMessageAgainCount(ids[0], key.participant); logger.debug({ attrs, key }, 'recv retry request'); await sendMessagesAgain(key, ids, retryNode, node) }
703
+ catch (error) { logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again') }
704
+ } else logger.info({ attrs, key }, 'recv retry for not fromMe message')
705
+ } else {
706
+ logger.info({ attrs, key, participant: key.participant }, 'retry limit exhausted - clearing broken session')
707
+ try {
708
+ await signalRepository.deleteSession([key.participant])
709
+ await msgRetryCache.del(`${ids[0]}:${key.participant}`)
710
+ } catch (err) { logger.error({ err, participant: key.participant }, 'failed to clear session/cache at retry exhaustion') }
711
+ }
712
+ }
713
+ })])
714
+ } finally { await sendMessageAck(node) }
715
+ }
716
+
717
+ // ── handleNotification ────────────────────────────────────────────────────
718
+
719
+ const handleNotification = async (node) => {
720
+ const remoteJid = node.attrs.from
721
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) { logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification'); await sendMessageAck(node); return }
722
+ try {
723
+ await Promise.all([notificationMutex.mutex(async () => {
724
+ const msg = await processNotification(node)
725
+ if (msg) {
726
+ const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id)
727
+ const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node)
728
+ msg.key = { remoteJid, fromMe, participant: node.attrs.participant, participantAlt, participantUsername: node.attrs.participant_username, addressingMode, id: node.attrs.id, ...(msg.key || {}) }
729
+ msg.participant ?? (msg.participant = node.attrs.participant)
730
+ msg.messageTimestamp = +node.attrs.t
731
+ await upsertMessage(proto.WebMessageInfo.fromObject(msg), 'append')
732
+ }
733
+ })])
734
+ } finally { await sendMessageAck(node) }
735
+ }
736
+
737
+ // ── handleMessage ─────────────────────────────────────────────────────────
738
+
739
+ const handleMessage = async (node) => {
740
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) { logger.debug({ key: node.attrs.key }, 'ignored message'); await sendMessageAck(node, NACK_REASONS.UnhandledError); return }
741
+
742
+ const encNode = getBinaryNodeChild(node, 'enc')
743
+ if (encNode && encNode.attrs.type === 'msmsg') {
744
+ const encIv = getBinaryNodeChildBuffer(encNode, 'enc_iv')
745
+ const encPayload = getBinaryNodeChildBuffer(encNode, 'enc_p') || encNode.content
746
+ if (!encIv || !encPayload) { logger.debug({ id: node.attrs.id, from: node.attrs.from, hasIv: !!encIv, hasPayload: !!encPayload }, 'msmsg missing enc_iv or enc_p, cannot decrypt'); await sendMessageAck(node); return }
747
+ try {
748
+ const messageSecret = authState.creds.myAppStateKeyId ? Buffer.from(authState.creds.myAppStateKeyId, 'base64') : undefined
749
+ if (!messageSecret) { logger.debug({ key: node.attrs.key }, 'no message secret for msmsg, skipping'); await sendMessageAck(node, NACK_REASONS.MissingMessageSecret); return }
750
+ const messageKey = { participant: node.attrs.participant || node.attrs.from, meId: authState.creds.me.id, meLid: authState.creds.me.lid, conversationJid: node.attrs.from, senderJid: node.attrs.participant, stanzaId: node.attrs.id, targetId: node.attrs.id }
751
+ const decrypted = await decryptMsmsgBotMessage(messageSecret, messageKey, { encPayload, encIv })
752
+ node.attrs._msmsgDecrypted = decodeDecryptedMsmsgMessage(decrypted)
753
+ logger.debug({ key: node.attrs.key }, 'decrypted msmsg bot message')
754
+ } catch (err) { logger.warn({ err, id: node.attrs.id }, 'failed to decrypt msmsg, falling back to nack'); await sendMessageAck(node, NACK_REASONS.MissingMessageSecret); return }
755
+ }
756
+
757
+ const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger)
758
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt
759
+ if (!!alt) {
760
+ const altServer = jidDecode(alt)?.server
761
+ const primaryJid = msg.key.participant || msg.key.remoteJid
762
+ if (altServer === 'lid') { if (!(await signalRepository.lidMapping.getPNForLID(alt))) { await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]); await signalRepository.migrateSession(primaryJid, alt) } }
763
+ else { await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]); await signalRepository.migrateSession(alt, primaryJid) }
764
+ }
765
+
766
+ let acked = false
767
+ try {
768
+ await messageMutex.mutex(async () => {
769
+ await decrypt()
770
+ if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message)
771
+
772
+ if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
773
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) { acked = true; return sendMessageAck(node, NACK_REASONS.ParsingError) }
774
+ if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
775
+ const unavailableNode = getBinaryNodeChild(node, 'unavailable')
776
+ const unavailableType = unavailableNode?.attrs?.type
777
+ if (['bot_unavailable_fanout', 'hosted_unavailable_fanout', 'view_once_unavailable_fanout'].includes(unavailableType)) { logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type'); acked = true; return sendMessageAck(node) }
778
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp)
779
+ if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) { logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message'); acked = true; return sendMessageAck(node) }
780
+ const cleanKey = { remoteJid: msg.key.remoteJid, fromMe: msg.key.fromMe, id: msg.key.id, participant: msg.key.participant }
781
+ const msgData = { key: msg.key, messageTimestamp: msg.messageTimestamp, pushName: msg.pushName, participant: msg.participant, verifiedBizName: msg.verifiedBizName }
782
+ requestPlaceholderResend(cleanKey, msgData).then(requestId => { if (requestId && requestId !== 'RESOLVED') { logger.debug({ msgId: msg.key.id, requestId }, 'requested placeholder resend for unavailable message'); ev.emit('messages.update', [{ key: msg.key, update: { messageStubParameters: [NO_MESSAGE_FOUND_ERROR_TEXT, requestId] } }]) } }).catch(err => logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message'))
783
+ acked = true; await sendMessageAck(node)
784
+ } else {
785
+ if ((msg.messageStubParameters?.[0] || '').includes('InvalidPreKeyId')) { logger.debug({ msgId: msg.key.id, remoteJid: msg.key.remoteJid }, 'skipping retry for InvalidPreKeyId, sender must re-establish session'); acked = true; return sendMessageAck(node, NACK_REASONS.UnhandledError) }
786
+ if (isJidStatusBroadcast(msg.key.remoteJid)) {
787
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp)
788
+ if (messageAge > STATUS_EXPIRY_SECONDS) { logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message'); acked = true; return sendMessageAck(node) }
789
+ }
790
+ retryMutex.mutex(async () => {
791
+ try { if (!ws.isOpen) { logger.debug({ node }, 'Connection closed, skipping retry'); return }; await sendRetryRequest(node, true); if (retryRequestDelayMs) await delay(retryRequestDelayMs) }
792
+ catch (err) { logger.error({ err }, 'Retry mechanism failed'); try { await sendRetryRequest(node, !getBinaryNodeChild(node, 'enc')) } catch (retryErr) { logger.error({ retryErr }, 'Final retry attempt failed') } }
793
+ acked = true; await sendMessageAck(node, NACK_REASONS.UnhandledError)
794
+ })
795
+ }
796
+ } else {
797
+ if (messageRetryManager && msg.key.id) messageRetryManager.cancelPendingPhoneRequest(msg.key.id)
798
+ const isNewsletter = isJidNewsletter(msg.key.remoteJid)
799
+ if (!isNewsletter) {
800
+ let type = undefined, participant = msg.key.participant
801
+ if (category === 'peer') type = 'peer_msg'
802
+ else if (msg.key.fromMe) { type = 'sender'; if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) participant = author }
803
+ else if (!sendActiveReceipts) type = 'inactive'
804
+ acked = true; await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type)
805
+ if (getHistoryMsg(msg.message)) await sendReceipt(jidNormalizedUser(msg.key.remoteJid), undefined, [msg.key.id], 'hist_sync')
806
+ } else { acked = true; await sendMessageAck(node); logger.debug({ key: msg.key }, 'processed newsletter message without receipts') }
807
+ }
808
+
809
+ cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid)
810
+
811
+ if (!msg.key.fromMe) {
812
+ try {
813
+ const info = extractReportingInfoFromStanza(node)
814
+ if (info) {
815
+ const senderJid = msg.key.participant || author || msg.key.remoteJid
816
+ const contentType = msg.message ? getContentType(msg.message) : undefined
817
+ config.reportingInfoStore?.add(senderJid, { stanzaId: info.stanzaId, timestamp: info.timestamp || Number(msg.messageTimestamp) || 0, reportingTag: info.reportingTag, reportingToken: info.reportingToken, tokenVersion: info.tokenVersion, validationPolicy: info.validationPolicy, text: extractMessageText(msg), pushName: msg.pushName || node.attrs?.notify || '', messageType: contentType === 'conversation' || contentType === 'extendedTextMessage' ? 'text' : contentType || 'text', fromJid: senderJid })
818
+ }
819
+ } catch (storeErr) { logger.warn({ err: storeErr, key: msg.key }, 'failed to store reporting_tag') }
820
+ }
821
+
822
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify')
823
+ })
824
+ } catch (error) {
825
+ const isClosed = error?.message?.includes('Connection Closed') || error?.output?.statusCode === 428
826
+ if (isClosed) logger.debug({ msg: error?.message }, 'Connection closed while handling message')
827
+ else logger.error({ error, stack: error?.stack, msg: error?.message || String(error), node: binaryNodeToString(node) }, 'error in handling message')
828
+ if (!acked) await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(ackErr => logger.error({ ackErr }, 'failed to ack message after error'))
829
+ }
830
+ }
831
+
832
+ // ── handleCall ────────────────────────────────────────────────────────────
833
+
834
+ const handleCall = async (node) => {
835
+ const { attrs } = node
836
+ try {
837
+ const [infoChild] = getAllBinaryNodeChildren(node)
838
+ if (!infoChild) throw new Boom('Missing call info in call node')
839
+ const status = getCallStatusFromNode(infoChild)
840
+ const callId = infoChild.attrs['call-id']
841
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator']
842
+ const call = { chatId: attrs.from, from, callerPn: infoChild.attrs['caller_pn'], id: callId, date: new Date(+attrs.t * 1000), offline: !!attrs.offline, status }
843
+ if (status === 'relaylatency') { const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms']; const latencyMs = latencyValue ? Number(latencyValue) : undefined; if (Number.isFinite(latencyMs)) call.latencyMs = latencyMs }
844
+ if (status === 'offer') { call.isVideo = !!getBinaryNodeChild(infoChild, 'video'); call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid']; call.groupJid = infoChild.attrs['group-jid']; await callOfferCache.set(call.id, call) }
845
+ const existingCall = await callOfferCache.get(call.id)
846
+ if (existingCall) { call.isVideo = existingCall.isVideo; call.isGroup = existingCall.isGroup; call.callerPn = call.callerPn || existingCall.callerPn }
847
+ if (['reject', 'accept', 'timeout', 'terminate'].includes(status)) await callOfferCache.del(call.id)
848
+ ev.emit('call', [call])
849
+ } catch (error) { logger.error({ error, node: binaryNodeToString(node) }, 'error in handling call') }
850
+ finally { await sendMessageAck(node) }
851
+ }
852
+
853
+ // ── handleBadAck ──────────────────────────────────────────────────────────
854
+
855
+ const handleBadAck = async ({ attrs }) => {
856
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id }
857
+ if (!attrs.error) return
858
+ const isReachoutTimelocked = attrs.error === String(NACK_REASONS.SenderReachoutTimelocked)
859
+ if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
860
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'error 463: account restricted or missing tctoken for contact')
861
+ const ackFrom = attrs.from
862
+ if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
863
+ inFlight463Recoveries.add(ackFrom)
864
+ void (async () => {
865
+ try {
866
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
867
+ const tcStorageJid = await resolveTcTokenJid(ackFrom, getLIDForPN)
868
+ const issueToLid = sock.serverProps?.lidTrustedTokenIssueToLid ?? false
869
+ const issueJid = await resolveIssuanceJid(ackFrom, issueToLid, getLIDForPN, getPNForLID)
870
+ const result = await issuePrivacyTokens([issueJid], unixTimestampSeconds())
871
+ await storeTcTokensFromIqResult({ result, fallbackJid: tcStorageJid, keys: authState.keys, getLIDForPN, onNewJidStored: trackTcTokenJid })
872
+ logger.debug({ from: ackFrom }, 'completed 463 token recovery issuance')
873
+ ev.emit('messages.update', [{ key, update: { status: WAMessageStatus.PENDING } }])
874
+ } catch (err) { logger.debug({ from: ackFrom, err: err?.message }, 'failed 463 token recovery issuance') }
875
+ finally { inFlight463Recoveries.delete(ackFrom) }
876
+ })()
877
+ }
878
+ } else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
879
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'smax-invalid (479): stale device session or malformed addressing')
880
+ } else if (isReachoutTimelocked) {
881
+ await fetchAccountReachoutTimelock().catch(err => logger.warn({ err }, 'failed to fetch reachout timelock'))
882
+ logger.warn({ attrs }, 'received error in ack')
883
+ } else {
884
+ logger.warn({ attrs }, 'received error in ack')
885
+ }
886
+ ev.emit('messages.update', [{ key, update: { status: WAMessageStatus.ERROR, messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error] } }])
887
+ }
888
+
889
+ // ── Offline node processor ────────────────────────────────────────────────
890
+
891
+ const processNodeWithBuffer = async (node, identifier, exec) => { ev.buffer(); await exec(node, false).catch(err => onUnexpectedError(err, identifier)); ev.flush() }
892
+ const yieldToEventLoop = () => new Promise(resolve => setImmediate(resolve))
893
+
894
+ const makeOfflineNodeProcessor = () => {
895
+ const nodeProcessorMap = new Map([['message', handleMessage], ['status', handleMessage], ['call', handleCall], ['receipt', handleReceipt], ['notification', handleNotification]])
896
+ const nodes = []
897
+ let isProcessing = false
898
+ const enqueue = (type, node) => {
899
+ nodes.push({ type, node })
900
+ if (isProcessing) return
901
+ isProcessing = true;
902
+ (async () => {
903
+ let processedInBatch = 0
904
+ while (nodes.length && ws.isOpen) {
905
+ const { type, node } = nodes.shift()
906
+ const processor = nodeProcessorMap.get(type)
907
+ if (!processor) { onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node'); continue }
908
+ await processor(node).catch(err => onUnexpectedError(err, `processing offline ${type}`))
909
+ if (++processedInBatch >= 10) { processedInBatch = 0; await yieldToEventLoop() }
910
+ }
911
+ isProcessing = false
912
+ })().catch(error => onUnexpectedError(error, 'processing offline nodes'))
913
+ }
914
+ return { enqueue }
915
+ }
916
+
917
+ const offlineNodeProcessor = makeOfflineNodeProcessor()
918
+
919
+ const processNode = async (type, node, identifier, exec) => {
920
+ const from = node.attrs.from
921
+ let ignoreJid = from
922
+ if (type === 'receipt' && from) { const isLid = from.includes('lid'); const isNodeFromMe = areJidsSameUser(node.attrs.participant || from, isLid ? authState.creds.me?.lid : authState.creds.me?.id); ignoreJid = !isNodeFromMe || isJidGroup(from) ? from : node.attrs.recipient }
923
+ if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) { await sendMessageAck(node, type === 'message' ? NACK_REASONS.UnhandledError : undefined); return }
924
+ if (node.attrs.offline) offlineNodeProcessor.enqueue(type, node)
925
+ else await processNodeWithBuffer(node, identifier, exec)
926
+ }
927
+
928
+ // ── WS event bindings ─────────────────────────────────────────────────────
929
+
930
+ ws.on('CB:message', async (node) => { await processNode('message', node, 'processing message', handleMessage) })
931
+ ws.on('CB:status', async (node) => { if (isJidNewsletter(node.attrs?.from)) return; await processNode('message', node, 'processing status', handleMessage) })
932
+ ws.on('CB:call', async (node) => { await processNode('call', node, 'handling call', handleCall) })
933
+ ws.on('CB:receipt', async (node) => { await processNode('receipt', node, 'handling receipt', handleReceipt) })
934
+ ws.on('CB:notification', async (node) => { await processNode('notification', node, 'handling notification', handleNotification) })
935
+ ws.on('CB:ack,class:message', (node) => { handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack')) })
936
+
937
+ ev.on('call', async ([call]) => {
938
+ if (!call) return
939
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
940
+ const msg = { key: { remoteJid: call.chatId, id: call.id, fromMe: false }, messageTimestamp: unixTimestampSeconds(call.date) }
941
+ if (call.status === 'timeout') msg.messageStubType = call.isGroup ? (call.isVideo ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO : WAMessageStubType.CALL_MISSED_GROUP_VOICE) : (call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE)
942
+ else msg.message = { call: { callKey: Buffer.from(call.id) } }
943
+ await upsertMessage(proto.WebMessageInfo.fromObject(msg), call.offline ? 'append' : 'notify')
944
+ }
945
+ })
946
+
947
+ // ── TC token pruning ──────────────────────────────────────────────────────
948
+
949
+ let lastTcTokenPruneTs = 0
950
+ const pruneExpiredTcTokens = async () => {
951
+ try {
952
+ await tcTokenIndexLoaded
953
+ const persisted = await readTcTokenIndex(authState.keys)
954
+ const allJids = new Set([...tcTokenKnownJids, ...persisted])
955
+ if (!allJids.size) return
956
+ const jids = [...allJids]
957
+ const allTokens = await authState.keys.get('tctoken', jids)
958
+ const writes = {}, survivors = new Set()
959
+ let mutated = 0
960
+ for (const jid of jids) {
961
+ const entry = allTokens[jid]
962
+ if (!entry) { mutated++; continue }
963
+ const hasPeerToken = !!entry.token?.length
964
+ const peerTokenExpired = hasPeerToken && isTcTokenExpired(entry.timestamp)
965
+ const hasSenderTs = entry.senderTimestamp !== undefined
966
+ const senderTsExpired = hasSenderTs && isTcTokenExpired(entry.senderTimestamp)
967
+ const keepPeer = hasPeerToken && !peerTokenExpired
968
+ const keepSender = hasSenderTs && !senderTsExpired
969
+ if (!keepPeer && !keepSender) { writes[jid] = null; mutated++ }
970
+ else if (peerTokenExpired && keepSender) { writes[jid] = { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }; survivors.add(jid); mutated++ }
971
+ else survivors.add(jid)
972
+ }
973
+ if (mutated === 0) return
974
+ await authState.keys.set({ tctoken: { ...writes, [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...survivors])) } } })
975
+ tcTokenKnownJids.clear(); for (const jid of survivors) tcTokenKnownJids.add(jid)
976
+ logger.debug({ mutated, remaining: survivors.size }, 'pruned expired tctokens')
977
+ } catch (err) { logger.warn({ err: err?.message }, 'failed to prune expired tctokens') }
978
+ }
979
+
980
+ ev.on('connection.update', ({ isOnline, connection }) => {
981
+ if (typeof isOnline !== 'undefined') { sendActiveReceipts = isOnline; logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`) }
982
+ if (connection === 'close' && tcTokenIndexTimer) { clearTimeout(tcTokenIndexTimer); tcTokenIndexTimer = undefined; try { void Promise.resolve(flushTcTokenIndex()).catch(() => { }) } catch { } }
983
+ if (isOnline) { const now = Date.now(); if (now - lastTcTokenPruneTs >= 86_400_000) { lastTcTokenPruneTs = now; void pruneExpiredTcTokens() } }
984
+ })
985
+
986
+ registerSocketEndHandler(() => {
987
+ if (!config.msgRetryCounterCache && msgRetryCache.close) msgRetryCache.close()
988
+ if (!config.callOfferCache && callOfferCache.close) callOfferCache.close()
989
+ identityAssertDebounce.close()
990
+ sendActiveReceipts = false
991
+ })
992
+
993
+ return { ...sock, sendMessageAck, sendRetryRequest, rejectCall, acceptCall, terminateCall, offerCall, fetchMessageHistory, requestPlaceholderResend, requestContactRefresh, messageRetryManager, tcTokenIndexLoaded }
994
994
  }