@rakku-kun/baileys 2.0.15 → 2.0.17

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 (175) hide show
  1. package/WAProto/fix-imports.js +22 -18
  2. package/WAProto/index.js +22 -18
  3. package/lib/Defaults/index.d.ts +8 -7
  4. package/lib/Defaults/index.d.ts.map +1 -1
  5. package/lib/Defaults/index.js +11 -17
  6. package/lib/Defaults/index.js.map +1 -1
  7. package/lib/Signal/libsignal.d.ts.map +1 -1
  8. package/lib/Signal/libsignal.js +52 -59
  9. package/lib/Signal/libsignal.js.map +1 -1
  10. package/lib/Signal/lid-mapping.d.ts.map +1 -1
  11. package/lib/Signal/lid-mapping.js.map +1 -1
  12. package/lib/Socket/business.d.ts +18 -3
  13. package/lib/Socket/business.d.ts.map +1 -1
  14. package/lib/Socket/chats.d.ts +16 -2
  15. package/lib/Socket/chats.d.ts.map +1 -1
  16. package/lib/Socket/chats.js +238 -173
  17. package/lib/Socket/chats.js.map +1 -1
  18. package/lib/Socket/communities.d.ts +18 -3
  19. package/lib/Socket/communities.d.ts.map +1 -1
  20. package/lib/Socket/groups.d.ts +13 -2
  21. package/lib/Socket/groups.d.ts.map +1 -1
  22. package/lib/Socket/groups.js +26 -138
  23. package/lib/Socket/groups.js.map +1 -1
  24. package/lib/Socket/index.d.ts +18 -3
  25. package/lib/Socket/index.d.ts.map +1 -1
  26. package/lib/Socket/messages-recv.d.ts +22 -6
  27. package/lib/Socket/messages-recv.d.ts.map +1 -1
  28. package/lib/Socket/messages-recv.js +736 -647
  29. package/lib/Socket/messages-recv.js.map +1 -1
  30. package/lib/Socket/messages-send.d.ts +18 -2
  31. package/lib/Socket/messages-send.d.ts.map +1 -1
  32. package/lib/Socket/messages-send.js +152 -642
  33. package/lib/Socket/messages-send.js.map +1 -1
  34. package/lib/Socket/newsletter.d.ts +11 -1
  35. package/lib/Socket/newsletter.d.ts.map +1 -1
  36. package/lib/Socket/newsletter.js +3 -92
  37. package/lib/Socket/newsletter.js.map +1 -1
  38. package/lib/Socket/socket.d.ts +6 -2
  39. package/lib/Socket/socket.d.ts.map +1 -1
  40. package/lib/Socket/socket.js +61 -35
  41. package/lib/Socket/socket.js.map +1 -1
  42. package/lib/Types/Auth.d.ts +1 -0
  43. package/lib/Types/Auth.d.ts.map +1 -1
  44. package/lib/Types/Call.d.ts +1 -1
  45. package/lib/Types/Call.d.ts.map +1 -1
  46. package/lib/Types/Chat.d.ts +1 -0
  47. package/lib/Types/Chat.d.ts.map +1 -1
  48. package/lib/Types/Contact.d.ts +2 -0
  49. package/lib/Types/Contact.d.ts.map +1 -1
  50. package/lib/Types/Events.d.ts +20 -1
  51. package/lib/Types/Events.d.ts.map +1 -1
  52. package/lib/Types/GroupMetadata.d.ts +4 -0
  53. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  54. package/lib/Types/Message.d.ts +25 -200
  55. package/lib/Types/Message.d.ts.map +1 -1
  56. package/lib/Types/Message.js.map +1 -1
  57. package/lib/Types/Mex.d.ts +141 -0
  58. package/lib/Types/Mex.d.ts.map +1 -0
  59. package/lib/Types/Mex.js +37 -0
  60. package/lib/Types/Mex.js.map +1 -0
  61. package/lib/Types/Signal.d.ts +12 -1
  62. package/lib/Types/Signal.d.ts.map +1 -1
  63. package/lib/Types/Socket.d.ts +3 -0
  64. package/lib/Types/Socket.d.ts.map +1 -1
  65. package/lib/Types/State.d.ts +58 -0
  66. package/lib/Types/State.d.ts.map +1 -1
  67. package/lib/Types/State.js +43 -0
  68. package/lib/Types/State.js.map +1 -1
  69. package/lib/Types/index.d.ts +2 -1
  70. package/lib/Types/index.d.ts.map +1 -1
  71. package/lib/Types/index.js +1 -2
  72. package/lib/Types/index.js.map +1 -1
  73. package/lib/Utils/auth-utils.d.ts +5 -0
  74. package/lib/Utils/auth-utils.d.ts.map +1 -1
  75. package/lib/Utils/auth-utils.js +12 -0
  76. package/lib/Utils/auth-utils.js.map +1 -1
  77. package/lib/Utils/browser-utils.d.ts.map +1 -1
  78. package/lib/Utils/browser-utils.js +21 -33
  79. package/lib/Utils/browser-utils.js.map +1 -1
  80. package/lib/Utils/chat-utils.d.ts +31 -1
  81. package/lib/Utils/chat-utils.d.ts.map +1 -1
  82. package/lib/Utils/chat-utils.js +80 -20
  83. package/lib/Utils/chat-utils.js.map +1 -1
  84. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  85. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  86. package/lib/Utils/companion-reg-client-utils.js +35 -0
  87. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  88. package/lib/Utils/decode-wa-message.d.ts +18 -0
  89. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  90. package/lib/Utils/decode-wa-message.js +34 -0
  91. package/lib/Utils/decode-wa-message.js.map +1 -1
  92. package/lib/Utils/event-buffer.d.ts +2 -0
  93. package/lib/Utils/event-buffer.d.ts.map +1 -1
  94. package/lib/Utils/event-buffer.js +49 -1
  95. package/lib/Utils/event-buffer.js.map +1 -1
  96. package/lib/Utils/generics.d.ts +1 -0
  97. package/lib/Utils/generics.d.ts.map +1 -1
  98. package/lib/Utils/generics.js +10 -28
  99. package/lib/Utils/generics.js.map +1 -1
  100. package/lib/Utils/history.d.ts +2 -0
  101. package/lib/Utils/history.d.ts.map +1 -1
  102. package/lib/Utils/history.js +12 -9
  103. package/lib/Utils/history.js.map +1 -1
  104. package/lib/Utils/identity-change-handler.d.ts +7 -0
  105. package/lib/Utils/identity-change-handler.d.ts.map +1 -1
  106. package/lib/Utils/identity-change-handler.js +1 -0
  107. package/lib/Utils/identity-change-handler.js.map +1 -1
  108. package/lib/Utils/index.d.ts +2 -2
  109. package/lib/Utils/index.d.ts.map +1 -1
  110. package/lib/Utils/index.js +2 -7
  111. package/lib/Utils/index.js.map +1 -1
  112. package/lib/Utils/link-preview.js +2 -2
  113. package/lib/Utils/link-preview.js.map +1 -1
  114. package/lib/Utils/message-retry-manager.d.ts +5 -0
  115. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  116. package/lib/Utils/message-retry-manager.js +40 -0
  117. package/lib/Utils/message-retry-manager.js.map +1 -1
  118. package/lib/Utils/messages-media.d.ts +4 -1
  119. package/lib/Utils/messages-media.d.ts.map +1 -1
  120. package/lib/Utils/messages-media.js +131 -173
  121. package/lib/Utils/messages-media.js.map +1 -1
  122. package/lib/Utils/messages.d.ts +0 -1
  123. package/lib/Utils/messages.d.ts.map +1 -1
  124. package/lib/Utils/messages.js +100 -906
  125. package/lib/Utils/messages.js.map +1 -1
  126. package/lib/Utils/offline-node-processor.d.ts +17 -0
  127. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  128. package/lib/Utils/offline-node-processor.js +40 -0
  129. package/lib/Utils/offline-node-processor.js.map +1 -0
  130. package/lib/Utils/process-message.d.ts.map +1 -1
  131. package/lib/Utils/process-message.js +103 -1
  132. package/lib/Utils/process-message.js.map +1 -1
  133. package/lib/Utils/signal.d.ts +13 -0
  134. package/lib/Utils/signal.d.ts.map +1 -1
  135. package/lib/Utils/signal.js +42 -0
  136. package/lib/Utils/signal.js.map +1 -1
  137. package/lib/Utils/stanza-ack.d.ts +11 -0
  138. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  139. package/lib/Utils/stanza-ack.js +38 -0
  140. package/lib/Utils/stanza-ack.js.map +1 -0
  141. package/lib/Utils/sync-action-utils.d.ts.map +1 -1
  142. package/lib/Utils/sync-action-utils.js +1 -0
  143. package/lib/Utils/sync-action-utils.js.map +1 -1
  144. package/lib/Utils/tc-token-utils.d.ts +26 -1
  145. package/lib/Utils/tc-token-utils.d.ts.map +1 -1
  146. package/lib/Utils/tc-token-utils.js +151 -5
  147. package/lib/Utils/tc-token-utils.js.map +1 -1
  148. package/lib/Utils/validate-connection.d.ts.map +1 -1
  149. package/lib/Utils/validate-connection.js +12 -2
  150. package/lib/Utils/validate-connection.js.map +1 -1
  151. package/lib/WABinary/generic-utils.js +0 -15
  152. package/lib/WABinary/index.js +0 -1
  153. package/lib/WABinary/jid-utils.js +0 -2
  154. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  155. package/lib/WAUSync/Protocols/USyncContactProtocol.js +26 -3
  156. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  157. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  158. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  159. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  160. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  161. package/lib/WAUSync/Protocols/index.d.ts +1 -0
  162. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  163. package/lib/WAUSync/Protocols/index.js +2 -2
  164. package/lib/WAUSync/Protocols/index.js.map +1 -1
  165. package/lib/WAUSync/USyncQuery.d.ts +1 -0
  166. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  167. package/lib/WAUSync/USyncQuery.js +6 -2
  168. package/lib/WAUSync/USyncQuery.js.map +1 -1
  169. package/lib/WAUSync/USyncUser.d.ts +4 -0
  170. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  171. package/lib/WAUSync/USyncUser.js +8 -0
  172. package/lib/WAUSync/USyncUser.js.map +1 -1
  173. package/lib/index.d.ts +1 -1
  174. package/lib/index.js +10 -24
  175. package/package.json +1 -1
@@ -1,38 +1,40 @@
1
1
  import NodeCache from '@cacheable/node-cache';
2
2
  import { Boom } from '@hapi/boom';
3
- import { randomBytes } from 'crypto';
4
3
  import { proto } from '../../WAProto/index.js';
5
4
  import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
- import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, prepareWAMessageMedia, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
5
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
7
6
  import { getUrlInfo } from '../Utils/link-preview.js';
8
- import { makeKeyedMutex } from '../Utils/make-mutex.js';
7
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
9
8
  import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
10
- import { areJidsSameUser, getBinaryFilteredBizBot, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidGroup, isJidUser, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET, STORIES_JID } from '../WABinary/index.js';
11
- import { delay } from '../Utils/generics.js';
12
-
9
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
10
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
13
11
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
14
12
  import { makeNewsletterSocket } from './newsletter.js';
15
- // Inline helper — no external import needed
16
- const _isNewsletterJid = (jid) => typeof jid === 'string' && jid.endsWith('@newsletter');
17
-
18
13
  export const makeMessagesSocket = (config) => {
19
14
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
20
15
  const sock = makeNewsletterSocket(config);
21
- const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
16
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
17
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
18
+ /**
19
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
20
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
21
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
22
+ */
23
+ const inFlightTcTokenIssuance = new Set();
22
24
  const userDevicesCache = config.userDevicesCache ||
23
25
  new NodeCache({
24
26
  stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
25
27
  useClones: false
26
28
  });
27
- const peerSessionsCache = new NodeCache({
28
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
29
- useClones: false
30
- });
29
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
30
+ const devicesMutex = makeMutex();
31
31
  // Initialize message retry manager if enabled
32
32
  const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
33
33
  // Prevent race conditions in Signal session encryption by user
34
34
  const encryptionMutex = makeKeyedMutex();
35
35
  let mediaConn;
36
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
37
+ let mediaHost = DEF_MEDIA_HOST;
36
38
  const refreshMediaConn = async (forceGet = false) => {
37
39
  const media = await mediaConn;
38
40
  if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
@@ -58,6 +60,9 @@ export const makeMessagesSocket = (config) => {
58
60
  fetchDate: new Date()
59
61
  };
60
62
  logger.debug('fetched media conn');
63
+ if (node.hosts[0]) {
64
+ mediaHost = node.hosts[0].hostname;
65
+ }
61
66
  return node;
62
67
  })();
63
68
  }
@@ -233,16 +238,18 @@ export const makeMessagesSocket = (config) => {
233
238
  }, 'Processed device with LID priority');
234
239
  }
235
240
  }
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]);
241
+ await devicesMutex.mutex(async () => {
242
+ if (userDevicesCache.mset) {
243
+ // if the cache supports mset, we can set all devices in one go
244
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
244
245
  }
245
- }
246
+ else {
247
+ for (const key in deviceMap) {
248
+ if (deviceMap[key])
249
+ await userDevicesCache.set(key, deviceMap[key]);
250
+ }
251
+ }
252
+ });
246
253
  const userDeviceUpdates = {};
247
254
  for (const [userId, devices] of Object.entries(deviceMap)) {
248
255
  if (devices && devices.length > 0) {
@@ -288,23 +295,13 @@ export const makeMessagesSocket = (config) => {
288
295
  };
289
296
  const assertSessions = async (jids, force) => {
290
297
  let didFetchNewSession = false;
291
- const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
298
+ const uniqueJids = [...new Set(jids)];
292
299
  const jidsRequiringFetch = [];
293
300
  logger.debug({ jids }, 'assertSessions call with jids');
294
- // Check peerSessionsCache and validate sessions using libsignal loadSession
295
301
  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 {
302
+ if (!force) {
304
303
  const sessionValidation = await signalRepository.validateSession(jid);
305
- const hasSession = sessionValidation.exists;
306
- peerSessionsCache.set(signalId, hasSession);
307
- if (hasSession && !force) {
304
+ if (sessionValidation.exists) {
308
305
  continue;
309
306
  }
310
307
  }
@@ -339,11 +336,6 @@ export const makeMessagesSocket = (config) => {
339
336
  });
340
337
  await parseAndInjectE2ESessions(result, signalRepository);
341
338
  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
339
  }
348
340
  return didFetchNewSession;
349
341
  };
@@ -433,8 +425,8 @@ export const makeMessagesSocket = (config) => {
433
425
  }
434
426
  return { nodes, shouldIncludeDeviceIdentity };
435
427
  };
436
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = false }) => {
437
- const meId = authState.creds.me.id;
428
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
429
+ const meId = assertMeId(authState.creds);
438
430
  const meLid = authState.creds.me?.lid;
439
431
  const isRetryResend = Boolean(participant?.jid);
440
432
  let shouldIncludeDeviceIdentity = isRetryResend;
@@ -479,89 +471,13 @@ export const makeMessagesSocket = (config) => {
479
471
  extraAttrs['mediatype'] = mediaType;
480
472
  }
481
473
  if (isNewsletter) {
482
- // Handle edit
483
- if (message.protocolMessage?.editedMessage) {
484
- msgId = message.protocolMessage.key?.id;
485
- message = message.protocolMessage.editedMessage;
486
- }
487
- // Handle delete/revoke
488
- if (message.protocolMessage?.type === proto.Message.ProtocolMessage.Type.REVOKE) {
489
- msgId = message.protocolMessage.key?.id;
490
- message = {};
491
- }
492
- // ── Newsletter Button Compatibility Patch ──────────────────────
493
- // interactiveMessage (quick_reply / single_select / cta_url) bisa
494
- // dikirim ke newsletter langsung — WA menerima via proto encoding.
495
- // listMessage & buttonsMessage dikonversi ke interactiveMessage
496
- // supaya konsisten dengan cara bot menulis pesan.
497
- // ──────────────────────────────────────────────────────────────
498
- if (message.listMessage) {
499
- const list = message.listMessage;
500
- message = {
501
- interactiveMessage: {
502
- nativeFlowMessage: {
503
- buttons: [{
504
- name: 'single_select',
505
- buttonParamsJson: JSON.stringify({
506
- title: list.buttonText || 'Select',
507
- sections: (list.sections || []).map(sec => ({
508
- title: sec.title || '',
509
- highlight_label: '',
510
- rows: (sec.rows || []).map(row => ({
511
- header: '',
512
- title: row.title || '',
513
- description: row.description || '',
514
- id: row.rowId || row.id || ''
515
- }))
516
- }))
517
- })
518
- }],
519
- messageParamsJson: '',
520
- messageVersion: 1
521
- },
522
- body: { text: list.description || '' },
523
- ...(list.footerText ? { footer: { text: list.footerText } } : {}),
524
- ...(list.title ? { header: { title: list.title, hasMediaAttachment: false, subtitle: '' } } : {})
525
- }
526
- };
527
- }
528
- else if (message.buttonsMessage) {
529
- const bMsg = message.buttonsMessage;
530
- message = {
531
- interactiveMessage: {
532
- nativeFlowMessage: {
533
- buttons: (bMsg.buttons || []).map(btn => ({
534
- name: 'quick_reply',
535
- buttonParamsJson: JSON.stringify({
536
- display_text: btn.buttonText?.displayText || btn.buttonText || '',
537
- id: btn.buttonId || btn.buttonText?.displayText || ''
538
- })
539
- })),
540
- messageParamsJson: '',
541
- messageVersion: 1
542
- },
543
- body: { text: bMsg.contentText || bMsg.text || '' },
544
- ...(bMsg.footerText ? { footer: { text: bMsg.footerText } } : {}),
545
- }
546
- };
547
- }
548
- // ── End Newsletter Button Compatibility Patch ──────────────────
549
474
  const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
550
- if (Array.isArray(patched)) {
551
- throw new Error('Per-jid patching is not supported in channel');
552
- }
553
475
  const bytes = encodeNewsletterMessage(patched);
554
- // Set mediatype for interactive messages
555
- if (patched.interactiveMessage && !extraAttrs['mediatype']) {
556
- extraAttrs['mediatype'] = 'interactive';
557
- }
558
- // extraAttrs already has mediatype set above if media message
559
476
  binaryNodeContent.push({
560
477
  tag: 'plaintext',
561
- attrs: extraAttrs,
478
+ attrs: {},
562
479
  content: bytes
563
480
  });
564
- logger.debug({ msgId, extraAttrs }, `sending newsletter message to ${jid}`);
565
481
  const stanza = {
566
482
  tag: 'message',
567
483
  attrs: {
@@ -572,6 +488,7 @@ export const makeMessagesSocket = (config) => {
572
488
  },
573
489
  content: binaryNodeContent
574
490
  };
491
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
575
492
  await sendNode(stanza);
576
493
  return;
577
494
  }
@@ -618,147 +535,6 @@ export const makeMessagesSocket = (config) => {
618
535
  addressing_mode: groupData?.addressingMode || 'lid'
619
536
  };
620
537
  }
621
- // Ensure groupStatusMessageV2 always has messageContextInfo.messageSecret
622
- if (message?.groupStatusMessageV2 && !message?.messageContextInfo?.messageSecret) {
623
- const { randomBytes } = await import('node:crypto');
624
- message = {
625
- ...message,
626
- messageContextInfo: {
627
- ...(message.messageContextInfo || {}),
628
- messageSecret: randomBytes(32)
629
- },
630
- groupStatusMessageV2: {
631
- ...message.groupStatusMessageV2,
632
- message: {
633
- ...(message.groupStatusMessageV2.message || {}),
634
- messageContextInfo: {
635
- ...(message.groupStatusMessageV2.message?.messageContextInfo || {}),
636
- messageSecret: message.messageContextInfo?.messageSecret || randomBytes(32)
637
- }
638
- }
639
- }
640
- };
641
- }
642
- // ── Group Interactive Message Compatibility Patch ──────────────
643
- // WhatsApp groups do NOT render listMessage, buttonsMessage, or
644
- // templateMessage natively in MD protocol. All must be converted
645
- // to interactiveMessage with nativeFlowMessage so they display
646
- // and are interactive in group chats.
647
- // ──────────────────────────────────────────────────────────────
648
-
649
- // 1. listMessage → interactiveMessage single_select
650
- if (message.listMessage) {
651
- const list = message.listMessage;
652
- const interactiveMessage = {
653
- nativeFlowMessage: {
654
- buttons: [{
655
- name: 'single_select',
656
- buttonParamsJson: JSON.stringify({
657
- title: list.buttonText || 'Select',
658
- sections: (list.sections || []).map(section => ({
659
- title: section.title || '',
660
- highlight_label: '',
661
- rows: (section.rows || []).map(row => ({
662
- header: '',
663
- title: row.title || '',
664
- description: row.description || '',
665
- id: row.rowId || row.id || ''
666
- }))
667
- }))
668
- })
669
- }],
670
- messageParamsJson: '',
671
- messageVersion: 1
672
- },
673
- body: { text: list.description || '' },
674
- footer: list.footerText ? { text: list.footerText } : undefined,
675
- header: list.title ? { title: list.title, hasMediaAttachment: false, subtitle: '' } : undefined,
676
- contextInfo: list.contextInfo
677
- };
678
- message = { interactiveMessage };
679
- }
680
-
681
- // 2. buttonsMessage → interactiveMessage nativeFlowMessage quick_reply buttons
682
- else if (message.buttonsMessage) {
683
- const bMsg = message.buttonsMessage;
684
- const buttons = (bMsg.buttons || []).map(btn => ({
685
- name: 'quick_reply',
686
- buttonParamsJson: JSON.stringify({
687
- display_text: btn.buttonText?.displayText || btn.buttonText || '',
688
- id: btn.buttonId || btn.buttonText?.displayText || ''
689
- })
690
- }));
691
- const interactiveMessage = {
692
- nativeFlowMessage: {
693
- buttons,
694
- messageParamsJson: '',
695
- messageVersion: 1
696
- },
697
- body: { text: bMsg.contentText || bMsg.text || '' },
698
- footer: bMsg.footerText ? { text: bMsg.footerText } : undefined,
699
- header: bMsg.text
700
- ? { title: bMsg.text, hasMediaAttachment: false, subtitle: '' }
701
- : (bMsg.imageMessage || bMsg.videoMessage || bMsg.documentMessage
702
- ? { hasMediaAttachment: true, ...(bMsg.imageMessage ? { imageMessage: bMsg.imageMessage } : {}), ...(bMsg.videoMessage ? { videoMessage: bMsg.videoMessage } : {}) }
703
- : undefined),
704
- contextInfo: bMsg.contextInfo
705
- };
706
- message = { interactiveMessage };
707
- }
708
-
709
- // 3. templateMessage (hydratedFourRowTemplate) → interactiveMessage nativeFlowMessage
710
- else if (message.templateMessage) {
711
- const tmpl = message.templateMessage.hydratedTemplate || message.templateMessage.fourRowTemplate;
712
- if (tmpl) {
713
- const hydratedButtons = tmpl.hydratedButtons || [];
714
- const buttons = hydratedButtons.map(hBtn => {
715
- if (hBtn.quickReplyButton) {
716
- return {
717
- name: 'quick_reply',
718
- buttonParamsJson: JSON.stringify({
719
- display_text: hBtn.quickReplyButton.displayText || '',
720
- id: hBtn.quickReplyButton.id || hBtn.quickReplyButton.displayText || ''
721
- })
722
- };
723
- } else if (hBtn.urlButton) {
724
- return {
725
- name: 'cta_url',
726
- buttonParamsJson: JSON.stringify({
727
- display_text: hBtn.urlButton.displayText || '',
728
- url: hBtn.urlButton.url || '',
729
- merchant_url: hBtn.urlButton.url || ''
730
- })
731
- };
732
- } else if (hBtn.callButton) {
733
- return {
734
- name: 'cta_call',
735
- buttonParamsJson: JSON.stringify({
736
- display_text: hBtn.callButton.displayText || '',
737
- phone_number: hBtn.callButton.phoneNumber || ''
738
- })
739
- };
740
- }
741
- return null;
742
- }).filter(Boolean);
743
- const interactiveMessage = {
744
- nativeFlowMessage: {
745
- buttons,
746
- messageParamsJson: '',
747
- messageVersion: 1
748
- },
749
- body: { text: tmpl.hydratedContentText || tmpl.contentText || '' },
750
- footer: tmpl.hydratedFooterText ? { text: tmpl.hydratedFooterText } : undefined,
751
- header: tmpl.hydratedTitleText
752
- ? { title: tmpl.hydratedTitleText, hasMediaAttachment: false, subtitle: '' }
753
- : (tmpl.imageMessage || tmpl.videoMessage || tmpl.documentMessage
754
- ? { hasMediaAttachment: true, ...(tmpl.imageMessage ? { imageMessage: tmpl.imageMessage } : {}), ...(tmpl.videoMessage ? { videoMessage: tmpl.videoMessage } : {}) }
755
- : undefined),
756
- contextInfo: tmpl.contextInfo
757
- };
758
- message = { interactiveMessage };
759
- }
760
- }
761
- // ── End Group Interactive Message Compatibility Patch ──────────
762
538
  const patched = await patchMessageBeforeSending(message);
763
539
  if (Array.isArray(patched)) {
764
540
  throw new Boom('Per-jid patching is not supported in groups');
@@ -894,14 +670,42 @@ export const makeMessagesSocket = (config) => {
894
670
  if (isRetryResend) {
895
671
  const isParticipantLid = isLidUser(participant.jid);
896
672
  const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
673
+ let messageToSend = message;
674
+ if (isGroupOrStatus) {
675
+ let groupSenderIdentity;
676
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
677
+ groupSenderIdentity = meLid;
678
+ }
679
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
680
+ groupSenderIdentity = meId;
681
+ }
682
+ if (groupSenderIdentity) {
683
+ try {
684
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
685
+ group: destinationJid,
686
+ meId: groupSenderIdentity
687
+ });
688
+ messageToSend = {
689
+ ...message,
690
+ senderKeyDistributionMessage: {
691
+ groupId: destinationJid,
692
+ axolotlSenderKeyDistributionMessage: skdm
693
+ }
694
+ };
695
+ }
696
+ catch (err) {
697
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
698
+ }
699
+ }
700
+ }
897
701
  const encodedMessageToSend = isMe
898
702
  ? encodeWAMessage({
899
703
  deviceSentMessage: {
900
704
  destinationJid,
901
- message
705
+ message: messageToSend
902
706
  }
903
707
  })
904
- : encodeWAMessage(message);
708
+ : encodeWAMessage(messageToSend);
905
709
  const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
906
710
  data: encodedMessageToSend,
907
711
  jid: participant.jid
@@ -992,9 +796,30 @@ export const makeMessagesSocket = (config) => {
992
796
  logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
993
797
  }
994
798
  }
995
- const contactTcTokenData = !isGroup && !isRetryResend && !isStatus ? await authState.keys.get('tctoken', [destinationJid]) : {};
996
- const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
997
- if (tcTokenBuffer) {
799
+ // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
800
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
801
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
802
+ // Resolve destination to LID for tctoken storage — matches Signal session key pattern
803
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
804
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
805
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
806
+ let tcTokenBuffer = existingTokenEntry?.token;
807
+ // Treat expired tokens the same as missing — clear from cache
808
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
809
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
810
+ tcTokenBuffer = undefined;
811
+ // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
812
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
813
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
814
+ : null;
815
+ try {
816
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
817
+ }
818
+ catch (err) {
819
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
820
+ }
821
+ }
822
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
998
823
  ;
999
824
  stanza.content.push({
1000
825
  tag: 'tctoken',
@@ -1002,24 +827,54 @@ export const makeMessagesSocket = (config) => {
1002
827
  content: tcTokenBuffer
1003
828
  });
1004
829
  }
1005
- if (AI && !isGroup && !isStatus && !isNewsletter) {
1006
- const existingBizBot = getBinaryFilteredBizBot(additionalNodes || []);
1007
- if (existingBizBot) {
1008
- if (additionalNodes && additionalNodes.length > 0) {
1009
- stanza.content.push(...additionalNodes);
1010
- }
1011
- } else {
1012
- stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } });
1013
- if (additionalNodes && additionalNodes.length > 0) {
1014
- stanza.content.push(...additionalNodes);
1015
- }
1016
- }
1017
- } else if (additionalNodes && additionalNodes.length > 0) {
830
+ if (additionalNodes && additionalNodes.length > 0) {
1018
831
  ;
1019
832
  stanza.content.push(...additionalNodes);
1020
833
  }
1021
834
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1022
835
  await sendNode(stanza);
836
+ // Fire-and-forget: issue our token to the contact AFTER message send.
837
+ // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
838
+ const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
839
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
840
+ if (is1on1Send &&
841
+ !isProtocolMsg &&
842
+ !isBotOrPSA &&
843
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
844
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
845
+ inFlightTcTokenIssuance.add(tcTokenJid);
846
+ const issueTimestamp = unixTimestampSeconds();
847
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
848
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
849
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
850
+ .then(async (result) => {
851
+ await storeTcTokensFromIqResult({
852
+ result,
853
+ fallbackJid: tcTokenJid,
854
+ keys: authState.keys,
855
+ getLIDForPN
856
+ });
857
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
858
+ const currentEntry = currentData[tcTokenJid];
859
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
860
+ await authState.keys.set({
861
+ tctoken: {
862
+ [tcTokenJid]: {
863
+ token: Buffer.alloc(0),
864
+ ...currentEntry,
865
+ senderTimestamp: issueTimestamp
866
+ },
867
+ ...indexWrite
868
+ }
869
+ });
870
+ })
871
+ .catch(err => {
872
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
873
+ })
874
+ .finally(() => {
875
+ inFlightTcTokenIssuance.delete(tcTokenJid);
876
+ });
877
+ }
1023
878
  // Add message to retry cache if enabled
1024
879
  if (messageRetryManager && !participant) {
1025
880
  messageRetryManager.addRecentMessage(destinationJid, msgId, message);
@@ -1028,11 +883,6 @@ export const makeMessagesSocket = (config) => {
1028
883
  return msgId;
1029
884
  };
1030
885
  const getMessageType = (message) => {
1031
- // groupStatusMessageV2 must be checked BEFORE normalizeMessageContent
1032
- // because normalizeMessageContent will unwrap it into inner message
1033
- if (message?.groupStatusMessageV2 || message?.groupStatusMessage) {
1034
- return 'text';
1035
- }
1036
886
  const normalizedMessage = normalizeMessageContent(message);
1037
887
  if (!normalizedMessage)
1038
888
  return 'text';
@@ -1048,9 +898,6 @@ export const makeMessagesSocket = (config) => {
1048
898
  if (normalizedMessage.eventMessage) {
1049
899
  return 'event';
1050
900
  }
1051
- if (normalizedMessage.interactiveMessage) {
1052
- return 'text';
1053
- }
1054
901
  if (getMediaType(normalizedMessage) !== '') {
1055
902
  return 'media';
1056
903
  }
@@ -1063,9 +910,6 @@ export const makeMessagesSocket = (config) => {
1063
910
  else if (message.videoMessage) {
1064
911
  return message.videoMessage.gifPlayback ? 'gif' : 'video';
1065
912
  }
1066
- else if (message.ptvMessage) {
1067
- return 'video';
1068
- }
1069
913
  else if (message.audioMessage) {
1070
914
  return message.audioMessage.ptt ? 'ptt' : 'audio';
1071
915
  }
@@ -1084,9 +928,6 @@ export const makeMessagesSocket = (config) => {
1084
928
  else if (message.stickerMessage) {
1085
929
  return 'sticker';
1086
930
  }
1087
- else if (message.stickerPackMessage) {
1088
- return 'sticker_pack';
1089
- }
1090
931
  else if (message.listMessage) {
1091
932
  return 'list';
1092
933
  }
@@ -1110,8 +951,8 @@ export const makeMessagesSocket = (config) => {
1110
951
  }
1111
952
  return '';
1112
953
  };
1113
- const getPrivacyTokens = async (jids) => {
1114
- const t = unixTimestampSeconds().toString();
954
+ const issuePrivacyTokens = async (jids, timestamp) => {
955
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1115
956
  const result = await query({
1116
957
  tag: 'iq',
1117
958
  attrs: {
@@ -1138,73 +979,28 @@ export const makeMessagesSocket = (config) => {
1138
979
  };
1139
980
  const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1140
981
  const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1141
- // ── Button type helpers (ported from itsukichan) ──────────────────────────
1142
- const getButtonType = (message) => {
1143
- if (message.listMessage) return 'list';
1144
- if (message.buttonsMessage) return 'buttons';
1145
- if (message.templateMessage) return 'template';
1146
- if (message.interactiveMessage?.nativeFlowMessage) return 'native_flow';
1147
- if (message.interactiveMessage?.shopStorefrontMessage) return 'shop';
1148
- if (message.interactiveMessage?.collectionMessage) return 'collection';
1149
- if (message.interactiveMessage?.carouselMessage) return 'carousel';
1150
- if (message.interactiveMessage) return 'interactive';
1151
- return null;
1152
- };
1153
- const getButtonArgs = (message) => {
1154
- const nativeFlow = message.interactiveMessage?.nativeFlowMessage;
1155
- const firstButtonName = nativeFlow?.buttons?.[0]?.name;
1156
- const nativeFlowSpecials = [
1157
- 'mpm', 'cta_catalog', 'send_location',
1158
- 'call_permission_request', 'wa_payment_transaction_details',
1159
- 'automated_greeting_message_view_catalog'
1160
- ];
1161
- const ts = unixTimestampSeconds().toString();
1162
- const bizBase = { actual_actors: '2', host_storage: '2', privacy_mode_ts: ts };
1163
- const qualityControl = { tag: 'quality_control', attrs: { source_type: 'third_party' } };
1164
- if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
1165
- return {
1166
- tag: 'biz',
1167
- attrs: { native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName }
1168
- };
1169
- } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1170
- return {
1171
- tag: 'biz', attrs: bizBase,
1172
- content: [{
1173
- tag: 'interactive', attrs: { type: 'native_flow', v: '1' },
1174
- content: [{ tag: 'native_flow', attrs: { v: '2', name: firstButtonName } }]
1175
- }, qualityControl]
1176
- };
1177
- } else if (nativeFlow || message.buttonsMessage || message.templateMessage || message.interactiveMessage) {
1178
- // All interactive types in groups use native_flow biz node
1179
- // This covers: nativeFlowMessage, buttonsMessage→interactiveMessage,
1180
- // templateMessage→interactiveMessage, and direct interactiveMessage
1181
- return {
1182
- tag: 'biz', attrs: bizBase,
1183
- content: [{
1184
- tag: 'interactive', attrs: { type: 'native_flow', v: '1' },
1185
- content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
1186
- }, qualityControl]
1187
- };
1188
- } else if (message.listMessage) {
1189
- // Standalone listMessage (private chat) keeps the list biz node
1190
- return {
1191
- tag: 'biz', attrs: bizBase,
1192
- content: [{ tag: 'list', attrs: { v: '2', type: 'product_list' } }, qualityControl]
1193
- };
1194
- } else {
1195
- return { tag: 'biz', attrs: bizBase };
982
+ registerSocketEndHandler(() => {
983
+ if (!config.userDevicesCache && userDevicesCache.close) {
984
+ userDevicesCache.close();
1196
985
  }
1197
- };
1198
- // ── End button type helpers ───────────────────────────────────────────────
986
+ mediaConn = undefined;
987
+ if (messageRetryManager) {
988
+ messageRetryManager.clear();
989
+ }
990
+ });
1199
991
  return {
1200
992
  ...sock,
1201
- getPrivacyTokens,
993
+ userDevicesCache,
994
+ devicesMutex,
995
+ issuePrivacyTokens,
1202
996
  assertSessions,
1203
997
  relayMessage,
1204
998
  sendReceipt,
1205
999
  sendReceipts,
1206
1000
  readMessages,
1207
1001
  refreshMediaConn,
1002
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1003
+ getMediaHost: () => mediaHost,
1208
1004
  waUploadToServer,
1209
1005
  fetchPrivacySettings,
1210
1006
  sendPeerDataOperationMessage,
@@ -1237,7 +1033,7 @@ export const makeMessagesSocket = (config) => {
1237
1033
  });
1238
1034
  }
1239
1035
  content.directPath = media.directPath;
1240
- content.url = getUrlFromDirectPath(content.directPath);
1036
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1241
1037
  logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1242
1038
  }
1243
1039
  catch (err) {
@@ -1254,259 +1050,8 @@ export const makeMessagesSocket = (config) => {
1254
1050
  ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1255
1051
  return message;
1256
1052
  },
1257
- resize: async (media, width, height) => {
1258
- const { getStream, toBuffer } = await import('../Utils/messages-media.js');
1259
- let sharp;
1260
- try { sharp = (await import('sharp')).default; } catch (_) {}
1261
- if (!sharp) throw new Error('sharp is required for resize');
1262
- const { stream } = await getStream(media);
1263
- const buf = await toBuffer(stream);
1264
- return sharp(buf).resize(width, height, { fit: 'cover' }).toBuffer();
1265
- },
1266
- sendStatusMentions: async (content, jids = []) => {
1267
- const userJid = jidNormalizedUser(authState.creds.me.id);
1268
- let allUsers = new Set();
1269
- allUsers.add(userJid);
1270
-
1271
- for (const id of jids) {
1272
- const isGroup = isJidGroup(id);
1273
- const isPrivate = isJidUser(id);
1274
- if (isGroup) {
1275
- try {
1276
- const metadata = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1277
- const participants = metadata.participants.map(p => jidNormalizedUser(p.id));
1278
- participants.forEach(j => allUsers.add(j));
1279
- } catch (error) {
1280
- logger.error(`Error getting metadata for group ${id}: ${error}`);
1281
- }
1282
- } else if (isPrivate) {
1283
- allUsers.add(jidNormalizedUser(id));
1284
- }
1285
- }
1286
-
1287
- const uniqueUsers = Array.from(allUsers);
1288
- const getRandomHexColor = () => '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
1289
-
1290
- const isMedia = content.image || content.video || content.audio;
1291
- const isAudio = !!content.audio;
1292
-
1293
- const messageContent = { ...content };
1294
-
1295
- if (isMedia && !isAudio) {
1296
- if (messageContent.text) {
1297
- messageContent.caption = messageContent.text;
1298
- delete messageContent.text;
1299
- }
1300
- delete messageContent.ptt;
1301
- delete messageContent.font;
1302
- delete messageContent.backgroundColor;
1303
- delete messageContent.textColor;
1304
- }
1305
- if (isAudio) {
1306
- delete messageContent.text;
1307
- delete messageContent.caption;
1308
- delete messageContent.font;
1309
- delete messageContent.textColor;
1310
- }
1311
-
1312
- const font = !isMedia ? (content.font ?? Math.floor(Math.random() * 9)) : undefined;
1313
- const textColor = !isMedia ? (content.textColor ?? getRandomHexColor()) : undefined;
1314
- const backgroundColor = (!isMedia || isAudio) ? (content.backgroundColor ?? getRandomHexColor()) : undefined;
1315
- const ptt = isAudio ? (typeof content.ptt === 'boolean' ? content.ptt : true) : undefined;
1316
-
1317
- let msg;
1318
- let mediaHandle;
1319
- try {
1320
- msg = await generateWAMessage(STORIES_JID, messageContent, {
1321
- logger,
1322
- userJid,
1323
- getUrlInfo: text => getUrlInfo(text, {
1324
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1325
- fetchOpts: { timeout: 3000 },
1326
- logger,
1327
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1328
- }),
1329
- upload: async (encFilePath, opts) => {
1330
- const up = await waUploadToServer(encFilePath, { ...opts });
1331
- mediaHandle = up.handle;
1332
- return up;
1333
- },
1334
- mediaCache: config.mediaCache,
1335
- options: config.options,
1336
- font,
1337
- textColor,
1338
- backgroundColor,
1339
- ptt
1340
- });
1341
- } catch (error) {
1342
- logger.error(`Error generating status message: ${error}`);
1343
- throw error;
1344
- }
1345
-
1346
- await relayMessage(STORIES_JID, msg.message, {
1347
- messageId: msg.key.id,
1348
- statusJidList: uniqueUsers,
1349
- additionalNodes: [{
1350
- tag: 'meta',
1351
- attrs: {},
1352
- content: [{
1353
- tag: 'mentioned_users',
1354
- attrs: {},
1355
- content: jids.map(jid => ({
1356
- tag: 'to',
1357
- attrs: { jid: jidNormalizedUser(jid) }
1358
- }))
1359
- }]
1360
- }]
1361
- });
1362
-
1363
- for (const id of jids) {
1364
- try {
1365
- const normalizedId = jidNormalizedUser(id);
1366
- const isPrivate = isJidUser(normalizedId);
1367
- const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage';
1368
- const protocolMessage = {
1369
- [type]: {
1370
- message: {
1371
- protocolMessage: {
1372
- key: msg.key,
1373
- type: 25
1374
- }
1375
- }
1376
- },
1377
- messageContextInfo: {
1378
- messageSecret: randomBytes(32)
1379
- }
1380
- };
1381
- const statusMsg = await generateWAMessageFromContent(normalizedId, protocolMessage, {});
1382
- await relayMessage(normalizedId, statusMsg.message, {
1383
- additionalNodes: [{
1384
- tag: 'meta',
1385
- attrs: isPrivate
1386
- ? { is_status_mention: 'true' }
1387
- : { is_group_status_mention: 'true' }
1388
- }]
1389
- });
1390
- await delay(2000);
1391
- } catch (error) {
1392
- logger.error(`Error sending status mention to ${id}: ${error}`);
1393
- }
1394
- }
1395
-
1396
- return msg;
1397
- },
1398
1053
  sendMessage: async (jid, content, options = {}) => {
1399
1054
  const userJid = authState.creds.me.id;
1400
- // ── Normalize: buttons[].nativeFlowInfo -> interactiveButtons ──────
1401
- if (
1402
- typeof content === 'object' &&
1403
- Array.isArray(content.buttons) &&
1404
- content.buttons.length > 0 &&
1405
- content.buttons.some(b => b.nativeFlowInfo)
1406
- ) {
1407
- const interactiveButtons = content.buttons.map(b => {
1408
- if (b.nativeFlowInfo) {
1409
- return {
1410
- name: b.nativeFlowInfo.name,
1411
- buttonParamsJson: b.nativeFlowInfo.paramsJson || '{}'
1412
- };
1413
- }
1414
- return {
1415
- name: 'quick_reply',
1416
- buttonParamsJson: JSON.stringify({
1417
- display_text: b.buttonText?.displayText || b.buttonId || 'Button',
1418
- id: b.buttonId || b.buttonText?.displayText || 'btn'
1419
- })
1420
- };
1421
- });
1422
- const { buttons, headerType, viewOnce, ...rest } = content;
1423
- content = { ...rest, interactiveButtons };
1424
- }
1425
- // ── Interactive Button (sendButton logic) ──────────────────────────
1426
- if (typeof content === 'object' && Array.isArray(content.interactiveButtons) && content.interactiveButtons.length > 0) {
1427
- const {
1428
- text = '',
1429
- caption = '',
1430
- title = '',
1431
- footer = '',
1432
- interactiveButtons,
1433
- hasMediaAttachment = false,
1434
- image = null,
1435
- video = null,
1436
- document = null,
1437
- mimetype = null,
1438
- jpegThumbnail = null,
1439
- location = null,
1440
- product = null,
1441
- businessOwnerJid = null,
1442
- externalAdReply = null,
1443
- } = content;
1444
- // Normalize buttons
1445
- const processedButtons = [];
1446
- for (let i = 0; i < interactiveButtons.length; i++) {
1447
- const btn = interactiveButtons[i];
1448
- if (!btn || typeof btn !== 'object') throw new Error(`interactiveButtons[${i}] must be an object`);
1449
- if (btn.name && btn.buttonParamsJson) { processedButtons.push(btn); continue; }
1450
- if (btn.id || btn.text || btn.displayText) {
1451
- processedButtons.push({ name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: btn.text || btn.displayText || `Button ${i + 1}`, id: btn.id || `quick_${i + 1}` }) });
1452
- continue;
1453
- }
1454
- if (btn.buttonId && btn.buttonText?.displayText) {
1455
- processedButtons.push({ name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: btn.buttonText.displayText, id: btn.buttonId }) });
1456
- continue;
1457
- }
1458
- throw new Error(`interactiveButtons[${i}] has invalid shape`);
1459
- }
1460
- let messageContent = {};
1461
- // Header
1462
- if (image) {
1463
- const mi = Buffer.isBuffer(image) ? { image } : { image: { url: typeof image === 'object' ? image.url : image } };
1464
- const pm = await prepareWAMessageMedia(mi, { upload: waUploadToServer });
1465
- messageContent.header = { title: title || '', hasMediaAttachment: true, imageMessage: pm.imageMessage };
1466
- } else if (video) {
1467
- const mi = Buffer.isBuffer(video) ? { video } : { video: { url: typeof video === 'object' ? video.url : video } };
1468
- const pm = await prepareWAMessageMedia(mi, { upload: waUploadToServer });
1469
- messageContent.header = { title: title || '', hasMediaAttachment: true, videoMessage: pm.videoMessage };
1470
- } else if (document) {
1471
- const mi = Buffer.isBuffer(document) ? { document } : { document: { url: typeof document === 'object' ? document.url : document } };
1472
- if (mimetype && typeof mi.document === 'object') mi.document.mimetype = mimetype;
1473
- if (jpegThumbnail) {
1474
- const thumb = Buffer.isBuffer(jpegThumbnail) ? jpegThumbnail : await (async () => { try { const r = await fetch(jpegThumbnail); return Buffer.from(await r.arrayBuffer()); } catch { return undefined; } })();
1475
- if (thumb) mi.document.jpegThumbnail = thumb;
1476
- }
1477
- const pm = await prepareWAMessageMedia(mi, { upload: waUploadToServer });
1478
- messageContent.header = { title: title || '', hasMediaAttachment: true, documentMessage: pm.documentMessage };
1479
- } else if (location && typeof location === 'object') {
1480
- messageContent.header = { title: title || location.name || 'Location', hasMediaAttachment: false, locationMessage: { degreesLatitude: location.degreesLatitude || location.degressLatitude || 0, degreesLongitude: location.degreesLongitude || location.degressLongitude || 0, name: location.name || '', address: location.address || '' } };
1481
- } else if (product && typeof product === 'object') {
1482
- let productImageMessage = null;
1483
- if (product.productImage) {
1484
- const mi = Buffer.isBuffer(product.productImage) ? { image: product.productImage } : { image: { url: typeof product.productImage === 'object' ? product.productImage.url : product.productImage } };
1485
- const pm = await prepareWAMessageMedia(mi, { upload: waUploadToServer });
1486
- productImageMessage = pm.imageMessage;
1487
- }
1488
- messageContent.header = { title: title || product.title || 'Product', hasMediaAttachment: false, productMessage: { product: { productImage: productImageMessage, productId: product.productId || '', title: product.title || '', description: product.description || '', currencyCode: product.currencyCode || 'USD', priceAmount1000: parseInt(product.priceAmount1000) || 0, retailerId: product.retailerId || '', url: product.url || '', productImageCount: product.productImageCount || 1 }, businessOwnerJid: businessOwnerJid || product.businessOwnerJid || userJid } };
1489
- } else if (title) {
1490
- messageContent.header = { title, hasMediaAttachment: false };
1491
- }
1492
- const hasMedia = !!(image || video || document || location || product);
1493
- const bodyText = hasMedia ? caption : text || caption;
1494
- if (bodyText) messageContent.body = { text: bodyText };
1495
- if (footer) messageContent.footer = { text: footer };
1496
- messageContent.nativeFlowMessage = { buttons: processedButtons };
1497
- // Context info
1498
- if (externalAdReply && typeof externalAdReply === 'object') {
1499
- messageContent.contextInfo = { externalAdReply: { title: externalAdReply.title || '', body: externalAdReply.body || '', mediaType: externalAdReply.mediaType || 1, sourceUrl: externalAdReply.sourceUrl || externalAdReply.url || '', thumbnailUrl: externalAdReply.thumbnailUrl || externalAdReply.thumbnail || '', renderLargerThumbnail: externalAdReply.renderLargerThumbnail || false, showAdAttribution: externalAdReply.showAdAttribution !== false, containsAutoReply: externalAdReply.containsAutoReply || false, ...(externalAdReply.mediaUrl && { mediaUrl: externalAdReply.mediaUrl }), ...(Buffer.isBuffer(externalAdReply.thumbnail) && { thumbnail: externalAdReply.thumbnail }), ...(externalAdReply.jpegThumbnail && { jpegThumbnail: externalAdReply.jpegThumbnail }) }, ...(options.mentionedJid && { mentionedJid: options.mentionedJid }) };
1500
- } else if (options.mentionedJid) {
1501
- messageContent.contextInfo = { mentionedJid: options.mentionedJid };
1502
- }
1503
- const payload = proto.Message.InteractiveMessage.create(messageContent);
1504
- const msg = generateWAMessageFromContent(jid, { viewOnceMessage: { message: { interactiveMessage: payload } } }, { userJid, quoted: options?.quoted || null });
1505
- const additionalNodes = [{ tag: 'biz', attrs: {}, content: [{ tag: 'interactive', attrs: { type: 'native_flow', v: '1' }, content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }] }] }];
1506
- await relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes });
1507
- return msg;
1508
- }
1509
- // ── End Interactive Button ─────────────────────────────────────────
1510
1055
  if (typeof content === 'object' &&
1511
1056
  'disappearingMessagesInChat' in content &&
1512
1057
  typeof content['disappearingMessagesInChat'] !== 'undefined' &&
@@ -1520,7 +1065,6 @@ export const makeMessagesSocket = (config) => {
1520
1065
  await groupToggleEphemeral(jid, value);
1521
1066
  }
1522
1067
  else {
1523
- let mediaHandle;
1524
1068
  const fullMsg = await generateWAMessage(jid, content, {
1525
1069
  logger,
1526
1070
  userJid,
@@ -1536,36 +1080,12 @@ export const makeMessagesSocket = (config) => {
1536
1080
  //TODO: CACHE
1537
1081
  getProfilePicUrl: sock.profilePictureUrl,
1538
1082
  getCallLink: sock.createCallLink,
1539
- newsletter: _isNewsletterJid(jid),
1540
- upload: async (encFilePath, opts) => {
1541
- const up = await waUploadToServer(encFilePath, { ...opts, newsletter: _isNewsletterJid(jid) });
1542
- mediaHandle = up.handle;
1543
- return up;
1544
- },
1083
+ upload: waUploadToServer,
1545
1084
  mediaCache: config.mediaCache,
1546
1085
  options: config.options,
1547
1086
  messageId: generateMessageIDV2(sock.user?.id),
1548
1087
  ...options
1549
1088
  });
1550
- if (content?.audio && options?.contextInfo) {
1551
- const msgContent = fullMsg.message;
1552
- if (msgContent?.audioMessage) {
1553
- msgContent.audioMessage.contextInfo = options.contextInfo;
1554
- }
1555
- }
1556
- // Extract handle from newsletter upload (set by prepareWAMessageMedia)
1557
- if (!mediaHandle) {
1558
- const msgContent = fullMsg.message;
1559
- const msgTypes = ['audioMessage','imageMessage','videoMessage','documentMessage','stickerMessage'];
1560
- for (const t of msgTypes) {
1561
- if (msgContent?.[t]?._uploadHandle) {
1562
- mediaHandle = msgContent[t]._uploadHandle;
1563
-
1564
- delete msgContent[t]._uploadHandle;
1565
- break;
1566
- }
1567
- }
1568
- }
1569
1089
  const isEventMsg = 'event' in content && !!content.event;
1570
1090
  const isDeleteMsg = 'delete' in content && !!content.delete;
1571
1091
  const isEditMsg = 'edit' in content && !!content.edit;
@@ -1605,22 +1125,12 @@ export const makeMessagesSocket = (config) => {
1605
1125
  }
1606
1126
  });
1607
1127
  }
1608
- // Auto-attach biz node for button/list/interactive messages
1609
- const buttonType = getButtonType(fullMsg.message);
1610
- if (buttonType) {
1611
- const btnNode = getButtonArgs(fullMsg.message);
1612
- if (btnNode) additionalNodes.push(btnNode);
1613
- }
1614
- if (mediaHandle) {
1615
- additionalAttributes['media_id'] = mediaHandle;
1616
- }
1617
1128
  await relayMessage(jid, fullMsg.message, {
1618
1129
  messageId: fullMsg.key.id,
1619
1130
  useCachedGroupMetadata: options.useCachedGroupMetadata,
1620
1131
  additionalAttributes,
1621
1132
  statusJidList: options.statusJidList,
1622
- additionalNodes,
1623
- AI: options.ai || false
1133
+ additionalNodes
1624
1134
  });
1625
1135
  if (config.emitOwnEvents) {
1626
1136
  process.nextTick(async () => {