budetzz 0.0.1-security → 2.0.4

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.

Potentially problematic release.


This version of budetzz might be problematic. Click here for more details.

Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.MD +1000 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/index.js +97692 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +120 -0
  9. package/lib/Defaults/wileys-version.json +3 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.js +64 -0
  12. package/lib/Signal/Group/group_cipher.js +96 -0
  13. package/lib/Signal/Group/index.js +57 -0
  14. package/lib/Signal/Group/keyhelper.js +55 -0
  15. package/lib/Signal/Group/queue-job.js +57 -0
  16. package/lib/Signal/Group/sender-chain-key.js +34 -0
  17. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  18. package/lib/Signal/Group/sender-key-message.js +69 -0
  19. package/lib/Signal/Group/sender-key-name.js +51 -0
  20. package/lib/Signal/Group/sender-key-record.js +53 -0
  21. package/lib/Signal/Group/sender-key-state.js +99 -0
  22. package/lib/Signal/Group/sender-message-key.js +29 -0
  23. package/lib/Signal/libsignal.js +184 -0
  24. package/lib/Socket/Client/index.js +18 -0
  25. package/lib/Socket/Client/types.js +13 -0
  26. package/lib/Socket/Client/websocket.js +72 -0
  27. package/lib/Socket/business.js +260 -0
  28. package/lib/Socket/chats.js +997 -0
  29. package/lib/Socket/groups.js +332 -0
  30. package/lib/Socket/index.js +10 -0
  31. package/lib/Socket/messages-recv.js +1155 -0
  32. package/lib/Socket/messages-send.js +913 -0
  33. package/lib/Socket/newsletter.js +283 -0
  34. package/lib/Socket/socket.js +646 -0
  35. package/lib/Socket/usync.js +70 -0
  36. package/lib/Store/index.js +8 -0
  37. package/lib/Store/make-in-memory-store.js +439 -0
  38. package/lib/Store/make-ordered-dictionary.js +81 -0
  39. package/lib/Store/object-repository.js +27 -0
  40. package/lib/Types/Auth.js +2 -0
  41. package/lib/Types/Call.js +2 -0
  42. package/lib/Types/Chat.js +4 -0
  43. package/lib/Types/Contact.js +2 -0
  44. package/lib/Types/Events.js +2 -0
  45. package/lib/Types/GroupMetadata.js +2 -0
  46. package/lib/Types/Label.js +27 -0
  47. package/lib/Types/LabelAssociation.js +9 -0
  48. package/lib/Types/Message.js +7 -0
  49. package/lib/Types/Newsletter.js +18 -0
  50. package/lib/Types/Product.js +2 -0
  51. package/lib/Types/Signal.js +2 -0
  52. package/lib/Types/Socket.js +2 -0
  53. package/lib/Types/State.js +2 -0
  54. package/lib/Types/USync.js +2 -0
  55. package/lib/Types/index.js +42 -0
  56. package/lib/Utils/auth-utils.js +199 -0
  57. package/lib/Utils/browser-utils.js +35 -0
  58. package/lib/Utils/business.js +234 -0
  59. package/lib/Utils/chat-utils.js +730 -0
  60. package/lib/Utils/crypto.js +193 -0
  61. package/lib/Utils/decode-wa-message.js +217 -0
  62. package/lib/Utils/event-buffer.js +518 -0
  63. package/lib/Utils/generics.js +467 -0
  64. package/lib/Utils/history.js +94 -0
  65. package/lib/Utils/index.js +35 -0
  66. package/lib/Utils/link-preview.js +126 -0
  67. package/lib/Utils/logger.js +7 -0
  68. package/lib/Utils/lt-hash.js +51 -0
  69. package/lib/Utils/make-mutex.js +43 -0
  70. package/lib/Utils/message-retry-manager.js +185 -0
  71. package/lib/Utils/messages-media.js +879 -0
  72. package/lib/Utils/messages.js +1828 -0
  73. package/lib/Utils/noise-handler.js +150 -0
  74. package/lib/Utils/process-message.js +404 -0
  75. package/lib/Utils/signal.js +153 -0
  76. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  77. package/lib/Utils/validate-connection.js +229 -0
  78. package/lib/Utils/wileys-event-stream.js +63 -0
  79. package/lib/WABinary/constants.js +1303 -0
  80. package/lib/WABinary/decode.js +265 -0
  81. package/lib/WABinary/encode.js +250 -0
  82. package/lib/WABinary/generic-utils.js +110 -0
  83. package/lib/WABinary/index.js +21 -0
  84. package/lib/WABinary/jid-utils.js +85 -0
  85. package/lib/WABinary/types.js +2 -0
  86. package/lib/WAM/BinaryInfo.js +13 -0
  87. package/lib/WAM/constants.js +15350 -0
  88. package/lib/WAM/encode.js +155 -0
  89. package/lib/WAM/index.js +19 -0
  90. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  91. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  92. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  93. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  94. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  95. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  96. package/lib/WAUSync/Protocols/index.js +20 -0
  97. package/lib/WAUSync/USyncQuery.js +89 -0
  98. package/lib/WAUSync/USyncUser.js +26 -0
  99. package/lib/WAUSync/index.js +19 -0
  100. package/lib/index.js +94 -0
  101. package/package.json +116 -4
  102. package/README.md +0 -5
@@ -0,0 +1,913 @@
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.makeMessagesSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const crypto_1 = require("crypto");
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Utils_1 = require("../Utils");
13
+ const link_preview_1 = require("../Utils/link-preview");
14
+ const WABinary_1 = require("../WABinary");
15
+ const WAUSync_1 = require("../WAUSync");
16
+ const newsletter_1 = require("./newsletter");
17
+ const makeMessagesSocket = (config) => {
18
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, albumMessageItemDelayMs = 0, } = config;
19
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
20
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
21
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
22
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
23
+ useClones: false
24
+ });
25
+ let mediaConn;
26
+ const refreshMediaConn = async (forceGet = false) => {
27
+ const media = await mediaConn;
28
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
29
+ mediaConn = (async () => {
30
+ const result = await query({
31
+ tag: 'iq',
32
+ attrs: {
33
+ type: 'set',
34
+ xmlns: 'w:m',
35
+ to: WABinary_1.S_WHATSAPP_NET,
36
+ },
37
+ content: [{ tag: 'media_conn', attrs: {} }]
38
+ });
39
+ const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn');
40
+ const node = {
41
+ hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
42
+ hostname: attrs.hostname,
43
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
44
+ })),
45
+ auth: mediaConnNode.attrs.auth,
46
+ ttl: +mediaConnNode.attrs.ttl,
47
+ fetchDate: new Date()
48
+ };
49
+ logger.debug('fetched media conn');
50
+ return node;
51
+ })();
52
+ }
53
+ return mediaConn;
54
+ };
55
+ /**
56
+ * generic send receipt function
57
+ * used for receipts of phone call, read, delivery etc.
58
+ * */
59
+ const sendReceipt = async (jid, participant, messageIds, type) => {
60
+ const node = {
61
+ tag: 'receipt',
62
+ attrs: {
63
+ id: messageIds[0],
64
+ },
65
+ };
66
+ const isReadReceipt = type === 'read' || type === 'read-self';
67
+ if (isReadReceipt) {
68
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
69
+ }
70
+ if (type === 'sender' && (0, WABinary_1.isJidUser)(jid)) {
71
+ node.attrs.recipient = jid;
72
+ node.attrs.to = participant;
73
+ }
74
+ else {
75
+ node.attrs.to = jid;
76
+ if (participant) {
77
+ node.attrs.participant = participant;
78
+ }
79
+ }
80
+ if (type) {
81
+ node.attrs.type = (0, WABinary_1.isJidNewsletter)(jid) ? 'read-self' : type;
82
+ }
83
+ const remainingMessageIds = messageIds.slice(1);
84
+ if (remainingMessageIds.length) {
85
+ node.content = [
86
+ {
87
+ tag: 'list',
88
+ attrs: {},
89
+ content: remainingMessageIds.map(id => ({
90
+ tag: 'item',
91
+ attrs: { id }
92
+ }))
93
+ }
94
+ ];
95
+ }
96
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
97
+ await sendNode(node);
98
+ };
99
+ /** Correctly bulk send receipts to multiple chats, participants */
100
+ const sendReceipts = async (keys, type) => {
101
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
102
+ for (const { jid, participant, messageIds } of recps) {
103
+ await sendReceipt(jid, participant, messageIds, type);
104
+ }
105
+ };
106
+ /** Bulk read messages. Keys can be from different chats & participants */
107
+ const readMessages = async (keys) => {
108
+ const privacySettings = await fetchPrivacySettings();
109
+ // based on privacy settings, we have to change the read type
110
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
111
+ await sendReceipts(keys, readType);
112
+ };
113
+ /** Fetch all the devices we've to send a message to */
114
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
115
+ var _a;
116
+ const deviceResults = [];
117
+ if (!useCache) {
118
+ logger.debug('not using cache for devices');
119
+ }
120
+ const toFetch = [];
121
+ jids = Array.from(new Set(jids));
122
+ for (let jid of jids) {
123
+ const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
124
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
125
+ if (useCache) {
126
+ const devices = userDevicesCache.get(user);
127
+ if (devices) {
128
+ deviceResults.push(...devices);
129
+ logger.trace({ user }, 'using cache for devices');
130
+ }
131
+ else {
132
+ toFetch.push(jid);
133
+ }
134
+ }
135
+ else {
136
+ toFetch.push(jid);
137
+ }
138
+ }
139
+ if (!toFetch.length) {
140
+ return deviceResults;
141
+ }
142
+ const query = new WAUSync_1.USyncQuery()
143
+ .withContext('message')
144
+ .withDeviceProtocol();
145
+ for (const jid of toFetch) {
146
+ query.withUser(new WAUSync_1.USyncUser().withId(jid));
147
+ }
148
+ const result = await sock.executeUSyncQuery(query);
149
+ if (result) {
150
+ const extracted = (0, Utils_1.extractDeviceJids)(result === null || result === void 0 ? void 0 : result.list, authState.creds.me.id, ignoreZeroDevices);
151
+ const deviceMap = {};
152
+ for (const item of extracted) {
153
+ deviceMap[item.user] = deviceMap[item.user] || [];
154
+ deviceMap[item.user].push(item);
155
+ deviceResults.push(item);
156
+ }
157
+ for (const key in deviceMap) {
158
+ userDevicesCache.set(key, deviceMap[key]);
159
+ }
160
+ }
161
+ return deviceResults;
162
+ };
163
+ const assertSessions = async (jids, force) => {
164
+ let didFetchNewSession = false;
165
+ let jidsRequiringFetch = [];
166
+ if (force) {
167
+ jidsRequiringFetch = jids;
168
+ }
169
+ else {
170
+ const addrs = jids.map(jid => (signalRepository
171
+ .jidToSignalProtocolAddress(jid)));
172
+ const sessions = await authState.keys.get('session', addrs);
173
+ for (const jid of jids) {
174
+ const signalId = signalRepository
175
+ .jidToSignalProtocolAddress(jid);
176
+ if (!sessions[signalId]) {
177
+ jidsRequiringFetch.push(jid);
178
+ }
179
+ }
180
+ }
181
+ if (jidsRequiringFetch.length) {
182
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
183
+ const result = await query({
184
+ tag: 'iq',
185
+ attrs: {
186
+ xmlns: 'encrypt',
187
+ type: 'get',
188
+ to: WABinary_1.S_WHATSAPP_NET,
189
+ },
190
+ content: [
191
+ {
192
+ tag: 'key',
193
+ attrs: {},
194
+ content: jidsRequiringFetch.map(jid => ({
195
+ tag: 'user',
196
+ attrs: { jid },
197
+ }))
198
+ }
199
+ ]
200
+ });
201
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
202
+ didFetchNewSession = true;
203
+ }
204
+ return didFetchNewSession;
205
+ };
206
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
207
+ var _a;
208
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
209
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
210
+ throw new boom_1.Boom('Not authenticated');
211
+ }
212
+ const protocolMessage = {
213
+ protocolMessage: {
214
+ peerDataOperationRequestMessage: pdoMessage,
215
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
216
+ }
217
+ };
218
+ const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
219
+ const msgId = await relayMessage(meJid, protocolMessage, {
220
+ additionalAttributes: {
221
+ category: 'peer',
222
+ // eslint-disable-next-line camelcase
223
+ push_priority: 'high_force',
224
+ },
225
+ });
226
+ return msgId;
227
+ };
228
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
229
+ let patched = await patchMessageBeforeSending(message, jids);
230
+ if (!Array.isArray(patched)) {
231
+ patched = jids ? jids.map(jid => ({ recipientJid: jid, ...patched })) : [patched];
232
+ }
233
+ let shouldIncludeDeviceIdentity = false;
234
+ const nodes = await Promise.all(patched.map(async (patchedMessageWithJid) => {
235
+ const { recipientJid: jid, ...patchedMessage } = patchedMessageWithJid;
236
+ if (!jid) {
237
+ return {};
238
+ }
239
+ const bytes = (0, Utils_1.encodeWAMessage)(patchedMessage);
240
+ const { type, ciphertext } = await signalRepository
241
+ .encryptMessage({ jid, data: bytes });
242
+ if (type === 'pkmsg') {
243
+ shouldIncludeDeviceIdentity = true;
244
+ }
245
+ const node = {
246
+ tag: 'to',
247
+ attrs: { jid },
248
+ content: [{
249
+ tag: 'enc',
250
+ attrs: {
251
+ v: '2',
252
+ type,
253
+ ...extraAttrs || {}
254
+ },
255
+ content: ciphertext
256
+ }]
257
+ };
258
+ return node;
259
+ }));
260
+ return { nodes, shouldIncludeDeviceIdentity };
261
+ };
262
+ const relayMessage = async (jid, message, {
263
+ messageId: msgId,
264
+ participant,
265
+ onTarget,
266
+ additionalAttributes,
267
+ additionalNodes,
268
+ useUserDevicesCache,
269
+ useCachedGroupMetadata,
270
+ statusJidList
271
+ }) => {
272
+ var _a;
273
+ const meId = authState.creds.me.id;
274
+ let shouldIncludeDeviceIdentity = false;
275
+ const { user, server } = (0, WABinary_1.jidDecode)(jid);
276
+ const statusJid = 'status@broadcast';
277
+ const isGroup = server === 'g.us';
278
+ const isNewsletter = server === 'newsletter';
279
+ const isStatus = jid === statusJid;
280
+ const isLid = server === 'lid';
281
+ msgId = msgId || (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
282
+ useUserDevicesCache = useUserDevicesCache !== false;
283
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
284
+ const participants = [];
285
+ const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
286
+ const binaryNodeContent = [];
287
+ const devices = [];
288
+ const meMsg = {
289
+ deviceSentMessage: {
290
+ destinationJid,
291
+ message
292
+ },
293
+ messageContextInfo: message.messageContextInfo
294
+ };
295
+ const extraAttrs = {};
296
+ if (participant) {
297
+ // when the retry request is not for a group
298
+ // only send to the specific device that asked for a retry
299
+ // otherwise the message is sent out to every device that should be a recipient
300
+ if (!isGroup && !isStatus) {
301
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
302
+ }
303
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
304
+ devices.push({ user, device });
305
+ }
306
+ await authState.keys.transaction(async () => {
307
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
308
+ const mediaType = getMediaType(message);
309
+ if (mediaType) {
310
+ extraAttrs['mediatype'] = mediaType;
311
+ }
312
+ if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
313
+ extraAttrs['decrypt-fail'] = 'hide';
314
+ }
315
+ if (isGroup || isStatus) {
316
+ const [groupData, senderKeyMap] = await Promise.all([
317
+ (async () => {
318
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
319
+ if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
320
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
321
+ }
322
+ else if (!isStatus) {
323
+ groupData = await groupMetadata(jid);
324
+ }
325
+ return groupData;
326
+ })(),
327
+ (async () => {
328
+ if (!participant && !isStatus) {
329
+ const result = await authState.keys.get('sender-key-memory', [jid]);
330
+ return result[jid] || {};
331
+ }
332
+ return {};
333
+ })()
334
+ ]);
335
+ if (!participant) {
336
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
337
+ if (isStatus && statusJidList) {
338
+ participantsList.push(...statusJidList);
339
+ }
340
+ if (!isStatus) {
341
+ additionalAttributes = {
342
+ ...additionalAttributes,
343
+ // eslint-disable-next-line camelcase
344
+ addressing_mode: (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) || 'pn'
345
+ };
346
+ }
347
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
348
+ devices.push(...additionalDevices);
349
+ }
350
+ const patched = await patchMessageBeforeSending(message);
351
+ if (Array.isArray(patched)) {
352
+ throw new boom_1.Boom('Per-jid patching is not supported in groups');
353
+ }
354
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
355
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
356
+ group: destinationJid,
357
+ data: bytes,
358
+ meId,
359
+ });
360
+ const senderKeyJids = [];
361
+ // ensure a connection is established with every device
362
+ for (const { user, device } of devices) {
363
+ const jid = (0, WABinary_1.jidEncode)(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
364
+ if (!senderKeyMap[jid] || !!participant) {
365
+ senderKeyJids.push(jid);
366
+ // store that this person has had the sender keys sent to them
367
+ senderKeyMap[jid] = true;
368
+ }
369
+ }
370
+ // if there are some participants with whom the session has not been established
371
+ // if there are, we re-send the senderkey
372
+ if (senderKeyJids.length) {
373
+ logger.debug({ senderKeyJids }, 'sending new sender key');
374
+ const senderKeyMsg = {
375
+ senderKeyDistributionMessage: {
376
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
377
+ groupId: destinationJid
378
+ }
379
+ };
380
+ await assertSessions(senderKeyJids, false);
381
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
382
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
383
+ participants.push(...result.nodes);
384
+ }
385
+ binaryNodeContent.push({
386
+ tag: 'enc',
387
+ attrs: { v: '2', type: 'skmsg' },
388
+ content: ciphertext
389
+ });
390
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
391
+ }
392
+ else if (isNewsletter) {
393
+ // Message edit
394
+ if ((_b = message.protocolMessage) === null || _b === void 0 ? void 0 : _b.editedMessage) {
395
+ msgId = (_c = message.protocolMessage.key) === null || _c === void 0 ? void 0 : _c.id;
396
+ message = message.protocolMessage.editedMessage;
397
+ }
398
+ // Message delete
399
+ if (((_d = message.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
400
+ msgId = (_e = message.protocolMessage.key) === null || _e === void 0 ? void 0 : _e.id;
401
+ message = {};
402
+ }
403
+ const patched = await patchMessageBeforeSending(message, []);
404
+ if (Array.isArray(patched)) {
405
+ throw new boom_1.Boom('Per-jid patching is not supported in channel');
406
+ }
407
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
408
+ binaryNodeContent.push({
409
+ tag: 'plaintext',
410
+ attrs: mediaType ? { mediatype: mediaType } : {},
411
+ content: bytes
412
+ });
413
+ }
414
+ else {
415
+ const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
416
+ if (!participant) {
417
+ devices.push({ user });
418
+ if (user !== meUser) {
419
+ devices.push({ user: meUser });
420
+ }
421
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
422
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
423
+ devices.push(...additionalDevices);
424
+ }
425
+ }
426
+
427
+ const allJids = [];
428
+ const meJids = [];
429
+ const otherJids = [];
430
+
431
+ const meLid = authState.creds.me?.lid;
432
+ const { user: mePnUser } = (0, WABinary_1.jidDecode)(meId);
433
+ const { user: meLidUser } = meLid
434
+ ? (0, WABinary_1.jidDecode)(meLid)
435
+ : { user: null };
436
+
437
+ for (const { user, device } of devices) {
438
+ const jid = (0, WABinary_1.jidEncode)(
439
+ user === meLidUser && isLid
440
+ ? (meLid?.split(":")[0] || user)
441
+ : user,
442
+ isLid ? "lid" : "s.whatsapp.net",
443
+ device
444
+ );
445
+
446
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
447
+ const isMe = user === mePnUser || user === meLidUser;
448
+
449
+ let skip = false;
450
+
451
+ if ((participant || onTarget) && !((0, WABinary_1.isJidGroup)(jid) || isStatus)) {
452
+ if (isExactSenderDevice) {
453
+ skip = true;
454
+ } else if (isMe) {
455
+ skip = true;
456
+ }
457
+ }
458
+
459
+ if (!skip) {
460
+ if (isMe) {
461
+ meJids.push(jid);
462
+ } else {
463
+ otherJids.push(jid);
464
+ }
465
+
466
+ allJids.push(jid);
467
+ }
468
+ }
469
+
470
+ await assertSessions(allJids, false);
471
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
472
+ createParticipantNodes(meJids, meMsg, extraAttrs),
473
+ createParticipantNodes(otherJids, message, extraAttrs)
474
+ ]);
475
+ participants.push(...meNodes);
476
+ participants.push(...otherNodes);
477
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
478
+ }
479
+ if (participants.length) {
480
+ if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
481
+ const peerNode = (_j = (_h = participants[0]) === null || _h === void 0 ? void 0 : _h.content) === null || _j === void 0 ? void 0 : _j[0];
482
+ if (peerNode) {
483
+ binaryNodeContent.push(peerNode); // push only enc
484
+ }
485
+ }
486
+ else {
487
+ binaryNodeContent.push({
488
+ tag: 'participants',
489
+ attrs: {},
490
+ content: participants
491
+ });
492
+ }
493
+ }
494
+ const stanza = {
495
+ tag: 'message',
496
+ attrs: {
497
+ id: msgId,
498
+ type: isNewsletter ? getTypeMessage(message) : 'text',
499
+ ...(additionalAttributes || {})
500
+ },
501
+ content: binaryNodeContent
502
+ };
503
+ // if the participant to send to is explicitly specified (generally retry recp)
504
+ // ensure the message is only sent to that person
505
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
506
+ if (participant) {
507
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
508
+ stanza.attrs.to = destinationJid;
509
+ stanza.attrs.participant = participant.jid;
510
+ }
511
+ else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
512
+ stanza.attrs.to = participant.jid;
513
+ stanza.attrs.recipient = destinationJid;
514
+ }
515
+ else {
516
+ stanza.attrs.to = participant.jid;
517
+ }
518
+ }
519
+ else {
520
+ stanza.attrs.to = destinationJid;
521
+ }
522
+ if (shouldIncludeDeviceIdentity) {
523
+ stanza.content.push({
524
+ tag: 'device-identity',
525
+ attrs: {},
526
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
527
+ });
528
+ logger.debug({ jid }, 'adding device identity');
529
+ }
530
+ if (additionalNodes && additionalNodes.length > 0) {
531
+ stanza.content.push(...additionalNodes);
532
+ }
533
+ const content = (0, Utils_1.normalizeMessageContent)(message);
534
+ const contentType = (0, Utils_1.getContentType)(content);
535
+ if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && (contentType === 'interactiveMessage' ||
536
+ contentType === 'buttonsMessage' ||
537
+ contentType === 'listMessage')) {
538
+ const bizNode = { tag: 'biz', attrs: {} };
539
+ if ((((_l = (_k = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _k === void 0 ? void 0 : _k.message) === null || _l === void 0 ? void 0 : _l.interactiveMessage) || ((_o = (_m = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _m === void 0 ? void 0 : _m.message) === null || _o === void 0 ? void 0 : _o.interactiveMessage) || ((_q = (_p = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _p === void 0 ? void 0 : _p.message) === null || _q === void 0 ? void 0 : _q.interactiveMessage) || (message === null || message === void 0 ? void 0 : message.interactiveMessage)) || (((_s = (_r = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _r === void 0 ? void 0 : _r.message) === null || _s === void 0 ? void 0 : _s.buttonsMessage) || ((_u = (_t = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _t === void 0 ? void 0 : _t.message) === null || _u === void 0 ? void 0 : _u.buttonsMessage) || ((_w = (_v = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _v === void 0 ? void 0 : _v.message) === null || _w === void 0 ? void 0 : _w.buttonsMessage) || (message === null || message === void 0 ? void 0 : message.buttonsMessage))) {
540
+ bizNode.content = [{
541
+ tag: 'interactive',
542
+ attrs: {
543
+ type: 'native_flow',
544
+ v: '1'
545
+ },
546
+ content: [{
547
+ tag: 'native_flow',
548
+ attrs: { v: '9', name: 'mixed' }
549
+ }]
550
+ }];
551
+ }
552
+ else if (message === null || message === void 0 ? void 0 : message.listMessage) {
553
+ // list message only support in private chat
554
+ bizNode.content = [{
555
+ tag: 'list',
556
+ attrs: {
557
+ type: 'product_list',
558
+ v: '2'
559
+ }
560
+ }];
561
+ }
562
+ stanza.content.push(bizNode);
563
+ }
564
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
565
+ await sendNode(stanza);
566
+ });
567
+ return msgId;
568
+ };
569
+ const getTypeMessage = (msg) => {
570
+ if (msg.viewOnceMessage) {
571
+ return getTypeMessage(msg.viewOnceMessage.message);
572
+ }
573
+ else if (msg.viewOnceMessageV2) {
574
+ return getTypeMessage(msg.viewOnceMessageV2.message);
575
+ }
576
+ else if (msg.viewOnceMessageV2Extension) {
577
+ return getTypeMessage(msg.viewOnceMessageV2Extension.message);
578
+ }
579
+ else if (msg.ephemeralMessage) {
580
+ return getTypeMessage(msg.ephemeralMessage.message);
581
+ }
582
+ else if (msg.documentWithCaptionMessage) {
583
+ return getTypeMessage(msg.documentWithCaptionMessage.message);
584
+ }
585
+ else if (msg.reactionMessage) {
586
+ return 'reaction';
587
+ }
588
+ else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
589
+ return 'poll';
590
+ }
591
+ else if (getMediaType(msg)) {
592
+ return 'media';
593
+ }
594
+ else {
595
+ return 'text';
596
+ }
597
+ };
598
+ const getMediaType = (message) => {
599
+ if (message.imageMessage) {
600
+ return 'image';
601
+ }
602
+ else if (message.videoMessage) {
603
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
604
+ }
605
+ else if (message.audioMessage) {
606
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
607
+ }
608
+ else if (message.contactMessage) {
609
+ return 'vcard';
610
+ }
611
+ else if (message.documentMessage) {
612
+ return 'document';
613
+ }
614
+ else if (message.contactsArrayMessage) {
615
+ return 'contact_array';
616
+ }
617
+ else if (message.liveLocationMessage) {
618
+ return 'livelocation';
619
+ }
620
+ else if (message.stickerMessage) {
621
+ return 'sticker';
622
+ }
623
+ else if (message.listMessage) {
624
+ return 'list';
625
+ }
626
+ else if (message.listResponseMessage) {
627
+ return 'list_response';
628
+ }
629
+ else if (message.buttonsResponseMessage) {
630
+ return 'buttons_response';
631
+ }
632
+ else if (message.orderMessage) {
633
+ return 'order';
634
+ }
635
+ else if (message.productMessage) {
636
+ return 'product';
637
+ }
638
+ else if (message.interactiveResponseMessage) {
639
+ return 'native_flow_response';
640
+ }
641
+ else if (message.groupInviteMessage) {
642
+ return 'url';
643
+ }
644
+ };
645
+ const getPrivacyTokens = async (jids) => {
646
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
647
+ const result = await query({
648
+ tag: 'iq',
649
+ attrs: {
650
+ to: WABinary_1.S_WHATSAPP_NET,
651
+ type: 'set',
652
+ xmlns: 'privacy'
653
+ },
654
+ content: [
655
+ {
656
+ tag: 'tokens',
657
+ attrs: {},
658
+ content: jids.map(jid => ({
659
+ tag: 'token',
660
+ attrs: {
661
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
662
+ t,
663
+ type: 'trusted_contact'
664
+ }
665
+ }))
666
+ }
667
+ ]
668
+ });
669
+ return result;
670
+ };
671
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
672
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
673
+ return {
674
+ ...sock,
675
+ getPrivacyTokens,
676
+ assertSessions,
677
+ relayMessage,
678
+ sendReceipt,
679
+ sendReceipts,
680
+ readMessages,
681
+ refreshMediaConn,
682
+ waUploadToServer,
683
+ fetchPrivacySettings,
684
+ getUSyncDevices,
685
+ createParticipantNodes,
686
+ sendPeerDataOperationMessage,
687
+ updateMediaMessage: async (message) => {
688
+ const content = (0, Utils_1.assertMediaContent)(message.message);
689
+ const mediaKey = content.mediaKey;
690
+ const meId = authState.creds.me.id;
691
+ const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
692
+ let error = undefined;
693
+ await Promise.all([
694
+ sendNode(node),
695
+ waitForMsgMediaUpdate(async (update) => {
696
+ const result = update.find(c => c.key.id === message.key.id);
697
+ if (result) {
698
+ if (result.error) {
699
+ error = result.error;
700
+ }
701
+ else {
702
+ try {
703
+ const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
704
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
705
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
706
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
707
+ }
708
+ content.directPath = media.directPath;
709
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
710
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
711
+ }
712
+ catch (err) {
713
+ error = err;
714
+ }
715
+ }
716
+ return true;
717
+ }
718
+ })
719
+ ]);
720
+ if (error) {
721
+ throw error;
722
+ }
723
+ ev.emit('messages.update', [
724
+ { key: message.key, update: { message: message.message } }
725
+ ]);
726
+ return message;
727
+ },
728
+ sendMessage: async (jid, content, options = {}) => {
729
+ var _a, _b, _c;
730
+ const userJid = authState.creds.me.id;
731
+ if (!options.ephemeralExpiration) {
732
+ if ((0, WABinary_1.isJidGroup)(jid)) {
733
+ const groups = await sock.groupQuery(jid, 'get', [{
734
+ tag: 'query',
735
+ attrs: {
736
+ request: 'interactive'
737
+ }
738
+ }]);
739
+ const metadata = (0, WABinary_1.getBinaryNodeChild)(groups, 'group');
740
+ const expiration = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(metadata, 'ephemeral')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.expiration) || 0;
741
+ options.ephemeralExpiration = expiration;
742
+ }
743
+ }
744
+ if (typeof content === 'object' &&
745
+ 'disappearingMessagesInChat' in content &&
746
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
747
+ (0, WABinary_1.isJidGroup)(jid)) {
748
+ const { disappearingMessagesInChat } = content;
749
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
750
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
751
+ disappearingMessagesInChat;
752
+ await groupToggleEphemeral(jid, value);
753
+ }
754
+ if (typeof content === 'object' && 'album' in content && content.album) {
755
+ const { album, caption } = content;
756
+ if (caption && !album[0].caption) {
757
+ album[0].caption = caption;
758
+ }
759
+ let mediaHandle;
760
+ let mediaMsg;
761
+ const albumMsg = (0, Utils_1.generateWAMessageFromContent)(jid, {
762
+ albumMessage: {
763
+ expectedImageCount: album.filter(item => 'image' in item).length,
764
+ expectedVideoCount: album.filter(item => 'video' in item).length
765
+ }
766
+ }, { userJid, ...options });
767
+ await relayMessage(jid, albumMsg.message, {
768
+ messageId: albumMsg.key.id
769
+ });
770
+ for (const i in album) {
771
+ const media = album[i];
772
+ if ('image' in media) {
773
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
774
+ image: media.image,
775
+ ...(media.caption ? { caption: media.caption } : {}),
776
+ ...options
777
+ }, {
778
+ userJid,
779
+ upload: async (readStream, opts) => {
780
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
781
+ mediaHandle = up.handle;
782
+ return up;
783
+ },
784
+ ...options,
785
+ });
786
+ }
787
+ else if ('video' in media) {
788
+ mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
789
+ video: media.video,
790
+ ...(media.caption ? { caption: media.caption } : {}),
791
+ ...(media.gifPlayback !== undefined ? { gifPlayback: media.gifPlayback } : {}),
792
+ ...options
793
+ }, {
794
+ userJid,
795
+ upload: async (readStream, opts) => {
796
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
797
+ mediaHandle = up.handle;
798
+ return up;
799
+ },
800
+ ...options,
801
+ });
802
+ }
803
+ if (mediaMsg) {
804
+ mediaMsg.message.messageContextInfo = {
805
+ messageSecret: (0, crypto_1.randomBytes)(32),
806
+ messageAssociation: {
807
+ associationType: 1,
808
+ parentMessageKey: albumMsg.key
809
+ }
810
+ };
811
+ }
812
+ await relayMessage(jid, mediaMsg.message, {
813
+ messageId: mediaMsg.key.id
814
+ });
815
+ if (albumMessageItemDelayMs > 0) {
816
+ await new Promise(resolve => setTimeout(resolve, albumMessageItemDelayMs));
817
+ }
818
+ }
819
+ return albumMsg;
820
+ }
821
+ else {
822
+ let mediaHandle;
823
+ const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
824
+ logger,
825
+ userJid,
826
+ getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
827
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
828
+ fetchOpts: {
829
+ timeout: 3000,
830
+ ...axiosOptions || {}
831
+ },
832
+ logger,
833
+ uploadImage: generateHighQualityLinkPreview
834
+ ? waUploadToServer
835
+ : undefined
836
+ }),
837
+ getProfilePicUrl: sock.profilePictureUrl,
838
+ upload: async (readStream, opts) => {
839
+ const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
840
+ mediaHandle = up.handle;
841
+ return up;
842
+ },
843
+ mediaCache: config.mediaCache,
844
+ options: config.options,
845
+ messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
846
+ ...options,
847
+ });
848
+ const isDeleteMsg = 'delete' in content && !!content.delete;
849
+ const isEditMsg = 'edit' in content && !!content.edit;
850
+ const isPinMsg = 'pin' in content && !!content.pin;
851
+ const isKeepMsg = 'keep' in content && content.keep;
852
+ const isPollMessage = 'poll' in content && !!content.poll;
853
+ const isAiMsg = 'ai' in content && !!content.ai;
854
+ const additionalAttributes = {};
855
+ const additionalNodes = [];
856
+ // required for delete
857
+ if (isDeleteMsg) {
858
+ // if the chat is a group, and I am not the author, then delete the message as an admin
859
+ if (((0, WABinary_1.isJidGroup)(content.delete.remoteJid) && !content.delete.fromMe) || (0, WABinary_1.isJidNewsletter)(jid)) {
860
+ additionalAttributes.edit = '8';
861
+ }
862
+ else {
863
+ additionalAttributes.edit = '7';
864
+ }
865
+ // required for edit message
866
+ }
867
+ else if (isEditMsg) {
868
+ additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
869
+ // required for pin message
870
+ }
871
+ else if (isPinMsg) {
872
+ additionalAttributes.edit = '2';
873
+ // required for keep message
874
+ }
875
+ else if (isKeepMsg) {
876
+ additionalAttributes.edit = '6';
877
+ // required for polling message
878
+ }
879
+ else if (isPollMessage) {
880
+ additionalNodes.push({
881
+ tag: 'meta',
882
+ attrs: {
883
+ polltype: 'creation'
884
+ },
885
+ });
886
+ // required to display AI icon on message
887
+ }
888
+ else if (isAiMsg) {
889
+ additionalNodes.push({
890
+ attrs: {
891
+ biz_bot: '1'
892
+ },
893
+ tag: "bot"
894
+ });
895
+ }
896
+ if (mediaHandle) {
897
+ additionalAttributes['media_id'] = mediaHandle;
898
+ }
899
+ if ('cachedGroupMetadata' in options) {
900
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
901
+ }
902
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
903
+ if (config.emitOwnEvents) {
904
+ process.nextTick(() => {
905
+ processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
906
+ });
907
+ }
908
+ return fullMsg;
909
+ }
910
+ }
911
+ };
912
+ };
913
+ exports.makeMessagesSocket = makeMessagesSocket;