@zannstore/baileys 2.2.6

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 (108) hide show
  1. package/README.md +13 -0
  2. package/WAProto/index.js +169661 -0
  3. package/engine-requirements.js +10 -0
  4. package/lib/Defaults/baileys-version.json +3 -0
  5. package/lib/Defaults/index.js +147 -0
  6. package/lib/Defaults/phonenumber-mcc.json +223 -0
  7. package/lib/Function/Download/tiktok.js +19 -0
  8. package/lib/Function/Tools/bypass.js +19 -0
  9. package/lib/Function/index.js +13 -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 +360 -0
  24. package/lib/Signal/lid-mapping.js +166 -0
  25. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  26. package/lib/Socket/Client/index.js +19 -0
  27. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  28. package/lib/Socket/Client/web-socket-client.js +62 -0
  29. package/lib/Socket/business.js +310 -0
  30. package/lib/Socket/chats.js +1145 -0
  31. package/lib/Socket/community.js +392 -0
  32. package/lib/Socket/dugong.js +658 -0
  33. package/lib/Socket/groups.js +317 -0
  34. package/lib/Socket/index.js +11 -0
  35. package/lib/Socket/messages-recv.js +1145 -0
  36. package/lib/Socket/messages-send.js +936 -0
  37. package/lib/Socket/newsletter.js +437 -0
  38. package/lib/Socket/registration.js +167 -0
  39. package/lib/Socket/socket.js +733 -0
  40. package/lib/Socket/usync.js +70 -0
  41. package/lib/Store/index.js +10 -0
  42. package/lib/Store/make-cache-manager-store.js +83 -0
  43. package/lib/Store/make-in-memory-store.js +427 -0
  44. package/lib/Store/make-ordered-dictionary.js +81 -0
  45. package/lib/Store/object-repository.js +27 -0
  46. package/lib/Types/Auth.js +2 -0
  47. package/lib/Types/Call.js +2 -0
  48. package/lib/Types/Chat.js +4 -0
  49. package/lib/Types/Contact.js +2 -0
  50. package/lib/Types/Events.js +2 -0
  51. package/lib/Types/GroupMetadata.js +2 -0
  52. package/lib/Types/Label.js +27 -0
  53. package/lib/Types/LabelAssociation.js +9 -0
  54. package/lib/Types/Message.js +10 -0
  55. package/lib/Types/MexUpdates.js +15 -0
  56. package/lib/Types/Newsletter.js +38 -0
  57. package/lib/Types/Product.js +2 -0
  58. package/lib/Types/Signal.js +2 -0
  59. package/lib/Types/Socket.js +2 -0
  60. package/lib/Types/State.js +2 -0
  61. package/lib/Types/USync.js +2 -0
  62. package/lib/Types/index.js +45 -0
  63. package/lib/Utils/auth-utils.js +206 -0
  64. package/lib/Utils/baileys-event-stream.js +63 -0
  65. package/lib/Utils/bot-toolkit.js +455 -0
  66. package/lib/Utils/business.js +234 -0
  67. package/lib/Utils/chat-utils.js +729 -0
  68. package/lib/Utils/crypto.js +151 -0
  69. package/lib/Utils/decode-wa-message.js +286 -0
  70. package/lib/Utils/event-buffer.js +530 -0
  71. package/lib/Utils/generics.js +527 -0
  72. package/lib/Utils/history.js +96 -0
  73. package/lib/Utils/index.js +34 -0
  74. package/lib/Utils/link-preview.js +93 -0
  75. package/lib/Utils/logger.js +7 -0
  76. package/lib/Utils/lt-hash.js +51 -0
  77. package/lib/Utils/make-mutex.js +43 -0
  78. package/lib/Utils/messages-media.js +819 -0
  79. package/lib/Utils/messages.js +787 -0
  80. package/lib/Utils/noise-handler.js +155 -0
  81. package/lib/Utils/process-message.js +321 -0
  82. package/lib/Utils/signal.js +153 -0
  83. package/lib/Utils/tc-token-utils.js +114 -0
  84. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  85. package/lib/Utils/validate-connection.js +229 -0
  86. package/lib/WABinary/constants.js +40 -0
  87. package/lib/WABinary/decode.js +252 -0
  88. package/lib/WABinary/encode.js +265 -0
  89. package/lib/WABinary/generic-utils.js +240 -0
  90. package/lib/WABinary/index.js +21 -0
  91. package/lib/WABinary/jid-utils.js +122 -0
  92. package/lib/WABinary/types.js +2 -0
  93. package/lib/WAM/BinaryInfo.js +13 -0
  94. package/lib/WAM/constants.js +15350 -0
  95. package/lib/WAM/encode.js +155 -0
  96. package/lib/WAM/index.js +19 -0
  97. package/lib/WAUSync/Protocols/USyncContactProtocol.js +40 -0
  98. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  99. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  100. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  101. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  102. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  103. package/lib/WAUSync/Protocols/index.js +20 -0
  104. package/lib/WAUSync/USyncQuery.js +89 -0
  105. package/lib/WAUSync/USyncUser.js +32 -0
  106. package/lib/WAUSync/index.js +19 -0
  107. package/lib/index.js +52 -0
  108. package/package.json +117 -0
@@ -0,0 +1,936 @@
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("node-cache"));
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const Types_1 = require("../Types");
12
+ const Utils_1 = require("../Utils");
13
+ const link_preview_1 = require("../Utils/link-preview");
14
+ const WABinary_1 = require("../WABinary");
15
+ const newsletter_1 = require("./newsletter");
16
+ const WAUSync_1 = require("../WAUSync");
17
+ const { isTcTokenExpired, shouldSendNewTcToken, resolveTcTokenJid, resolveIssuanceJid, buildMergedTcTokenIndexWrite, storeTcTokensFromIqResult } = require("../Utils/tc-token-utils");
18
+ const kikyy = require('./dugong');
19
+ const makeMessagesSocket = (config) => {
20
+ const {
21
+ logger,
22
+ linkPreviewImageThumbnailWidth,
23
+ generateHighQualityLinkPreview,
24
+ options: axiosOptions,
25
+ patchMessageBeforeSending
26
+ } = config;
27
+ const sock = (0, newsletter_1.makeNewsletterSocket)(config);
28
+ const {
29
+ ev,
30
+ authState,
31
+ processingMutex,
32
+ signalRepository,
33
+ upsertMessage,
34
+ query,
35
+ fetchPrivacySettings,
36
+ sendNode,
37
+ groupMetadata,
38
+ groupToggleEphemeral,
39
+ executeUSyncQuery
40
+ } = sock;
41
+ const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
42
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
43
+ useClones: false
44
+ });
45
+ let mediaConn;
46
+ const refreshMediaConn = async (forceGet = false) => {
47
+ const media = await mediaConn;
48
+ if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
49
+ mediaConn = (async () => {
50
+ const result = await query({
51
+ tag: 'iq',
52
+ attrs: {
53
+ type: 'set',
54
+ xmlns: 'w:m',
55
+ to: WABinary_1.S_WHATSAPP_NET,
56
+ },
57
+ content: [{ tag: 'media_conn', attrs: {} }]
58
+ });
59
+ const mediaConnNode = WABinary_1.getBinaryNodeChild(result, 'media_conn');
60
+ const node = {
61
+ hosts: WABinary_1.getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
62
+ hostname: attrs.hostname,
63
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
64
+ })),
65
+ auth: mediaConnNode.attrs.auth,
66
+ ttl: +mediaConnNode.attrs.ttl,
67
+ fetchDate: new Date()
68
+ };
69
+ logger.debug('fetched media conn');
70
+ return node;
71
+ })();
72
+ }
73
+ return mediaConn;
74
+ };
75
+ const sendReceipt = async (jid, participant, messageIds, type) => {
76
+ const node = {
77
+ tag: 'receipt',
78
+ attrs: {
79
+ id: messageIds[0],
80
+ },
81
+ };
82
+ const isReadReceipt = type === 'read' || type === 'read-self';
83
+ if (isReadReceipt) {
84
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
85
+ }
86
+ if (type === 'sender' && WABinary_1.isJidUser(jid)) {
87
+ node.attrs.recipient = jid;
88
+ node.attrs.to = participant;
89
+ }
90
+ else {
91
+ node.attrs.to = jid;
92
+ if (participant) {
93
+ node.attrs.participant = participant;
94
+ }
95
+ }
96
+ if (type) {
97
+ node.attrs.type = WABinary_1.isJidNewsLetter(jid) ? 'read-self' : type;
98
+ }
99
+ const remainingMessageIds = messageIds.slice(1);
100
+ if (remainingMessageIds.length) {
101
+ node.content = [
102
+ {
103
+ tag: 'list',
104
+ attrs: {},
105
+ content: remainingMessageIds.map(id => ({
106
+ tag: 'item',
107
+ attrs: { id }
108
+ }))
109
+ }
110
+ ];
111
+ }
112
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
113
+ await sendNode(node);
114
+ };
115
+ const sendReceipts = async (keys, type) => {
116
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
117
+ for (const { jid, participant, messageIds } of recps) {
118
+ await sendReceipt(jid, participant, messageIds, type);
119
+ }
120
+ };
121
+ const readMessages = async (keys) => {
122
+ const privacySettings = await fetchPrivacySettings();
123
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
124
+ await sendReceipts(keys, readType);
125
+ };
126
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
127
+ const deviceResults = []
128
+ if (!useCache) {
129
+ logger.debug('not using cache for devices')
130
+ }
131
+ const toFetch = []
132
+ jids = Array.from(new Set(jids))
133
+ for (let jid of jids) {
134
+ const user = WABinary_1.jidDecode(jid)?.user
135
+ jid = WABinary_1.jidNormalizedUser(jid)
136
+ if (useCache) {
137
+ const devices = userDevicesCache.get(user)
138
+ if (devices) {
139
+ deviceResults.push(...devices)
140
+ logger.trace({ user }, 'using cache for devices')
141
+ }
142
+ else {
143
+ toFetch.push(jid)
144
+ }
145
+ }
146
+ else {
147
+ toFetch.push(jid)
148
+ }
149
+ }
150
+ if (!toFetch.length) {
151
+ return deviceResults
152
+ }
153
+ const query = new WAUSync_1.USyncQuery()
154
+ .withContext('message')
155
+ .withDeviceProtocol()
156
+ for (const jid of toFetch) {
157
+ query.withUser(new WAUSync_1.USyncUser().withId(jid))
158
+ }
159
+ let result = await executeUSyncQuery(query)
160
+ if (!result) {
161
+ logger.debug({ toFetch }, 'usync device query empty, retrying once')
162
+ result = await executeUSyncQuery(query)
163
+ }
164
+ if (result) {
165
+ const extracted = Utils_1.extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices)
166
+ const deviceMap = {}
167
+ for (const item of extracted) {
168
+ deviceMap[item.user] = deviceMap[item.user] || []
169
+ deviceMap[item.user].push(item)
170
+ deviceResults.push(item)
171
+ }
172
+ for (const key in deviceMap) {
173
+ userDevicesCache.set(key, deviceMap[key])
174
+ }
175
+ }
176
+ return deviceResults
177
+ }
178
+ const assertSessions = async (jids, force) => {
179
+ let didFetchNewSession = false;
180
+ let jidsRequiringFetch = [];
181
+ if (force) {
182
+ jidsRequiringFetch = jids;
183
+ }
184
+ else {
185
+ const addrs = jids.map(jid => (signalRepository
186
+ .jidToSignalProtocolAddress(jid)));
187
+ const sessions = await authState.keys.get('session', addrs);
188
+ for (const jid of jids) {
189
+ const signalId = signalRepository
190
+ .jidToSignalProtocolAddress(jid);
191
+ if (!sessions[signalId]) {
192
+ jidsRequiringFetch.push(jid);
193
+ }
194
+ }
195
+ }
196
+ if (jidsRequiringFetch.length) {
197
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
198
+ const result = await query({
199
+ tag: 'iq',
200
+ attrs: {
201
+ xmlns: 'encrypt',
202
+ type: 'get',
203
+ to: WABinary_1.S_WHATSAPP_NET,
204
+ },
205
+ content: [
206
+ {
207
+ tag: 'key',
208
+ attrs: {},
209
+ content: jidsRequiringFetch.map(jid => ({
210
+ tag: 'user',
211
+ attrs: { jid },
212
+ }))
213
+ }
214
+ ]
215
+ });
216
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
217
+ didFetchNewSession = true;
218
+ }
219
+ return didFetchNewSession;
220
+ };
221
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
222
+ if (!authState.creds.me?.id) {
223
+ throw new boom_1.Boom('Not authenticated')
224
+ }
225
+ const protocolMessage = {
226
+ protocolMessage: {
227
+ peerDataOperationRequestMessage: pdoMessage,
228
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
229
+ }
230
+ };
231
+ const meJid = WABinary_1.jidNormalizedUser(authState.creds.me.id);
232
+ const msgId = await relayMessage(meJid, protocolMessage, {
233
+ additionalAttributes: {
234
+ category: 'peer',
235
+ push_priority: 'high_force',
236
+ },
237
+ });
238
+ return msgId;
239
+ };
240
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
241
+ const patched = await patchMessageBeforeSending(message, jids);
242
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
243
+ let shouldIncludeDeviceIdentity = false;
244
+ const nodes = (await Promise.all(jids.map(async (jid) => {
245
+ try {
246
+ const { type, ciphertext } = await signalRepository
247
+ .encryptMessage({ jid, data: bytes });
248
+ if (type === 'pkmsg') {
249
+ shouldIncludeDeviceIdentity = true;
250
+ }
251
+ const node = {
252
+ tag: 'to',
253
+ attrs: { jid },
254
+ content: [{
255
+ tag: 'enc',
256
+ attrs: {
257
+ v: '2',
258
+ type,
259
+ ...extraAttrs || {}
260
+ },
261
+ content: ciphertext
262
+ }]
263
+ };
264
+ return node;
265
+ }
266
+ catch (error) {
267
+ logger.warn({ jid, trace: error?.stack, err: error?.toString?.() ?? error }, 'failed to encrypt message for device, skipping (no session?)');
268
+ return null;
269
+ }
270
+ }))).filter(Boolean);
271
+ return { nodes, shouldIncludeDeviceIdentity };
272
+ };
273
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList, AI = true }) => {
274
+ const meId = authState.creds.me.id;
275
+ const meLid = authState.creds.me.lid;
276
+ let shouldIncludeDeviceIdentity = false;
277
+ let didPushAdditional = false
278
+ const { user, server } = WABinary_1.jidDecode(jid);
279
+ const statusJid = 'status@broadcast';
280
+ const isGroup = server === 'g.us';
281
+ const isStatus = jid === statusJid;
282
+ const isLid = server === 'lid';
283
+ const isPrivate = server === 's.whatsapp.net'
284
+ const isNewsletter = server === 'newsletter';
285
+ msgId = msgId || (0, Utils_1.generateMessageID)();
286
+ useUserDevicesCache = useUserDevicesCache !== false;
287
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
288
+ const participants = [];
289
+ const destinationJid = (!isStatus) ? WABinary_1.jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
290
+ const binaryNodeContent = [];
291
+ const devices = [];
292
+ const meMsg = {
293
+ deviceSentMessage: {
294
+ destinationJid,
295
+ message
296
+ }
297
+ };
298
+ const extraAttrs = {}
299
+ const messages = Utils_1.normalizeMessageContent(message);
300
+ const buttonType = getButtonType(messages);
301
+ if (participant) {
302
+ if (!isGroup && !isStatus) {
303
+ additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
304
+ }
305
+ const { user, device } = WABinary_1.jidDecode(participant.jid);
306
+ devices.push({ user, device });
307
+ }
308
+ await authState.keys.transaction(async () => {
309
+ const mediaType = getMediaType(messages);
310
+ if (mediaType) {
311
+ extraAttrs['mediatype'] = mediaType
312
+ }
313
+ if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
314
+ extraAttrs['decrypt-fail'] = 'hide'
315
+ }
316
+ if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
317
+ extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
318
+ }
319
+ if (isGroup || isStatus) {
320
+ const [groupData, senderKeyMap] = await Promise.all([
321
+ (async () => {
322
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined
323
+ if (groupData) {
324
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
325
+ }
326
+ else if (!isStatus) {
327
+ groupData = await groupMetadata(jid)
328
+ }
329
+ return groupData;
330
+ })(),
331
+ (async () => {
332
+ if (!participant && !isStatus) {
333
+ const result = await authState.keys.get('sender-key-memory', [jid])
334
+ return result[jid] || {}
335
+ }
336
+ return {}
337
+ })()
338
+ ]);
339
+ if (!participant) {
340
+ const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : []
341
+ if (isStatus && statusJidList) {
342
+ participantsList.push(...statusJidList)
343
+ }
344
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
345
+ devices.push(...additionalDevices)
346
+ }
347
+ if (groupData && !groupData.addressingMode && groupData.participants?.length) {
348
+ const lidCount = groupData.participants.filter(p => WABinary_1.isLidUser(p.id)).length
349
+ if (lidCount > 0 && lidCount === groupData.participants.length) {
350
+ groupData.addressingMode = 'lid'
351
+ logger.trace({ jid }, 'inferred addressingMode=lid from participant jid suffix (fallback)')
352
+ }
353
+ }
354
+ const patched = await patchMessageBeforeSending(message, devices.map(d => WABinary_1.jidEncode(d.user, isLid ? 'lid' : 's.whatsapp.net', d.device)));
355
+ const bytes = Utils_1.encodeWAMessage(patched);
356
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
357
+ group: destinationJid,
358
+ data: bytes,
359
+ meId,
360
+ });
361
+ const senderKeyJids = [];
362
+ const myRecipients = [];
363
+ const peerRecipients = [];
364
+ const { user: selfPnUser } = WABinary_1.jidDecode(meId);
365
+ const { user: selfLidUser } = meLid ? WABinary_1.jidDecode(meLid) : { user: null };
366
+ for (const { user, device } of devices) {
367
+ const targetJid = WABinary_1.jidEncode(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
368
+ const isSendingDeviceItself = targetJid === meId || (meLid && targetJid === meLid);
369
+ if (isSendingDeviceItself) {
370
+ logger.debug({ targetJid, meId, meLid }, 'skipping sender\'s own device for sender-key distribution');
371
+ continue;
372
+ }
373
+ const belongsToSelf = user === selfPnUser || user === selfLidUser;
374
+ const isSkippedAsOwnDeviceDuringTargetedResend = !!participant && !(0, WABinary_1.isJidGroup)(targetJid) && !isStatus && belongsToSelf;
375
+ if (isSkippedAsOwnDeviceDuringTargetedResend) {
376
+ continue;
377
+ }
378
+ (belongsToSelf ? myRecipients : peerRecipients).push(targetJid);
379
+ if (!senderKeyMap[targetJid] || !!participant) {
380
+ senderKeyJids.push(targetJid);
381
+ senderKeyMap[targetJid] = true;
382
+ }
383
+ }
384
+ if (senderKeyJids.length) {
385
+ logger.debug({ senderKeyJids }, 'sending new sender key');
386
+ const senderKeyMsg = {
387
+ senderKeyDistributionMessage: {
388
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
389
+ groupId: destinationJid
390
+ }
391
+ };
392
+ await assertSessions(senderKeyJids, false);
393
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs)
394
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
395
+ participants.push(...result.nodes);
396
+ }
397
+ binaryNodeContent.push({
398
+ tag: 'enc',
399
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
400
+ content: ciphertext
401
+ });
402
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
403
+ }
404
+ else if (isNewsletter) {
405
+ if (message.protocolMessage?.editedMessage) {
406
+ msgId = message.protocolMessage.key?.id
407
+ message = message.protocolMessage.editedMessage
408
+ }
409
+ if (message.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
410
+ msgId = message.protocolMessage.key?.id
411
+ message = {}
412
+ }
413
+ const patched = await patchMessageBeforeSending(message, [])
414
+ const bytes = Utils_1.encodeNewsletterMessage(patched)
415
+ binaryNodeContent.push({
416
+ tag: 'plaintext',
417
+ attrs: extraAttrs ? extraAttrs : {},
418
+ content: bytes
419
+ })
420
+ }
421
+ else {
422
+ const { user: meUser } = WABinary_1.jidDecode(meId);
423
+ if (!participant) {
424
+ devices.push({ user })
425
+ if (user !== meUser) {
426
+ devices.push({ user: meUser })
427
+ }
428
+ if (additionalAttributes?.['category'] !== 'peer') {
429
+ const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true)
430
+ devices.push(...additionalDevices)
431
+ }
432
+ }
433
+ const allJids = [];
434
+ const meJids = [];
435
+ const otherJids = [];
436
+ for (const { user, device } of devices) {
437
+ const isMe = user === meUser
438
+ const jid = WABinary_1.jidEncode(isMe && isLid ? authState.creds?.me?.lid?.split(':')[0] || user : user, isLid ? 'lid' : 's.whatsapp.net', device)
439
+ if (isMe) {
440
+ meJids.push(jid)
441
+ }
442
+ else {
443
+ otherJids.push(jid)
444
+ }
445
+ allJids.push(jid)
446
+ }
447
+ await assertSessions(allJids, false);
448
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
449
+ createParticipantNodes(meJids, meMsg, extraAttrs),
450
+ createParticipantNodes(otherJids, message, extraAttrs)
451
+ ])
452
+ participants.push(...meNodes);
453
+ participants.push(...otherNodes);
454
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
455
+ }
456
+ if (participants.length) {
457
+ if (additionalAttributes?.['category'] === 'peer') {
458
+ const peerNode = participants[0]?.content?.[0]
459
+ if (peerNode) {
460
+ binaryNodeContent.push(peerNode)
461
+ }
462
+ }
463
+ else {
464
+ binaryNodeContent.push({
465
+ tag: 'participants',
466
+ attrs: {},
467
+ content: participants
468
+ })
469
+ }
470
+ }
471
+ const stanza = {
472
+ tag: 'message',
473
+ attrs: {
474
+ id: msgId,
475
+ type: getTypeMessage(messages),
476
+ ...(additionalAttributes || {})
477
+ },
478
+ content: binaryNodeContent
479
+ }
480
+ if (participant) {
481
+ if (WABinary_1.isJidGroup(destinationJid)) {
482
+ stanza.attrs.to = destinationJid;
483
+ stanza.attrs.participant = participant.jid;
484
+ }
485
+ else if (WABinary_1.areJidsSameUser(participant.jid, meId)) {
486
+ stanza.attrs.to = participant.jid;
487
+ stanza.attrs.recipient = destinationJid;
488
+ }
489
+ else {
490
+ stanza.attrs.to = participant.jid;
491
+ }
492
+ }
493
+ else {
494
+ stanza.attrs.to = destinationJid;
495
+ }
496
+ if (shouldIncludeDeviceIdentity) {
497
+ stanza.content.push({
498
+ tag: 'device-identity',
499
+ attrs: {},
500
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
501
+ });
502
+ logger.debug({ jid }, 'adding device identity');
503
+ }
504
+ if (AI && isPrivate) {
505
+ const botNode = {
506
+ tag: 'bot',
507
+ attrs: {
508
+ biz_bot: '1'
509
+ }
510
+ }
511
+ const filteredBizBot = WABinary_1.getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
512
+ if (filteredBizBot) {
513
+ stanza.content.push(...additionalNodes)
514
+ didPushAdditional = true
515
+ }
516
+ else {
517
+ stanza.content.push(botNode)
518
+ }
519
+ }
520
+ if (!isNewsletter && buttonType && !isStatus) {
521
+ const content = WABinary_1.getAdditionalNode(buttonType)
522
+ const filteredNode = WABinary_1.getBinaryNodeFilter(additionalNodes)
523
+ if (filteredNode) {
524
+ didPushAdditional = true
525
+ stanza.content.push(...additionalNodes)
526
+ }
527
+ else {
528
+ stanza.content.push(...content)
529
+ }
530
+ logger.debug({ jid }, 'adding business node')
531
+ }
532
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
533
+ stanza.content.push(...additionalNodes);
534
+ }
535
+ const is1on1Send = isPrivate && !isStatus;
536
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
537
+ let tcTokenJid = jid;
538
+ let existingTokenEntry;
539
+ if (is1on1Send) {
540
+ try {
541
+ tcTokenJid = await resolveTcTokenJid(jid, getLIDForPN);
542
+ const contactTcTokenData = await authState.keys.get('tctoken', [tcTokenJid]);
543
+ existingTokenEntry = contactTcTokenData[tcTokenJid];
544
+ if (existingTokenEntry?.token?.length && !isTcTokenExpired(existingTokenEntry?.timestamp)) {
545
+ stanza.content.push({
546
+ tag: 'tctoken',
547
+ attrs: { t: String(existingTokenEntry.timestamp) },
548
+ content: existingTokenEntry.token
549
+ });
550
+ }
551
+ }
552
+ catch (err) {
553
+ logger.debug({ err }, 'tctoken attach failed, sending without it');
554
+ }
555
+ }
556
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
557
+ await sendNode(stanza);
558
+ if (is1on1Send) {
559
+ try {
560
+ const isProtocolMsg = !!Types_1.WAProto.Message.fromObject(message)?.protocolMessage;
561
+ const isBotOrPSA = jid === WABinary_1.PSA_WID || WABinary_1.isJidBot(jid) || WABinary_1.isJidMetaAI(jid);
562
+ if (!isProtocolMsg && !isBotOrPSA && shouldSendNewTcToken(existingTokenEntry?.senderTimestamp)) {
563
+ const issueTimestamp = (0, Utils_1.unixTimestampSeconds)();
564
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
565
+ resolveIssuanceJid(jid, !!sock.serverProps?.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
566
+ .then((issueJid) => sock.issuePrivacyTokens ? sock.issuePrivacyTokens([issueJid], issueTimestamp) : null)
567
+ .then(async (result) => {
568
+ if (!result) {
569
+ return;
570
+ }
571
+ await storeTcTokensFromIqResult({ result, fallbackJid: tcTokenJid, keys: authState.keys, getLIDForPN });
572
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
573
+ await authState.keys.set({ tctoken: indexWrite });
574
+ })
575
+ .catch((err) => logger.debug({ err }, 'tctoken issuance failed'));
576
+ }
577
+ }
578
+ catch (err) {
579
+ logger.debug({ err }, 'tctoken post-send issuance setup failed');
580
+ }
581
+ }
582
+ });
583
+ message = Types_1.WAProto.Message.fromObject(message)
584
+ const messageJSON = {
585
+ key: {
586
+ remoteJid: jid,
587
+ fromMe: true,
588
+ id: msgId
589
+ },
590
+ message: message,
591
+ messageTimestamp: Utils_1.unixTimestampSeconds(new Date()),
592
+ messageStubParameters: [],
593
+ participant: WABinary_1.isJidGroup(jid) || WABinary_1.isJidStatusBroadcast(jid) ? meId : undefined,
594
+ status: Types_1.WAMessageStatus.PENDING
595
+ }
596
+ return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON);
597
+ };
598
+ const getTypeMessage = (msg) => {
599
+ const message = Utils_1.normalizeMessageContent(msg);
600
+ if (message.reactionMessage) {
601
+ return 'reaction'
602
+ }
603
+ else if (getMediaType(message)) {
604
+ return 'media'
605
+ }
606
+ else {
607
+ return 'text'
608
+ }
609
+ }
610
+ const getMediaType = (message) => {
611
+ if (message.imageMessage) {
612
+ return 'image'
613
+ }
614
+ else if (message.videoMessage) {
615
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
616
+ }
617
+ else if (message.audioMessage) {
618
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
619
+ }
620
+ else if (message.contactMessage) {
621
+ return 'vcard'
622
+ }
623
+ else if (message.documentMessage) {
624
+ return 'document'
625
+ }
626
+ else if (message.contactsArrayMessage) {
627
+ return 'contact_array'
628
+ }
629
+ else if (message.liveLocationMessage) {
630
+ return 'livelocation'
631
+ }
632
+ else if (message.stickerMessage) {
633
+ return 'sticker'
634
+ }
635
+ else if (message.listMessage) {
636
+ return 'list'
637
+ }
638
+ else if (message.listResponseMessage) {
639
+ return 'list_response'
640
+ }
641
+ else if (message.buttonsResponseMessage) {
642
+ return 'buttons_response'
643
+ }
644
+ else if (message.orderMessage) {
645
+ return 'order'
646
+ }
647
+ else if (message.productMessage) {
648
+ return 'product'
649
+ }
650
+ else if (message.interactiveResponseMessage) {
651
+ return 'native_flow_response'
652
+ }
653
+ else if (message.groupInviteMessage) {
654
+ return 'url'
655
+ }
656
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
657
+ return 'productlink'
658
+ }
659
+ }
660
+ const getButtonType = (message) => {
661
+ if (message.listMessage) {
662
+ return 'list'
663
+ }
664
+ else if (message.buttonsMessage) {
665
+ return 'buttons'
666
+ }
667
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
668
+ return 'review_and_pay'
669
+ }
670
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
671
+ return 'review_order'
672
+ }
673
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
674
+ return 'payment_info'
675
+ }
676
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
677
+ return 'payment_status'
678
+ }
679
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
680
+ return 'payment_method'
681
+ }
682
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_key_info') {
683
+ return 'payment_key_info'
684
+ }
685
+ else if (message.listMessage?.listType === Types_1.WAProto.Message.ListMessage.ListType.PRODUCT_LIST) {
686
+ return 'catalog_message'
687
+ }
688
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
689
+ return 'interactive'
690
+ }
691
+ else if (message.interactiveMessage?.nativeFlowMessage) {
692
+ return 'native_flow'
693
+ }
694
+ }
695
+ const getPrivacyTokens = async (jids) => {
696
+ const t = Utils_1.unixTimestampSeconds().toString();
697
+ const result = await query({
698
+ tag: 'iq',
699
+ attrs: {
700
+ to: WABinary_1.S_WHATSAPP_NET,
701
+ type: 'set',
702
+ xmlns: 'privacy'
703
+ },
704
+ content: [
705
+ {
706
+ tag: 'tokens',
707
+ attrs: {},
708
+ content: jids.map(jid => ({
709
+ tag: 'token',
710
+ attrs: {
711
+ jid: WABinary_1.jidNormalizedUser(jid),
712
+ t,
713
+ type: 'trusted_contact'
714
+ }
715
+ }))
716
+ }
717
+ ]
718
+ });
719
+ return result;
720
+ }
721
+ /** */
722
+ const issuePrivacyTokens = async (jids, timestamp) => {
723
+ const t = (timestamp !== undefined ? timestamp : (0, Utils_1.unixTimestampSeconds)()).toString();
724
+ const result = await query({
725
+ tag: 'iq',
726
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, type: 'set', xmlns: 'privacy' },
727
+ content: [
728
+ {
729
+ tag: 'tokens',
730
+ attrs: {},
731
+ content: jids.map((jid) => ({
732
+ tag: 'token',
733
+ attrs: { jid: WABinary_1.jidNormalizedUser(jid), t, type: 'trusted_contact' }
734
+ }))
735
+ }
736
+ ]
737
+ });
738
+ return result;
739
+ };
740
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
741
+ const rahmi = new kikyy(Utils_1, waUploadToServer, relayMessage, config, sock);
742
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
743
+ return {
744
+ ...sock,
745
+ issuePrivacyTokens,
746
+ getPrivacyTokens,
747
+ assertSessions,
748
+ relayMessage,
749
+ sendReceipt,
750
+ sendReceipts,
751
+ rahmi,
752
+ readMessages,
753
+ refreshMediaConn,
754
+ getUSyncDevices,
755
+ createParticipantNodes,
756
+ waUploadToServer,
757
+ sendPeerDataOperationMessage,
758
+ fetchPrivacySettings,
759
+ updateMediaMessage: async (message) => {
760
+ const content = (0, Utils_1.assertMediaContent)(message.message);
761
+ const mediaKey = content.mediaKey;
762
+ const meId = authState.creds.me.id;
763
+ const node = (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
764
+ let error = undefined;
765
+ await Promise.all([
766
+ sendNode(node),
767
+ waitForMsgMediaUpdate(update => {
768
+ const result = update.find(c => c.key.id === message.key.id);
769
+ if (result) {
770
+ if (result.error) {
771
+ error = result.error;
772
+ }
773
+ else {
774
+ try {
775
+ const media = (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
776
+ if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
777
+ const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
778
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
779
+ }
780
+ content.directPath = media.directPath;
781
+ content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
782
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
783
+ }
784
+ catch (err) {
785
+ error = err;
786
+ }
787
+ }
788
+ return true;
789
+ }
790
+ })
791
+ ]);
792
+ if (error) {
793
+ throw error;
794
+ }
795
+ ev.emit('messages.update', [
796
+ {
797
+ key: message.key,
798
+ update: {
799
+ message: message.message
800
+ }
801
+ }
802
+ ]);
803
+ return message;
804
+ },
805
+ setLabelGroup: async (id, text) => {
806
+ await relayMessage(id, {
807
+ protocolMessage: {
808
+ type: 30,
809
+ memberLabel: {
810
+ label: text.slice(0, 30)
811
+ }
812
+ }
813
+ }, {
814
+ additionalNodes: [
815
+ {
816
+ tag: "meta",
817
+ attrs: {
818
+ tag_reason: "user_update",
819
+ appdata: "member_tag"
820
+ },
821
+ content: undefined
822
+ }
823
+ ]
824
+ })
825
+ },
826
+ sendStatusMention: async (content, jids = []) => {
827
+ return await rahmi.sendStatusWhatsApp(content, jids);
828
+ },
829
+ sendMessage: async (jid, content, options = {}) => {
830
+ const userJid = authState.creds.me.id;
831
+ delete options.ephemeralExpiration
832
+ const { filter = false, quoted } = options;
833
+ const getParticipantAttr = () => filter ? { participant: { jid } } : {};
834
+ const messageType = rahmi.detectType(content);
835
+ if (typeof content === 'object' && 'disappearingMessagesInChat' in content &&
836
+ typeof content['disappearingMessagesInChat'] !== 'undefined' && WABinary_1.isJidGroup(jid)) {
837
+ const { disappearingMessagesInChat } = content
838
+ const value = typeof disappearingMessagesInChat === 'boolean' ?
839
+ (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
840
+ disappearingMessagesInChat
841
+ await groupToggleEphemeral(jid, value)
842
+ }
843
+ else {
844
+ let mediaHandle
845
+ if (messageType) {
846
+ switch (messageType) {
847
+ case 'PAYMENT':
848
+ const paymentContent = await rahmi.handlePayment(content, quoted);
849
+ return await relayMessage(jid, paymentContent, {
850
+ messageId: Utils_1.generateMessageID(),
851
+ ...getParticipantAttr()
852
+ });
853
+ case 'PRODUCT':
854
+ const productContent = await rahmi.handleProduct(content, jid, quoted);
855
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
856
+ return await relayMessage(jid, productMsg.message, {
857
+ messageId: productMsg.key.id,
858
+ ...getParticipantAttr()
859
+ });
860
+ case 'INTERACTIVE':
861
+ const interactiveContent = await rahmi.handleInteractive(content, jid, quoted);
862
+ const interactiveMsg = await Utils_1.generateWAMessageFromContent(jid, interactiveContent, { quoted });
863
+ return await relayMessage(jid, interactiveMsg.message, {
864
+ messageId: interactiveMsg.key.id,
865
+ ...getParticipantAttr()
866
+ });
867
+ case 'ALBUM':
868
+ return await rahmi.handleAlbum(content, jid, quoted)
869
+ case 'EVENT':
870
+ return await rahmi.handleEvent(content, jid, quoted)
871
+ case 'POLL_RESULT':
872
+ return await rahmi.handlePollResult(content, jid, quoted)
873
+ case 'GROUP_STORY':
874
+ return await rahmi.handleGroupStory(content, jid, quoted)
875
+ }
876
+ }
877
+ const fullMsg = await Utils_1.generateWAMessage(jid, content, {
878
+ logger,
879
+ userJid,
880
+ quoted,
881
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
882
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
883
+ fetchOpts: {
884
+ timeout: 3000,
885
+ ...axiosOptions || {}
886
+ },
887
+ logger,
888
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
889
+ }),
890
+ upload: async (readStream, opts) => {
891
+ const up = await waUploadToServer(readStream, {
892
+ ...opts,
893
+ newsletter: WABinary_1.isJidNewsLetter(jid)
894
+ });
895
+ return up;
896
+ },
897
+ mediaCache: config.mediaCache,
898
+ options: config.options,
899
+ ...options
900
+ });
901
+ const isDeleteMsg = 'delete' in content && !!content.delete;
902
+ const isEditMsg = 'edit' in content && !!content.edit;
903
+ const isAiMsg = 'ai' in content && !!content.ai;
904
+ const additionalAttributes = {};
905
+ const additionalNodes = [];
906
+ if (isDeleteMsg) {
907
+ const fromMe = content.delete?.fromMe;
908
+ const isGroup = WABinary_1.isJidGroup(content.delete?.remoteJid);
909
+ additionalAttributes.edit = (isGroup && !fromMe) || WABinary_1.isJidNewsLetter(jid) ? '8' : '7';
910
+ } else if (isEditMsg) {
911
+ additionalAttributes.edit = WABinary_1.isJidNewsLetter(jid) ? '3' : '1';
912
+ } else if (isAiMsg) {
913
+ additionalNodes.push({
914
+ attrs: {
915
+ biz_bot: '1'
916
+ }, tag: "bot"
917
+ });
918
+ }
919
+ await relayMessage(jid, fullMsg.message, {
920
+ messageId: fullMsg.key.id,
921
+ cachedGroupMetadata: options.cachedGroupMetadata,
922
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes,
923
+ additionalAttributes,
924
+ statusJidList: options.statusJidList
925
+ });
926
+ if (config.emitOwnEvents) {
927
+ process.nextTick(() => {
928
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
929
+ });
930
+ }
931
+ return fullMsg;
932
+ }
933
+ }
934
+ }
935
+ };
936
+ exports.makeMessagesSocket = makeMessagesSocket;