fixo-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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +431 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97691 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.js +129 -0
  10. package/lib/Signal/Group/ciphertext-message.js +12 -0
  11. package/lib/Signal/Group/group-session-builder.js +30 -0
  12. package/lib/Signal/Group/group_cipher.js +82 -0
  13. package/lib/Signal/Group/index.js +12 -0
  14. package/lib/Signal/Group/keyhelper.js +18 -0
  15. package/lib/Signal/Group/sender-chain-key.js +26 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  17. package/lib/Signal/Group/sender-key-message.js +66 -0
  18. package/lib/Signal/Group/sender-key-name.js +48 -0
  19. package/lib/Signal/Group/sender-key-record.js +41 -0
  20. package/lib/Signal/Group/sender-key-state.js +84 -0
  21. package/lib/Signal/Group/sender-message-key.js +26 -0
  22. package/lib/Signal/libsignal.js +431 -0
  23. package/lib/Signal/lid-mapping.js +277 -0
  24. package/lib/Socket/Client/index.js +3 -0
  25. package/lib/Socket/Client/types.js +11 -0
  26. package/lib/Socket/Client/websocket.js +54 -0
  27. package/lib/Socket/business.js +379 -0
  28. package/lib/Socket/chats.js +1198 -0
  29. package/lib/Socket/communities.js +431 -0
  30. package/lib/Socket/groups.js +347 -0
  31. package/lib/Socket/index.js +12 -0
  32. package/lib/Socket/messages-recv.js +1772 -0
  33. package/lib/Socket/messages-send.js +1408 -0
  34. package/lib/Socket/mex.js +42 -0
  35. package/lib/Socket/newsletter.js +419 -0
  36. package/lib/Socket/socket.js +999 -0
  37. package/lib/Types/Auth.js +2 -0
  38. package/lib/Types/Bussines.js +2 -0
  39. package/lib/Types/Call.js +2 -0
  40. package/lib/Types/Chat.js +8 -0
  41. package/lib/Types/Contact.js +2 -0
  42. package/lib/Types/Events.js +2 -0
  43. package/lib/Types/GroupMetadata.js +2 -0
  44. package/lib/Types/Label.js +25 -0
  45. package/lib/Types/LabelAssociation.js +7 -0
  46. package/lib/Types/Message.js +11 -0
  47. package/lib/Types/Mex.js +37 -0
  48. package/lib/Types/Product.js +2 -0
  49. package/lib/Types/Signal.js +2 -0
  50. package/lib/Types/Socket.js +3 -0
  51. package/lib/Types/State.js +56 -0
  52. package/lib/Types/USync.js +2 -0
  53. package/lib/Types/index.js +26 -0
  54. package/lib/Types/temp +1 -0
  55. package/lib/Utils/auth-utils.js +302 -0
  56. package/lib/Utils/browser-utils.js +29 -0
  57. package/lib/Utils/business.js +231 -0
  58. package/lib/Utils/chat-utils.js +872 -0
  59. package/lib/Utils/companion-reg-client-utils.js +35 -0
  60. package/lib/Utils/crypto.js +118 -0
  61. package/lib/Utils/decode-wa-message.js +317 -0
  62. package/lib/Utils/event-buffer.js +622 -0
  63. package/lib/Utils/generics.js +393 -0
  64. package/lib/Utils/history.js +134 -0
  65. package/lib/Utils/identity-change-handler.js +50 -0
  66. package/lib/Utils/index.js +22 -0
  67. package/lib/Utils/link-preview.js +85 -0
  68. package/lib/Utils/logger.js +3 -0
  69. package/lib/Utils/lt-hash.js +8 -0
  70. package/lib/Utils/make-mutex.js +33 -0
  71. package/lib/Utils/message-retry-manager.js +265 -0
  72. package/lib/Utils/messages-media.js +795 -0
  73. package/lib/Utils/messages.js +1056 -0
  74. package/lib/Utils/noise-handler.js +201 -0
  75. package/lib/Utils/offline-node-processor.js +40 -0
  76. package/lib/Utils/pre-key-manager.js +106 -0
  77. package/lib/Utils/process-message.js +630 -0
  78. package/lib/Utils/reporting-utils.js +258 -0
  79. package/lib/Utils/signal.js +201 -0
  80. package/lib/Utils/stanza-ack.js +38 -0
  81. package/lib/Utils/sync-action-utils.js +49 -0
  82. package/lib/Utils/tc-token-utils.js +164 -0
  83. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  84. package/lib/Utils/validate-connection.js +210 -0
  85. package/lib/WABinary/constants.js +1301 -0
  86. package/lib/WABinary/decode.js +262 -0
  87. package/lib/WABinary/encode.js +220 -0
  88. package/lib/WABinary/generic-utils.js +113 -0
  89. package/lib/WABinary/index.js +6 -0
  90. package/lib/WABinary/jid-utils.js +96 -0
  91. package/lib/WABinary/types.js +2 -0
  92. package/lib/WAM/BinaryInfo.js +10 -0
  93. package/lib/WAM/constants.js +22853 -0
  94. package/lib/WAM/encode.js +150 -0
  95. package/lib/WAM/index.js +4 -0
  96. package/lib/WAM/temp +1 -0
  97. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  98. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  99. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  100. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  101. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  102. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  103. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  104. package/lib/WAUSync/Protocols/index.js +6 -0
  105. package/lib/WAUSync/USyncQuery.js +98 -0
  106. package/lib/WAUSync/USyncUser.js +31 -0
  107. package/lib/WAUSync/index.js +4 -0
  108. package/lib/index.js +11 -0
  109. package/package.json +79 -0
@@ -0,0 +1,1408 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
+ import {
6
+ aggregateMessageKeysNotFromMe,
7
+ assertMediaContent,
8
+ assertMeId,
9
+ bindWaitForEvent,
10
+ decryptMediaRetryData,
11
+ DEF_MEDIA_HOST,
12
+ encodeNewsletterMessage,
13
+ encodeSignedDeviceIdentity,
14
+ encodeWAMessage,
15
+ encryptMediaRetryRequest,
16
+ extractDeviceJids,
17
+ generateMessageIDV2,
18
+ generateParticipantHashV2,
19
+ generateWAMessage,
20
+ getStatusCodeForMediaRetry,
21
+ getUrlFromDirectPath,
22
+ getWAUploadToServer,
23
+ MessageRetryManager,
24
+ normalizeMessageContent,
25
+ parseAndInjectE2ESessions,
26
+ prepareWAMessageMedia,
27
+ unixTimestampSeconds
28
+ } from '../Utils/index.js';
29
+ import { getUrlInfo } from '../Utils/link-preview.js';
30
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
31
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
32
+ import {
33
+ buildMergedTcTokenIndexWrite,
34
+ isTcTokenExpired,
35
+ resolveIssuanceJid,
36
+ resolveTcTokenJid,
37
+ shouldSendNewTcToken,
38
+ storeTcTokensFromIqResult
39
+ } from '../Utils/tc-token-utils.js';
40
+ import {
41
+ areJidsSameUser,
42
+ getBinaryNodeChild,
43
+ getBinaryNodeChildren,
44
+ isHostedLidUser,
45
+ isHostedPnUser,
46
+ isJidBot,
47
+ isJidGroup,
48
+ isJidMetaAI,
49
+ isLidUser,
50
+ isPnUser,
51
+ jidDecode,
52
+ jidEncode,
53
+ jidNormalizedUser,
54
+ PSA_WID,
55
+ S_WHATSAPP_NET
56
+ } from '../WABinary/index.js';
57
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
58
+ import { makeNewsletterSocket } from './newsletter.js';
59
+
60
+ export const makeMessagesSocket = (config) => {
61
+ const {
62
+ logger,
63
+ linkPreviewImageThumbnailWidth,
64
+ generateHighQualityLinkPreview,
65
+ options: httpRequestOptions,
66
+ patchMessageBeforeSending,
67
+ cachedGroupMetadata,
68
+ enableRecentMessageCache,
69
+ maxMsgRetryCount
70
+ } = config;
71
+
72
+ const sock = makeNewsletterSocket(config);
73
+ const {
74
+ ev,
75
+ authState,
76
+ messageMutex,
77
+ signalRepository,
78
+ upsertMessage,
79
+ query,
80
+ fetchPrivacySettings,
81
+ sendNode,
82
+ groupMetadata,
83
+ groupToggleEphemeral,
84
+ registerSocketEndHandler
85
+ } = sock;
86
+
87
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
88
+
89
+ const inFlightTcTokenIssuance = new Set();
90
+
91
+ const userDevicesCache =
92
+ config.userDevicesCache ||
93
+ new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, useClones: false });
94
+
95
+ const devicesMutex = makeMutex();
96
+
97
+ const messageRetryManager = enableRecentMessageCache
98
+ ? new MessageRetryManager(logger, maxMsgRetryCount)
99
+ : null;
100
+
101
+ const encryptionMutex = makeKeyedMutex();
102
+
103
+ let mediaConn;
104
+ let mediaHost = DEF_MEDIA_HOST;
105
+
106
+ const refreshMediaConn = async (forceGet = false) => {
107
+ const media = await mediaConn;
108
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
109
+ mediaConn = (async () => {
110
+ const result = await query({
111
+ tag: 'iq',
112
+ attrs: { type: 'set', xmlns: 'w:m', to: S_WHATSAPP_NET },
113
+ content: [{ tag: 'media_conn', attrs: {} }]
114
+ });
115
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
116
+ const node = {
117
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
118
+ hostname: attrs.hostname,
119
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
120
+ })),
121
+ auth: mediaConnNode.attrs.auth,
122
+ ttl: +mediaConnNode.attrs.ttl,
123
+ fetchDate: new Date()
124
+ };
125
+ logger.debug('fetched media conn');
126
+ if (node.hosts[0]) {
127
+ mediaHost = node.hosts[0].hostname;
128
+ }
129
+ return node;
130
+ })();
131
+ }
132
+ return mediaConn;
133
+ };
134
+
135
+ const sendReceipt = async (jid, participant, messageIds, type) => {
136
+ if (!messageIds || messageIds.length === 0) {
137
+ throw new Boom('missing ids in receipt');
138
+ }
139
+ const node = {
140
+ tag: 'receipt',
141
+ attrs: { id: messageIds[0] }
142
+ };
143
+ const isReadReceipt = type === 'read' || type === 'read-self';
144
+ if (isReadReceipt) {
145
+ node.attrs.t = unixTimestampSeconds().toString();
146
+ }
147
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
148
+ node.attrs.recipient = jid;
149
+ node.attrs.to = participant;
150
+ } else {
151
+ node.attrs.to = jid;
152
+ if (participant) node.attrs.participant = participant;
153
+ }
154
+ if (type) node.attrs.type = type;
155
+ const remainingMessageIds = messageIds.slice(1);
156
+ if (remainingMessageIds.length) {
157
+ node.content = [
158
+ {
159
+ tag: 'list',
160
+ attrs: {},
161
+ content: remainingMessageIds.map((id) => ({ tag: 'item', attrs: { id } }))
162
+ }
163
+ ];
164
+ }
165
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
166
+ await sendNode(node);
167
+ };
168
+
169
+ const sendReceipts = async (keys, type) => {
170
+ const recps = aggregateMessageKeysNotFromMe(keys);
171
+ for (const { jid, participant, messageIds } of recps) {
172
+ await sendReceipt(jid, participant, messageIds, type);
173
+ }
174
+ };
175
+
176
+ const readMessages = async (keys) => {
177
+ const privacySettings = await fetchPrivacySettings();
178
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
179
+ await sendReceipts(keys, readType);
180
+ };
181
+
182
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
183
+ const deviceResults = [];
184
+ if (!useCache) logger.debug('not using cache for devices');
185
+
186
+ const toFetch = [];
187
+ const jidsWithUser = jids
188
+ .map((jid) => {
189
+ const decoded = jidDecode(jid);
190
+ const user = decoded?.user;
191
+ const device = decoded?.device;
192
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
193
+ if (isExplicitDevice && user) {
194
+ deviceResults.push({ user, device, jid });
195
+ return null;
196
+ }
197
+ jid = jidNormalizedUser(jid);
198
+ return { jid, user };
199
+ })
200
+ .filter((jid) => jid !== null);
201
+
202
+ let mgetDevices;
203
+ if (useCache && userDevicesCache.mget) {
204
+ const usersToFetch = jidsWithUser.map((j) => j?.user).filter(Boolean);
205
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
206
+ }
207
+
208
+ for (const { jid, user } of jidsWithUser) {
209
+ if (useCache) {
210
+ const devices =
211
+ mgetDevices?.[user] ||
212
+ (userDevicesCache.mget ? undefined : await userDevicesCache.get(user));
213
+ if (devices) {
214
+ const devicesWithJid = devices.map((d) => ({
215
+ ...d,
216
+ jid: jidEncode(d.user, d.server, d.device)
217
+ }));
218
+ deviceResults.push(...devicesWithJid);
219
+ logger.trace({ user }, 'using cache for devices');
220
+ } else {
221
+ toFetch.push(jid);
222
+ }
223
+ } else {
224
+ toFetch.push(jid);
225
+ }
226
+ }
227
+
228
+ if (!toFetch.length) return deviceResults;
229
+
230
+ const requestedLidUsers = new Set();
231
+ for (const jid of toFetch) {
232
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
233
+ const user = jidDecode(jid)?.user;
234
+ if (user) requestedLidUsers.add(user);
235
+ }
236
+ }
237
+
238
+ const uSyncQuery = new USyncQuery()
239
+ .withContext('message')
240
+ .withDeviceProtocol()
241
+ .withLIDProtocol();
242
+ for (const jid of toFetch) uSyncQuery.withUser(new USyncUser().withId(jid));
243
+
244
+ const result = await sock.executeUSyncQuery(uSyncQuery);
245
+ if (result) {
246
+ const lidResults = result.list.filter((a) => !!a.lid);
247
+ if (lidResults.length > 0) {
248
+ logger.trace('Storing LID maps from device call');
249
+ await signalRepository.lidMapping.storeLIDPNMappings(
250
+ lidResults.map((a) => ({ lid: a.lid, pn: a.id }))
251
+ );
252
+ try {
253
+ const lids = lidResults.map((a) => a.lid);
254
+ if (lids.length) await assertSessions(lids, true);
255
+ } catch (e) {
256
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
257
+ }
258
+ }
259
+
260
+ const extracted = extractDeviceJids(
261
+ result?.list,
262
+ authState.creds.me.id,
263
+ authState.creds.me.lid,
264
+ ignoreZeroDevices
265
+ );
266
+ const deviceMap = {};
267
+ for (const item of extracted) {
268
+ deviceMap[item.user] = deviceMap[item.user] || [];
269
+ deviceMap[item.user]?.push(item);
270
+ }
271
+
272
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
273
+ const isLidUsr = requestedLidUsers.has(user);
274
+ for (const item of userDevices) {
275
+ const finalJid = isLidUsr
276
+ ? jidEncode(user, item.server, item.device)
277
+ : jidEncode(item.user, item.server, item.device);
278
+ deviceResults.push({ ...item, jid: finalJid });
279
+ logger.debug(
280
+ { user: item.user, device: item.device, finalJid, usedLid: isLidUsr },
281
+ 'Processed device with LID priority'
282
+ );
283
+ }
284
+ }
285
+
286
+ await devicesMutex.mutex(async () => {
287
+ if (userDevicesCache.mset) {
288
+ await userDevicesCache.mset(
289
+ Object.entries(deviceMap).map(([key, value]) => ({ key, value }))
290
+ );
291
+ } else {
292
+ for (const key in deviceMap) {
293
+ if (deviceMap[key]) await userDevicesCache.set(key, deviceMap[key]);
294
+ }
295
+ }
296
+ });
297
+
298
+ const userDeviceUpdates = {};
299
+ for (const [userId, devices] of Object.entries(deviceMap)) {
300
+ if (devices && devices.length > 0) {
301
+ userDeviceUpdates[userId] = devices.map((d) => d.device?.toString() || '0');
302
+ }
303
+ }
304
+ if (Object.keys(userDeviceUpdates).length > 0) {
305
+ try {
306
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
307
+ logger.debug(
308
+ { userCount: Object.keys(userDeviceUpdates).length },
309
+ 'stored user device lists for bulk migration'
310
+ );
311
+ } catch (error) {
312
+ logger.warn({ error }, 'failed to store user device lists');
313
+ }
314
+ }
315
+ }
316
+
317
+ return deviceResults;
318
+ };
319
+
320
+ const updateMemberLabel = (jid, memberLabel) => {
321
+ return relayMessage(
322
+ jid,
323
+ {
324
+ protocolMessage: {
325
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
326
+ memberLabel: {
327
+ label: memberLabel?.slice(0, 30),
328
+ labelTimestamp: unixTimestampSeconds()
329
+ }
330
+ }
331
+ },
332
+ {
333
+ additionalNodes: [
334
+ {
335
+ tag: 'meta',
336
+ attrs: { tag_reason: 'user_update', appdata: 'member_tag' },
337
+ content: undefined
338
+ }
339
+ ]
340
+ }
341
+ );
342
+ };
343
+
344
+ const assertSessions = async (jids, force) => {
345
+ let didFetchNewSession = false;
346
+ const uniqueJids = [...new Set(jids)];
347
+ const jidsRequiringFetch = [];
348
+ logger.debug({ jids }, 'assertSessions call with jids');
349
+
350
+ for (const jid of uniqueJids) {
351
+ if (!force) {
352
+ const sessionValidation = await signalRepository.validateSession(jid);
353
+ if (sessionValidation.exists) continue;
354
+ }
355
+ jidsRequiringFetch.push(jid);
356
+ }
357
+
358
+ if (jidsRequiringFetch.length) {
359
+ const wireJids = [
360
+ ...jidsRequiringFetch.filter((jid) => !!isLidUser(jid) || !!isHostedLidUser(jid)),
361
+ ...((await signalRepository.lidMapping.getLIDsForPNs(
362
+ jidsRequiringFetch.filter((jid) => !!isPnUser(jid) || !!isHostedPnUser(jid))
363
+ )) || []).map((a) => a.lid)
364
+ ];
365
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
366
+ const result = await query({
367
+ tag: 'iq',
368
+ attrs: { xmlns: 'encrypt', type: 'get', to: S_WHATSAPP_NET },
369
+ content: [
370
+ {
371
+ tag: 'key',
372
+ attrs: {},
373
+ content: wireJids.map((jid) => {
374
+ const attrs = { jid };
375
+ if (force) attrs.reason = 'identity';
376
+ return { tag: 'user', attrs };
377
+ })
378
+ }
379
+ ]
380
+ });
381
+ await parseAndInjectE2ESessions(result, signalRepository);
382
+ didFetchNewSession = true;
383
+ }
384
+
385
+ return didFetchNewSession;
386
+ };
387
+
388
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
389
+ if (!authState.creds.me?.id) throw new Boom('Not authenticated');
390
+ const protocolMessage = {
391
+ protocolMessage: {
392
+ peerDataOperationRequestMessage: pdoMessage,
393
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
394
+ }
395
+ };
396
+ const meJid = jidNormalizedUser(authState.creds.me.id);
397
+ const msgId = await relayMessage(meJid, protocolMessage, {
398
+ additionalAttributes: { category: 'peer', push_priority: 'high_force' },
399
+ additionalNodes: [{ tag: 'meta', attrs: { appdata: 'default' } }]
400
+ });
401
+ return msgId;
402
+ };
403
+
404
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
405
+ if (!recipientJids.length) {
406
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
407
+ }
408
+ const patched = await patchMessageBeforeSending(message, recipientJids);
409
+ const patchedMessages = Array.isArray(patched)
410
+ ? patched
411
+ : recipientJids.map((jid) => ({ recipientJid: jid, message: patched }));
412
+
413
+ let shouldIncludeDeviceIdentity = false;
414
+ const meId = authState.creds.me.id;
415
+ const meLid = authState.creds.me?.lid;
416
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
417
+
418
+ const encryptionPromises = patchedMessages.map(
419
+ async ({ recipientJid: jid, message: patchedMessage }) => {
420
+ try {
421
+ if (!jid) return null;
422
+ let msgToEncrypt = patchedMessage;
423
+ if (dsmMessage) {
424
+ const { user: targetUser } = jidDecode(jid);
425
+ const { user: ownPnUser } = jidDecode(meId);
426
+ const ownLidUser = meLidUser;
427
+ const isOwnUser =
428
+ targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
429
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
430
+ if (isOwnUser && !isExactSenderDevice) {
431
+ msgToEncrypt = dsmMessage;
432
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
433
+ }
434
+ }
435
+ const bytes = encodeWAMessage(msgToEncrypt);
436
+ const node = await encryptionMutex.mutex(jid, async () => {
437
+ const { type, ciphertext } = await signalRepository.encryptMessage({
438
+ jid,
439
+ data: bytes
440
+ });
441
+ if (type === 'pkmsg') shouldIncludeDeviceIdentity = true;
442
+ return {
443
+ tag: 'to',
444
+ attrs: { jid },
445
+ content: [
446
+ {
447
+ tag: 'enc',
448
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
449
+ content: ciphertext
450
+ }
451
+ ]
452
+ };
453
+ });
454
+ return node;
455
+ } catch (err) {
456
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
457
+ return null;
458
+ }
459
+ }
460
+ );
461
+
462
+ const nodes = (await Promise.all(encryptionPromises)).filter((node) => node !== null);
463
+ if (recipientJids.length > 0 && nodes.length === 0) {
464
+ throw new Boom('All encryptions failed', { statusCode: 500 });
465
+ }
466
+ return { nodes, shouldIncludeDeviceIdentity };
467
+ };
468
+
469
+ const hasButtonContent = (message) => {
470
+ const content = normalizeMessageContent(message);
471
+ if (!content) return false;
472
+ return !!(
473
+ content.buttonsMessage ||
474
+ content.buttonsResponseMessage ||
475
+ content.listMessage ||
476
+ content.listResponseMessage ||
477
+ content.interactiveMessage ||
478
+ content.interactiveResponseMessage ||
479
+ content.nativeFlowMessage ||
480
+ content.templateMessage
481
+ );
482
+ };
483
+
484
+ const getBizNodeForButtons = (message) => {
485
+ const content = normalizeMessageContent(message);
486
+ if (!content) return null;
487
+
488
+ if (content.buttonsMessage || content.interactiveMessage || content.nativeFlowMessage) {
489
+ return {
490
+ tag: 'biz',
491
+ attrs: {},
492
+ content: [
493
+ {
494
+ tag: 'interactive',
495
+ attrs: { type: 'native_flow', v: '1' },
496
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
497
+ }
498
+ ]
499
+ };
500
+ }
501
+
502
+ if (content.listMessage) {
503
+ return {
504
+ tag: 'biz',
505
+ attrs: {},
506
+ content: [{ tag: 'list', attrs: { type: 'product_list', v: '2' } }]
507
+ };
508
+ }
509
+
510
+ return null;
511
+ };
512
+
513
+ const isGroupStatusMessage = (message) => {
514
+ const content = normalizeMessageContent(message);
515
+ if (!content) return false;
516
+ return !!(content.groupStatusMessage || content.groupStatusMessageV2);
517
+ };
518
+
519
+ const getMessageType = (message) => {
520
+ const normalizedMessage = normalizeMessageContent(message);
521
+ if (!normalizedMessage) return 'text';
522
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
523
+ return 'reaction';
524
+ }
525
+ if (
526
+ normalizedMessage.pollCreationMessage ||
527
+ normalizedMessage.pollCreationMessageV2 ||
528
+ normalizedMessage.pollCreationMessageV3 ||
529
+ normalizedMessage.pollUpdateMessage
530
+ ) {
531
+ return 'poll';
532
+ }
533
+ if (normalizedMessage.eventMessage) {
534
+ return 'event';
535
+ }
536
+ if (getMediaType(normalizedMessage) !== '') {
537
+ return 'media';
538
+ }
539
+ return 'text';
540
+ };
541
+
542
+ const getMediaType = (message) => {
543
+ if (message.imageMessage) return 'image';
544
+ if (message.videoMessage) return message.videoMessage.gifPlayback ? 'gif' : 'video';
545
+ if (message.audioMessage) return message.audioMessage.ptt ? 'ptt' : 'audio';
546
+ if (message.contactMessage) return 'vcard';
547
+ if (message.documentMessage) return 'document';
548
+ if (message.contactsArrayMessage) return 'contact_array';
549
+ if (message.liveLocationMessage) return 'livelocation';
550
+ if (message.stickerMessage) return 'sticker';
551
+ if (message.listMessage) return 'list';
552
+ if (message.listResponseMessage) return 'list_response';
553
+ if (message.buttonsResponseMessage) return 'buttons_response';
554
+ if (message.orderMessage) return 'order';
555
+ if (message.productMessage) return 'product';
556
+ if (message.interactiveResponseMessage) return 'native_flow_response';
557
+ if (message.groupInviteMessage) return 'url';
558
+ return '';
559
+ };
560
+
561
+ const issuePrivacyTokens = async (jids, timestamp) => {
562
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
563
+ return query({
564
+ tag: 'iq',
565
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'privacy' },
566
+ content: [
567
+ {
568
+ tag: 'tokens',
569
+ attrs: {},
570
+ content: jids.map((jid) => ({
571
+ tag: 'token',
572
+ attrs: { jid: jidNormalizedUser(jid), t, type: 'trusted_contact' }
573
+ }))
574
+ }
575
+ ]
576
+ });
577
+ };
578
+
579
+ const relayMessage = async (
580
+ jid,
581
+ message,
582
+ {
583
+ messageId: msgId,
584
+ participant,
585
+ additionalAttributes,
586
+ additionalNodes,
587
+ useUserDevicesCache,
588
+ useCachedGroupMetadata,
589
+ statusJidList
590
+ } = {}
591
+ ) => {
592
+ const meId = assertMeId(authState.creds);
593
+ const meLid = authState.creds.me?.lid;
594
+ const isRetryResend = Boolean(participant?.jid);
595
+ let shouldIncludeDeviceIdentity = isRetryResend;
596
+
597
+ const statusJid = 'status@broadcast';
598
+ const { user, server } = jidDecode(jid);
599
+ const isGroup = server === 'g.us';
600
+ const isStatus = jid === statusJid;
601
+ const isLid = server === 'lid';
602
+ const isNewsletter = server === 'newsletter';
603
+ const isGroupOrStatus = isGroup || isStatus;
604
+ const finalJid = jid;
605
+
606
+ msgId = msgId || generateMessageIDV2(meId);
607
+ useUserDevicesCache = useUserDevicesCache !== false;
608
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
609
+
610
+ const participants = [];
611
+ const destinationJid = !isStatus ? finalJid : statusJid;
612
+ const binaryNodeContent = [];
613
+ const devices = [];
614
+ let reportingMessage;
615
+
616
+ const meMsg = {
617
+ deviceSentMessage: { destinationJid, message },
618
+ messageContextInfo: message.messageContextInfo
619
+ };
620
+ const extraAttrs = {};
621
+
622
+ if (participant) {
623
+ if (!isGroup && !isStatus) {
624
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
625
+ }
626
+ const { user: pUser, device } = jidDecode(participant.jid);
627
+ devices.push({ user: pUser, device, jid: participant.jid });
628
+ }
629
+
630
+ await authState.keys.transaction(async () => {
631
+ const mediaType = getMediaType(normalizeMessageContent(message) || message);
632
+ if (mediaType) extraAttrs['mediatype'] = mediaType;
633
+
634
+ if (isNewsletter) {
635
+ if (sock.newsletterSendDirect) {
636
+ const result = await sock.newsletterSendDirect(jid, message, {
637
+ messageId: msgId,
638
+ additionalAttributes
639
+ });
640
+ if (result) return;
641
+ }
642
+
643
+ const patched = patchMessageBeforeSending
644
+ ? await patchMessageBeforeSending(message, [])
645
+ : message;
646
+ const bytes = encodeNewsletterMessage(patched);
647
+ binaryNodeContent.push({ tag: 'plaintext', attrs: {}, content: bytes });
648
+ const stanza = {
649
+ tag: 'message',
650
+ attrs: {
651
+ to: jid,
652
+ id: msgId,
653
+ type: getMessageType(message),
654
+ ...(additionalAttributes || {})
655
+ },
656
+ content: binaryNodeContent
657
+ };
658
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
659
+ await sendNode(stanza);
660
+ return;
661
+ }
662
+
663
+ const normalizedForAttrs = normalizeMessageContent(message);
664
+ if (
665
+ normalizedForAttrs?.pinInChatMessage ||
666
+ normalizedForAttrs?.reactionMessage
667
+ ) {
668
+ extraAttrs['decrypt-fail'] = 'hide';
669
+ }
670
+
671
+ if (isGroupOrStatus && !isRetryResend) {
672
+ const [groupData, senderKeyMap] = await Promise.all([
673
+ (async () => {
674
+ let gd = useCachedGroupMetadata && cachedGroupMetadata
675
+ ? await cachedGroupMetadata(jid)
676
+ : undefined;
677
+ if (gd && Array.isArray(gd?.participants)) {
678
+ logger.trace(
679
+ { jid, participants: gd.participants.length },
680
+ 'using cached group metadata'
681
+ );
682
+ } else if (!isStatus) {
683
+ gd = await groupMetadata(jid);
684
+ }
685
+ return gd;
686
+ })(),
687
+ (async () => {
688
+ if (!participant && !isStatus) {
689
+ const result = await authState.keys.get('sender-key-memory', [jid]);
690
+ return result[jid] || {};
691
+ }
692
+ return {};
693
+ })()
694
+ ]);
695
+
696
+ const participantsList = groupData ? groupData.participants.map((p) => p.id) : [];
697
+
698
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
699
+ additionalAttributes = {
700
+ ...additionalAttributes,
701
+ expiration: groupData.ephemeralDuration.toString()
702
+ };
703
+ }
704
+
705
+ if (isStatus && statusJidList) {
706
+ participantsList.push(...statusJidList);
707
+ }
708
+
709
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
710
+ devices.push(...additionalDevices);
711
+
712
+ if (isGroup) {
713
+ additionalAttributes = {
714
+ ...additionalAttributes,
715
+ addressing_mode: groupData?.addressingMode || 'lid'
716
+ };
717
+ }
718
+
719
+ const patched = await patchMessageBeforeSending(message);
720
+ if (Array.isArray(patched)) {
721
+ throw new Boom('Per-jid patching is not supported in groups');
722
+ }
723
+ const bytes = encodeWAMessage(patched);
724
+ reportingMessage = patched;
725
+
726
+ const groupAddressingMode =
727
+ additionalAttributes?.['addressing_mode'] ||
728
+ groupData?.addressingMode ||
729
+ 'lid';
730
+ const groupSenderIdentity =
731
+ groupAddressingMode === 'lid' && meLid ? meLid : meId;
732
+
733
+ const { ciphertext, senderKeyDistributionMessage } =
734
+ await signalRepository.encryptGroupMessage({
735
+ group: destinationJid,
736
+ data: bytes,
737
+ meId: groupSenderIdentity
738
+ });
739
+
740
+ const senderKeyRecipients = [];
741
+ for (const device of devices) {
742
+ const deviceJid = device.jid;
743
+ const hasKey = !!senderKeyMap[deviceJid];
744
+ if (
745
+ (!hasKey || !!participant) &&
746
+ !isHostedLidUser(deviceJid) &&
747
+ !isHostedPnUser(deviceJid) &&
748
+ device.device !== 99
749
+ ) {
750
+ senderKeyRecipients.push(deviceJid);
751
+ senderKeyMap[deviceJid] = true;
752
+ }
753
+ }
754
+
755
+ if (senderKeyRecipients.length) {
756
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
757
+ const senderKeyMsg = {
758
+ senderKeyDistributionMessage: {
759
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
760
+ groupId: destinationJid
761
+ }
762
+ };
763
+ await assertSessions(senderKeyRecipients);
764
+ const result = await createParticipantNodes(
765
+ senderKeyRecipients,
766
+ senderKeyMsg,
767
+ extraAttrs
768
+ );
769
+ shouldIncludeDeviceIdentity =
770
+ shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
771
+ participants.push(...result.nodes);
772
+ }
773
+
774
+ binaryNodeContent.push({
775
+ tag: 'enc',
776
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
777
+ content: ciphertext
778
+ });
779
+
780
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
781
+
782
+ } else if (!isGroupOrStatus) {
783
+ let ownId = meId;
784
+ if (isLid && meLid) {
785
+ ownId = meLid;
786
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
787
+ } else {
788
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
789
+ }
790
+ const { user: ownUser } = jidDecode(ownId);
791
+
792
+ if (!participant) {
793
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
794
+ reportingMessage = Array.isArray(patchedForReporting)
795
+ ? patchedForReporting.find((item) => item.recipientJid === jid) ||
796
+ patchedForReporting[0]
797
+ : patchedForReporting;
798
+ }
799
+
800
+ if (!isRetryResend) {
801
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
802
+ devices.push({
803
+ user,
804
+ device: 0,
805
+ jid: jidEncode(user, targetUserServer, 0)
806
+ });
807
+ if (user !== ownUser) {
808
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
809
+ const ownUserForAddressing =
810
+ isLid && meLid
811
+ ? jidDecode(meLid).user
812
+ : jidDecode(meId).user;
813
+ devices.push({
814
+ user: ownUserForAddressing,
815
+ device: 0,
816
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
817
+ });
818
+ }
819
+ if (additionalAttributes?.['category'] !== 'peer') {
820
+ devices.length = 0;
821
+ const senderIdentity =
822
+ isLid && meLid
823
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
824
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
825
+ const sessionDevices = await getUSyncDevices(
826
+ [senderIdentity, jid],
827
+ true,
828
+ false
829
+ );
830
+ devices.push(...sessionDevices);
831
+ logger.debug(
832
+ {
833
+ deviceCount: devices.length,
834
+ devices: devices.map(
835
+ (d) => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`
836
+ )
837
+ },
838
+ 'Device enumeration complete with unified addressing'
839
+ );
840
+ }
841
+ }
842
+
843
+ const allRecipients = [];
844
+ const meRecipients = [];
845
+ const otherRecipients = [];
846
+ const { user: mePnUser } = jidDecode(meId);
847
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
848
+
849
+ for (const { user: devUser, jid: devJid } of devices) {
850
+ const isExactSenderDevice = devJid === meId || (meLid && devJid === meLid);
851
+ if (isExactSenderDevice) {
852
+ logger.debug({ jid: devJid, meId, meLid }, 'Skipping exact sender device');
853
+ continue;
854
+ }
855
+ const isMe = devUser === mePnUser || devUser === meLidUser;
856
+ if (isMe) meRecipients.push(devJid);
857
+ else otherRecipients.push(devJid);
858
+ allRecipients.push(devJid);
859
+ }
860
+
861
+ await assertSessions(allRecipients);
862
+
863
+ const [
864
+ { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
865
+ { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
866
+ ] = await Promise.all([
867
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
868
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
869
+ ]);
870
+
871
+ participants.push(...meNodes, ...otherNodes);
872
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
873
+ extraAttrs['phash'] = generateParticipantHashV2([
874
+ ...meRecipients,
875
+ ...otherRecipients
876
+ ]);
877
+ }
878
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
879
+ }
880
+
881
+ if (isRetryResend) {
882
+ const isParticipantLid = isLidUser(participant.jid);
883
+ const isMe = areJidsSameUser(
884
+ participant.jid,
885
+ isParticipantLid ? meLid : meId
886
+ );
887
+ let messageToSend = message;
888
+ if (isGroupOrStatus) {
889
+ let groupSenderIdentity;
890
+ if (
891
+ meLid &&
892
+ (await signalRepository.hasSenderKey({
893
+ group: destinationJid,
894
+ meId: meLid
895
+ }))
896
+ ) {
897
+ groupSenderIdentity = meLid;
898
+ } else if (
899
+ await signalRepository.hasSenderKey({ group: destinationJid, meId })
900
+ ) {
901
+ groupSenderIdentity = meId;
902
+ }
903
+ if (groupSenderIdentity) {
904
+ try {
905
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
906
+ group: destinationJid,
907
+ meId: groupSenderIdentity
908
+ });
909
+ messageToSend = {
910
+ ...message,
911
+ senderKeyDistributionMessage: {
912
+ groupId: destinationJid,
913
+ axolotlSenderKeyDistributionMessage: skdm
914
+ }
915
+ };
916
+ } catch (err) {
917
+ logger.warn(
918
+ { err, jid: destinationJid },
919
+ 'failed to build SKDM for retry, sending without it'
920
+ );
921
+ }
922
+ }
923
+ }
924
+ const encodedMessageToSend = isMe
925
+ ? encodeWAMessage({ deviceSentMessage: { destinationJid, message: messageToSend } })
926
+ : encodeWAMessage(messageToSend);
927
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
928
+ data: encodedMessageToSend,
929
+ jid: participant.jid
930
+ });
931
+ binaryNodeContent.push({
932
+ tag: 'enc',
933
+ attrs: { v: '2', type, count: participant.count.toString() },
934
+ content: encryptedContent
935
+ });
936
+ }
937
+
938
+ if (participants.length) {
939
+ if (additionalAttributes?.['category'] === 'peer') {
940
+ const peerNode = participants[0]?.content?.[0];
941
+ if (peerNode) binaryNodeContent.push(peerNode);
942
+ } else {
943
+ binaryNodeContent.push({
944
+ tag: 'participants',
945
+ attrs: {},
946
+ content: participants
947
+ });
948
+ }
949
+ }
950
+
951
+ const normalizedForBiz = normalizeMessageContent(message);
952
+ const isLocationButtonMessage = !!(normalizedForBiz?.buttonsMessage && normalizedForBiz?.locationMessage);
953
+ const isMediaMsg = !!(
954
+ normalizedForBiz?.imageMessage ||
955
+ normalizedForBiz?.videoMessage ||
956
+ normalizedForBiz?.audioMessage ||
957
+ normalizedForBiz?.documentMessage ||
958
+ normalizedForBiz?.stickerMessage
959
+ );
960
+
961
+ const hasButtonContentCheck = (msg) => {
962
+ const content = normalizeMessageContent(msg);
963
+ if (!content) return false;
964
+ return !!(
965
+ content.buttonsMessage ||
966
+ content.buttonsResponseMessage ||
967
+ content.listMessage ||
968
+ content.listResponseMessage ||
969
+ content.interactiveMessage ||
970
+ content.interactiveResponseMessage ||
971
+ content.nativeFlowMessage ||
972
+ content.templateMessage
973
+ );
974
+ };
975
+
976
+ if (
977
+ !isNewsletter &&
978
+ !isGroupStatusMessage(message) &&
979
+ hasButtonContent(message) &&
980
+ (!isMediaMsg || isLocationButtonMessage)
981
+ ) {
982
+ let hasBizNode = false;
983
+ if (additionalNodes && additionalNodes.length > 0) {
984
+ hasBizNode = additionalNodes.some(node => node.tag === 'biz');
985
+ }
986
+
987
+ if (!hasBizNode) {
988
+ const bizNode = getBizNodeForButtons(message);
989
+ if (bizNode) {
990
+ binaryNodeContent.push(bizNode);
991
+ logger.debug({ jid }, 'adding auto biz node for button message');
992
+ }
993
+ } else {
994
+ logger.debug({ jid }, 'using user-provided biz node for button message');
995
+ }
996
+ }
997
+
998
+ const stanza = {
999
+ tag: 'message',
1000
+ attrs: {
1001
+ id: msgId,
1002
+ to: destinationJid,
1003
+ type: getMessageType(message),
1004
+ ...(additionalAttributes || {})
1005
+ },
1006
+ content: binaryNodeContent
1007
+ };
1008
+
1009
+ if (participant) {
1010
+ if (isJidGroup(destinationJid)) {
1011
+ stanza.attrs.to = destinationJid;
1012
+ stanza.attrs.participant = participant.jid;
1013
+ } else if (areJidsSameUser(participant.jid, meId)) {
1014
+ stanza.attrs.to = participant.jid;
1015
+ stanza.attrs.recipient = destinationJid;
1016
+ } else {
1017
+ stanza.attrs.to = participant.jid;
1018
+ }
1019
+ } else {
1020
+ stanza.attrs.to = destinationJid;
1021
+ }
1022
+
1023
+ if (shouldIncludeDeviceIdentity) {
1024
+ stanza.content.push({
1025
+ tag: 'device-identity',
1026
+ attrs: {},
1027
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
1028
+ });
1029
+ logger.debug({ jid }, 'adding device identity');
1030
+ }
1031
+
1032
+ if (
1033
+ !isNewsletter &&
1034
+ !isRetryResend &&
1035
+ reportingMessage?.messageContextInfo?.messageSecret &&
1036
+ shouldIncludeReportingToken(reportingMessage)
1037
+ ) {
1038
+ try {
1039
+ const encoded = encodeWAMessage(reportingMessage);
1040
+ const reportingKey = {
1041
+ id: msgId,
1042
+ fromMe: true,
1043
+ remoteJid: destinationJid,
1044
+ participant: participant?.jid
1045
+ };
1046
+ const reportingNode = await getMessageReportingToken(
1047
+ encoded,
1048
+ reportingMessage,
1049
+ reportingKey
1050
+ );
1051
+ if (reportingNode) {
1052
+ stanza.content.push(reportingNode);
1053
+ logger.trace({ jid }, 'added reporting token to message');
1054
+ }
1055
+ } catch (error) {
1056
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
1057
+ }
1058
+ }
1059
+
1060
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
1061
+ const is1on1Send =
1062
+ !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
1063
+ const tcTokenJid = is1on1Send
1064
+ ? await resolveTcTokenJid(destinationJid, getLIDForPN)
1065
+ : destinationJid;
1066
+ const contactTcTokenData = is1on1Send
1067
+ ? await authState.keys.get('tctoken', [tcTokenJid])
1068
+ : {};
1069
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
1070
+ let tcTokenBuffer = existingTokenEntry?.token;
1071
+
1072
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
1073
+ logger.debug(
1074
+ { jid: destinationJid, timestamp: existingTokenEntry?.timestamp },
1075
+ 'tctoken expired, clearing'
1076
+ );
1077
+ tcTokenBuffer = undefined;
1078
+ const cleared =
1079
+ existingTokenEntry?.senderTimestamp !== undefined
1080
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
1081
+ : null;
1082
+ try {
1083
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
1084
+ } catch (err) {
1085
+ logger.debug(
1086
+ { jid: destinationJid, err: err?.message },
1087
+ 'failed to persist tctoken expiry cleanup'
1088
+ );
1089
+ }
1090
+ }
1091
+
1092
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
1093
+ stanza.content.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer });
1094
+ }
1095
+
1096
+ if (additionalNodes && additionalNodes.length > 0) {
1097
+ stanza.content.push(...additionalNodes);
1098
+ }
1099
+
1100
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1101
+ await sendNode(stanza);
1102
+
1103
+ const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
1104
+ const isBotOrPSA =
1105
+ destinationJid === PSA_WID ||
1106
+ isJidBot(destinationJid) ||
1107
+ isJidMetaAI(destinationJid);
1108
+ if (
1109
+ is1on1Send &&
1110
+ !isProtocolMsg &&
1111
+ !isBotOrPSA &&
1112
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
1113
+ !inFlightTcTokenIssuance.has(tcTokenJid)
1114
+ ) {
1115
+ inFlightTcTokenIssuance.add(tcTokenJid);
1116
+ const issueTimestamp = unixTimestampSeconds();
1117
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(
1118
+ signalRepository.lidMapping
1119
+ );
1120
+ resolveIssuanceJid(
1121
+ destinationJid,
1122
+ sock.serverProps.lidTrustedTokenIssueToLid,
1123
+ getLIDForPN,
1124
+ getPNForLID
1125
+ )
1126
+ .then((issueJid) => issuePrivacyTokens([issueJid], issueTimestamp))
1127
+ .then(async (result) => {
1128
+ await storeTcTokensFromIqResult({
1129
+ result,
1130
+ fallbackJid: tcTokenJid,
1131
+ keys: authState.keys,
1132
+ getLIDForPN
1133
+ });
1134
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
1135
+ const currentEntry = currentData[tcTokenJid];
1136
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [
1137
+ tcTokenJid
1138
+ ]);
1139
+ await authState.keys.set({
1140
+ tctoken: {
1141
+ [tcTokenJid]: {
1142
+ token: Buffer.alloc(0),
1143
+ ...currentEntry,
1144
+ senderTimestamp: issueTimestamp
1145
+ },
1146
+ ...indexWrite
1147
+ }
1148
+ });
1149
+ })
1150
+ .catch((err) => {
1151
+ logger.debug(
1152
+ { jid: destinationJid, err: err?.message },
1153
+ 'fire-and-forget tctoken issuance failed'
1154
+ );
1155
+ })
1156
+ .finally(() => {
1157
+ inFlightTcTokenIssuance.delete(tcTokenJid);
1158
+ });
1159
+ }
1160
+
1161
+ if (messageRetryManager && !participant) {
1162
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1163
+ }
1164
+ }, meId);
1165
+
1166
+ return msgId;
1167
+ };
1168
+
1169
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
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
+ });
1181
+
1182
+ return {
1183
+ ...sock,
1184
+ userDevicesCache,
1185
+ devicesMutex,
1186
+ issuePrivacyTokens,
1187
+ assertSessions,
1188
+ relayMessage,
1189
+ sendReceipt,
1190
+ sendReceipts,
1191
+ readMessages,
1192
+ refreshMediaConn,
1193
+ getMediaHost: () => mediaHost,
1194
+ waUploadToServer,
1195
+ fetchPrivacySettings,
1196
+ sendPeerDataOperationMessage,
1197
+ createParticipantNodes,
1198
+ getUSyncDevices,
1199
+ messageRetryManager,
1200
+ updateMemberLabel,
1201
+
1202
+ updateMediaMessage: async (message) => {
1203
+ const content = assertMediaContent(message.message);
1204
+ const mediaKey = content.mediaKey;
1205
+ const meId = authState.creds.me.id;
1206
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1207
+ let error;
1208
+
1209
+ await Promise.all([
1210
+ sendNode(node),
1211
+ waitForMsgMediaUpdate(async (update) => {
1212
+ const result = update.find((c) => c.key.id === message.key.id);
1213
+ if (result) {
1214
+ if (result.error) {
1215
+ error = result.error;
1216
+ } else {
1217
+ try {
1218
+ const media = decryptMediaRetryData(
1219
+ result.media,
1220
+ mediaKey,
1221
+ result.key.id
1222
+ );
1223
+ if (
1224
+ media.result !==
1225
+ proto.MediaRetryNotification.ResultType.SUCCESS
1226
+ ) {
1227
+ const resultStr =
1228
+ proto.MediaRetryNotification.ResultType[media.result];
1229
+ throw new Boom(
1230
+ `Media re-upload failed by device (${resultStr})`,
1231
+ {
1232
+ data: media,
1233
+ statusCode:
1234
+ getStatusCodeForMediaRetry(media.result) || 404
1235
+ }
1236
+ );
1237
+ }
1238
+ content.directPath = media.directPath;
1239
+ content.url = getUrlFromDirectPath(
1240
+ content.directPath,
1241
+ mediaHost
1242
+ );
1243
+ logger.debug(
1244
+ { directPath: media.directPath, key: result.key },
1245
+ 'media update successful'
1246
+ );
1247
+ } catch (err) {
1248
+ error = err;
1249
+ }
1250
+ }
1251
+ return true;
1252
+ }
1253
+ })
1254
+ ]);
1255
+
1256
+ if (error) throw error;
1257
+ ev.emit('messages.update', [
1258
+ { key: message.key, update: { message: message.message } }
1259
+ ]);
1260
+ return message;
1261
+ },
1262
+
1263
+ sendMessage: async (jid, content, options = {}) => {
1264
+ const userJid = authState.creds.me.id;
1265
+
1266
+ // Check if this is a newsletter JID
1267
+ const isNewsletterJid = jid && (jid.includes('@newsletter') || jid.endsWith('@newsletter'));
1268
+
1269
+ // If it's a newsletter, use the newsletter send function
1270
+ if (isNewsletterJid && sock.newsletterSend) {
1271
+ try {
1272
+ // Use the working newsletter send method
1273
+ const result = await sock.newsletterSend(jid, content, waUploadToServer, {
1274
+ ...options,
1275
+ messageId: options.messageId || generateMessageIDV2(sock.user?.id || userJid)
1276
+ });
1277
+
1278
+ if (config.emitOwnEvents && result.message) {
1279
+ // Create a full message structure for events
1280
+ const fullMsg = {
1281
+ key: result.key,
1282
+ message: result.message,
1283
+ messageTimestamp: unixTimestampSeconds(),
1284
+ messageStubParameters: [],
1285
+ participant: userJid,
1286
+ status: 'PENDING',
1287
+ messageStubType: 0
1288
+ };
1289
+
1290
+ process.nextTick(async () => {
1291
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1292
+ });
1293
+ }
1294
+
1295
+ return result;
1296
+ } catch (error) {
1297
+ logger.error({ jid, error }, 'Failed to send newsletter message, falling back to regular send');
1298
+ // Fall through to regular send if newsletter send fails
1299
+ }
1300
+ }
1301
+
1302
+ // ── Group story / status (addition) ───────────────────────────────
1303
+ if (typeof content === 'object' && content.groupStatusMessage) {
1304
+ const { generateWAMessageContent, generateMessageIDV2: genId } =
1305
+ await import('../Utils/index.js');
1306
+ const waMsgContent = await generateWAMessageContent(
1307
+ content.groupStatusMessage,
1308
+ {
1309
+ upload: waUploadToServer,
1310
+ logger: config.logger,
1311
+ mediaCache: config.mediaCache,
1312
+ options: config.options
1313
+ }
1314
+ );
1315
+ const wrappedMsg = {
1316
+ groupStatusMessageV2: {
1317
+ message: waMsgContent.message || waMsgContent
1318
+ }
1319
+ };
1320
+ return relayMessage(jid, wrappedMsg, {
1321
+ messageId: options.messageId || genId(sock.user?.id),
1322
+ ...options
1323
+ });
1324
+ }
1325
+
1326
+ // ── Disappearing messages toggle ───────────────────────────────────
1327
+ if (
1328
+ typeof content === 'object' &&
1329
+ 'disappearingMessagesInChat' in content &&
1330
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1331
+ isJidGroup(jid)
1332
+ ) {
1333
+ const { disappearingMessagesInChat } = content;
1334
+ const value =
1335
+ typeof disappearingMessagesInChat === 'boolean'
1336
+ ? disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0
1337
+ : disappearingMessagesInChat;
1338
+ await groupToggleEphemeral(jid, value);
1339
+ return;
1340
+ }
1341
+
1342
+ // ── Regular message ───────────────────────────────────────────────
1343
+ const fullMsg = await generateWAMessage(jid, content, {
1344
+ logger,
1345
+ userJid,
1346
+ getUrlInfo: (text) =>
1347
+ getUrlInfo(text, {
1348
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1349
+ fetchOpts: { timeout: 3000, ...(httpRequestOptions || {}) },
1350
+ logger,
1351
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1352
+ }),
1353
+ getProfilePicUrl: sock.profilePictureUrl,
1354
+ getCallLink: sock.createCallLink,
1355
+ upload: waUploadToServer,
1356
+ mediaCache: config.mediaCache,
1357
+ options: config.options,
1358
+ messageId: generateMessageIDV2(sock.user?.id || userJid),
1359
+ ...options
1360
+ });
1361
+
1362
+ const isEventMsg = 'event' in content && !!content.event;
1363
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1364
+ const isEditMsg = 'edit' in content && !!content.edit;
1365
+ const isPinMsg = 'pin' in content && !!content.pin;
1366
+ const isPollMessage = 'poll' in content && !!content.poll;
1367
+
1368
+ const additionalAttributes = {};
1369
+ const additionalNodes = [];
1370
+
1371
+ if (isDeleteMsg) {
1372
+ additionalAttributes.edit =
1373
+ isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe ? '8' : '7';
1374
+ } else if (isEditMsg) {
1375
+ additionalAttributes.edit = '1';
1376
+ } else if (isPinMsg) {
1377
+ additionalAttributes.edit = '2';
1378
+ } else if (isPollMessage) {
1379
+ additionalNodes.push({ tag: 'meta', attrs: { polltype: 'creation' } });
1380
+ } else if (isEventMsg) {
1381
+ additionalNodes.push({ tag: 'meta', attrs: { event_type: 'creation' } });
1382
+ }
1383
+
1384
+ if ('cachedGroupMetadata' in options) {
1385
+ console.warn(
1386
+ 'cachedGroupMetadata in sendMessage is deprecated; pass it via socket config.'
1387
+ );
1388
+ }
1389
+
1390
+ await relayMessage(jid, fullMsg.message, {
1391
+ messageId: fullMsg.key.id,
1392
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1393
+ additionalAttributes,
1394
+ statusJidList: options.statusJidList,
1395
+ additionalNodes
1396
+ });
1397
+
1398
+ if (config.emitOwnEvents) {
1399
+ process.nextTick(async () => {
1400
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1401
+ });
1402
+ }
1403
+
1404
+ return fullMsg;
1405
+ }
1406
+ };
1407
+ };
1408
+ //# sourceMappingURL=messages-send.js.map