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