@hiroosy/baileys-lite 0.0.4 → 0.3.1

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 (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +658 -10
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +716 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -1,9 +1,5 @@
1
- /**
2
- * Message-send socket layer (wraps makeNewsletterSocket).
3
- * Faithful port of upstream Socket/messages-send.js: relayMessage builds the exact stanza WhatsApp
4
- * expects (participants, device-identity, phash, DSM for own devices, tctoken, reporting token).
5
- * messages-recv.js (wraps this) lives in the sibling file messages-recv.js.
6
- */
1
+ import { randomBytes } from 'node:crypto'
2
+ import { AIRichBuilder } from '../foundation/ai-rich.js'
7
3
  import { Boom } from '../foundation/boom.js'
8
4
  import { Cache } from '../foundation/cache.js'
9
5
  import { makeKeyedMutex, makeMutex } from '../foundation/concurrency.js'
@@ -28,8 +24,10 @@ import {
28
24
  aggregateMessageKeysNotFromMe,
29
25
  assertMediaContent,
30
26
  generateWAMessage,
27
+ generateWAMessageFromContent,
31
28
  hasValidAlbumMedia,
32
- normalizeMessageContent
29
+ normalizeMessageContent,
30
+ shouldIncludeBizBinaryNode
33
31
  } from '../utils/message-compose.js'
34
32
  import { decryptMediaRetryData, DEF_MEDIA_HOST, encryptMediaRetryRequest, getStatusCodeForMediaRetry, getUrlFromDirectPath, getUrlInfo, getWAUploadToServer } from '../utils/media.js'
35
33
  import { MessageRetryManager } from '../utils/message-processing.js'
@@ -38,11 +36,13 @@ import {
38
36
  areJidsSameUser,
39
37
  getBinaryNodeChild,
40
38
  getBinaryNodeChildren,
39
+ getBizBinaryNode,
41
40
  isHostedLidUser,
42
41
  isHostedPnUser,
43
42
  isJidBot,
44
43
  isJidGroup,
45
44
  isJidMetaAI,
45
+ isJidNewsletter,
46
46
  isLidUser,
47
47
  isPnUser,
48
48
  jidDecode,
@@ -55,29 +55,27 @@ import { USyncQuery, USyncUser } from './usync.js'
55
55
  import { makeNewsletterSocket } from './groups-newsletter.js'
56
56
 
57
57
  export const makeMessagesSocket = (config) => {
58
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
58
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
59
+ let currentPatchMessageBeforeSending = config.patchMessageBeforeSending;
60
+ const patchMessageBeforeSending = (message, jids) => currentPatchMessageBeforeSending(message, jids);
59
61
  const sock = makeNewsletterSocket(config);
60
62
  const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
61
63
  const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
62
- /**
63
- * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
64
- * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
65
- * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
66
- */
64
+
67
65
  const inFlightTcTokenIssuance = new Set();
68
66
  const userDevicesCache = config.userDevicesCache ||
69
67
  new Cache({
70
- ttl: DEFAULT_CACHE_TTLS.USER_DEVICES * 1000, // 5 minutes
68
+ ttl: DEFAULT_CACHE_TTLS.USER_DEVICES * 1000,
71
69
  max: 1000
72
70
  });
73
- /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
71
+
74
72
  const devicesMutex = makeMutex();
75
- // Initialize message retry manager if enabled
73
+
76
74
  const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
77
- // Prevent race conditions in Signal session encryption by user
75
+
78
76
  const encryptionMutex = makeKeyedMutex();
79
77
  let mediaConn;
80
- /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
78
+
81
79
  let mediaHost = DEF_MEDIA_HOST;
82
80
  const refreshMediaConn = async (forceGet = false) => {
83
81
  const media = await mediaConn;
@@ -93,7 +91,7 @@ export const makeMessagesSocket = (config) => {
93
91
  content: [{ tag: 'media_conn', attrs: {} }]
94
92
  });
95
93
  const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
96
- // TODO: explore full length of data that whatsapp provides
94
+
97
95
  const node = {
98
96
  hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
99
97
  hostname: attrs.hostname,
@@ -112,10 +110,7 @@ export const makeMessagesSocket = (config) => {
112
110
  }
113
111
  return mediaConn;
114
112
  };
115
- /**
116
- * generic send receipt function
117
- * used for receipts of phone call, read, delivery etc.
118
- * */
113
+
119
114
  const sendReceipt = async (jid, participant, messageIds, type) => {
120
115
  if (!messageIds || messageIds.length === 0) {
121
116
  throw new Boom('missing ids in receipt');
@@ -159,21 +154,21 @@ export const makeMessagesSocket = (config) => {
159
154
  logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
160
155
  await sendNode(node);
161
156
  };
162
- /** Correctly bulk send receipts to multiple chats, participants */
157
+
163
158
  const sendReceipts = async (keys, type) => {
164
159
  const recps = aggregateMessageKeysNotFromMe(keys);
165
160
  for (const { jid, participant, messageIds } of recps) {
166
161
  await sendReceipt(jid, participant, messageIds, type);
167
162
  }
168
163
  };
169
- /** Bulk read messages. Keys can be from different chats & participants */
164
+
170
165
  const readMessages = async (keys) => {
171
166
  const privacySettings = await fetchPrivacySettings();
172
- // based on privacy settings, we have to change the read type
167
+
173
168
  const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
174
169
  await sendReceipts(keys, readType);
175
170
  };
176
- /** Fetch all the devices we've to send a message to */
171
+
177
172
  const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
178
173
  const deviceResults = [];
179
174
  if (!useCache) {
@@ -236,16 +231,16 @@ export const makeMessagesSocket = (config) => {
236
231
  }
237
232
  const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
238
233
  for (const jid of toFetch) {
239
- query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
234
+ query.withUser(new USyncUser().withId(jid));
240
235
  }
241
236
  const result = await sock.executeUSyncQuery(query);
242
237
  if (result) {
243
- // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
238
+
244
239
  const lidResults = result.list.filter(a => !!a.lid);
245
240
  if (lidResults.length > 0) {
246
241
  logger.trace('Storing LID maps from device call');
247
242
  await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
248
- // Force-refresh sessions for newly mapped LIDs to align identity addressing
243
+
249
244
  try {
250
245
  const lids = lidResults.map(a => a.lid);
251
246
  if (lids.length) {
@@ -262,10 +257,10 @@ export const makeMessagesSocket = (config) => {
262
257
  deviceMap[item.user] = deviceMap[item.user] || [];
263
258
  deviceMap[item.user]?.push(item);
264
259
  }
265
- // Process each user's devices as a group for bulk LID migration
260
+
266
261
  for (const [user, userDevices] of Object.entries(deviceMap)) {
267
262
  const isLidUser = requestedLidUsers.has(user);
268
- // Process all devices for this user
263
+
269
264
  for (const item of userDevices) {
270
265
  const finalJid = isLidUser
271
266
  ? jidEncode(user, item.server, item.device)
@@ -284,7 +279,7 @@ export const makeMessagesSocket = (config) => {
284
279
  }
285
280
  await devicesMutex.mutex(async () => {
286
281
  if (userDevicesCache.mset) {
287
- // if the cache supports mset, we can set all devices in one go
282
+
288
283
  await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
289
284
  }
290
285
  else {
@@ -312,9 +307,7 @@ export const makeMessagesSocket = (config) => {
312
307
  }
313
308
  return deviceResults;
314
309
  };
315
- /**
316
- * Update Member Label
317
- */
310
+
318
311
  const updateMemberLabel = (jid, memberLabel) => {
319
312
  return relayMessage(jid, {
320
313
  protocolMessage: {
@@ -352,7 +345,7 @@ export const makeMessagesSocket = (config) => {
352
345
  jidsRequiringFetch.push(jid);
353
346
  }
354
347
  if (jidsRequiringFetch.length) {
355
- // LID if mapped, otherwise original
348
+
356
349
  const wireJids = [
357
350
  ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
358
351
  ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
@@ -384,7 +377,7 @@ export const makeMessagesSocket = (config) => {
384
377
  return didFetchNewSession;
385
378
  };
386
379
  const sendPeerDataOperationMessage = async (pdoMessage) => {
387
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
380
+
388
381
  if (!authState.creds.me?.id) {
389
382
  throw new Boom('Not authenticated');
390
383
  }
@@ -409,11 +402,11 @@ export const makeMessagesSocket = (config) => {
409
402
  });
410
403
  return msgId;
411
404
  };
412
- const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
405
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage, alreadyPatched = false) => {
413
406
  if (!recipientJids.length) {
414
407
  return { nodes: [], shouldIncludeDeviceIdentity: false };
415
408
  }
416
- const patched = await patchMessageBeforeSending(message, recipientJids);
409
+ const patched = alreadyPatched ? message : await patchMessageBeforeSending(message, recipientJids);
417
410
  const patchedMessages = Array.isArray(patched)
418
411
  ? patched
419
412
  : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
@@ -423,7 +416,7 @@ export const makeMessagesSocket = (config) => {
423
416
  const meLidUser = meLid ? jidDecode(meLid)?.user : null;
424
417
  const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
425
418
  try {
426
- if (!jid)
419
+ if (!jid || !patchedMessage)
427
420
  return null;
428
421
  let msgToEncrypt = patchedMessage;
429
422
  if (dsmMessage) {
@@ -460,6 +453,7 @@ export const makeMessagesSocket = (config) => {
460
453
  }
461
454
  catch (err) {
462
455
  logger.error({ jid, err }, 'Failed to encrypt for recipient');
456
+ console.error('[sPR-DEBUG] encrypt failed for', jid, err?.message, err?.stack?.split('\n')[1]);
463
457
  return null;
464
458
  }
465
459
  });
@@ -469,7 +463,7 @@ export const makeMessagesSocket = (config) => {
469
463
  }
470
464
  return { nodes, shouldIncludeDeviceIdentity };
471
465
  };
472
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
466
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList }) => {
473
467
  const meId = assertMeId(authState.creds);
474
468
  const meLid = authState.creds.me?.lid;
475
469
  const isRetryResend = Boolean(participant?.jid);
@@ -510,16 +504,20 @@ export const makeMessagesSocket = (config) => {
510
504
  });
511
505
  }
512
506
  await authState.keys.transaction(async () => {
513
- const mediaType = getMediaType(message);
507
+ const innerMessage = normalizeMessageContent(message);
508
+ const mediaType = getMediaType(innerMessage);
514
509
  if (mediaType) {
515
510
  extraAttrs['mediatype'] = mediaType;
516
511
  }
517
512
  if (isNewsletter) {
518
513
  const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
519
514
  const bytes = encodeNewsletterMessage(patched);
515
+ if (additionalNodes && additionalNodes.length > 0) {
516
+ binaryNodeContent.push(...additionalNodes);
517
+ }
520
518
  binaryNodeContent.push({
521
519
  tag: 'plaintext',
522
- attrs: {},
520
+ attrs: extraAttrs,
523
521
  content: bytes
524
522
  });
525
523
  const stanza = {
@@ -527,7 +525,7 @@ export const makeMessagesSocket = (config) => {
527
525
  attrs: {
528
526
  to: jid,
529
527
  id: msgId,
530
- type: getMessageType(message),
528
+ type: getMessageType(innerMessage),
531
529
  ...(additionalAttributes || {})
532
530
  },
533
531
  content: binaryNodeContent
@@ -536,26 +534,48 @@ export const makeMessagesSocket = (config) => {
536
534
  await sendNode(stanza);
537
535
  return;
538
536
  }
539
- if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
540
- extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
537
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
538
+ const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
539
+ const isPollUpdate = innerMessage?.pollUpdateMessage;
540
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
541
+ const metaAttrs = {};
542
+ if (isNeedMetaAttrs) {
543
+ metaAttrs.content_type = 'add_on';
544
+ }
545
+ if (isPollUpdate && !isGroupStatus) {
546
+ metaAttrs.polltype = 'vote';
547
+ }
548
+ if (isGroupStatus) {
549
+ metaAttrs.is_group_status = 'true';
550
+ }
551
+ binaryNodeContent.push({
552
+ tag: 'meta',
553
+ attrs: metaAttrs,
554
+ content: undefined
555
+ });
556
+ }
557
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
558
+ extraAttrs['decrypt-fail'] = 'hide';
559
+ }
560
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
561
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
541
562
  }
542
563
  if (isGroupOrStatus && !isRetryResend) {
543
564
  const [groupData, senderKeyMap] = await Promise.all([
544
565
  (async () => {
545
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
566
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
546
567
  if (groupData && Array.isArray(groupData?.participants)) {
547
568
  logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
548
569
  }
549
570
  else if (!isStatus) {
550
- groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
571
+ groupData = await groupMetadata(jid);
551
572
  }
552
573
  return groupData;
553
574
  })(),
554
575
  (async () => {
555
576
  if (!participant && !isStatus) {
556
- // what if sender memory is less accurate than the cached metadata
557
- // on participant change in group, we should do sender memory manipulation
558
- const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
577
+
578
+ const result = await authState.keys.get('sender-key-memory', [jid]);
559
579
  return result[jid] || {};
560
580
  }
561
581
  return {};
@@ -579,57 +599,106 @@ export const makeMessagesSocket = (config) => {
579
599
  addressing_mode: groupData?.addressingMode || 'lid'
580
600
  };
581
601
  }
582
- const patched = await patchMessageBeforeSending(message);
602
+ const patched = await patchMessageBeforeSending(message, isGroup ? devices.map(d => d.jid) : undefined);
583
603
  if (Array.isArray(patched)) {
584
- throw new Boom('Per-jid patching is not supported in groups');
585
- }
586
- const bytes = encodeWAMessage(patched);
587
- reportingMessage = patched;
588
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
589
- const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
590
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
591
- group: destinationJid,
592
- data: bytes,
593
- meId: groupSenderIdentity
594
- });
595
- const senderKeyRecipients = [];
596
- for (const device of devices) {
597
- const deviceJid = device.jid;
598
- const hasKey = !!senderKeyMap[deviceJid];
599
- if ((!hasKey || !!participant) &&
600
- !isHostedLidUser(deviceJid) &&
601
- !isHostedPnUser(deviceJid) &&
602
- device.device !== 99) {
603
- //todo: revamp all this logic
604
- // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
605
- senderKeyRecipients.push(deviceJid);
606
- senderKeyMap[deviceJid] = true;
604
+
605
+ logger.debug({ jid, devices: devices.length }, 'per-jid group patch: skmsg+pkmsg hybrid');
606
+
607
+ const userMsgMap = new Map();
608
+ let fallbackPatchedMsg = message;
609
+ for (const { recipientJid, message: msg } of patched) {
610
+ if (!msg) continue;
611
+ const decoded = jidDecode(recipientJid);
612
+ if (decoded) userMsgMap.set(decoded.user, msg);
613
+ else fallbackPatchedMsg = msg;
614
+ }
615
+ if (!userMsgMap.size) fallbackPatchedMsg = patched.find(p => p.message)?.message || message;
616
+
617
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
618
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
619
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
620
+ group: destinationJid,
621
+ data: encodeWAMessage(fallbackPatchedMsg),
622
+ meId: groupSenderIdentity
623
+ });
624
+ reportingMessage = fallbackPatchedMsg;
625
+
626
+ const senderKeyRecipients = [];
627
+ for (const device of devices) {
628
+ const deviceJid = device.jid;
629
+ if ((!senderKeyMap[deviceJid] || !!participant) &&
630
+ !isHostedLidUser(deviceJid) && !isHostedPnUser(deviceJid) && device.device !== 99) {
631
+ senderKeyRecipients.push(deviceJid);
632
+ senderKeyMap[deviceJid] = true;
633
+ }
634
+ }
635
+ if (senderKeyRecipients.length) {
636
+ const senderKeyMsg = { senderKeyDistributionMessage: { axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage, groupId: destinationJid } };
637
+ await assertSessions(senderKeyRecipients);
638
+ const r = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
639
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || r.shouldIncludeDeviceIdentity;
640
+ participants.push(...r.nodes);
641
+ }
642
+ binaryNodeContent.push({ tag: 'enc', attrs: { v: '2', type: 'skmsg', ...extraAttrs }, content: ciphertext });
643
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
644
+
645
+ const customDevices = devices
646
+ .map(d => { const dec = jidDecode(d.jid); return dec && userMsgMap.has(dec.user) ? { recipientJid: d.jid, message: userMsgMap.get(dec.user) } : null; })
647
+ .filter(Boolean);
648
+ if (customDevices.length) {
649
+ await assertSessions(customDevices.map(d => d.recipientJid));
650
+ const r = await createParticipantNodes(customDevices.map(d => d.recipientJid), customDevices, extraAttrs, undefined, true);
651
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || r.shouldIncludeDeviceIdentity;
652
+ participants.push(...r.nodes);
607
653
  }
608
654
  }
609
- if (senderKeyRecipients.length) {
610
- logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
611
- const senderKeyMsg = {
612
- senderKeyDistributionMessage: {
613
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
614
- groupId: destinationJid
655
+ else {
656
+ const bytes = encodeWAMessage(patched);
657
+ reportingMessage = patched;
658
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
659
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
660
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
661
+ group: destinationJid,
662
+ data: bytes,
663
+ meId: groupSenderIdentity
664
+ });
665
+ const senderKeyRecipients = [];
666
+ for (const device of devices) {
667
+ const deviceJid = device.jid;
668
+ const hasKey = !!senderKeyMap[deviceJid];
669
+ if ((!hasKey || !!participant) &&
670
+ !isHostedLidUser(deviceJid) &&
671
+ !isHostedPnUser(deviceJid) &&
672
+ device.device !== 99) {
673
+
674
+ senderKeyRecipients.push(deviceJid);
675
+ senderKeyMap[deviceJid] = true;
615
676
  }
616
- };
617
- const senderKeySessionTargets = senderKeyRecipients;
618
- await assertSessions(senderKeySessionTargets);
619
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
620
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
621
- participants.push(...result.nodes);
677
+ }
678
+ if (senderKeyRecipients.length) {
679
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
680
+ const senderKeyMsg = {
681
+ senderKeyDistributionMessage: {
682
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
683
+ groupId: destinationJid
684
+ }
685
+ };
686
+ const senderKeySessionTargets = senderKeyRecipients;
687
+ await assertSessions(senderKeySessionTargets);
688
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
689
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
690
+ participants.push(...result.nodes);
691
+ }
692
+ binaryNodeContent.push({
693
+ tag: 'enc',
694
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
695
+ content: ciphertext
696
+ });
697
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
622
698
  }
623
- binaryNodeContent.push({
624
- tag: 'enc',
625
- attrs: { v: '2', type: 'skmsg', ...extraAttrs },
626
- content: ciphertext
627
- });
628
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
629
699
  }
630
700
  else {
631
- // ADDRESSING CONSISTENCY: Match own identity to conversation context
632
- // TODO: investigate if this is true
701
+
633
702
  let ownId = meId;
634
703
  if (isLid && meLid) {
635
704
  ownId = meLid;
@@ -650,7 +719,7 @@ export const makeMessagesSocket = (config) => {
650
719
  devices.push({
651
720
  user,
652
721
  device: 0,
653
- jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
722
+ jid: jidEncode(user, targetUserServer, 0)
654
723
  });
655
724
  if (user !== ownUser) {
656
725
  const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
@@ -662,13 +731,13 @@ export const makeMessagesSocket = (config) => {
662
731
  });
663
732
  }
664
733
  if (additionalAttributes?.['category'] !== 'peer') {
665
- // Clear placeholders and enumerate actual devices
734
+
666
735
  devices.length = 0;
667
- // Use conversation-appropriate sender identity
736
+
668
737
  const senderIdentity = isLid && meLid
669
738
  ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
670
739
  : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
671
- // Enumerate devices for sender and target with consistent addressing
740
+
672
741
  const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
673
742
  devices.push(...sessionDevices);
674
743
  logger.debug({
@@ -688,7 +757,7 @@ export const makeMessagesSocket = (config) => {
688
757
  logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
689
758
  continue;
690
759
  }
691
- // Check if this is our device (could match either PN or LID user)
760
+
692
761
  const isMe = user === mePnUser || user === meLidUser;
693
762
  if (isMe) {
694
763
  meRecipients.push(jid);
@@ -700,7 +769,7 @@ export const makeMessagesSocket = (config) => {
700
769
  }
701
770
  await assertSessions(allRecipients);
702
771
  const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
703
- // For own devices: use DSM if available (1:1 chats only)
772
+
704
773
  createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
705
774
  createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
706
775
  ]);
@@ -768,7 +837,7 @@ export const makeMessagesSocket = (config) => {
768
837
  if (additionalAttributes?.['category'] === 'peer') {
769
838
  const peerNode = participants[0]?.content?.[0];
770
839
  if (peerNode) {
771
- binaryNodeContent.push(peerNode); // push only enc
840
+ binaryNodeContent.push(peerNode);
772
841
  }
773
842
  }
774
843
  else {
@@ -784,14 +853,12 @@ export const makeMessagesSocket = (config) => {
784
853
  attrs: {
785
854
  id: msgId,
786
855
  to: destinationJid,
787
- type: getMessageType(message),
856
+ type: getMessageType(innerMessage),
788
857
  ...(additionalAttributes || {})
789
858
  },
790
859
  content: binaryNodeContent
791
860
  };
792
- // if the participant to send to is explicitly specified (generally retry recp)
793
- // ensure the message is only sent to that person
794
- // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
861
+
795
862
  if (participant) {
796
863
  if (isJidGroup(destinationJid)) {
797
864
  stanza.attrs.to = destinationJid;
@@ -840,19 +907,19 @@ export const makeMessagesSocket = (config) => {
840
907
  logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
841
908
  }
842
909
  }
843
- // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
910
+
844
911
  const isPeerMessage = additionalAttributes?.['category'] === 'peer';
845
912
  const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
846
- // Resolve destination to LID for tctoken storage — matches Signal session key pattern
913
+
847
914
  const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
848
915
  const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
849
916
  const existingTokenEntry = contactTcTokenData[tcTokenJid];
850
917
  let tcTokenBuffer = existingTokenEntry?.token;
851
- // Treat expired tokens the same as missing — clear from cache
918
+
852
919
  if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
853
920
  logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
854
921
  tcTokenBuffer = undefined;
855
- // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
922
+
856
923
  const cleared = existingTokenEntry?.senderTimestamp !== undefined
857
924
  ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
858
925
  : null;
@@ -871,15 +938,19 @@ export const makeMessagesSocket = (config) => {
871
938
  content: tcTokenBuffer
872
939
  });
873
940
  }
941
+ let alreadyHasBizNode = false;
874
942
  if (additionalNodes && additionalNodes.length > 0) {
875
- ;
876
943
  stanza.content.push(...additionalNodes);
944
+ alreadyHasBizNode = !addBizAttributes && additionalNodes.some(node => node.tag === 'biz');
945
+ }
946
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
947
+ const bizNode = getBizBinaryNode(innerMessage);
948
+ stanza.content.push(bizNode);
877
949
  }
878
950
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
879
951
  await sendNode(stanza);
880
- // Fire-and-forget: issue our token to the contact AFTER message send.
881
- // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
882
- const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
952
+
953
+ const isProtocolMsg = !!innerMessage?.protocolMessage;
883
954
  const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
884
955
  if (is1on1Send &&
885
956
  !isProtocolMsg &&
@@ -919,7 +990,7 @@ export const makeMessagesSocket = (config) => {
919
990
  inFlightTcTokenIssuance.delete(tcTokenJid);
920
991
  });
921
992
  }
922
- // Add message to retry cache if enabled
993
+
923
994
  if (messageRetryManager && !participant) {
924
995
  messageRetryManager.addRecentMessage(destinationJid, msgId, message);
925
996
  }
@@ -1034,7 +1105,7 @@ export const makeMessagesSocket = (config) => {
1034
1105
  messageRetryManager.clear();
1035
1106
  }
1036
1107
  });
1037
- return {
1108
+ const fullSock = {
1038
1109
  ...sock,
1039
1110
  userDevicesCache,
1040
1111
  devicesMutex,
@@ -1045,7 +1116,7 @@ export const makeMessagesSocket = (config) => {
1045
1116
  sendReceipts,
1046
1117
  readMessages,
1047
1118
  refreshMediaConn,
1048
- // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1119
+
1049
1120
  getMediaHost: () => mediaHost,
1050
1121
  waUploadToServer,
1051
1122
  fetchPrivacySettings,
@@ -1054,6 +1125,9 @@ export const makeMessagesSocket = (config) => {
1054
1125
  getUSyncDevices,
1055
1126
  messageRetryManager,
1056
1127
  updateMemberLabel,
1128
+
1129
+ getPatchMessageBeforeSending: () => currentPatchMessageBeforeSending,
1130
+ setPatchMessageBeforeSending: fn => { currentPatchMessageBeforeSending = fn; },
1057
1131
  updateMediaMessage: async (message) => {
1058
1132
  const content = assertMediaContent(message.message);
1059
1133
  const mediaKey = content.mediaKey;
@@ -1098,8 +1172,101 @@ export const makeMessagesSocket = (config) => {
1098
1172
  },
1099
1173
  sendMessage: async (jid, content, options = {}) => {
1100
1174
  const userJid = authState.creds.me.id;
1101
- if (typeof content === 'object' &&
1102
- 'disappearingMessagesInChat' in content &&
1175
+ if (Array.isArray(jid)) {
1176
+ const { delayMs = 1500 } = options;
1177
+ const allUsers = new Set();
1178
+ const fullMsg = await generateWAMessage('status@broadcast', content, {
1179
+ logger,
1180
+ userJid,
1181
+ upload: waUploadToServer,
1182
+ mediaCache: config.mediaCache,
1183
+ options: config.options,
1184
+ messageId: generateMessageIDV2(userJid),
1185
+ ...options
1186
+ });
1187
+ for (const id of jid) {
1188
+ if (isJidGroup(id)) {
1189
+ try {
1190
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1191
+ for (const participant of groupData.participants) {
1192
+ if (allUsers.has(participant.id))
1193
+ continue;
1194
+ allUsers.add(participant.id);
1195
+ }
1196
+ }
1197
+ catch (error) {
1198
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
1199
+ }
1200
+ }
1201
+ else if (!allUsers.has(id)) {
1202
+ allUsers.add(id);
1203
+ }
1204
+ }
1205
+ await relayMessage('status@broadcast', fullMsg.message, {
1206
+ messageId: fullMsg.key.id,
1207
+ statusJidList: Array.from(allUsers),
1208
+ additionalNodes: [
1209
+ {
1210
+ tag: 'meta',
1211
+ attrs: {},
1212
+ content: [
1213
+ {
1214
+ tag: 'mentioned_users',
1215
+ attrs: {},
1216
+ content: jid.map(id => ({
1217
+ tag: 'to',
1218
+ attrs: { jid: id },
1219
+ content: undefined
1220
+ }))
1221
+ }
1222
+ ]
1223
+ }
1224
+ ]
1225
+ });
1226
+ if (config.emitOwnEvents) {
1227
+ process.nextTick(async () => {
1228
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1229
+ });
1230
+ }
1231
+ for (const id of jid) {
1232
+ const isGroup = isJidGroup(id);
1233
+ const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1234
+ const mentionMsg = generateWAMessageFromContent(id, {
1235
+ messageContextInfo: {
1236
+ messageSecret: randomBytes(32)
1237
+ },
1238
+ [sendType]: {
1239
+ message: {
1240
+ protocolMessage: {
1241
+ key: fullMsg.key,
1242
+ type: 25
1243
+ }
1244
+ }
1245
+ }
1246
+ }, {
1247
+ userJid
1248
+ });
1249
+ await relayMessage(id, mentionMsg.message, {
1250
+ additionalNodes: [
1251
+ {
1252
+ tag: 'meta',
1253
+ attrs: isGroup ?
1254
+ { is_group_status_mention: 'true' } :
1255
+ { is_status_mention: 'true' },
1256
+ content: undefined
1257
+ }
1258
+ ]
1259
+ });
1260
+ if (config.emitOwnEvents) {
1261
+ process.nextTick(async () => {
1262
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1263
+ });
1264
+ }
1265
+ await delay(delayMs);
1266
+ }
1267
+ return fullMsg;
1268
+ }
1269
+ else if ('disappearingMessagesInChat' in content &&
1103
1270
  typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1104
1271
  isJidGroup(jid)) {
1105
1272
  const { disappearingMessagesInChat } = content;
@@ -1123,25 +1290,30 @@ export const makeMessagesSocket = (config) => {
1123
1290
  logger,
1124
1291
  uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1125
1292
  }),
1126
- //TODO: CACHE
1293
+
1127
1294
  getProfilePicUrl: sock.profilePictureUrl,
1128
1295
  getCallLink: sock.createCallLink,
1129
1296
  upload: waUploadToServer,
1130
1297
  mediaCache: config.mediaCache,
1131
1298
  options: config.options,
1132
- messageId: generateMessageIDV2(sock.user?.id),
1133
- ...options
1299
+ ...options,
1300
+ messageId: generateMessageIDV2(userJid)
1134
1301
  });
1302
+ const isNewsletter = isJidNewsletter(jid);
1135
1303
  const isEventMsg = 'event' in content && !!content.event;
1136
1304
  const isDeleteMsg = 'delete' in content && !!content.delete;
1137
1305
  const isEditMsg = 'edit' in content && !!content.edit;
1138
1306
  const isPinMsg = 'pin' in content && !!content.pin;
1139
- const isPollMessage = 'poll' in content && !!content.poll;
1140
- const additionalAttributes = {};
1141
- const additionalNodes = [];
1142
- // required for delete
1143
- if (isDeleteMsg) {
1144
- // if the chat is a group, and I am not the author, then delete the message as an admin
1307
+ const isKeepMsg = 'keep' in content && !!content.keep;
1308
+ const isPollMsg = 'poll' in content && !!content.poll;
1309
+ const isQuizMsg = 'poll' in content && !!content.poll?.pollType;
1310
+ const isAiMsg = 'ai' in content && !!content.ai;
1311
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
1312
+ const additionalAttributes = options.additionalAttributes || {};
1313
+ const additionalNodes = options.additionalNodes || [];
1314
+
1315
+ if (isDeleteMsg || isKeepMsg) {
1316
+
1145
1317
  if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1146
1318
  additionalAttributes.edit = '8';
1147
1319
  }
@@ -1150,17 +1322,22 @@ export const makeMessagesSocket = (config) => {
1150
1322
  }
1151
1323
  }
1152
1324
  else if (isEditMsg) {
1153
- additionalAttributes.edit = '1';
1325
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
1154
1326
  }
1155
1327
  else if (isPinMsg) {
1156
1328
  additionalAttributes.edit = '2';
1157
1329
  }
1158
- else if (isPollMessage) {
1330
+ else if (isPollMsg) {
1331
+ if (!isNewsletter && isQuizMsg) {
1332
+ throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
1333
+ }
1159
1334
  additionalNodes.push({
1160
1335
  tag: 'meta',
1161
1336
  attrs: {
1162
- polltype: 'creation'
1163
- }
1337
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
1338
+ contenttype: isPollMsg && isNewsletter ? 'text' : undefined
1339
+ },
1340
+ content: undefined
1164
1341
  });
1165
1342
  }
1166
1343
  else if (isEventMsg) {
@@ -1168,19 +1345,36 @@ export const makeMessagesSocket = (config) => {
1168
1345
  tag: 'meta',
1169
1346
  attrs: {
1170
1347
  event_type: 'creation'
1171
- }
1348
+ },
1349
+ content: undefined
1350
+ });
1351
+ }
1352
+
1353
+ else if (isAiMsg) {
1354
+ if (!(isPnUser(jid) || isLidUser(jid))) {
1355
+ throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
1356
+ }
1357
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1358
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1359
+ }
1360
+ additionalNodes.push({
1361
+ tag: 'bot',
1362
+ attrs: {
1363
+ biz_bot: '1'
1364
+ },
1365
+ content: undefined
1172
1366
  });
1367
+ delete content.ai;
1173
1368
  }
1174
1369
  await relayMessage(jid, fullMsg.message, {
1175
1370
  messageId: fullMsg.key.id,
1176
1371
  useCachedGroupMetadata: options.useCachedGroupMetadata,
1177
- additionalAttributes,
1372
+ addBizAttributes: isNeedBizAttrs,
1178
1373
  statusJidList: options.statusJidList,
1374
+ additionalAttributes,
1179
1375
  additionalNodes
1180
1376
  });
1181
- // A late <receipt type="retry"> for the pre-edit/pre-revoke message could
1182
- // otherwise resend stale content after this succeeds (see messageRetryManager
1183
- // in messages-recv.js). Only invalidate once the edit/revoke actually went out.
1377
+
1184
1378
  if (messageRetryManager && (isDeleteMsg || isEditMsg)) {
1185
1379
  const targetKey = isDeleteMsg ? content.delete : content.edit;
1186
1380
  if (targetKey?.id) {
@@ -1192,11 +1386,50 @@ export const makeMessagesSocket = (config) => {
1192
1386
  await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1193
1387
  });
1194
1388
  }
1389
+
1390
+ if ('album' in content) {
1391
+ const { delayMs = 1500 } = options;
1392
+ for (const albumMedia of content.album) {
1393
+ const albumMsg = await generateWAMessage(jid, albumMedia, {
1394
+ logger,
1395
+ userJid,
1396
+ upload: waUploadToServer,
1397
+ mediaCache: config.mediaCache,
1398
+ options: config.options,
1399
+ ...options,
1400
+ messageId: generateMessageIDV2(userJid)
1401
+ });
1402
+ if (!hasValidAlbumMedia(normalizeMessageContent(albumMsg.message))) {
1403
+ throw new Boom('Invalid message type for album', { statusCode: 400 });
1404
+ }
1405
+ albumMsg.message.messageContextInfo ||= {};
1406
+ albumMsg.message.messageContextInfo.messageAssociation = {
1407
+ parentMessageKey: fullMsg.key,
1408
+ associationType: AssociationType.MEDIA_ALBUM
1409
+ };
1410
+ await relayMessage(jid, albumMsg.message, {
1411
+ messageId: albumMsg.key.id,
1412
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1413
+ addBizAttributes: isNeedBizAttrs,
1414
+ statusJidList: options.statusJidList,
1415
+ additionalAttributes,
1416
+ additionalNodes
1417
+ });
1418
+ if (config.emitOwnEvents) {
1419
+ process.nextTick(async () => {
1420
+ await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
1421
+ });
1422
+ }
1423
+ await delay(delayMs);
1424
+ }
1425
+ }
1195
1426
  return fullMsg;
1196
1427
  }
1197
1428
  }
1198
1429
  };
1430
+
1431
+ fullSock.aiRich = () => new AIRichBuilder(fullSock);
1432
+ return fullSock;
1199
1433
  };
1200
1434
 
1201
- // Re-exports kept from the previous lite layout so existing deep imports keep working.
1202
1435
  export { AssociationType, BIZ_BOT_SUPPORT_PAYLOAD, isJidBot, isJidMetaAI, PSA_WID, shouldSendNewTcToken, resolveIssuanceJid, resolveTcTokenJid, isTcTokenExpired, buildMergedTcTokenIndexWrite, assertMeId, delay, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, generateParticipantHashV2, hasValidAlbumMedia, encodeNewsletterMessage, DEF_MEDIA_HOST, makeMutex }