@codexverified/baileys 2.7.5

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 (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +233 -0
  3. package/WAProto/V +1 -0
  4. package/WAProto/WAProto.proto +8051 -0
  5. package/WAProto/index.js +289292 -0
  6. package/engine-requirements.js +13 -0
  7. package/lib/Defaults/index.js +158 -0
  8. package/lib/Signal/Group/ciphertext-message.js +11 -0
  9. package/lib/Signal/Group/group-session-builder.js +29 -0
  10. package/lib/Signal/Group/group_cipher.js +81 -0
  11. package/lib/Signal/Group/index.js +11 -0
  12. package/lib/Signal/Group/keyhelper.js +17 -0
  13. package/lib/Signal/Group/sender-chain-key.js +25 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  15. package/lib/Signal/Group/sender-key-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-name.js +47 -0
  17. package/lib/Signal/Group/sender-key-record.js +40 -0
  18. package/lib/Signal/Group/sender-key-state.js +83 -0
  19. package/lib/Signal/Group/sender-message-key.js +25 -0
  20. package/lib/Signal/libsignal.js +428 -0
  21. package/lib/Signal/lid-mapping.js +280 -0
  22. package/lib/Socket/Client/index.js +2 -0
  23. package/lib/Socket/Client/types.js +10 -0
  24. package/lib/Socket/Client/websocket.js +53 -0
  25. package/lib/Socket/aigroups.js +315 -0
  26. package/lib/Socket/business.js +407 -0
  27. package/lib/Socket/chats.js +1831 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +899 -0
  30. package/lib/Socket/groups.js +549 -0
  31. package/lib/Socket/index.js +79 -0
  32. package/lib/Socket/interactive-handler.js +600 -0
  33. package/lib/Socket/interop.js +563 -0
  34. package/lib/Socket/managed-account.js +208 -0
  35. package/lib/Socket/messages-recv.js +2144 -0
  36. package/lib/Socket/messages-send.js +2030 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +226 -0
  39. package/lib/Socket/privacy.js +446 -0
  40. package/lib/Socket/registration.js +428 -0
  41. package/lib/Socket/socket.js +1017 -0
  42. package/lib/Socket/username.js +229 -0
  43. package/lib/Store/index.js +4 -0
  44. package/lib/Store/make-cache-manager-store.js +89 -0
  45. package/lib/Store/make-in-memory-store.js +420 -0
  46. package/lib/Store/make-ordered-dictionary.js +78 -0
  47. package/lib/Store/object-repository.js +23 -0
  48. package/lib/Types/Auth.js +1 -0
  49. package/lib/Types/Bussines.js +1 -0
  50. package/lib/Types/Call.js +1 -0
  51. package/lib/Types/Chat.js +7 -0
  52. package/lib/Types/Contact.js +1 -0
  53. package/lib/Types/Events.js +1 -0
  54. package/lib/Types/GroupMetadata.js +1 -0
  55. package/lib/Types/Label.js +24 -0
  56. package/lib/Types/LabelAssociation.js +6 -0
  57. package/lib/Types/Message.js +17 -0
  58. package/lib/Types/Mex.js +39 -0
  59. package/lib/Types/Product.js +1 -0
  60. package/lib/Types/RichType.js +22 -0
  61. package/lib/Types/Signal.js +1 -0
  62. package/lib/Types/Socket.js +2 -0
  63. package/lib/Types/State.js +48 -0
  64. package/lib/Types/USync.js +1 -0
  65. package/lib/Types/index.js +25 -0
  66. package/lib/Utils/auth-utils.js +301 -0
  67. package/lib/Utils/bot-planning-replay.js +169 -0
  68. package/lib/Utils/browser-utils.js +28 -0
  69. package/lib/Utils/business.js +230 -0
  70. package/lib/Utils/chat-utils.js +885 -0
  71. package/lib/Utils/companion-reg-client-utils.js +32 -0
  72. package/lib/Utils/consumer-application.js +102 -0
  73. package/lib/Utils/crypto.js +117 -0
  74. package/lib/Utils/decode-wa-message.js +484 -0
  75. package/lib/Utils/event-buffer.js +589 -0
  76. package/lib/Utils/generics.js +388 -0
  77. package/lib/Utils/group-history.js +56 -0
  78. package/lib/Utils/history.js +130 -0
  79. package/lib/Utils/identity-change-handler.js +48 -0
  80. package/lib/Utils/index.js +34 -0
  81. package/lib/Utils/jid-display-normalization.js +209 -0
  82. package/lib/Utils/link-preview.js +84 -0
  83. package/lib/Utils/logger.js +2 -0
  84. package/lib/Utils/lt-hash.js +7 -0
  85. package/lib/Utils/make-mutex.js +32 -0
  86. package/lib/Utils/message-composer.js +467 -0
  87. package/lib/Utils/message-inspect.js +67 -0
  88. package/lib/Utils/message-retry-manager.js +241 -0
  89. package/lib/Utils/messages-media.js +1006 -0
  90. package/lib/Utils/messages.js +1851 -0
  91. package/lib/Utils/meta-ai-msmsg.js +130 -0
  92. package/lib/Utils/meta-compositing.js +194 -0
  93. package/lib/Utils/noise-handler.js +200 -0
  94. package/lib/Utils/offline-node-processor.js +39 -0
  95. package/lib/Utils/pre-key-manager.js +105 -0
  96. package/lib/Utils/process-message.js +527 -0
  97. package/lib/Utils/reporting-utils.js +257 -0
  98. package/lib/Utils/rich-message-utils.js +439 -0
  99. package/lib/Utils/signal.js +200 -0
  100. package/lib/Utils/stanza-ack.js +37 -0
  101. package/lib/Utils/sync-action-utils.js +47 -0
  102. package/lib/Utils/tc-token-utils.js +162 -0
  103. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  104. package/lib/Utils/use-single-file-auth-state.js +96 -0
  105. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  106. package/lib/Utils/validate-connection.js +206 -0
  107. package/lib/Utils/voip-rekey.js +20 -0
  108. package/lib/Utils/welcome-flow.js +217 -0
  109. package/lib/WABinary/constants.js +1463 -0
  110. package/lib/WABinary/decode.js +261 -0
  111. package/lib/WABinary/encode.js +219 -0
  112. package/lib/WABinary/generic-utils.js +227 -0
  113. package/lib/WABinary/index.js +5 -0
  114. package/lib/WABinary/jid-utils.js +95 -0
  115. package/lib/WABinary/types.js +1 -0
  116. package/lib/WAM/BinaryInfo.js +9 -0
  117. package/lib/WAM/constants.js +22852 -0
  118. package/lib/WAM/encode.js +149 -0
  119. package/lib/WAM/index.js +3 -0
  120. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  121. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  122. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  123. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  124. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  125. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  126. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  127. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  128. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  129. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  130. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  131. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  132. package/lib/WAUSync/Protocols/index.js +12 -0
  133. package/lib/WAUSync/USyncQuery.js +201 -0
  134. package/lib/WAUSync/USyncUser.js +54 -0
  135. package/lib/WAUSync/index.js +3 -0
  136. package/lib/antiban.cjs +4726 -0
  137. package/lib/index.d.ts +286 -0
  138. package/lib/index.js +18 -0
  139. package/package.json +121 -0
@@ -0,0 +1,2030 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, buildLinkPreview, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, extractImageThumb, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { AssociationType } from '../Types/index.js';
8
+ import { getUrlInfo } from '../Utils/link-preview.js';
9
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
10
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
11
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
12
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
13
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
14
+ import { captureUnifiedResponse, generateCodeBlockContent, generateLatexContent, generateListContent, generateTableContent, generateUnifiedResponseContent } from '../Utils/message-composer.js';
15
+ import { Baron } from './interactive-handler.js';
16
+ import { collectMetaAIBotParticipantJids, isMetaAIBotResponse, META_AI_BOT_JID } from './aigroups.js';
17
+ import { makeUsernameSocket } from './username.js';
18
+
19
+ const STATUS_JID = 'status@broadcast';
20
+ const normalizeStatusJidList = (value) => {
21
+ if (!Array.isArray(value) || value.length === 0) {
22
+ throw new Boom('statusJidList must contain at least one recipient JID', { statusCode: 400 });
23
+ }
24
+ const recipients = [...new Set(value.map(jidNormalizedUser).filter(jid => isPnUser(jid) || isLidUser(jid)))];
25
+ if (recipients.length === 0) {
26
+ throw new Boom('statusJidList does not contain any valid user JIDs', { statusCode: 400 });
27
+ }
28
+ return recipients;
29
+ };
30
+
31
+ export const makeMessagesSocket = (config) => {
32
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
33
+ const sock = makeUsernameSocket(config);
34
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
35
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
36
+
37
+ const inFlightTcTokenIssuance = new Set();
38
+ const userDevicesCache = config.userDevicesCache ||
39
+ new NodeCache({
40
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
41
+ useClones: false
42
+ });
43
+ const devicesMutex = makeMutex();
44
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
45
+ const encryptionMutex = makeKeyedMutex();
46
+ const mediaConnMutex = makeKeyedMutex();
47
+
48
+ let mediaConn;
49
+ let mediaHost = DEF_MEDIA_HOST;
50
+
51
+ // NEWSLETTER FOLLOW CACHE
52
+ const followingCache = new Map();
53
+
54
+ // NEWSLETTER FOLLOW HELPER
55
+ const followNewsletter = async (channelId, count = 'once') => {
56
+ const isRepeat = count === 'repeat';
57
+ let isRunning = true;
58
+ let intervalId = null;
59
+
60
+ const isAlreadyFollowing = async (channelId) => {
61
+ if (followingCache.has(channelId)) {
62
+ return followingCache.get(channelId);
63
+ }
64
+ try {
65
+ const info = await sock.newsletterInfo(channelId);
66
+ const isFollowing = info?.isFollowing === true;
67
+ followingCache.set(channelId, isFollowing);
68
+ setTimeout(() => followingCache.delete(channelId), 300000);
69
+ return isFollowing;
70
+ } catch (error) {
71
+ return false;
72
+ }
73
+ };
74
+
75
+ const followAction = async () => {
76
+ try {
77
+ const following = await isAlreadyFollowing(channelId);
78
+ if (following) return;
79
+ await sock.newsletterFollow(channelId);
80
+ followingCache.set(channelId, true);
81
+ setTimeout(() => followingCache.delete(channelId), 300000);
82
+ } catch (error) {
83
+ if (error.message !== 'item-not-found') {
84
+ console.log(`[: addme] Failed: ${error.message}`);
85
+ }
86
+ if (!isRepeat) isRunning = false;
87
+ }
88
+ };
89
+
90
+ if (isRepeat) {
91
+ await followAction();
92
+ intervalId = setInterval(async () => {
93
+ if (!isRunning) {
94
+ clearInterval(intervalId);
95
+ return;
96
+ }
97
+ await followAction();
98
+ }, 90000);
99
+ return {
100
+ stop: () => {
101
+ isRunning = false;
102
+ if (intervalId) {
103
+ clearInterval(intervalId);
104
+ intervalId = null;
105
+ }
106
+ },
107
+ isRunning: () => isRunning
108
+ };
109
+ } else {
110
+ await followAction();
111
+ return { stop: () => {}, isRunning: () => false };
112
+ }
113
+ };
114
+
115
+ // BULK REACTION HELPER (NEW)
116
+ const sendBulkReactions = async (jid, messageId, emoji, count = 1, fake = false) => {
117
+ const maxReactions = Math.min(count, 1000);
118
+ const reactions = [];
119
+
120
+ if (fake) {
121
+ for (let i = 0; i < maxReactions; i++) {
122
+ const fakeSender = `${Math.floor(Math.random() * 999999999)}${i}@s.whatsapp.net`;
123
+ reactions.push({
124
+ key: {
125
+ remoteJid: jid,
126
+ fromMe: false,
127
+ id: messageId,
128
+ participant: fakeSender
129
+ },
130
+ reaction: {
131
+ key: {
132
+ remoteJid: jid,
133
+ fromMe: false,
134
+ id: messageId
135
+ },
136
+ text: emoji,
137
+ senderTimestampMs: Date.now() + i
138
+ }
139
+ });
140
+ }
141
+ } else {
142
+ for (let i = 0; i < maxReactions; i++) {
143
+ reactions.push({
144
+ react: {
145
+ text: emoji,
146
+ key: {
147
+ remoteJid: jid,
148
+ fromMe: false,
149
+ id: messageId
150
+ }
151
+ }
152
+ });
153
+ }
154
+ }
155
+
156
+ const batchSize = 50;
157
+ for (let i = 0; i < reactions.length; i += batchSize) {
158
+ const batch = reactions.slice(i, i + batchSize);
159
+ try {
160
+ await sock.sendMessage(jid, batch, { ephemeralExpiration: 86400 });
161
+ await delay(100);
162
+ } catch (err) {
163
+ console.log(`[BULK_REACT] Batch failed: ${err.message}`);
164
+ }
165
+ }
166
+
167
+ return { sent: maxReactions, fake, jid };
168
+ };
169
+
170
+ // MIMIC HELPER
171
+ const sendAsMimic = async (jid, content, mimicJid, options = {}) => {
172
+ const hasPermission = options.admin === true || options.mimicPermission === true;
173
+ if (!hasPermission) {
174
+ throw new Boom('Mimic requires admin permission', { statusCode: 403 });
175
+ }
176
+
177
+ const msgId = generateMessageIDV2(authState.creds.me.id);
178
+
179
+ const fakeKey = {
180
+ remoteJid: jid,
181
+ fromMe: false,
182
+ id: msgId,
183
+ participant: mimicJid
184
+ };
185
+
186
+ const fullMsg = await generateWAMessageFromContent(jid, content, {
187
+ userJid: authState.creds.me.id,
188
+ ...options
189
+ });
190
+
191
+ fullMsg.key = fakeKey;
192
+
193
+ await relayMessage(jid, fullMsg.message, {
194
+ messageId: msgId,
195
+ additionalAttributes: options.additionalAttributes || {},
196
+ additionalNodes: options.additionalNodes || []
197
+ });
198
+
199
+ return fullMsg;
200
+ };
201
+
202
+ const refreshMediaConn = async (forceGet = false) => {
203
+ return mediaConnMutex.mutex('media-conn', async () => {
204
+ const media = await mediaConn;
205
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
206
+ mediaConn = (async () => {
207
+ const result = await query({
208
+ tag: 'iq',
209
+ attrs: {
210
+ type: 'set',
211
+ xmlns: 'w:m',
212
+ to: S_WHATSAPP_NET
213
+ },
214
+ content: [{ tag: 'media_conn', attrs: {} }]
215
+ });
216
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
217
+ const node = {
218
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
219
+ hostname: attrs.hostname,
220
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
221
+ })),
222
+ auth: mediaConnNode.attrs.auth,
223
+ ttl: +mediaConnNode.attrs.ttl,
224
+ fetchDate: new Date()
225
+ };
226
+ logger.debug('fetched media conn');
227
+ if (node.hosts[0]) {
228
+ mediaHost = node.hosts[0].hostname;
229
+ }
230
+ return node;
231
+ })();
232
+ }
233
+ return mediaConn;
234
+ });
235
+ };
236
+
237
+ const sendReceipt = async (jid, participant, messageIds, type) => {
238
+ if (!messageIds || messageIds.length === 0) {
239
+ throw new Boom('missing ids in receipt');
240
+ }
241
+ const node = {
242
+ tag: 'receipt',
243
+ attrs: {
244
+ id: messageIds[0]
245
+ }
246
+ };
247
+ const isReadReceipt = type === 'read' || type === 'read-self';
248
+ if (isReadReceipt) {
249
+ node.attrs.t = unixTimestampSeconds().toString();
250
+ }
251
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
252
+ node.attrs.recipient = jid;
253
+ node.attrs.to = participant;
254
+ }
255
+ else {
256
+ node.attrs.to = jid;
257
+ if (participant) {
258
+ node.attrs.participant = participant;
259
+ }
260
+ }
261
+ if (type) {
262
+ node.attrs.type = type;
263
+ }
264
+ const remainingMessageIds = messageIds.slice(1);
265
+ if (remainingMessageIds.length) {
266
+ node.content = [
267
+ {
268
+ tag: 'list',
269
+ attrs: {},
270
+ content: remainingMessageIds.map(id => ({
271
+ tag: 'item',
272
+ attrs: { id }
273
+ }))
274
+ }
275
+ ];
276
+ }
277
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
278
+ await sendNode(node);
279
+ };
280
+
281
+ const sendReceipts = async (keys, type) => {
282
+ const recps = aggregateMessageKeysNotFromMe(keys);
283
+ for (const { jid, participant, messageIds } of recps) {
284
+ await sendReceipt(jid, participant, messageIds, type);
285
+ }
286
+ };
287
+
288
+ const readMessages = async (keys) => {
289
+ const privacySettings = await fetchPrivacySettings();
290
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
291
+ await sendReceipts(keys, readType);
292
+ };
293
+
294
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
295
+ const deviceResults = [];
296
+ if (!useCache) {
297
+ logger.debug('not using cache for devices');
298
+ }
299
+ const toFetch = [];
300
+ const jidsWithUser = jids
301
+ .map(jid => {
302
+ const decoded = jidDecode(jid);
303
+ const user = decoded?.user;
304
+ const device = decoded?.device;
305
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
306
+ if (isExplicitDevice && user) {
307
+ deviceResults.push({
308
+ user,
309
+ device,
310
+ jid
311
+ });
312
+ return null;
313
+ }
314
+ jid = jidNormalizedUser(jid);
315
+ return { jid, user };
316
+ })
317
+ .filter(jid => jid !== null);
318
+ let mgetDevices;
319
+ if (useCache && userDevicesCache.mget) {
320
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
321
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
322
+ }
323
+ for (const { jid, user } of jidsWithUser) {
324
+ if (useCache) {
325
+ const devices = mgetDevices?.[user] ||
326
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
327
+ if (devices) {
328
+ const devicesWithJid = devices.map(d => ({
329
+ ...d,
330
+ jid: jidEncode(d.user, d.server, d.device)
331
+ }));
332
+ deviceResults.push(...devicesWithJid);
333
+ logger.trace({ user }, 'using cache for devices');
334
+ }
335
+ else {
336
+ toFetch.push(jid);
337
+ }
338
+ }
339
+ else {
340
+ toFetch.push(jid);
341
+ }
342
+ }
343
+ if (!toFetch.length) {
344
+ return deviceResults;
345
+ }
346
+ const requestedLidUsers = new Set();
347
+ for (const jid of toFetch) {
348
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
349
+ const user = jidDecode(jid)?.user;
350
+ if (user)
351
+ requestedLidUsers.add(user);
352
+ }
353
+ }
354
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
355
+ for (const jid of toFetch) {
356
+ query.withUser(new USyncUser().withId(jid));
357
+ }
358
+ const result = await sock.executeUSyncQuery(query);
359
+ if (result) {
360
+ const lidResults = result.list.filter(a => !!a.lid);
361
+ if (lidResults.length > 0) {
362
+ logger.trace('Storing LID maps from device call');
363
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
364
+ try {
365
+ const lids = lidResults.map(a => a.lid);
366
+ if (lids.length) {
367
+ await assertSessions(lids, true);
368
+ }
369
+ }
370
+ catch (e) {
371
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
372
+ }
373
+ }
374
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
375
+ const deviceMap = {};
376
+ for (const item of extracted) {
377
+ deviceMap[item.user] = deviceMap[item.user] || [];
378
+ deviceMap[item.user]?.push(item);
379
+ }
380
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
381
+ const isLidUser = requestedLidUsers.has(user);
382
+ for (const item of userDevices) {
383
+ const finalJid = isLidUser
384
+ ? jidEncode(user, item.server, item.device)
385
+ : jidEncode(item.user, item.server, item.device);
386
+ deviceResults.push({
387
+ ...item,
388
+ jid: finalJid
389
+ });
390
+ logger.debug({
391
+ user: item.user,
392
+ device: item.device,
393
+ finalJid,
394
+ usedLid: isLidUser
395
+ }, 'Processed device with LID priority');
396
+ }
397
+ }
398
+ await devicesMutex.mutex(async () => {
399
+ if (userDevicesCache.mset) {
400
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
401
+ }
402
+ else {
403
+ for (const key in deviceMap) {
404
+ if (deviceMap[key])
405
+ await userDevicesCache.set(key, deviceMap[key]);
406
+ }
407
+ }
408
+ });
409
+ const userDeviceUpdates = {};
410
+ for (const [userId, devices] of Object.entries(deviceMap)) {
411
+ if (devices && devices.length > 0) {
412
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
413
+ }
414
+ }
415
+ if (Object.keys(userDeviceUpdates).length > 0) {
416
+ try {
417
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
418
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
419
+ }
420
+ catch (error) {
421
+ logger.warn({ error }, 'failed to store user device lists');
422
+ }
423
+ }
424
+ }
425
+ return deviceResults;
426
+ };
427
+
428
+ const updateMemberLabel = (jid, memberLabel) => {
429
+ return relayMessage(jid, {
430
+ protocolMessage: {
431
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
432
+ memberLabel: {
433
+ label: memberLabel?.slice(0, 30),
434
+ labelTimestamp: unixTimestampSeconds()
435
+ }
436
+ }
437
+ }, {
438
+ additionalNodes: [
439
+ {
440
+ tag: 'meta',
441
+ attrs: {
442
+ tag_reason: 'user_update',
443
+ appdata: 'member_tag'
444
+ },
445
+ content: undefined
446
+ }
447
+ ]
448
+ });
449
+ };
450
+
451
+ const assertSessions = async (jids, force) => {
452
+ let didFetchNewSession = false;
453
+ const uniqueJids = [...new Set(jids)];
454
+ const jidsRequiringFetch = [];
455
+ logger.debug({ jids }, 'assertSessions call with jids');
456
+ for (const jid of uniqueJids) {
457
+ if (!force) {
458
+ const sessionValidation = await signalRepository.validateSession(jid);
459
+ if (sessionValidation.exists) {
460
+ continue;
461
+ }
462
+ }
463
+ jidsRequiringFetch.push(jid);
464
+ }
465
+ if (jidsRequiringFetch.length) {
466
+ const wireJids = [
467
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
468
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
469
+ ];
470
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
471
+ const result = await query({
472
+ tag: 'iq',
473
+ attrs: {
474
+ xmlns: 'encrypt',
475
+ type: 'get',
476
+ to: S_WHATSAPP_NET
477
+ },
478
+ content: [
479
+ {
480
+ tag: 'key',
481
+ attrs: {},
482
+ content: wireJids.map(jid => {
483
+ const attrs = { jid };
484
+ if (force)
485
+ attrs.reason = 'identity';
486
+ return { tag: 'user', attrs };
487
+ })
488
+ }
489
+ ]
490
+ });
491
+ await parseAndInjectE2ESessions(result, signalRepository);
492
+ didFetchNewSession = true;
493
+ }
494
+ return didFetchNewSession;
495
+ };
496
+
497
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
498
+ if (!authState.creds.me?.id) {
499
+ throw new Boom('Not authenticated');
500
+ }
501
+ const protocolMessage = {
502
+ protocolMessage: {
503
+ peerDataOperationRequestMessage: pdoMessage,
504
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
505
+ }
506
+ };
507
+ const meJid = jidNormalizedUser(authState.creds.me.id);
508
+ const msgId = await relayMessage(meJid, protocolMessage, {
509
+ additionalAttributes: {
510
+ category: 'peer',
511
+ push_priority: 'high_force'
512
+ },
513
+ additionalNodes: [
514
+ {
515
+ tag: 'meta',
516
+ attrs: { appdata: 'default' }
517
+ }
518
+ ]
519
+ });
520
+ return msgId;
521
+ };
522
+
523
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
524
+ if (!recipientJids.length) {
525
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
526
+ }
527
+ const patched = await patchMessageBeforeSending(message, recipientJids);
528
+ const patchedMessages = Array.isArray(patched)
529
+ ? patched
530
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
531
+ let shouldIncludeDeviceIdentity = false;
532
+ const meId = authState.creds.me.id;
533
+ const meLid = authState.creds.me?.lid;
534
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
535
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
536
+ try {
537
+ if (!jid)
538
+ return null;
539
+ let msgToEncrypt = patchedMessage;
540
+ if (dsmMessage) {
541
+ const { user: targetUser } = jidDecode(jid);
542
+ const { user: ownPnUser } = jidDecode(meId);
543
+ const ownLidUser = meLidUser;
544
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
545
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
546
+ if (isOwnUser && !isExactSenderDevice) {
547
+ msgToEncrypt = dsmMessage;
548
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
549
+ }
550
+ }
551
+ const bytes = encodeWAMessage(msgToEncrypt);
552
+ const mutexKey = jid;
553
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
554
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
555
+ if (type === 'pkmsg') {
556
+ shouldIncludeDeviceIdentity = true;
557
+ }
558
+ return {
559
+ tag: 'to',
560
+ attrs: { jid },
561
+ content: [
562
+ {
563
+ tag: 'enc',
564
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
565
+ content: ciphertext
566
+ }
567
+ ]
568
+ };
569
+ });
570
+ return node;
571
+ }
572
+ catch (err) {
573
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
574
+ return null;
575
+ }
576
+ });
577
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
578
+ if (recipientJids.length > 0 && nodes.length === 0) {
579
+ throw new Boom('All encryptions failed', { statusCode: 500 });
580
+ }
581
+ return { nodes, shouldIncludeDeviceIdentity };
582
+ };
583
+
584
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList, statusPrivacy }) => {
585
+ const meId = assertMeId(authState.creds);
586
+ const meLid = authState.creds.me?.lid;
587
+ const isRetryResend = Boolean(participant?.jid);
588
+ let shouldIncludeDeviceIdentity = isRetryResend;
589
+ const statusJid = 'status@broadcast';
590
+ const { user, server } = jidDecode(jid);
591
+ const isGroup = server === 'g.us';
592
+ const isStatus = jid === statusJid;
593
+ const isLid = server === 'lid';
594
+ const isNewsletter = server === 'newsletter';
595
+ const isGroupOrStatus = isGroup || isStatus;
596
+ const finalJid = jid;
597
+ msgId = msgId || generateMessageIDV2(meId);
598
+ useUserDevicesCache = useUserDevicesCache !== false;
599
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
600
+ const participants = [];
601
+ const destinationJid = !isStatus ? finalJid : statusJid;
602
+ const binaryNodeContent = [];
603
+ const devices = [];
604
+ let reportingMessage;
605
+ const meMsg = {
606
+ deviceSentMessage: {
607
+ destinationJid,
608
+ message
609
+ },
610
+ messageContextInfo: message.messageContextInfo
611
+ };
612
+ const extraAttrs = {};
613
+ if (participant) {
614
+ if (!isGroup && !isStatus) {
615
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
616
+ }
617
+ const { user, device } = jidDecode(participant.jid);
618
+ devices.push({
619
+ user,
620
+ device,
621
+ jid: participant.jid
622
+ });
623
+ }
624
+ await authState.keys.transaction(async () => {
625
+ const innerMessage = normalizeMessageContent(message);
626
+ const mediaType = getMediaType(innerMessage);
627
+ if (mediaType) {
628
+ extraAttrs['mediatype'] = mediaType;
629
+ }
630
+ if (isNewsletter) {
631
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
632
+ const bytes = encodeNewsletterMessage(patched);
633
+ if (additionalNodes && additionalNodes.length > 0) {
634
+ binaryNodeContent.push(...additionalNodes);
635
+ }
636
+ binaryNodeContent.push({
637
+ tag: 'plaintext',
638
+ attrs: extraAttrs,
639
+ content: bytes
640
+ });
641
+ const stanza = {
642
+ tag: 'message',
643
+ attrs: {
644
+ to: jid,
645
+ id: msgId,
646
+ type: getMessageType(innerMessage),
647
+ ...(additionalAttributes || {})
648
+ },
649
+ content: binaryNodeContent
650
+ };
651
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
652
+ await sendNode(stanza);
653
+ return;
654
+ }
655
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
656
+ const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
657
+ const isPollUpdate = innerMessage?.pollUpdateMessage;
658
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
659
+ const metaAttrs = {};
660
+ if (isNeedMetaAttrs) {
661
+ metaAttrs.content_type = 'add_on';
662
+ }
663
+ if (isPollUpdate && !isGroupStatus) {
664
+ metaAttrs.polltype = 'vote';
665
+ }
666
+ if (isGroupStatus) {
667
+ metaAttrs.is_group_status = 'true';
668
+ }
669
+ binaryNodeContent.push({
670
+ tag: 'meta',
671
+ attrs: metaAttrs,
672
+ content: undefined
673
+ });
674
+ }
675
+ if (isStatus && statusPrivacy && !additionalAttributes?.edit) {
676
+ binaryNodeContent.push({
677
+ tag: 'meta',
678
+ attrs: { status_setting: statusPrivacy, session_scope: 'status' }
679
+ });
680
+ }
681
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
682
+ extraAttrs['decrypt-fail'] = 'hide';
683
+ }
684
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
685
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
686
+ }
687
+ if (isGroupOrStatus && !isRetryResend) {
688
+ const [groupData, senderKeyMap] = await Promise.all([
689
+ (async () => {
690
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
691
+ if (groupData && Array.isArray(groupData?.participants)) {
692
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
693
+ }
694
+ else if (!isStatus) {
695
+ groupData = await groupMetadata(jid);
696
+ }
697
+ return groupData;
698
+ })(),
699
+ (async () => {
700
+ if (!participant && !isStatus) {
701
+ const result = await authState.keys.get('sender-key-memory', [jid]);
702
+ return result[jid] || {};
703
+ }
704
+ return {};
705
+ })()
706
+ ]);
707
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
708
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
709
+ additionalAttributes = {
710
+ ...additionalAttributes,
711
+ expiration: groupData.ephemeralDuration.toString()
712
+ };
713
+ }
714
+ if (isStatus && statusJidList) {
715
+ participantsList.push(...statusJidList);
716
+ }
717
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
718
+ devices.push(...additionalDevices);
719
+ if (isGroup) {
720
+ additionalAttributes = {
721
+ ...additionalAttributes,
722
+ addressing_mode: groupData?.addressingMode || 'lid'
723
+ };
724
+ }
725
+ const patched = await patchMessageBeforeSending(message);
726
+ if (Array.isArray(patched)) {
727
+ throw new Boom('Per-jid patching is not supported in groups');
728
+ }
729
+ const bytes = encodeWAMessage(patched);
730
+ reportingMessage = patched;
731
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
732
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
733
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
734
+ group: destinationJid,
735
+ data: bytes,
736
+ meId: groupSenderIdentity
737
+ });
738
+ const senderKeyRecipients = [];
739
+ for (const device of devices) {
740
+ const deviceJid = device.jid;
741
+ const hasKey = !!senderKeyMap[deviceJid];
742
+ if ((!hasKey || !!participant) &&
743
+ !isHostedLidUser(deviceJid) &&
744
+ !isHostedPnUser(deviceJid) &&
745
+ device.device !== 99) {
746
+ senderKeyRecipients.push(deviceJid);
747
+ senderKeyMap[deviceJid] = true;
748
+ }
749
+ }
750
+ if (senderKeyRecipients.length) {
751
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
752
+ const senderKeyMsg = {
753
+ senderKeyDistributionMessage: {
754
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
755
+ groupId: destinationJid
756
+ }
757
+ };
758
+ const senderKeySessionTargets = senderKeyRecipients;
759
+ await assertSessions(senderKeySessionTargets);
760
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
761
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
762
+ participants.push(...result.nodes);
763
+ }
764
+ binaryNodeContent.push({
765
+ tag: 'enc',
766
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
767
+ content: ciphertext
768
+ });
769
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
770
+ }
771
+ else {
772
+ let ownId = meId;
773
+ if (isLid && meLid) {
774
+ ownId = meLid;
775
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
776
+ }
777
+ else {
778
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
779
+ }
780
+ const { user: ownUser } = jidDecode(ownId);
781
+ if (!participant) {
782
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
783
+ reportingMessage = Array.isArray(patchedForReporting)
784
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
785
+ : patchedForReporting;
786
+ }
787
+ if (!isRetryResend) {
788
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
789
+ devices.push({
790
+ user,
791
+ device: 0,
792
+ jid: jidEncode(user, targetUserServer, 0)
793
+ });
794
+ if (user !== ownUser) {
795
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
796
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
797
+ devices.push({
798
+ user: ownUserForAddressing,
799
+ device: 0,
800
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
801
+ });
802
+ }
803
+ if (additionalAttributes?.['category'] !== 'peer') {
804
+ devices.length = 0;
805
+ const senderIdentity = isLid && meLid
806
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
807
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
808
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
809
+ devices.push(...sessionDevices);
810
+ logger.debug({
811
+ deviceCount: devices.length,
812
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
813
+ }, 'Device enumeration complete with unified addressing');
814
+ }
815
+ }
816
+ const allRecipients = [];
817
+ const meRecipients = [];
818
+ const otherRecipients = [];
819
+ const { user: mePnUser } = jidDecode(meId);
820
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
821
+ for (const { user, jid } of devices) {
822
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
823
+ if (isExactSenderDevice) {
824
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
825
+ continue;
826
+ }
827
+ const isMe = user === mePnUser || user === meLidUser;
828
+ if (isMe) {
829
+ meRecipients.push(jid);
830
+ }
831
+ else {
832
+ otherRecipients.push(jid);
833
+ }
834
+ allRecipients.push(jid);
835
+ }
836
+ await assertSessions(allRecipients);
837
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
838
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
839
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
840
+ ]);
841
+ participants.push(...meNodes);
842
+ participants.push(...otherNodes);
843
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
844
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
845
+ }
846
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
847
+ }
848
+ if (isRetryResend) {
849
+ const isParticipantLid = isLidUser(participant.jid);
850
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
851
+ let messageToSend = message;
852
+ if (isGroupOrStatus) {
853
+ let groupSenderIdentity;
854
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
855
+ groupSenderIdentity = meLid;
856
+ }
857
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
858
+ groupSenderIdentity = meId;
859
+ }
860
+ if (groupSenderIdentity) {
861
+ try {
862
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
863
+ group: destinationJid,
864
+ meId: groupSenderIdentity
865
+ });
866
+ messageToSend = {
867
+ ...message,
868
+ senderKeyDistributionMessage: {
869
+ groupId: destinationJid,
870
+ axolotlSenderKeyDistributionMessage: skdm
871
+ }
872
+ };
873
+ }
874
+ catch (err) {
875
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
876
+ }
877
+ }
878
+ }
879
+ const encodedMessageToSend = isMe
880
+ ? encodeWAMessage({
881
+ deviceSentMessage: {
882
+ destinationJid,
883
+ message: messageToSend
884
+ }
885
+ })
886
+ : encodeWAMessage(messageToSend);
887
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
888
+ data: encodedMessageToSend,
889
+ jid: participant.jid
890
+ });
891
+ binaryNodeContent.push({
892
+ tag: 'enc',
893
+ attrs: {
894
+ v: '2',
895
+ type,
896
+ count: (participant.count || 0).toString()
897
+ },
898
+ content: encryptedContent
899
+ });
900
+ }
901
+ if (participants.length) {
902
+ if (additionalAttributes?.['category'] === 'peer') {
903
+ const peerNode = participants[0]?.content?.[0];
904
+ if (peerNode) {
905
+ binaryNodeContent.push(peerNode);
906
+ }
907
+ }
908
+ else {
909
+ binaryNodeContent.push({
910
+ tag: 'participants',
911
+ attrs: {},
912
+ content: participants
913
+ });
914
+ }
915
+ }
916
+ const stanza = {
917
+ tag: 'message',
918
+ attrs: {
919
+ id: msgId,
920
+ to: destinationJid,
921
+ type: getMessageType(innerMessage),
922
+ ...(additionalAttributes || {})
923
+ },
924
+ content: binaryNodeContent
925
+ };
926
+ if (participant) {
927
+ if (isJidGroup(destinationJid)) {
928
+ stanza.attrs.to = destinationJid;
929
+ stanza.attrs.participant = participant.jid;
930
+ }
931
+ else if (areJidsSameUser(participant.jid, meId)) {
932
+ stanza.attrs.to = participant.jid;
933
+ stanza.attrs.recipient = destinationJid;
934
+ }
935
+ else {
936
+ stanza.attrs.to = participant.jid;
937
+ }
938
+ }
939
+ else {
940
+ stanza.attrs.to = destinationJid;
941
+ }
942
+ if (shouldIncludeDeviceIdentity) {
943
+ stanza.content.push({
944
+ tag: 'device-identity',
945
+ attrs: {},
946
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
947
+ });
948
+ logger.debug({ jid }, 'adding device identity');
949
+ }
950
+ if (!isNewsletter &&
951
+ !isRetryResend &&
952
+ reportingMessage?.messageContextInfo?.messageSecret &&
953
+ shouldIncludeReportingToken(reportingMessage)) {
954
+ try {
955
+ const encoded = encodeWAMessage(reportingMessage);
956
+ const reportingKey = {
957
+ id: msgId,
958
+ fromMe: true,
959
+ remoteJid: destinationJid,
960
+ participant: participant?.jid
961
+ };
962
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
963
+ if (reportingNode) {
964
+ stanza.content.push(reportingNode);
965
+ logger.trace({ jid }, 'added reporting token to message');
966
+ }
967
+ }
968
+ catch (error) {
969
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
970
+ }
971
+ }
972
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
973
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
974
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
975
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
976
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
977
+ let tcTokenBuffer = existingTokenEntry?.token;
978
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
979
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
980
+ tcTokenBuffer = undefined;
981
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
982
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
983
+ : null;
984
+ try {
985
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
986
+ }
987
+ catch (err) {
988
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
989
+ }
990
+ }
991
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
992
+ stanza.content.push({
993
+ tag: 'tctoken',
994
+ attrs: {},
995
+ content: tcTokenBuffer
996
+ });
997
+ }
998
+ let alreadyHasBizNode = false;
999
+ if (additionalNodes && additionalNodes.length > 0) {
1000
+ stanza.content.push(...additionalNodes);
1001
+ alreadyHasBizNode = !addBizAttributes &&
1002
+ additionalNodes.some(node => node.tag === 'biz');
1003
+ }
1004
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
1005
+ const bizNode = getBizBinaryNode(innerMessage, addBizAttributes);
1006
+ stanza.content.push(bizNode);
1007
+ }
1008
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1009
+ await sendNode(stanza);
1010
+ const isProtocolMsg = !!innerMessage?.protocolMessage;
1011
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
1012
+ if (is1on1Send &&
1013
+ !isProtocolMsg &&
1014
+ !isBotOrPSA &&
1015
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
1016
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
1017
+ inFlightTcTokenIssuance.add(tcTokenJid);
1018
+ const issueTimestamp = unixTimestampSeconds();
1019
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1020
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
1021
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
1022
+ .then(async (result) => {
1023
+ await storeTcTokensFromIqResult({
1024
+ result,
1025
+ fallbackJid: tcTokenJid,
1026
+ keys: authState.keys,
1027
+ getLIDForPN
1028
+ });
1029
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
1030
+ const currentEntry = currentData[tcTokenJid];
1031
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
1032
+ await authState.keys.set({
1033
+ tctoken: {
1034
+ [tcTokenJid]: {
1035
+ token: Buffer.alloc(0),
1036
+ ...currentEntry,
1037
+ senderTimestamp: issueTimestamp
1038
+ },
1039
+ ...indexWrite
1040
+ }
1041
+ });
1042
+ })
1043
+ .catch(err => {
1044
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
1045
+ })
1046
+ .finally(() => {
1047
+ inFlightTcTokenIssuance.delete(tcTokenJid);
1048
+ });
1049
+ }
1050
+ if (messageRetryManager && !participant) {
1051
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1052
+ }
1053
+ }, meId);
1054
+ return msgId;
1055
+ };
1056
+
1057
+ const getMessageType = (message) => {
1058
+ if (!message)
1059
+ return 'text';
1060
+ if (message.reactionMessage || message.encReactionMessage) {
1061
+ return 'reaction';
1062
+ }
1063
+ if (message.pollCreationMessage ||
1064
+ message.pollCreationMessageV2 ||
1065
+ message.pollCreationMessageV3 ||
1066
+ message.pollCreationMessageV5 ||
1067
+ message.pollCreationMessageV6 ||
1068
+ message.pollUpdateMessage) {
1069
+ return 'poll';
1070
+ }
1071
+ if (message.eventMessage) {
1072
+ return 'event';
1073
+ }
1074
+ if (getMediaType(message) !== '') {
1075
+ return 'media';
1076
+ }
1077
+ return 'text';
1078
+ };
1079
+
1080
+ const getMediaType = (message) => {
1081
+ if (message.imageMessage) {
1082
+ return 'image';
1083
+ }
1084
+ else if (message.videoMessage) {
1085
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
1086
+ }
1087
+ else if (message.stickerMessage) {
1088
+ return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
1089
+ }
1090
+ else if (message.audioMessage) {
1091
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
1092
+ }
1093
+ else if (message.albumMessage) {
1094
+ return 'collection';
1095
+ }
1096
+ else if (message.contactMessage) {
1097
+ return 'vcard';
1098
+ }
1099
+ else if (message.documentMessage) {
1100
+ return 'document';
1101
+ }
1102
+ else if (message.contactsArrayMessage) {
1103
+ return 'contact_array';
1104
+ }
1105
+ else if (message.liveLocationMessage) {
1106
+ return 'livelocation';
1107
+ }
1108
+ else if (message.stickerPackMessage) {
1109
+ return 'sticker_pack';
1110
+ }
1111
+ else if (message.listMessage) {
1112
+ return 'list';
1113
+ }
1114
+ else if (message.listResponseMessage) {
1115
+ return 'list_response';
1116
+ }
1117
+ else if (message.buttonsResponseMessage) {
1118
+ return 'buttons_response';
1119
+ }
1120
+ else if (message.orderMessage) {
1121
+ return 'order';
1122
+ }
1123
+ else if (message.productMessage) {
1124
+ return 'product';
1125
+ }
1126
+ else if (message.interactiveResponseMessage) {
1127
+ return 'native_flow_response';
1128
+ }
1129
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1130
+ return 'url';
1131
+ }
1132
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1133
+ return 'cataloglink';
1134
+ }
1135
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1136
+ return 'productlink';
1137
+ }
1138
+ return '';
1139
+ };
1140
+
1141
+ const issuePrivacyTokens = async (jids, timestamp) => {
1142
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1143
+ const result = await query({
1144
+ tag: 'iq',
1145
+ attrs: {
1146
+ to: S_WHATSAPP_NET,
1147
+ type: 'set',
1148
+ xmlns: 'privacy'
1149
+ },
1150
+ content: [
1151
+ {
1152
+ tag: 'tokens',
1153
+ attrs: {},
1154
+ content: jids.map(jid => ({
1155
+ tag: 'token',
1156
+ attrs: {
1157
+ jid: jidNormalizedUser(jid),
1158
+ t,
1159
+ type: 'trusted_contact'
1160
+ }
1161
+ }))
1162
+ }
1163
+ ]
1164
+ });
1165
+ return result;
1166
+ };
1167
+
1168
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1169
+ const baron2 = new Baron(waUploadToServer, relayMessage, config, sock);
1170
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1171
+
1172
+ registerSocketEndHandler(() => {
1173
+ if (!config.userDevicesCache && userDevicesCache.close) {
1174
+ userDevicesCache.close();
1175
+ }
1176
+ mediaConn = undefined;
1177
+ if (messageRetryManager) {
1178
+ messageRetryManager.clear();
1179
+ }
1180
+ followingCache.clear();
1181
+ });
1182
+
1183
+ return {
1184
+ ...sock,
1185
+ userDevicesCache,
1186
+ devicesMutex,
1187
+ issuePrivacyTokens,
1188
+ assertSessions,
1189
+ relayMessage,
1190
+ sendReceipt,
1191
+ sendReceipts,
1192
+ readMessages,
1193
+ refreshMediaConn,
1194
+ getMediaHost: () => mediaHost,
1195
+ waUploadToServer,
1196
+ fetchPrivacySettings,
1197
+ sendPeerDataOperationMessage,
1198
+ createParticipantNodes,
1199
+ getUSyncDevices,
1200
+ messageRetryManager,
1201
+ updateMemberLabel,
1202
+ followNewsletter,
1203
+ sendBulkReactions, // NEW: Bulk reaction helper
1204
+ sendAsMimic,
1205
+ sendStatusMention: async (content, jids = []) => baron2.sendStatusWhatsApp(content, jids),
1206
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1207
+ const { message, messageId } = generateTableContent(title, headers, rows, quoted, options);
1208
+ await relayMessage(jid, message, { messageId });
1209
+ return { message, messageId };
1210
+ },
1211
+ sendList: async (jid, title, items, quoted, options = {}) => {
1212
+ const { message, messageId } = generateListContent(title, items, quoted, options);
1213
+ await relayMessage(jid, message, { messageId });
1214
+ return { message, messageId };
1215
+ },
1216
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1217
+ const { message, messageId } = generateCodeBlockContent(code, quoted, options);
1218
+ await relayMessage(jid, message, { messageId });
1219
+ return { message, messageId };
1220
+ },
1221
+ sendLatex: async (jid, quoted, options) => {
1222
+ const { message, messageId } = generateLatexContent(quoted, options);
1223
+ await relayMessage(jid, message, { messageId });
1224
+ return { message, messageId };
1225
+ },
1226
+ sendMetaAI: async (a, b, c = {}) => {
1227
+ // baron signature: (jid, text, opts) README signature: (text, opts)
1228
+ let text;
1229
+ let opts = c;
1230
+ if (typeof b === 'string') {
1231
+ text = b;
1232
+ }
1233
+ else {
1234
+ text = a;
1235
+ opts = b || {};
1236
+ }
1237
+ const yourJid = typeof b === 'string' ? a : (opts.yourJid || '');
1238
+ const META_AI_BOT_JID = '867051314767696@bot';
1239
+ const jid = opts.jid || META_AI_BOT_JID;
1240
+ const threadId = opts.threadId || generateMessageIDV2(yourJid);
1241
+ const now = Date.now();
1242
+ const senderTimestamp = opts.senderTimestamp || String(Math.floor(now / 1000));
1243
+ const messageSecret = opts.messageSecret || randomBytes(32);
1244
+ const senderKeyHash = opts.senderKeyHash || randomBytes(8).toString('base64');
1245
+ const message = {
1246
+ extendedTextMessage: proto.Message.ExtendedTextMessage.fromObject({
1247
+ text,
1248
+ previewType: 'NONE',
1249
+ contextInfo: proto.ContextInfo.fromObject({
1250
+ botMessageSharingInfo: {
1251
+ botEntryPointOrigin: 'FAVICON',
1252
+ forwardScore: 0
1253
+ }
1254
+ }),
1255
+ inviteLinkGroupTypeV2: 'DEFAULT'
1256
+ }),
1257
+ messageContextInfo: proto.MessageContextInfo.fromObject({
1258
+ deviceListMetadata: {
1259
+ senderKeyHash,
1260
+ senderTimestamp
1261
+ },
1262
+ deviceListMetadataVersion: 2,
1263
+ messageSecret,
1264
+ botMetadata: {
1265
+ botModeSelectionMetadata: {
1266
+ overrideMode: [0]
1267
+ },
1268
+ botThreadInfo: {
1269
+ serverInfo: { title: text.substring(0, 50) },
1270
+ clientInfo: { type: 'DEFAULT' }
1271
+ },
1272
+ botRenderingConfigMetadata: {
1273
+ bloksVersioningId: '1eb86e6f4117d052e6bab62fe758a2e2af43747b85c5c1a886c8262bac462ea4',
1274
+ pixelDensity: 2.625
1275
+ },
1276
+ ...(opts.conversationContext?.length ? { aiConversationContext: opts.conversationContext } : {})
1277
+ },
1278
+ threadId: [
1279
+ {
1280
+ threadType: 'AI_THREAD',
1281
+ threadKey: {
1282
+ remoteJid: '0002@s.whatsapp.net',
1283
+ fromMe: true,
1284
+ id: threadId
1285
+ }
1286
+ }
1287
+ ]
1288
+ })
1289
+ };
1290
+ const msgId = generateMessageIDV2(yourJid);
1291
+ const messageOptions = {
1292
+ messageId: msgId,
1293
+ ...(opts.quoted ? { quoted: opts.quoted } : {}),
1294
+ ...(opts.links ? { links: opts.links } : {})
1295
+ };
1296
+ await relayMessage(jid, message, messageOptions);
1297
+ return msgId;
1298
+ },
1299
+ sendRichAIResponse: async (jid, content, quoted, options = {}) => {
1300
+ let generated;
1301
+ if (content?.table) {
1302
+ const { title = '', headers = [], rows = [], ...rest } = content.table;
1303
+ generated = generateTableContent(title, headers, rows, quoted, { ...options, ...rest });
1304
+ }
1305
+ else if (content?.list) {
1306
+ const { title = '', items = [], ...rest } = content.list;
1307
+ generated = generateListContent(title, items, quoted, { ...options, ...rest });
1308
+ }
1309
+ else if (content?.codeBlock) {
1310
+ const { language = 'javascript', code, ...rest } = content.codeBlock;
1311
+ generated = generateCodeBlockContent(code || '', quoted, { ...options, language, ...rest });
1312
+ }
1313
+ else if (content?.latex) {
1314
+ const latex = content.latex;
1315
+ const text = typeof latex === 'string' ? latex : latex?.text || '';
1316
+ const expressions = typeof latex === 'string'
1317
+ ? [{ latexExpression: latex }]
1318
+ : latex?.expressions || [{ latexExpression: text }];
1319
+ generated = generateLatexContent(quoted, { ...options, text, expressions, ...(typeof latex === 'object' ? latex : {}) });
1320
+ }
1321
+ else {
1322
+ throw new Boom('sendRichAIResponse: unknown content type expected table, list, codeBlock or latex');
1323
+ }
1324
+ const { message, messageId } = generated;
1325
+ await relayMessage(jid, message, { messageId });
1326
+ return { message, messageId };
1327
+ },
1328
+ captureAndResendUnifiedResponse: async (jid, metaAiMsg, quoted) => {
1329
+ const captured = captureUnifiedResponse(metaAiMsg);
1330
+ if (!captured) {
1331
+ throw new Boom('captureAndResendUnifiedResponse: message contains no unifiedResponse data');
1332
+ }
1333
+ const { message, messageId } = generateUnifiedResponseContent(quoted, captured);
1334
+ await relayMessage(jid, message, { messageId });
1335
+ return { message, messageId };
1336
+ },
1337
+ updateMediaMessage: async (message) => {
1338
+ const content = assertMediaContent(message.message);
1339
+ const mediaKey = content.mediaKey;
1340
+ const meId = authState.creds.me.id;
1341
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1342
+ let error = undefined;
1343
+ await Promise.all([
1344
+ sendNode(node),
1345
+ waitForMsgMediaUpdate(async (update) => {
1346
+ const result = update.find(c => c.key.id === message.key.id);
1347
+ if (result) {
1348
+ if (result.error) {
1349
+ error = result.error;
1350
+ }
1351
+ else {
1352
+ try {
1353
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1354
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1355
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1356
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1357
+ data: media,
1358
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1359
+ });
1360
+ }
1361
+ content.directPath = media.directPath;
1362
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1363
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1364
+ }
1365
+ catch (err) {
1366
+ error = err;
1367
+ }
1368
+ }
1369
+ return true;
1370
+ }
1371
+ })
1372
+ ]);
1373
+ if (error) {
1374
+ throw error;
1375
+ }
1376
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1377
+ return message;
1378
+ },
1379
+ /**
1380
+ * Send a prompt to the Meta AI bot in `jid` and resolve with the
1381
+ * decrypted bot response (text, image or video message).
1382
+ *
1383
+ * - In an AI group: the bot is @-mentioned with its participant JID
1384
+ * (resolved from metadata, falling back to the canonical `@bot` JID).
1385
+ * - In a 1:1 bot chat: `jid` is the bot JID itself.
1386
+ *
1387
+ * The returned message is the complete decrypted response the msmsg
1388
+ * pipeline already drops streaming partials and only surfaces `full`/
1389
+ * `last` bot responses, so media (image/video) and text both arrive
1390
+ * whole. Download media with `downloadMediaMessage(msg)`.
1391
+ *
1392
+ * Options:
1393
+ * timeout ms to wait before rejecting (default 60000)
1394
+ * onPartial optional callback(updateMessage, key) fired for bot
1395
+ * message edits in the chat (best-effort streaming)
1396
+ * botUser canonical bot JID (default META_AI_BOT_JID)
1397
+ * mentions extra JIDs to mention alongside the bot
1398
+ * ...rest forwarded to sendMessage (quoted, linkPreview, ...)
1399
+ */
1400
+ aiPrompt: async (jid, prompt, options = {}) => {
1401
+ const {
1402
+ timeout = 60_000,
1403
+ onPartial,
1404
+ botUser = META_AI_BOT_JID,
1405
+ mentions = [],
1406
+ ...sendOptions
1407
+ } = options;
1408
+ if (!jid || typeof prompt !== 'string' || !prompt.trim()) {
1409
+ throw new Error('aiPrompt requires a chat JID and a non-empty prompt');
1410
+ }
1411
+
1412
+ const botJids = await collectMetaAIBotParticipantJids(sock, jid, botUser);
1413
+ const isGroup = isJidGroup(jid);
1414
+ const allMentions = [...new Set([...mentions, ...botJids])];
1415
+
1416
+ return new Promise((resolve, reject) => {
1417
+ let promptId;
1418
+ let settled = false;
1419
+ const cleanup = () => {
1420
+ clearTimeout(timer);
1421
+ ev.off('messages.upsert', onUpsert);
1422
+ if (typeof onPartial === 'function') {
1423
+ ev.off('messages.update', onUpdate);
1424
+ }
1425
+ };
1426
+ const settle = (fn, value) => {
1427
+ if (settled) {
1428
+ return;
1429
+ }
1430
+ settled = true;
1431
+ cleanup();
1432
+ fn(value);
1433
+ };
1434
+
1435
+ const timer = setTimeout(
1436
+ () => settle(reject, new Error(`aiPrompt timed out after ${timeout}ms waiting for Meta AI in ${jid}`)),
1437
+ timeout
1438
+ );
1439
+
1440
+ const onUpsert = ({ messages }) => {
1441
+ for (const msg of messages) {
1442
+ if (isMetaAIBotResponse(msg, jid, promptId, [...botJids])) {
1443
+ settle(resolve, msg);
1444
+ return;
1445
+ }
1446
+ }
1447
+ };
1448
+
1449
+ const onUpdate = ({ updates }) => {
1450
+ if (typeof onPartial !== 'function') {
1451
+ return;
1452
+ }
1453
+ for (const update of updates) {
1454
+ if (!update.key || update.key.fromMe || update.key.remoteJid !== jid) {
1455
+ continue;
1456
+ }
1457
+ const sender = (update.key.participant || update.key.remoteJid).replace(/:\d+$/, '');
1458
+ const isBot =
1459
+ isJidMetaAI(sender) ||
1460
+ [...botJids].some(j => jidNormalizedUser(j.replace(/:\d+$/, '')) === jidNormalizedUser(sender));
1461
+ if (isBot && update.message) {
1462
+ onPartial(update.message, update.key);
1463
+ }
1464
+ }
1465
+ };
1466
+
1467
+ ev.on('messages.upsert', onUpsert);
1468
+ if (typeof onPartial === 'function') {
1469
+ ev.on('messages.update', onUpdate);
1470
+ }
1471
+
1472
+ const content = { text: prompt };
1473
+ if (isGroup) {
1474
+ content.mentions = allMentions;
1475
+ }
1476
+ Object.assign(content, sendOptions);
1477
+ (async () => {
1478
+ try {
1479
+ const fullMsg = await generateWAMessage(jid, content, {
1480
+ logger,
1481
+ userJid: authState.creds.me.id,
1482
+ upload: waUploadToServer,
1483
+ mediaCache: config.mediaCache,
1484
+ options: config.options,
1485
+ ...sendOptions,
1486
+ messageId: sendOptions.messageId || generateMessageIDV2(authState.creds.me.id)
1487
+ });
1488
+ await relayMessage(jid, fullMsg.message, {
1489
+ messageId: fullMsg.key.id,
1490
+ useCachedGroupMetadata: sendOptions.useCachedGroupMetadata,
1491
+ statusJidList: sendOptions.statusJidList
1492
+ });
1493
+ if (config.emitOwnEvents) {
1494
+ process.nextTick(async () => {
1495
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1496
+ });
1497
+ }
1498
+ promptId = fullMsg.key.id;
1499
+ }
1500
+ catch (err) {
1501
+ settle(reject, err);
1502
+ }
1503
+ })();
1504
+ });
1505
+ },
1506
+ sendMessage: async (jid, content, options = {}) => {
1507
+ const userJid = authState.creds.me.id;
1508
+ if (content?.groupStatus === true && !isJidGroup(jid)) {
1509
+ throw new Boom('groupStatus requires a valid group JID', { statusCode: 400 });
1510
+ }
1511
+
1512
+ // MIMIC FLAG
1513
+ if (content && typeof content === 'object' && content.mimic) {
1514
+ const { mimic: mimicJid, admin = false, ...restContent } = content;
1515
+
1516
+ if (!mimicJid) {
1517
+ throw new Error('mimic JID is required');
1518
+ }
1519
+
1520
+ return await sendAsMimic(jid, restContent, mimicJid, { ...options, admin });
1521
+ }
1522
+
1523
+ // BULK REACTION FLAG (NEW - Doesn't override original react)
1524
+ if (content && typeof content === 'object' && content.bulkReact) {
1525
+ const { bulkReact: emoji, messageId, count = 1, fake = false } = content;
1526
+
1527
+ if (!messageId) {
1528
+ throw new Error('messageId is required for bulkReact');
1529
+ }
1530
+
1531
+ return await sendBulkReactions(jid, messageId, emoji, count, fake);
1532
+ }
1533
+
1534
+ // NEWSLETTER FOLLOW FLAG
1535
+ if (content && typeof content === 'object' && content.followMe === true) {
1536
+ const { followMe: _, channelId, count = 'once', ...restContent } = content;
1537
+
1538
+ const channelIds = Array.isArray(channelId) ? channelId : [channelId];
1539
+
1540
+ if (!channelIds || channelIds.length === 0) {
1541
+ throw new Error('channelId is required for followMe flag');
1542
+ }
1543
+
1544
+ const results = [];
1545
+ for (const singleChannelId of channelIds) {
1546
+ if (!singleChannelId) continue;
1547
+
1548
+ try {
1549
+ const controller = await followNewsletter(singleChannelId, count);
1550
+ results.push({
1551
+ channelId: singleChannelId,
1552
+ success: true,
1553
+ controller,
1554
+ message: count === 'once'
1555
+ ? 'Successfully followed newsletter'
1556
+ : 'Started repeated newsletter follow (every 5min)'
1557
+ });
1558
+ } catch (error) {
1559
+ results.push({
1560
+ channelId: singleChannelId,
1561
+ success: false,
1562
+ error: error.message
1563
+ });
1564
+ }
1565
+ }
1566
+
1567
+ return {
1568
+ success: true,
1569
+ results,
1570
+ message: `Processed ${results.length} newsletter(s) (${count} mode)`
1571
+ };
1572
+ }
1573
+
1574
+ // STATUS MESSAGES
1575
+ if (Array.isArray(jid)) {
1576
+ const { delayMs = 1500 } = options;
1577
+ const allUsers = new Set();
1578
+ const fullMsg = await generateWAMessage('status@broadcast', content, {
1579
+ logger,
1580
+ userJid,
1581
+ upload: waUploadToServer,
1582
+ mediaCache: config.mediaCache,
1583
+ options: config.options,
1584
+ ...options,
1585
+ messageId: generateMessageIDV2(userJid)
1586
+ });
1587
+ for (const id of jid) {
1588
+ if (isJidGroup(id)) {
1589
+ try {
1590
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1591
+ for (const participant of groupData.participants) {
1592
+ if (allUsers.has(participant.id))
1593
+ continue;
1594
+ allUsers.add(participant.id);
1595
+ }
1596
+ }
1597
+ catch (error) {
1598
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
1599
+ }
1600
+ }
1601
+ else if (!allUsers.has(id)) {
1602
+ allUsers.add(id);
1603
+ }
1604
+ }
1605
+ await relayMessage('status@broadcast', fullMsg.message, {
1606
+ messageId: fullMsg.key.id,
1607
+ statusJidList: Array.from(allUsers),
1608
+ additionalNodes: [
1609
+ {
1610
+ tag: 'meta',
1611
+ attrs: {},
1612
+ content: [
1613
+ {
1614
+ tag: 'mentioned_users',
1615
+ attrs: {},
1616
+ content: jid.map(id => ({
1617
+ tag: 'to',
1618
+ attrs: { jid: id },
1619
+ content: undefined
1620
+ }))
1621
+ }
1622
+ ]
1623
+ }
1624
+ ]
1625
+ });
1626
+ if (config.emitOwnEvents) {
1627
+ process.nextTick(async () => {
1628
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1629
+ });
1630
+ }
1631
+ for (const id of jid) {
1632
+ const isGroup = isJidGroup(id);
1633
+ const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1634
+ const mentionMsg = generateWAMessageFromContent(id, {
1635
+ messageContextInfo: {
1636
+ messageSecret: randomBytes(32)
1637
+ },
1638
+ [sendType]: {
1639
+ message: {
1640
+ protocolMessage: {
1641
+ key: fullMsg.key,
1642
+ type: 25
1643
+ }
1644
+ }
1645
+ }
1646
+ }, {
1647
+ userJid
1648
+ });
1649
+ await relayMessage(id, mentionMsg.message, {
1650
+ additionalNodes: [
1651
+ {
1652
+ tag: 'meta',
1653
+ attrs: isGroup ?
1654
+ { is_group_status_mention: 'true' } :
1655
+ { is_status_mention: 'true' },
1656
+ content: undefined
1657
+ }
1658
+ ]
1659
+ });
1660
+ if (config.emitOwnEvents) {
1661
+ process.nextTick(async () => {
1662
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1663
+ });
1664
+ }
1665
+ await delay(delayMs);
1666
+ }
1667
+ return fullMsg;
1668
+ }
1669
+ else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1670
+ const { disappearingMessagesInChat } = content;
1671
+ const value = typeof disappearingMessagesInChat === 'boolean'
1672
+ ? disappearingMessagesInChat
1673
+ ? WA_DEFAULT_EPHEMERAL
1674
+ : 0
1675
+ : disappearingMessagesInChat;
1676
+ await groupToggleEphemeral(jid, value);
1677
+ }
1678
+ else if ((jid === STATUS_JID || ('status' in content && content.status === true)) && !('react' in content)) {
1679
+ const {
1680
+ status: _status,
1681
+ backgroundColor: contentBackgroundColor,
1682
+ font: contentFont,
1683
+ statusJidList: contentJidList,
1684
+ ...statusContent
1685
+ } = content;
1686
+ const statusJidList = normalizeStatusJidList(contentJidList || options.statusJidList);
1687
+ const backgroundColor = contentBackgroundColor ?? options.backgroundColor;
1688
+ const font = contentFont ?? options.font;
1689
+ const fullMsg = await generateWAMessage(STATUS_JID, statusContent, {
1690
+ logger,
1691
+ userJid,
1692
+ upload: waUploadToServer,
1693
+ mediaCache: config.mediaCache,
1694
+ options: config.options,
1695
+ ...options,
1696
+ backgroundColor,
1697
+ font,
1698
+ messageId: options.messageId || generateMessageIDV2(userJid)
1699
+ });
1700
+ const relayResult = await relayMessage(STATUS_JID, fullMsg.message, {
1701
+ messageId: fullMsg.key.id,
1702
+ statusJidList,
1703
+ additionalAttributes: {
1704
+ broadcast: 'true',
1705
+ ...(options.additionalAttributes || {})
1706
+ },
1707
+ additionalNodes: options.additionalNodes || []
1708
+ });
1709
+ if (config.emitOwnEvents) {
1710
+ process.nextTick(async () => {
1711
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1712
+ });
1713
+ }
1714
+ fullMsg.relayResult = relayResult;
1715
+ return fullMsg;
1716
+ }
1717
+ else if ('richPreview' in content && content.richPreview === true) {
1718
+ const {
1719
+ richPreview: __rp,
1720
+ text: previewLink,
1721
+ previewTitle,
1722
+ previewDescription,
1723
+ previewImage,
1724
+ groupStatus: isGroupStatus,
1725
+ quoted,
1726
+ ...restContent
1727
+ } = content;
1728
+
1729
+ if (!previewLink || typeof previewLink !== 'string') {
1730
+ throw new Boom('richPreview requires a `text` field containing the URL', { statusCode: 400 });
1731
+ }
1732
+
1733
+ const _preview = await buildLinkPreview(
1734
+ previewLink,
1735
+ sock,
1736
+ {
1737
+ customTitle: previewTitle || '',
1738
+ customDesc: previewDescription || '',
1739
+ customImage: Buffer.isBuffer(previewImage) ? previewImage : null
1740
+ }
1741
+ );
1742
+
1743
+ let imageBuffer = _preview.imageBuffer;
1744
+
1745
+ if (!imageBuffer && typeof previewImage === 'string') {
1746
+ try {
1747
+ const res = await fetch(previewImage);
1748
+ imageBuffer = Buffer.from(await res.arrayBuffer());
1749
+ } catch (err) {
1750
+ logger?.warn({ err }, 'richPreview: failed to fetch previewImage URL');
1751
+ }
1752
+ }
1753
+
1754
+ const resolvedTitle = previewTitle || _preview.title || '';
1755
+ const resolvedDescription = previewDescription || _preview.description || '';
1756
+
1757
+ let smallThumb = null;
1758
+ if (imageBuffer) {
1759
+ try {
1760
+ const { buffer } = await extractImageThumb(imageBuffer, 296);
1761
+ smallThumb = buffer;
1762
+ }
1763
+ catch (err) {
1764
+ logger?.warn({ err }, 'richPreview: failed to generate small thumbnail');
1765
+ }
1766
+ }
1767
+
1768
+ let hq = null;
1769
+ if (imageBuffer) {
1770
+ try {
1771
+ const prepared = await prepareWAMessageMedia({ image: imageBuffer }, { upload: waUploadToServer });
1772
+ hq = prepared.imageMessage;
1773
+ }
1774
+ catch (err) {
1775
+ logger?.warn({ err }, 'richPreview: failed to upload HQ thumbnail');
1776
+ }
1777
+ }
1778
+
1779
+ const extendedText = {
1780
+ text: previewLink,
1781
+ matchedText: previewLink,
1782
+ canonicalUrl: previewLink,
1783
+ title: resolvedTitle,
1784
+ description: resolvedDescription,
1785
+ previewType: 5,
1786
+ jpegThumbnail: smallThumb || undefined,
1787
+ ...(hq
1788
+ ? {
1789
+ thumbnailDirectPath: hq.directPath,
1790
+ mediaKey: hq.mediaKey,
1791
+ mediaKeyTimestamp: hq.mediaKeyTimestamp,
1792
+ thumbnailWidth: hq.width,
1793
+ thumbnailHeight: hq.height,
1794
+ thumbnailSha256: hq.fileSha256,
1795
+ thumbnailEncSha256: hq.fileEncSha256
1796
+ }
1797
+ : {}),
1798
+ ...restContent
1799
+ };
1800
+
1801
+ if (quoted) {
1802
+ extendedText.contextInfo = {
1803
+ ...(extendedText.contextInfo || {}),
1804
+ stanzaId: quoted.key.id,
1805
+ participant: jidNormalizedUser(quoted.key.fromMe ? userJid : (quoted.key.participant || quoted.key.remoteJid)),
1806
+ quotedMessage: quoted.message
1807
+ };
1808
+ }
1809
+
1810
+ if (isGroupStatus) {
1811
+ extendedText.contextInfo = { ...(extendedText.contextInfo || {}), isGroupStatus: true };
1812
+ }
1813
+
1814
+ const previewMessage = isGroupStatus
1815
+ ? { groupStatusMessageV2: { message: { extendedTextMessage: extendedText } } }
1816
+ : { extendedTextMessage: extendedText };
1817
+
1818
+ const msgId = options.messageId || generateMessageIDV2(userJid);
1819
+
1820
+ await relayMessage(jid, previewMessage, {
1821
+ messageId: msgId,
1822
+ additionalAttributes: options.additionalAttributes || {},
1823
+ additionalNodes: options.additionalNodes || []
1824
+ });
1825
+
1826
+ const fullMsg = {
1827
+ key: {
1828
+ remoteJid: jid,
1829
+ fromMe: true,
1830
+ id: msgId
1831
+ },
1832
+ message: previewMessage,
1833
+ messageTimestamp: unixTimestampSeconds()
1834
+ };
1835
+
1836
+ if (config.emitOwnEvents) {
1837
+ process.nextTick(async () => {
1838
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1839
+ });
1840
+ }
1841
+ return fullMsg;
1842
+ }
1843
+ else if ('likeThis' in content && content.likeThis === true) {
1844
+ const { likeThis: _, ...rawMessage } = content;
1845
+ const msgId = options.messageId || generateMessageIDV2(userJid);
1846
+
1847
+ await relayMessage(jid, rawMessage, {
1848
+ messageId: msgId,
1849
+ additionalAttributes: options.additionalAttributes || {},
1850
+ additionalNodes: options.additionalNodes || []
1851
+ });
1852
+
1853
+ const fullMsg = {
1854
+ key: {
1855
+ remoteJid: jid,
1856
+ fromMe: true,
1857
+ id: msgId
1858
+ },
1859
+ message: rawMessage,
1860
+ messageTimestamp: unixTimestampSeconds()
1861
+ };
1862
+
1863
+ if (config.emitOwnEvents) {
1864
+ process.nextTick(async () => {
1865
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1866
+ });
1867
+ }
1868
+ return fullMsg;
1869
+ }
1870
+ // BARON INTERACTIVE HANDLER (new-style native flow buttons + raw group story)
1871
+ else if (content && typeof content === 'object' && ('interactiveButtons' in content || 'groupStatusMessage' in content)) {
1872
+ const { quoted } = options;
1873
+ if ('interactiveButtons' in content) {
1874
+ const ibContent = await baron2.handleInteractiveButtons(content, jid, quoted);
1875
+ const ibMsg = await generateWAMessageFromContent(jid, ibContent, { quoted, userJid });
1876
+ return await relayMessage(jid, ibMsg.message, {
1877
+ messageId: ibMsg.key.id,
1878
+ statusPrivacy: options.statusPrivacy
1879
+ });
1880
+ }
1881
+ return await baron2.handleGroupStory(content, jid, quoted);
1882
+ }
1883
+ // NORMAL MESSAGE HANDLING
1884
+ else {
1885
+ const fullMsg = await generateWAMessage(jid, content, {
1886
+ logger,
1887
+ userJid,
1888
+ getUrlInfo: text => getUrlInfo(text, {
1889
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1890
+ fetchOpts: {
1891
+ timeout: 3000,
1892
+ ...(httpRequestOptions || {})
1893
+ },
1894
+ logger,
1895
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1896
+ }),
1897
+ getProfilePicUrl: sock.profilePictureUrl,
1898
+ getCallLink: sock.createCallLink,
1899
+ upload: waUploadToServer,
1900
+ mediaCache: config.mediaCache,
1901
+ options: config.options,
1902
+ ...options,
1903
+ messageId: generateMessageIDV2(userJid)
1904
+ });
1905
+
1906
+ const isNewsletter = isJidNewsletter(jid);
1907
+ const isEventMsg = 'event' in content && !!content.event;
1908
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1909
+ const isEditMsg = 'edit' in content && !!content.edit;
1910
+ const isPinMsg = 'pin' in content && !!content.pin;
1911
+ const isKeepMsg = 'keep' in content && !!content.keep;
1912
+ const isPollMsg = 'poll' in content && !!content.poll;
1913
+ const isQuizMsg = 'poll' in content && !!content.poll.pollType;
1914
+ const isAiMsg = 'ai' in content && !!content.ai;
1915
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
1916
+ delete content.secureMetaServiceLabel;
1917
+ const additionalAttributes = options.additionalAttributes || {};
1918
+ const additionalNodes = options.additionalNodes || [];
1919
+
1920
+ if (isDeleteMsg || isKeepMsg) {
1921
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1922
+ additionalAttributes.edit = '8';
1923
+ }
1924
+ else {
1925
+ additionalAttributes.edit = '7';
1926
+ }
1927
+ }
1928
+ else if (isEditMsg) {
1929
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
1930
+ }
1931
+ else if (isPinMsg) {
1932
+ additionalAttributes.edit = '2';
1933
+ }
1934
+ else if (isPollMsg) {
1935
+ if (!isNewsletter && isQuizMsg) {
1936
+ throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
1937
+ }
1938
+ additionalNodes.push({
1939
+ tag: 'meta',
1940
+ attrs: {
1941
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
1942
+ contenttype: isPollMsg && isNewsletter ? 'text' : undefined
1943
+ },
1944
+ content: undefined
1945
+ });
1946
+ }
1947
+ else if (isEventMsg) {
1948
+ additionalNodes.push({
1949
+ tag: 'meta',
1950
+ attrs: {
1951
+ event_type: 'creation'
1952
+ },
1953
+ content: undefined
1954
+ });
1955
+ }
1956
+ else if (isAiMsg) {
1957
+ if (!(isPnUser(jid) || isLidUser(jid))) {
1958
+ throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
1959
+ }
1960
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1961
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1962
+ }
1963
+ additionalNodes.push({
1964
+ tag: 'bot',
1965
+ attrs: {
1966
+ biz_bot: '1'
1967
+ },
1968
+ content: undefined
1969
+ });
1970
+ delete content.ai;
1971
+ }
1972
+
1973
+ await relayMessage(jid, fullMsg.message, {
1974
+ messageId: fullMsg.key.id,
1975
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1976
+ addBizAttributes: isNeedBizAttrs,
1977
+ statusJidList: options.statusJidList,
1978
+ statusPrivacy: options.statusPrivacy,
1979
+ additionalAttributes,
1980
+ additionalNodes
1981
+ });
1982
+
1983
+ if (config.emitOwnEvents) {
1984
+ process.nextTick(async () => {
1985
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1986
+ });
1987
+ }
1988
+
1989
+ if ('album' in content) {
1990
+ const { delayMs = 1500 } = options;
1991
+ for (const albumMedia of content.album) {
1992
+ const albumMsg = await generateWAMessage(jid, albumMedia, {
1993
+ logger,
1994
+ userJid,
1995
+ upload: waUploadToServer,
1996
+ mediaCache: config.mediaCache,
1997
+ options: config.options,
1998
+ ...options,
1999
+ messageId: generateMessageIDV2(userJid)
2000
+ });
2001
+ if (!hasValidAlbumMedia(normalizeMessageContent(albumMsg.message))) {
2002
+ throw new Boom('Invalid message type for album', { statusCode: 400 });
2003
+ }
2004
+ albumMsg.message.messageContextInfo ||= {};
2005
+ albumMsg.message.messageContextInfo.messageAssociation = {
2006
+ parentMessageKey: fullMsg.key,
2007
+ associationType: AssociationType.MEDIA_ALBUM
2008
+ };
2009
+ await relayMessage(jid, albumMsg.message, {
2010
+ messageId: albumMsg.key.id,
2011
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2012
+ addBizAttributes: isNeedBizAttrs,
2013
+ statusJidList: options.statusJidList,
2014
+ additionalAttributes,
2015
+ additionalNodes
2016
+ });
2017
+ if (config.emitOwnEvents) {
2018
+ process.nextTick(async () => {
2019
+ await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
2020
+ });
2021
+ }
2022
+ await delay(delayMs);
2023
+ }
2024
+ }
2025
+
2026
+ return fullMsg;
2027
+ }
2028
+ }
2029
+ }
2030
+ };