@x4r1s3/baileys 0.0.0-stage → 1.0.0

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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1262 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/audio-feeder.mjs +179 -0
  18. package/lib/Call/audio-recorder.mjs +250 -0
  19. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  20. package/lib/Call/index.mjs +680 -0
  21. package/lib/Call/relay-transport.mjs +563 -0
  22. package/lib/Call/signaling.mjs +641 -0
  23. package/lib/Call/types.mjs +17 -0
  24. package/lib/Call/video-feeder.mjs +94 -0
  25. package/lib/Call/wasm-engine.mjs +1372 -0
  26. package/lib/Call/worker-bootstrap.mjs +1042 -0
  27. package/lib/Defaults/ban-checker.js +56 -0
  28. package/lib/Defaults/index.js +170 -0
  29. package/lib/Signal/Group/ciphertext-message.js +23 -0
  30. package/lib/Signal/Group/group-session-builder.js +41 -0
  31. package/lib/Signal/Group/group_cipher.js +93 -0
  32. package/lib/Signal/Group/index.js +23 -0
  33. package/lib/Signal/Group/keyhelper.js +29 -0
  34. package/lib/Signal/Group/sender-chain-key.js +37 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  36. package/lib/Signal/Group/sender-key-message.js +77 -0
  37. package/lib/Signal/Group/sender-key-name.js +59 -0
  38. package/lib/Signal/Group/sender-key-record.js +52 -0
  39. package/lib/Signal/Group/sender-key-state.js +95 -0
  40. package/lib/Signal/Group/sender-message-key.js +37 -0
  41. package/lib/Signal/libsignal.js +440 -0
  42. package/lib/Signal/lid-mapping.js +292 -0
  43. package/lib/Socket/Client/index.js +14 -0
  44. package/lib/Socket/Client/types.js +22 -0
  45. package/lib/Socket/Client/websocket.js +65 -0
  46. package/lib/Socket/aigroups.js +327 -0
  47. package/lib/Socket/ban-checker.js +165 -0
  48. package/lib/Socket/business.js +419 -0
  49. package/lib/Socket/chats.js +1921 -0
  50. package/lib/Socket/communities.js +443 -0
  51. package/lib/Socket/graphql.js +911 -0
  52. package/lib/Socket/groups.js +561 -0
  53. package/lib/Socket/index.js +49 -0
  54. package/lib/Socket/interactive-handler.js +612 -0
  55. package/lib/Socket/interop.js +575 -0
  56. package/lib/Socket/managed-account.js +220 -0
  57. package/lib/Socket/messages-recv.js +2191 -0
  58. package/lib/Socket/messages-send.js +4104 -0
  59. package/lib/Socket/mex.js +53 -0
  60. package/lib/Socket/newsletter.js +291 -0
  61. package/lib/Socket/privacy.js +458 -0
  62. package/lib/Socket/registration.js +440 -0
  63. package/lib/Socket/socket.js +1029 -0
  64. package/lib/Socket/status-actions.js +287 -0
  65. package/lib/Socket/username.js +241 -0
  66. package/lib/Store/index.js +16 -0
  67. package/lib/Store/make-cache-manager-store.js +101 -0
  68. package/lib/Store/make-in-memory-store.js +432 -0
  69. package/lib/Store/make-ordered-dictionary.js +90 -0
  70. package/lib/Store/object-repository.js +35 -0
  71. package/lib/Types/Auth.js +13 -0
  72. package/lib/Types/Bussines.js +13 -0
  73. package/lib/Types/Call.js +13 -0
  74. package/lib/Types/Chat.js +19 -0
  75. package/lib/Types/Contact.js +13 -0
  76. package/lib/Types/Events.js +13 -0
  77. package/lib/Types/GroupMetadata.js +13 -0
  78. package/lib/Types/Label.js +36 -0
  79. package/lib/Types/LabelAssociation.js +18 -0
  80. package/lib/Types/Message.js +30 -0
  81. package/lib/Types/Mex.js +53 -0
  82. package/lib/Types/Product.js +13 -0
  83. package/lib/Types/RichType.js +34 -0
  84. package/lib/Types/Signal.js +13 -0
  85. package/lib/Types/Socket.js +14 -0
  86. package/lib/Types/State.js +60 -0
  87. package/lib/Types/USync.js +13 -0
  88. package/lib/Types/index.js +37 -0
  89. package/lib/Utils/auth-utils.js +313 -0
  90. package/lib/Utils/ban-checker.js +48 -0
  91. package/lib/Utils/bot-capabilities.js +96 -0
  92. package/lib/Utils/bot-planning-replay.js +177 -0
  93. package/lib/Utils/browser-utils.js +40 -0
  94. package/lib/Utils/business.js +242 -0
  95. package/lib/Utils/c2582.js +147 -0
  96. package/lib/Utils/chat-utils.js +905 -0
  97. package/lib/Utils/companion-reg-client-utils.js +44 -0
  98. package/lib/Utils/consumer-application.js +114 -0
  99. package/lib/Utils/crypto.js +129 -0
  100. package/lib/Utils/decode-wa-message.js +496 -0
  101. package/lib/Utils/direct-chat-theme.js +164 -0
  102. package/lib/Utils/event-buffer.js +601 -0
  103. package/lib/Utils/experimental-proto.js +206 -0
  104. package/lib/Utils/games/miniapp.js +17 -0
  105. package/lib/Utils/games/slot-machine.js +270 -0
  106. package/lib/Utils/games/website-preview.js +306 -0
  107. package/lib/Utils/generics.js +402 -0
  108. package/lib/Utils/group-history.js +68 -0
  109. package/lib/Utils/group-wallpaper.js +168 -0
  110. package/lib/Utils/history.js +162 -0
  111. package/lib/Utils/identity-change-handler.js +60 -0
  112. package/lib/Utils/index.js +61 -0
  113. package/lib/Utils/jid-display-normalization.js +221 -0
  114. package/lib/Utils/link-preview.js +96 -0
  115. package/lib/Utils/logger.js +14 -0
  116. package/lib/Utils/lt-hash.js +19 -0
  117. package/lib/Utils/make-mutex.js +44 -0
  118. package/lib/Utils/message-composer.js +709 -0
  119. package/lib/Utils/message-inspect.js +79 -0
  120. package/lib/Utils/message-retry-manager.js +253 -0
  121. package/lib/Utils/message-security.js +167 -0
  122. package/lib/Utils/messages-media.js +1027 -0
  123. package/lib/Utils/messages.js +2467 -0
  124. package/lib/Utils/meta-ai-msmsg.js +215 -0
  125. package/lib/Utils/meta-compositing.js +239 -0
  126. package/lib/Utils/native-flow.js +158 -0
  127. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  128. package/lib/Utils/newsletter-status-utils.js +152 -0
  129. package/lib/Utils/noise-handler.js +212 -0
  130. package/lib/Utils/offline-node-processor.js +51 -0
  131. package/lib/Utils/poll-manager.js +206 -0
  132. package/lib/Utils/portable-compat.js +12 -0
  133. package/lib/Utils/pre-key-manager.js +117 -0
  134. package/lib/Utils/process-message.js +610 -0
  135. package/lib/Utils/reporting-utils.js +269 -0
  136. package/lib/Utils/rich-message-utils.js +2841 -0
  137. package/lib/Utils/scheduled-message.js +107 -0
  138. package/lib/Utils/signal.js +212 -0
  139. package/lib/Utils/source-grep.js +57 -0
  140. package/lib/Utils/stanza-ack.js +49 -0
  141. package/lib/Utils/sticker-annotation.js +87 -0
  142. package/lib/Utils/sync-action-utils.js +59 -0
  143. package/lib/Utils/tc-token-utils.js +174 -0
  144. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  145. package/lib/Utils/use-single-file-auth-state.js +108 -0
  146. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  147. package/lib/Utils/validate-connection.js +220 -0
  148. package/lib/Utils/view-once-utils.js +218 -0
  149. package/lib/Utils/voip-rekey.js +32 -0
  150. package/lib/Utils/website-preview.js +27 -0
  151. package/lib/Utils/welcome-flow.js +228 -0
  152. package/lib/Utils/x4r1s3.js +144 -0
  153. package/lib/WABinary/constants.js +1475 -0
  154. package/lib/WABinary/decode.js +273 -0
  155. package/lib/WABinary/encode.js +231 -0
  156. package/lib/WABinary/generic-utils.js +242 -0
  157. package/lib/WABinary/index.js +17 -0
  158. package/lib/WABinary/jid-utils.js +107 -0
  159. package/lib/WABinary/types.js +13 -0
  160. package/lib/WAM/BinaryInfo.js +21 -0
  161. package/lib/WAM/constants.js +22864 -0
  162. package/lib/WAM/encode.js +161 -0
  163. package/lib/WAM/index.js +15 -0
  164. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  167. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  168. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  169. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  170. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  172. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  173. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  174. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  176. package/lib/WAUSync/Protocols/index.js +24 -0
  177. package/lib/WAUSync/USyncQuery.js +213 -0
  178. package/lib/WAUSync/USyncUser.js +66 -0
  179. package/lib/WAUSync/index.js +15 -0
  180. package/lib/antiban.cjs +4726 -0
  181. package/lib/index.d.ts +1285 -0
  182. package/lib/index.js +30 -0
  183. package/package.json +125 -4
@@ -0,0 +1,2191 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Socket/messages-recv.js
5
+ * About: Messages recv module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: buildGroupCallStanza, buildGroupCallCancelStanza, makeMessagesRecvSocket
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import NodeCache from '@cacheable/node-cache';
14
+ import { Boom } from '@hapi/boom';
15
+ import { randomBytes } from 'crypto';
16
+ import Long from 'long';
17
+ import { proto } from '../../WAProto/index.js';
18
+ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/index.js';
19
+ import { ReachoutTimelockEnforcementType, WAMessageStatus, WAMessageStubType } from '../Types/index.js';
20
+ import { ACCOUNT_RESTRICTED_TEXT, aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, extractE2ESessionFromRetryReceipt, generateMessageID, setBotMessageSecret, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, NO_MESSAGE_FOUND_ERROR_TEXT, SERVER_ERROR_CODES, toNumber, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
21
+ import { makeMutex } from '../Utils/make-mutex.js';
22
+ import { makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
23
+ import { buildAckStanza } from '../Utils/stanza-ack.js';
24
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, readTcTokenIndex, resolveIssuanceJid, resolveTcTokenJid, storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY } from '../Utils/tc-token-utils.js';
25
+ import { emitNewsletterLiveUpdate } from '../Utils/newsletter-live-update-utils.js';
26
+ import { findUnknownReceiptIds, MessageSecurityStore } from '../Utils/message-security.js';
27
+ import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, getBinaryNodeChildUInt, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
28
+ import { extractGroupMetadata } from './groups.js';
29
+ import { makeMessagesSocket } from './messages-send.js';
30
+ const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(ReachoutTimelockEnforcementType));
31
+ function isValidEnforcementType(value) {
32
+ return typeof value === 'string' && ENFORCEMENT_TYPE_VALUES.has(value);
33
+ }
34
+
35
+ /** Build the verified protobuf payload for a recent-conversations PDO request. */
36
+ export const buildRecentConversationsOnDemandRequest = ({ conversationCount, messagesPerConversation } = {}) => {
37
+ const isPositiveUint32 = value => Number.isInteger(value) && value > 0 && value <= 0xFFFFFFFF;
38
+ if (!isPositiveUint32(conversationCount) || !isPositiveUint32(messagesPerConversation)) {
39
+ throw new Boom('requestRecentConversationsOnDemand requires positive uint32 conversationCount and messagesPerConversation values', { statusCode: 400 });
40
+ }
41
+ return {
42
+ recentConversationsOnDemandRequest: { conversationCount, messagesPerConversation },
43
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.RECENT_CONVERSATIONS_ON_DEMAND_REQUEST
44
+ };
45
+ };
46
+ /**
47
+ * Build the <call><offer type="group" group-jid=..> stanza used to start a group call.
48
+ * Pure: no socket state, unit-testable.
49
+ */
50
+ export const buildGroupCallStanza = ({ id, to, callId, callCreator, offerContent }) => ({
51
+ tag: 'call',
52
+ attrs: {
53
+ id,
54
+ to
55
+ },
56
+ content: [
57
+ {
58
+ tag: 'offer',
59
+ attrs: {
60
+ 'call-id': callId,
61
+ 'call-creator': callCreator,
62
+ type: 'group',
63
+ 'group-jid': to
64
+ },
65
+ content: offerContent
66
+ }
67
+ ]
68
+ });
69
+ /**
70
+ * Build the <call><terminate> stanza used to cancel / hang up a group call.
71
+ * Pure: no socket state, unit-testable.
72
+ */
73
+ export const buildGroupCallCancelStanza = ({ to, callId, callCreator }) => ({
74
+ tag: 'call',
75
+ attrs: {
76
+ from: callCreator,
77
+ to
78
+ },
79
+ content: [
80
+ {
81
+ tag: 'terminate',
82
+ attrs: {
83
+ 'call-id': callId,
84
+ 'call-creator': callCreator,
85
+ reason: 'user-terminated',
86
+ count: '0'
87
+ },
88
+ content: undefined
89
+ }
90
+ ]
91
+ });
92
+ export const makeMessagesRecvSocket = (config) => {
93
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
94
+ const sock = makeMessagesSocket(config);
95
+ const { userDevicesCache, devicesMutex, ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager, registerSocketEndHandler, issuePrivacyTokens, fetchAccountReachoutTimelock, placeholderResendCache, getUSyncDevices, createParticipantNodes, newsletterServerIdCache } = sock;
96
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
97
+ const messageSecurityStore = config.messageSecurityStore || new MessageSecurityStore(authState.keys, logger);
98
+ config.messageSecurityStore = messageSecurityStore;
99
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
100
+ const retryMutex = makeMutex();
101
+ const msgRetryCache = config.msgRetryCounterCache ||
102
+ new NodeCache({
103
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
104
+ useClones: false
105
+ });
106
+ const callOfferCache = config.callOfferCache ||
107
+ new NodeCache({
108
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
109
+ useClones: false
110
+ });
111
+ // Debounce identity-change session refreshes per JID to avoid bursts
112
+ const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
113
+ let sendActiveReceipts = false;
114
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
115
+ if (!authState.creds.me?.id) {
116
+ throw new Boom('Not authenticated');
117
+ }
118
+ const pdoMessage = {
119
+ historySyncOnDemandRequest: {
120
+ chatJid: oldestMsgKey.remoteJid,
121
+ oldestMsgFromMe: oldestMsgKey.fromMe,
122
+ oldestMsgId: oldestMsgKey.id,
123
+ oldestMsgTimestampMs: oldestMsgTimestamp,
124
+ onDemandMsgCount: count
125
+ },
126
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
127
+ };
128
+ return sendPeerDataOperationMessage(pdoMessage);
129
+ };
130
+ const requestRecentConversationsOnDemand = async ({ conversationCount, messagesPerConversation } = {}) => {
131
+ if (!authState.creds.me?.id) {
132
+ throw new Boom('Not authenticated');
133
+ }
134
+ return sendPeerDataOperationMessage(buildRecentConversationsOnDemandRequest({ conversationCount, messagesPerConversation }));
135
+ };
136
+ const requestPlaceholderResend = async (messageKey, msgData) => {
137
+ if (!authState.creds.me?.id) {
138
+ throw new Boom('Not authenticated');
139
+ }
140
+ if (await placeholderResendCache.get(messageKey?.id)) {
141
+ logger.debug({ messageKey }, 'already requested resend');
142
+ return;
143
+ }
144
+ else {
145
+ // Store original message data so PDO response handler can preserve
146
+ // metadata (LID details, timestamps, etc.) that the phone may omit
147
+ await placeholderResendCache.set(messageKey?.id, msgData || true);
148
+ }
149
+ await delay(2000);
150
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
151
+ logger.debug({ messageKey }, 'message received while resend requested');
152
+ return 'RESOLVED';
153
+ }
154
+ const pdoMessage = {
155
+ placeholderMessageResendRequest: [
156
+ {
157
+ messageKey
158
+ }
159
+ ],
160
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
161
+ };
162
+ setTimeout(async () => {
163
+ if (await placeholderResendCache.get(messageKey?.id)) {
164
+ logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline');
165
+ await placeholderResendCache.del(messageKey?.id);
166
+ }
167
+ }, 8000);
168
+ return sendPeerDataOperationMessage(pdoMessage);
169
+ };
170
+ const handleMexNotification = async (node) => {
171
+ const updateNode = getBinaryNodeChild(node, 'update');
172
+ if (updateNode) {
173
+ const opName = updateNode.attrs?.op_name;
174
+ if (!opName) {
175
+ logger.warn({ node: binaryNodeToString(node) }, 'mex notification missing op_name, fallback to legacy');
176
+ await handleLegacyMexNewsletterNotification(node);
177
+ return;
178
+ }
179
+ let mexResponse;
180
+ try {
181
+ mexResponse = JSON.parse(updateNode.content.toString());
182
+ }
183
+ catch (error) {
184
+ logger.error({ err: error, opName }, 'failed to parse mex notification JSON');
185
+ return;
186
+ }
187
+ if (mexResponse.errors?.length) {
188
+ logger.warn({ errors: mexResponse.errors, opName }, 'mex notification has GQL errors');
189
+ return;
190
+ }
191
+ const data = mexResponse.data;
192
+ if (!data) {
193
+ logger.warn({ opName }, 'mex notification has null data');
194
+ return;
195
+ }
196
+ logger.debug({ opName }, 'processing mex notification');
197
+ switch (opName) {
198
+ case 'NotificationUserReachoutTimelockUpdate':
199
+ handleReachoutTimelockNotification(data);
200
+ break;
201
+ case 'MessageCappingInfoNotification':
202
+ handleMessageCappingNotification(data);
203
+ break;
204
+ // newsletter ops still use the legacy <mex> child structure
205
+ case 'NotificationNewsletterUpdate':
206
+ case 'NotificationLinkedProfilesUpdates':
207
+ case 'NotificationNewsletterAdminPromote':
208
+ case 'NotificationNewsletterAdminDemote':
209
+ case 'NotificationNewsletterUserSettingChange':
210
+ case 'NotificationNewsletterJoin':
211
+ case 'NotificationNewsletterLeave':
212
+ case 'NotificationNewsletterStateChange':
213
+ case 'NotificationNewsletterAdminMetadataUpdate':
214
+ case 'NotificationNewsletterOwnerUpdate':
215
+ case 'NotificationNewsletterAdminInviteRevoke':
216
+ case 'NotificationNewsletterWamoSubStatusChange':
217
+ case 'NotificationNewsletterBlockUser':
218
+ case 'NotificationNewsletterPaidPartnership':
219
+ case 'NotificationNewsletterMilestone':
220
+ case 'NewsletterResponseStateUpdate':
221
+ await handleLegacyMexNewsletterNotification(node);
222
+ break;
223
+ default:
224
+ logger.debug({ opName }, 'unhandled mex notification');
225
+ break;
226
+ }
227
+ return;
228
+ }
229
+ await handleLegacyMexNewsletterNotification(node);
230
+ };
231
+ const handleReachoutTimelockNotification = (data) => {
232
+ const payload = data.xwa2_notify_account_reachout_timelock;
233
+ if (!payload) {
234
+ logger.warn('reachout timelock notification missing payload');
235
+ return;
236
+ }
237
+ if (!payload.is_active) {
238
+ logger.info('reachout timelock restriction lifted');
239
+ ev.emit('connection.update', {
240
+ reachoutTimeLock: {
241
+ isActive: false,
242
+ enforcementType: ReachoutTimelockEnforcementType.DEFAULT
243
+ }
244
+ });
245
+ return;
246
+ }
247
+ // WA Web defaults to now+60s when the server omits the expiry
248
+ const timeEnforcementEnds = payload.time_enforcement_ends
249
+ ? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000)
250
+ : new Date(Date.now() + 60000);
251
+ const enforcementType = isValidEnforcementType(payload.enforcement_type)
252
+ ? payload.enforcement_type
253
+ : ReachoutTimelockEnforcementType.DEFAULT;
254
+ logger.info({ enforcementType, timeEnforcementEnds }, 'reachout timelock restriction set');
255
+ ev.emit('connection.update', {
256
+ reachoutTimeLock: {
257
+ isActive: true,
258
+ timeEnforcementEnds,
259
+ enforcementType
260
+ }
261
+ });
262
+ };
263
+ const handleMessageCappingNotification = (data) => {
264
+ const payload = data.xwa2_notify_new_chat_messages_capping_info_update;
265
+ if (!payload) {
266
+ logger.warn('message capping notification missing payload');
267
+ return;
268
+ }
269
+ logger.info({ payload }, 'received message capping update');
270
+ ev.emit('message-capping.update', payload);
271
+ };
272
+ const handleLegacyMexNewsletterNotification = async (node) => {
273
+ const mexNode = getBinaryNodeChild(node, 'mex');
274
+ const updateNode = mexNode?.content ? null : getBinaryNodeChild(node, 'update') || getAllBinaryNodeChildren(node)[0];
275
+ const payloadNode = mexNode?.content ? mexNode : updateNode;
276
+ if (!payloadNode?.content) {
277
+ logger.warn({ node: binaryNodeToString(node) }, 'invalid mex newsletter notification');
278
+ return;
279
+ }
280
+ let data;
281
+ try {
282
+ const payloadContent = payloadNode.content;
283
+ if (Array.isArray(payloadContent)) {
284
+ logger.warn({ payloadNode }, 'invalid mex newsletter notification payload format');
285
+ return;
286
+ }
287
+ const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent);
288
+ data = JSON.parse(contentBuf.toString());
289
+ }
290
+ catch (error) {
291
+ logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification');
292
+ return;
293
+ }
294
+ const operation = data?.operation ?? payloadNode?.attrs?.op_name;
295
+ let updates = data?.updates;
296
+ if (!updates) {
297
+ const linkedProfiles = data?.data?.xwa2_notify_linked_profiles;
298
+ if (linkedProfiles) {
299
+ updates = [linkedProfiles];
300
+ }
301
+ }
302
+ if (!updates || !operation) {
303
+ logger.warn({ data }, 'invalid mex newsletter notification content');
304
+ return;
305
+ }
306
+ logger.info({ operation, updates }, 'got mex newsletter notification');
307
+ switch (operation) {
308
+ case 'NotificationNewsletterUpdate':
309
+ for (const update of updates) {
310
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
311
+ ev.emit('newsletter-settings.update', {
312
+ id: update.jid,
313
+ update: update.settings
314
+ });
315
+ }
316
+ }
317
+ break;
318
+ case 'NotificationNewsletterAdminPromote':
319
+ for (const update of updates) {
320
+ if (update.jid && update.user) {
321
+ ev.emit('newsletter-participants.update', {
322
+ id: update.jid,
323
+ author: node.attrs.from,
324
+ user: update.user,
325
+ new_role: 'ADMIN',
326
+ action: 'promote'
327
+ });
328
+ }
329
+ }
330
+ break;
331
+ case 'NotificationLinkedProfilesUpdates':
332
+ for (const update of updates) {
333
+ const lid = update?.jid;
334
+ const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : [];
335
+ const mappings = [];
336
+ for (const profile of addedProfiles) {
337
+ const pn = typeof profile === 'string' ? profile : (profile?.pn ?? profile?.jid ?? null);
338
+ if (lid && pn) {
339
+ const mapping = { lid, pn };
340
+ ev.emit('lid-mapping.update', mapping);
341
+ mappings.push(mapping);
342
+ }
343
+ }
344
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
345
+ }
346
+ break;
347
+ default:
348
+ logger.info({ operation, data }, 'unhandled mex newsletter notification');
349
+ break;
350
+ }
351
+ };
352
+ // Handles newsletter notifications
353
+ const handleNewsletterNotification = async (node) => {
354
+ const from = node.attrs.from;
355
+ const children = getAllBinaryNodeChildren(node);
356
+ const author = node.attrs.participant;
357
+ for (const child of children) {
358
+ logger.debug({ from, child }, 'got newsletter notification');
359
+ switch (child.tag) {
360
+ case 'reaction': {
361
+ const reactionUpdate = {
362
+ id: from,
363
+ server_id: child.attrs.message_id,
364
+ reaction: {
365
+ code: getBinaryNodeChildString(child, 'reaction'),
366
+ count: 1
367
+ }
368
+ };
369
+ ev.emit('newsletter.reaction', reactionUpdate);
370
+ break;
371
+ }
372
+ case 'view': {
373
+ const viewUpdate = {
374
+ id: from,
375
+ server_id: child.attrs.message_id,
376
+ count: parseInt(child.content?.toString() || '0', 10)
377
+ };
378
+ ev.emit('newsletter.view', viewUpdate);
379
+ break;
380
+ }
381
+ case 'participant': {
382
+ const participantUpdate = {
383
+ id: from,
384
+ author,
385
+ user: child.attrs.jid,
386
+ action: child.attrs.action,
387
+ new_role: child.attrs.role
388
+ };
389
+ ev.emit('newsletter-participants.update', participantUpdate);
390
+ break;
391
+ }
392
+ case 'update': {
393
+ const settingsNode = getBinaryNodeChild(child, 'settings');
394
+ if (settingsNode) {
395
+ const update = {};
396
+ const nameNode = getBinaryNodeChild(settingsNode, 'name');
397
+ if (nameNode?.content)
398
+ update.name = nameNode.content.toString();
399
+ const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
400
+ if (descriptionNode?.content)
401
+ update.description = descriptionNode.content.toString();
402
+ ev.emit('newsletter-settings.update', {
403
+ id: from,
404
+ update
405
+ });
406
+ }
407
+ break;
408
+ }
409
+ case 'live_updates': {
410
+ emitNewsletterLiveUpdate(ev, node);
411
+ break;
412
+ }
413
+ case 'message': {
414
+ const plaintextNode = getBinaryNodeChild(child, 'plaintext');
415
+ if (plaintextNode?.content) {
416
+ try {
417
+ const contentBuf = typeof plaintextNode.content === 'string'
418
+ ? Buffer.from(plaintextNode.content, 'binary')
419
+ : Buffer.from(plaintextNode.content);
420
+ const messageProto = proto.Message.decode(contentBuf).toJSON();
421
+ const fullMessage = proto.WebMessageInfo.fromObject({
422
+ key: {
423
+ remoteJid: from,
424
+ id: child.attrs.message_id || child.attrs.server_id,
425
+ fromMe: false // TODO: is this really true though
426
+ },
427
+ message: messageProto,
428
+ messageTimestamp: +child.attrs.t
429
+ }).toJSON();
430
+ await upsertMessage(fullMessage, 'append');
431
+ logger.debug('Processed plaintext newsletter message');
432
+ }
433
+ catch (error) {
434
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
435
+ }
436
+ }
437
+ break;
438
+ }
439
+ default:
440
+ logger.warn({ node, child }, 'Unknown newsletter notification child');
441
+ break;
442
+ }
443
+ }
444
+ };
445
+ const sendMessageAck = async (node, errorCode) => {
446
+ const stanza = buildAckStanza(node, errorCode, authState.creds.me.id);
447
+ logger.debug({ recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs }, 'sent ack');
448
+ await sendNode(stanza);
449
+ };
450
+ const rejectCall = async (callId, callFrom) => {
451
+ const stanza = {
452
+ tag: 'call',
453
+ attrs: {
454
+ from: authState.creds.me.id,
455
+ to: callFrom
456
+ },
457
+ content: [
458
+ {
459
+ tag: 'reject',
460
+ attrs: {
461
+ 'call-id': callId,
462
+ 'call-creator': callFrom,
463
+ count: '0'
464
+ },
465
+ content: undefined
466
+ }
467
+ ]
468
+ };
469
+ await query(stanza);
470
+ };
471
+ const acceptCall = async (callId, callFrom) => {
472
+ const stanza = {
473
+ tag: 'call',
474
+ attrs: {
475
+ from: authState.creds.me.id,
476
+ to: callFrom
477
+ },
478
+ content: [
479
+ {
480
+ tag: 'accept',
481
+ attrs: {
482
+ 'call-id': callId,
483
+ 'call-creator': callFrom,
484
+ count: '0'
485
+ },
486
+ content: undefined
487
+ }
488
+ ]
489
+ };
490
+ await query(stanza);
491
+ };
492
+ const terminateCall = async (callId, callFrom) => {
493
+ const stanza = {
494
+ tag: 'call',
495
+ attrs: {
496
+ from: authState.creds.me.id,
497
+ to: callFrom
498
+ },
499
+ content: [
500
+ {
501
+ tag: 'terminate',
502
+ attrs: {
503
+ 'call-id': callId,
504
+ 'call-creator': callFrom,
505
+ reason: 'user-terminated',
506
+ count: '0'
507
+ },
508
+ content: undefined
509
+ }
510
+ ]
511
+ };
512
+ await query(stanza);
513
+ };
514
+ const offerCall = async (toJid, isVideo = false) => {
515
+ const callId = randomBytes(16).toString('hex').toUpperCase().substring(0, 64);
516
+ const offerContent = [];
517
+ offerContent.push({
518
+ tag: 'audio',
519
+ attrs: { enc: 'opus', rate: '16000' },
520
+ content: undefined
521
+ });
522
+ offerContent.push({
523
+ tag: 'audio',
524
+ attrs: { enc: 'opus', rate: '8000' },
525
+ content: undefined
526
+ });
527
+ if (isVideo) {
528
+ offerContent.push({
529
+ tag: 'video',
530
+ attrs: {
531
+ enc: 'vp8',
532
+ dec: 'vp8',
533
+ orientation: '0',
534
+ screen_width: '1920',
535
+ screen_height: '1080',
536
+ device_orientation: '0'
537
+ },
538
+ content: undefined
539
+ });
540
+ }
541
+ offerContent.push({
542
+ tag: 'net',
543
+ attrs: { medium: '3' },
544
+ content: undefined
545
+ });
546
+ offerContent.push({
547
+ tag: 'capability',
548
+ attrs: { ver: '1' },
549
+ content: new Uint8Array([1, 4, 255, 131, 207, 4])
550
+ });
551
+ offerContent.push({
552
+ tag: 'encopt',
553
+ attrs: { keygen: '2' },
554
+ content: undefined
555
+ });
556
+ const encKey = randomBytes(32);
557
+ const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => jidEncode(user, 's.whatsapp.net', device));
558
+ await assertSessions(devices, true);
559
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
560
+ call: {
561
+ callKey: new Uint8Array(encKey)
562
+ }
563
+ }, { count: '0' });
564
+ offerContent.push({ tag: 'destination', attrs: {}, content: destinations });
565
+ if (shouldIncludeDeviceIdentity) {
566
+ offerContent.push({
567
+ tag: 'device-identity',
568
+ attrs: {},
569
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
570
+ });
571
+ }
572
+ const stanza = {
573
+ tag: 'call',
574
+ attrs: {
575
+ id: generateMessageID(),
576
+ to: toJid
577
+ },
578
+ content: [
579
+ {
580
+ tag: 'offer',
581
+ attrs: {
582
+ 'call-id': callId,
583
+ 'call-creator': authState.creds.me.id
584
+ },
585
+ content: offerContent
586
+ }
587
+ ]
588
+ };
589
+ await query(stanza);
590
+ return {
591
+ id: callId,
592
+ to: toJid
593
+ };
594
+ };
595
+ /**
596
+ * Start a group call. Mirrors the proven 1:1 `offerCall` stanza (encrypted
597
+ * callKey envelope per destination) but addressed to the group with the
598
+ * `type="group"` + `group-jid` offer attributes that the receive pipeline
599
+ * recognizes for group calls.
600
+ * @param jid the group JID (e.g. 120363012345678901@g.us)
601
+ * @param participants participant JIDs to ring
602
+ * @param isVideo whether to offer a video call
603
+ */
604
+ const groupCall = async (jid, participants = [], isVideo = false) => {
605
+ const callId = randomBytes(16).toString('hex').toUpperCase().substring(0, 64);
606
+ const offerContent = [];
607
+ offerContent.push({
608
+ tag: 'audio',
609
+ attrs: { enc: 'opus', rate: '16000' },
610
+ content: undefined
611
+ });
612
+ offerContent.push({
613
+ tag: 'audio',
614
+ attrs: { enc: 'opus', rate: '8000' },
615
+ content: undefined
616
+ });
617
+ if (isVideo) {
618
+ offerContent.push({
619
+ tag: 'video',
620
+ attrs: {
621
+ enc: 'vp8',
622
+ dec: 'vp8',
623
+ orientation: '0',
624
+ screen_width: '1920',
625
+ screen_height: '1080',
626
+ device_orientation: '0'
627
+ },
628
+ content: undefined
629
+ });
630
+ }
631
+ offerContent.push({
632
+ tag: 'net',
633
+ attrs: { medium: '3' },
634
+ content: undefined
635
+ });
636
+ offerContent.push({
637
+ tag: 'capability',
638
+ attrs: { ver: '1' },
639
+ content: new Uint8Array([1, 4, 255, 131, 207, 4])
640
+ });
641
+ offerContent.push({
642
+ tag: 'encopt',
643
+ attrs: { keygen: '2' },
644
+ content: undefined
645
+ });
646
+ const encKey = randomBytes(32);
647
+ const devices = (await getUSyncDevices(participants, true, false)).map(({ user, device }) => jidEncode(user, 's.whatsapp.net', device));
648
+ await assertSessions(devices, true);
649
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
650
+ call: {
651
+ callKey: new Uint8Array(encKey)
652
+ }
653
+ }, { count: '0' });
654
+ offerContent.push({ tag: 'destination', attrs: {}, content: destinations });
655
+ if (shouldIncludeDeviceIdentity) {
656
+ offerContent.push({
657
+ tag: 'device-identity',
658
+ attrs: {},
659
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
660
+ });
661
+ }
662
+ const stanza = buildGroupCallStanza({
663
+ id: generateMessageID(),
664
+ to: jid,
665
+ callId,
666
+ callCreator: authState.creds.me.id,
667
+ offerContent
668
+ });
669
+ await query(stanza);
670
+ return {
671
+ id: callId,
672
+ to: jid
673
+ };
674
+ };
675
+ /**
676
+ * Cancel / terminate a group call started with `groupCall`.
677
+ * Mirrors the proven 1:1 `terminateCall` stanza addressed to the group.
678
+ * @param jid the group JID the call was started in
679
+ * @param callId the call id returned by `groupCall`
680
+ */
681
+ const cancelGroupCall = async (jid, callId) => {
682
+ const stanza = buildGroupCallCancelStanza({
683
+ to: jid,
684
+ callId,
685
+ callCreator: authState.creds.me.id
686
+ });
687
+ await query(stanza);
688
+ return {
689
+ id: callId,
690
+ to: jid
691
+ };
692
+ };
693
+ // Expose the group-call methods on the socket surface. Attached to the inner
694
+ // `sock` so they ride the `...sock` spread of this layer's return object
695
+ // (the return block lives beyond the edit window of the receive pipeline).
696
+ sock.groupCall = groupCall;
697
+ sock.cancelGroupCall = cancelGroupCall;
698
+ // Handles incoming <status> stanzas pushed by the server for newsletter posts.
699
+ // These arrive on the CB:status channel (AB-gated by status_e2ee_recv_over_status_stanza).
700
+ const handleNewsletterStatus = async (node) => {
701
+ const { id, from, server_id, t, is_sender, offline, type, edit } = node.attrs;
702
+ const serverId = server_id ? +server_id : undefined;
703
+ const timestamp = t ? +t : undefined;
704
+ const isSender = is_sender === 'true';
705
+ const offlineIndex = offline !== undefined ? +offline : undefined;
706
+ // Cache messageId → serverId so the bot can look up server_id when a message is quoted
707
+ if (id && serverId != null) {
708
+ newsletterServerIdCache?.set(id, serverId);
709
+ }
710
+ // Parse optional <meta> child: edit timestamps, interaction type, admin profile
711
+ const metaNode = getBinaryNodeChild(node, 'meta');
712
+ const meta = metaNode
713
+ ? {
714
+ ...(metaNode.attrs.msg_edit_t ? { editedAt: +metaNode.attrs.msg_edit_t } : {}),
715
+ ...(metaNode.attrs.original_msg_t ? { originalTimestamp: +metaNode.attrs.original_msg_t } : {}),
716
+ ...(metaNode.attrs.interaction_type ? { interactionType: metaNode.attrs.interaction_type } : {}),
717
+ ...(metaNode.attrs.parent_server_id ? { parentServerId: +metaNode.attrs.parent_server_id } : {}),
718
+ ...(metaNode.attrs.response_server_id ? { responseServerId: +metaNode.attrs.response_server_id } : {})
719
+ }
720
+ : undefined;
721
+ // Parse engagement counters
722
+ const viewsNode = getBinaryNodeChild(node, 'views_count');
723
+ const viewsCount = viewsNode?.attrs?.count !== undefined ? +viewsNode.attrs.count : undefined;
724
+ const responsesNode = getBinaryNodeChild(node, 'responses_count');
725
+ const responsesCount = responsesNode?.attrs?.count !== undefined ? +responsesNode.attrs.count : undefined;
726
+ const reactionsNode = getBinaryNodeChild(node, 'reactions');
727
+ const reactionCounts = getBinaryNodeChildren(reactionsNode ?? { content: [] }, 'reaction').map(r => ({
728
+ code: r.attrs.code,
729
+ count: +r.attrs.count
730
+ }));
731
+ let content = null;
732
+ let mediaType = undefined;
733
+ if (type === 'reaction') {
734
+ const reactionNode = getBinaryNodeChild(node, 'reaction');
735
+ content = { type: 'reaction', code: reactionNode?.attrs?.code };
736
+ }
737
+ else if (type === 'text' || type === 'media') {
738
+ const plaintextNode = getBinaryNodeChild(node, 'plaintext');
739
+ if (type === 'media')
740
+ mediaType = plaintextNode?.attrs?.mediatype;
741
+ if (edit === '7' || edit === '8') {
742
+ content = { type: 'revoke', edit };
743
+ }
744
+ else if (plaintextNode?.content) {
745
+ try {
746
+ const buf = Buffer.isBuffer(plaintextNode.content)
747
+ ? plaintextNode.content
748
+ : Buffer.from(plaintextNode.content);
749
+ const message = proto.Message.decode(buf).toJSON();
750
+ content = { type, message, ...(mediaType ? { mediaType } : {}) };
751
+ }
752
+ catch (err) {
753
+ logger.error({ err }, 'Failed to decode newsletter status plaintext');
754
+ content = { type, raw: true, ...(mediaType ? { mediaType } : {}) };
755
+ }
756
+ }
757
+ }
758
+ // Send ACK back to server
759
+ const ackType = type === 'reaction' ? 'reaction' : edit ? 'revoke' : type;
760
+ await sendNode({
761
+ tag: 'ack',
762
+ attrs: { id, to: from, class: 'status', type: ackType || 'text' },
763
+ content: undefined
764
+ });
765
+ ev.emit('newsletter.status', {
766
+ id: from,
767
+ messageId: id,
768
+ serverId,
769
+ timestamp,
770
+ isSender,
771
+ ...(offlineIndex !== undefined ? { offlineIndex } : {}),
772
+ ...(meta ? { meta } : {}),
773
+ ...(viewsCount !== undefined ? { viewsCount } : {}),
774
+ ...(responsesCount !== undefined ? { responsesCount } : {}),
775
+ ...(reactionCounts.length ? { reactionCounts } : {}),
776
+ content
777
+ });
778
+ };
779
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
780
+ const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
781
+ const { key: msgKey } = fullMessage;
782
+ const msgId = msgKey.id;
783
+ if (messageRetryManager) {
784
+ // Check if we've exceeded max retries using the new system
785
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
786
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
787
+ messageRetryManager.markRetryFailed(msgId);
788
+ return;
789
+ }
790
+ // Increment retry count using new system
791
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
792
+ // Use the new retry count for the rest of the logic
793
+ const key = `${msgId}:${msgKey?.participant}`;
794
+ await msgRetryCache.set(key, retryCount);
795
+ }
796
+ else {
797
+ // Fallback to old system
798
+ const key = `${msgId}:${msgKey?.participant}`;
799
+ let retryCount = (await msgRetryCache.get(key)) || 0;
800
+ if (retryCount >= maxMsgRetryCount) {
801
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
802
+ await msgRetryCache.del(key);
803
+ return;
804
+ }
805
+ retryCount += 1;
806
+ await msgRetryCache.set(key, retryCount);
807
+ }
808
+ const key = `${msgId}:${msgKey?.participant}`;
809
+ const retryCount = (await msgRetryCache.get(key)) || 1;
810
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
811
+ const fromJid = node.attrs.from;
812
+ // Check if we should recreate the session
813
+ let shouldRecreateSession = false;
814
+ let recreateReason = '';
815
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
816
+ try {
817
+ // Check if we have a session with this JID
818
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
819
+ const hasSession = await signalRepository.validateSession(fromJid);
820
+ const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
821
+ shouldRecreateSession = result.recreate;
822
+ recreateReason = result.reason;
823
+ if (shouldRecreateSession) {
824
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
825
+ // Delete existing session to force recreation
826
+ await authState.keys.set({ session: { [sessionId]: null } });
827
+ forceIncludeKeys = true;
828
+ }
829
+ }
830
+ catch (error) {
831
+ logger.warn({ error, fromJid }, 'failed to check session recreation');
832
+ }
833
+ }
834
+ if (retryCount <= 2) {
835
+ // Use new retry manager for phone requests if available
836
+ if (messageRetryManager) {
837
+ // Schedule phone request with delay (like whatsmeow)
838
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
839
+ try {
840
+ const requestId = await requestPlaceholderResend(msgKey);
841
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
842
+ }
843
+ catch (error) {
844
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request');
845
+ }
846
+ });
847
+ }
848
+ else {
849
+ // Fallback to immediate request
850
+ const msgId = await requestPlaceholderResend(msgKey);
851
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
852
+ }
853
+ }
854
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true);
855
+ await authState.keys.transaction(async () => {
856
+ const receipt = {
857
+ tag: 'receipt',
858
+ attrs: {
859
+ id: msgId,
860
+ type: 'retry',
861
+ to: node.attrs.from
862
+ },
863
+ content: [
864
+ {
865
+ tag: 'retry',
866
+ attrs: {
867
+ count: retryCount.toString(),
868
+ id: node.attrs.id,
869
+ t: node.attrs.t,
870
+ v: '1',
871
+ // ADD ERROR FIELD
872
+ error: '0'
873
+ }
874
+ },
875
+ {
876
+ tag: 'registration',
877
+ attrs: {},
878
+ content: encodeBigEndian(authState.creds.registrationId)
879
+ }
880
+ ]
881
+ };
882
+ if (node.attrs.recipient) {
883
+ receipt.attrs.recipient = node.attrs.recipient;
884
+ }
885
+ if (node.attrs.participant) {
886
+ receipt.attrs.participant = node.attrs.participant;
887
+ }
888
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
889
+ const { update, preKeys } = await getNextPreKeys(authState, 1);
890
+ const [keyId] = Object.keys(preKeys);
891
+ const key = preKeys[+keyId];
892
+ const content = receipt.content;
893
+ content.push({
894
+ tag: 'keys',
895
+ attrs: {},
896
+ content: [
897
+ { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
898
+ { tag: 'identity', attrs: {}, content: identityKey.public },
899
+ xmppPreKey(key, +keyId),
900
+ xmppSignedPreKey(signedPreKey),
901
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
902
+ ]
903
+ });
904
+ ev.emit('creds.update', update);
905
+ }
906
+ await sendNode(receipt);
907
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
908
+ }, authState?.creds?.me?.id || 'sendRetryRequest');
909
+ };
910
+ // Mirrors WAWeb/Handle/PreKeyLow.js: skip a re-issued notification with the same stanza id.
911
+ const inFlightPreKeyLow = new Set();
912
+ /**
913
+ * Fire-and-forget tctoken re-issuance after a peer's device identity changed.
914
+ * Mirrors WAWebSendTcTokenWhenDeviceIdentityChange — runs in parallel with
915
+ * the session refresh (not after it).
916
+ */
917
+ const reissueTcTokenAfterIdentityChange = (from) => {
918
+ void (async () => {
919
+ const normalizedJid = jidNormalizedUser(from);
920
+ const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN);
921
+ const tcTokenData = await authState.keys.get('tctoken', [tcJid]);
922
+ const senderTs = tcTokenData?.[tcJid]?.senderTimestamp;
923
+ if (senderTs === null || senderTs === undefined || isTcTokenExpired(senderTs)) {
924
+ return;
925
+ }
926
+ logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken');
927
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
928
+ const issueJid = await resolveIssuanceJid(normalizedJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
929
+ const result = await issuePrivacyTokens([issueJid], senderTs);
930
+ await storeTcTokensFromIqResult({
931
+ result,
932
+ fallbackJid: tcJid,
933
+ keys: authState.keys,
934
+ getLIDForPN,
935
+ onNewJidStored: trackTcTokenJid
936
+ });
937
+ })().catch(err => {
938
+ logger.debug({ jid: from, err: err?.message }, 'failed to re-issue tctoken after identity change');
939
+ });
940
+ };
941
+ const handleEncryptNotification = async (node) => {
942
+ const from = node.attrs.from;
943
+ if (from === S_WHATSAPP_NET) {
944
+ const stanzaId = node.attrs.id;
945
+ if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
946
+ return;
947
+ }
948
+ const countChild = getBinaryNodeChild(node, 'count');
949
+ const count = +countChild.attrs.value;
950
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
951
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
952
+ if (shouldUploadMorePreKeys) {
953
+ if (stanzaId)
954
+ inFlightPreKeyLow.add(stanzaId);
955
+ try {
956
+ await uploadPreKeys();
957
+ }
958
+ finally {
959
+ if (stanzaId)
960
+ inFlightPreKeyLow.delete(stanzaId);
961
+ }
962
+ }
963
+ }
964
+ else {
965
+ const result = await handleIdentityChange(node, {
966
+ meId: authState.creds.me?.id,
967
+ meLid: authState.creds.me?.lid,
968
+ validateSession: signalRepository.validateSession,
969
+ assertSessions,
970
+ debounceCache: identityAssertDebounce,
971
+ logger,
972
+ onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
973
+ });
974
+ if (result.action === 'no_identity_node') {
975
+ logger.info({ node }, 'unknown encrypt notification');
976
+ }
977
+ }
978
+ };
979
+ const handleGroupNotification = (fullNode, child, msg) => {
980
+ // TODO: Support PN/LID (Here is only LID now)
981
+ const actingParticipantLid = fullNode.attrs.participant;
982
+ const actingParticipantPn = fullNode.attrs.participant_pn;
983
+ const actingParticipantUsername = fullNode.attrs.participant_username;
984
+ const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
985
+ const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
986
+ switch (child?.tag) {
987
+ case 'create':
988
+ const metadata = extractGroupMetadata(child);
989
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE;
990
+ msg.messageStubParameters = [metadata.subject];
991
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
992
+ ev.emit('chats.upsert', [
993
+ {
994
+ id: metadata.id,
995
+ name: metadata.subject,
996
+ conversationTimestamp: metadata.creation
997
+ }
998
+ ]);
999
+ ev.emit('groups.upsert', [
1000
+ {
1001
+ ...metadata,
1002
+ author: actingParticipantLid,
1003
+ authorPn: actingParticipantPn,
1004
+ authorUsername: actingParticipantUsername
1005
+ }
1006
+ ]);
1007
+ break;
1008
+ case 'ephemeral':
1009
+ case 'not_ephemeral':
1010
+ msg.message = {
1011
+ protocolMessage: {
1012
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
1013
+ ephemeralExpiration: +(child.attrs.expiration || 0)
1014
+ }
1015
+ };
1016
+ break;
1017
+ case 'modify':
1018
+ const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
1019
+ msg.messageStubParameters = oldNumber || [];
1020
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
1021
+ break;
1022
+ case 'promote':
1023
+ case 'demote':
1024
+ case 'remove':
1025
+ case 'add':
1026
+ case 'leave':
1027
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
1028
+ msg.messageStubType = WAMessageStubType[stubType];
1029
+ const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
1030
+ // TODO: Store LID MAPPINGS
1031
+ return {
1032
+ id: attrs.jid,
1033
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
1034
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
1035
+ username: attrs.participant_username || attrs.username || undefined,
1036
+ admin: (attrs.type || null)
1037
+ };
1038
+ });
1039
+ if (participants.length === 1 &&
1040
+ // if recv. "remove" message and sender removed themselves
1041
+ // mark as left
1042
+ (areJidsSameUser(participants[0].id, actingParticipantLid) ||
1043
+ areJidsSameUser(participants[0].id, actingParticipantPn)) &&
1044
+ child.tag === 'remove') {
1045
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
1046
+ }
1047
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a));
1048
+ break;
1049
+ case 'subject':
1050
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
1051
+ msg.messageStubParameters = [child.attrs.subject];
1052
+ break;
1053
+ case 'description':
1054
+ const description = getBinaryNodeChild(child, 'body')?.content?.toString();
1055
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
1056
+ msg.messageStubParameters = description ? [description] : undefined;
1057
+ break;
1058
+ case 'announcement':
1059
+ case 'not_announcement':
1060
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
1061
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
1062
+ break;
1063
+ case 'locked':
1064
+ case 'unlocked':
1065
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
1066
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
1067
+ break;
1068
+ case 'invite':
1069
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
1070
+ msg.messageStubParameters = [child.attrs.code];
1071
+ break;
1072
+ case 'member_add_mode':
1073
+ const addMode = child.content;
1074
+ if (addMode) {
1075
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
1076
+ msg.messageStubParameters = [addMode.toString()];
1077
+ }
1078
+ break;
1079
+ case 'membership_approval_mode':
1080
+ const approvalMode = getBinaryNodeChild(child, 'group_join');
1081
+ if (approvalMode) {
1082
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
1083
+ msg.messageStubParameters = [approvalMode.attrs.state];
1084
+ }
1085
+ break;
1086
+ case 'created_membership_requests':
1087
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
1088
+ msg.messageStubParameters = [
1089
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
1090
+ 'created',
1091
+ child.attrs.request_method
1092
+ ];
1093
+ break;
1094
+ case 'revoked_membership_requests':
1095
+ const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
1096
+ // TODO: LIDMAPPING SUPPORT
1097
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
1098
+ msg.messageStubParameters = [
1099
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
1100
+ isDenied ? 'revoked' : 'rejected'
1101
+ ];
1102
+ break;
1103
+ }
1104
+ };
1105
+ const handleDevicesNotification = async (node) => {
1106
+ const [child] = getAllBinaryNodeChildren(node);
1107
+ const from = jidNormalizedUser(node.attrs.from);
1108
+ if (!child) {
1109
+ logger.debug({ from }, 'devices notification missing child, skipping');
1110
+ return;
1111
+ }
1112
+ const tag = child.tag;
1113
+ const deviceHash = child.attrs.device_hash;
1114
+ const devices = getBinaryNodeChildren(child, 'device');
1115
+ if (areJidsSameUser(from, authState.creds.me.id) || areJidsSameUser(from, authState.creds.me.lid)) {
1116
+ const deviceJids = devices.map(d => d.attrs.jid);
1117
+ logger.info({ deviceJids }, 'got my own devices');
1118
+ }
1119
+ if (!devices.length) {
1120
+ logger.debug({ from, tag }, 'no devices in notification, skipping');
1121
+ return;
1122
+ }
1123
+ const decoded = [];
1124
+ for (const d of devices) {
1125
+ const jid = d.attrs.jid;
1126
+ if (!jid)
1127
+ continue;
1128
+ const parts = jidDecode(jid);
1129
+ if (!parts) {
1130
+ logger.debug({ jid }, 'failed to decode device jid, skipping');
1131
+ continue;
1132
+ }
1133
+ decoded.push({ jid, user: parts.user, server: parts.server, device: parts.device });
1134
+ }
1135
+ if (!decoded.length)
1136
+ return;
1137
+ await devicesMutex.mutex(async () => {
1138
+ const byUser = new Map();
1139
+ for (const d of decoded) {
1140
+ const list = byUser.get(d.user) || [];
1141
+ list.push(d);
1142
+ byUser.set(d.user, list);
1143
+ }
1144
+ for (const [user, entries] of byUser) {
1145
+ if (tag === 'update') {
1146
+ logger.debug({ user }, `${user}'s device list updated, dropping cached devices`);
1147
+ await userDevicesCache?.del(user);
1148
+ continue;
1149
+ }
1150
+ if (tag === 'remove') {
1151
+ await signalRepository.deleteSession(entries.map(e => e.jid));
1152
+ }
1153
+ const existingCache = (await userDevicesCache?.get(user)) || [];
1154
+ if (!existingCache.length) {
1155
+ // No baseline yet; skip applying the delta so getUSyncDevices can
1156
+ // later fetch the full device list. Caching just the notification
1157
+ // entries would make a partial list look authoritative.
1158
+ logger.debug({ user, tag }, 'device list not cached, deferring to USync refresh');
1159
+ continue;
1160
+ }
1161
+ const affected = new Set(entries.map(e => e.device));
1162
+ let updatedDevices;
1163
+ switch (tag) {
1164
+ case 'add':
1165
+ logger.info({ deviceHash, count: entries.length }, 'devices added');
1166
+ updatedDevices = [
1167
+ ...existingCache.filter(d => !affected.has(d.device)),
1168
+ ...entries.map(e => ({ user: e.user, server: e.server, device: e.device }))
1169
+ ];
1170
+ break;
1171
+ case 'remove':
1172
+ logger.info({ deviceHash, count: entries.length }, 'devices removed');
1173
+ updatedDevices = existingCache.filter(d => !affected.has(d.device));
1174
+ break;
1175
+ default:
1176
+ logger.debug({ tag }, 'Unknown device list change tag');
1177
+ continue;
1178
+ }
1179
+ if (updatedDevices.length === 0) {
1180
+ await userDevicesCache?.del(user);
1181
+ }
1182
+ else {
1183
+ await userDevicesCache?.set(user, updatedDevices);
1184
+ }
1185
+ }
1186
+ });
1187
+ };
1188
+ const processNotification = async (node) => {
1189
+ const result = {};
1190
+ const [child] = getAllBinaryNodeChildren(node);
1191
+ const nodeType = node.attrs.type;
1192
+ const from = jidNormalizedUser(node.attrs.from);
1193
+ switch (nodeType) {
1194
+ case 'newsletter':
1195
+ await handleNewsletterNotification(node);
1196
+ break;
1197
+ case 'mex':
1198
+ await handleMexNotification(node);
1199
+ break;
1200
+ case 'w:gp2':
1201
+ // TODO: HANDLE PARTICIPANT_PN
1202
+ handleGroupNotification(node, child, result);
1203
+ break;
1204
+ case 'mediaretry':
1205
+ const event = decodeMediaRetryNode(node);
1206
+ ev.emit('messages.media-update', [event]);
1207
+ break;
1208
+ case 'encrypt':
1209
+ await handleEncryptNotification(node);
1210
+ break;
1211
+ case 'devices':
1212
+ try {
1213
+ await handleDevicesNotification(node);
1214
+ }
1215
+ catch (error) {
1216
+ logger.error({ error, node }, 'failed to handle devices notification');
1217
+ }
1218
+ break;
1219
+ case 'server_sync':
1220
+ const update = getBinaryNodeChild(node, 'collection');
1221
+ if (update) {
1222
+ const name = update.attrs.name;
1223
+ await resyncAppState([name], false);
1224
+ }
1225
+ break;
1226
+ case 'picture':
1227
+ const setPicture = getBinaryNodeChild(node, 'set');
1228
+ const delPicture = getBinaryNodeChild(node, 'delete');
1229
+ // TODO: WAJIDHASH stuff proper support inhouse
1230
+ ev.emit('contacts.update', [
1231
+ {
1232
+ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
1233
+ imgUrl: setPicture ? 'changed' : 'removed'
1234
+ }
1235
+ ]);
1236
+ if (isJidGroup(from)) {
1237
+ const node = setPicture || delPicture;
1238
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
1239
+ if (setPicture) {
1240
+ result.messageStubParameters = [setPicture.attrs.id];
1241
+ }
1242
+ result.participant = node?.attrs.author;
1243
+ result.key = {
1244
+ ...(result.key || {}),
1245
+ participant: setPicture?.attrs.author
1246
+ };
1247
+ }
1248
+ break;
1249
+ case 'account_sync':
1250
+ if (child.tag === 'disappearing_mode') {
1251
+ const newDuration = +child.attrs.duration;
1252
+ const timestamp = +child.attrs.t;
1253
+ logger.info({ newDuration }, 'updated account disappearing mode');
1254
+ ev.emit('creds.update', {
1255
+ accountSettings: {
1256
+ ...authState.creds.accountSettings,
1257
+ defaultDisappearingMode: {
1258
+ ephemeralExpiration: newDuration,
1259
+ ephemeralSettingTimestamp: timestamp
1260
+ }
1261
+ }
1262
+ });
1263
+ }
1264
+ else if (child.tag === 'blocklist') {
1265
+ const blocklists = getBinaryNodeChildren(child, 'item');
1266
+ for (const { attrs } of blocklists) {
1267
+ const blocklist = [attrs.jid];
1268
+ const type = attrs.action === 'block' ? 'add' : 'remove';
1269
+ ev.emit('blocklist.update', { blocklist, type });
1270
+ }
1271
+ }
1272
+ break;
1273
+ case 'link_code_companion_reg':
1274
+ const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
1275
+ const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
1276
+ const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
1277
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
1278
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
1279
+ const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
1280
+ const random = randomBytes(32);
1281
+ const linkCodeSalt = randomBytes(32);
1282
+ const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
1283
+ salt: linkCodeSalt,
1284
+ info: 'link_code_pairing_key_bundle_encryption_key'
1285
+ });
1286
+ const encryptPayload = Buffer.concat([
1287
+ Buffer.from(authState.creds.signedIdentityKey.public),
1288
+ primaryIdentityPublicKey,
1289
+ random
1290
+ ]);
1291
+ const encryptIv = randomBytes(12);
1292
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
1293
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
1294
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
1295
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
1296
+ authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
1297
+ await query({
1298
+ tag: 'iq',
1299
+ attrs: {
1300
+ to: S_WHATSAPP_NET,
1301
+ type: 'set',
1302
+ id: sock.generateMessageTag(),
1303
+ xmlns: 'md'
1304
+ },
1305
+ content: [
1306
+ {
1307
+ tag: 'link_code_companion_reg',
1308
+ attrs: {
1309
+ jid: authState.creds.me.id,
1310
+ stage: 'companion_finish'
1311
+ },
1312
+ content: [
1313
+ {
1314
+ tag: 'link_code_pairing_wrapped_key_bundle',
1315
+ attrs: {},
1316
+ content: encryptedPayload
1317
+ },
1318
+ {
1319
+ tag: 'companion_identity_public',
1320
+ attrs: {},
1321
+ content: authState.creds.signedIdentityKey.public
1322
+ },
1323
+ {
1324
+ tag: 'link_code_pairing_ref',
1325
+ attrs: {},
1326
+ content: ref
1327
+ }
1328
+ ]
1329
+ }
1330
+ ]
1331
+ });
1332
+ authState.creds.registered = true;
1333
+ ev.emit('creds.update', authState.creds);
1334
+ break;
1335
+ case 'privacy_token':
1336
+ await handlePrivacyTokenNotification(node);
1337
+ break;
1338
+ }
1339
+ if (Object.keys(result).length) {
1340
+ return result;
1341
+ }
1342
+ };
1343
+ /**
1344
+ * In-memory cache of storage JIDs with stored tctokens, seeded from the persisted index.
1345
+ * Used to coalesce writes during a session; pruning always re-reads the persisted index
1346
+ * to cover writes made by other layers (e.g. history sync).
1347
+ */
1348
+ const tcTokenKnownJids = new Set();
1349
+ const tcTokenIndexLoaded = (async () => {
1350
+ try {
1351
+ const jids = await readTcTokenIndex(authState.keys);
1352
+ for (const jid of jids)
1353
+ tcTokenKnownJids.add(jid);
1354
+ logger.debug({ count: tcTokenKnownJids.size }, 'loaded tctoken index');
1355
+ }
1356
+ catch (err) {
1357
+ logger.warn({ err: err?.message }, 'failed to load tctoken index');
1358
+ }
1359
+ })();
1360
+ let tcTokenIndexTimer;
1361
+ async function flushTcTokenIndex() {
1362
+ if (tcTokenIndexTimer) {
1363
+ clearTimeout(tcTokenIndexTimer);
1364
+ tcTokenIndexTimer = undefined;
1365
+ }
1366
+ // Merge with whatever is already persisted so we don't clobber writes from other
1367
+ // paths (history sync, concurrent sessions on the same store).
1368
+ const write = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids);
1369
+ return authState.keys.set({ tctoken: write });
1370
+ }
1371
+ function scheduleTcTokenIndexSave() {
1372
+ if (tcTokenIndexTimer) {
1373
+ clearTimeout(tcTokenIndexTimer);
1374
+ }
1375
+ tcTokenIndexTimer = setTimeout(() => {
1376
+ tcTokenIndexTimer = undefined;
1377
+ flushTcTokenIndex().catch(err => {
1378
+ logger.warn({ err: err?.message }, 'failed to save tctoken index');
1379
+ });
1380
+ }, 5000);
1381
+ }
1382
+ function trackTcTokenJid(jid) {
1383
+ if (jid && jid !== TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
1384
+ tcTokenKnownJids.add(jid);
1385
+ scheduleTcTokenIndexSave();
1386
+ }
1387
+ }
1388
+ const handlePrivacyTokenNotification = async (node) => {
1389
+ const tokensNode = getBinaryNodeChild(node, 'tokens');
1390
+ if (!tokensNode)
1391
+ return;
1392
+ const from = jidNormalizedUser(node.attrs.from);
1393
+ // WA Web uses: senderLid ?? toLid(from) for the storage key
1394
+ // The sender_lid attribute provides the LID directly when available
1395
+ const senderLid = node.attrs.sender_lid && isLidUser(jidNormalizedUser(node.attrs.sender_lid))
1396
+ ? jidNormalizedUser(node.attrs.sender_lid)
1397
+ : undefined;
1398
+ const fallbackJid = senderLid ?? (await resolveTcTokenJid(from, getLIDForPN));
1399
+ logger.debug({ from, storageJid: fallbackJid }, 'processing privacy token notification');
1400
+ await storeTcTokensFromIqResult({
1401
+ result: node,
1402
+ fallbackJid,
1403
+ keys: authState.keys,
1404
+ getLIDForPN,
1405
+ onNewJidStored: trackTcTokenJid
1406
+ });
1407
+ };
1408
+ async function decipherLinkPublicKey(data) {
1409
+ const buffer = toRequiredBuffer(data);
1410
+ const salt = buffer.slice(0, 32);
1411
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
1412
+ const iv = buffer.slice(32, 48);
1413
+ const payload = buffer.slice(48, 80);
1414
+ return aesDecryptCTR(payload, secretKey, iv);
1415
+ }
1416
+ function toRequiredBuffer(data) {
1417
+ if (data === undefined) {
1418
+ throw new Boom('Invalid buffer', { statusCode: 400 });
1419
+ }
1420
+ return data instanceof Buffer ? data : Buffer.from(data);
1421
+ }
1422
+ const willSendMessageAgain = async (id, participant) => {
1423
+ const key = `${id}:${participant}`;
1424
+ const retryCount = (await msgRetryCache.get(key)) || 0;
1425
+ return retryCount < maxMsgRetryCount;
1426
+ };
1427
+ const updateSendMessageAgainCount = async (id, participant) => {
1428
+ const key = `${id}:${participant}`;
1429
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
1430
+ await msgRetryCache.set(key, newValue);
1431
+ };
1432
+ const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
1433
+ const remoteJid = key.remoteJid;
1434
+ const participant = key.participant || remoteJid;
1435
+ const retryCount = +retryNode.attrs.count || 1;
1436
+ const msgId = ids[0];
1437
+ // Try to get messages from cache first, then fallback to getMessage
1438
+ const msgs = [];
1439
+ for (const id of ids) {
1440
+ let msg;
1441
+ // Try to get from retry cache first if enabled
1442
+ if (messageRetryManager) {
1443
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
1444
+ if (cachedMsg) {
1445
+ msg = cachedMsg.message;
1446
+ logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
1447
+ // Mark retry as successful since we found the message
1448
+ messageRetryManager.markRetrySuccess(id);
1449
+ }
1450
+ }
1451
+ // Fallback to getMessage if not found in cache
1452
+ if (!msg && getMessage) {
1453
+ msg = await getMessage({ ...key, id });
1454
+ if (msg) {
1455
+ logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
1456
+ // Also mark as successful if found via getMessage
1457
+ if (messageRetryManager) {
1458
+ messageRetryManager.markRetrySuccess(id);
1459
+ }
1460
+ }
1461
+ }
1462
+ msgs.push(msg);
1463
+ }
1464
+ // if it's the primary jid sending the request
1465
+ // just re-send the message to everyone
1466
+ // prevents the first message decryption failure
1467
+ const sendToAll = !jidDecode(participant)?.device;
1468
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
1469
+ let injectedFromBundle = false;
1470
+ const bundle = extractE2ESessionFromRetryReceipt(receiptNode);
1471
+ if (bundle) {
1472
+ try {
1473
+ await signalRepository.injectE2ESession({ jid: participant, session: bundle });
1474
+ injectedFromBundle = true;
1475
+ logger.debug({ participant, retryCount }, 'injected session from retry receipt key bundle');
1476
+ }
1477
+ catch (error) {
1478
+ logger.warn({ error, participant }, 'failed to inject session from retry receipt');
1479
+ }
1480
+ }
1481
+ if (!injectedFromBundle) {
1482
+ const receivedRegId = getBinaryNodeChildUInt(receiptNode, 'registration', 4);
1483
+ if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
1484
+ const info = await signalRepository.getSessionInfo(participant);
1485
+ if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) {
1486
+ logger.info({ participant, stored: info.registrationId, received: receivedRegId }, 'reg id mismatch on retry without bundle, deleting session');
1487
+ await authState.keys.set({ session: { [sessionId]: null } });
1488
+ }
1489
+ }
1490
+ }
1491
+ const BASE_KEY_CHECK_RETRY = 2;
1492
+ if (msgId && messageRetryManager) {
1493
+ const info = await signalRepository.getSessionInfo(participant);
1494
+ if (info) {
1495
+ if (retryCount === BASE_KEY_CHECK_RETRY) {
1496
+ messageRetryManager.saveBaseKey(sessionId, msgId, info.baseKey);
1497
+ }
1498
+ else if (retryCount > BASE_KEY_CHECK_RETRY) {
1499
+ if (messageRetryManager.hasSameBaseKey(sessionId, msgId, info.baseKey)) {
1500
+ logger.warn({ participant, retryCount }, 'base key collision on retry, forcing fresh session');
1501
+ await authState.keys.set({ session: { [sessionId]: null } });
1502
+ }
1503
+ messageRetryManager.deleteBaseKey(sessionId, msgId);
1504
+ }
1505
+ }
1506
+ }
1507
+ let shouldRecreateSession = false;
1508
+ let recreateReason = '';
1509
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
1510
+ try {
1511
+ const hasSession = await signalRepository.validateSession(participant);
1512
+ const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
1513
+ shouldRecreateSession = result.recreate;
1514
+ recreateReason = result.reason;
1515
+ if (shouldRecreateSession) {
1516
+ logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry');
1517
+ await authState.keys.set({ session: { [sessionId]: null } });
1518
+ }
1519
+ }
1520
+ catch (error) {
1521
+ logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
1522
+ }
1523
+ }
1524
+ if (!injectedFromBundle) {
1525
+ await assertSessions([participant], true);
1526
+ }
1527
+ if (isJidGroup(remoteJid)) {
1528
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
1529
+ }
1530
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
1531
+ for (const [i, msg] of msgs.entries()) {
1532
+ if (!ids[i])
1533
+ continue;
1534
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
1535
+ await updateSendMessageAgainCount(ids[i], participant);
1536
+ const msgRelayOpts = { messageId: ids[i] };
1537
+ if (sendToAll) {
1538
+ msgRelayOpts.useUserDevicesCache = false;
1539
+ }
1540
+ else {
1541
+ msgRelayOpts.participant = {
1542
+ jid: participant,
1543
+ count: +retryNode.attrs.count
1544
+ };
1545
+ }
1546
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
1547
+ }
1548
+ else {
1549
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
1550
+ }
1551
+ }
1552
+ };
1553
+ const handleReceipt = async (node) => {
1554
+ const { attrs, content } = node;
1555
+ const isLid = attrs.from.includes('lid');
1556
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
1557
+ const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
1558
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
1559
+ const key = {
1560
+ remoteJid,
1561
+ id: '',
1562
+ fromMe,
1563
+ participant: attrs.participant
1564
+ };
1565
+ const ids = [attrs.id];
1566
+ if (Array.isArray(content)) {
1567
+ const items = getBinaryNodeChildren(content[0], 'item');
1568
+ ids.push(...items.map(i => i.attrs.id));
1569
+ }
1570
+ try {
1571
+ await Promise.all([
1572
+ receiptMutex.mutex(async () => {
1573
+ const receiptType = attrs.type || 'delivery';
1574
+ if (!isNodeFromMe && !isJidGroup(remoteJid) && !isJidStatusBroadcast(remoteJid) &&
1575
+ ['delivery', 'read', 'played'].includes(receiptType)) {
1576
+ const unknownIds = await findUnknownReceiptIds(ids, messageSecurityStore);
1577
+ if (unknownIds.length) {
1578
+ ev.emit('fake-chat', { jid: remoteJid, ids: unknownIds, type: receiptType });
1579
+ }
1580
+ }
1581
+ const status = getStatusFromReceiptType(attrs.type);
1582
+ if (typeof status !== 'undefined' &&
1583
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
1584
+ // or another device of ours has read some messages
1585
+ (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
1586
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
1587
+ if (attrs.participant) {
1588
+ const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
1589
+ ev.emit('message-receipt.update', ids.map(id => ({
1590
+ key: { ...key, id },
1591
+ receipt: {
1592
+ userJid: jidNormalizedUser(attrs.participant),
1593
+ [updateKey]: +attrs.t
1594
+ }
1595
+ })));
1596
+ }
1597
+ }
1598
+ else {
1599
+ ev.emit('messages.update', ids.map(id => ({
1600
+ key: { ...key, id },
1601
+ update: { status, messageTimestamp: toNumber(+(attrs.t ?? 0)) }
1602
+ })));
1603
+ }
1604
+ }
1605
+ if (attrs.type === 'retry') {
1606
+ // correctly set who is asking for the retry
1607
+ key.participant = key.participant || attrs.from;
1608
+ const retryNode = getBinaryNodeChild(node, 'retry');
1609
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
1610
+ if (key.fromMe) {
1611
+ try {
1612
+ await updateSendMessageAgainCount(ids[0], key.participant);
1613
+ logger.debug({ attrs, key }, 'recv retry request');
1614
+ await sendMessagesAgain(key, ids, retryNode, node);
1615
+ }
1616
+ catch (error) {
1617
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
1618
+ }
1619
+ }
1620
+ else {
1621
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
1622
+ }
1623
+ }
1624
+ else {
1625
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
1626
+ }
1627
+ }
1628
+ })
1629
+ ]);
1630
+ }
1631
+ finally {
1632
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
1633
+ }
1634
+ };
1635
+ const handleNotification = async (node) => {
1636
+ const remoteJid = node.attrs.from;
1637
+ try {
1638
+ await Promise.all([
1639
+ notificationMutex.mutex(async () => {
1640
+ const msg = await processNotification(node);
1641
+ if (msg) {
1642
+ const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
1643
+ const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node);
1644
+ msg.key = {
1645
+ remoteJid,
1646
+ fromMe,
1647
+ participant: node.attrs.participant,
1648
+ participantAlt,
1649
+ participantUsername: node.attrs.participant_username,
1650
+ addressingMode,
1651
+ id: node.attrs.id,
1652
+ ...(msg.key || {})
1653
+ };
1654
+ msg.participant ?? (msg.participant = node.attrs.participant);
1655
+ msg.messageTimestamp = +node.attrs.t;
1656
+ const fullMsg = proto.WebMessageInfo.fromObject(msg);
1657
+ await upsertMessage(fullMsg, 'append');
1658
+ }
1659
+ })
1660
+ ]);
1661
+ }
1662
+ finally {
1663
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
1664
+ }
1665
+ };
1666
+ const handleMessage = async (node) => {
1667
+ const encNode = getBinaryNodeChild(node, 'enc');
1668
+ // Pre-populate botMessageSecrets from store so msmsg can be decrypted after restart
1669
+ if (encNode?.attrs.type === 'msmsg') {
1670
+ if (getMessage) {
1671
+ const metaNode = getBinaryNodeChild(node, 'meta');
1672
+ const targetId = metaNode?.attrs?.target_id;
1673
+ if (targetId) {
1674
+ try {
1675
+ const targetMsg = await getMessage({ remoteJid: node.attrs.from, id: targetId, fromMe: true });
1676
+ const secret = targetMsg?.messageContextInfo?.messageSecret;
1677
+ if (secret) {
1678
+ setBotMessageSecret(targetId, secret);
1679
+ }
1680
+ }
1681
+ catch (err) {
1682
+ logger.debug({ err, targetId }, 'failed to retrieve message secret for msmsg');
1683
+ }
1684
+ }
1685
+ }
1686
+ }
1687
+ let acked = false;
1688
+ try {
1689
+ const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
1690
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
1691
+ // store new mappings we didn't have before
1692
+ if (!!alt) {
1693
+ const altServer = jidDecode(alt)?.server;
1694
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
1695
+ if (altServer === 'lid') {
1696
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
1697
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
1698
+ await signalRepository.migrateSession(primaryJid, alt);
1699
+ }
1700
+ }
1701
+ else {
1702
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
1703
+ await signalRepository.migrateSession(alt, primaryJid);
1704
+ }
1705
+ }
1706
+ await messageMutex.mutex(async () => {
1707
+ await decrypt();
1708
+ if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
1709
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
1710
+ }
1711
+ // message failed to decrypt
1712
+ if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
1713
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
1714
+ acked = true;
1715
+ return sendMessageAck(node, NACK_REASONS.ParsingError);
1716
+ }
1717
+ if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
1718
+ // Message arrived without encryption (e.g. CTWA ads messages).
1719
+ // Check if this is eligible for placeholder resend (matching WA Web filters).
1720
+ const unavailableNode = getBinaryNodeChild(node, 'unavailable');
1721
+ const unavailableType = unavailableNode?.attrs?.type;
1722
+ if (unavailableType === 'bot_unavailable_fanout' ||
1723
+ unavailableType === 'hosted_unavailable_fanout' ||
1724
+ unavailableType === 'view_once_unavailable_fanout') {
1725
+ logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
1726
+ acked = true;
1727
+ return sendMessageAck(node);
1728
+ }
1729
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1730
+ if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
1731
+ logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
1732
+ acked = true;
1733
+ return sendMessageAck(node);
1734
+ }
1735
+ // Request the real content from the phone via placeholder resend PDO.
1736
+ // Upsert the CIPHERTEXT stub as a placeholder (like WA Web's processPlaceholderMsg),
1737
+ // and store the requestId in stubParameters[1] so users can correlate
1738
+ // with the incoming PDO response event.
1739
+ const cleanKey = {
1740
+ remoteJid: msg.key.remoteJid,
1741
+ fromMe: msg.key.fromMe,
1742
+ id: msg.key.id,
1743
+ participant: msg.key.participant
1744
+ };
1745
+ // Cache the original message metadata so the PDO response handler
1746
+ // can preserve key fields (LID details etc.) that the phone may omit
1747
+ const msgData = {
1748
+ key: msg.key,
1749
+ messageTimestamp: msg.messageTimestamp,
1750
+ pushName: msg.pushName,
1751
+ participant: msg.participant,
1752
+ verifiedBizName: msg.verifiedBizName
1753
+ };
1754
+ requestPlaceholderResend(cleanKey, msgData)
1755
+ .then(requestId => {
1756
+ if (requestId && requestId !== 'RESOLVED') {
1757
+ logger.debug({ msgId: msg.key.id, requestId }, 'requested placeholder resend for unavailable message');
1758
+ ev.emit('messages.update', [
1759
+ {
1760
+ key: msg.key,
1761
+ update: { messageStubParameters: [NO_MESSAGE_FOUND_ERROR_TEXT, requestId] }
1762
+ }
1763
+ ]);
1764
+ }
1765
+ })
1766
+ .catch(err => {
1767
+ logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
1768
+ });
1769
+ acked = true;
1770
+ await sendMessageAck(node);
1771
+ // Don't return — fall through to upsertMessage so the stub is emitted
1772
+ }
1773
+ else {
1774
+ // Skip retry for expired status messages (>24h old)
1775
+ if (isJidStatusBroadcast(msg.key.remoteJid)) {
1776
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1777
+ if (messageAge > STATUS_EXPIRY_SECONDS) {
1778
+ logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message');
1779
+ acked = true;
1780
+ return sendMessageAck(node);
1781
+ }
1782
+ }
1783
+ logger.debug('[handleMessage] Attempting retry request for failed decryption');
1784
+ // WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
1785
+ await retryMutex.mutex(async () => {
1786
+ try {
1787
+ if (!ws.isOpen) {
1788
+ logger.debug({ node }, 'Connection closed, skipping retry');
1789
+ return;
1790
+ }
1791
+ const encNode = getBinaryNodeChild(node, 'enc');
1792
+ await sendRetryRequest(node, !encNode);
1793
+ if (retryRequestDelayMs) {
1794
+ await delay(retryRequestDelayMs);
1795
+ }
1796
+ }
1797
+ catch (err) {
1798
+ logger.error({ err }, 'Failed to send retry');
1799
+ }
1800
+ acked = true;
1801
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
1802
+ });
1803
+ }
1804
+ }
1805
+ else {
1806
+ if (messageRetryManager && msg.key.id) {
1807
+ messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
1808
+ }
1809
+ const isNewsletter = isJidNewsletter(msg.key.remoteJid);
1810
+ if (!isNewsletter) {
1811
+ // no type in the receipt => message delivered
1812
+ let type = undefined;
1813
+ let participant = msg.key.participant;
1814
+ if (category === 'peer') {
1815
+ // special peer message
1816
+ type = 'peer_msg';
1817
+ }
1818
+ else if (msg.key.fromMe) {
1819
+ // message was sent by us from a different device
1820
+ type = 'sender';
1821
+ // need to specially handle this case
1822
+ if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1823
+ participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1824
+ }
1825
+ }
1826
+ else if (!sendActiveReceipts) {
1827
+ type = 'inactive';
1828
+ }
1829
+ acked = true;
1830
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1831
+ // send ack for history message
1832
+ const isAnyHistoryMsg = getHistoryMsg(msg.message);
1833
+ if (isAnyHistoryMsg) {
1834
+ const jid = jidNormalizedUser(msg.key.remoteJid);
1835
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync'); // TODO: investigate
1836
+ }
1837
+ }
1838
+ else {
1839
+ acked = true;
1840
+ await sendMessageAck(node);
1841
+ logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
1842
+ }
1843
+ }
1844
+ cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1845
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1846
+ });
1847
+ }
1848
+ catch (error) {
1849
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
1850
+ if (!acked) {
1851
+ await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(ackErr => logger.error({ ackErr }, 'failed to ack message after error'));
1852
+ }
1853
+ }
1854
+ };
1855
+ const handleCall = async (node) => {
1856
+ try {
1857
+ const { attrs } = node;
1858
+ const [infoChild] = getAllBinaryNodeChildren(node);
1859
+ if (!infoChild) {
1860
+ throw new Boom('Missing call info in call node');
1861
+ }
1862
+ const status = getCallStatusFromNode(infoChild);
1863
+ const callId = infoChild.attrs['call-id'];
1864
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1865
+ const call = {
1866
+ chatId: attrs.from,
1867
+ from,
1868
+ callerPn: infoChild.attrs['caller_pn'],
1869
+ id: callId,
1870
+ date: new Date(+attrs.t * 1000),
1871
+ offline: !!attrs.offline,
1872
+ status
1873
+ };
1874
+ if (status === 'relaylatency') {
1875
+ const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms'];
1876
+ const latencyMs = latencyValue ? Number(latencyValue) : undefined;
1877
+ if (Number.isFinite(latencyMs)) {
1878
+ call.latencyMs = latencyMs;
1879
+ }
1880
+ }
1881
+ if (status === 'offer') {
1882
+ call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1883
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1884
+ call.groupJid = infoChild.attrs['group-jid'];
1885
+ await callOfferCache.set(call.id, call);
1886
+ }
1887
+ const existingCall = await callOfferCache.get(call.id);
1888
+ // use existing call info to populate this event
1889
+ if (existingCall) {
1890
+ call.isVideo = existingCall.isVideo;
1891
+ call.isGroup = existingCall.isGroup;
1892
+ call.callerPn = call.callerPn || existingCall.callerPn;
1893
+ }
1894
+ // delete data once call has ended
1895
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1896
+ await callOfferCache.del(call.id);
1897
+ }
1898
+ ev.emit('call', [call]);
1899
+ }
1900
+ catch (error) {
1901
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling call');
1902
+ }
1903
+ finally {
1904
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'));
1905
+ }
1906
+ };
1907
+ const handleBadAck = async ({ attrs }) => {
1908
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1909
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1910
+ // // current hypothesis is that if pash is sent in the ack
1911
+ // // it means -- the message hasn't reached all devices yet
1912
+ // // we'll retry sending the message here
1913
+ // if(attrs.phash) {
1914
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
1915
+ // const msg = await getMessage(key)
1916
+ // if(msg) {
1917
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1918
+ // } else {
1919
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
1920
+ // }
1921
+ // }
1922
+ // error in acknowledgement,
1923
+ // device could not display the message
1924
+ if (attrs.error) {
1925
+ const isReachoutTimelocked = attrs.error === String(NACK_REASONS.SenderReachoutTimelocked);
1926
+ if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
1927
+ // 463 = 1:1 message missing privacy token (tctoken). Usually means the
1928
+ // account is restricted: WhatsApp blocks starting new chats but preserves
1929
+ // existing ones, since established chats already carry a tctoken.
1930
+ // WA Web prevents this client-side (disables the compose bar).
1931
+ // No retry — retrying counts as another "reach out" and worsens the restriction.
1932
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'error 463: account restricted or missing tctoken for contact');
1933
+ const ackFrom = attrs.from;
1934
+ if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
1935
+ inFlight463Recoveries.add(ackFrom);
1936
+ void (async () => {
1937
+ try {
1938
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1939
+ const tcStorageJid = await resolveTcTokenJid(ackFrom, getLIDForPN);
1940
+ const issueJid = await resolveIssuanceJid(ackFrom, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
1941
+ const result = await issuePrivacyTokens([issueJid], unixTimestampSeconds());
1942
+ await storeTcTokensFromIqResult({
1943
+ result,
1944
+ fallbackJid: tcStorageJid,
1945
+ keys: authState.keys,
1946
+ getLIDForPN,
1947
+ onNewJidStored: trackTcTokenJid
1948
+ });
1949
+ logger.debug({ from: ackFrom }, 'completed 463 token recovery issuance');
1950
+ }
1951
+ catch (err) {
1952
+ logger.debug({ from: ackFrom, err: err?.message }, 'failed 463 token recovery issuance');
1953
+ }
1954
+ finally {
1955
+ inFlight463Recoveries.delete(ackFrom);
1956
+ }
1957
+ })();
1958
+ }
1959
+ }
1960
+ else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
1961
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing');
1962
+ }
1963
+ else if (isReachoutTimelocked) {
1964
+ // user is temporarily restricted, fetch current restriction details
1965
+ await fetchAccountReachoutTimelock().catch(err => logger.warn({ err }, 'failed to fetch reachout timelock'));
1966
+ logger.warn({ attrs }, 'received error in ack');
1967
+ }
1968
+ else {
1969
+ logger.warn({ attrs }, 'received error in ack');
1970
+ }
1971
+ ev.emit('messages.update', [
1972
+ {
1973
+ key,
1974
+ update: {
1975
+ status: WAMessageStatus.ERROR,
1976
+ messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
1977
+ }
1978
+ }
1979
+ ]);
1980
+ }
1981
+ };
1982
+ /// processes a node with the given function
1983
+ /// and adds the task to the existing buffer if we're buffering events
1984
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1985
+ ev.buffer();
1986
+ await execTask();
1987
+ ev.flush();
1988
+ function execTask() {
1989
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1990
+ }
1991
+ };
1992
+ const offlineNodeProcessor = makeOfflineNodeProcessor(new Map([
1993
+ ['message', handleMessage],
1994
+ ['call', handleCall],
1995
+ ['receipt', handleReceipt],
1996
+ ['notification', handleNotification]
1997
+ ]), {
1998
+ isWsOpen: () => ws.isOpen,
1999
+ onUnexpectedError,
2000
+ yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
2001
+ });
2002
+ const processNode = async (type, node, identifier, exec) => {
2003
+ // Fast path: ack and drop ignored JIDs before entering the buffer/queue
2004
+ const from = node.attrs.from;
2005
+ let ignoreJid = from;
2006
+ if (type === 'receipt' && from) {
2007
+ const attrs = node.attrs;
2008
+ const isLid = attrs.from.includes('lid');
2009
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
2010
+ ignoreJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
2011
+ }
2012
+ if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
2013
+ await sendMessageAck(node, type === 'message' ? NACK_REASONS.UnhandledError : undefined);
2014
+ return;
2015
+ }
2016
+ const isOffline = !!node.attrs.offline;
2017
+ if (isOffline) {
2018
+ offlineNodeProcessor.enqueue(type, node);
2019
+ }
2020
+ else {
2021
+ await processNodeWithBuffer(node, identifier, exec);
2022
+ }
2023
+ };
2024
+ // recv a message
2025
+ ws.on('CB:message', async (node) => {
2026
+ await processNode('message', node, 'processing message', handleMessage);
2027
+ });
2028
+ ws.on('CB:call', async (node) => {
2029
+ await processNode('call', node, 'handling call', handleCall);
2030
+ });
2031
+ ws.on('CB:receipt', async (node) => {
2032
+ await processNode('receipt', node, 'handling receipt', handleReceipt);
2033
+ });
2034
+ ws.on('CB:notification', async (node) => {
2035
+ await processNode('notification', node, 'handling notification', handleNotification);
2036
+ });
2037
+ ws.on('CB:status', async (node) => {
2038
+ await handleNewsletterStatus(node).catch(error => onUnexpectedError(error, 'handling newsletter status'));
2039
+ });
2040
+ ws.on('CB:ack,class:message', (node) => {
2041
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
2042
+ });
2043
+ ev.on('call', async ([call]) => {
2044
+ if (!call) {
2045
+ return;
2046
+ }
2047
+ // missed call + group call notification message generation
2048
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
2049
+ const msg = {
2050
+ key: {
2051
+ remoteJid: call.chatId,
2052
+ id: call.id,
2053
+ fromMe: false
2054
+ },
2055
+ messageTimestamp: unixTimestampSeconds(call.date)
2056
+ };
2057
+ if (call.status === 'timeout') {
2058
+ if (call.isGroup) {
2059
+ msg.messageStubType = call.isVideo
2060
+ ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
2061
+ : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
2062
+ }
2063
+ else {
2064
+ msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
2065
+ }
2066
+ }
2067
+ else {
2068
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
2069
+ }
2070
+ const protoMsg = proto.WebMessageInfo.fromObject(msg);
2071
+ await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
2072
+ }
2073
+ });
2074
+ /** timestamp of last tctoken prune run — throttles to once per 24h */
2075
+ let lastTcTokenPruneTs = 0;
2076
+ /** dedupe in-flight 463 recovery token issuance by target JID */
2077
+ const inFlight463Recoveries = new Set();
2078
+ ev.on('connection.update', ({ isOnline, connection }) => {
2079
+ if (typeof isOnline !== 'undefined') {
2080
+ sendActiveReceipts = isOnline;
2081
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
2082
+ }
2083
+ // Flush pending tctoken index save on disconnect to avoid writing after close
2084
+ if (connection === 'close' && tcTokenIndexTimer) {
2085
+ clearTimeout(tcTokenIndexTimer);
2086
+ tcTokenIndexTimer = undefined;
2087
+ // Best-effort flush — may fail if store is already closed
2088
+ try {
2089
+ void Promise.resolve(flushTcTokenIndex()).catch(() => { });
2090
+ }
2091
+ catch {
2092
+ /* ignore sync errors */
2093
+ }
2094
+ }
2095
+ // Prune expired tctokens when coming online, at most once per 24 hours
2096
+ // Matches WA Web's CLEAN_TC_TOKENS task
2097
+ // Note: don't gate on tcTokenKnownJids.size — the index may still be loading
2098
+ if (isOnline) {
2099
+ const now = Date.now();
2100
+ const DAY_MS = 24 * 60 * 60 * 1000;
2101
+ if (now - lastTcTokenPruneTs >= DAY_MS) {
2102
+ lastTcTokenPruneTs = now;
2103
+ void pruneExpiredTcTokens();
2104
+ }
2105
+ }
2106
+ });
2107
+ registerSocketEndHandler(() => {
2108
+ if (!config.msgRetryCounterCache && msgRetryCache.close) {
2109
+ msgRetryCache.close();
2110
+ }
2111
+ if (!config.callOfferCache && callOfferCache.close) {
2112
+ callOfferCache.close();
2113
+ }
2114
+ identityAssertDebounce.close();
2115
+ sendActiveReceipts = false;
2116
+ });
2117
+ async function pruneExpiredTcTokens() {
2118
+ try {
2119
+ await tcTokenIndexLoaded;
2120
+ // Union with the persisted index picks up JIDs added by other layers
2121
+ // (history sync) without needing inter-module wiring.
2122
+ const persisted = await readTcTokenIndex(authState.keys);
2123
+ const allJids = new Set(tcTokenKnownJids);
2124
+ for (const jid of persisted)
2125
+ allJids.add(jid);
2126
+ if (!allJids.size)
2127
+ return;
2128
+ const jids = [...allJids];
2129
+ const allTokens = await authState.keys.get('tctoken', jids);
2130
+ const writes = {};
2131
+ const survivors = new Set();
2132
+ let mutated = 0;
2133
+ for (const jid of jids) {
2134
+ const entry = allTokens[jid];
2135
+ if (!entry) {
2136
+ // Tracked but nothing in store — drop from index.
2137
+ mutated++;
2138
+ continue;
2139
+ }
2140
+ const hasPeerToken = !!entry.token?.length;
2141
+ const peerTokenExpired = hasPeerToken && isTcTokenExpired(entry.timestamp);
2142
+ const hasSenderTs = entry.senderTimestamp !== undefined;
2143
+ const senderTsExpired = hasSenderTs && isTcTokenExpired(entry.senderTimestamp);
2144
+ const keepPeerToken = hasPeerToken && !peerTokenExpired;
2145
+ const keepSenderTs = hasSenderTs && !senderTsExpired;
2146
+ if (!keepPeerToken && !keepSenderTs) {
2147
+ writes[jid] = null;
2148
+ mutated++;
2149
+ }
2150
+ else if (peerTokenExpired && keepSenderTs) {
2151
+ writes[jid] = { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp };
2152
+ survivors.add(jid);
2153
+ mutated++;
2154
+ }
2155
+ else {
2156
+ survivors.add(jid);
2157
+ }
2158
+ }
2159
+ if (mutated === 0)
2160
+ return;
2161
+ await authState.keys.set({
2162
+ tctoken: {
2163
+ ...writes,
2164
+ [TC_TOKEN_INDEX_KEY]: {
2165
+ token: Buffer.from(JSON.stringify([...survivors]))
2166
+ }
2167
+ }
2168
+ });
2169
+ tcTokenKnownJids.clear();
2170
+ for (const jid of survivors)
2171
+ tcTokenKnownJids.add(jid);
2172
+ logger.debug({ mutated, remaining: survivors.size }, 'pruned expired tctokens');
2173
+ }
2174
+ catch (err) {
2175
+ logger.warn({ err: err?.message }, 'failed to prune expired tctokens');
2176
+ }
2177
+ }
2178
+ return {
2179
+ ...sock,
2180
+ sendMessageAck,
2181
+ sendRetryRequest,
2182
+ rejectCall,
2183
+ acceptCall,
2184
+ terminateCall,
2185
+ offerCall,
2186
+ fetchMessageHistory,
2187
+ requestRecentConversationsOnDemand,
2188
+ requestPlaceholderResend,
2189
+ messageRetryManager
2190
+ };
2191
+ };