@d0v3riz/baileys 6.7.12 → 6.7.17

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 (161) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +35 -1267
  3. package/WAProto/index.d.ts +16106 -2739
  4. package/WAProto/index.js +128593 -73944
  5. package/engine-requirements.js +10 -0
  6. package/lib/Defaults/baileys-version.json +3 -3
  7. package/lib/Defaults/index.d.ts +51 -53
  8. package/lib/Defaults/index.js +105 -106
  9. package/lib/Signal/libsignal.d.ts +3 -3
  10. package/lib/Signal/libsignal.js +161 -152
  11. package/lib/Socket/Client/index.d.ts +2 -2
  12. package/lib/Socket/Client/index.js +18 -18
  13. package/lib/Socket/Client/types.d.ts +15 -17
  14. package/lib/Socket/Client/types.js +13 -13
  15. package/lib/Socket/Client/websocket.d.ts +12 -12
  16. package/lib/Socket/Client/websocket.js +62 -62
  17. package/lib/Socket/business.d.ts +146 -148
  18. package/lib/Socket/business.js +260 -260
  19. package/lib/Socket/chats.d.ts +85 -84
  20. package/lib/Socket/chats.js +880 -846
  21. package/lib/Socket/groups.d.ts +124 -123
  22. package/lib/Socket/groups.js +314 -314
  23. package/lib/Socket/index.d.ts +146 -148
  24. package/lib/Socket/index.js +10 -10
  25. package/lib/Socket/messages-recv.d.ts +135 -135
  26. package/lib/Socket/messages-recv.js +920 -913
  27. package/lib/Socket/messages-send.d.ts +130 -129
  28. package/lib/Socket/messages-send.js +683 -673
  29. package/lib/Socket/socket.d.ts +42 -45
  30. package/lib/Socket/socket.js +622 -622
  31. package/lib/Socket/usync.d.ts +36 -38
  32. package/lib/Socket/usync.js +70 -70
  33. package/lib/Types/Auth.d.ts +103 -105
  34. package/lib/Types/Auth.js +2 -2
  35. package/lib/Types/Call.d.ts +13 -13
  36. package/lib/Types/Call.js +2 -2
  37. package/lib/Types/Chat.d.ts +112 -107
  38. package/lib/Types/Chat.js +4 -4
  39. package/lib/Types/Contact.d.ts +19 -19
  40. package/lib/Types/Contact.js +2 -2
  41. package/lib/Types/Events.d.ts +172 -172
  42. package/lib/Types/Events.js +2 -2
  43. package/lib/Types/GroupMetadata.d.ts +56 -56
  44. package/lib/Types/GroupMetadata.js +2 -2
  45. package/lib/Types/Label.d.ts +46 -46
  46. package/lib/Types/Label.js +27 -27
  47. package/lib/Types/LabelAssociation.d.ts +29 -29
  48. package/lib/Types/LabelAssociation.js +9 -9
  49. package/lib/Types/Message.d.ts +269 -273
  50. package/lib/Types/Message.js +7 -9
  51. package/lib/Types/Product.d.ts +78 -78
  52. package/lib/Types/Product.js +2 -2
  53. package/lib/Types/Signal.d.ts +57 -57
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.d.ts +121 -118
  56. package/lib/Types/Socket.js +2 -2
  57. package/lib/Types/State.d.ts +27 -27
  58. package/lib/Types/State.js +2 -2
  59. package/lib/Types/USync.d.ts +25 -25
  60. package/lib/Types/USync.js +2 -2
  61. package/lib/Types/index.d.ts +63 -63
  62. package/lib/Types/index.js +41 -41
  63. package/lib/Utils/auth-utils.d.ts +18 -18
  64. package/lib/Utils/auth-utils.js +200 -200
  65. package/lib/Utils/baileys-event-stream.d.ts +16 -16
  66. package/lib/Utils/baileys-event-stream.js +63 -63
  67. package/lib/Utils/business.d.ts +22 -22
  68. package/lib/Utils/business.js +234 -234
  69. package/lib/Utils/chat-utils.d.ts +70 -72
  70. package/lib/Utils/chat-utils.js +745 -745
  71. package/lib/Utils/crypto.d.ts +40 -42
  72. package/lib/Utils/crypto.js +193 -153
  73. package/lib/Utils/decode-wa-message.d.ts +36 -36
  74. package/lib/Utils/decode-wa-message.js +205 -205
  75. package/lib/Utils/event-buffer.d.ts +35 -35
  76. package/lib/Utils/event-buffer.js +520 -520
  77. package/lib/Utils/generics.d.ts +90 -94
  78. package/lib/Utils/generics.js +398 -421
  79. package/lib/Utils/history.d.ts +19 -19
  80. package/lib/Utils/history.js +94 -94
  81. package/lib/Utils/index.d.ts +17 -17
  82. package/lib/Utils/index.js +33 -33
  83. package/lib/Utils/link-preview.d.ts +21 -21
  84. package/lib/Utils/link-preview.js +126 -116
  85. package/lib/Utils/logger.d.ts +11 -4
  86. package/lib/Utils/logger.js +7 -7
  87. package/lib/Utils/lt-hash.d.ts +12 -12
  88. package/lib/Utils/lt-hash.js +51 -51
  89. package/lib/Utils/make-mutex.d.ts +7 -7
  90. package/lib/Utils/make-mutex.js +44 -44
  91. package/lib/Utils/messages-media.d.ts +104 -108
  92. package/lib/Utils/messages-media.js +677 -667
  93. package/lib/Utils/messages.d.ts +75 -78
  94. package/lib/Utils/messages.js +765 -762
  95. package/lib/Utils/noise-handler.d.ts +19 -21
  96. package/lib/Utils/noise-handler.js +150 -150
  97. package/lib/Utils/process-message.d.ts +41 -42
  98. package/lib/Utils/process-message.js +382 -371
  99. package/lib/Utils/signal.d.ts +33 -33
  100. package/lib/Utils/signal.js +153 -153
  101. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -12
  102. package/lib/Utils/use-multi-file-auth-state.js +125 -94
  103. package/lib/Utils/validate-connection.d.ts +10 -10
  104. package/lib/Utils/validate-connection.js +175 -175
  105. package/lib/WABinary/constants.d.ts +27 -27
  106. package/lib/WABinary/constants.js +40 -40
  107. package/lib/WABinary/decode.d.ts +6 -8
  108. package/lib/WABinary/decode.js +264 -254
  109. package/lib/WABinary/encode.d.ts +2 -4
  110. package/lib/WABinary/encode.js +252 -234
  111. package/lib/WABinary/generic-utils.d.ts +14 -16
  112. package/lib/WABinary/generic-utils.js +110 -110
  113. package/lib/WABinary/index.d.ts +5 -5
  114. package/lib/WABinary/index.js +21 -21
  115. package/lib/WABinary/jid-utils.d.ts +33 -31
  116. package/lib/WABinary/jid-utils.js +66 -62
  117. package/lib/WABinary/types.d.ts +18 -18
  118. package/lib/WABinary/types.js +2 -2
  119. package/lib/WAM/BinaryInfo.d.ts +8 -18
  120. package/lib/WAM/BinaryInfo.js +13 -13
  121. package/lib/WAM/constants.d.ts +39 -39
  122. package/lib/WAM/constants.js +15350 -15350
  123. package/lib/WAM/encode.d.ts +2 -4
  124. package/lib/WAM/encode.js +155 -155
  125. package/lib/WAM/index.d.ts +3 -3
  126. package/lib/WAM/index.js +19 -19
  127. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -9
  128. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -32
  129. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -22
  130. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -57
  131. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -12
  132. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -30
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -12
  134. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -42
  135. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  136. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  137. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  138. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  139. package/lib/WAUSync/Protocols/index.d.ts +4 -4
  140. package/lib/WAUSync/Protocols/index.js +20 -20
  141. package/lib/WAUSync/USyncQuery.d.ts +28 -26
  142. package/lib/WAUSync/USyncQuery.js +89 -79
  143. package/lib/WAUSync/USyncUser.d.ts +12 -10
  144. package/lib/WAUSync/USyncUser.js +26 -22
  145. package/lib/WAUSync/index.d.ts +3 -3
  146. package/lib/WAUSync/index.js +19 -19
  147. package/lib/index.d.ts +11 -12
  148. package/lib/index.js +30 -31
  149. package/package.json +27 -35
  150. package/WAProto/GenerateStatics.sh +0 -4
  151. package/WAProto/WAProto.proto +0 -3344
  152. package/lib/Store/index.d.ts +0 -3
  153. package/lib/Store/index.js +0 -10
  154. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  155. package/lib/Store/make-cache-manager-store.js +0 -83
  156. package/lib/Store/make-in-memory-store.d.ts +0 -118
  157. package/lib/Store/make-in-memory-store.js +0 -420
  158. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  159. package/lib/Store/make-ordered-dictionary.js +0 -81
  160. package/lib/Store/object-repository.d.ts +0 -10
  161. package/lib/Store/object-repository.js +0 -27
@@ -1,913 +1,920 @@
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, sendPeerDataOperationMessage, } = sock;
23
- /** this mutex ensures that each retryRequest will wait for the previous one to finish */
24
- const retryMutex = (0, make_mutex_1.makeMutex)();
25
- const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
26
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
27
- useClones: false
28
- });
29
- const callOfferCache = config.callOfferCache || new node_cache_1.default({
30
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER,
31
- useClones: false
32
- });
33
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
34
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
35
- useClones: false
36
- });
37
- let sendActiveReceipts = false;
38
- const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
39
- const stanza = {
40
- tag: 'ack',
41
- attrs: {
42
- id: attrs.id,
43
- to: attrs.from,
44
- class: tag
45
- }
46
- };
47
- if (!!errorCode) {
48
- stanza.attrs.error = errorCode.toString();
49
- }
50
- if (!!attrs.participant) {
51
- stanza.attrs.participant = attrs.participant;
52
- }
53
- if (!!attrs.recipient) {
54
- stanza.attrs.recipient = attrs.recipient;
55
- }
56
- if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
57
- stanza.attrs.type = attrs.type;
58
- }
59
- if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
60
- stanza.attrs.from = authState.creds.me.id;
61
- }
62
- logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
63
- await sendNode(stanza);
64
- };
65
- const rejectCall = async (callId, callFrom) => {
66
- const stanza = ({
67
- tag: 'call',
68
- attrs: {
69
- from: authState.creds.me.id,
70
- to: callFrom,
71
- },
72
- content: [{
73
- tag: 'reject',
74
- attrs: {
75
- 'call-id': callId,
76
- 'call-creator': callFrom,
77
- count: '0',
78
- },
79
- content: undefined,
80
- }],
81
- });
82
- await query(stanza);
83
- };
84
- const sendRetryRequest = async (node, forceIncludeKeys = false) => {
85
- const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
86
- const { key: msgKey } = fullMessage;
87
- const msgId = msgKey.id;
88
- const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
89
- let retryCount = msgRetryCache.get(key) || 0;
90
- if (retryCount >= maxMsgRetryCount) {
91
- logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
92
- msgRetryCache.del(key);
93
- return;
94
- }
95
- retryCount += 1;
96
- msgRetryCache.set(key, retryCount);
97
- const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
98
- if (retryCount === 1) {
99
- //request a resend via phone
100
- const msgId = await requestPlaceholderResend(msgKey);
101
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
102
- }
103
- const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
104
- await authState.keys.transaction(async () => {
105
- const receipt = {
106
- tag: 'receipt',
107
- attrs: {
108
- id: msgId,
109
- type: 'retry',
110
- to: node.attrs.from
111
- },
112
- content: [
113
- {
114
- tag: 'retry',
115
- attrs: {
116
- count: retryCount.toString(),
117
- id: node.attrs.id,
118
- t: node.attrs.t,
119
- v: '1'
120
- }
121
- },
122
- {
123
- tag: 'registration',
124
- attrs: {},
125
- content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
126
- }
127
- ]
128
- };
129
- if (node.attrs.recipient) {
130
- receipt.attrs.recipient = node.attrs.recipient;
131
- }
132
- if (node.attrs.participant) {
133
- receipt.attrs.participant = node.attrs.participant;
134
- }
135
- if (retryCount > 1 || forceIncludeKeys) {
136
- const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
137
- const [keyId] = Object.keys(preKeys);
138
- const key = preKeys[+keyId];
139
- const content = receipt.content;
140
- content.push({
141
- tag: 'keys',
142
- attrs: {},
143
- content: [
144
- { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
145
- { tag: 'identity', attrs: {}, content: identityKey.public },
146
- (0, Utils_1.xmppPreKey)(key, +keyId),
147
- (0, Utils_1.xmppSignedPreKey)(signedPreKey),
148
- { tag: 'device-identity', attrs: {}, content: deviceIdentity }
149
- ]
150
- });
151
- ev.emit('creds.update', update);
152
- }
153
- await sendNode(receipt);
154
- logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
155
- });
156
- };
157
- const handleEncryptNotification = async (node) => {
158
- const from = node.attrs.from;
159
- if (from === WABinary_1.S_WHATSAPP_NET) {
160
- const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
161
- const count = +countChild.attrs.value;
162
- const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
163
- logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
164
- if (shouldUploadMorePreKeys) {
165
- await uploadPreKeys();
166
- }
167
- }
168
- else {
169
- const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
170
- if (identityNode) {
171
- logger.info({ jid: from }, 'identity changed');
172
- // not handling right now
173
- // signal will override new identity anyway
174
- }
175
- else {
176
- logger.info({ node }, 'unknown encrypt notification');
177
- }
178
- }
179
- };
180
- const handleGroupNotification = (participant, child, msg) => {
181
- var _a, _b, _c, _d;
182
- 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;
183
- switch (child === null || child === void 0 ? void 0 : child.tag) {
184
- case 'create':
185
- const metadata = (0, groups_1.extractGroupMetadata)(child);
186
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
187
- msg.messageStubParameters = [metadata.subject];
188
- msg.key = { participant: metadata.owner };
189
- ev.emit('chats.upsert', [{
190
- id: metadata.id,
191
- name: metadata.subject,
192
- conversationTimestamp: metadata.creation,
193
- }]);
194
- ev.emit('groups.upsert', [{
195
- ...metadata,
196
- author: participant
197
- }]);
198
- break;
199
- case 'ephemeral':
200
- case 'not_ephemeral':
201
- msg.message = {
202
- protocolMessage: {
203
- type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
204
- ephemeralExpiration: +(child.attrs.expiration || 0)
205
- }
206
- };
207
- break;
208
- case 'modify':
209
- const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
210
- msg.messageStubParameters = oldNumber || [];
211
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
212
- break;
213
- case 'promote':
214
- case 'demote':
215
- case 'remove':
216
- case 'add':
217
- case 'leave':
218
- const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
219
- msg.messageStubType = Types_1.WAMessageStubType[stubType];
220
- const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
221
- if (participants.length === 1 &&
222
- // if recv. "remove" message and sender removed themselves
223
- // mark as left
224
- (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
225
- child.tag === 'remove') {
226
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
227
- }
228
- msg.messageStubParameters = participants;
229
- break;
230
- case 'subject':
231
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
232
- msg.messageStubParameters = [child.attrs.subject];
233
- break;
234
- case 'description':
235
- 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();
236
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
237
- msg.messageStubParameters = description ? [description] : undefined;
238
- break;
239
- case 'announcement':
240
- case 'not_announcement':
241
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
242
- msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off'];
243
- break;
244
- case 'locked':
245
- case 'unlocked':
246
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
247
- msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off'];
248
- break;
249
- case 'invite':
250
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
251
- msg.messageStubParameters = [child.attrs.code];
252
- break;
253
- case 'member_add_mode':
254
- const addMode = child.content;
255
- if (addMode) {
256
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
257
- msg.messageStubParameters = [addMode.toString()];
258
- }
259
- break;
260
- case 'membership_approval_mode':
261
- const approvalMode = (0, WABinary_1.getBinaryNodeChild)(child, 'group_join');
262
- if (approvalMode) {
263
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
264
- msg.messageStubParameters = [approvalMode.attrs.state];
265
- }
266
- break;
267
- case 'created_membership_requests':
268
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
269
- msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
270
- break;
271
- case 'revoked_membership_requests':
272
- const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
273
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
274
- msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
275
- break;
276
- }
277
- };
278
- const processNotification = async (node) => {
279
- var _a, _b, _c;
280
- const result = {};
281
- const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
282
- const nodeType = node.attrs.type;
283
- const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
284
- switch (nodeType) {
285
- case 'privacy_token':
286
- const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
287
- for (const { attrs, content } of tokenList) {
288
- const jid = attrs.jid;
289
- ev.emit('chats.update', [
290
- {
291
- id: jid,
292
- tcToken: content
293
- }
294
- ]);
295
- logger.debug({ jid }, 'got privacy token update');
296
- }
297
- break;
298
- case 'w:gp2':
299
- handleGroupNotification(node.attrs.participant, child, result);
300
- break;
301
- case 'mediaretry':
302
- const event = (0, Utils_1.decodeMediaRetryNode)(node);
303
- ev.emit('messages.media-update', [event]);
304
- break;
305
- case 'encrypt':
306
- await handleEncryptNotification(node);
307
- break;
308
- case 'devices':
309
- const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
310
- if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
311
- const deviceJids = devices.map(d => d.attrs.jid);
312
- logger.info({ deviceJids }, 'got my own devices');
313
- }
314
- break;
315
- case 'server_sync':
316
- const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
317
- if (update) {
318
- const name = update.attrs.name;
319
- await resyncAppState([name], false);
320
- }
321
- break;
322
- case 'picture':
323
- const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
324
- const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
325
- ev.emit('contacts.update', [{
326
- id: (0, WABinary_1.jidNormalizedUser)((_a = node === null || node === void 0 ? void 0 : node.attrs) === null || _a === void 0 ? void 0 : _a.from) || ((_c = (_b = (setPicture || delPicture)) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.hash) || '',
327
- imgUrl: setPicture ? 'changed' : 'removed'
328
- }]);
329
- if ((0, WABinary_1.isJidGroup)(from)) {
330
- const node = setPicture || delPicture;
331
- result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
332
- if (setPicture) {
333
- result.messageStubParameters = [setPicture.attrs.id];
334
- }
335
- result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
336
- result.key = {
337
- ...result.key || {},
338
- participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
339
- };
340
- }
341
- break;
342
- case 'account_sync':
343
- if (child.tag === 'disappearing_mode') {
344
- const newDuration = +child.attrs.duration;
345
- const timestamp = +child.attrs.t;
346
- logger.info({ newDuration }, 'updated account disappearing mode');
347
- ev.emit('creds.update', {
348
- accountSettings: {
349
- ...authState.creds.accountSettings,
350
- defaultDisappearingMode: {
351
- ephemeralExpiration: newDuration,
352
- ephemeralSettingTimestamp: timestamp,
353
- },
354
- }
355
- });
356
- }
357
- else if (child.tag === 'blocklist') {
358
- const blocklists = (0, WABinary_1.getBinaryNodeChildren)(child, 'item');
359
- for (const { attrs } of blocklists) {
360
- const blocklist = [attrs.jid];
361
- const type = (attrs.action === 'block') ? 'add' : 'remove';
362
- ev.emit('blocklist.update', { blocklist, type });
363
- }
364
- }
365
- break;
366
- case 'link_code_companion_reg':
367
- const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg');
368
- const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
369
- const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
370
- const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
371
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
372
- const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
373
- const random = (0, crypto_1.randomBytes)(32);
374
- const linkCodeSalt = (0, crypto_1.randomBytes)(32);
375
- const linkCodePairingExpanded = (0, Utils_1.hkdf)(companionSharedKey, 32, {
376
- salt: linkCodeSalt,
377
- info: 'link_code_pairing_key_bundle_encryption_key'
378
- });
379
- const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
380
- const encryptIv = (0, crypto_1.randomBytes)(12);
381
- const encrypted = (0, Utils_1.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
382
- const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
383
- const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
384
- const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
385
- authState.creds.advSecretKey = (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' }).toString('base64');
386
- await query({
387
- tag: 'iq',
388
- attrs: {
389
- to: WABinary_1.S_WHATSAPP_NET,
390
- type: 'set',
391
- id: sock.generateMessageTag(),
392
- xmlns: 'md'
393
- },
394
- content: [
395
- {
396
- tag: 'link_code_companion_reg',
397
- attrs: {
398
- jid: authState.creds.me.id,
399
- stage: 'companion_finish',
400
- },
401
- content: [
402
- {
403
- tag: 'link_code_pairing_wrapped_key_bundle',
404
- attrs: {},
405
- content: encryptedPayload
406
- },
407
- {
408
- tag: 'companion_identity_public',
409
- attrs: {},
410
- content: authState.creds.signedIdentityKey.public
411
- },
412
- {
413
- tag: 'link_code_pairing_ref',
414
- attrs: {},
415
- content: ref
416
- }
417
- ]
418
- }
419
- ]
420
- });
421
- authState.creds.registered = true;
422
- ev.emit('creds.update', authState.creds);
423
- }
424
- if (Object.keys(result).length) {
425
- return result;
426
- }
427
- };
428
- async function decipherLinkPublicKey(data) {
429
- const buffer = toRequiredBuffer(data);
430
- const salt = buffer.slice(0, 32);
431
- const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
432
- const iv = buffer.slice(32, 48);
433
- const payload = buffer.slice(48, 80);
434
- return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
435
- }
436
- function toRequiredBuffer(data) {
437
- if (data === undefined) {
438
- throw new boom_1.Boom('Invalid buffer', { statusCode: 400 });
439
- }
440
- return data instanceof Buffer ? data : Buffer.from(data);
441
- }
442
- const willSendMessageAgain = (id, participant) => {
443
- const key = `${id}:${participant}`;
444
- const retryCount = msgRetryCache.get(key) || 0;
445
- return retryCount < maxMsgRetryCount;
446
- };
447
- const updateSendMessageAgainCount = (id, participant) => {
448
- const key = `${id}:${participant}`;
449
- const newValue = (msgRetryCache.get(key) || 0) + 1;
450
- msgRetryCache.set(key, newValue);
451
- };
452
- const sendMessagesAgain = async (key, ids, retryNode) => {
453
- var _a;
454
- const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
455
- const remoteJid = key.remoteJid;
456
- const participant = key.participant || remoteJid;
457
- // if it's the primary jid sending the request
458
- // just re-send the message to everyone
459
- // prevents the first message decryption failure
460
- const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
461
- await assertSessions([participant], true);
462
- if ((0, WABinary_1.isJidGroup)(remoteJid)) {
463
- await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
464
- }
465
- logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
466
- for (const [i, msg] of msgs.entries()) {
467
- if (msg) {
468
- updateSendMessageAgainCount(ids[i], participant);
469
- const msgRelayOpts = { messageId: ids[i] };
470
- if (sendToAll) {
471
- msgRelayOpts.useUserDevicesCache = false;
472
- }
473
- else {
474
- msgRelayOpts.participant = {
475
- jid: participant,
476
- count: +retryNode.attrs.count
477
- };
478
- }
479
- await relayMessage(key.remoteJid, msg, msgRelayOpts);
480
- }
481
- else {
482
- logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
483
- }
484
- }
485
- };
486
- const handleReceipt = async (node) => {
487
- var _a, _b;
488
- const { attrs, content } = node;
489
- const isLid = attrs.from.includes('lid');
490
- 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);
491
- const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
492
- const fromMe = !attrs.recipient || (attrs.type === 'retry' && isNodeFromMe);
493
- const key = {
494
- remoteJid,
495
- id: '',
496
- fromMe,
497
- participant: attrs.participant
498
- };
499
- if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
500
- logger.debug({ remoteJid }, 'ignoring receipt from jid');
501
- await sendMessageAck(node);
502
- return;
503
- }
504
- const ids = [attrs.id];
505
- if (Array.isArray(content)) {
506
- const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
507
- ids.push(...items.map(i => i.attrs.id));
508
- }
509
- try {
510
- await Promise.all([
511
- processingMutex.mutex(async () => {
512
- const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
513
- if (typeof status !== 'undefined' &&
514
- (
515
- // basically, we only want to know when a message from us has been delivered to/read by the other person
516
- // or another device of ours has read some messages
517
- status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
518
- !isNodeFromMe)) {
519
- if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
520
- if (attrs.participant) {
521
- const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
522
- ev.emit('message-receipt.update', ids.map(id => ({
523
- key: { ...key, id },
524
- receipt: {
525
- userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
526
- [updateKey]: +attrs.t
527
- }
528
- })));
529
- }
530
- }
531
- else {
532
- ev.emit('messages.update', ids.map(id => ({
533
- key: { ...key, id },
534
- update: { status }
535
- })));
536
- }
537
- }
538
- if (attrs.type === 'retry') {
539
- // correctly set who is asking for the retry
540
- key.participant = key.participant || attrs.from;
541
- const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
542
- if (willSendMessageAgain(ids[0], key.participant)) {
543
- if (key.fromMe) {
544
- try {
545
- logger.debug({ attrs, key }, 'recv retry request');
546
- await sendMessagesAgain(key, ids, retryNode);
547
- }
548
- catch (error) {
549
- logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
550
- }
551
- }
552
- else {
553
- logger.info({ attrs, key }, 'recv retry for not fromMe message');
554
- }
555
- }
556
- else {
557
- logger.info({ attrs, key }, 'will not send message again, as sent too many times');
558
- }
559
- }
560
- })
561
- ]);
562
- }
563
- finally {
564
- await sendMessageAck(node);
565
- }
566
- };
567
- const handleNotification = async (node) => {
568
- const remoteJid = node.attrs.from;
569
- if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
570
- logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
571
- await sendMessageAck(node);
572
- return;
573
- }
574
- try {
575
- await Promise.all([
576
- processingMutex.mutex(async () => {
577
- var _a;
578
- const msg = await processNotification(node);
579
- if (msg) {
580
- const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
581
- msg.key = {
582
- remoteJid,
583
- fromMe,
584
- participant: node.attrs.participant,
585
- id: node.attrs.id,
586
- ...(msg.key || {})
587
- };
588
- (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
589
- msg.messageTimestamp = +node.attrs.t;
590
- const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
591
- await upsertMessage(fullMsg, 'append');
592
- }
593
- })
594
- ]);
595
- }
596
- finally {
597
- await sendMessageAck(node);
598
- }
599
- };
600
- const handleMessage = async (node) => {
601
- var _a, _b, _c;
602
- if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
603
- logger.debug({ key: node.attrs.key }, 'ignored message');
604
- await sendMessageAck(node);
605
- return;
606
- }
607
- let response;
608
- if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !(0, WABinary_1.getBinaryNodeChild)(node, 'enc')) {
609
- await sendMessageAck(node);
610
- const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
611
- response = await requestPlaceholderResend(key);
612
- if (response === 'RESOLVED') {
613
- return;
614
- }
615
- logger.debug('received unavailable message, acked and requested resend from phone');
616
- }
617
- else {
618
- if (placeholderResendCache.get(node.attrs.id)) {
619
- placeholderResendCache.del(node.attrs.id);
620
- }
621
- }
622
- const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
623
- 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) {
624
- msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
625
- }
626
- if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER && node.attrs.sender_pn) {
627
- ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
628
- }
629
- try {
630
- await Promise.all([
631
- processingMutex.mutex(async () => {
632
- var _a;
633
- await decrypt();
634
- // message failed to decrypt
635
- if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
636
- if (((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.MISSING_KEYS_ERROR_TEXT) {
637
- return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
638
- }
639
- retryMutex.mutex(async () => {
640
- if (ws.isOpen) {
641
- if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
642
- return;
643
- }
644
- const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
645
- await sendRetryRequest(node, !encNode);
646
- if (retryRequestDelayMs) {
647
- await (0, Utils_1.delay)(retryRequestDelayMs);
648
- }
649
- }
650
- else {
651
- logger.debug({ node }, 'connection closed, ignoring retry req');
652
- }
653
- });
654
- }
655
- else {
656
- // no type in the receipt => message delivered
657
- let type = undefined;
658
- let participant = msg.key.participant;
659
- if (category === 'peer') { // special peer message
660
- type = 'peer_msg';
661
- }
662
- else if (msg.key.fromMe) { // message was sent by us from a different device
663
- type = 'sender';
664
- // need to specially handle this case
665
- if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
666
- participant = author;
667
- }
668
- }
669
- else if (!sendActiveReceipts) {
670
- type = 'inactive';
671
- }
672
- await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
673
- // send ack for history message
674
- const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
675
- if (isAnyHistoryMsg) {
676
- const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
677
- await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
678
- }
679
- }
680
- (0, Utils_2.cleanMessage)(msg, authState.creds.me.id);
681
- await sendMessageAck(node);
682
- await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
683
- })
684
- ]);
685
- }
686
- catch (error) {
687
- logger.error({ error, node }, 'error in handling message');
688
- }
689
- };
690
- const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
691
- var _a;
692
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
693
- throw new boom_1.Boom('Not authenticated');
694
- }
695
- const pdoMessage = {
696
- historySyncOnDemandRequest: {
697
- chatJid: oldestMsgKey.remoteJid,
698
- oldestMsgFromMe: oldestMsgKey.fromMe,
699
- oldestMsgId: oldestMsgKey.id,
700
- oldestMsgTimestampMs: oldestMsgTimestamp,
701
- onDemandMsgCount: count
702
- },
703
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
704
- };
705
- return sendPeerDataOperationMessage(pdoMessage);
706
- };
707
- const requestPlaceholderResend = async (messageKey) => {
708
- var _a;
709
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
710
- throw new boom_1.Boom('Not authenticated');
711
- }
712
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
713
- logger.debug('already requested resend', { messageKey });
714
- return;
715
- }
716
- else {
717
- placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
718
- }
719
- await (0, Utils_1.delay)(5000);
720
- if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
721
- logger.debug('message received while resend requested', { messageKey });
722
- return 'RESOLVED';
723
- }
724
- const pdoMessage = {
725
- placeholderMessageResendRequest: [{
726
- messageKey
727
- }],
728
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
729
- };
730
- setTimeout(() => {
731
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
732
- logger.debug('PDO message without response after 15 seconds. Phone possibly offline', { messageKey });
733
- placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
734
- }
735
- }, 15000);
736
- return sendPeerDataOperationMessage(pdoMessage);
737
- };
738
- const handleCall = async (node) => {
739
- const { attrs } = node;
740
- const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
741
- const callId = infoChild.attrs['call-id'];
742
- const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
743
- const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
744
- const call = {
745
- chatId: attrs.from,
746
- from,
747
- id: callId,
748
- date: new Date(+attrs.t * 1000),
749
- offline: !!attrs.offline,
750
- status,
751
- };
752
- if (status === 'offer') {
753
- call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
754
- call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
755
- call.groupJid = infoChild.attrs['group-jid'];
756
- callOfferCache.set(call.id, call);
757
- }
758
- const existingCall = callOfferCache.get(call.id);
759
- // use existing call info to populate this event
760
- if (existingCall) {
761
- call.isVideo = existingCall.isVideo;
762
- call.isGroup = existingCall.isGroup;
763
- }
764
- // delete data once call has ended
765
- if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
766
- callOfferCache.del(call.id);
767
- }
768
- ev.emit('call', [call]);
769
- await sendMessageAck(node);
770
- };
771
- const handleBadAck = async ({ attrs }) => {
772
- const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
773
- // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
774
- // // current hypothesis is that if pash is sent in the ack
775
- // // it means -- the message hasn't reached all devices yet
776
- // // we'll retry sending the message here
777
- // if(attrs.phash) {
778
- // logger.info({ attrs }, 'received phash in ack, resending message...')
779
- // const msg = await getMessage(key)
780
- // if(msg) {
781
- // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
782
- // } else {
783
- // logger.warn({ attrs }, 'could not send message again, as it was not found')
784
- // }
785
- // }
786
- // error in acknowledgement,
787
- // device could not display the message
788
- if (attrs.error) {
789
- logger.warn({ attrs }, 'received error in ack');
790
- ev.emit('messages.update', [
791
- {
792
- key,
793
- update: {
794
- status: Types_1.WAMessageStatus.ERROR,
795
- messageStubParameters: [
796
- attrs.error
797
- ]
798
- }
799
- }
800
- ]);
801
- }
802
- };
803
- /// processes a node with the given function
804
- /// and adds the task to the existing buffer if we're buffering events
805
- const processNodeWithBuffer = async (node, identifier, exec) => {
806
- ev.buffer();
807
- await execTask();
808
- ev.flush();
809
- function execTask() {
810
- return exec(node, false)
811
- .catch(err => onUnexpectedError(err, identifier));
812
- }
813
- };
814
- const makeOfflineNodeProcessor = () => {
815
- const nodeProcessorMap = new Map([
816
- ['message', handleMessage],
817
- ['call', handleCall],
818
- ['receipt', handleReceipt],
819
- ['notification', handleNotification]
820
- ]);
821
- const nodes = [];
822
- let isProcessing = false;
823
- const enqueue = (type, node) => {
824
- nodes.push({ type, node });
825
- if (isProcessing) {
826
- return;
827
- }
828
- isProcessing = true;
829
- const promise = async () => {
830
- while (nodes.length && ws.isOpen) {
831
- const { type, node } = nodes.shift();
832
- const nodeProcessor = nodeProcessorMap.get(type);
833
- if (!nodeProcessor) {
834
- onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
835
- continue;
836
- }
837
- await nodeProcessor(node);
838
- }
839
- isProcessing = false;
840
- };
841
- promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
842
- };
843
- return { enqueue };
844
- };
845
- const offlineNodeProcessor = makeOfflineNodeProcessor();
846
- const processNode = (type, node, identifier, exec) => {
847
- const isOffline = !!node.attrs.offline;
848
- if (isOffline) {
849
- offlineNodeProcessor.enqueue(type, node);
850
- }
851
- else {
852
- processNodeWithBuffer(node, identifier, exec);
853
- }
854
- };
855
- // recv a message
856
- ws.on('CB:message', (node) => {
857
- processNode('message', node, 'processing message', handleMessage);
858
- });
859
- ws.on('CB:call', async (node) => {
860
- processNode('call', node, 'handling call', handleCall);
861
- });
862
- ws.on('CB:receipt', node => {
863
- processNode('receipt', node, 'handling receipt', handleReceipt);
864
- });
865
- ws.on('CB:notification', async (node) => {
866
- processNode('notification', node, 'handling notification', handleNotification);
867
- });
868
- ws.on('CB:ack,class:message', (node) => {
869
- handleBadAck(node)
870
- .catch(error => onUnexpectedError(error, 'handling bad ack'));
871
- });
872
- ev.on('call', ([call]) => {
873
- // missed call + group call notification message generation
874
- if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
875
- const msg = {
876
- key: {
877
- remoteJid: call.chatId,
878
- id: call.id,
879
- fromMe: false
880
- },
881
- messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
882
- };
883
- if (call.status === 'timeout') {
884
- if (call.isGroup) {
885
- msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
886
- }
887
- else {
888
- msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
889
- }
890
- }
891
- else {
892
- msg.message = { call: { callKey: Buffer.from(call.id) } };
893
- }
894
- const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
895
- upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
896
- }
897
- });
898
- ev.on('connection.update', ({ isOnline }) => {
899
- if (typeof isOnline !== 'undefined') {
900
- sendActiveReceipts = isOnline;
901
- logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
902
- }
903
- });
904
- return {
905
- ...sock,
906
- sendMessageAck,
907
- sendRetryRequest,
908
- rejectCall,
909
- fetchMessageHistory,
910
- requestPlaceholderResend,
911
- };
912
- };
913
- exports.makeMessagesRecvSocket = makeMessagesRecvSocket;
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 node_cache_1 = __importDefault(require("@cacheable/node-cache"));
8
+ const boom_1 = require("@hapi/boom");
9
+ const crypto_1 = require("crypto");
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 make_mutex_1 = require("../Utils/make-mutex");
15
+ const WABinary_1 = require("../WABinary");
16
+ const groups_1 = require("./groups");
17
+ const messages_send_1 = require("./messages-send");
18
+ const makeMessagesRecvSocket = (config) => {
19
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
20
+ const sock = (0, messages_send_1.makeMessagesSocket)(config);
21
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, } = sock;
22
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
23
+ const retryMutex = (0, make_mutex_1.makeMutex)();
24
+ const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
25
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
26
+ useClones: false
27
+ });
28
+ const callOfferCache = config.callOfferCache || new node_cache_1.default({
29
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
30
+ useClones: false
31
+ });
32
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
33
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
+ useClones: false
35
+ });
36
+ let sendActiveReceipts = false;
37
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
38
+ const stanza = {
39
+ tag: 'ack',
40
+ attrs: {
41
+ id: attrs.id,
42
+ to: attrs.from,
43
+ class: tag
44
+ }
45
+ };
46
+ if (!!errorCode) {
47
+ stanza.attrs.error = errorCode.toString();
48
+ }
49
+ if (!!attrs.participant) {
50
+ stanza.attrs.participant = attrs.participant;
51
+ }
52
+ if (!!attrs.recipient) {
53
+ stanza.attrs.recipient = attrs.recipient;
54
+ }
55
+ if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
56
+ stanza.attrs.type = attrs.type;
57
+ }
58
+ if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
59
+ stanza.attrs.from = authState.creds.me.id;
60
+ }
61
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
62
+ await sendNode(stanza);
63
+ };
64
+ const rejectCall = async (callId, callFrom) => {
65
+ const stanza = ({
66
+ tag: 'call',
67
+ attrs: {
68
+ from: authState.creds.me.id,
69
+ to: callFrom,
70
+ },
71
+ content: [{
72
+ tag: 'reject',
73
+ attrs: {
74
+ 'call-id': callId,
75
+ 'call-creator': callFrom,
76
+ count: '0',
77
+ },
78
+ content: undefined,
79
+ }],
80
+ });
81
+ await query(stanza);
82
+ };
83
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
84
+ const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
85
+ const { key: msgKey } = fullMessage;
86
+ const msgId = msgKey.id;
87
+ const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
88
+ let retryCount = msgRetryCache.get(key) || 0;
89
+ if (retryCount >= maxMsgRetryCount) {
90
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
91
+ msgRetryCache.del(key);
92
+ return;
93
+ }
94
+ retryCount += 1;
95
+ msgRetryCache.set(key, retryCount);
96
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
97
+ if (retryCount === 1) {
98
+ //request a resend via phone
99
+ const msgId = await requestPlaceholderResend(msgKey);
100
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
101
+ }
102
+ const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
103
+ await authState.keys.transaction(async () => {
104
+ const receipt = {
105
+ tag: 'receipt',
106
+ attrs: {
107
+ id: msgId,
108
+ type: 'retry',
109
+ to: node.attrs.from
110
+ },
111
+ content: [
112
+ {
113
+ tag: 'retry',
114
+ attrs: {
115
+ count: retryCount.toString(),
116
+ id: node.attrs.id,
117
+ t: node.attrs.t,
118
+ v: '1'
119
+ }
120
+ },
121
+ {
122
+ tag: 'registration',
123
+ attrs: {},
124
+ content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
125
+ }
126
+ ]
127
+ };
128
+ if (node.attrs.recipient) {
129
+ receipt.attrs.recipient = node.attrs.recipient;
130
+ }
131
+ if (node.attrs.participant) {
132
+ receipt.attrs.participant = node.attrs.participant;
133
+ }
134
+ if (retryCount > 1 || forceIncludeKeys) {
135
+ const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
136
+ const [keyId] = Object.keys(preKeys);
137
+ const key = preKeys[+keyId];
138
+ const content = receipt.content;
139
+ content.push({
140
+ tag: 'keys',
141
+ attrs: {},
142
+ content: [
143
+ { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
144
+ { tag: 'identity', attrs: {}, content: identityKey.public },
145
+ (0, Utils_1.xmppPreKey)(key, +keyId),
146
+ (0, Utils_1.xmppSignedPreKey)(signedPreKey),
147
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
148
+ ]
149
+ });
150
+ ev.emit('creds.update', update);
151
+ }
152
+ await sendNode(receipt);
153
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
154
+ });
155
+ };
156
+ const handleEncryptNotification = async (node) => {
157
+ const from = node.attrs.from;
158
+ if (from === WABinary_1.S_WHATSAPP_NET) {
159
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
160
+ const count = +countChild.attrs.value;
161
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
162
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
163
+ if (shouldUploadMorePreKeys) {
164
+ await uploadPreKeys();
165
+ }
166
+ }
167
+ else {
168
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
169
+ if (identityNode) {
170
+ logger.info({ jid: from }, 'identity changed');
171
+ // not handling right now
172
+ // signal will override new identity anyway
173
+ }
174
+ else {
175
+ logger.info({ node }, 'unknown encrypt notification');
176
+ }
177
+ }
178
+ };
179
+ const handleGroupNotification = (participant, child, msg) => {
180
+ var _a, _b, _c, _d;
181
+ 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;
182
+ switch (child === null || child === void 0 ? void 0 : child.tag) {
183
+ case 'create':
184
+ const metadata = (0, groups_1.extractGroupMetadata)(child);
185
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
186
+ msg.messageStubParameters = [metadata.subject];
187
+ msg.key = { participant: metadata.owner };
188
+ ev.emit('chats.upsert', [{
189
+ id: metadata.id,
190
+ name: metadata.subject,
191
+ conversationTimestamp: metadata.creation,
192
+ }]);
193
+ ev.emit('groups.upsert', [{
194
+ ...metadata,
195
+ author: participant
196
+ }]);
197
+ break;
198
+ case 'ephemeral':
199
+ case 'not_ephemeral':
200
+ msg.message = {
201
+ protocolMessage: {
202
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
203
+ ephemeralExpiration: +(child.attrs.expiration || 0)
204
+ }
205
+ };
206
+ break;
207
+ case 'modify':
208
+ const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
209
+ msg.messageStubParameters = oldNumber || [];
210
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
211
+ break;
212
+ case 'promote':
213
+ case 'demote':
214
+ case 'remove':
215
+ case 'add':
216
+ case 'leave':
217
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
218
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
219
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
220
+ if (participants.length === 1 &&
221
+ // if recv. "remove" message and sender removed themselves
222
+ // mark as left
223
+ (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
224
+ child.tag === 'remove') {
225
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
226
+ }
227
+ msg.messageStubParameters = participants;
228
+ break;
229
+ case 'subject':
230
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
231
+ msg.messageStubParameters = [child.attrs.subject];
232
+ break;
233
+ case 'description':
234
+ 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();
235
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
236
+ msg.messageStubParameters = description ? [description] : undefined;
237
+ break;
238
+ case 'announcement':
239
+ case 'not_announcement':
240
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
241
+ msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off'];
242
+ break;
243
+ case 'locked':
244
+ case 'unlocked':
245
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
246
+ msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off'];
247
+ break;
248
+ case 'invite':
249
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
250
+ msg.messageStubParameters = [child.attrs.code];
251
+ break;
252
+ case 'member_add_mode':
253
+ const addMode = child.content;
254
+ if (addMode) {
255
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
256
+ msg.messageStubParameters = [addMode.toString()];
257
+ }
258
+ break;
259
+ case 'membership_approval_mode':
260
+ const approvalMode = (0, WABinary_1.getBinaryNodeChild)(child, 'group_join');
261
+ if (approvalMode) {
262
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
263
+ msg.messageStubParameters = [approvalMode.attrs.state];
264
+ }
265
+ break;
266
+ case 'created_membership_requests':
267
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
268
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
269
+ break;
270
+ case 'revoked_membership_requests':
271
+ const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
272
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
273
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
274
+ break;
275
+ }
276
+ };
277
+ const processNotification = async (node) => {
278
+ var _a, _b, _c;
279
+ const result = {};
280
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
281
+ const nodeType = node.attrs.type;
282
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
283
+ switch (nodeType) {
284
+ case 'privacy_token':
285
+ const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
286
+ for (const { attrs, content } of tokenList) {
287
+ const jid = attrs.jid;
288
+ ev.emit('chats.update', [
289
+ {
290
+ id: jid,
291
+ tcToken: content
292
+ }
293
+ ]);
294
+ logger.debug({ jid }, 'got privacy token update');
295
+ }
296
+ break;
297
+ case 'w:gp2':
298
+ handleGroupNotification(node.attrs.participant, child, result);
299
+ break;
300
+ case 'mediaretry':
301
+ const event = (0, Utils_1.decodeMediaRetryNode)(node);
302
+ ev.emit('messages.media-update', [event]);
303
+ break;
304
+ case 'encrypt':
305
+ await handleEncryptNotification(node);
306
+ break;
307
+ case 'devices':
308
+ const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
309
+ if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
310
+ const deviceJids = devices.map(d => d.attrs.jid);
311
+ logger.info({ deviceJids }, 'got my own devices');
312
+ }
313
+ break;
314
+ case 'server_sync':
315
+ const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
316
+ if (update) {
317
+ const name = update.attrs.name;
318
+ await resyncAppState([name], false);
319
+ }
320
+ break;
321
+ case 'picture':
322
+ const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
323
+ const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
324
+ ev.emit('contacts.update', [{
325
+ id: (0, WABinary_1.jidNormalizedUser)((_a = node === null || node === void 0 ? void 0 : node.attrs) === null || _a === void 0 ? void 0 : _a.from) || ((_c = (_b = (setPicture || delPicture)) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.hash) || '',
326
+ imgUrl: setPicture ? 'changed' : 'removed'
327
+ }]);
328
+ if ((0, WABinary_1.isJidGroup)(from)) {
329
+ const node = setPicture || delPicture;
330
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
331
+ if (setPicture) {
332
+ result.messageStubParameters = [setPicture.attrs.id];
333
+ }
334
+ result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
335
+ result.key = {
336
+ ...result.key || {},
337
+ participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
338
+ };
339
+ }
340
+ break;
341
+ case 'account_sync':
342
+ if (child.tag === 'disappearing_mode') {
343
+ const newDuration = +child.attrs.duration;
344
+ const timestamp = +child.attrs.t;
345
+ logger.info({ newDuration }, 'updated account disappearing mode');
346
+ ev.emit('creds.update', {
347
+ accountSettings: {
348
+ ...authState.creds.accountSettings,
349
+ defaultDisappearingMode: {
350
+ ephemeralExpiration: newDuration,
351
+ ephemeralSettingTimestamp: timestamp,
352
+ },
353
+ }
354
+ });
355
+ }
356
+ else if (child.tag === 'blocklist') {
357
+ const blocklists = (0, WABinary_1.getBinaryNodeChildren)(child, 'item');
358
+ for (const { attrs } of blocklists) {
359
+ const blocklist = [attrs.jid];
360
+ const type = (attrs.action === 'block') ? 'add' : 'remove';
361
+ ev.emit('blocklist.update', { blocklist, type });
362
+ }
363
+ }
364
+ break;
365
+ case 'link_code_companion_reg':
366
+ const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg');
367
+ const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
368
+ const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
369
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
370
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
371
+ const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
372
+ const random = (0, crypto_1.randomBytes)(32);
373
+ const linkCodeSalt = (0, crypto_1.randomBytes)(32);
374
+ const linkCodePairingExpanded = await (0, Utils_1.hkdf)(companionSharedKey, 32, {
375
+ salt: linkCodeSalt,
376
+ info: 'link_code_pairing_key_bundle_encryption_key'
377
+ });
378
+ const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
379
+ const encryptIv = (0, crypto_1.randomBytes)(12);
380
+ const encrypted = (0, Utils_1.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
381
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
382
+ const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
383
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
384
+ authState.creds.advSecretKey = (await (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
385
+ await query({
386
+ tag: 'iq',
387
+ attrs: {
388
+ to: WABinary_1.S_WHATSAPP_NET,
389
+ type: 'set',
390
+ id: sock.generateMessageTag(),
391
+ xmlns: 'md'
392
+ },
393
+ content: [
394
+ {
395
+ tag: 'link_code_companion_reg',
396
+ attrs: {
397
+ jid: authState.creds.me.id,
398
+ stage: 'companion_finish',
399
+ },
400
+ content: [
401
+ {
402
+ tag: 'link_code_pairing_wrapped_key_bundle',
403
+ attrs: {},
404
+ content: encryptedPayload
405
+ },
406
+ {
407
+ tag: 'companion_identity_public',
408
+ attrs: {},
409
+ content: authState.creds.signedIdentityKey.public
410
+ },
411
+ {
412
+ tag: 'link_code_pairing_ref',
413
+ attrs: {},
414
+ content: ref
415
+ }
416
+ ]
417
+ }
418
+ ]
419
+ });
420
+ authState.creds.registered = true;
421
+ ev.emit('creds.update', authState.creds);
422
+ }
423
+ if (Object.keys(result).length) {
424
+ return result;
425
+ }
426
+ };
427
+ async function decipherLinkPublicKey(data) {
428
+ const buffer = toRequiredBuffer(data);
429
+ const salt = buffer.slice(0, 32);
430
+ const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
431
+ const iv = buffer.slice(32, 48);
432
+ const payload = buffer.slice(48, 80);
433
+ return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
434
+ }
435
+ function toRequiredBuffer(data) {
436
+ if (data === undefined) {
437
+ throw new boom_1.Boom('Invalid buffer', { statusCode: 400 });
438
+ }
439
+ return data instanceof Buffer ? data : Buffer.from(data);
440
+ }
441
+ const willSendMessageAgain = (id, participant) => {
442
+ const key = `${id}:${participant}`;
443
+ const retryCount = msgRetryCache.get(key) || 0;
444
+ return retryCount < maxMsgRetryCount;
445
+ };
446
+ const updateSendMessageAgainCount = (id, participant) => {
447
+ const key = `${id}:${participant}`;
448
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
449
+ msgRetryCache.set(key, newValue);
450
+ };
451
+ const sendMessagesAgain = async (key, ids, retryNode) => {
452
+ var _a;
453
+ // todo: implement a cache to store the last 256 sent messages (copy whatsmeow)
454
+ const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
455
+ const remoteJid = key.remoteJid;
456
+ const participant = key.participant || remoteJid;
457
+ // if it's the primary jid sending the request
458
+ // just re-send the message to everyone
459
+ // prevents the first message decryption failure
460
+ const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
461
+ await assertSessions([participant], true);
462
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
463
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
464
+ }
465
+ logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
466
+ for (const [i, msg] of msgs.entries()) {
467
+ if (msg) {
468
+ updateSendMessageAgainCount(ids[i], participant);
469
+ const msgRelayOpts = { messageId: ids[i] };
470
+ if (sendToAll) {
471
+ msgRelayOpts.useUserDevicesCache = false;
472
+ }
473
+ else {
474
+ msgRelayOpts.participant = {
475
+ jid: participant,
476
+ count: +retryNode.attrs.count
477
+ };
478
+ }
479
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
480
+ }
481
+ else {
482
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
483
+ }
484
+ }
485
+ };
486
+ const handleReceipt = async (node) => {
487
+ var _a, _b;
488
+ const { attrs, content } = node;
489
+ const isLid = attrs.from.includes('lid');
490
+ 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);
491
+ const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
492
+ const fromMe = !attrs.recipient || (attrs.type === 'retry' && isNodeFromMe);
493
+ const key = {
494
+ remoteJid,
495
+ id: '',
496
+ fromMe,
497
+ participant: attrs.participant
498
+ };
499
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
500
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
501
+ await sendMessageAck(node);
502
+ return;
503
+ }
504
+ const ids = [attrs.id];
505
+ if (Array.isArray(content)) {
506
+ const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
507
+ ids.push(...items.map(i => i.attrs.id));
508
+ }
509
+ try {
510
+ await Promise.all([
511
+ processingMutex.mutex(async () => {
512
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
513
+ if (typeof status !== 'undefined' &&
514
+ (
515
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
516
+ // or another device of ours has read some messages
517
+ status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
518
+ !isNodeFromMe)) {
519
+ if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
520
+ if (attrs.participant) {
521
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
522
+ ev.emit('message-receipt.update', ids.map(id => ({
523
+ key: { ...key, id },
524
+ receipt: {
525
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
526
+ [updateKey]: +attrs.t
527
+ }
528
+ })));
529
+ }
530
+ }
531
+ else {
532
+ ev.emit('messages.update', ids.map(id => ({
533
+ key: { ...key, id },
534
+ update: { status }
535
+ })));
536
+ }
537
+ }
538
+ if (attrs.type === 'retry') {
539
+ // correctly set who is asking for the retry
540
+ key.participant = key.participant || attrs.from;
541
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
542
+ if (willSendMessageAgain(ids[0], key.participant)) {
543
+ if (key.fromMe) {
544
+ try {
545
+ logger.debug({ attrs, key }, 'recv retry request');
546
+ await sendMessagesAgain(key, ids, retryNode);
547
+ }
548
+ catch (error) {
549
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
550
+ }
551
+ }
552
+ else {
553
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
554
+ }
555
+ }
556
+ else {
557
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
558
+ }
559
+ }
560
+ })
561
+ ]);
562
+ }
563
+ finally {
564
+ await sendMessageAck(node);
565
+ }
566
+ };
567
+ const handleNotification = async (node) => {
568
+ const remoteJid = node.attrs.from;
569
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
570
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
571
+ await sendMessageAck(node);
572
+ return;
573
+ }
574
+ try {
575
+ await Promise.all([
576
+ processingMutex.mutex(async () => {
577
+ var _a;
578
+ const msg = await processNotification(node);
579
+ if (msg) {
580
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
581
+ msg.key = {
582
+ remoteJid,
583
+ fromMe,
584
+ participant: node.attrs.participant,
585
+ id: node.attrs.id,
586
+ ...(msg.key || {})
587
+ };
588
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
589
+ msg.messageTimestamp = +node.attrs.t;
590
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
591
+ await upsertMessage(fullMsg, 'append');
592
+ }
593
+ })
594
+ ]);
595
+ }
596
+ finally {
597
+ await sendMessageAck(node);
598
+ }
599
+ };
600
+ const handleMessage = async (node) => {
601
+ var _a, _b, _c;
602
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
603
+ logger.debug({ key: node.attrs.key }, 'ignored message');
604
+ await sendMessageAck(node);
605
+ return;
606
+ }
607
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
608
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
609
+ if (encNode && encNode.attrs.type === 'msmsg') {
610
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
611
+ await sendMessageAck(node);
612
+ return;
613
+ }
614
+ let response;
615
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !encNode) {
616
+ await sendMessageAck(node);
617
+ const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
618
+ response = await requestPlaceholderResend(key);
619
+ if (response === 'RESOLVED') {
620
+ return;
621
+ }
622
+ logger.debug('received unavailable message, acked and requested resend from phone');
623
+ }
624
+ else {
625
+ if (placeholderResendCache.get(node.attrs.id)) {
626
+ placeholderResendCache.del(node.attrs.id);
627
+ }
628
+ }
629
+ const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
630
+ 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) {
631
+ msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
632
+ }
633
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER && node.attrs.sender_pn) {
634
+ ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
635
+ }
636
+ try {
637
+ await Promise.all([
638
+ processingMutex.mutex(async () => {
639
+ var _a;
640
+ await decrypt();
641
+ // message failed to decrypt
642
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
643
+ if (((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.MISSING_KEYS_ERROR_TEXT) {
644
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
645
+ }
646
+ retryMutex.mutex(async () => {
647
+ if (ws.isOpen) {
648
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
649
+ return;
650
+ }
651
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
652
+ await sendRetryRequest(node, !encNode);
653
+ if (retryRequestDelayMs) {
654
+ await (0, Utils_1.delay)(retryRequestDelayMs);
655
+ }
656
+ }
657
+ else {
658
+ logger.debug({ node }, 'connection closed, ignoring retry req');
659
+ }
660
+ });
661
+ }
662
+ else {
663
+ // no type in the receipt => message delivered
664
+ let type = undefined;
665
+ let participant = msg.key.participant;
666
+ if (category === 'peer') { // special peer message
667
+ type = 'peer_msg';
668
+ }
669
+ else if (msg.key.fromMe) { // message was sent by us from a different device
670
+ type = 'sender';
671
+ // need to specially handle this case
672
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
673
+ participant = author;
674
+ }
675
+ }
676
+ else if (!sendActiveReceipts) {
677
+ type = 'inactive';
678
+ }
679
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
680
+ // send ack for history message
681
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
682
+ if (isAnyHistoryMsg) {
683
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
684
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
685
+ }
686
+ }
687
+ (0, Utils_1.cleanMessage)(msg, authState.creds.me.id);
688
+ await sendMessageAck(node);
689
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
690
+ })
691
+ ]);
692
+ }
693
+ catch (error) {
694
+ logger.error({ error, node }, 'error in handling message');
695
+ }
696
+ };
697
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
698
+ var _a;
699
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
700
+ throw new boom_1.Boom('Not authenticated');
701
+ }
702
+ const pdoMessage = {
703
+ historySyncOnDemandRequest: {
704
+ chatJid: oldestMsgKey.remoteJid,
705
+ oldestMsgFromMe: oldestMsgKey.fromMe,
706
+ oldestMsgId: oldestMsgKey.id,
707
+ oldestMsgTimestampMs: oldestMsgTimestamp,
708
+ onDemandMsgCount: count
709
+ },
710
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
711
+ };
712
+ return sendPeerDataOperationMessage(pdoMessage);
713
+ };
714
+ const requestPlaceholderResend = async (messageKey) => {
715
+ var _a;
716
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
717
+ throw new boom_1.Boom('Not authenticated');
718
+ }
719
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
720
+ logger.debug({ messageKey }, 'already requested resend');
721
+ return;
722
+ }
723
+ else {
724
+ placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
725
+ }
726
+ await (0, Utils_1.delay)(5000);
727
+ if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
728
+ logger.debug({ messageKey }, 'message received while resend requested');
729
+ return 'RESOLVED';
730
+ }
731
+ const pdoMessage = {
732
+ placeholderMessageResendRequest: [{
733
+ messageKey
734
+ }],
735
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
736
+ };
737
+ setTimeout(() => {
738
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
739
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
740
+ placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
741
+ }
742
+ }, 15000);
743
+ return sendPeerDataOperationMessage(pdoMessage);
744
+ };
745
+ const handleCall = async (node) => {
746
+ const { attrs } = node;
747
+ const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
748
+ const callId = infoChild.attrs['call-id'];
749
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
750
+ const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
751
+ const call = {
752
+ chatId: attrs.from,
753
+ from,
754
+ id: callId,
755
+ date: new Date(+attrs.t * 1000),
756
+ offline: !!attrs.offline,
757
+ status,
758
+ };
759
+ if (status === 'offer') {
760
+ call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
761
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
762
+ call.groupJid = infoChild.attrs['group-jid'];
763
+ callOfferCache.set(call.id, call);
764
+ }
765
+ const existingCall = callOfferCache.get(call.id);
766
+ // use existing call info to populate this event
767
+ if (existingCall) {
768
+ call.isVideo = existingCall.isVideo;
769
+ call.isGroup = existingCall.isGroup;
770
+ }
771
+ // delete data once call has ended
772
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
773
+ callOfferCache.del(call.id);
774
+ }
775
+ ev.emit('call', [call]);
776
+ await sendMessageAck(node);
777
+ };
778
+ const handleBadAck = async ({ attrs }) => {
779
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
780
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
781
+ // // current hypothesis is that if pash is sent in the ack
782
+ // // it means -- the message hasn't reached all devices yet
783
+ // // we'll retry sending the message here
784
+ // if(attrs.phash) {
785
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
786
+ // const msg = await getMessage(key)
787
+ // if(msg) {
788
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
789
+ // } else {
790
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
791
+ // }
792
+ // }
793
+ // error in acknowledgement,
794
+ // device could not display the message
795
+ if (attrs.error) {
796
+ logger.warn({ attrs }, 'received error in ack');
797
+ ev.emit('messages.update', [
798
+ {
799
+ key,
800
+ update: {
801
+ status: Types_1.WAMessageStatus.ERROR,
802
+ messageStubParameters: [
803
+ attrs.error
804
+ ]
805
+ }
806
+ }
807
+ ]);
808
+ }
809
+ };
810
+ /// processes a node with the given function
811
+ /// and adds the task to the existing buffer if we're buffering events
812
+ const processNodeWithBuffer = async (node, identifier, exec) => {
813
+ ev.buffer();
814
+ await execTask();
815
+ ev.flush();
816
+ function execTask() {
817
+ return exec(node, false)
818
+ .catch(err => onUnexpectedError(err, identifier));
819
+ }
820
+ };
821
+ const makeOfflineNodeProcessor = () => {
822
+ const nodeProcessorMap = new Map([
823
+ ['message', handleMessage],
824
+ ['call', handleCall],
825
+ ['receipt', handleReceipt],
826
+ ['notification', handleNotification]
827
+ ]);
828
+ const nodes = [];
829
+ let isProcessing = false;
830
+ const enqueue = (type, node) => {
831
+ nodes.push({ type, node });
832
+ if (isProcessing) {
833
+ return;
834
+ }
835
+ isProcessing = true;
836
+ const promise = async () => {
837
+ while (nodes.length && ws.isOpen) {
838
+ const { type, node } = nodes.shift();
839
+ const nodeProcessor = nodeProcessorMap.get(type);
840
+ if (!nodeProcessor) {
841
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
842
+ continue;
843
+ }
844
+ await nodeProcessor(node);
845
+ }
846
+ isProcessing = false;
847
+ };
848
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
849
+ };
850
+ return { enqueue };
851
+ };
852
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
853
+ const processNode = (type, node, identifier, exec) => {
854
+ const isOffline = !!node.attrs.offline;
855
+ if (isOffline) {
856
+ offlineNodeProcessor.enqueue(type, node);
857
+ }
858
+ else {
859
+ processNodeWithBuffer(node, identifier, exec);
860
+ }
861
+ };
862
+ // recv a message
863
+ ws.on('CB:message', (node) => {
864
+ processNode('message', node, 'processing message', handleMessage);
865
+ });
866
+ ws.on('CB:call', async (node) => {
867
+ processNode('call', node, 'handling call', handleCall);
868
+ });
869
+ ws.on('CB:receipt', node => {
870
+ processNode('receipt', node, 'handling receipt', handleReceipt);
871
+ });
872
+ ws.on('CB:notification', async (node) => {
873
+ processNode('notification', node, 'handling notification', handleNotification);
874
+ });
875
+ ws.on('CB:ack,class:message', (node) => {
876
+ handleBadAck(node)
877
+ .catch(error => onUnexpectedError(error, 'handling bad ack'));
878
+ });
879
+ ev.on('call', ([call]) => {
880
+ // missed call + group call notification message generation
881
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
882
+ const msg = {
883
+ key: {
884
+ remoteJid: call.chatId,
885
+ id: call.id,
886
+ fromMe: false
887
+ },
888
+ messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
889
+ };
890
+ if (call.status === 'timeout') {
891
+ if (call.isGroup) {
892
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
893
+ }
894
+ else {
895
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
896
+ }
897
+ }
898
+ else {
899
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
900
+ }
901
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
902
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
903
+ }
904
+ });
905
+ ev.on('connection.update', ({ isOnline }) => {
906
+ if (typeof isOnline !== 'undefined') {
907
+ sendActiveReceipts = isOnline;
908
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
909
+ }
910
+ });
911
+ return {
912
+ ...sock,
913
+ sendMessageAck,
914
+ sendRetryRequest,
915
+ rejectCall,
916
+ fetchMessageHistory,
917
+ requestPlaceholderResend,
918
+ };
919
+ };
920
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;