@realvare/based 2.7.62 → 2.7.71

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