@zetagoaurum-socket/wasocket 2.2.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +84 -67
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +3344 -0
  5. package/WAProto/index.d.ts +37016 -0
  6. package/WAProto/index.js +79296 -118676
  7. package/WASignalGroup/GroupProtocol.js +1697 -0
  8. package/WASignalGroup/ciphertext_message.js +16 -0
  9. package/WASignalGroup/group_cipher.js +120 -0
  10. package/WASignalGroup/group_session_builder.js +46 -0
  11. package/WASignalGroup/index.js +5 -0
  12. package/WASignalGroup/keyhelper.js +21 -0
  13. package/WASignalGroup/protobufs.js +3 -0
  14. package/WASignalGroup/queue_job.js +69 -0
  15. package/WASignalGroup/sender_chain_key.js +50 -0
  16. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  17. package/WASignalGroup/sender_key_message.js +92 -0
  18. package/WASignalGroup/sender_key_name.js +70 -0
  19. package/WASignalGroup/sender_key_record.js +56 -0
  20. package/WASignalGroup/sender_key_state.js +129 -0
  21. package/{lib/Signal/Group/sender-message-key.js → WASignalGroup/sender_message_key.js} +16 -6
  22. package/lib/Defaults/baileys-version.json +1 -1
  23. package/lib/Defaults/index.js +9 -50
  24. package/lib/Signal/libsignal.js +29 -51
  25. package/lib/Socket/business.d.ts +2 -3
  26. package/lib/Socket/chats.d.ts +28 -215
  27. package/lib/Socket/chats.js +70 -185
  28. package/lib/Socket/dugong.js +141 -432
  29. package/lib/Socket/groups.js +23 -20
  30. package/lib/Socket/index.js +15 -2
  31. package/lib/Socket/messages-recv.d.ts +55 -56
  32. package/lib/Socket/messages-recv.js +112 -370
  33. package/lib/Socket/messages-send.d.ts +2 -3
  34. package/lib/Socket/messages-send.js +368 -465
  35. package/lib/Socket/newsletter.js +28 -175
  36. package/lib/Socket/socket.js +174 -203
  37. package/lib/Socket/usync.d.ts +3 -3
  38. package/lib/Types/GroupMetadata.d.ts +0 -1
  39. package/lib/Types/Newsletter.d.ts +86 -97
  40. package/lib/Types/Newsletter.js +32 -38
  41. package/lib/Utils/chat-utils.js +3 -17
  42. package/lib/Utils/generics.js +31 -68
  43. package/lib/Utils/history.js +1 -6
  44. package/lib/Utils/link-preview.js +2 -5
  45. package/lib/Utils/messages-media.js +57 -145
  46. package/lib/Utils/messages.js +305 -89
  47. package/lib/Utils/signal.js +46 -48
  48. package/lib/Utils/use-multi-file-auth-state.js +6 -45
  49. package/lib/Utils/validate-connection.js +65 -91
  50. package/lib/WABinary/constants.d.ts +24 -27
  51. package/lib/WABinary/encode.js +123 -160
  52. package/lib/WABinary/generic-utils.d.ts +0 -2
  53. package/lib/WABinary/generic-utils.js +36 -124
  54. package/lib/WABinary/jid-utils.js +26 -5
  55. package/lib/WAUSync/Fall +1 -0
  56. package/lib/WAUSync/Protocols/Fal +1 -0
  57. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  58. package/lib/index.d.ts +0 -1
  59. package/lib/index.js +0 -9
  60. package/package.json +100 -105
  61. package/engine-requirements.js +0 -10
  62. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  63. package/lib/Signal/Group/ciphertext-message.js +0 -15
  64. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  65. package/lib/Signal/Group/group-session-builder.js +0 -64
  66. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  67. package/lib/Signal/Group/group_cipher.js +0 -96
  68. package/lib/Signal/Group/index.d.ts +0 -11
  69. package/lib/Signal/Group/index.js +0 -57
  70. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  71. package/lib/Signal/Group/keyhelper.js +0 -55
  72. package/lib/Signal/Group/queue-job.d.ts +0 -1
  73. package/lib/Signal/Group/queue-job.js +0 -57
  74. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  75. package/lib/Signal/Group/sender-chain-key.js +0 -34
  76. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  77. package/lib/Signal/Group/sender-key-distribution-message.js +0 -66
  78. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  79. package/lib/Signal/Group/sender-key-message.js +0 -69
  80. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  81. package/lib/Signal/Group/sender-key-name.js +0 -51
  82. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  83. package/lib/Signal/Group/sender-key-record.js +0 -53
  84. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  85. package/lib/Signal/Group/sender-key-state.js +0 -99
  86. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  87. package/lib/Socket/chats.js.bak +0 -981
  88. package/lib/Socket/dugong.d.ts +0 -254
  89. package/lib/Types/USync.d.ts +0 -25
  90. package/lib/Types/USync.js +0 -2
  91. package/lib/Utils/anti-crash.js +0 -20
  92. package/lib/Utils/auto-contact.js +0 -74
  93. package/lib/Utils/generics.js.bak +0 -433
  94. package/lib/Utils/validate-connection.js.bak +0 -237
@@ -6,147 +6,78 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.makeMessagesRecvSocket = void 0;
7
7
  const boom_1 = require("@hapi/boom");
8
8
  const crypto_1 = require("crypto");
9
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const node_cache_1 = __importDefault(require("node-cache"));
10
10
  const WAProto_1 = require("../../WAProto");
11
11
  const Defaults_1 = require("../Defaults");
12
12
  const Types_1 = require("../Types");
13
13
  const Utils_1 = require("../Utils");
14
+ const Utils_2 = require("../Utils");
14
15
  const make_mutex_1 = require("../Utils/make-mutex");
15
16
  const WABinary_1 = require("../WABinary");
16
17
  const groups_1 = require("./groups");
17
18
  const messages_send_1 = require("./messages-send");
18
- const { ContactManager } = require("../Utils/auto-contact");
19
19
  const makeMessagesRecvSocket = (config) => {
20
- const {
21
- logger,
22
- retryRequestDelayMs,
23
- maxMsgRetryCount,
24
- getMessage,
25
- shouldIgnoreJid
26
- } = config;
20
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
27
21
  const sock = (0, messages_send_1.makeMessagesSocket)(config);
28
- const {
29
- ev,
30
- authState,
31
- ws,
32
- processingMutex,
33
- signalRepository,
34
- query,
35
- upsertMessage,
36
- resyncAppState,
37
- groupMetadata,
38
- onUnexpectedError,
39
- assertSessions,
40
- sendNode,
41
- relayMessage,
42
- sendReceipt,
43
- uploadPreKeys,
44
- createParticipantNodes,
45
- getUSyncDevices,
46
- sendPeerDataOperationMessage
47
- } = sock;
22
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, getUSyncDevices, createParticipantNodes } = sock;
48
23
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
49
24
  const retryMutex = (0, make_mutex_1.makeMutex)();
50
25
  const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
51
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
26
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
52
27
  useClones: false
53
28
  });
54
29
  const callOfferCache = config.callOfferCache || new node_cache_1.default({
55
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
56
- useClones: false
57
- });
58
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
59
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
30
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER,
60
31
  useClones: false
61
32
  });
62
33
  let sendActiveReceipts = false;
63
- const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
34
+ const sendMessageAck = async ({ tag, attrs, content }) => {
64
35
  const stanza = {
65
36
  tag: 'ack',
66
37
  attrs: {
67
38
  id: attrs.id,
68
39
  to: attrs.from,
69
- class: tag
40
+ class: tag,
70
41
  }
71
- }
72
- if (!!errorCode) {
73
- stanza.attrs.error = errorCode.toString();
74
- }
42
+ };
75
43
  if (!!attrs.participant) {
76
44
  stanza.attrs.participant = attrs.participant;
77
45
  }
78
46
  if (!!attrs.recipient) {
79
47
  stanza.attrs.recipient = attrs.recipient;
80
48
  }
81
- if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
49
+ if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable'))) {
82
50
  stanza.attrs.type = attrs.type;
83
51
  }
84
52
  if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
85
53
  stanza.attrs.from = authState.creds.me.id;
86
54
  }
87
- logger.debug({
88
- recv: {
89
- tag,
90
- attrs
91
- },
92
- sent: stanza.attrs }, 'sent ack');
55
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
93
56
  await sendNode(stanza);
94
57
  };
95
58
  const offerCall = async (toJid, isVideo = false) => {
96
59
  const callId = (0, crypto_1.randomBytes)(16).toString('hex').toUpperCase().substring(0, 64);
97
60
  const offerContent = [];
98
- offerContent.push({
99
- tag: 'audio',
100
- attrs: {
101
- enc: 'opus',
102
- rate: '16000'
103
- }, content: undefined
104
- });
105
- offerContent.push({
106
- tag: 'audio',
107
- attrs: {
108
- enc: 'opus',
109
- rate: '8000'
110
- }, content: undefined
111
- });
61
+ offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '16000' }, content: undefined });
62
+ offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '8000' }, content: undefined });
112
63
  if (isVideo) {
113
64
  offerContent.push({
114
65
  tag: 'video',
115
- attrs: {
116
- orientation: '0',
117
- 'screen_width': '1920',
118
- 'screen_height': '1080',
119
- 'device_orientation': '0',
120
- enc: 'vp8',
121
- dec: 'vp8',
122
- }
66
+ attrs: { enc: 'vp8', dec: 'vp8', orientation: '0', 'screen_width': '1920', 'screen_height': '1080', 'device_orientation': '0' },
67
+ content: undefined
123
68
  });
124
69
  }
125
- offerContent.push({
126
- tag: 'net',
127
- attrs: {
128
- medium: '3'
129
- }, content: undefined
130
- });
131
- offerContent.push({
132
- tag: 'capability',
133
- attrs: {
134
- ver: '1'
135
- }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) });
136
- offerContent.push({
137
- tag: 'encopt',
138
- attrs: {
139
- keygen: '2'
140
- }, content: undefined
141
- })
70
+ offerContent.push({ tag: 'net', attrs: { medium: '3' }, content: undefined });
71
+ offerContent.push({ tag: 'capability', attrs: { ver: '1' }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) });
72
+ offerContent.push({ tag: 'encopt', attrs: { keygen: '2' }, content: undefined });
142
73
  const encKey = (0, crypto_1.randomBytes)(32);
143
74
  const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device));
144
75
  await assertSessions(devices, true);
145
76
  const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
146
77
  call: {
147
- callKey: encKey
78
+ callKey: new Uint8Array(encKey)
148
79
  }
149
- });
80
+ }, { count: '0' });
150
81
  offerContent.push({ tag: 'destination', attrs: {}, content: destinations });
151
82
  if (shouldIncludeDeviceIdentity) {
152
83
  offerContent.push({
@@ -158,6 +89,7 @@ const makeMessagesRecvSocket = (config) => {
158
89
  const stanza = ({
159
90
  tag: 'call',
160
91
  attrs: {
92
+ id: (0, Utils_1.generateMessageIDV2)(),
161
93
  to: toJid,
162
94
  },
163
95
  content: [{
@@ -171,9 +103,8 @@ const makeMessagesRecvSocket = (config) => {
171
103
  });
172
104
  await query(stanza);
173
105
  return {
174
- callId,
175
- toJid,
176
- isVideo,
106
+ id: callId,
107
+ to: toJid
177
108
  };
178
109
  };
179
110
  const rejectCall = async (callId, callFrom) => {
@@ -196,24 +127,16 @@ const makeMessagesRecvSocket = (config) => {
196
127
  await query(stanza);
197
128
  };
198
129
  const sendRetryRequest = async (node, forceIncludeKeys = false) => {
199
- const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
200
- const { key: msgKey } = fullMessage;
201
- const msgId = msgKey.id;
202
- const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
203
- let retryCount = msgRetryCache.get(key) || 0;
130
+ const msgId = node.attrs.id;
131
+ let retryCount = msgRetryCache.get(msgId) || 0;
204
132
  if (retryCount >= maxMsgRetryCount) {
205
133
  logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
206
- msgRetryCache.del(key);
134
+ msgRetryCache.del(msgId);
207
135
  return;
208
136
  }
209
137
  retryCount += 1;
210
- msgRetryCache.set(key, retryCount);
138
+ msgRetryCache.set(msgId, retryCount);
211
139
  const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
212
- if (retryCount === 1) {
213
- //request a resend via phone
214
- const msgId = await requestPlaceholderResend(msgKey);
215
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
216
- }
217
140
  const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
218
141
  await authState.keys.transaction(async () => {
219
142
  const receipt = {
@@ -292,8 +215,6 @@ const makeMessagesRecvSocket = (config) => {
292
215
  }
293
216
  };
294
217
  const handleGroupNotification = (participant, child, msg) => {
295
- var _a, _b, _c, _d;
296
- 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;
297
218
  switch (child === null || child === void 0 ? void 0 : child.tag) {
298
219
  case 'create':
299
220
  const metadata = (0, groups_1.extractGroupMetadata)(child);
@@ -319,11 +240,6 @@ const makeMessagesRecvSocket = (config) => {
319
240
  }
320
241
  };
321
242
  break;
322
- case 'modify':
323
- const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
324
- msg.messageStubParameters = oldNumber || [];
325
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
326
- break;
327
243
  case 'promote':
328
244
  case 'demote':
329
245
  case 'remove':
@@ -345,11 +261,6 @@ const makeMessagesRecvSocket = (config) => {
345
261
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
346
262
  msg.messageStubParameters = [child.attrs.subject];
347
263
  break;
348
- case 'description':
349
- 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();
350
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
351
- msg.messageStubParameters = description ? [description] : undefined;
352
- break;
353
264
  case 'announcement':
354
265
  case 'not_announcement':
355
266
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
@@ -378,66 +289,10 @@ const makeMessagesRecvSocket = (config) => {
378
289
  msg.messageStubParameters = [approvalMode.attrs.state];
379
290
  }
380
291
  break;
381
- case 'created_membership_requests':
382
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
383
- msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
384
- break;
385
- case 'revoked_membership_requests':
386
- const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
387
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
388
- msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
389
- break;
390
- break;
391
- default:
392
- // console.log("BAILEYS-DEBUG:", JSON.stringify({ ...child, content: Buffer.isBuffer(child.content) ? child.content.toString() : child.content, participant }, null, 2))
393
- }
394
- };
395
- const handleNewsletterNotification = (id, node) => {
396
- const messages = (0, WABinary_1.getBinaryNodeChild)(node, 'messages');
397
- const message = (0, WABinary_1.getBinaryNodeChild)(messages, 'message');
398
- const serverId = message.attrs.server_id;
399
- const reactionsList = (0, WABinary_1.getBinaryNodeChild)(message, 'reactions');
400
- const viewsList = (0, WABinary_1.getBinaryNodeChildren)(message, 'views_count');
401
- if (reactionsList) {
402
- const reactions = (0, WABinary_1.getBinaryNodeChildren)(reactionsList, 'reaction');
403
- if (reactions.length === 0) {
404
- ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { removed: true } });
405
- }
406
- reactions.forEach(item => {
407
- var _a, _b;
408
- 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) } });
409
- });
410
- }
411
- if (viewsList.length) {
412
- viewsList.forEach(item => {
413
- ev.emit('newsletter.view', { id, 'server_id': serverId, count: +item.attrs.count });
414
- });
415
- }
416
- };
417
- const handleMexNewsletterNotification = (id, node) => {
418
- var _a;
419
- const operation = node === null || node === void 0 ? void 0 : node.attrs.op_name;
420
- const content = JSON.parse((_a = node === null || node === void 0 ? void 0 : node.content) === null || _a === void 0 ? void 0 : _a.toString());
421
- let contentPath;
422
- if (operation === Types_1.MexOperations.PROMOTE || operation === Types_1.MexOperations.DEMOTE) {
423
- let action;
424
- if (operation === Types_1.MexOperations.PROMOTE) {
425
- action = 'promote';
426
- contentPath = content.data[Types_1.XWAPaths.PROMOTE];
427
- }
428
- if (operation === Types_1.MexOperations.DEMOTE) {
429
- action = 'demote';
430
- contentPath = content.data[Types_1.XWAPaths.DEMOTE];
431
- }
432
- ev.emit('newsletter-participants.update', { id, author: contentPath.actor.pn, user: contentPath.user.pn, new_role: contentPath.user_new_role, action });
433
- }
434
- if (operation === Types_1.MexOperations.UPDATE) {
435
- contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE];
436
- ev.emit('newsletter-settings.update', { id, update: contentPath.thread_metadata.settings });
437
292
  }
438
293
  };
439
294
  const processNotification = async (node) => {
440
- var _a, _b;
295
+ var _a, _b, _c;
441
296
  const result = {};
442
297
  const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
443
298
  const nodeType = node.attrs.type;
@@ -456,12 +311,6 @@ const makeMessagesRecvSocket = (config) => {
456
311
  logger.debug({ jid }, 'got privacy token update');
457
312
  }
458
313
  break;
459
- case 'newsletter':
460
- handleNewsletterNotification(node.attrs.from, child);
461
- break;
462
- case 'mex':
463
- handleMexNewsletterNotification(node.attrs.from, child);
464
- break;
465
314
  case 'w:gp2':
466
315
  handleGroupNotification(node.attrs.participant, child, result);
467
316
  break;
@@ -472,6 +321,9 @@ const makeMessagesRecvSocket = (config) => {
472
321
  case 'encrypt':
473
322
  await handleEncryptNotification(node);
474
323
  break;
324
+ case 'newsletter':
325
+ // TO DO
326
+ break;
475
327
  case 'devices':
476
328
  const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
477
329
  if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
@@ -490,7 +342,7 @@ const makeMessagesRecvSocket = (config) => {
490
342
  const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
491
343
  const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
492
344
  ev.emit('contacts.update', [{
493
- id: from || ((_b = (_a = (setPicture || delPicture)) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.hash) || '',
345
+ id: (0, WABinary_1.jidNormalizedUser)((_a = node === null || node === void 0 ? void 0 : node.attrs) === null || _a === void 0 ? void 0 : _a.jid) || ((_c = (_b = (setPicture || delPicture)) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.hash) || '',
494
346
  imgUrl: setPicture ? 'changed' : 'removed'
495
347
  }]);
496
348
  if ((0, WABinary_1.isJidGroup)(from)) {
@@ -535,11 +387,11 @@ const makeMessagesRecvSocket = (config) => {
535
387
  const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
536
388
  const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
537
389
  const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
538
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
390
+ const codePairingPublicKey = decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
539
391
  const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
540
392
  const random = (0, crypto_1.randomBytes)(32);
541
393
  const linkCodeSalt = (0, crypto_1.randomBytes)(32);
542
- const linkCodePairingExpanded = await (0, Utils_1.hkdf)(companionSharedKey, 32, {
394
+ const linkCodePairingExpanded = (0, Utils_1.hkdf)(companionSharedKey, 32, {
543
395
  salt: linkCodeSalt,
544
396
  info: 'link_code_pairing_key_bundle_encryption_key'
545
397
  });
@@ -549,7 +401,7 @@ const makeMessagesRecvSocket = (config) => {
549
401
  const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
550
402
  const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
551
403
  const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
552
- authState.creds.advSecretKey = (await (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
404
+ authState.creds.advSecretKey = (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' }).toString('base64');
553
405
  await query({
554
406
  tag: 'iq',
555
407
  attrs: {
@@ -592,10 +444,10 @@ const makeMessagesRecvSocket = (config) => {
592
444
  return result;
593
445
  }
594
446
  };
595
- async function decipherLinkPublicKey(data) {
447
+ function decipherLinkPublicKey(data) {
596
448
  const buffer = toRequiredBuffer(data);
597
449
  const salt = buffer.slice(0, 32);
598
- const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
450
+ const secretKey = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
599
451
  const iv = buffer.slice(32, 48);
600
452
  const payload = buffer.slice(48, 80);
601
453
  return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
@@ -618,7 +470,6 @@ const makeMessagesRecvSocket = (config) => {
618
470
  };
619
471
  const sendMessagesAgain = async (key, ids, retryNode) => {
620
472
  var _a;
621
- // todo: implement a cache to store the last 256 sent messages (copy whatsmeow)
622
473
  const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
623
474
  const remoteJid = key.remoteJid;
624
475
  const participant = key.participant || remoteJid;
@@ -631,7 +482,8 @@ const makeMessagesRecvSocket = (config) => {
631
482
  await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
632
483
  }
633
484
  logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
634
- for (const [i, msg] of msgs.entries()) {
485
+ for (let i = 0; i < msgs.length; i++) {
486
+ const msg = msgs[i];
635
487
  if (msg) {
636
488
  updateSendMessageAgainCount(ids[i], participant);
637
489
  const msgRelayOpts = { messageId: ids[i] };
@@ -657,7 +509,7 @@ const makeMessagesRecvSocket = (config) => {
657
509
  const isLid = attrs.from.includes('lid');
658
510
  const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(attrs.participant || 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);
659
511
  const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
660
- const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
512
+ const fromMe = !attrs.recipient || (attrs.type === 'retry' && isNodeFromMe);
661
513
  const key = {
662
514
  remoteJid,
663
515
  id: '',
@@ -674,63 +526,59 @@ const makeMessagesRecvSocket = (config) => {
674
526
  const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
675
527
  ids.push(...items.map(i => i.attrs.id));
676
528
  }
677
- try {
678
- await Promise.all([
679
- processingMutex.mutex(async () => {
680
- const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
681
- if (typeof status !== 'undefined' &&
682
- (
683
- // basically, we only want to know when a message from us has been delivered to/read by the other person
684
- // or another device of ours has read some messages
685
- status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
686
- !isNodeFromMe)) {
687
- if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
688
- if (attrs.participant) {
689
- const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
690
- ev.emit('message-receipt.update', ids.map(id => ({
691
- key: { ...key, id },
692
- receipt: {
693
- userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
694
- [updateKey]: +attrs.t
695
- }
696
- })));
697
- }
698
- }
699
- else {
700
- ev.emit('messages.update', ids.map(id => ({
529
+ await Promise.all([
530
+ processingMutex.mutex(async () => {
531
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
532
+ if (typeof status !== 'undefined' &&
533
+ (
534
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
535
+ // or another device of ours has read some messages
536
+ status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
537
+ !isNodeFromMe)) {
538
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
539
+ if (attrs.participant) {
540
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
541
+ ev.emit('message-receipt.update', ids.map(id => ({
701
542
  key: { ...key, id },
702
- update: { status }
543
+ receipt: {
544
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
545
+ [updateKey]: +attrs.t
546
+ }
703
547
  })));
704
548
  }
705
549
  }
706
- if (attrs.type === 'retry') {
707
- // correctly set who is asking for the retry
708
- key.participant = key.participant || attrs.from;
709
- const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
710
- if (willSendMessageAgain(ids[0], key.participant)) {
711
- if (key.fromMe) {
712
- try {
713
- logger.debug({ attrs, key }, 'recv retry request');
714
- await sendMessagesAgain(key, ids, retryNode);
715
- }
716
- catch (error) {
717
- logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
718
- }
550
+ else {
551
+ ev.emit('messages.update', ids.map(id => ({
552
+ key: { ...key, id },
553
+ update: { status }
554
+ })));
555
+ }
556
+ }
557
+ if (attrs.type === 'retry') {
558
+ // correctly set who is asking for the retry
559
+ key.participant = key.participant || attrs.from;
560
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
561
+ if (willSendMessageAgain(ids[0], key.participant)) {
562
+ if (key.fromMe) {
563
+ try {
564
+ logger.debug({ attrs, key }, 'recv retry request');
565
+ await sendMessagesAgain(key, ids, retryNode);
719
566
  }
720
- else {
721
- logger.info({ attrs, key }, 'recv retry for not fromMe message');
567
+ catch (error) {
568
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
722
569
  }
723
570
  }
724
571
  else {
725
- logger.info({ attrs, key }, 'will not send message again, as sent too many times');
572
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
726
573
  }
727
574
  }
728
- })
729
- ]);
730
- }
731
- finally {
732
- await sendMessageAck(node);
733
- }
575
+ else {
576
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
577
+ }
578
+ }
579
+ }),
580
+ sendMessageAck(node)
581
+ ]);
734
582
  };
735
583
  const handleNotification = async (node) => {
736
584
  const remoteJid = node.attrs.from;
@@ -739,31 +587,27 @@ const makeMessagesRecvSocket = (config) => {
739
587
  await sendMessageAck(node);
740
588
  return;
741
589
  }
742
- try {
743
- await Promise.all([
744
- processingMutex.mutex(async () => {
745
- var _a;
746
- const msg = await processNotification(node);
747
- if (msg) {
748
- const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
749
- msg.key = {
750
- remoteJid,
751
- fromMe,
752
- participant: node.attrs.participant,
753
- id: node.attrs.id,
754
- ...(msg.key || {})
755
- };
756
- (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
757
- msg.messageTimestamp = +node.attrs.t;
758
- const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
759
- await upsertMessage(fullMsg, 'append');
760
- }
761
- })
762
- ]);
763
- }
764
- finally {
765
- await sendMessageAck(node);
766
- }
590
+ await Promise.all([
591
+ processingMutex.mutex(async () => {
592
+ var _a;
593
+ const msg = await processNotification(node);
594
+ if (msg) {
595
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
596
+ msg.key = {
597
+ remoteJid,
598
+ fromMe,
599
+ participant: node.attrs.participant,
600
+ id: node.attrs.id,
601
+ ...(msg.key || {})
602
+ };
603
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
604
+ msg.messageTimestamp = +node.attrs.t;
605
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
606
+ await upsertMessage(fullMsg, 'append');
607
+ }
608
+ }),
609
+ sendMessageAck(node)
610
+ ]);
767
611
  };
768
612
  const handleMessage = async (node) => {
769
613
  var _a, _b, _c;
@@ -813,9 +657,6 @@ const makeMessagesRecvSocket = (config) => {
813
657
  }
814
658
  throw error;
815
659
  }
816
-
817
- // Auto Safe Contact
818
- ContactManager.checkAndSave(author || msg.key.remoteJid, { user: authState.creds.me });
819
660
  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) {
820
661
  msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
821
662
  }
@@ -897,54 +738,6 @@ const makeMessagesRecvSocket = (config) => {
897
738
  logger.error({ error, node }, 'error in handling message');
898
739
  }
899
740
  };
900
- const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
901
- var _a;
902
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
903
- throw new boom_1.Boom('Not authenticated');
904
- }
905
- const pdoMessage = {
906
- historySyncOnDemandRequest: {
907
- chatJid: oldestMsgKey.remoteJid,
908
- oldestMsgFromMe: oldestMsgKey.fromMe,
909
- oldestMsgId: oldestMsgKey.id,
910
- oldestMsgTimestampMs: oldestMsgTimestamp,
911
- onDemandMsgCount: count
912
- },
913
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
914
- };
915
- return sendPeerDataOperationMessage(pdoMessage);
916
- };
917
- const requestPlaceholderResend = async (messageKey) => {
918
- var _a;
919
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
920
- throw new boom_1.Boom('Not authenticated');
921
- }
922
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
923
- logger.debug({ messageKey }, 'already requested resend');
924
- return;
925
- }
926
- else {
927
- placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
928
- }
929
- await (0, Utils_1.delay)(5000);
930
- if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
931
- logger.debug({ messageKey }, 'message received while resend requested');
932
- return 'RESOLVED';
933
- }
934
- const pdoMessage = {
935
- placeholderMessageResendRequest: [{
936
- messageKey
937
- }],
938
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
939
- };
940
- setTimeout(() => {
941
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
942
- logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
943
- placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
944
- }
945
- }, 15000);
946
- return sendPeerDataOperationMessage(pdoMessage);
947
- };
948
741
  const handleCall = async (node) => {
949
742
  const { attrs } = node;
950
743
  const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
@@ -972,30 +765,22 @@ const makeMessagesRecvSocket = (config) => {
972
765
  call.isGroup = existingCall.isGroup;
973
766
  }
974
767
  // delete data once call has ended
975
- if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
768
+ if (status === 'reject' || status === 'accept' || status === 'timeout') {
976
769
  callOfferCache.del(call.id);
977
770
  }
978
771
  ev.emit('call', [call]);
979
772
  await sendMessageAck(node);
980
773
  };
981
774
  const handleBadAck = async ({ attrs }) => {
982
- const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id, 'server_id': attrs === null || attrs === void 0 ? void 0 : attrs.server_id };
775
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
983
776
  // current hypothesis is that if pash is sent in the ack
984
777
  // it means -- the message hasn't reached all devices yet
985
778
  // we'll retry sending the message here
986
779
  if (attrs.phash) {
987
780
  logger.info({ attrs }, 'received phash in ack, resending message...');
988
- const cacheKey = `${key.remoteJid}:${key.id}`;
989
- if ((msgRetryCache.get(cacheKey) || 0) >= maxMsgRetryCount) {
990
- logger.warn({ attrs }, 'reached max retry count, not sending message again');
991
- msgRetryCache.del(cacheKey);
992
- return;
993
- }
994
- const retryCount = msgRetryCache.get(cacheKey) || 0;
995
781
  const msg = await getMessage(key);
996
782
  if (msg) {
997
783
  await relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
998
- msgRetryCache.set(cacheKey, retryCount + 1);
999
784
  }
1000
785
  else {
1001
786
  logger.warn({ attrs }, 'could not send message again, as it was not found');
@@ -1025,63 +810,22 @@ const makeMessagesRecvSocket = (config) => {
1025
810
  await execTask();
1026
811
  ev.flush();
1027
812
  function execTask() {
1028
- return exec(node, false)
813
+ return exec(node)
1029
814
  .catch(err => onUnexpectedError(err, identifier));
1030
815
  }
1031
816
  };
1032
- const makeOfflineNodeProcessor = () => {
1033
- const nodeProcessorMap = new Map([
1034
- ['message', handleMessage],
1035
- ['call', handleCall],
1036
- ['receipt', handleReceipt],
1037
- ['notification', handleNotification]
1038
- ]);
1039
- const nodes = [];
1040
- let isProcessing = false;
1041
- const enqueue = (type, node) => {
1042
- nodes.push({ type, node });
1043
- if (isProcessing) {
1044
- return;
1045
- }
1046
- isProcessing = true;
1047
- const promise = async () => {
1048
- while (nodes.length && ws.isOpen) {
1049
- const { type, node } = nodes.shift();
1050
- const nodeProcessor = nodeProcessorMap.get(type);
1051
- if (!nodeProcessor) {
1052
- onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1053
- continue;
1054
- }
1055
- await nodeProcessor(node);
1056
- }
1057
- isProcessing = false;
1058
- };
1059
- promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1060
- };
1061
- return { enqueue };
1062
- };
1063
- const offlineNodeProcessor = makeOfflineNodeProcessor();
1064
- const processNode = (type, node, identifier, exec) => {
1065
- const isOffline = !!node.attrs.offline;
1066
- if (isOffline) {
1067
- offlineNodeProcessor.enqueue(type, node);
1068
- }
1069
- else {
1070
- processNodeWithBuffer(node, identifier, exec);
1071
- }
1072
- };
1073
817
  // recv a message
1074
818
  ws.on('CB:message', (node) => {
1075
- processNode('message', node, 'processing message', handleMessage);
819
+ processNodeWithBuffer(node, 'processing message', handleMessage);
1076
820
  });
1077
821
  ws.on('CB:call', async (node) => {
1078
- processNode('call', node, 'handling call', handleCall);
822
+ processNodeWithBuffer(node, 'handling call', handleCall);
1079
823
  });
1080
824
  ws.on('CB:receipt', node => {
1081
- processNode('receipt', node, 'handling receipt', handleReceipt);
825
+ processNodeWithBuffer(node, 'handling receipt', handleReceipt);
1082
826
  });
1083
827
  ws.on('CB:notification', async (node) => {
1084
- processNode('notification', node, 'handling notification', handleNotification);
828
+ processNodeWithBuffer(node, 'handling notification', handleNotification);
1085
829
  });
1086
830
  ws.on('CB:ack,class:message', (node) => {
1087
831
  handleBadAck(node)
@@ -1123,10 +867,8 @@ const makeMessagesRecvSocket = (config) => {
1123
867
  ...sock,
1124
868
  sendMessageAck,
1125
869
  sendRetryRequest,
1126
- rejectCall,
1127
870
  offerCall,
1128
- fetchMessageHistory,
1129
- requestPlaceholderResend,
871
+ rejectCall
1130
872
  };
1131
873
  };
1132
874
  exports.makeMessagesRecvSocket = makeMessagesRecvSocket;