@queenanya/baileys 6.5.8

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 (149) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +960 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +2879 -0
  5. package/WAProto/index.d.ts +32245 -0
  6. package/WAProto/index.js +87831 -0
  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/readme.md +6 -0
  16. package/WASignalGroup/sender_chain_key.js +50 -0
  17. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  18. package/WASignalGroup/sender_key_message.js +92 -0
  19. package/WASignalGroup/sender_key_name.js +70 -0
  20. package/WASignalGroup/sender_key_record.js +56 -0
  21. package/WASignalGroup/sender_key_state.js +129 -0
  22. package/WASignalGroup/sender_message_key.js +39 -0
  23. package/lib/Defaults/baileys-version.json +3 -0
  24. package/lib/Defaults/index.d.ts +283 -0
  25. package/lib/Defaults/index.js +115 -0
  26. package/lib/Defaults/phonenumber-mcc.json +223 -0
  27. package/lib/Signal/libsignal.d.ts +3 -0
  28. package/lib/Signal/libsignal.js +152 -0
  29. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  30. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  31. package/lib/Socket/Client/index.d.ts +3 -0
  32. package/lib/Socket/Client/index.js +19 -0
  33. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  34. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  35. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  36. package/lib/Socket/Client/web-socket-client.js +62 -0
  37. package/lib/Socket/business.d.ts +126 -0
  38. package/lib/Socket/business.js +259 -0
  39. package/lib/Socket/chats.d.ts +75 -0
  40. package/lib/Socket/chats.js +842 -0
  41. package/lib/Socket/groups.d.ts +107 -0
  42. package/lib/Socket/groups.js +291 -0
  43. package/lib/Socket/index.d.ts +128 -0
  44. package/lib/Socket/index.js +10 -0
  45. package/lib/Socket/messages-recv.d.ts +115 -0
  46. package/lib/Socket/messages-recv.js +725 -0
  47. package/lib/Socket/messages-send.d.ts +112 -0
  48. package/lib/Socket/messages-send.js +660 -0
  49. package/lib/Socket/registration.d.ts +223 -0
  50. package/lib/Socket/registration.js +166 -0
  51. package/lib/Socket/socket.d.ts +42 -0
  52. package/lib/Socket/socket.js +587 -0
  53. package/lib/Store/index.d.ts +3 -0
  54. package/lib/Store/index.js +10 -0
  55. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  56. package/lib/Store/make-cache-manager-store.js +83 -0
  57. package/lib/Store/make-in-memory-store.d.ts +117 -0
  58. package/lib/Store/make-in-memory-store.js +437 -0
  59. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  60. package/lib/Store/make-ordered-dictionary.js +81 -0
  61. package/lib/Store/object-repository.d.ts +10 -0
  62. package/lib/Store/object-repository.js +27 -0
  63. package/lib/Types/Auth.d.ts +108 -0
  64. package/lib/Types/Auth.js +2 -0
  65. package/lib/Types/Call.d.ts +12 -0
  66. package/lib/Types/Call.js +2 -0
  67. package/lib/Types/Chat.d.ts +102 -0
  68. package/lib/Types/Chat.js +4 -0
  69. package/lib/Types/Contact.d.ts +18 -0
  70. package/lib/Types/Contact.js +2 -0
  71. package/lib/Types/Events.d.ts +152 -0
  72. package/lib/Types/Events.js +2 -0
  73. package/lib/Types/GroupMetadata.d.ts +44 -0
  74. package/lib/Types/GroupMetadata.js +2 -0
  75. package/lib/Types/Label.d.ts +35 -0
  76. package/lib/Types/Label.js +27 -0
  77. package/lib/Types/LabelAssociation.d.ts +29 -0
  78. package/lib/Types/LabelAssociation.js +9 -0
  79. package/lib/Types/Message.d.ts +255 -0
  80. package/lib/Types/Message.js +9 -0
  81. package/lib/Types/Product.d.ts +78 -0
  82. package/lib/Types/Product.js +2 -0
  83. package/lib/Types/Signal.d.ts +57 -0
  84. package/lib/Types/Signal.js +2 -0
  85. package/lib/Types/Socket.d.ts +109 -0
  86. package/lib/Types/Socket.js +2 -0
  87. package/lib/Types/State.d.ts +27 -0
  88. package/lib/Types/State.js +2 -0
  89. package/lib/Types/index.d.ts +54 -0
  90. package/lib/Types/index.js +39 -0
  91. package/lib/Utils/auth-utils.d.ts +18 -0
  92. package/lib/Utils/auth-utils.js +204 -0
  93. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  94. package/lib/Utils/baileys-event-stream.js +63 -0
  95. package/lib/Utils/business.d.ts +22 -0
  96. package/lib/Utils/business.js +234 -0
  97. package/lib/Utils/chat-utils.d.ts +71 -0
  98. package/lib/Utils/chat-utils.js +710 -0
  99. package/lib/Utils/crypto.d.ts +41 -0
  100. package/lib/Utils/crypto.js +151 -0
  101. package/lib/Utils/decode-wa-message.d.ts +19 -0
  102. package/lib/Utils/decode-wa-message.js +160 -0
  103. package/lib/Utils/event-buffer.d.ts +35 -0
  104. package/lib/Utils/event-buffer.js +514 -0
  105. package/lib/Utils/generics.d.ts +93 -0
  106. package/lib/Utils/generics.js +366 -0
  107. package/lib/Utils/history.d.ts +15 -0
  108. package/lib/Utils/history.js +91 -0
  109. package/lib/Utils/index.d.ts +17 -0
  110. package/lib/Utils/index.js +33 -0
  111. package/lib/Utils/link-preview.d.ts +21 -0
  112. package/lib/Utils/link-preview.js +93 -0
  113. package/lib/Utils/logger.d.ts +4 -0
  114. package/lib/Utils/logger.js +7 -0
  115. package/lib/Utils/lt-hash.d.ts +12 -0
  116. package/lib/Utils/lt-hash.js +51 -0
  117. package/lib/Utils/make-mutex.d.ts +7 -0
  118. package/lib/Utils/make-mutex.js +43 -0
  119. package/lib/Utils/messages-media.d.ts +107 -0
  120. package/lib/Utils/messages-media.js +680 -0
  121. package/lib/Utils/messages.d.ts +76 -0
  122. package/lib/Utils/messages.js +762 -0
  123. package/lib/Utils/noise-handler.d.ts +20 -0
  124. package/lib/Utils/noise-handler.js +142 -0
  125. package/lib/Utils/process-message.d.ts +41 -0
  126. package/lib/Utils/process-message.js +297 -0
  127. package/lib/Utils/signal.d.ts +32 -0
  128. package/lib/Utils/signal.js +151 -0
  129. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  130. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  131. package/lib/Utils/validate-connection.d.ts +11 -0
  132. package/lib/Utils/validate-connection.js +187 -0
  133. package/lib/WABinary/constants.d.ts +27 -0
  134. package/lib/WABinary/constants.js +40 -0
  135. package/lib/WABinary/decode.d.ts +7 -0
  136. package/lib/WABinary/decode.js +252 -0
  137. package/lib/WABinary/encode.d.ts +3 -0
  138. package/lib/WABinary/encode.js +228 -0
  139. package/lib/WABinary/generic-utils.d.ts +15 -0
  140. package/lib/WABinary/generic-utils.js +110 -0
  141. package/lib/WABinary/index.d.ts +5 -0
  142. package/lib/WABinary/index.js +21 -0
  143. package/lib/WABinary/jid-utils.d.ts +27 -0
  144. package/lib/WABinary/jid-utils.js +56 -0
  145. package/lib/WABinary/types.d.ts +18 -0
  146. package/lib/WABinary/types.js +2 -0
  147. package/lib/index.d.ts +10 -0
  148. package/lib/index.js +29 -0
  149. package/package.json +113 -0
@@ -0,0 +1,725 @@
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("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 Utils_2 = require("../Utils");
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, getMessage, shouldIgnoreJid } = config;
21
+ const sock = (0, messages_send_1.makeMessagesSocket)(config);
22
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, } = 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
+ let sendActiveReceipts = false;
34
+ const sendMessageAck = async ({ tag, attrs }) => {
35
+ const stanza = {
36
+ tag: 'ack',
37
+ attrs: {
38
+ id: attrs.id,
39
+ to: attrs.from,
40
+ class: tag,
41
+ }
42
+ };
43
+ if (!!attrs.participant) {
44
+ stanza.attrs.participant = attrs.participant;
45
+ }
46
+ if (!!attrs.recipient) {
47
+ stanza.attrs.recipient = attrs.recipient;
48
+ }
49
+ if (tag !== 'message' && attrs.type) {
50
+ stanza.attrs.type = attrs.type;
51
+ }
52
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
53
+ await sendNode(stanza);
54
+ };
55
+ const rejectCall = async (callId, callFrom) => {
56
+ const stanza = ({
57
+ tag: 'call',
58
+ attrs: {
59
+ from: authState.creds.me.id,
60
+ to: callFrom,
61
+ },
62
+ content: [{
63
+ tag: 'reject',
64
+ attrs: {
65
+ 'call-id': callId,
66
+ 'call-creator': callFrom,
67
+ count: '0',
68
+ },
69
+ content: undefined,
70
+ }],
71
+ });
72
+ await query(stanza);
73
+ };
74
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
75
+ const msgId = node.attrs.id;
76
+ let retryCount = msgRetryCache.get(msgId) || 0;
77
+ if (retryCount >= 5) {
78
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
79
+ msgRetryCache.del(msgId);
80
+ return;
81
+ }
82
+ retryCount += 1;
83
+ msgRetryCache.set(msgId, retryCount);
84
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
85
+ const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
86
+ await authState.keys.transaction(async () => {
87
+ const receipt = {
88
+ tag: 'receipt',
89
+ attrs: {
90
+ id: msgId,
91
+ type: 'retry',
92
+ to: node.attrs.from
93
+ },
94
+ content: [
95
+ {
96
+ tag: 'retry',
97
+ attrs: {
98
+ count: retryCount.toString(),
99
+ id: node.attrs.id,
100
+ t: node.attrs.t,
101
+ v: '1'
102
+ }
103
+ },
104
+ {
105
+ tag: 'registration',
106
+ attrs: {},
107
+ content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
108
+ }
109
+ ]
110
+ };
111
+ if (node.attrs.recipient) {
112
+ receipt.attrs.recipient = node.attrs.recipient;
113
+ }
114
+ if (node.attrs.participant) {
115
+ receipt.attrs.participant = node.attrs.participant;
116
+ }
117
+ if (retryCount > 1 || forceIncludeKeys) {
118
+ const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
119
+ const [keyId] = Object.keys(preKeys);
120
+ const key = preKeys[+keyId];
121
+ const content = receipt.content;
122
+ content.push({
123
+ tag: 'keys',
124
+ attrs: {},
125
+ content: [
126
+ { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
127
+ { tag: 'identity', attrs: {}, content: identityKey.public },
128
+ (0, Utils_1.xmppPreKey)(key, +keyId),
129
+ (0, Utils_1.xmppSignedPreKey)(signedPreKey),
130
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
131
+ ]
132
+ });
133
+ ev.emit('creds.update', update);
134
+ }
135
+ await sendNode(receipt);
136
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
137
+ });
138
+ };
139
+ const handleEncryptNotification = async (node) => {
140
+ const from = node.attrs.from;
141
+ if (from === WABinary_1.S_WHATSAPP_NET) {
142
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
143
+ const count = +countChild.attrs.value;
144
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
145
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
146
+ if (shouldUploadMorePreKeys) {
147
+ await uploadPreKeys();
148
+ }
149
+ }
150
+ else {
151
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
152
+ if (identityNode) {
153
+ logger.info({ jid: from }, 'identity changed');
154
+ // not handling right now
155
+ // signal will override new identity anyway
156
+ }
157
+ else {
158
+ logger.info({ node }, 'unknown encrypt notification');
159
+ }
160
+ }
161
+ };
162
+ const handleGroupNotification = (participant, child, msg) => {
163
+ switch (child === null || child === void 0 ? void 0 : child.tag) {
164
+ case 'create':
165
+ const metadata = (0, groups_1.extractGroupMetadata)(child);
166
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
167
+ msg.messageStubParameters = [metadata.subject];
168
+ msg.key = { participant: metadata.owner };
169
+ ev.emit('chats.upsert', [{
170
+ id: metadata.id,
171
+ name: metadata.subject,
172
+ conversationTimestamp: metadata.creation,
173
+ }]);
174
+ ev.emit('groups.upsert', [{
175
+ ...metadata,
176
+ author: participant
177
+ }]);
178
+ break;
179
+ case 'ephemeral':
180
+ case 'not_ephemeral':
181
+ msg.message = {
182
+ protocolMessage: {
183
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
184
+ ephemeralExpiration: +(child.attrs.expiration || 0)
185
+ }
186
+ };
187
+ break;
188
+ case 'promote':
189
+ case 'demote':
190
+ case 'remove':
191
+ case 'add':
192
+ case 'leave':
193
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
194
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
195
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
196
+ if (participants.length === 1 &&
197
+ // if recv. "remove" message and sender removed themselves
198
+ // mark as left
199
+ (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
200
+ child.tag === 'remove') {
201
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
202
+ }
203
+ msg.messageStubParameters = participants;
204
+ break;
205
+ case 'subject':
206
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
207
+ msg.messageStubParameters = [child.attrs.subject];
208
+ break;
209
+ case 'announcement':
210
+ case 'not_announcement':
211
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
212
+ msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off'];
213
+ break;
214
+ case 'locked':
215
+ case 'unlocked':
216
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
217
+ msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off'];
218
+ break;
219
+ case 'invite':
220
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
221
+ msg.messageStubParameters = [child.attrs.code];
222
+ break;
223
+ }
224
+ };
225
+ const processNotification = async (node) => {
226
+ const result = {};
227
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
228
+ const nodeType = node.attrs.type;
229
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
230
+ switch (nodeType) {
231
+ case 'privacy_token':
232
+ const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
233
+ for (const { attrs, content } of tokenList) {
234
+ const jid = attrs.jid;
235
+ ev.emit('chats.update', [
236
+ {
237
+ id: jid,
238
+ tcToken: content
239
+ }
240
+ ]);
241
+ logger.debug({ jid }, 'got privacy token update');
242
+ }
243
+ break;
244
+ case 'w:gp2':
245
+ handleGroupNotification(node.attrs.participant, child, result);
246
+ break;
247
+ case 'mediaretry':
248
+ const event = (0, Utils_1.decodeMediaRetryNode)(node);
249
+ ev.emit('messages.media-update', [event]);
250
+ break;
251
+ case 'encrypt':
252
+ await handleEncryptNotification(node);
253
+ break;
254
+ case 'devices':
255
+ const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
256
+ if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
257
+ const deviceJids = devices.map(d => d.attrs.jid);
258
+ logger.info({ deviceJids }, 'got my own devices');
259
+ }
260
+ break;
261
+ case 'server_sync':
262
+ const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
263
+ if (update) {
264
+ const name = update.attrs.name;
265
+ await resyncAppState([name], false);
266
+ }
267
+ break;
268
+ case 'picture':
269
+ const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
270
+ const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
271
+ ev.emit('contacts.update', [{
272
+ id: from,
273
+ imgUrl: setPicture ? 'changed' : null
274
+ }]);
275
+ if ((0, WABinary_1.isJidGroup)(from)) {
276
+ const node = setPicture || delPicture;
277
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
278
+ if (setPicture) {
279
+ result.messageStubParameters = [setPicture.attrs.id];
280
+ }
281
+ result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
282
+ result.key = {
283
+ ...result.key || {},
284
+ participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
285
+ };
286
+ }
287
+ break;
288
+ case 'account_sync':
289
+ if (child.tag === 'disappearing_mode') {
290
+ const newDuration = +child.attrs.duration;
291
+ const timestamp = +child.attrs.t;
292
+ logger.info({ newDuration }, 'updated account disappearing mode');
293
+ ev.emit('creds.update', {
294
+ accountSettings: {
295
+ ...authState.creds.accountSettings,
296
+ defaultDisappearingMode: {
297
+ ephemeralExpiration: newDuration,
298
+ ephemeralSettingTimestamp: timestamp,
299
+ },
300
+ }
301
+ });
302
+ }
303
+ else if (child.tag === 'blocklist') {
304
+ const blocklists = (0, WABinary_1.getBinaryNodeChildren)(child, 'item');
305
+ for (const { attrs } of blocklists) {
306
+ const blocklist = [attrs.jid];
307
+ const type = (attrs.action === 'block') ? 'add' : 'remove';
308
+ ev.emit('blocklist.update', { blocklist, type });
309
+ }
310
+ }
311
+ break;
312
+ case 'link_code_companion_reg':
313
+ const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg');
314
+ const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
315
+ const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
316
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
317
+ const codePairingPublicKey = decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
318
+ const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
319
+ const random = (0, crypto_1.randomBytes)(32);
320
+ const linkCodeSalt = (0, crypto_1.randomBytes)(32);
321
+ const linkCodePairingExpanded = (0, Utils_1.hkdf)(companionSharedKey, 32, {
322
+ salt: linkCodeSalt,
323
+ info: 'link_code_pairing_key_bundle_encryption_key'
324
+ });
325
+ const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
326
+ const encryptIv = (0, crypto_1.randomBytes)(12);
327
+ const encrypted = (0, Utils_1.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
328
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
329
+ const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
330
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
331
+ authState.creds.advSecretKey = (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' }).toString('base64');
332
+ await query({
333
+ tag: 'iq',
334
+ attrs: {
335
+ to: WABinary_1.S_WHATSAPP_NET,
336
+ type: 'set',
337
+ id: sock.generateMessageTag(),
338
+ xmlns: 'md'
339
+ },
340
+ content: [
341
+ {
342
+ tag: 'link_code_companion_reg',
343
+ attrs: {
344
+ jid: authState.creds.me.id,
345
+ stage: 'companion_finish',
346
+ },
347
+ content: [
348
+ {
349
+ tag: 'link_code_pairing_wrapped_key_bundle',
350
+ attrs: {},
351
+ content: encryptedPayload
352
+ },
353
+ {
354
+ tag: 'companion_identity_public',
355
+ attrs: {},
356
+ content: authState.creds.signedIdentityKey.public
357
+ },
358
+ {
359
+ tag: 'link_code_pairing_ref',
360
+ attrs: {},
361
+ content: ref
362
+ }
363
+ ]
364
+ }
365
+ ]
366
+ });
367
+ authState.creds.registered = true;
368
+ ev.emit('creds.update', authState.creds);
369
+ }
370
+ if (Object.keys(result).length) {
371
+ return result;
372
+ }
373
+ };
374
+ function decipherLinkPublicKey(data) {
375
+ const buffer = toRequiredBuffer(data);
376
+ const salt = buffer.slice(0, 32);
377
+ const secretKey = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
378
+ const iv = buffer.slice(32, 48);
379
+ const payload = buffer.slice(48, 80);
380
+ return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
381
+ }
382
+ function toRequiredBuffer(data) {
383
+ if (data === undefined) {
384
+ throw new boom_1.Boom('Invalid buffer', { statusCode: 400 });
385
+ }
386
+ return data instanceof Buffer ? data : Buffer.from(data);
387
+ }
388
+ const willSendMessageAgain = (id, participant) => {
389
+ const key = `${id}:${participant}`;
390
+ const retryCount = msgRetryCache.get(key) || 0;
391
+ return retryCount < 5;
392
+ };
393
+ const updateSendMessageAgainCount = (id, participant) => {
394
+ const key = `${id}:${participant}`;
395
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
396
+ msgRetryCache.set(key, newValue);
397
+ };
398
+ const sendMessagesAgain = async (key, ids, retryNode) => {
399
+ var _a;
400
+ const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
401
+ const remoteJid = key.remoteJid;
402
+ const participant = key.participant || remoteJid;
403
+ // if it's the primary jid sending the request
404
+ // just re-send the message to everyone
405
+ // prevents the first message decryption failure
406
+ const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
407
+ await assertSessions([participant], true);
408
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
409
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
410
+ }
411
+ logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
412
+ for (let i = 0; i < msgs.length; i++) {
413
+ const msg = msgs[i];
414
+ if (msg) {
415
+ updateSendMessageAgainCount(ids[i], participant);
416
+ const msgRelayOpts = { messageId: ids[i] };
417
+ if (sendToAll) {
418
+ msgRelayOpts.useUserDevicesCache = false;
419
+ }
420
+ else {
421
+ msgRelayOpts.participant = {
422
+ jid: participant,
423
+ count: +retryNode.attrs.count
424
+ };
425
+ }
426
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
427
+ }
428
+ else {
429
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
430
+ }
431
+ }
432
+ };
433
+ const handleReceipt = async (node) => {
434
+ var _a;
435
+ const { attrs, content } = node;
436
+ const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(attrs.participant || attrs.from, (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id);
437
+ const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
438
+ const fromMe = !attrs.recipient || (attrs.type === 'retry' && isNodeFromMe);
439
+ const key = {
440
+ remoteJid,
441
+ id: '',
442
+ fromMe,
443
+ participant: attrs.participant
444
+ };
445
+ if (shouldIgnoreJid(remoteJid)) {
446
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
447
+ await sendMessageAck(node);
448
+ return;
449
+ }
450
+ const ids = [attrs.id];
451
+ if (Array.isArray(content)) {
452
+ const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
453
+ ids.push(...items.map(i => i.attrs.id));
454
+ }
455
+ await Promise.all([
456
+ processingMutex.mutex(async () => {
457
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
458
+ if (typeof status !== 'undefined' &&
459
+ (
460
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
461
+ // or another device of ours has read some messages
462
+ status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
463
+ !isNodeFromMe)) {
464
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
465
+ if (attrs.participant) {
466
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
467
+ ev.emit('message-receipt.update', ids.map(id => ({
468
+ key: { ...key, id },
469
+ receipt: {
470
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
471
+ [updateKey]: +attrs.t
472
+ }
473
+ })));
474
+ }
475
+ }
476
+ else {
477
+ ev.emit('messages.update', ids.map(id => ({
478
+ key: { ...key, id },
479
+ update: { status }
480
+ })));
481
+ }
482
+ }
483
+ if (attrs.type === 'retry') {
484
+ // correctly set who is asking for the retry
485
+ key.participant = key.participant || attrs.from;
486
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
487
+ if (willSendMessageAgain(ids[0], key.participant)) {
488
+ if (key.fromMe) {
489
+ try {
490
+ logger.debug({ attrs, key }, 'recv retry request');
491
+ await sendMessagesAgain(key, ids, retryNode);
492
+ }
493
+ catch (error) {
494
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
495
+ }
496
+ }
497
+ else {
498
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
499
+ }
500
+ }
501
+ else {
502
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
503
+ }
504
+ }
505
+ }),
506
+ sendMessageAck(node)
507
+ ]);
508
+ };
509
+ const handleNotification = async (node) => {
510
+ const remoteJid = node.attrs.from;
511
+ if (shouldIgnoreJid(remoteJid)) {
512
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
513
+ await sendMessageAck(node);
514
+ return;
515
+ }
516
+ await Promise.all([
517
+ processingMutex.mutex(async () => {
518
+ var _a;
519
+ const msg = await processNotification(node);
520
+ if (msg) {
521
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
522
+ msg.key = {
523
+ remoteJid,
524
+ fromMe,
525
+ participant: node.attrs.participant,
526
+ id: node.attrs.id,
527
+ ...(msg.key || {})
528
+ };
529
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
530
+ msg.messageTimestamp = +node.attrs.t;
531
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
532
+ await upsertMessage(fullMsg, 'append');
533
+ }
534
+ }),
535
+ sendMessageAck(node)
536
+ ]);
537
+ };
538
+ const handleMessage = async (node) => {
539
+ const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, signalRepository, logger);
540
+ if (shouldIgnoreJid(msg.key.remoteJid)) {
541
+ logger.debug({ key: msg.key }, 'ignored message');
542
+ await sendMessageAck(node);
543
+ return;
544
+ }
545
+ await Promise.all([
546
+ processingMutex.mutex(async () => {
547
+ await decrypt();
548
+ // message failed to decrypt
549
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
550
+ retryMutex.mutex(async () => {
551
+ if (ws.isOpen) {
552
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
553
+ await sendRetryRequest(node, !encNode);
554
+ if (retryRequestDelayMs) {
555
+ await (0, Utils_1.delay)(retryRequestDelayMs);
556
+ }
557
+ }
558
+ else {
559
+ logger.debug({ node }, 'connection closed, ignoring retry req');
560
+ }
561
+ });
562
+ }
563
+ else {
564
+ // no type in the receipt => message delivered
565
+ let type = undefined;
566
+ let participant = msg.key.participant;
567
+ if (category === 'peer') { // special peer message
568
+ type = 'peer_msg';
569
+ }
570
+ else if (msg.key.fromMe) { // message was sent by us from a different device
571
+ type = 'sender';
572
+ // need to specially handle this case
573
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
574
+ participant = author;
575
+ }
576
+ }
577
+ else if (!sendActiveReceipts) {
578
+ type = 'inactive';
579
+ }
580
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
581
+ // send ack for history message
582
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
583
+ if (isAnyHistoryMsg) {
584
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
585
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
586
+ }
587
+ }
588
+ (0, Utils_2.cleanMessage)(msg, authState.creds.me.id);
589
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
590
+ }),
591
+ sendMessageAck(node)
592
+ ]);
593
+ };
594
+ const handleCall = async (node) => {
595
+ const { attrs } = node;
596
+ const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
597
+ const callId = infoChild.attrs['call-id'];
598
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
599
+ const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
600
+ const call = {
601
+ chatId: attrs.from,
602
+ from,
603
+ id: callId,
604
+ date: new Date(+attrs.t * 1000),
605
+ offline: !!attrs.offline,
606
+ status,
607
+ };
608
+ if (status === 'offer') {
609
+ call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
610
+ call.isGroup = infoChild.attrs.type === 'group';
611
+ callOfferCache.set(call.id, call);
612
+ }
613
+ const existingCall = callOfferCache.get(call.id);
614
+ // use existing call info to populate this event
615
+ if (existingCall) {
616
+ call.isVideo = existingCall.isVideo;
617
+ call.isGroup = existingCall.isGroup;
618
+ }
619
+ // delete data once call has ended
620
+ if (status === 'reject' || status === 'accept' || status === 'timeout') {
621
+ callOfferCache.del(call.id);
622
+ }
623
+ ev.emit('call', [call]);
624
+ await sendMessageAck(node);
625
+ };
626
+ const handleBadAck = async ({ attrs }) => {
627
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
628
+ // current hypothesis is that if pash is sent in the ack
629
+ // it means -- the message hasn't reached all devices yet
630
+ // we'll retry sending the message here
631
+ if (attrs.phash) {
632
+ logger.info({ attrs }, 'received phash in ack, resending message...');
633
+ const msg = await getMessage(key);
634
+ if (msg) {
635
+ await relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
636
+ }
637
+ else {
638
+ logger.warn({ attrs }, 'could not send message again, as it was not found');
639
+ }
640
+ }
641
+ // error in acknowledgement,
642
+ // device could not display the message
643
+ if (attrs.error) {
644
+ logger.warn({ attrs }, 'received error in ack');
645
+ ev.emit('messages.update', [
646
+ {
647
+ key,
648
+ update: {
649
+ status: Types_1.WAMessageStatus.ERROR,
650
+ messageStubParameters: [
651
+ attrs.error
652
+ ]
653
+ }
654
+ }
655
+ ]);
656
+ }
657
+ };
658
+ /// processes a node with the given function
659
+ /// and adds the task to the existing buffer if we're buffering events
660
+ const processNodeWithBuffer = async (node, identifier, exec) => {
661
+ ev.buffer();
662
+ await execTask();
663
+ ev.flush();
664
+ function execTask() {
665
+ return exec(node)
666
+ .catch(err => onUnexpectedError(err, identifier));
667
+ }
668
+ };
669
+ // recv a message
670
+ ws.on('CB:message', (node) => {
671
+ processNodeWithBuffer(node, 'processing message', handleMessage);
672
+ });
673
+ ws.on('CB:call', async (node) => {
674
+ processNodeWithBuffer(node, 'handling call', handleCall);
675
+ });
676
+ ws.on('CB:receipt', node => {
677
+ processNodeWithBuffer(node, 'handling receipt', handleReceipt);
678
+ });
679
+ ws.on('CB:notification', async (node) => {
680
+ processNodeWithBuffer(node, 'handling notification', handleNotification);
681
+ });
682
+ ws.on('CB:ack,class:message', (node) => {
683
+ handleBadAck(node)
684
+ .catch(error => onUnexpectedError(error, 'handling bad ack'));
685
+ });
686
+ ev.on('call', ([call]) => {
687
+ // missed call + group call notification message generation
688
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
689
+ const msg = {
690
+ key: {
691
+ remoteJid: call.chatId,
692
+ id: call.id,
693
+ fromMe: false
694
+ },
695
+ messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
696
+ };
697
+ if (call.status === 'timeout') {
698
+ if (call.isGroup) {
699
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
700
+ }
701
+ else {
702
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
703
+ }
704
+ }
705
+ else {
706
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
707
+ }
708
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
709
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
710
+ }
711
+ });
712
+ ev.on('connection.update', ({ isOnline }) => {
713
+ if (typeof isOnline !== 'undefined') {
714
+ sendActiveReceipts = isOnline;
715
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
716
+ }
717
+ });
718
+ return {
719
+ ...sock,
720
+ sendMessageAck,
721
+ sendRetryRequest,
722
+ rejectCall
723
+ };
724
+ };
725
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;