@nexustechpro/baileys 1.0.1 → 1.0.3-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1240 +1,1354 @@
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 { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT } from '../Defaults/index.js';
7
- import { WAMessageStatus, WAMessageStubType } from '../Types/index.js';
8
- import { aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
9
- import { makeMutex } from '../Utils/make-mutex.js';
10
- import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
11
- import { extractGroupMetadata } from './groups.js';
12
- import { makeMessagesSocket } from './messages-send.js';
1
+ import NodeCache from "@cacheable/node-cache"
2
+ import { Boom } from "@hapi/boom"
3
+ import { randomBytes } from "crypto"
4
+ import { proto } from "../../WAProto/index.js"
5
+ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT } from "../Defaults/index.js"
6
+ import { WAMessageStatus, WAMessageStubType } from "../Types/index.js"
7
+ import {
8
+ aesDecryptCTR,
9
+ aesEncryptGCM,
10
+ cleanMessage,
11
+ Curve,
12
+ decodeMediaRetryNode,
13
+ decodeMessageNode,
14
+ decryptMessageNode,
15
+ delay,
16
+ derivePairingCodeKey,
17
+ encodeBigEndian,
18
+ encodeSignedDeviceIdentity,
19
+ extractAddressingContext,
20
+ getCallStatusFromNode,
21
+ getHistoryMsg,
22
+ getNextPreKeys,
23
+ getStatusFromReceiptType,
24
+ hkdf,
25
+ MISSING_KEYS_ERROR_TEXT,
26
+ NACK_REASONS,
27
+ unixTimestampSeconds,
28
+ xmppPreKey,
29
+ xmppSignedPreKey,
30
+ } from "../Utils/index.js"
31
+ import { makeMutex } from "../Utils/make-mutex.js"
32
+ import {
33
+ areJidsSameUser,
34
+ binaryNodeToString,
35
+ getAllBinaryNodeChildren,
36
+ getBinaryNodeChild,
37
+ getBinaryNodeChildBuffer,
38
+ getBinaryNodeChildren,
39
+ getBinaryNodeChildString,
40
+ isJidGroup,
41
+ isJidStatusBroadcast,
42
+ isLidUser,
43
+ isPnUser,
44
+ jidDecode,
45
+ jidNormalizedUser,
46
+ S_WHATSAPP_NET,
47
+ } from "../WABinary/index.js"
48
+ import { extractGroupMetadata } from "./groups.js"
49
+ import { makeMessagesSocket } from "./messages-send.js"
13
50
  export const makeMessagesRecvSocket = (config) => {
14
- const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
15
- const sock = makeMessagesSocket(config);
16
- const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
17
- /** this mutex ensures that each retryRequest will wait for the previous one to finish */
18
- const retryMutex = makeMutex();
19
- const msgRetryCache = config.msgRetryCounterCache ||
20
- new NodeCache({
21
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
22
- useClones: false
23
- });
24
- const callOfferCache = config.callOfferCache ||
25
- new NodeCache({
26
- stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
27
- useClones: false
28
- });
29
- const placeholderResendCache = config.placeholderResendCache ||
30
- new NodeCache({
31
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
32
- useClones: false
33
- });
34
- let sendActiveReceipts = false;
35
- const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
36
- if (!authState.creds.me?.id) {
37
- throw new Boom('Not authenticated');
38
- }
39
- const pdoMessage = {
40
- historySyncOnDemandRequest: {
41
- chatJid: oldestMsgKey.remoteJid,
42
- oldestMsgFromMe: oldestMsgKey.fromMe,
43
- oldestMsgId: oldestMsgKey.id,
44
- oldestMsgTimestampMs: oldestMsgTimestamp,
45
- onDemandMsgCount: count
46
- },
47
- peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
48
- };
49
- return sendPeerDataOperationMessage(pdoMessage);
50
- };
51
- const requestPlaceholderResend = async (messageKey) => {
52
- if (!authState.creds.me?.id) {
53
- throw new Boom('Not authenticated');
54
- }
55
- if (placeholderResendCache.get(messageKey?.id)) {
56
- logger.debug({ messageKey }, 'already requested resend');
57
- return;
58
- }
59
- else {
60
- placeholderResendCache.set(messageKey?.id, true);
51
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } =
52
+ config
53
+ const sock = makeMessagesSocket(config)
54
+ const {
55
+ ev,
56
+ authState,
57
+ ws,
58
+ processingMutex,
59
+ signalRepository,
60
+ query,
61
+ upsertMessage,
62
+ resyncAppState,
63
+ onUnexpectedError,
64
+ assertSessions,
65
+ sendNode,
66
+ relayMessage,
67
+ sendReceipt,
68
+ uploadPreKeys,
69
+ sendPeerDataOperationMessage,
70
+ messageRetryManager,
71
+ } = sock
72
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
73
+ const retryMutex = makeMutex()
74
+ const msgRetryCache =
75
+ config.msgRetryCounterCache ||
76
+ new NodeCache({
77
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
78
+ useClones: false,
79
+ })
80
+ const callOfferCache =
81
+ config.callOfferCache ||
82
+ new NodeCache({
83
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
84
+ useClones: false,
85
+ })
86
+ const placeholderResendCache =
87
+ config.placeholderResendCache ||
88
+ new NodeCache({
89
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
90
+ useClones: false,
91
+ })
92
+ let sendActiveReceipts = false
93
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
94
+ if (!authState.creds.me?.id) {
95
+ throw new Boom("Not authenticated")
96
+ }
97
+ const pdoMessage = {
98
+ historySyncOnDemandRequest: {
99
+ chatJid: oldestMsgKey.remoteJid,
100
+ oldestMsgFromMe: oldestMsgKey.fromMe,
101
+ oldestMsgId: oldestMsgKey.id,
102
+ oldestMsgTimestampMs: oldestMsgTimestamp,
103
+ onDemandMsgCount: count,
104
+ },
105
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND,
106
+ }
107
+ return sendPeerDataOperationMessage(pdoMessage)
108
+ }
109
+ const requestPlaceholderResend = async (messageKey) => {
110
+ if (!authState.creds.me?.id) {
111
+ throw new Boom("Not authenticated")
112
+ }
113
+ if (placeholderResendCache.get(messageKey?.id)) {
114
+ logger.debug({ messageKey }, "already requested resend")
115
+ return
116
+ } else {
117
+ placeholderResendCache.set(messageKey?.id, true)
118
+ }
119
+ await delay(5000)
120
+ if (!placeholderResendCache.get(messageKey?.id)) {
121
+ logger.debug({ messageKey }, "message received while resend requested")
122
+ return "RESOLVED"
123
+ }
124
+ const pdoMessage = {
125
+ placeholderMessageResendRequest: [
126
+ {
127
+ messageKey,
128
+ },
129
+ ],
130
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND,
131
+ }
132
+ setTimeout(() => {
133
+ if (placeholderResendCache.get(messageKey?.id)) {
134
+ logger.debug({ messageKey }, "PDO message without response after 15 seconds. Phone possibly offline")
135
+ placeholderResendCache.del(messageKey?.id)
136
+ }
137
+ }, 15000)
138
+ return sendPeerDataOperationMessage(pdoMessage)
139
+ }
140
+ // Handles mex newsletter notifications
141
+ const handleMexNewsletterNotification = async (node) => {
142
+ const mexNode = getBinaryNodeChild(node, "mex")
143
+ if (!mexNode?.content) {
144
+ logger.warn({ node }, "Invalid mex newsletter notification")
145
+ return
146
+ }
147
+ let data
148
+ try {
149
+ data = JSON.parse(mexNode.content.toString())
150
+ } catch (error) {
151
+ logger.error({ err: error, node }, "Failed to parse mex newsletter notification")
152
+ return
153
+ }
154
+ const operation = data?.operation
155
+ const updates = data?.updates
156
+ if (!updates || !operation) {
157
+ logger.warn({ data }, "Invalid mex newsletter notification content")
158
+ return
159
+ }
160
+ logger.info({ operation, updates }, "got mex newsletter notification")
161
+ switch (operation) {
162
+ case "NotificationNewsletterUpdate":
163
+ for (const update of updates) {
164
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
165
+ ev.emit("newsletter-settings.update", {
166
+ id: update.jid,
167
+ update: update.settings,
168
+ })
169
+ }
61
170
  }
62
- await delay(5000);
63
- if (!placeholderResendCache.get(messageKey?.id)) {
64
- logger.debug({ messageKey }, 'message received while resend requested');
65
- return 'RESOLVED';
171
+ break
172
+ case "NotificationNewsletterAdminPromote":
173
+ for (const update of updates) {
174
+ if (update.jid && update.user) {
175
+ ev.emit("newsletter-participants.update", {
176
+ id: update.jid,
177
+ author: node.attrs.from,
178
+ user: update.user,
179
+ new_role: "ADMIN",
180
+ action: "promote",
181
+ })
182
+ }
66
183
  }
67
- const pdoMessage = {
68
- placeholderMessageResendRequest: [
69
- {
70
- messageKey
71
- }
72
- ],
73
- peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
74
- };
75
- setTimeout(() => {
76
- if (placeholderResendCache.get(messageKey?.id)) {
77
- logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
78
- placeholderResendCache.del(messageKey?.id);
79
- }
80
- }, 15000);
81
- return sendPeerDataOperationMessage(pdoMessage);
82
- };
83
- // Handles mex newsletter notifications
84
- const handleMexNewsletterNotification = async (node) => {
85
- const mexNode = getBinaryNodeChild(node, 'mex');
86
- if (!mexNode?.content) {
87
- logger.warn({ node }, 'Invalid mex newsletter notification');
88
- return;
184
+ break
185
+ default:
186
+ logger.info({ operation, data }, "Unhandled mex newsletter notification")
187
+ break
188
+ }
189
+ }
190
+ // Handles newsletter notifications
191
+ const handleNewsletterNotification = async (node) => {
192
+ const from = node.attrs.from
193
+ const child = getAllBinaryNodeChildren(node)[0]
194
+ const author = node.attrs.participant
195
+ logger.info({ from, child }, "got newsletter notification")
196
+ switch (child.tag) {
197
+ case "reaction":
198
+ const reactionUpdate = {
199
+ id: from,
200
+ server_id: child.attrs.message_id,
201
+ reaction: {
202
+ code: getBinaryNodeChildString(child, "reaction"),
203
+ count: 1,
204
+ },
89
205
  }
90
- let data;
91
- try {
92
- data = JSON.parse(mexNode.content.toString());
206
+ ev.emit("newsletter.reaction", reactionUpdate)
207
+ break
208
+ case "view":
209
+ const viewUpdate = {
210
+ id: from,
211
+ server_id: child.attrs.message_id,
212
+ count: Number.parseInt(child.content?.toString() || "0", 10),
93
213
  }
94
- catch (error) {
95
- logger.error({ err: error, node }, 'Failed to parse mex newsletter notification');
96
- return;
214
+ ev.emit("newsletter.view", viewUpdate)
215
+ break
216
+ case "participant":
217
+ const participantUpdate = {
218
+ id: from,
219
+ author,
220
+ user: child.attrs.jid,
221
+ action: child.attrs.action,
222
+ new_role: child.attrs.role,
97
223
  }
98
- const operation = data?.operation;
99
- const updates = data?.updates;
100
- if (!updates || !operation) {
101
- logger.warn({ data }, 'Invalid mex newsletter notification content');
102
- return;
224
+ ev.emit("newsletter-participants.update", participantUpdate)
225
+ break
226
+ case "update":
227
+ const settingsNode = getBinaryNodeChild(child, "settings")
228
+ if (settingsNode) {
229
+ const update = {}
230
+ const nameNode = getBinaryNodeChild(settingsNode, "name")
231
+ if (nameNode?.content) update.name = nameNode.content.toString()
232
+ const descriptionNode = getBinaryNodeChild(settingsNode, "description")
233
+ if (descriptionNode?.content) update.description = descriptionNode.content.toString()
234
+ ev.emit("newsletter-settings.update", {
235
+ id: from,
236
+ update,
237
+ })
103
238
  }
104
- logger.info({ operation, updates }, 'got mex newsletter notification');
105
- switch (operation) {
106
- case 'NotificationNewsletterUpdate':
107
- for (const update of updates) {
108
- if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
109
- ev.emit('newsletter-settings.update', {
110
- id: update.jid,
111
- update: update.settings
112
- });
113
- }
114
- }
115
- break;
116
- case 'NotificationNewsletterAdminPromote':
117
- for (const update of updates) {
118
- if (update.jid && update.user) {
119
- ev.emit('newsletter-participants.update', {
120
- id: update.jid,
121
- author: node.attrs.from,
122
- user: update.user,
123
- new_role: 'ADMIN',
124
- action: 'promote'
125
- });
126
- }
127
- }
128
- break;
129
- default:
130
- logger.info({ operation, data }, 'Unhandled mex newsletter notification');
131
- break;
239
+ break
240
+ case "message":
241
+ const plaintextNode = getBinaryNodeChild(child, "plaintext")
242
+ if (plaintextNode?.content) {
243
+ try {
244
+ const contentBuf =
245
+ typeof plaintextNode.content === "string"
246
+ ? Buffer.from(plaintextNode.content, "binary")
247
+ : Buffer.from(plaintextNode.content)
248
+ const messageProto = proto.Message.decode(contentBuf).toJSON()
249
+ const fullMessage = proto.WebMessageInfo.fromObject({
250
+ key: {
251
+ remoteJid: from,
252
+ id: child.attrs.message_id || child.attrs.server_id,
253
+ fromMe: false, // TODO: is this really true though
254
+ },
255
+ message: messageProto,
256
+ messageTimestamp: +child.attrs.t,
257
+ }).toJSON()
258
+ await upsertMessage(fullMessage, "append")
259
+ logger.info("Processed plaintext newsletter message")
260
+ } catch (error) {
261
+ logger.error({ error }, "Failed to decode plaintext newsletter message")
262
+ }
132
263
  }
133
- };
134
- // Handles newsletter notifications
135
- const handleNewsletterNotification = async (node) => {
136
- const from = node.attrs.from;
137
- const child = getAllBinaryNodeChildren(node)[0];
138
- const author = node.attrs.participant;
139
- logger.info({ from, child }, 'got newsletter notification');
140
- switch (child.tag) {
141
- case 'reaction':
142
- const reactionUpdate = {
143
- id: from,
144
- server_id: child.attrs.message_id,
145
- reaction: {
146
- code: getBinaryNodeChildString(child, 'reaction'),
147
- count: 1
148
- }
149
- };
150
- ev.emit('newsletter.reaction', reactionUpdate);
151
- break;
152
- case 'view':
153
- const viewUpdate = {
154
- id: from,
155
- server_id: child.attrs.message_id,
156
- count: parseInt(child.content?.toString() || '0', 10)
157
- };
158
- ev.emit('newsletter.view', viewUpdate);
159
- break;
160
- case 'participant':
161
- const participantUpdate = {
162
- id: from,
163
- author,
164
- user: child.attrs.jid,
165
- action: child.attrs.action,
166
- new_role: child.attrs.role
167
- };
168
- ev.emit('newsletter-participants.update', participantUpdate);
169
- break;
170
- case 'update':
171
- const settingsNode = getBinaryNodeChild(child, 'settings');
172
- if (settingsNode) {
173
- const update = {};
174
- const nameNode = getBinaryNodeChild(settingsNode, 'name');
175
- if (nameNode?.content)
176
- update.name = nameNode.content.toString();
177
- const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
178
- if (descriptionNode?.content)
179
- update.description = descriptionNode.content.toString();
180
- ev.emit('newsletter-settings.update', {
181
- id: from,
182
- update
183
- });
184
- }
185
- break;
186
- case 'message':
187
- const plaintextNode = getBinaryNodeChild(child, 'plaintext');
188
- if (plaintextNode?.content) {
189
- try {
190
- const contentBuf = typeof plaintextNode.content === 'string'
191
- ? Buffer.from(plaintextNode.content, 'binary')
192
- : Buffer.from(plaintextNode.content);
193
- const messageProto = proto.Message.decode(contentBuf).toJSON();
194
- const fullMessage = proto.WebMessageInfo.fromObject({
195
- key: {
196
- remoteJid: from,
197
- id: child.attrs.message_id || child.attrs.server_id,
198
- fromMe: false // TODO: is this really true though
199
- },
200
- message: messageProto,
201
- messageTimestamp: +child.attrs.t
202
- }).toJSON();
203
- await upsertMessage(fullMessage, 'append');
204
- logger.info('Processed plaintext newsletter message');
205
- }
206
- catch (error) {
207
- logger.error({ error }, 'Failed to decode plaintext newsletter message');
208
- }
209
- }
210
- break;
211
- default:
212
- logger.warn({ node }, 'Unknown newsletter notification');
213
- break;
264
+ break
265
+ default:
266
+ logger.warn({ node }, "Unknown newsletter notification")
267
+ break
268
+ }
269
+ }
270
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
271
+ const stanza = {
272
+ tag: "ack",
273
+ attrs: {
274
+ id: attrs.id,
275
+ to: attrs.from,
276
+ class: tag,
277
+ },
278
+ }
279
+ if (!!errorCode) {
280
+ stanza.attrs.error = errorCode.toString()
281
+ }
282
+ if (!!attrs.participant) {
283
+ stanza.attrs.participant = attrs.participant
284
+ }
285
+ if (!!attrs.recipient) {
286
+ stanza.attrs.recipient = attrs.recipient
287
+ }
288
+ if (
289
+ !!attrs.type &&
290
+ (tag !== "message" || getBinaryNodeChild({ tag, attrs, content }, "unavailable") || errorCode !== 0)
291
+ ) {
292
+ stanza.attrs.type = attrs.type
293
+ }
294
+ if (tag === "message" && getBinaryNodeChild({ tag, attrs, content }, "unavailable")) {
295
+ stanza.attrs.from = authState.creds.me.id
296
+ }
297
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, "sent ack")
298
+ try {
299
+ await sendNode(stanza)
300
+ } catch (error) {
301
+ // Handle connection closed errors gracefully
302
+ // Don't crash if ACK fails - the message was already received
303
+ if (error?.output?.statusCode === 428 || error?.message?.includes("Connection")) {
304
+ logger.warn(
305
+ { id: attrs.id, error: error?.message },
306
+ "Failed to send ACK (connection closed) - message already received",
307
+ )
308
+ // Silently continue instead of throwing
309
+ } else {
310
+ // Re-throw other errors
311
+ throw error
312
+ }
313
+ }
314
+ }
315
+ const rejectCall = async (callId, callFrom) => {
316
+ const stanza = {
317
+ tag: "call",
318
+ attrs: {
319
+ from: authState.creds.me.id,
320
+ to: callFrom,
321
+ },
322
+ content: [
323
+ {
324
+ tag: "reject",
325
+ attrs: {
326
+ "call-id": callId,
327
+ "call-creator": callFrom,
328
+ count: "0",
329
+ },
330
+ content: undefined,
331
+ },
332
+ ],
333
+ }
334
+ await query(stanza)
335
+ }
336
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
337
+ const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || "")
338
+ const { key: msgKey } = fullMessage
339
+ const msgId = msgKey.id
340
+ if (messageRetryManager) {
341
+ // Check if we've exceeded max retries using the new system
342
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
343
+ logger.debug({ msgId }, "reached retry limit with new retry manager, clearing")
344
+ messageRetryManager.markRetryFailed(msgId)
345
+ return
346
+ }
347
+ // Increment retry count using new system
348
+ const retryCount = messageRetryManager.incrementRetryCount(msgId)
349
+ // Use the new retry count for the rest of the logic
350
+ const key = `${msgId}:${msgKey?.participant}`
351
+ msgRetryCache.set(key, retryCount)
352
+ } else {
353
+ // Fallback to old system
354
+ const key = `${msgId}:${msgKey?.participant}`
355
+ let retryCount = (await msgRetryCache.get(key)) || 0
356
+ if (retryCount >= maxMsgRetryCount) {
357
+ logger.debug({ retryCount, msgId }, "reached retry limit, clearing")
358
+ msgRetryCache.del(key)
359
+ return
360
+ }
361
+ retryCount += 1
362
+ await msgRetryCache.set(key, retryCount)
363
+ }
364
+ const key = `${msgId}:${msgKey?.participant}`
365
+ const retryCount = (await msgRetryCache.get(key)) || 1
366
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
367
+ const fromJid = node.attrs.from
368
+ // Check if we should recreate the session
369
+ let shouldRecreateSession = false
370
+ let recreateReason = ""
371
+ if (enableAutoSessionRecreation && messageRetryManager) {
372
+ try {
373
+ // Check if we have a session with this JID
374
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid)
375
+ const hasSession = await signalRepository.validateSession(fromJid)
376
+ const result = messageRetryManager.shouldRecreateSession(fromJid, retryCount, hasSession.exists)
377
+ shouldRecreateSession = result.recreate
378
+ recreateReason = result.reason
379
+ if (shouldRecreateSession) {
380
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, "recreating session for retry")
381
+ // Delete existing session to force recreation
382
+ await authState.keys.set({ session: { [sessionId]: null } })
383
+ forceIncludeKeys = true
214
384
  }
215
- };
216
- const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
217
- const stanza = {
218
- tag: 'ack',
385
+ } catch (error) {
386
+ logger.warn({ error, fromJid }, "failed to check session recreation")
387
+ }
388
+ }
389
+ if (retryCount <= 2) {
390
+ // Use new retry manager for phone requests if available
391
+ if (messageRetryManager) {
392
+ // Schedule phone request with delay (like whatsmeow)
393
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
394
+ try {
395
+ const requestId = await requestPlaceholderResend(msgKey)
396
+ logger.debug(
397
+ `sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`,
398
+ )
399
+ } catch (error) {
400
+ logger.warn({ error, msgId }, "failed to send scheduled phone request")
401
+ }
402
+ })
403
+ } else {
404
+ // Fallback to immediate request
405
+ const msgId = await requestPlaceholderResend(msgKey)
406
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`)
407
+ }
408
+ }
409
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true)
410
+ await authState.keys.transaction(async () => {
411
+ const receipt = {
412
+ tag: "receipt",
413
+ attrs: {
414
+ id: msgId,
415
+ type: "retry",
416
+ to: node.attrs.from,
417
+ },
418
+ content: [
419
+ {
420
+ tag: "retry",
219
421
  attrs: {
220
- id: attrs.id,
221
- to: attrs.from,
222
- class: tag
223
- }
224
- };
225
- if (!!errorCode) {
226
- stanza.attrs.error = errorCode.toString();
227
- }
228
- if (!!attrs.participant) {
229
- stanza.attrs.participant = attrs.participant;
230
- }
231
- if (!!attrs.recipient) {
232
- stanza.attrs.recipient = attrs.recipient;
422
+ count: retryCount.toString(),
423
+ id: node.attrs.id,
424
+ t: node.attrs.t,
425
+ v: "1",
426
+ // ADD ERROR FIELD
427
+ error: "0",
428
+ },
429
+ },
430
+ {
431
+ tag: "registration",
432
+ attrs: {},
433
+ content: encodeBigEndian(authState.creds.registrationId),
434
+ },
435
+ ],
436
+ }
437
+ if (node.attrs.recipient) {
438
+ receipt.attrs.recipient = node.attrs.recipient
439
+ }
440
+ if (node.attrs.participant) {
441
+ receipt.attrs.participant = node.attrs.participant
442
+ }
443
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
444
+ const { update, preKeys } = await getNextPreKeys(authState, 1)
445
+ const [keyId] = Object.keys(preKeys)
446
+ const key = preKeys[+keyId]
447
+ const content = receipt.content
448
+ content.push({
449
+ tag: "keys",
450
+ attrs: {},
451
+ content: [
452
+ { tag: "type", attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
453
+ { tag: "identity", attrs: {}, content: identityKey.public },
454
+ xmppPreKey(key, +keyId),
455
+ xmppSignedPreKey(signedPreKey),
456
+ { tag: "device-identity", attrs: {}, content: deviceIdentity },
457
+ ],
458
+ })
459
+ ev.emit("creds.update", update)
460
+ }
461
+ await sendNode(receipt)
462
+ logger.info({ msgAttrs: node.attrs, retryCount }, "sent retry receipt")
463
+ }, authState?.creds?.me?.id || "sendRetryRequest")
464
+ }
465
+ const handleEncryptNotification = async (node) => {
466
+ const from = node.attrs.from
467
+ if (from === S_WHATSAPP_NET) {
468
+ const countChild = getBinaryNodeChild(node, "count")
469
+ const count = +countChild.attrs.value
470
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT
471
+ logger.debug({ count, shouldUploadMorePreKeys }, "recv pre-key count")
472
+ if (shouldUploadMorePreKeys) {
473
+ smartPreKeyMonitor("server-notification").catch(err => {
474
+ logger.error({ err }, "Failed to upload pre-keys after server notification")
475
+ })
476
+ }
477
+ } else {
478
+ const identityNode = getBinaryNodeChild(node, "identity")
479
+ if (identityNode) {
480
+ logger.info({ jid: from }, "identity changed")
481
+ // not handling right now
482
+ // signal will override new identity anyway
483
+ } else {
484
+ logger.info({ node }, "unknown encrypt notification")
485
+ }
486
+ }
487
+ }
488
+ const handleGroupNotification = (fullNode, child, msg) => {
489
+ // TODO: Support PN/LID (Here is only LID now)
490
+ const actingParticipantLid = fullNode.attrs.participant
491
+ const actingParticipantPn = fullNode.attrs.participant_pn
492
+ const affectedParticipantLid = getBinaryNodeChild(child, "participant")?.attrs?.jid || actingParticipantLid
493
+ const affectedParticipantPn = getBinaryNodeChild(child, "participant")?.attrs?.phone_number || actingParticipantPn
494
+ switch (child?.tag) {
495
+ case "create":
496
+ const metadata = extractGroupMetadata(child)
497
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE
498
+ msg.messageStubParameters = [metadata.subject]
499
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn }
500
+ ev.emit("chats.upsert", [
501
+ {
502
+ id: metadata.id,
503
+ name: metadata.subject,
504
+ conversationTimestamp: metadata.creation,
505
+ },
506
+ ])
507
+ ev.emit("groups.upsert", [
508
+ {
509
+ ...metadata,
510
+ author: actingParticipantLid,
511
+ authorPn: actingParticipantPn,
512
+ },
513
+ ])
514
+ break
515
+ case "ephemeral":
516
+ case "not_ephemeral":
517
+ msg.message = {
518
+ protocolMessage: {
519
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
520
+ ephemeralExpiration: +(child.attrs.expiration || 0),
521
+ },
233
522
  }
234
- if (!!attrs.type &&
235
- (tag !== 'message' || getBinaryNodeChild({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
236
- stanza.attrs.type = attrs.type;
523
+ break
524
+ case "modify":
525
+ const oldNumber = getBinaryNodeChildren(child, "participant").map((p) => p.attrs.jid)
526
+ msg.messageStubParameters = oldNumber || []
527
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER
528
+ break
529
+ case "promote":
530
+ case "demote":
531
+ case "remove":
532
+ case "add":
533
+ case "leave":
534
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`
535
+ msg.messageStubType = WAMessageStubType[stubType]
536
+ const participants = getBinaryNodeChildren(child, "participant").map(({ attrs }) => {
537
+ // TODO: Store LID MAPPINGS
538
+ return {
539
+ id: attrs.jid,
540
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
541
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
542
+ admin: attrs.type || null,
543
+ }
544
+ })
545
+ if (
546
+ participants.length === 1 &&
547
+ // if recv. "remove" message and sender removed themselves
548
+ // mark as left
549
+ (areJidsSameUser(participants[0].id, actingParticipantLid) ||
550
+ areJidsSameUser(participants[0].id, actingParticipantPn)) &&
551
+ child.tag === "remove"
552
+ ) {
553
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE
237
554
  }
238
- if (tag === 'message' && getBinaryNodeChild({ tag, attrs, content }, 'unavailable')) {
239
- stanza.attrs.from = authState.creds.me.id;
555
+ msg.messageStubParameters = participants.map((a) => JSON.stringify(a))
556
+ break
557
+ case "subject":
558
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT
559
+ msg.messageStubParameters = [child.attrs.subject]
560
+ break
561
+ case "description":
562
+ const description = getBinaryNodeChild(child, "body")?.content?.toString()
563
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION
564
+ msg.messageStubParameters = description ? [description] : undefined
565
+ break
566
+ case "announcement":
567
+ case "not_announcement":
568
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE
569
+ msg.messageStubParameters = [child.tag === "announcement" ? "on" : "off"]
570
+ break
571
+ case "locked":
572
+ case "unlocked":
573
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT
574
+ msg.messageStubParameters = [child.tag === "locked" ? "on" : "off"]
575
+ break
576
+ case "invite":
577
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK
578
+ msg.messageStubParameters = [child.attrs.code]
579
+ break
580
+ case "member_add_mode":
581
+ const addMode = child.content
582
+ if (addMode) {
583
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE
584
+ msg.messageStubParameters = [addMode.toString()]
240
585
  }
241
- logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
242
- try {
243
- await sendNode(stanza);
244
- } catch (error) {
245
- // Handle connection closed errors gracefully
246
- // Don't crash if ACK fails - the message was already received
247
- if (error?.output?.statusCode === 428 || error?.message?.includes('Connection')) {
248
- logger.warn({ id: attrs.id, error: error?.message }, 'Failed to send ACK (connection closed) - message already received');
249
- // Silently continue instead of throwing
250
- } else {
251
- // Re-throw other errors
252
- throw error;
253
- }
586
+ break
587
+ case "membership_approval_mode":
588
+ const approvalMode = getBinaryNodeChild(child, "group_join")
589
+ if (approvalMode) {
590
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE
591
+ msg.messageStubParameters = [approvalMode.attrs.state]
254
592
  }
255
- };
256
- const rejectCall = async (callId, callFrom) => {
257
- const stanza = {
258
- tag: 'call',
259
- attrs: {
260
- from: authState.creds.me.id,
261
- to: callFrom
593
+ break
594
+ case "created_membership_requests":
595
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
596
+ msg.messageStubParameters = [
597
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
598
+ "created",
599
+ child.attrs.request_method,
600
+ ]
601
+ break
602
+ case "revoked_membership_requests":
603
+ const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid)
604
+ // TODO: LIDMAPPING SUPPORT
605
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
606
+ msg.messageStubParameters = [
607
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
608
+ isDenied ? "revoked" : "rejected",
609
+ ]
610
+ break
611
+ }
612
+ }
613
+ const processNotification = async (node) => {
614
+ const result = {}
615
+ const [child] = getAllBinaryNodeChildren(node)
616
+ const nodeType = node.attrs.type
617
+ const from = jidNormalizedUser(node.attrs.from)
618
+ switch (nodeType) {
619
+ case "privacy_token":
620
+ const tokenList = getBinaryNodeChildren(child, "token")
621
+ for (const { attrs, content } of tokenList) {
622
+ const jid = attrs.jid
623
+ ev.emit("chats.update", [
624
+ {
625
+ id: jid,
626
+ tcToken: content,
262
627
  },
263
- content: [
264
- {
265
- tag: 'reject',
266
- attrs: {
267
- 'call-id': callId,
268
- 'call-creator': callFrom,
269
- count: '0'
270
- },
271
- content: undefined
272
- }
273
- ]
274
- };
275
- await query(stanza);
276
- };
277
- const sendRetryRequest = async (node, forceIncludeKeys = false) => {
278
- const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
279
- const { key: msgKey } = fullMessage;
280
- const msgId = msgKey.id;
281
- if (messageRetryManager) {
282
- // Check if we've exceeded max retries using the new system
283
- if (messageRetryManager.hasExceededMaxRetries(msgId)) {
284
- logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
285
- messageRetryManager.markRetryFailed(msgId);
286
- return;
287
- }
288
- // Increment retry count using new system
289
- const retryCount = messageRetryManager.incrementRetryCount(msgId);
290
- // Use the new retry count for the rest of the logic
291
- const key = `${msgId}:${msgKey?.participant}`;
292
- msgRetryCache.set(key, retryCount);
628
+ ])
629
+ logger.debug({ jid }, "got privacy token update")
293
630
  }
294
- else {
295
- // Fallback to old system
296
- const key = `${msgId}:${msgKey?.participant}`;
297
- let retryCount = (await msgRetryCache.get(key)) || 0;
298
- if (retryCount >= maxMsgRetryCount) {
299
- logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
300
- msgRetryCache.del(key);
301
- return;
302
- }
303
- retryCount += 1;
304
- await msgRetryCache.set(key, retryCount);
631
+ break
632
+ case "newsletter":
633
+ await handleNewsletterNotification(node)
634
+ break
635
+ case "mex":
636
+ await handleMexNewsletterNotification(node)
637
+ break
638
+ case "w:gp2":
639
+ // TODO: HANDLE PARTICIPANT_PN
640
+ handleGroupNotification(node, child, result)
641
+ break
642
+ case "mediaretry":
643
+ const event = decodeMediaRetryNode(node)
644
+ ev.emit("messages.media-update", [event])
645
+ break
646
+ case "encrypt":
647
+ await handleEncryptNotification(node)
648
+ break
649
+ case "devices":
650
+ const devices = getBinaryNodeChildren(child, "device")
651
+ if (
652
+ areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
653
+ areJidsSameUser(child.attrs.lid, authState.creds.me.lid)
654
+ ) {
655
+ const deviceData = devices.map((d) => ({ id: d.attrs.jid, lid: d.attrs.lid }))
656
+ logger.info({ deviceData }, "my own devices changed")
305
657
  }
306
- const key = `${msgId}:${msgKey?.participant}`;
307
- const retryCount = (await msgRetryCache.get(key)) || 1;
308
- const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
309
- const fromJid = node.attrs.from;
310
- // Check if we should recreate the session
311
- let shouldRecreateSession = false;
312
- let recreateReason = '';
313
- if (enableAutoSessionRecreation && messageRetryManager) {
314
- try {
315
- // Check if we have a session with this JID
316
- const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
317
- const hasSession = await signalRepository.validateSession(fromJid);
318
- const result = messageRetryManager.shouldRecreateSession(fromJid, retryCount, hasSession.exists);
319
- shouldRecreateSession = result.recreate;
320
- recreateReason = result.reason;
321
- if (shouldRecreateSession) {
322
- logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
323
- // Delete existing session to force recreation
324
- await authState.keys.set({ session: { [sessionId]: null } });
325
- forceIncludeKeys = true;
326
- }
327
- }
328
- catch (error) {
329
- logger.warn({ error, fromJid }, 'failed to check session recreation');
330
- }
658
+ //TODO: drop a new event, add hashes
659
+ break
660
+ case "server_sync":
661
+ const update = getBinaryNodeChild(node, "collection")
662
+ if (update) {
663
+ const name = update.attrs.name
664
+ await resyncAppState([name], false)
331
665
  }
332
- if (retryCount <= 2) {
333
- // Use new retry manager for phone requests if available
334
- if (messageRetryManager) {
335
- // Schedule phone request with delay (like whatsmeow)
336
- messageRetryManager.schedulePhoneRequest(msgId, async () => {
337
- try {
338
- const requestId = await requestPlaceholderResend(msgKey);
339
- logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
340
- }
341
- catch (error) {
342
- logger.warn({ error, msgId }, 'failed to send scheduled phone request');
343
- }
344
- });
345
- }
346
- else {
347
- // Fallback to immediate request
348
- const msgId = await requestPlaceholderResend(msgKey);
349
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
350
- }
666
+ break
667
+ case "picture":
668
+ const setPicture = getBinaryNodeChild(node, "set")
669
+ const delPicture = getBinaryNodeChild(node, "delete")
670
+ ev.emit("contacts.update", [
671
+ {
672
+ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || "",
673
+ imgUrl: setPicture ? "changed" : "removed",
674
+ },
675
+ ])
676
+ if (isJidGroup(from)) {
677
+ const node = setPicture || delPicture
678
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON
679
+ if (setPicture) {
680
+ result.messageStubParameters = [setPicture.attrs.id]
681
+ }
682
+ result.participant = node?.attrs.author
683
+ result.key = {
684
+ ...(result.key || {}),
685
+ participant: setPicture?.attrs.author,
686
+ }
351
687
  }
352
- const deviceIdentity = encodeSignedDeviceIdentity(account, true);
353
- await authState.keys.transaction(async () => {
354
- const receipt = {
355
- tag: 'receipt',
356
- attrs: {
357
- id: msgId,
358
- type: 'retry',
359
- to: node.attrs.from
360
- },
361
- content: [
362
- {
363
- tag: 'retry',
364
- attrs: {
365
- count: retryCount.toString(),
366
- id: node.attrs.id,
367
- t: node.attrs.t,
368
- v: '1',
369
- // ADD ERROR FIELD
370
- error: '0'
371
- }
372
- },
373
- {
374
- tag: 'registration',
375
- attrs: {},
376
- content: encodeBigEndian(authState.creds.registrationId)
377
- }
378
- ]
379
- };
380
- if (node.attrs.recipient) {
381
- receipt.attrs.recipient = node.attrs.recipient;
382
- }
383
- if (node.attrs.participant) {
384
- receipt.attrs.participant = node.attrs.participant;
385
- }
386
- if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
387
- const { update, preKeys } = await getNextPreKeys(authState, 1);
388
- const [keyId] = Object.keys(preKeys);
389
- const key = preKeys[+keyId];
390
- const content = receipt.content;
391
- content.push({
392
- tag: 'keys',
393
- attrs: {},
394
- content: [
395
- { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
396
- { tag: 'identity', attrs: {}, content: identityKey.public },
397
- xmppPreKey(key, +keyId),
398
- xmppSignedPreKey(signedPreKey),
399
- { tag: 'device-identity', attrs: {}, content: deviceIdentity }
400
- ]
401
- });
402
- ev.emit('creds.update', update);
403
- }
404
- await sendNode(receipt);
405
- logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
406
- }, authState?.creds?.me?.id || 'sendRetryRequest');
407
- };
408
- const handleEncryptNotification = async (node) => {
409
- const from = node.attrs.from;
410
- if (from === S_WHATSAPP_NET) {
411
- const countChild = getBinaryNodeChild(node, 'count');
412
- const count = +countChild.attrs.value;
413
- const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
414
- logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
415
- if (shouldUploadMorePreKeys) {
416
- await uploadPreKeys();
417
- }
418
- }
419
- else {
420
- const identityNode = getBinaryNodeChild(node, 'identity');
421
- if (identityNode) {
422
- logger.info({ jid: from }, 'identity changed');
423
- // not handling right now
424
- // signal will override new identity anyway
425
- }
426
- else {
427
- logger.info({ node }, 'unknown encrypt notification');
428
- }
688
+ break
689
+ case "account_sync":
690
+ if (child.tag === "disappearing_mode") {
691
+ const newDuration = +child.attrs.duration
692
+ const timestamp = +child.attrs.t
693
+ logger.info({ newDuration }, "updated account disappearing mode")
694
+ ev.emit("creds.update", {
695
+ accountSettings: {
696
+ ...authState.creds.accountSettings,
697
+ defaultDisappearingMode: {
698
+ ephemeralExpiration: newDuration,
699
+ ephemeralSettingTimestamp: timestamp,
700
+ },
701
+ },
702
+ })
703
+ } else if (child.tag === "blocklist") {
704
+ const blocklists = getBinaryNodeChildren(child, "item")
705
+ for (const { attrs } of blocklists) {
706
+ const blocklist = [attrs.jid]
707
+ const type = attrs.action === "block" ? "add" : "remove"
708
+ ev.emit("blocklist.update", { blocklist, type })
709
+ }
429
710
  }
430
- };
431
- const handleGroupNotification = (fullNode, child, msg) => {
432
- // TODO: Support PN/LID (Here is only LID now)
433
- const actingParticipantLid = fullNode.attrs.participant;
434
- const actingParticipantPn = fullNode.attrs.participant_pn;
435
- const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
436
- const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
437
- switch (child?.tag) {
438
- case 'create':
439
- const metadata = extractGroupMetadata(child);
440
- msg.messageStubType = WAMessageStubType.GROUP_CREATE;
441
- msg.messageStubParameters = [metadata.subject];
442
- msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
443
- ev.emit('chats.upsert', [
444
- {
445
- id: metadata.id,
446
- name: metadata.subject,
447
- conversationTimestamp: metadata.creation
448
- }
449
- ]);
450
- ev.emit('groups.upsert', [
451
- {
452
- ...metadata,
453
- author: actingParticipantLid,
454
- authorPn: actingParticipantPn
455
- }
456
- ]);
457
- break;
458
- case 'ephemeral':
459
- case 'not_ephemeral':
460
- msg.message = {
461
- protocolMessage: {
462
- type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
463
- ephemeralExpiration: +(child.attrs.expiration || 0)
464
- }
465
- };
466
- break;
467
- case 'modify':
468
- const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
469
- msg.messageStubParameters = oldNumber || [];
470
- msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
471
- break;
472
- case 'promote':
473
- case 'demote':
474
- case 'remove':
475
- case 'add':
476
- case 'leave':
477
- const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
478
- msg.messageStubType = WAMessageStubType[stubType];
479
- const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
480
- // TODO: Store LID MAPPINGS
481
- return {
482
- id: attrs.jid,
483
- phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
484
- lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
485
- admin: (attrs.type || null)
486
- };
487
- });
488
- if (participants.length === 1 &&
489
- // if recv. "remove" message and sender removed themselves
490
- // mark as left
491
- (areJidsSameUser(participants[0].id, actingParticipantLid) ||
492
- areJidsSameUser(participants[0].id, actingParticipantPn)) &&
493
- child.tag === 'remove') {
494
- msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
495
- }
496
- msg.messageStubParameters = participants.map(a => JSON.stringify(a));
497
- break;
498
- case 'subject':
499
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
500
- msg.messageStubParameters = [child.attrs.subject];
501
- break;
502
- case 'description':
503
- const description = getBinaryNodeChild(child, 'body')?.content?.toString();
504
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
505
- msg.messageStubParameters = description ? [description] : undefined;
506
- break;
507
- case 'announcement':
508
- case 'not_announcement':
509
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
510
- msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
511
- break;
512
- case 'locked':
513
- case 'unlocked':
514
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
515
- msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
516
- break;
517
- case 'invite':
518
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
519
- msg.messageStubParameters = [child.attrs.code];
520
- break;
521
- case 'member_add_mode':
522
- const addMode = child.content;
523
- if (addMode) {
524
- msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
525
- msg.messageStubParameters = [addMode.toString()];
526
- }
527
- break;
528
- case 'membership_approval_mode':
529
- const approvalMode = getBinaryNodeChild(child, 'group_join');
530
- if (approvalMode) {
531
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
532
- msg.messageStubParameters = [approvalMode.attrs.state];
533
- }
534
- break;
535
- case 'created_membership_requests':
536
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
537
- msg.messageStubParameters = [
538
- JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
539
- 'created',
540
- child.attrs.request_method
541
- ];
542
- break;
543
- case 'revoked_membership_requests':
544
- const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
545
- // TODO: LIDMAPPING SUPPORT
546
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
547
- msg.messageStubParameters = [
548
- JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
549
- isDenied ? 'revoked' : 'rejected'
550
- ];
551
- break;
711
+ break
712
+ case "link_code_companion_reg":
713
+ const linkCodeCompanionReg = getBinaryNodeChild(node, "link_code_companion_reg")
714
+ const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, "link_code_pairing_ref"))
715
+ const primaryIdentityPublicKey = toRequiredBuffer(
716
+ getBinaryNodeChildBuffer(linkCodeCompanionReg, "primary_identity_pub"),
717
+ )
718
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(
719
+ getBinaryNodeChildBuffer(linkCodeCompanionReg, "link_code_pairing_wrapped_primary_ephemeral_pub"),
720
+ )
721
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped)
722
+ const companionSharedKey = Curve.sharedKey(
723
+ authState.creds.pairingEphemeralKeyPair.private,
724
+ codePairingPublicKey,
725
+ )
726
+ const random = randomBytes(32)
727
+ const linkCodeSalt = randomBytes(32)
728
+ const linkCodePairingExpanded = await hkdf(companionSharedKey, 32, {
729
+ salt: linkCodeSalt,
730
+ info: "link_code_pairing_key_bundle_encryption_key",
731
+ })
732
+ const encryptPayload = Buffer.concat([
733
+ Buffer.from(authState.creds.signedIdentityKey.public),
734
+ primaryIdentityPublicKey,
735
+ random,
736
+ ])
737
+ const encryptIv = randomBytes(12)
738
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0))
739
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted])
740
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey)
741
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random])
742
+ authState.creds.advSecretKey = (await hkdf(identityPayload, 32, { info: "adv_secret" })).toString("base64")
743
+ await query({
744
+ tag: "iq",
745
+ attrs: {
746
+ to: S_WHATSAPP_NET,
747
+ type: "set",
748
+ id: sock.generateMessageTag(),
749
+ xmlns: "md",
750
+ },
751
+ content: [
752
+ {
753
+ tag: "link_code_companion_reg",
754
+ attrs: {
755
+ jid: authState.creds.me.id,
756
+ stage: "companion_finish",
757
+ },
758
+ content: [
759
+ {
760
+ tag: "link_code_pairing_wrapped_key_bundle",
761
+ attrs: {},
762
+ content: encryptedPayload,
763
+ },
764
+ {
765
+ tag: "companion_identity_public",
766
+ attrs: {},
767
+ content: authState.creds.signedIdentityKey.public,
768
+ },
769
+ {
770
+ tag: "link_code_pairing_ref",
771
+ attrs: {},
772
+ content: ref,
773
+ },
774
+ ],
775
+ },
776
+ ],
777
+ })
778
+ authState.creds.registered = true
779
+ ev.emit("creds.update", authState.creds)
780
+ }
781
+ if (Object.keys(result).length) {
782
+ return result
783
+ }
784
+ }
785
+ async function decipherLinkPublicKey(data) {
786
+ const buffer = toRequiredBuffer(data)
787
+ const salt = buffer.slice(0, 32)
788
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt)
789
+ const iv = buffer.slice(32, 48)
790
+ const payload = buffer.slice(48, 80)
791
+ return aesDecryptCTR(payload, secretKey, iv)
792
+ }
793
+ function toRequiredBuffer(data) {
794
+ if (data === undefined) {
795
+ throw new Boom("Invalid buffer", { statusCode: 400 })
796
+ }
797
+ return data instanceof Buffer ? data : Buffer.from(data)
798
+ }
799
+ const willSendMessageAgain = async (id, participant) => {
800
+ const key = `${id}:${participant}`
801
+ const retryCount = (await msgRetryCache.get(key)) || 0
802
+ return retryCount < maxMsgRetryCount
803
+ }
804
+ const updateSendMessageAgainCount = async (id, participant) => {
805
+ const key = `${id}:${participant}`
806
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1
807
+ await msgRetryCache.set(key, newValue)
808
+ }
809
+ const sendMessagesAgain = async (key, ids, retryNode) => {
810
+ const remoteJid = key.remoteJid
811
+ const participant = key.participant || remoteJid
812
+ const retryCount = +retryNode.attrs.count || 1
813
+ // Try to get messages from cache first, then fallback to getMessage
814
+ const msgs = []
815
+ for (const id of ids) {
816
+ let msg
817
+ // Try to get from retry cache first if enabled
818
+ if (messageRetryManager) {
819
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id)
820
+ if (cachedMsg) {
821
+ msg = cachedMsg.message
822
+ logger.debug({ jid: remoteJid, id }, "found message in retry cache")
823
+ // Mark retry as successful since we found the message
824
+ messageRetryManager.markRetrySuccess(id)
552
825
  }
553
- };
554
- const processNotification = async (node) => {
555
- const result = {};
556
- const [child] = getAllBinaryNodeChildren(node);
557
- const nodeType = node.attrs.type;
558
- const from = jidNormalizedUser(node.attrs.from);
559
- switch (nodeType) {
560
- case 'privacy_token':
561
- const tokenList = getBinaryNodeChildren(child, 'token');
562
- for (const { attrs, content } of tokenList) {
563
- const jid = attrs.jid;
564
- ev.emit('chats.update', [
565
- {
566
- id: jid,
567
- tcToken: content
568
- }
569
- ]);
570
- logger.debug({ jid }, 'got privacy token update');
571
- }
572
- break;
573
- case 'newsletter':
574
- await handleNewsletterNotification(node);
575
- break;
576
- case 'mex':
577
- await handleMexNewsletterNotification(node);
578
- break;
579
- case 'w:gp2':
580
- // TODO: HANDLE PARTICIPANT_PN
581
- handleGroupNotification(node, child, result);
582
- break;
583
- case 'mediaretry':
584
- const event = decodeMediaRetryNode(node);
585
- ev.emit('messages.media-update', [event]);
586
- break;
587
- case 'encrypt':
588
- await handleEncryptNotification(node);
589
- break;
590
- case 'devices':
591
- const devices = getBinaryNodeChildren(child, 'device');
592
- if (areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
593
- areJidsSameUser(child.attrs.lid, authState.creds.me.lid)) {
594
- const deviceData = devices.map(d => ({ id: d.attrs.jid, lid: d.attrs.lid }));
595
- logger.info({ deviceData }, 'my own devices changed');
596
- }
597
- //TODO: drop a new event, add hashes
598
- break;
599
- case 'server_sync':
600
- const update = getBinaryNodeChild(node, 'collection');
601
- if (update) {
602
- const name = update.attrs.name;
603
- await resyncAppState([name], false);
604
- }
605
- break;
606
- case 'picture':
607
- const setPicture = getBinaryNodeChild(node, 'set');
608
- const delPicture = getBinaryNodeChild(node, 'delete');
609
- ev.emit('contacts.update', [
610
- {
611
- id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
612
- imgUrl: setPicture ? 'changed' : 'removed'
613
- }
614
- ]);
615
- if (isJidGroup(from)) {
616
- const node = setPicture || delPicture;
617
- result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
618
- if (setPicture) {
619
- result.messageStubParameters = [setPicture.attrs.id];
620
- }
621
- result.participant = node?.attrs.author;
622
- result.key = {
623
- ...(result.key || {}),
624
- participant: setPicture?.attrs.author
625
- };
626
- }
627
- break;
628
- case 'account_sync':
629
- if (child.tag === 'disappearing_mode') {
630
- const newDuration = +child.attrs.duration;
631
- const timestamp = +child.attrs.t;
632
- logger.info({ newDuration }, 'updated account disappearing mode');
633
- ev.emit('creds.update', {
634
- accountSettings: {
635
- ...authState.creds.accountSettings,
636
- defaultDisappearingMode: {
637
- ephemeralExpiration: newDuration,
638
- ephemeralSettingTimestamp: timestamp
639
- }
640
- }
641
- });
642
- }
643
- else if (child.tag === 'blocklist') {
644
- const blocklists = getBinaryNodeChildren(child, 'item');
645
- for (const { attrs } of blocklists) {
646
- const blocklist = [attrs.jid];
647
- const type = attrs.action === 'block' ? 'add' : 'remove';
648
- ev.emit('blocklist.update', { blocklist, type });
649
- }
650
- }
651
- break;
652
- case 'link_code_companion_reg':
653
- const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
654
- const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
655
- const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
656
- const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
657
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
658
- const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
659
- const random = randomBytes(32);
660
- const linkCodeSalt = randomBytes(32);
661
- const linkCodePairingExpanded = await hkdf(companionSharedKey, 32, {
662
- salt: linkCodeSalt,
663
- info: 'link_code_pairing_key_bundle_encryption_key'
664
- });
665
- const encryptPayload = Buffer.concat([
666
- Buffer.from(authState.creds.signedIdentityKey.public),
667
- primaryIdentityPublicKey,
668
- random
669
- ]);
670
- const encryptIv = randomBytes(12);
671
- const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
672
- const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
673
- const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
674
- const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
675
- authState.creds.advSecretKey = (await hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
676
- await query({
677
- tag: 'iq',
678
- attrs: {
679
- to: S_WHATSAPP_NET,
680
- type: 'set',
681
- id: sock.generateMessageTag(),
682
- xmlns: 'md'
683
- },
684
- content: [
685
- {
686
- tag: 'link_code_companion_reg',
687
- attrs: {
688
- jid: authState.creds.me.id,
689
- stage: 'companion_finish'
690
- },
691
- content: [
692
- {
693
- tag: 'link_code_pairing_wrapped_key_bundle',
694
- attrs: {},
695
- content: encryptedPayload
696
- },
697
- {
698
- tag: 'companion_identity_public',
699
- attrs: {},
700
- content: authState.creds.signedIdentityKey.public
701
- },
702
- {
703
- tag: 'link_code_pairing_ref',
704
- attrs: {},
705
- content: ref
706
- }
707
- ]
708
- }
709
- ]
710
- });
711
- authState.creds.registered = true;
712
- ev.emit('creds.update', authState.creds);
826
+ }
827
+ // Fallback to getMessage if not found in cache
828
+ if (!msg) {
829
+ msg = await getMessage({ ...key, id })
830
+ if (msg) {
831
+ logger.debug({ jid: remoteJid, id }, "found message via getMessage")
832
+ // Also mark as successful if found via getMessage
833
+ if (messageRetryManager) {
834
+ messageRetryManager.markRetrySuccess(id)
835
+ }
713
836
  }
714
- if (Object.keys(result).length) {
715
- return result;
837
+ }
838
+ msgs.push(msg)
839
+ }
840
+ // if it's the primary jid sending the request
841
+ // just re-send the message to everyone
842
+ // prevents the first message decryption failure
843
+ const sendToAll = !jidDecode(participant)?.device
844
+ // Check if we should recreate session for this retry
845
+ let shouldRecreateSession = false
846
+ let recreateReason = ""
847
+ if (enableAutoSessionRecreation && messageRetryManager) {
848
+ try {
849
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant)
850
+ const hasSession = await signalRepository.validateSession(participant)
851
+ const result = messageRetryManager.shouldRecreateSession(participant, retryCount, hasSession.exists)
852
+ shouldRecreateSession = result.recreate
853
+ recreateReason = result.reason
854
+ if (shouldRecreateSession) {
855
+ logger.debug({ participant, retryCount, reason: recreateReason }, "recreating session for outgoing retry")
856
+ await authState.keys.set({ session: { [sessionId]: null } })
716
857
  }
717
- };
718
- async function decipherLinkPublicKey(data) {
719
- const buffer = toRequiredBuffer(data);
720
- const salt = buffer.slice(0, 32);
721
- const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
722
- const iv = buffer.slice(32, 48);
723
- const payload = buffer.slice(48, 80);
724
- return aesDecryptCTR(payload, secretKey, iv);
858
+ } catch (error) {
859
+ logger.warn({ error, participant }, "failed to check session recreation for outgoing retry")
860
+ }
725
861
  }
726
- function toRequiredBuffer(data) {
727
- if (data === undefined) {
728
- throw new Boom('Invalid buffer', { statusCode: 400 });
862
+ await assertSessions([participant])
863
+ if (isJidGroup(remoteJid)) {
864
+ await authState.keys.set({ "sender-key-memory": { [remoteJid]: null } })
865
+ }
866
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, "forced new session for retry recp")
867
+ for (const [i, msg] of msgs.entries()) {
868
+ if (!ids[i]) continue
869
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
870
+ updateSendMessageAgainCount(ids[i], participant)
871
+ const msgRelayOpts = { messageId: ids[i] }
872
+ if (sendToAll) {
873
+ msgRelayOpts.useUserDevicesCache = false
874
+ } else {
875
+ msgRelayOpts.participant = {
876
+ jid: participant,
877
+ count: +retryNode.attrs.count,
878
+ }
729
879
  }
730
- return data instanceof Buffer ? data : Buffer.from(data);
880
+ await relayMessage(key.remoteJid, msg, msgRelayOpts)
881
+ } else {
882
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, "recv retry request, but message not available")
883
+ }
731
884
  }
732
- const willSendMessageAgain = async (id, participant) => {
733
- const key = `${id}:${participant}`;
734
- const retryCount = (await msgRetryCache.get(key)) || 0;
735
- return retryCount < maxMsgRetryCount;
736
- };
737
- const updateSendMessageAgainCount = async (id, participant) => {
738
- const key = `${id}:${participant}`;
739
- const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
740
- await msgRetryCache.set(key, newValue);
741
- };
742
- const sendMessagesAgain = async (key, ids, retryNode) => {
743
- const remoteJid = key.remoteJid;
744
- const participant = key.participant || remoteJid;
745
- const retryCount = +retryNode.attrs.count || 1;
746
- // Try to get messages from cache first, then fallback to getMessage
747
- const msgs = [];
748
- for (const id of ids) {
749
- let msg;
750
- // Try to get from retry cache first if enabled
751
- if (messageRetryManager) {
752
- const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
753
- if (cachedMsg) {
754
- msg = cachedMsg.message;
755
- logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
756
- // Mark retry as successful since we found the message
757
- messageRetryManager.markRetrySuccess(id);
758
- }
885
+ }
886
+ const handleReceipt = async (node) => {
887
+ const { attrs, content } = node
888
+ const isLid = attrs.from.includes("lid")
889
+ const isNodeFromMe = areJidsSameUser(
890
+ attrs.participant || attrs.from,
891
+ isLid ? authState.creds.me?.lid : authState.creds.me?.id,
892
+ )
893
+ const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient
894
+ const fromMe = !attrs.recipient || ((attrs.type === "retry" || attrs.type === "sender") && isNodeFromMe)
895
+ const key = {
896
+ remoteJid,
897
+ id: "",
898
+ fromMe,
899
+ participant: attrs.participant,
900
+ }
901
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
902
+ logger.debug({ remoteJid }, "ignoring receipt from jid")
903
+ await sendMessageAck(node)
904
+ return
905
+ }
906
+ const ids = [attrs.id]
907
+ if (Array.isArray(content)) {
908
+ const items = getBinaryNodeChildren(content[0], "item")
909
+ ids.push(...items.map((i) => i.attrs.id))
910
+ }
911
+ try {
912
+ await Promise.all([
913
+ processingMutex.mutex(async () => {
914
+ const status = getStatusFromReceiptType(attrs.type)
915
+ if (
916
+ typeof status !== "undefined" &&
917
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
918
+ // or another device of ours has read some messages
919
+ (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)
920
+ ) {
921
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
922
+ if (attrs.participant) {
923
+ const updateKey =
924
+ status === proto.WebMessageInfo.Status.DELIVERY_ACK ? "receiptTimestamp" : "readTimestamp"
925
+ ev.emit(
926
+ "message-receipt.update",
927
+ ids.map((id) => ({
928
+ key: { ...key, id },
929
+ receipt: {
930
+ userJid: jidNormalizedUser(attrs.participant),
931
+ [updateKey]: +attrs.t,
932
+ },
933
+ })),
934
+ )
935
+ }
936
+ } else {
937
+ ev.emit(
938
+ "messages.update",
939
+ ids.map((id) => ({
940
+ key: { ...key, id },
941
+ update: { status },
942
+ })),
943
+ )
759
944
  }
760
- // Fallback to getMessage if not found in cache
761
- if (!msg) {
762
- msg = await getMessage({ ...key, id });
763
- if (msg) {
764
- logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
765
- // Also mark as successful if found via getMessage
766
- if (messageRetryManager) {
767
- messageRetryManager.markRetrySuccess(id);
768
- }
945
+ }
946
+ if (attrs.type === "retry") {
947
+ // correctly set who is asking for the retry
948
+ key.participant = key.participant || attrs.from
949
+ const retryNode = getBinaryNodeChild(node, "retry")
950
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
951
+ if (key.fromMe) {
952
+ try {
953
+ updateSendMessageAgainCount(ids[0], key.participant)
954
+ logger.debug({ attrs, key }, "recv retry request")
955
+ await sendMessagesAgain(key, ids, retryNode)
956
+ } catch (error) {
957
+ logger.error(
958
+ { key, ids, trace: error instanceof Error ? error.stack : "Unknown error" },
959
+ "error in sending message again",
960
+ )
769
961
  }
962
+ } else {
963
+ logger.info({ attrs, key }, "recv retry for not fromMe message")
964
+ }
965
+ } else {
966
+ logger.info({ attrs, key }, "will not send message again, as sent too many times")
770
967
  }
771
- msgs.push(msg);
968
+ }
969
+ }),
970
+ ])
971
+ } finally {
972
+ await sendMessageAck(node)
973
+ }
974
+ }
975
+ const handleNotification = async (node) => {
976
+ const remoteJid = node.attrs.from
977
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
978
+ logger.debug({ remoteJid, id: node.attrs.id }, "ignored notification")
979
+ await sendMessageAck(node)
980
+ return
981
+ }
982
+ try {
983
+ await Promise.all([
984
+ processingMutex.mutex(async () => {
985
+ const msg = await processNotification(node)
986
+ if (msg) {
987
+ const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id)
988
+ const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node)
989
+ msg.key = {
990
+ remoteJid,
991
+ fromMe,
992
+ participant: node.attrs.participant,
993
+ participantAlt,
994
+ addressingMode,
995
+ id: node.attrs.id,
996
+ ...(msg.key || {}),
997
+ }
998
+ msg.participant ?? (msg.participant = node.attrs.participant)
999
+ msg.messageTimestamp = +node.attrs.t
1000
+ const fullMsg = proto.WebMessageInfo.fromObject(msg)
1001
+ await upsertMessage(fullMsg, "append")
1002
+ }
1003
+ }),
1004
+ ])
1005
+ } finally {
1006
+ await sendMessageAck(node)
1007
+ }
1008
+ }
1009
+
1010
+ const handleMessage = async (node) => {
1011
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
1012
+ logger.debug({ key: node.attrs.key }, "ignored message")
1013
+ await sendMessageAck(node, NACK_REASONS.UnhandledError)
1014
+ return
1015
+ }
1016
+
1017
+ const encNode = getBinaryNodeChild(node, "enc")
1018
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
1019
+ if (encNode && encNode.attrs.type === "msmsg") {
1020
+ logger.debug({ key: node.attrs.key }, "ignored msmsg")
1021
+ await sendMessageAck(node, NACK_REASONS.MissingMessageSecret)
1022
+ return
1023
+ }
1024
+
1025
+ const {
1026
+ fullMessage: msg,
1027
+ category,
1028
+ author,
1029
+ decrypt,
1030
+ } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || "", signalRepository, logger)
1031
+
1032
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt
1033
+ // store new mappings we didn't have before
1034
+ if (!!alt) {
1035
+ const altServer = jidDecode(alt)?.server
1036
+ const primaryJid = msg.key.participant || msg.key.remoteJid
1037
+ if (altServer === "lid") {
1038
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
1039
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }])
1040
+ await signalRepository.migrateSession(primaryJid, alt)
1041
+ }
1042
+ } else {
1043
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }])
1044
+ await signalRepository.migrateSession(alt, primaryJid)
1045
+ }
1046
+ }
1047
+
1048
+ if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
1049
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message)
1050
+ logger.debug(
1051
+ {
1052
+ jid: msg.key.remoteJid,
1053
+ id: msg.key.id,
1054
+ },
1055
+ "Added message to recent cache for retry receipts",
1056
+ )
1057
+ }
1058
+
1059
+ try {
1060
+ await processingMutex.mutex(async () => {
1061
+ await decrypt()
1062
+
1063
+ // message failed to decrypt
1064
+ if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT) {
1065
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
1066
+ return sendMessageAck(node, NACK_REASONS.ParsingError)
772
1067
  }
773
- // if it's the primary jid sending the request
774
- // just re-send the message to everyone
775
- // prevents the first message decryption failure
776
- const sendToAll = !jidDecode(participant)?.device;
777
- // Check if we should recreate session for this retry
778
- let shouldRecreateSession = false;
779
- let recreateReason = '';
780
- if (enableAutoSessionRecreation && messageRetryManager) {
1068
+
1069
+ const errorMessage = msg?.messageStubParameters?.[0] || ""
1070
+ const isPreKeyError = errorMessage.includes("PreKey")
1071
+ const isBadMacError = errorMessage.includes("Bad MAC")
1072
+ const isMessageCounterError = errorMessage.includes("Key used already or never filled")
1073
+
1074
+ logger.debug(`[handleMessage] Failed decryption - PreKey: ${isPreKeyError}, BadMAC: ${isBadMacError}`)
1075
+
1076
+ // IMMEDIATE SESSION RESET FOR BAD MAC - Don't wait for retry
1077
+ if (isBadMacError || isMessageCounterError) {
1078
+ const jidToReset = msg.key.participant || msg.key.remoteJid
1079
+ logger.error({ jid: jidToReset, error: errorMessage },
1080
+ "BAD MAC ERROR - Corrupted session detected, initiating emergency recovery")
1081
+
1082
+ // Execute recovery immediately (not in retry mutex)
1083
+ Promise.resolve().then(async () => {
781
1084
  try {
782
- const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
783
- const hasSession = await signalRepository.validateSession(participant);
784
- const result = messageRetryManager.shouldRecreateSession(participant, retryCount, hasSession.exists);
785
- shouldRecreateSession = result.recreate;
786
- recreateReason = result.reason;
787
- if (shouldRecreateSession) {
788
- logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry');
789
- await authState.keys.set({ session: { [sessionId]: null } });
790
- }
1085
+ // 1. Delete corrupted session NOW
1086
+ await signalRepository.deleteSession([jidToReset])
1087
+ logger.info({ jid: jidToReset }, "✓ Deleted corrupted session")
1088
+
1089
+ // 2. Force upload fresh pre-keys NOW
1090
+ await uploadPreKeys(MIN_PREKEY_COUNT)
1091
+ logger.info("✓ Uploaded fresh pre-keys")
1092
+
1093
+ // 3. Small delay for server sync
1094
+ await delay(500)
1095
+
1096
+ logger.info({ jid: jidToReset }, "✓ Emergency recovery complete - ready for retry")
1097
+ } catch (recoveryErr) {
1098
+ logger.error({ err: recoveryErr, jid: jidToReset }, "✗ Emergency recovery failed")
791
1099
  }
792
- catch (error) {
793
- logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
794
- }
795
- }
796
- await assertSessions([participant]);
797
- if (isJidGroup(remoteJid)) {
798
- await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
1100
+ }).catch(err => logger.error({ err }, "Recovery promise failed"))
799
1101
  }
800
- logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp');
801
- for (const [i, msg] of msgs.entries()) {
802
- if (!ids[i])
803
- continue;
804
- if (msg && (await willSendMessageAgain(ids[i], participant))) {
805
- updateSendMessageAgainCount(ids[i], participant);
806
- const msgRelayOpts = { messageId: ids[i] };
807
- if (sendToAll) {
808
- msgRelayOpts.useUserDevicesCache = false;
809
- }
810
- else {
811
- msgRelayOpts.participant = {
812
- jid: participant,
813
- count: +retryNode.attrs.count
814
- };
815
- }
816
- await relayMessage(key.remoteJid, msg, msgRelayOpts);
1102
+
1103
+ // Then proceed with normal retry mechanism
1104
+ retryMutex.mutex(async () => {
1105
+ try {
1106
+ if (!ws.isOpen) {
1107
+ logger.debug({ node }, "Connection closed, skipping retry")
1108
+ return
817
1109
  }
818
- else {
819
- logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
820
- }
821
- }
822
- };
823
- const handleReceipt = async (node) => {
824
- const { attrs, content } = node;
825
- const isLid = attrs.from.includes('lid');
826
- const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
827
- const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
828
- const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
829
- const key = {
830
- remoteJid,
831
- id: '',
832
- fromMe,
833
- participant: attrs.participant
834
- };
835
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
836
- logger.debug({ remoteJid }, 'ignoring receipt from jid');
837
- await sendMessageAck(node);
838
- return;
839
- }
840
- const ids = [attrs.id];
841
- if (Array.isArray(content)) {
842
- const items = getBinaryNodeChildren(content[0], 'item');
843
- ids.push(...items.map(i => i.attrs.id));
844
- }
845
- try {
846
- await Promise.all([
847
- processingMutex.mutex(async () => {
848
- const status = getStatusFromReceiptType(attrs.type);
849
- if (typeof status !== 'undefined' &&
850
- // basically, we only want to know when a message from us has been delivered to/read by the other person
851
- // or another device of ours has read some messages
852
- (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
853
- if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
854
- if (attrs.participant) {
855
- const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
856
- ev.emit('message-receipt.update', ids.map(id => ({
857
- key: { ...key, id },
858
- receipt: {
859
- userJid: jidNormalizedUser(attrs.participant),
860
- [updateKey]: +attrs.t
861
- }
862
- })));
863
- }
864
- }
865
- else {
866
- ev.emit('messages.update', ids.map(id => ({
867
- key: { ...key, id },
868
- update: { status }
869
- })));
870
- }
871
- }
872
- if (attrs.type === 'retry') {
873
- // correctly set who is asking for the retry
874
- key.participant = key.participant || attrs.from;
875
- const retryNode = getBinaryNodeChild(node, 'retry');
876
- if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
877
- if (key.fromMe) {
878
- try {
879
- updateSendMessageAgainCount(ids[0], key.participant);
880
- logger.debug({ attrs, key }, 'recv retry request');
881
- await sendMessagesAgain(key, ids, retryNode);
882
- }
883
- catch (error) {
884
- logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
885
- }
886
- }
887
- else {
888
- logger.info({ attrs, key }, 'recv retry for not fromMe message');
889
- }
890
- }
891
- else {
892
- logger.info({ attrs, key }, 'will not send message again, as sent too many times');
893
- }
894
- }
895
- })
896
- ]);
897
- }
898
- finally {
899
- await sendMessageAck(node);
900
- }
901
- };
902
- const handleNotification = async (node) => {
903
- const remoteJid = node.attrs.from;
904
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
905
- logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
906
- await sendMessageAck(node);
907
- return;
908
- }
909
- try {
910
- await Promise.all([
911
- processingMutex.mutex(async () => {
912
- const msg = await processNotification(node);
913
- if (msg) {
914
- const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
915
- const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node);
916
- msg.key = {
917
- remoteJid,
918
- fromMe,
919
- participant: node.attrs.participant,
920
- participantAlt,
921
- addressingMode,
922
- id: node.attrs.id,
923
- ...(msg.key || {})
924
- };
925
- msg.participant ?? (msg.participant = node.attrs.participant);
926
- msg.messageTimestamp = +node.attrs.t;
927
- const fullMsg = proto.WebMessageInfo.fromObject(msg);
928
- await upsertMessage(fullMsg, 'append');
929
- }
930
- })
931
- ]);
932
- }
933
- finally {
934
- await sendMessageAck(node);
935
- }
936
- };
937
- const handleMessage = async (node) => {
938
- if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
939
- logger.debug({ key: node.attrs.key }, 'ignored message');
940
- await sendMessageAck(node, NACK_REASONS.UnhandledError);
941
- return;
942
- }
943
- const encNode = getBinaryNodeChild(node, 'enc');
944
- // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
945
- if (encNode && encNode.attrs.type === 'msmsg') {
946
- logger.debug({ key: node.attrs.key }, 'ignored msmsg');
947
- await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
948
- return;
949
- }
950
- const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
951
- const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
952
- // store new mappings we didn't have before
953
- if (!!alt) {
954
- const altServer = jidDecode(alt)?.server;
955
- const primaryJid = msg.key.participant || msg.key.remoteJid;
956
- if (altServer === 'lid') {
957
- if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
958
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
959
- await signalRepository.migrateSession(primaryJid, alt);
960
- }
1110
+
1111
+ // Handle pre-key errors
1112
+ if (isPreKeyError) {
1113
+ logger.info({ error: errorMessage }, "PreKey error detected, uploading before retry")
1114
+ try {
1115
+ await uploadPreKeys(MIN_PREKEY_COUNT)
1116
+ await delay(1000)
1117
+ } catch (uploadErr) {
1118
+ logger.error({ uploadErr }, "Pre-key upload failed during retry")
1119
+ }
961
1120
  }
962
- else {
963
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
964
- await signalRepository.migrateSession(alt, primaryJid);
1121
+
1122
+ const encNode = getBinaryNodeChild(node, "enc")
1123
+ // Force include keys for Bad MAC or PreKey errors
1124
+ await sendRetryRequest(node, !encNode || isBadMacError || isMessageCounterError || isPreKeyError)
1125
+
1126
+ if (retryRequestDelayMs) {
1127
+ await delay(retryRequestDelayMs)
965
1128
  }
966
- }
967
- if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
968
- messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
969
- logger.debug({
970
- jid: msg.key.remoteJid,
971
- id: msg.key.id
972
- }, 'Added message to recent cache for retry receipts');
973
- }
974
- try {
975
- await processingMutex.mutex(async () => {
976
- await decrypt();
977
- // message failed to decrypt
978
- if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT) {
979
- if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
980
- return sendMessageAck(node, NACK_REASONS.ParsingError);
981
- }
982
- const errorMessage = msg?.messageStubParameters?.[0] || '';
983
- const isPreKeyError = errorMessage.includes('PreKey');
984
- logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
985
- // Handle both pre-key and normal retries in single mutex
986
- retryMutex.mutex(async () => {
987
- try {
988
- if (!ws.isOpen) {
989
- logger.debug({ node }, 'Connection closed, skipping retry');
990
- return;
991
- }
992
- // Handle pre-key errors with upload and delay
993
- if (isPreKeyError) {
994
- logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
995
- try {
996
- logger.debug('Uploading pre-keys for error recovery');
997
- await uploadPreKeys(5);
998
- logger.debug('Waiting for server to process new pre-keys');
999
- await delay(1000);
1000
- }
1001
- catch (uploadErr) {
1002
- logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
1003
- }
1004
- }
1005
- const encNode = getBinaryNodeChild(node, 'enc');
1006
- await sendRetryRequest(node, !encNode);
1007
- if (retryRequestDelayMs) {
1008
- await delay(retryRequestDelayMs);
1009
- }
1010
- }
1011
- catch (err) {
1012
- logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry');
1013
- // Still attempt retry even if pre-key upload failed
1014
- try {
1015
- const encNode = getBinaryNodeChild(node, 'enc');
1016
- await sendRetryRequest(node, !encNode);
1017
- }
1018
- catch (retryErr) {
1019
- logger.error({ retryErr }, 'Failed to send retry after error handling');
1020
- }
1021
- }
1022
- await sendMessageAck(node, NACK_REASONS.UnhandledError);
1023
- });
1024
- }
1025
- else {
1026
- // no type in the receipt => message delivered
1027
- let type = undefined;
1028
- let participant = msg.key.participant;
1029
- if (category === 'peer') {
1030
- // special peer message
1031
- type = 'peer_msg';
1032
- }
1033
- else if (msg.key.fromMe) {
1034
- // message was sent by us from a different device
1035
- type = 'sender';
1036
- // need to specially handle this case
1037
- if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1038
- participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1039
- }
1040
- }
1041
- else if (!sendActiveReceipts) {
1042
- type = 'inactive';
1043
- }
1044
- await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1045
- // send ack for history message
1046
- const isAnyHistoryMsg = getHistoryMsg(msg.message);
1047
- if (isAnyHistoryMsg) {
1048
- const jid = jidNormalizedUser(msg.key.remoteJid);
1049
- await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
1050
- }
1051
- }
1052
- cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1053
- await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1054
- });
1055
- }
1056
- catch (error) {
1057
- logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
1058
- }
1059
- };
1060
- const handleCall = async (node) => {
1061
- const { attrs } = node;
1062
- const [infoChild] = getAllBinaryNodeChildren(node);
1063
- const status = getCallStatusFromNode(infoChild);
1064
- if (!infoChild) {
1065
- throw new Boom('Missing call info in call node');
1066
- }
1067
- const callId = infoChild.attrs['call-id'];
1068
- const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1069
- const call = {
1070
- chatId: attrs.from,
1071
- from,
1072
- id: callId,
1073
- date: new Date(+attrs.t * 1000),
1074
- offline: !!attrs.offline,
1075
- status
1076
- };
1077
- if (status === 'offer') {
1078
- call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1079
- call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1080
- call.groupJid = infoChild.attrs['group-jid'];
1081
- await callOfferCache.set(call.id, call);
1082
- }
1083
- const existingCall = await callOfferCache.get(call.id);
1084
- // use existing call info to populate this event
1085
- if (existingCall) {
1086
- call.isVideo = existingCall.isVideo;
1087
- call.isGroup = existingCall.isGroup;
1088
- }
1089
- // delete data once call has ended
1090
- if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1091
- await callOfferCache.del(call.id);
1092
- }
1093
- ev.emit('call', [call]);
1094
- await sendMessageAck(node);
1095
- };
1096
- const handleBadAck = async ({ attrs }) => {
1097
- const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1098
- // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1099
- // // current hypothesis is that if pash is sent in the ack
1100
- // // it means -- the message hasn't reached all devices yet
1101
- // // we'll retry sending the message here
1102
- // if(attrs.phash) {
1103
- // logger.info({ attrs }, 'received phash in ack, resending message...')
1104
- // const msg = await getMessage(key)
1105
- // if(msg) {
1106
- // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1107
- // } else {
1108
- // logger.warn({ attrs }, 'could not send message again, as it was not found')
1109
- // }
1110
- // }
1111
- // error in acknowledgement,
1112
- // device could not display the message
1113
- if (attrs.error) {
1114
- logger.warn({ attrs }, 'received error in ack');
1115
- ev.emit('messages.update', [
1116
- {
1117
- key,
1118
- update: {
1119
- status: WAMessageStatus.ERROR,
1120
- messageStubParameters: [attrs.error]
1121
- }
1122
- }
1123
- ]);
1124
- }
1125
- };
1126
- /// processes a node with the given function
1127
- /// and adds the task to the existing buffer if we're buffering events
1128
- const processNodeWithBuffer = async (node, identifier, exec) => {
1129
- ev.buffer();
1130
- await execTask();
1131
- ev.flush();
1132
- function execTask() {
1133
- return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1134
- }
1135
- };
1136
- const makeOfflineNodeProcessor = () => {
1137
- const nodeProcessorMap = new Map([
1138
- ['message', handleMessage],
1139
- ['call', handleCall],
1140
- ['receipt', handleReceipt],
1141
- ['notification', handleNotification]
1142
- ]);
1143
- const nodes = [];
1144
- let isProcessing = false;
1145
- const enqueue = (type, node) => {
1146
- nodes.push({ type, node });
1147
- if (isProcessing) {
1148
- return;
1129
+ } catch (err) {
1130
+ logger.error({ err, isBadMacError, isPreKeyError }, "Retry mechanism failed")
1131
+ try {
1132
+ const encNode = getBinaryNodeChild(node, "enc")
1133
+ await sendRetryRequest(node, !encNode)
1134
+ } catch (retryErr) {
1135
+ logger.error({ retryErr }, "Final retry attempt failed")
1149
1136
  }
1150
- isProcessing = true;
1151
- const promise = async () => {
1152
- while (nodes.length && ws.isOpen) {
1153
- const { type, node } = nodes.shift();
1154
- const nodeProcessor = nodeProcessorMap.get(type);
1155
- if (!nodeProcessor) {
1156
- onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1157
- continue;
1158
- }
1159
- await nodeProcessor(node);
1160
- }
1161
- isProcessing = false;
1162
- };
1163
- promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1164
- };
1165
- return { enqueue };
1166
- };
1167
- const offlineNodeProcessor = makeOfflineNodeProcessor();
1168
- const processNode = (type, node, identifier, exec) => {
1169
- const isOffline = !!node.attrs.offline;
1170
- if (isOffline) {
1171
- offlineNodeProcessor.enqueue(type, node);
1137
+ }
1138
+
1139
+ await sendMessageAck(node, NACK_REASONS.UnhandledError)
1140
+ })
1141
+ } else {
1142
+ // no type in the receipt => message delivered
1143
+ let type = undefined
1144
+ let participant = msg.key.participant
1145
+ if (category === "peer") {
1146
+ // special peer message
1147
+ type = "peer_msg"
1148
+ } else if (msg.key.fromMe) {
1149
+ // message was sent by us from a different device
1150
+ type = "sender"
1151
+ // need to specially handle this case
1152
+ if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1153
+ participant = author // TODO: investigate sending receipts to LIDs and not PNs
1154
+ }
1155
+ } else if (!sendActiveReceipts) {
1156
+ type = "inactive"
1172
1157
  }
1173
- else {
1174
- processNodeWithBuffer(node, identifier, exec);
1158
+
1159
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type)
1160
+
1161
+ // send ack for history message
1162
+ const isAnyHistoryMsg = getHistoryMsg(msg.message)
1163
+ if (isAnyHistoryMsg) {
1164
+ const jid = jidNormalizedUser(msg.key.remoteJid)
1165
+ await sendReceipt(jid, undefined, [msg.key.id], "hist_sync")
1175
1166
  }
1176
- };
1177
- // recv a message
1178
- ws.on('CB:message', (node) => {
1179
- processNode('message', node, 'processing message', handleMessage);
1180
- });
1181
- ws.on('CB:call', async (node) => {
1182
- processNode('call', node, 'handling call', handleCall);
1183
- });
1184
- ws.on('CB:receipt', node => {
1185
- processNode('receipt', node, 'handling receipt', handleReceipt);
1186
- });
1187
- ws.on('CB:notification', async (node) => {
1188
- processNode('notification', node, 'handling notification', handleNotification);
1189
- });
1190
- ws.on('CB:ack,class:message', (node) => {
1191
- handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1192
- });
1193
- ev.on('call', ([call]) => {
1194
- if (!call) {
1195
- return;
1196
- }
1197
- // missed call + group call notification message generation
1198
- if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1199
- const msg = {
1200
- key: {
1201
- remoteJid: call.chatId,
1202
- id: call.id,
1203
- fromMe: false
1204
- },
1205
- messageTimestamp: unixTimestampSeconds(call.date)
1206
- };
1207
- if (call.status === 'timeout') {
1208
- if (call.isGroup) {
1209
- msg.messageStubType = call.isVideo
1210
- ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1211
- : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1212
- }
1213
- else {
1214
- msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
1215
- }
1216
- }
1217
- else {
1218
- msg.message = { call: { callKey: Buffer.from(call.id) } };
1219
- }
1220
- const protoMsg = proto.WebMessageInfo.fromObject(msg);
1221
- upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1167
+ }
1168
+
1169
+ cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid)
1170
+ await upsertMessage(msg, node.attrs.offline ? "append" : "notify")
1171
+ })
1172
+ } catch (error) {
1173
+ logger.error({ error, node: binaryNodeToString(node) }, "error in handling message")
1174
+ }
1175
+ }
1176
+
1177
+ const handleCall = async (node) => {
1178
+ const { attrs } = node
1179
+ const [infoChild] = getAllBinaryNodeChildren(node)
1180
+ const status = getCallStatusFromNode(infoChild)
1181
+ if (!infoChild) {
1182
+ throw new Boom("Missing call info in call node")
1183
+ }
1184
+ const callId = infoChild.attrs["call-id"]
1185
+ const from = infoChild.attrs.from || infoChild.attrs["call-creator"]
1186
+ const call = {
1187
+ chatId: attrs.from,
1188
+ from,
1189
+ id: callId,
1190
+ date: new Date(+attrs.t * 1000),
1191
+ offline: !!attrs.offline,
1192
+ status,
1193
+ }
1194
+ if (status === "offer") {
1195
+ call.isVideo = !!getBinaryNodeChild(infoChild, "video")
1196
+ call.isGroup = infoChild.attrs.type === "group" || !!infoChild.attrs["group-jid"]
1197
+ call.groupJid = infoChild.attrs["group-jid"]
1198
+ await callOfferCache.set(call.id, call)
1199
+ }
1200
+ const existingCall = await callOfferCache.get(call.id)
1201
+ // use existing call info to populate this event
1202
+ if (existingCall) {
1203
+ call.isVideo = existingCall.isVideo
1204
+ call.isGroup = existingCall.isGroup
1205
+ }
1206
+ // delete data once call has ended
1207
+ if (status === "reject" || status === "accept" || status === "timeout" || status === "terminate") {
1208
+ await callOfferCache.del(call.id)
1209
+ }
1210
+ ev.emit("call", [call])
1211
+ await sendMessageAck(node)
1212
+ }
1213
+ const handleBadAck = async ({ attrs }) => {
1214
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id }
1215
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1216
+ // // current hypothesis is that if pash is sent in the ack
1217
+ // // it means -- the message hasn't reached all devices yet
1218
+ // // we'll retry sending the message here
1219
+ // if(attrs.phash) {
1220
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
1221
+ // const msg = await getMessage(key)
1222
+ // if(msg) {
1223
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1224
+ // } else {
1225
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
1226
+ // }
1227
+ // }
1228
+ // error in acknowledgement,
1229
+ // device could not display the message
1230
+ if (attrs.error) {
1231
+ logger.warn({ attrs }, "received error in ack")
1232
+ ev.emit("messages.update", [
1233
+ {
1234
+ key,
1235
+ update: {
1236
+ status: WAMessageStatus.ERROR,
1237
+ messageStubParameters: [attrs.error],
1238
+ },
1239
+ },
1240
+ ])
1241
+ }
1242
+ }
1243
+ /// processes a node with the given function
1244
+ /// and adds the task to the existing buffer if we're buffering events
1245
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1246
+ ev.buffer()
1247
+ await execTask()
1248
+ ev.flush()
1249
+ function execTask() {
1250
+ return exec(node, false).catch((err) => onUnexpectedError(err, identifier))
1251
+ }
1252
+ }
1253
+ const makeOfflineNodeProcessor = () => {
1254
+ const nodeProcessorMap = new Map([
1255
+ ["message", handleMessage],
1256
+ ["call", handleCall],
1257
+ ["receipt", handleReceipt],
1258
+ ["notification", handleNotification],
1259
+ ])
1260
+ const nodes = []
1261
+ let isProcessing = false
1262
+ const enqueue = (type, node) => {
1263
+ nodes.push({ type, node })
1264
+ if (isProcessing) {
1265
+ return
1266
+ }
1267
+ isProcessing = true
1268
+ const promise = async () => {
1269
+ while (nodes.length && ws.isOpen) {
1270
+ const { type, node } = nodes.shift()
1271
+ const nodeProcessor = nodeProcessorMap.get(type)
1272
+ if (!nodeProcessor) {
1273
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), "processing offline node")
1274
+ continue
1275
+ }
1276
+ await nodeProcessor(node)
1222
1277
  }
1223
- });
1224
- ev.on('connection.update', ({ isOnline }) => {
1225
- if (typeof isOnline !== 'undefined') {
1226
- sendActiveReceipts = isOnline;
1227
- logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1278
+ isProcessing = false
1279
+ }
1280
+ promise().catch((error) => onUnexpectedError(error, "processing offline nodes"))
1281
+ }
1282
+ return { enqueue }
1283
+ }
1284
+ const offlineNodeProcessor = makeOfflineNodeProcessor()
1285
+ const processNode = (type, node, identifier, exec) => {
1286
+ const isOffline = !!node.attrs.offline
1287
+ if (isOffline) {
1288
+ offlineNodeProcessor.enqueue(type, node)
1289
+ } else {
1290
+ processNodeWithBuffer(node, identifier, exec)
1291
+ }
1292
+ }
1293
+ // recv a message
1294
+ ws.on("CB:message", (node) => {
1295
+ processNode("message", node, "processing message", handleMessage)
1296
+ })
1297
+ ws.on("CB:call", async (node) => {
1298
+ processNode("call", node, "handling call", handleCall)
1299
+ })
1300
+ ws.on("CB:receipt", (node) => {
1301
+ processNode("receipt", node, "handling receipt", handleReceipt)
1302
+ })
1303
+ ws.on("CB:notification", async (node) => {
1304
+ processNode("notification", node, "handling notification", handleNotification)
1305
+ })
1306
+ ws.on("CB:ack,class:message", (node) => {
1307
+ handleBadAck(node).catch((error) => onUnexpectedError(error, "handling bad ack"))
1308
+ })
1309
+ ev.on("call", ([call]) => {
1310
+ if (!call) {
1311
+ return
1312
+ }
1313
+ // missed call + group call notification message generation
1314
+ if (call.status === "timeout" || (call.status === "offer" && call.isGroup)) {
1315
+ const msg = {
1316
+ key: {
1317
+ remoteJid: call.chatId,
1318
+ id: call.id,
1319
+ fromMe: false,
1320
+ },
1321
+ messageTimestamp: unixTimestampSeconds(call.date),
1322
+ }
1323
+ if (call.status === "timeout") {
1324
+ if (call.isGroup) {
1325
+ msg.messageStubType = call.isVideo
1326
+ ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1327
+ : WAMessageStubType.CALL_MISSED_GROUP_VOICE
1328
+ } else {
1329
+ msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE
1228
1330
  }
1229
- });
1230
- return {
1231
- ...sock,
1232
- sendMessageAck,
1233
- sendRetryRequest,
1234
- rejectCall,
1235
- fetchMessageHistory,
1236
- requestPlaceholderResend,
1237
- messageRetryManager
1238
- };
1239
- };
1240
- //# sourceMappingURL=messages-recv.js.map
1331
+ } else {
1332
+ msg.message = { call: { callKey: Buffer.from(call.id) } }
1333
+ }
1334
+ const protoMsg = proto.WebMessageInfo.fromObject(msg)
1335
+ upsertMessage(protoMsg, call.offline ? "append" : "notify")
1336
+ }
1337
+ })
1338
+ ev.on("connection.update", ({ isOnline }) => {
1339
+ if (typeof isOnline !== "undefined") {
1340
+ sendActiveReceipts = isOnline
1341
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`)
1342
+ }
1343
+ })
1344
+ return {
1345
+ ...sock,
1346
+ sendMessageAck,
1347
+ sendRetryRequest,
1348
+ rejectCall,
1349
+ fetchMessageHistory,
1350
+ requestPlaceholderResend,
1351
+ messageRetryManager,
1352
+ }
1353
+ }
1354
+ //# sourceMappingURL=messages-recv.js.map