@vinzsocket/baileys 2.8.10 → 2.8.30

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