@skycodee/baileys 8.0.3 → 8.0.4

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