@boruto_vk7/baileys 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1388 -0
  3. package/WAProto/index.js +104236 -0
  4. package/engine-requirements.js +13 -0
  5. package/lib/Defaults/index.js +148 -0
  6. package/lib/Signal/Group/ciphertext-message.js +11 -0
  7. package/lib/Signal/Group/group-session-builder.js +29 -0
  8. package/lib/Signal/Group/group_cipher.js +81 -0
  9. package/lib/Signal/Group/index.js +11 -0
  10. package/lib/Signal/Group/keyhelper.js +17 -0
  11. package/lib/Signal/Group/sender-chain-key.js +25 -0
  12. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  13. package/lib/Signal/Group/sender-key-message.js +65 -0
  14. package/lib/Signal/Group/sender-key-name.js +47 -0
  15. package/lib/Signal/Group/sender-key-record.js +40 -0
  16. package/lib/Signal/Group/sender-key-state.js +83 -0
  17. package/lib/Signal/Group/sender-message-key.js +25 -0
  18. package/lib/Signal/libsignal.js +406 -0
  19. package/lib/Signal/lid-mapping.js +276 -0
  20. package/lib/Socket/Client/index.js +2 -0
  21. package/lib/Socket/Client/types.js +10 -0
  22. package/lib/Socket/Client/websocket.js +53 -0
  23. package/lib/Socket/business.js +378 -0
  24. package/lib/Socket/chats.js +1059 -0
  25. package/lib/Socket/communities.js +430 -0
  26. package/lib/Socket/groups.js +329 -0
  27. package/lib/Socket/index.js +11 -0
  28. package/lib/Socket/messages-recv.js +1476 -0
  29. package/lib/Socket/messages-send.js +1268 -0
  30. package/lib/Socket/mex.js +41 -0
  31. package/lib/Socket/newsletter.js +227 -0
  32. package/lib/Socket/socket.js +949 -0
  33. package/lib/Store/index.js +3 -0
  34. package/lib/Store/make-in-memory-store.js +420 -0
  35. package/lib/Store/make-ordered-dictionary.js +78 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Types/Auth.js +1 -0
  38. package/lib/Types/Bussines.js +1 -0
  39. package/lib/Types/Call.js +1 -0
  40. package/lib/Types/Chat.js +7 -0
  41. package/lib/Types/Contact.js +1 -0
  42. package/lib/Types/Events.js +1 -0
  43. package/lib/Types/GroupMetadata.js +1 -0
  44. package/lib/Types/Label.js +24 -0
  45. package/lib/Types/LabelAssociation.js +6 -0
  46. package/lib/Types/Message.js +17 -0
  47. package/lib/Types/Newsletter.js +33 -0
  48. package/lib/Types/Product.js +1 -0
  49. package/lib/Types/RichType.js +22 -0
  50. package/lib/Types/Signal.js +1 -0
  51. package/lib/Types/Socket.js +2 -0
  52. package/lib/Types/State.js +12 -0
  53. package/lib/Types/USync.js +1 -0
  54. package/lib/Types/index.js +25 -0
  55. package/lib/Utils/auth-utils.js +289 -0
  56. package/lib/Utils/browser-utils.js +28 -0
  57. package/lib/Utils/business.js +230 -0
  58. package/lib/Utils/chat-utils.js +811 -0
  59. package/lib/Utils/companion-reg-client-utils.js +32 -0
  60. package/lib/Utils/crypto.js +117 -0
  61. package/lib/Utils/decode-wa-message.js +282 -0
  62. package/lib/Utils/event-buffer.js +589 -0
  63. package/lib/Utils/generics.js +385 -0
  64. package/lib/Utils/history.js +130 -0
  65. package/lib/Utils/identity-change-handler.js +48 -0
  66. package/lib/Utils/index.js +23 -0
  67. package/lib/Utils/link-preview.js +84 -0
  68. package/lib/Utils/logger.js +2 -0
  69. package/lib/Utils/lt-hash.js +7 -0
  70. package/lib/Utils/make-mutex.js +32 -0
  71. package/lib/Utils/message-retry-manager.js +241 -0
  72. package/lib/Utils/messages-media.js +830 -0
  73. package/lib/Utils/messages.js +1879 -0
  74. package/lib/Utils/noise-handler.js +200 -0
  75. package/lib/Utils/offline-node-processor.js +39 -0
  76. package/lib/Utils/pre-key-manager.js +105 -0
  77. package/lib/Utils/process-message.js +527 -0
  78. package/lib/Utils/reporting-utils.js +257 -0
  79. package/lib/Utils/rich-message-utils.js +387 -0
  80. package/lib/Utils/signal.js +158 -0
  81. package/lib/Utils/stanza-ack.js +37 -0
  82. package/lib/Utils/sync-action-utils.js +47 -0
  83. package/lib/Utils/tc-token-utils.js +17 -0
  84. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  85. package/lib/Utils/use-single-file-auth-state.js +96 -0
  86. package/lib/Utils/validate-connection.js +206 -0
  87. package/lib/WABinary/constants.js +1372 -0
  88. package/lib/WABinary/decode.js +261 -0
  89. package/lib/WABinary/encode.js +219 -0
  90. package/lib/WABinary/generic-utils.js +227 -0
  91. package/lib/WABinary/index.js +5 -0
  92. package/lib/WABinary/jid-utils.js +95 -0
  93. package/lib/WABinary/types.js +1 -0
  94. package/lib/WAM/BinaryInfo.js +9 -0
  95. package/lib/WAM/constants.js +22852 -0
  96. package/lib/WAM/encode.js +149 -0
  97. package/lib/WAM/index.js +3 -0
  98. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  99. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  100. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  101. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  102. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  103. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  104. package/lib/WAUSync/Protocols/index.js +4 -0
  105. package/lib/WAUSync/USyncQuery.js +93 -0
  106. package/lib/WAUSync/USyncUser.js +22 -0
  107. package/lib/WAUSync/index.js +3 -0
  108. package/lib/index.js +14 -0
  109. package/lib/logger.js +87 -0
  110. package/package.json +80 -0
@@ -0,0 +1,1268 @@
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, bindWaitForEvent, decryptMediaRetryData, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessageFromContent, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { AssociationType } from '../Types/index.js';
8
+ import { getUrlInfo } from '../Utils/link-preview.js';
9
+ import { makeKeyedMutex } from '../Utils/make-mutex.js';
10
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
11
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidGroup, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
12
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
+ import { makeNewsletterSocket } from './newsletter.js';
14
+ export const makeMessagesSocket = (config) => {
15
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
16
+ const sock = makeNewsletterSocket(config);
17
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
18
+ const userDevicesCache = config.userDevicesCache ??=
19
+ new NodeCache({
20
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
21
+ useClones: false
22
+ });
23
+ const peerSessionsCache = new NodeCache({
24
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
25
+ useClones: false
26
+ });
27
+ // Initialize message retry manager if enabled
28
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
29
+ // Prevent race conditions in Signal session encryption by user
30
+ const encryptionMutex = makeKeyedMutex();
31
+ // Prevent race conditions in media connection refresh
32
+ const mediaConnMutex = makeKeyedMutex();
33
+ let mediaConn;
34
+ const refreshMediaConn = async (forceGet = false) => {
35
+ return mediaConnMutex.mutex('media-conn', async () => {
36
+ const media = await mediaConn;
37
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
38
+ mediaConn = (async () => {
39
+ const result = await query({
40
+ tag: 'iq',
41
+ attrs: {
42
+ type: 'set',
43
+ xmlns: 'w:m',
44
+ to: S_WHATSAPP_NET
45
+ },
46
+ content: [{ tag: 'media_conn', attrs: {} }]
47
+ });
48
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
49
+ // TODO: explore full length of data that whatsapp provides
50
+ const node = {
51
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
52
+ hostname: attrs.hostname,
53
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
54
+ })),
55
+ auth: mediaConnNode.attrs.auth,
56
+ ttl: +mediaConnNode.attrs.ttl,
57
+ fetchDate: new Date()
58
+ };
59
+ logger.debug('fetched media conn');
60
+ return node;
61
+ })();
62
+ }
63
+ return mediaConn;
64
+ });
65
+ };
66
+ /**
67
+ * generic send receipt function
68
+ * used for receipts of phone call, read, delivery etc.
69
+ * */
70
+ const sendReceipt = async (jid, participant, messageIds, type) => {
71
+ if (!messageIds || messageIds.length === 0) {
72
+ throw new Boom('missing ids in receipt');
73
+ }
74
+ const node = {
75
+ tag: 'receipt',
76
+ attrs: {
77
+ id: messageIds[0]
78
+ }
79
+ };
80
+ const isReadReceipt = type === 'read' || type === 'read-self';
81
+ if (isReadReceipt) {
82
+ node.attrs.t = unixTimestampSeconds().toString();
83
+ }
84
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
85
+ node.attrs.recipient = jid;
86
+ node.attrs.to = participant;
87
+ }
88
+ else {
89
+ node.attrs.to = jid;
90
+ if (participant) {
91
+ node.attrs.participant = participant;
92
+ }
93
+ }
94
+ if (type) {
95
+ node.attrs.type = type;
96
+ }
97
+ const remainingMessageIds = messageIds.slice(1);
98
+ if (remainingMessageIds.length) {
99
+ node.content = [
100
+ {
101
+ tag: 'list',
102
+ attrs: {},
103
+ content: remainingMessageIds.map(id => ({
104
+ tag: 'item',
105
+ attrs: { id }
106
+ }))
107
+ }
108
+ ];
109
+ }
110
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
111
+ await sendNode(node);
112
+ };
113
+ /** Correctly bulk send receipts to multiple chats, participants */
114
+ const sendReceipts = async (keys, type) => {
115
+ const recps = aggregateMessageKeysNotFromMe(keys);
116
+ for (const { jid, participant, messageIds } of recps) {
117
+ await sendReceipt(jid, participant, messageIds, type);
118
+ }
119
+ };
120
+ /** Bulk read messages. Keys can be from different chats & participants */
121
+ const readMessages = async (keys) => {
122
+ const privacySettings = await fetchPrivacySettings();
123
+ // based on privacy settings, we have to change the read type
124
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
125
+ await sendReceipts(keys, readType);
126
+ };
127
+ /** Fetch all the devices we've to send a message to */
128
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
129
+ const deviceResults = [];
130
+ if (!useCache) {
131
+ logger.debug('not using cache for devices');
132
+ }
133
+ const toFetch = [];
134
+ const jidsWithUser = jids
135
+ .map(jid => {
136
+ const decoded = jidDecode(jid);
137
+ const user = decoded?.user;
138
+ const device = decoded?.device;
139
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
140
+ if (isExplicitDevice && user) {
141
+ deviceResults.push({
142
+ user,
143
+ device,
144
+ jid
145
+ });
146
+ return null;
147
+ }
148
+ jid = jidNormalizedUser(jid);
149
+ return { jid, user };
150
+ })
151
+ .filter(jid => jid !== null);
152
+ let mgetDevices;
153
+ if (useCache && userDevicesCache.mget) {
154
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
155
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
156
+ }
157
+ for (const { jid, user } of jidsWithUser) {
158
+ if (useCache) {
159
+ const devices = mgetDevices?.[user] ||
160
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
161
+ if (devices) {
162
+ const devicesWithJid = devices.map(d => ({
163
+ ...d,
164
+ jid: jidEncode(d.user, d.server, d.device)
165
+ }));
166
+ deviceResults.push(...devicesWithJid);
167
+ logger.trace({ user }, 'using cache for devices');
168
+ }
169
+ else {
170
+ toFetch.push(jid);
171
+ }
172
+ }
173
+ else {
174
+ toFetch.push(jid);
175
+ }
176
+ }
177
+ if (!toFetch.length) {
178
+ return deviceResults;
179
+ }
180
+ const requestedLidUsers = new Set();
181
+ for (const jid of toFetch) {
182
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
183
+ const user = jidDecode(jid)?.user;
184
+ if (user)
185
+ requestedLidUsers.add(user);
186
+ }
187
+ }
188
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
189
+ for (const jid of toFetch) {
190
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
191
+ }
192
+ const result = await sock.executeUSyncQuery(query);
193
+ if (result) {
194
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
195
+ const lidResults = result.list.filter(a => !!a.lid);
196
+ if (lidResults.length > 0) {
197
+ logger.trace('Storing LID maps from device call');
198
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
199
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
200
+ try {
201
+ const lids = lidResults.map(a => a.lid);
202
+ if (lids.length) {
203
+ await assertSessions(lids, true);
204
+ }
205
+ }
206
+ catch (e) {
207
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
208
+ }
209
+ }
210
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
211
+ const deviceMap = {};
212
+ for (const item of extracted) {
213
+ deviceMap[item.user] = deviceMap[item.user] || [];
214
+ deviceMap[item.user]?.push(item);
215
+ }
216
+ // Process each user's devices as a group for bulk LID migration
217
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
218
+ const isLidUser = requestedLidUsers.has(user);
219
+ // Process all devices for this user
220
+ for (const item of userDevices) {
221
+ const finalJid = isLidUser
222
+ ? jidEncode(user, item.server, item.device)
223
+ : jidEncode(item.user, item.server, item.device);
224
+ deviceResults.push({
225
+ ...item,
226
+ jid: finalJid
227
+ });
228
+ logger.debug({
229
+ user: item.user,
230
+ device: item.device,
231
+ finalJid,
232
+ usedLid: isLidUser
233
+ }, 'Processed device with LID priority');
234
+ }
235
+ }
236
+ if (userDevicesCache.mset) {
237
+ // if the cache supports mset, we can set all devices in one go
238
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
239
+ }
240
+ else {
241
+ for (const key in deviceMap) {
242
+ if (deviceMap[key])
243
+ await userDevicesCache.set(key, deviceMap[key]);
244
+ }
245
+ }
246
+ const userDeviceUpdates = {};
247
+ for (const [userId, devices] of Object.entries(deviceMap)) {
248
+ if (devices && devices.length > 0) {
249
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString());
250
+ }
251
+ }
252
+ if (Object.keys(userDeviceUpdates).length > 0) {
253
+ try {
254
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
255
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
256
+ }
257
+ catch (error) {
258
+ logger.warn({ error }, 'failed to store user device lists');
259
+ }
260
+ }
261
+ }
262
+ return deviceResults;
263
+ };
264
+ /**
265
+ * Update Member Label
266
+ */
267
+ const updateMemberLabel = (jid, memberLabel) => {
268
+ return relayMessage(jid, {
269
+ protocolMessage: {
270
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
271
+ memberLabel: {
272
+ label: memberLabel?.slice(0, 30),
273
+ labelTimestamp: unixTimestampSeconds()
274
+ }
275
+ }
276
+ }, {
277
+ additionalNodes: [
278
+ {
279
+ tag: 'meta',
280
+ attrs: {
281
+ tag_reason: 'user_update',
282
+ appdata: 'member_tag'
283
+ },
284
+ content: undefined
285
+ }
286
+ ]
287
+ });
288
+ };
289
+ const assertSessions = async (jids, force) => {
290
+ let didFetchNewSession = false;
291
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
292
+ const jidsRequiringFetch = [];
293
+ logger.debug({ jids }, 'assertSessions call with jids');
294
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
295
+ for (const jid of uniqueJids) {
296
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
297
+ const cachedSession = peerSessionsCache.get(signalId);
298
+ if (cachedSession !== undefined) {
299
+ if (cachedSession && !force) {
300
+ continue; // Session exists in cache
301
+ }
302
+ }
303
+ else {
304
+ const sessionValidation = await signalRepository.validateSession(jid);
305
+ const hasSession = sessionValidation.exists;
306
+ peerSessionsCache.set(signalId, hasSession);
307
+ if (hasSession && !force) {
308
+ continue;
309
+ }
310
+ }
311
+ jidsRequiringFetch.push(jid);
312
+ }
313
+ if (jidsRequiringFetch.length) {
314
+ // LID if mapped, otherwise original
315
+ const wireJids = [
316
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
317
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
318
+ ];
319
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
320
+ const result = await query({
321
+ tag: 'iq',
322
+ attrs: {
323
+ xmlns: 'encrypt',
324
+ type: 'get',
325
+ to: S_WHATSAPP_NET
326
+ },
327
+ content: [
328
+ {
329
+ tag: 'key',
330
+ attrs: {},
331
+ content: wireJids.map(jid => {
332
+ const attrs = { jid };
333
+ if (force)
334
+ attrs.reason = 'identity';
335
+ return { tag: 'user', attrs };
336
+ })
337
+ }
338
+ ]
339
+ });
340
+ await parseAndInjectE2ESessions(result, signalRepository);
341
+ didFetchNewSession = true;
342
+ // Cache fetched sessions using wire JIDs
343
+ for (const wireJid of wireJids) {
344
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
345
+ peerSessionsCache.set(signalId, true);
346
+ }
347
+ }
348
+ return didFetchNewSession;
349
+ };
350
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
351
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
352
+ if (!authState.creds.me?.id) {
353
+ throw new Boom('Not authenticated');
354
+ }
355
+ const protocolMessage = {
356
+ protocolMessage: {
357
+ peerDataOperationRequestMessage: pdoMessage,
358
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
359
+ }
360
+ };
361
+ const meJid = jidNormalizedUser(authState.creds.me.id);
362
+ const msgId = await relayMessage(meJid, protocolMessage, {
363
+ additionalAttributes: {
364
+ category: 'peer',
365
+ push_priority: 'high_force'
366
+ },
367
+ additionalNodes: [
368
+ {
369
+ tag: 'meta',
370
+ attrs: { appdata: 'default' }
371
+ }
372
+ ]
373
+ });
374
+ return msgId;
375
+ };
376
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
377
+ if (!recipientJids.length) {
378
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
379
+ }
380
+ const patched = await patchMessageBeforeSending(message, recipientJids);
381
+ const patchedMessages = Array.isArray(patched)
382
+ ? patched
383
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
384
+ let shouldIncludeDeviceIdentity = false;
385
+ const meId = authState.creds.me.id;
386
+ const meLid = authState.creds.me?.lid;
387
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
388
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
389
+ try {
390
+ if (!jid)
391
+ return null;
392
+ let msgToEncrypt = patchedMessage;
393
+ if (dsmMessage) {
394
+ const { user: targetUser } = jidDecode(jid);
395
+ const { user: ownPnUser } = jidDecode(meId);
396
+ const ownLidUser = meLidUser;
397
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
398
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
399
+ if (isOwnUser && !isExactSenderDevice) {
400
+ msgToEncrypt = dsmMessage;
401
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
402
+ }
403
+ }
404
+ const bytes = encodeWAMessage(msgToEncrypt);
405
+ const mutexKey = jid;
406
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
407
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
408
+ if (type === 'pkmsg') {
409
+ shouldIncludeDeviceIdentity = true;
410
+ }
411
+ return {
412
+ tag: 'to',
413
+ attrs: { jid },
414
+ content: [
415
+ {
416
+ tag: 'enc',
417
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
418
+ content: ciphertext
419
+ }
420
+ ]
421
+ };
422
+ });
423
+ return node;
424
+ }
425
+ catch (err) {
426
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
427
+ return null;
428
+ }
429
+ });
430
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
431
+ if (recipientJids.length > 0 && nodes.length === 0) {
432
+ throw new Boom('All encryptions failed', { statusCode: 500 });
433
+ }
434
+ return { nodes, shouldIncludeDeviceIdentity };
435
+ };
436
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList }) => {
437
+ const meId = authState.creds.me.id;
438
+ const meLid = authState.creds.me?.lid;
439
+ const isRetryResend = !!participant?.jid;
440
+ let shouldIncludeDeviceIdentity = isRetryResend;
441
+ const statusJid = 'status@broadcast';
442
+ const { user, server } = jidDecode(jid);
443
+ const isGroup = server === 'g.us';
444
+ const isStatus = jid === statusJid;
445
+ const isLid = server === 'lid';
446
+ const isNewsletter = server === 'newsletter';
447
+ const isGroupOrStatus = isGroup || isStatus;
448
+ const finalJid = jid;
449
+ msgId = msgId || generateMessageIDV2(meId);
450
+ useUserDevicesCache = useUserDevicesCache !== false;
451
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
452
+ const participants = [];
453
+ const destinationJid = !isStatus ? finalJid : statusJid;
454
+ const binaryNodeContent = [];
455
+ const devices = [];
456
+ let reportingMessage;
457
+ const meMsg = {
458
+ deviceSentMessage: {
459
+ destinationJid,
460
+ message
461
+ },
462
+ messageContextInfo: message.messageContextInfo
463
+ };
464
+ const extraAttrs = {};
465
+ if (participant) {
466
+ if (!isGroup && !isStatus) {
467
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
468
+ }
469
+ const { user, device } = jidDecode(participant.jid);
470
+ devices.push({
471
+ user,
472
+ device,
473
+ jid: participant.jid
474
+ });
475
+ }
476
+ await authState.keys.transaction(async () => {
477
+ // Lia@Changes 02-02-26 --- Normalize message first to extract the original message and valid media type
478
+ const innerMessage = normalizeMessageContent(message);
479
+ const mediaType = getMediaType(innerMessage);
480
+ if (mediaType) {
481
+ extraAttrs['mediatype'] = mediaType;
482
+ }
483
+ if (isNewsletter) {
484
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
485
+ const bytes = encodeNewsletterMessage(patched);
486
+ // Lia@Changes 08-02-26 --- Add "additionalNodes" for newsletter too (⁠っ⁠˘̩⁠╭⁠╮⁠˘̩⁠)⁠っ
487
+ if (additionalNodes && additionalNodes.length > 0) {
488
+ ;
489
+ binaryNodeContent.push(...additionalNodes);
490
+ }
491
+ binaryNodeContent.push({
492
+ tag: 'plaintext',
493
+ attrs: extraAttrs, // Lia@Changes 02-02-26 --- Add extraAttrs to fix media being rejected when sending to newsletter (⁠◠⁠‿⁠◕⁠)
494
+ content: bytes
495
+ });
496
+ const stanza = {
497
+ tag: 'message',
498
+ attrs: {
499
+ to: jid,
500
+ id: msgId,
501
+ type: getMessageType(innerMessage),
502
+ ...(additionalAttributes || {})
503
+ },
504
+ content: binaryNodeContent
505
+ };
506
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
507
+ await sendNode(stanza);
508
+ return;
509
+ }
510
+ // Lia@Changes 02-02-26 --- Add keepInChat, editedMessage, mediaNotifyMessage and pollUpdateMessage
511
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage
512
+ if (isNeedMetaAttrs) {
513
+ const metaAttrs = {};
514
+ if (innerMessage?.pollUpdateMessage) {
515
+ metaAttrs.polltype = 'vote';
516
+ }
517
+ metaAttrs.content_type = 'add_on';
518
+ binaryNodeContent.push({
519
+ tag: 'meta',
520
+ attrs: metaAttrs,
521
+ content: undefined
522
+ });
523
+ }
524
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
525
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
526
+ }
527
+ // Lia@Changes 02-02-26 --- Add native_flow_name to extraAttrs when sending interactiveResponseMessage
528
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
529
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
530
+ }
531
+ if (isGroupOrStatus && !isRetryResend) {
532
+ const [groupData, senderKeyMap] = await Promise.all([
533
+ (async () => {
534
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
535
+ if (groupData && Array.isArray(groupData?.participants)) {
536
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
537
+ }
538
+ else if (!isStatus) {
539
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
540
+ }
541
+ return groupData;
542
+ })(),
543
+ (async () => {
544
+ if (!participant && !isStatus) {
545
+ // what if sender memory is less accurate than the cached metadata
546
+ // on participant change in group, we should do sender memory manipulation
547
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
548
+ return result[jid] || {};
549
+ }
550
+ return {};
551
+ })()
552
+ ]);
553
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
554
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
555
+ additionalAttributes = {
556
+ ...additionalAttributes,
557
+ expiration: groupData.ephemeralDuration.toString()
558
+ };
559
+ }
560
+ if (isStatus && statusJidList) {
561
+ participantsList.push(...statusJidList);
562
+ }
563
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
564
+ devices.push(...additionalDevices);
565
+ if (isGroup) {
566
+ additionalAttributes = {
567
+ ...additionalAttributes,
568
+ addressing_mode: groupData?.addressingMode || 'lid'
569
+ };
570
+ }
571
+ const patched = await patchMessageBeforeSending(message);
572
+ if (Array.isArray(patched)) {
573
+ throw new Boom('Per-jid patching is not supported in groups');
574
+ }
575
+ const bytes = encodeWAMessage(patched);
576
+ reportingMessage = patched;
577
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
578
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
579
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
580
+ group: destinationJid,
581
+ data: bytes,
582
+ meId: groupSenderIdentity
583
+ });
584
+ const senderKeyRecipients = [];
585
+ for (const device of devices) {
586
+ const deviceJid = device.jid;
587
+ const hasKey = !!senderKeyMap[deviceJid];
588
+ if ((!hasKey || !!participant) &&
589
+ !isHostedLidUser(deviceJid) &&
590
+ !isHostedPnUser(deviceJid) &&
591
+ device.device !== 99) {
592
+ //todo: revamp all this logic
593
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
594
+ senderKeyRecipients.push(deviceJid);
595
+ senderKeyMap[deviceJid] = true;
596
+ }
597
+ }
598
+ if (senderKeyRecipients.length) {
599
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
600
+ const senderKeyMsg = {
601
+ senderKeyDistributionMessage: {
602
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
603
+ groupId: destinationJid
604
+ }
605
+ };
606
+ const senderKeySessionTargets = senderKeyRecipients;
607
+ await assertSessions(senderKeySessionTargets);
608
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
609
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
610
+ participants.push(...result.nodes);
611
+ }
612
+ binaryNodeContent.push({
613
+ tag: 'enc',
614
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
615
+ content: ciphertext
616
+ });
617
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
618
+ }
619
+ else {
620
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
621
+ // TODO: investigate if this is true
622
+ let ownId = meId;
623
+ if (isLid && meLid) {
624
+ ownId = meLid;
625
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
626
+ }
627
+ else {
628
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
629
+ }
630
+ const { user: ownUser } = jidDecode(ownId);
631
+ if (!participant) {
632
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
633
+ reportingMessage = Array.isArray(patchedForReporting)
634
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
635
+ : patchedForReporting;
636
+ }
637
+ if (!isRetryResend) {
638
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
639
+ devices.push({
640
+ user,
641
+ device: 0,
642
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
643
+ });
644
+ if (user !== ownUser) {
645
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
646
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
647
+ devices.push({
648
+ user: ownUserForAddressing,
649
+ device: 0,
650
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
651
+ });
652
+ }
653
+ if (additionalAttributes?.['category'] !== 'peer') {
654
+ // Clear placeholders and enumerate actual devices
655
+ devices.length = 0;
656
+ // Use conversation-appropriate sender identity
657
+ const senderIdentity = isLid && meLid
658
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
659
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
660
+ // Enumerate devices for sender and target with consistent addressing
661
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
662
+ devices.push(...sessionDevices);
663
+ logger.debug({
664
+ deviceCount: devices.length,
665
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
666
+ }, 'Device enumeration complete with unified addressing');
667
+ }
668
+ }
669
+ const allRecipients = [];
670
+ const meRecipients = [];
671
+ const otherRecipients = [];
672
+ const { user: mePnUser } = jidDecode(meId);
673
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
674
+ for (const { user, jid } of devices) {
675
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
676
+ if (isExactSenderDevice) {
677
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
678
+ continue;
679
+ }
680
+ // Check if this is our device (could match either PN or LID user)
681
+ const isMe = user === mePnUser || user === meLidUser;
682
+ if (isMe) {
683
+ meRecipients.push(jid);
684
+ }
685
+ else {
686
+ otherRecipients.push(jid);
687
+ }
688
+ allRecipients.push(jid);
689
+ }
690
+ await assertSessions(allRecipients);
691
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
692
+ // For own devices: use DSM if available (1:1 chats only)
693
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
694
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
695
+ ]);
696
+ participants.push(...meNodes);
697
+ participants.push(...otherNodes);
698
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
699
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
700
+ }
701
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
702
+ }
703
+ if (isRetryResend) {
704
+ const isParticipantLid = isLidUser(participant.jid);
705
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
706
+ const encodedMessageToSend = isMe
707
+ ? encodeWAMessage({
708
+ deviceSentMessage: {
709
+ destinationJid,
710
+ message
711
+ }
712
+ })
713
+ : encodeWAMessage(message);
714
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
715
+ data: encodedMessageToSend,
716
+ jid: participant.jid
717
+ });
718
+ binaryNodeContent.push({
719
+ tag: 'enc',
720
+ attrs: {
721
+ v: '2',
722
+ type,
723
+ count: participant.count?.toString() || '0'
724
+ },
725
+ content: encryptedContent
726
+ });
727
+ }
728
+ if (participants.length) {
729
+ if (additionalAttributes?.['category'] === 'peer') {
730
+ const peerNode = participants[0]?.content?.[0];
731
+ if (peerNode) {
732
+ binaryNodeContent.push(peerNode); // push only enc
733
+ }
734
+ }
735
+ else {
736
+ binaryNodeContent.push({
737
+ tag: 'participants',
738
+ attrs: {},
739
+ content: participants
740
+ });
741
+ }
742
+ }
743
+ const stanza = {
744
+ tag: 'message',
745
+ attrs: {
746
+ id: msgId,
747
+ to: destinationJid,
748
+ type: getMessageType(innerMessage),
749
+ ...(additionalAttributes || {})
750
+ },
751
+ content: binaryNodeContent
752
+ };
753
+ // if the participant to send to is explicitly specified (generally retry recp)
754
+ // ensure the message is only sent to that person
755
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
756
+ if (participant) {
757
+ if (isJidGroup(destinationJid)) {
758
+ stanza.attrs.to = destinationJid;
759
+ stanza.attrs.participant = participant.jid;
760
+ }
761
+ else if (areJidsSameUser(participant.jid, meId)) {
762
+ stanza.attrs.to = participant.jid;
763
+ stanza.attrs.recipient = destinationJid;
764
+ }
765
+ else {
766
+ stanza.attrs.to = participant.jid;
767
+ }
768
+ }
769
+ else {
770
+ stanza.attrs.to = destinationJid;
771
+ }
772
+ if (shouldIncludeDeviceIdentity) {
773
+ ;
774
+ stanza.content.push({
775
+ tag: 'device-identity',
776
+ attrs: {},
777
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
778
+ });
779
+ logger.debug({ jid }, 'adding device identity');
780
+ }
781
+ if (!isNewsletter &&
782
+ !isRetryResend &&
783
+ reportingMessage?.messageContextInfo?.messageSecret &&
784
+ shouldIncludeReportingToken(reportingMessage)) {
785
+ try {
786
+ const encoded = encodeWAMessage(reportingMessage);
787
+ const reportingKey = {
788
+ id: msgId,
789
+ fromMe: true,
790
+ remoteJid: destinationJid,
791
+ participant: participant?.jid
792
+ };
793
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
794
+ if (reportingNode) {
795
+ ;
796
+ stanza.content.push(reportingNode);
797
+ logger.trace({ jid }, 'added reporting token to message');
798
+ }
799
+ }
800
+ catch (error) {
801
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
802
+ }
803
+ }
804
+ const contactTcTokenData = !isGroup && !isRetryResend && !isStatus ? await authState.keys.get('tctoken', [destinationJid]) : {};
805
+ const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
806
+ if (tcTokenBuffer) {
807
+ ;
808
+ stanza.content.push({
809
+ tag: 'tctoken',
810
+ attrs: {},
811
+ content: tcTokenBuffer
812
+ });
813
+ }
814
+ let alreadyHasBizNode = false;
815
+ if (additionalNodes && additionalNodes.length > 0) {
816
+ ;
817
+ stanza.content.push(...additionalNodes);
818
+ alreadyHasBizNode = !addBizAttributes &&
819
+ additionalNodes.some(node => node.tag === 'biz');
820
+ }
821
+ // Lia@Changes 30-01-26 --- Add Biz Binary Node to support button messages
822
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
823
+ const bizNode = getBizBinaryNode(innerMessage, addBizAttributes);
824
+ stanza.content.push(bizNode);
825
+ }
826
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
827
+ await sendNode(stanza);
828
+ // Add message to retry cache if enabled
829
+ if (messageRetryManager && !participant) {
830
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
831
+ }
832
+ }, meId);
833
+ return msgId;
834
+ };
835
+ const getMessageType = (message) => {
836
+ if (!message)
837
+ return 'text';
838
+ if (message.reactionMessage || message.encReactionMessage) {
839
+ return 'reaction';
840
+ }
841
+ if (message.pollCreationMessage ||
842
+ message.pollCreationMessageV2 ||
843
+ message.pollCreationMessageV3 ||
844
+ message.pollCreationMessageV5 ||
845
+ message.pollCreationMessageV6 ||
846
+ message.pollUpdateMessage) {
847
+ return 'poll';
848
+ }
849
+ if (message.eventMessage) {
850
+ return 'event';
851
+ }
852
+ if (getMediaType(message) !== '') {
853
+ return 'media';
854
+ }
855
+ return 'text';
856
+ };
857
+ const getMediaType = (message) => {
858
+ if (message.imageMessage) {
859
+ return 'image';
860
+ }
861
+ else if (message.videoMessage) {
862
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
863
+ }
864
+ else if (message.stickerMessage) {
865
+ return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
866
+ }
867
+ else if (message.audioMessage) {
868
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
869
+ }
870
+ else if (message.albumMessage) {
871
+ return 'collection';
872
+ }
873
+ else if (message.contactMessage) {
874
+ return 'vcard';
875
+ }
876
+ else if (message.documentMessage) {
877
+ return 'document';
878
+ }
879
+ else if (message.contactsArrayMessage) {
880
+ return 'contact_array';
881
+ }
882
+ else if (message.liveLocationMessage) {
883
+ return 'livelocation';
884
+ }
885
+ else if (message.stickerPackMessage) {
886
+ return 'sticker_pack';
887
+ }
888
+ else if (message.listMessage) {
889
+ return 'list';
890
+ }
891
+ else if (message.listResponseMessage) {
892
+ return 'list_response';
893
+ }
894
+ else if (message.buttonsResponseMessage) {
895
+ return 'buttons_response';
896
+ }
897
+ else if (message.orderMessage) {
898
+ return 'order';
899
+ }
900
+ else if (message.productMessage) {
901
+ return 'product';
902
+ }
903
+ else if (message.interactiveResponseMessage) {
904
+ return 'native_flow_response';
905
+ }
906
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
907
+ return 'url';
908
+ }
909
+ // Lia@Note 02-02-26 --- Add more message type here
910
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
911
+ return 'cataloglink';
912
+ }
913
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
914
+ return 'productlink';
915
+ }
916
+ return ''
917
+ };
918
+ const getPrivacyTokens = async (jids) => {
919
+ const t = unixTimestampSeconds().toString();
920
+ const result = await query({
921
+ tag: 'iq',
922
+ attrs: {
923
+ to: S_WHATSAPP_NET,
924
+ type: 'set',
925
+ xmlns: 'privacy'
926
+ },
927
+ content: [
928
+ {
929
+ tag: 'tokens',
930
+ attrs: {},
931
+ content: jids.map(jid => ({
932
+ tag: 'token',
933
+ attrs: {
934
+ jid: jidNormalizedUser(jid),
935
+ t,
936
+ type: 'trusted_contact'
937
+ }
938
+ }))
939
+ }
940
+ ]
941
+ });
942
+ return result;
943
+ };
944
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
945
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
946
+ registerSocketEndHandler(() => {
947
+ if (!config.userDevicesCache && userDevicesCache.close) {
948
+ userDevicesCache.close();
949
+ }
950
+ if (peerSessionsCache.close) {
951
+ peerSessionsCache.close();
952
+ }
953
+ mediaConn = undefined;
954
+ if (messageRetryManager) {
955
+ messageRetryManager.clear();
956
+ }
957
+ });
958
+ return {
959
+ ...sock,
960
+ getPrivacyTokens,
961
+ assertSessions,
962
+ relayMessage,
963
+ sendReceipt,
964
+ sendReceipts,
965
+ readMessages,
966
+ refreshMediaConn,
967
+ waUploadToServer,
968
+ fetchPrivacySettings,
969
+ sendPeerDataOperationMessage,
970
+ createParticipantNodes,
971
+ getUSyncDevices,
972
+ messageRetryManager,
973
+ updateMemberLabel,
974
+ updateMediaMessage: async (message) => {
975
+ const content = assertMediaContent(message.message);
976
+ const mediaKey = content.mediaKey;
977
+ const meId = authState.creds.me.id;
978
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
979
+ let error = undefined;
980
+ await Promise.all([
981
+ sendNode(node),
982
+ waitForMsgMediaUpdate(async (update) => {
983
+ const result = update.find(c => c.key.id === message.key.id);
984
+ if (result) {
985
+ if (result.error) {
986
+ error = result.error;
987
+ }
988
+ else {
989
+ try {
990
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
991
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
992
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
993
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
994
+ data: media,
995
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
996
+ });
997
+ }
998
+ content.directPath = media.directPath;
999
+ content.url = getUrlFromDirectPath(content.directPath);
1000
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1001
+ }
1002
+ catch (err) {
1003
+ error = err;
1004
+ }
1005
+ }
1006
+ return true;
1007
+ }
1008
+ })
1009
+ ]);
1010
+ if (error) {
1011
+ throw error;
1012
+ }
1013
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1014
+ return message;
1015
+ },
1016
+ // Lia@Changes 30-01-26 --- Add support for modifying additionalNodes and additionalAttributes using "options" in sendMessage()
1017
+ sendMessage: async (jid, content, options = {}) => {
1018
+ const userJid = authState.creds.me.id;
1019
+ // Lia@Changes 13-03-26 --- Add status mentions!
1020
+ if (Array.isArray(jid)) {
1021
+ const { delayMs = 1500 } = options;
1022
+ const allUsers = new Set();
1023
+ const fullMsg = await generateWAMessage('status@broadcast', content, {
1024
+ logger,
1025
+ userJid,
1026
+ upload: waUploadToServer,
1027
+ mediaCache: config.mediaCache,
1028
+ options: config.options,
1029
+ ...options,
1030
+ messageId: generateMessageIDV2(userJid)
1031
+ });
1032
+ for (const id of jid) {
1033
+ if (isJidGroup(id)) {
1034
+ try {
1035
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1036
+ for (const participant of groupData.participants) {
1037
+ if (allUsers.has(participant.id))
1038
+ continue;
1039
+ allUsers.add(participant.id);
1040
+ }
1041
+ }
1042
+ catch (error) {
1043
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
1044
+ }
1045
+ }
1046
+ else if (!allUsers.has(id)) {
1047
+ allUsers.add(id);
1048
+ }
1049
+ }
1050
+ await relayMessage('status@broadcast', fullMsg.message, {
1051
+ messageId: fullMsg.key.id,
1052
+ statusJidList: Array.from(allUsers),
1053
+ additionalNodes: [
1054
+ {
1055
+ tag: 'meta',
1056
+ attrs: {},
1057
+ content: [
1058
+ {
1059
+ tag: 'mentioned_users',
1060
+ attrs: {},
1061
+ content: jid.map(id => ({
1062
+ tag: 'to',
1063
+ attrs: { jid: id },
1064
+ content: undefined
1065
+ }))
1066
+ }
1067
+ ]
1068
+ }
1069
+ ]
1070
+ });
1071
+ if (config.emitOwnEvents) {
1072
+ process.nextTick(async () => {
1073
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1074
+ });
1075
+ }
1076
+ for (const id of jid) {
1077
+ const isGroup = isJidGroup(id)
1078
+ const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1079
+ const mentionMsg = generateWAMessageFromContent(id, {
1080
+ messageContextInfo: {
1081
+ messageSecret: randomBytes(32)
1082
+ },
1083
+ [sendType]: {
1084
+ message: {
1085
+ protocolMessage: {
1086
+ key: fullMsg.key,
1087
+ type: 25
1088
+ }
1089
+ }
1090
+ }
1091
+ }, {
1092
+ userJid
1093
+ });
1094
+ await relayMessage(id, mentionMsg.message, {
1095
+ additionalNodes: [
1096
+ {
1097
+ tag: 'meta',
1098
+ attrs: isGroup ?
1099
+ { is_group_status_mention: 'true' } :
1100
+ { is_status_mention: 'true' },
1101
+ content: undefined
1102
+ }
1103
+ ]
1104
+ });
1105
+ if (config.emitOwnEvents) {
1106
+ process.nextTick(async () => {
1107
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1108
+ });
1109
+ }
1110
+ await delay(delayMs);
1111
+ }
1112
+ return fullMsg;
1113
+ }
1114
+ else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1115
+ const { disappearingMessagesInChat } = content;
1116
+ const value = typeof disappearingMessagesInChat === 'boolean'
1117
+ ? disappearingMessagesInChat
1118
+ ? WA_DEFAULT_EPHEMERAL
1119
+ : 0
1120
+ : disappearingMessagesInChat;
1121
+ await groupToggleEphemeral(jid, value);
1122
+ }
1123
+ else {
1124
+ const fullMsg = await generateWAMessage(jid, content, {
1125
+ logger,
1126
+ userJid,
1127
+ getUrlInfo: text => getUrlInfo(text, {
1128
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1129
+ fetchOpts: {
1130
+ timeout: 3000,
1131
+ ...(httpRequestOptions || {})
1132
+ },
1133
+ logger,
1134
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1135
+ }),
1136
+ //TODO: CACHE
1137
+ getProfilePicUrl: sock.profilePictureUrl,
1138
+ getCallLink: sock.createCallLink,
1139
+ upload: waUploadToServer,
1140
+ mediaCache: config.mediaCache,
1141
+ options: config.options,
1142
+ ...options,
1143
+ messageId: generateMessageIDV2(userJid)
1144
+ });
1145
+ const isNewsletter = isJidNewsletter(jid);
1146
+ const isEventMsg = 'event' in content && !!content.event;
1147
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1148
+ const isEditMsg = 'edit' in content && !!content.edit;
1149
+ const isPinMsg = 'pin' in content && !!content.pin;
1150
+ const isKeepMsg = 'keep' in content && !!content.keep;
1151
+ const isPollMsg = 'poll' in content && !!content.poll;
1152
+ const isQuizMsg = 'poll' in content && !!content.poll.pollType;
1153
+ const isAiMsg = 'ai' in content && !!content.ai;
1154
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
1155
+ const additionalAttributes = options.additionalAttributes || {};
1156
+ const additionalNodes = options.additionalNodes || [];
1157
+ // required for delete
1158
+ if (isDeleteMsg || isKeepMsg) {
1159
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1160
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1161
+ additionalAttributes.edit = '8';
1162
+ }
1163
+ else {
1164
+ additionalAttributes.edit = '7';
1165
+ }
1166
+ }
1167
+ else if (isEditMsg) {
1168
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
1169
+ }
1170
+ else if (isPinMsg) {
1171
+ additionalAttributes.edit = '2';
1172
+ }
1173
+ else if (isPollMsg) {
1174
+ if (!isNewsletter && isQuizMsg) {
1175
+ throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
1176
+ }
1177
+ additionalNodes.push({
1178
+ tag: 'meta',
1179
+ attrs: {
1180
+ // Lia@Note 08-02-26 --- Still a hypothesis regarding PollResult ༎ຶ⁠‿⁠༎ຶ
1181
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
1182
+ contenttype: isPollMsg && isNewsletter ? 'text' : undefined
1183
+ },
1184
+ content: undefined
1185
+ });
1186
+ }
1187
+ else if (isEventMsg) {
1188
+ additionalNodes.push({
1189
+ tag: 'meta',
1190
+ attrs: {
1191
+ event_type: 'creation'
1192
+ },
1193
+ content: undefined
1194
+ });
1195
+ }
1196
+ // Lia@Changes 30-01-26 --- Add support for AI label in message when "ai" is true, but works only in private chat
1197
+ else if (isAiMsg) {
1198
+ if (!(isPnUser(jid) || isLidUser(jid))) {
1199
+ throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
1200
+ }
1201
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1202
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1203
+ };
1204
+ additionalNodes.push({
1205
+ tag: 'bot',
1206
+ attrs: {
1207
+ biz_bot: '1'
1208
+ },
1209
+ content: undefined
1210
+ });
1211
+ delete content.ai;
1212
+ }
1213
+ await relayMessage(jid, fullMsg.message, {
1214
+ messageId: fullMsg.key.id,
1215
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1216
+ addBizAttributes: isNeedBizAttrs,
1217
+ statusJidList: options.statusJidList,
1218
+ additionalAttributes,
1219
+ additionalNodes
1220
+ });
1221
+ if (config.emitOwnEvents) {
1222
+ process.nextTick(async () => {
1223
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1224
+ });
1225
+ }
1226
+ // Lia@Changes 31-01-26 --- Add support for album messages
1227
+ // Lia@Note 06-02-26 --- Refactored to reduce high RSS usage (⁠╥⁠﹏⁠╥⁠)
1228
+ if ('album' in content) {
1229
+ const { delayMs = 1500 } = options;
1230
+ for (const albumMedia of content.album) {
1231
+ const albumMsg = await generateWAMessage(jid, albumMedia, {
1232
+ logger,
1233
+ userJid,
1234
+ upload: waUploadToServer,
1235
+ mediaCache: config.mediaCache,
1236
+ options: config.options,
1237
+ ...options,
1238
+ messageId: generateMessageIDV2(userJid)
1239
+ });
1240
+ if (!hasValidAlbumMedia(normalizeMessageContent(albumMsg.message))) {
1241
+ throw new Boom('Invalid message type for album', { statusCode: 400 });
1242
+ }
1243
+ albumMsg.message.messageContextInfo ||= {};
1244
+ albumMsg.message.messageContextInfo.messageAssociation = {
1245
+ parentMessageKey: fullMsg.key,
1246
+ associationType: AssociationType.MEDIA_ALBUM
1247
+ };
1248
+ await relayMessage(jid, albumMsg.message, {
1249
+ messageId: albumMsg.key.id,
1250
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1251
+ addBizAttributes: isNeedBizAttrs,
1252
+ statusJidList: options.statusJidList,
1253
+ additionalAttributes,
1254
+ additionalNodes
1255
+ });
1256
+ if (config.emitOwnEvents) {
1257
+ process.nextTick(async () => {
1258
+ await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
1259
+ });
1260
+ }
1261
+ await delay(delayMs);
1262
+ }
1263
+ }
1264
+ return fullMsg;
1265
+ }
1266
+ }
1267
+ };
1268
+ };