@rizzxdc/baileys 8.0.10 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/LICENSE +4 -2
  2. package/README.md +107 -245
  3. package/WAProto/index.d.ts +15795 -0
  4. package/WAProto/index.js +25587 -4867
  5. package/lib/Defaults/index.d.ts +147 -0
  6. package/lib/Defaults/index.js +134 -104
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +9 -11
  9. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  10. package/lib/Signal/Group/group-session-builder.js +5 -8
  11. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  12. package/lib/Signal/Group/group_cipher.js +72 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +11 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  16. package/lib/Signal/Group/keyhelper.js +11 -14
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +23 -26
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +58 -61
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +61 -64
  23. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  24. package/lib/Signal/Group/sender-key-name.js +39 -44
  25. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  26. package/lib/Signal/Group/sender-key-record.js +35 -38
  27. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -79
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -26
  31. package/lib/Signal/libsignal.d.ts +55 -0
  32. package/lib/Signal/libsignal.js +414 -308
  33. package/lib/Signal/lid-mapping.d.ts +21 -0
  34. package/lib/Signal/lid-mapping.js +270 -149
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +2 -4
  37. package/lib/Socket/Client/types.d.ts +6 -0
  38. package/lib/Socket/Client/types.js +8 -11
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +51 -50
  41. package/lib/Socket/business.d.ts +395 -0
  42. package/lib/Socket/business.js +357 -355
  43. package/lib/Socket/chats.d.ts +137 -0
  44. package/lib/Socket/chats.js +1195 -867
  45. package/lib/Socket/communities.d.ts +562 -0
  46. package/lib/Socket/communities.js +416 -398
  47. package/lib/Socket/dugong.js +8 -1
  48. package/lib/Socket/groups.d.ts +286 -0
  49. package/lib/Socket/groups.js +336 -301
  50. package/lib/Socket/index.d.ts +530 -0
  51. package/lib/Socket/index.js +8 -13
  52. package/lib/Socket/messages-recv.d.ts +334 -0
  53. package/lib/Socket/messages-recv.js +1729 -1121
  54. package/lib/Socket/messages-send.d.ts +330 -0
  55. package/lib/Socket/messages-send.js +684 -462
  56. package/lib/Socket/mex.d.ts +2 -0
  57. package/lib/Socket/mex.js +36 -40
  58. package/lib/Socket/newsletter.d.ts +284 -0
  59. package/lib/Socket/newsletter.js +247 -237
  60. package/lib/Socket/socket.d.ts +61 -0
  61. package/lib/Socket/socket.js +968 -790
  62. package/lib/Store/index.d.ts +4 -0
  63. package/lib/Store/index.js +4 -6
  64. package/lib/Store/make-cache-manager-store.js +2 -2
  65. package/lib/Store/make-in-memory-store.d.ts +63 -0
  66. package/lib/Store/make-in-memory-store.js +414 -284
  67. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  68. package/lib/Store/make-ordered-dictionary.js +75 -76
  69. package/lib/Store/object-repository.d.ts +11 -0
  70. package/lib/Store/object-repository.js +21 -23
  71. package/lib/Types/Auth.d.ts +2 -0
  72. package/lib/Types/Auth.js +0 -2
  73. package/lib/Types/Bussines.d.ts +2 -0
  74. package/lib/Types/Bussines.js +0 -2
  75. package/lib/Types/Call.d.ts +2 -0
  76. package/lib/Types/Call.js +0 -2
  77. package/lib/Types/Chat.d.ts +2 -0
  78. package/lib/Types/Chat.js +5 -7
  79. package/lib/Types/Contact.d.ts +2 -0
  80. package/lib/Types/Contact.js +0 -2
  81. package/lib/Types/Events.d.ts +2 -0
  82. package/lib/Types/Events.js +1 -3
  83. package/lib/Types/GroupMetadata.d.ts +2 -0
  84. package/lib/Types/GroupMetadata.js +0 -2
  85. package/lib/Types/Label.d.ts +3 -0
  86. package/lib/Types/Label.js +21 -22
  87. package/lib/Types/LabelAssociation.d.ts +3 -0
  88. package/lib/Types/LabelAssociation.js +3 -4
  89. package/lib/Types/Message.d.ts +12 -0
  90. package/lib/Types/Message.js +11 -6
  91. package/lib/Types/Mex.d.ts +3 -0
  92. package/lib/Types/Mex.js +38 -0
  93. package/lib/Types/Product.d.ts +2 -0
  94. package/lib/Types/Product.js +0 -2
  95. package/lib/Types/RichType.d.ts +3 -0
  96. package/lib/Types/RichType.js +22 -0
  97. package/lib/Types/Signal.d.ts +2 -0
  98. package/lib/Types/Signal.js +1 -3
  99. package/lib/Types/Socket.d.ts +2 -0
  100. package/lib/Types/Socket.js +1 -4
  101. package/lib/Types/State.d.ts +6 -0
  102. package/lib/Types/State.js +52 -8
  103. package/lib/Types/USync.d.ts +2 -0
  104. package/lib/Types/USync.js +1 -3
  105. package/lib/Types/index.d.ts +14 -0
  106. package/lib/Types/index.js +22 -25
  107. package/lib/Utils/auth-utils.d.ts +58 -0
  108. package/lib/Utils/auth-utils.js +285 -203
  109. package/lib/Utils/browser-utils.d.ts +9 -0
  110. package/lib/Utils/browser-utils.js +21 -19
  111. package/lib/Utils/business.d.ts +50 -0
  112. package/lib/Utils/business.js +206 -209
  113. package/lib/Utils/chat-utils.d.ts +409 -0
  114. package/lib/Utils/chat-utils.js +825 -706
  115. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  116. package/lib/Utils/companion-reg-client-utils.js +39 -0
  117. package/lib/Utils/crypto.d.ts +40 -0
  118. package/lib/Utils/crypto.js +88 -101
  119. package/lib/Utils/decode-wa-message.d.ts +84 -0
  120. package/lib/Utils/decode-wa-message.js +287 -238
  121. package/lib/Utils/event-buffer.d.ts +13 -0
  122. package/lib/Utils/event-buffer.js +602 -509
  123. package/lib/Utils/generics.d.ts +64 -0
  124. package/lib/Utils/generics.js +334 -295
  125. package/lib/Utils/history.d.ts +76 -0
  126. package/lib/Utils/history.js +125 -79
  127. package/lib/Utils/identity-change-handler.d.ts +14 -0
  128. package/lib/Utils/identity-change-handler.js +49 -0
  129. package/lib/Utils/index.d.ts +25 -0
  130. package/lib/Utils/index.js +25 -21
  131. package/lib/Utils/link-preview.d.ts +13 -0
  132. package/lib/Utils/link-preview.js +73 -70
  133. package/lib/Utils/logger.d.ts +3 -0
  134. package/lib/Utils/logger.js +1 -4
  135. package/lib/Utils/lt-hash.d.ts +7 -0
  136. package/lib/Utils/lt-hash.js +7 -45
  137. package/lib/Utils/make-mutex.d.ts +7 -0
  138. package/lib/Utils/make-mutex.js +27 -31
  139. package/lib/Utils/message-retry-manager.d.ts +80 -0
  140. package/lib/Utils/message-retry-manager.js +165 -14
  141. package/lib/Utils/messages-media.d.ts +137 -0
  142. package/lib/Utils/messages-media.js +768 -572
  143. package/lib/Utils/messages.d.ts +46 -0
  144. package/lib/Utils/messages.js +1082 -130
  145. package/lib/Utils/noise-handler.d.ts +21 -0
  146. package/lib/Utils/noise-handler.js +191 -135
  147. package/lib/Utils/offline-node-processor.d.ts +10 -0
  148. package/lib/Utils/offline-node-processor.js +39 -0
  149. package/lib/Utils/pre-key-manager.d.ts +26 -0
  150. package/lib/Utils/pre-key-manager.js +96 -76
  151. package/lib/Utils/process-message.d.ts +84 -0
  152. package/lib/Utils/process-message.js +718 -311
  153. package/lib/Utils/reporting-utils.d.ts +13 -0
  154. package/lib/Utils/reporting-utils.js +257 -0
  155. package/lib/Utils/rich-message-utils.d.ts +49 -0
  156. package/lib/Utils/rich-message-utils.js +257 -0
  157. package/lib/Utils/signal.d.ts +83 -0
  158. package/lib/Utils/signal.js +174 -135
  159. package/lib/Utils/stanza-ack.d.ts +17 -0
  160. package/lib/Utils/stanza-ack.js +37 -0
  161. package/lib/Utils/sync-action-utils.d.ts +3 -0
  162. package/lib/Utils/sync-action-utils.js +48 -0
  163. package/lib/Utils/tc-token-utils.d.ts +30 -0
  164. package/lib/Utils/tc-token-utils.js +162 -0
  165. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  166. package/lib/Utils/use-multi-file-auth-state.js +104 -95
  167. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  168. package/lib/Utils/use-single-file-auth-state.js +108 -0
  169. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  170. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  171. package/lib/Utils/validate-connection.d.ts +44 -0
  172. package/lib/Utils/validate-connection.js +182 -180
  173. package/lib/WABinary/constants.d.ts +62 -0
  174. package/lib/WABinary/constants.js +1455 -1292
  175. package/lib/WABinary/decode.d.ts +10 -0
  176. package/lib/WABinary/decode.js +249 -228
  177. package/lib/WABinary/encode.d.ts +3 -0
  178. package/lib/WABinary/encode.js +207 -206
  179. package/lib/WABinary/generic-utils.d.ts +77 -0
  180. package/lib/WABinary/generic-utils.js +135 -99
  181. package/lib/WABinary/index.d.ts +6 -0
  182. package/lib/WABinary/index.js +5 -7
  183. package/lib/WABinary/jid-utils.d.ts +29 -0
  184. package/lib/WABinary/jid-utils.js +80 -78
  185. package/lib/WABinary/types.d.ts +2 -0
  186. package/lib/WABinary/types.js +1 -3
  187. package/lib/WAM/BinaryInfo.d.ts +8 -0
  188. package/lib/WAM/BinaryInfo.js +7 -9
  189. package/lib/WAM/constants.d.ts +34927 -0
  190. package/lib/WAM/constants.js +22847 -22848
  191. package/lib/WAM/encode.d.ts +2 -0
  192. package/lib/WAM/encode.js +129 -134
  193. package/lib/WAM/index.d.ts +4 -0
  194. package/lib/WAM/index.js +3 -5
  195. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  196. package/lib/WAUSync/Protocols/USyncContactProtocol.js +48 -27
  197. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  198. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -48
  199. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  200. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -26
  201. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  202. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -35
  203. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  204. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  205. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  206. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +46 -49
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +23 -25
  209. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  210. package/lib/WAUSync/Protocols/index.js +5 -6
  211. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  212. package/lib/WAUSync/USyncQuery.js +92 -85
  213. package/lib/WAUSync/USyncUser.d.ts +17 -0
  214. package/lib/WAUSync/USyncUser.js +28 -22
  215. package/lib/WAUSync/index.d.ts +4 -0
  216. package/lib/WAUSync/index.js +3 -5
  217. package/lib/index.d.ts +12 -0
  218. package/lib/index.js +31 -19
  219. package/package.json +12 -6
  220. package/lib/Types/Newsletter.js +0 -33
@@ -1,100 +1,79 @@
1
1
  import NodeCache from '@cacheable/node-cache';
2
2
  import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
3
4
  import { proto } from '../../WAProto/index.js';
4
- import { Dugong } from "./dugong.js";
5
- import {
6
- DEFAULT_CACHE_TTLS,
7
- WA_DEFAULT_EPHEMERAL
8
- } from '../Defaults/index.js';
9
- import {
10
- aggregateMessageKeysNotFromMe,
11
- assertMediaContent,
12
- bindWaitForEvent,
13
- decryptMediaRetryData,
14
- encodeNewsletterMessage,
15
- encodeSignedDeviceIdentity,
16
- encodeWAMessage,
17
- encryptMediaRetryRequest,
18
- extractDeviceJids,
19
- generateMessageIDV2,
20
- generateParticipantHashV2,
21
- generateWAMessage,
22
- getStatusCodeForMediaRetry,
23
- getUrlFromDirectPath,
24
- getWAUploadToServer,
25
- MessageRetryManager,
26
- normalizeMessageContent,
27
- parseAndInjectE2ESessions,
28
- unixTimestampSeconds
29
- } from '../Utils/index.js';
30
- import {
31
- areJidsSameUser,
32
- getBinaryNodeChild,
33
- getBinaryNodeChildren,
34
- getAdditionalNode,
35
- getBinaryNodeFilter,
36
- isHostedLidUser,
37
- isHostedPnUser,
38
- isJidGroup,
39
- isLidUser,
40
- isPnUser,
41
- jidDecode,
42
- jidEncode,
43
- isJidNewsletter,
44
- jidNormalizedUser,
45
- S_WHATSAPP_NET
46
- } from '../WABinary/index.js';
5
+ import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { AssociationType } from '../Types/index.js';
47
8
  import { getUrlInfo } from '../Utils/link-preview.js';
48
- import { makeKeyedMutex } from '../Utils/make-mutex.js';
9
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
10
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
11
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
12
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
49
13
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
50
14
  import { makeNewsletterSocket } from './newsletter.js';
15
+ import { Dugong } from './dugong.js';
51
16
  export const makeMessagesSocket = (config) => {
52
17
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
53
18
  const sock = makeNewsletterSocket(config);
54
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
19
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
20
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
21
+ /**
22
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
23
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
24
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
25
+ */
26
+ const inFlightTcTokenIssuance = new Set();
55
27
  const userDevicesCache = config.userDevicesCache ||
56
28
  new NodeCache({
57
29
  stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
58
30
  useClones: false
59
31
  });
60
- const peerSessionsCache = new NodeCache({
61
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
62
- useClones: false
63
- });
32
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
33
+ const devicesMutex = makeMutex();
64
34
  // Initialize message retry manager if enabled
65
35
  const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
66
36
  // Prevent race conditions in Signal session encryption by user
67
37
  const encryptionMutex = makeKeyedMutex();
38
+ // Prevent race conditions in media connection refresh
39
+ const mediaConnMutex = makeKeyedMutex();
68
40
  let mediaConn;
41
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
42
+ let mediaHost = DEF_MEDIA_HOST;
69
43
  const refreshMediaConn = async (forceGet = false) => {
70
- const media = await mediaConn;
71
- if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
72
- mediaConn = (async () => {
73
- const result = await query({
74
- tag: 'iq',
75
- attrs: {
76
- type: 'set',
77
- xmlns: 'w:m',
78
- to: S_WHATSAPP_NET
79
- },
80
- content: [{ tag: 'media_conn', attrs: {} }]
81
- });
82
- const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
83
- // TODO: explore full length of data that whatsapp provides
84
- const node = {
85
- hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
86
- hostname: attrs.hostname,
87
- maxContentLengthBytes: +attrs.maxContentLengthBytes
88
- })),
89
- auth: mediaConnNode.attrs.auth,
90
- ttl: +mediaConnNode.attrs.ttl,
91
- fetchDate: new Date()
92
- };
93
- logger.debug('fetched media conn');
94
- return node;
95
- })();
96
- }
97
- return mediaConn;
44
+ return mediaConnMutex.mutex('media-conn', async () => {
45
+ const media = await mediaConn;
46
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
47
+ mediaConn = (async () => {
48
+ const result = await query({
49
+ tag: 'iq',
50
+ attrs: {
51
+ type: 'set',
52
+ xmlns: 'w:m',
53
+ to: S_WHATSAPP_NET
54
+ },
55
+ content: [{ tag: 'media_conn', attrs: {} }]
56
+ });
57
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
58
+ // TODO: explore full length of data that whatsapp provides
59
+ const node = {
60
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
61
+ hostname: attrs.hostname,
62
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
63
+ })),
64
+ auth: mediaConnNode.attrs.auth,
65
+ ttl: +mediaConnNode.attrs.ttl,
66
+ fetchDate: new Date()
67
+ };
68
+ logger.debug('fetched media conn');
69
+ if (node.hosts[0]) {
70
+ mediaHost = node.hosts[0].hostname;
71
+ }
72
+ return node;
73
+ })();
74
+ }
75
+ return mediaConn;
76
+ });
98
77
  };
99
78
  /**
100
79
  * generic send receipt function
@@ -229,6 +208,16 @@ export const makeMessagesSocket = (config) => {
229
208
  if (lidResults.length > 0) {
230
209
  logger.trace('Storing LID maps from device call');
231
210
  await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
211
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
212
+ try {
213
+ const lids = lidResults.map(a => a.lid);
214
+ if (lids.length) {
215
+ await assertSessions(lids, true);
216
+ }
217
+ }
218
+ catch (e) {
219
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
220
+ }
232
221
  }
233
222
  const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
234
223
  const deviceMap = {};
@@ -256,16 +245,18 @@ export const makeMessagesSocket = (config) => {
256
245
  }, 'Processed device with LID priority');
257
246
  }
258
247
  }
259
- if (userDevicesCache.mset) {
260
- // if the cache supports mset, we can set all devices in one go
261
- await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
262
- }
263
- else {
264
- for (const key in deviceMap) {
265
- if (deviceMap[key])
266
- await userDevicesCache.set(key, deviceMap[key]);
248
+ await devicesMutex.mutex(async () => {
249
+ if (userDevicesCache.mset) {
250
+ // if the cache supports mset, we can set all devices in one go
251
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
267
252
  }
268
- }
253
+ else {
254
+ for (const key in deviceMap) {
255
+ if (deviceMap[key])
256
+ await userDevicesCache.set(key, deviceMap[key]);
257
+ }
258
+ }
259
+ });
269
260
  const userDeviceUpdates = {};
270
261
  for (const [userId, devices] of Object.entries(deviceMap)) {
271
262
  if (devices && devices.length > 0) {
@@ -284,25 +275,40 @@ export const makeMessagesSocket = (config) => {
284
275
  }
285
276
  return deviceResults;
286
277
  };
287
- const assertSessions = async (jids) => {
278
+ /**
279
+ * Update Member Label
280
+ */
281
+ const updateMemberLabel = (jid, memberLabel) => {
282
+ return relayMessage(jid, {
283
+ protocolMessage: {
284
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
285
+ memberLabel: {
286
+ label: memberLabel?.slice(0, 30),
287
+ labelTimestamp: unixTimestampSeconds()
288
+ }
289
+ }
290
+ }, {
291
+ additionalNodes: [
292
+ {
293
+ tag: 'meta',
294
+ attrs: {
295
+ tag_reason: 'user_update',
296
+ appdata: 'member_tag'
297
+ },
298
+ content: undefined
299
+ }
300
+ ]
301
+ });
302
+ };
303
+ const assertSessions = async (jids, force) => {
288
304
  let didFetchNewSession = false;
289
- const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
305
+ const uniqueJids = [...new Set(jids)];
290
306
  const jidsRequiringFetch = [];
291
307
  logger.debug({ jids }, 'assertSessions call with jids');
292
- // Check peerSessionsCache and validate sessions using libsignal loadSession
293
308
  for (const jid of uniqueJids) {
294
- const signalId = signalRepository.jidToSignalProtocolAddress(jid);
295
- const cachedSession = peerSessionsCache.get(signalId);
296
- if (cachedSession !== undefined) {
297
- if (cachedSession) {
298
- continue; // Session exists in cache
299
- }
300
- }
301
- else {
309
+ if (!force) {
302
310
  const sessionValidation = await signalRepository.validateSession(jid);
303
- const hasSession = sessionValidation.exists;
304
- peerSessionsCache.set(signalId, hasSession);
305
- if (hasSession) {
311
+ if (sessionValidation.exists) {
306
312
  continue;
307
313
  }
308
314
  }
@@ -326,20 +332,17 @@ export const makeMessagesSocket = (config) => {
326
332
  {
327
333
  tag: 'key',
328
334
  attrs: {},
329
- content: wireJids.map(jid => ({
330
- tag: 'user',
331
- attrs: { jid }
332
- }))
335
+ content: wireJids.map(jid => {
336
+ const attrs = { jid };
337
+ if (force)
338
+ attrs.reason = 'identity';
339
+ return { tag: 'user', attrs };
340
+ })
333
341
  }
334
342
  ]
335
343
  });
336
344
  await parseAndInjectE2ESessions(result, signalRepository);
337
345
  didFetchNewSession = true;
338
- // Cache fetched sessions using wire JIDs
339
- for (const wireJid of wireJids) {
340
- const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
341
- peerSessionsCache.set(signalId, true);
342
- }
343
346
  }
344
347
  return didFetchNewSession;
345
348
  };
@@ -382,55 +385,55 @@ export const makeMessagesSocket = (config) => {
382
385
  const meLid = authState.creds.me?.lid;
383
386
  const meLidUser = meLid ? jidDecode(meLid)?.user : null;
384
387
  const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
385
- if (!jid)
386
- return null;
387
- let msgToEncrypt = patchedMessage;
388
- if (dsmMessage) {
389
- const { user: targetUser } = jidDecode(jid);
390
- const { user: ownPnUser } = jidDecode(meId);
391
- const ownLidUser = meLidUser;
392
- const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
393
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
394
- if (isOwnUser && !isExactSenderDevice) {
395
- msgToEncrypt = dsmMessage;
396
- logger.debug({ jid, targetUser }, 'Using DSM for own device');
388
+ try {
389
+ if (!jid)
390
+ return null;
391
+ let msgToEncrypt = patchedMessage;
392
+ if (dsmMessage) {
393
+ const { user: targetUser } = jidDecode(jid);
394
+ const { user: ownPnUser } = jidDecode(meId);
395
+ const ownLidUser = meLidUser;
396
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
397
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
398
+ if (isOwnUser && !isExactSenderDevice) {
399
+ msgToEncrypt = dsmMessage;
400
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
401
+ }
397
402
  }
398
- }
399
- const bytes = encodeWAMessage(msgToEncrypt);
400
- const mutexKey = jid;
401
- const node = await encryptionMutex.mutex(mutexKey, async () => {
402
- const { type, ciphertext } = await signalRepository.encryptMessage({
403
- jid,
404
- data: bytes
403
+ const bytes = encodeWAMessage(msgToEncrypt);
404
+ const mutexKey = jid;
405
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
406
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
407
+ if (type === 'pkmsg') {
408
+ shouldIncludeDeviceIdentity = true;
409
+ }
410
+ return {
411
+ tag: 'to',
412
+ attrs: { jid },
413
+ content: [
414
+ {
415
+ tag: 'enc',
416
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
417
+ content: ciphertext
418
+ }
419
+ ]
420
+ };
405
421
  });
406
- if (type === 'pkmsg') {
407
- shouldIncludeDeviceIdentity = true;
408
- }
409
- return {
410
- tag: 'to',
411
- attrs: { jid },
412
- content: [
413
- {
414
- tag: 'enc',
415
- attrs: {
416
- v: '2',
417
- type,
418
- ...(extraAttrs || {})
419
- },
420
- content: ciphertext
421
- }
422
- ]
423
- };
424
- });
425
- return node;
422
+ return node;
423
+ }
424
+ catch (err) {
425
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
426
+ return null;
427
+ }
426
428
  });
427
429
  const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
430
+ if (recipientJids.length > 0 && nodes.length === 0) {
431
+ throw new Boom('All encryptions failed', { statusCode: 500 });
432
+ }
428
433
  return { nodes, shouldIncludeDeviceIdentity };
429
434
  };
430
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = false }) => {
431
- // let shouldIncludeDeviceIdentity = false;
432
- let didPushAdditional = false
433
- const meId = authState.creds.me.id;
435
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList }) => {
436
+ const meId = assertMeId(authState.creds);
434
437
  const meLid = authState.creds.me?.lid;
435
438
  const isRetryResend = Boolean(participant?.jid);
436
439
  let shouldIncludeDeviceIdentity = isRetryResend;
@@ -440,7 +443,7 @@ export const makeMessagesSocket = (config) => {
440
443
  const isStatus = jid === statusJid;
441
444
  const isLid = server === 'lid';
442
445
  const isNewsletter = server === 'newsletter';
443
- const isPrivate = server === 's.whatsapp.net'
446
+ const isGroupOrStatus = isGroup || isStatus;
444
447
  const finalJid = jid;
445
448
  msgId = msgId || generateMessageIDV2(meId);
446
449
  useUserDevicesCache = useUserDevicesCache !== false;
@@ -449,6 +452,7 @@ export const makeMessagesSocket = (config) => {
449
452
  const destinationJid = !isStatus ? finalJid : statusJid;
450
453
  const binaryNodeContent = [];
451
454
  const devices = [];
455
+ let reportingMessage;
452
456
  const meMsg = {
453
457
  deviceSentMessage: {
454
458
  destinationJid,
@@ -457,14 +461,9 @@ export const makeMessagesSocket = (config) => {
457
461
  messageContextInfo: message.messageContextInfo
458
462
  };
459
463
  const extraAttrs = {};
460
- const messages = normalizeMessageContent(message)
461
- const buttonType = getButtonType(messages);
462
464
  if (participant) {
463
465
  if (!isGroup && !isStatus) {
464
- additionalAttributes = {
465
- ...additionalAttributes,
466
- device_fanout: 'false'
467
- };
466
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
468
467
  }
469
468
  const { user, device } = jidDecode(participant.jid);
470
469
  devices.push({
@@ -474,51 +473,74 @@ export const makeMessagesSocket = (config) => {
474
473
  });
475
474
  }
476
475
  await authState.keys.transaction(async () => {
477
- const mediaType = getMediaType(message);
476
+ // Lia@Changes 02-02-26 --- Normalize message first to extract the original message and valid media type
477
+ const innerMessage = normalizeMessageContent(message);
478
+ const mediaType = getMediaType(innerMessage);
478
479
  if (mediaType) {
479
480
  extraAttrs['mediatype'] = mediaType;
480
481
  }
481
-
482
- if (isNewsletter) {
483
- const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
484
- const bytes = encodeNewsletterMessage(patched);
485
- binaryNodeContent.push({
486
- tag: "plaintext",
487
- attrs: mediaType ? { mediatype: mediaType } : {},
488
- content: bytes
489
- });
490
- const stanza = {
491
- tag: "message",
492
- attrs: {
493
- to: jid,
494
- id: msgId,
495
- type: getTypeMessage(message),
496
- ...(additionalAttributes || {})
497
- },
498
- content: binaryNodeContent
499
- };
500
- logger.debug({ msgId }, `sending newsletter message to ${jid}`);
501
- await sendNode(stanza);
502
- return;
503
- }
504
-
505
- if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
506
- extraAttrs['decrypt-fail'] = 'hide'
507
- }
508
-
509
- if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
510
- extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
482
+ if (isNewsletter) {
483
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
484
+ const bytes = encodeNewsletterMessage(patched);
485
+ // Lia@Changes 08-02-26 --- Add "additionalNodes" for newsletter too (⁠っ⁠˘̩⁠╭⁠╮⁠˘̩⁠)⁠っ
486
+ if (additionalNodes && additionalNodes.length > 0) {
487
+ ;
488
+ binaryNodeContent.push(...additionalNodes);
489
+ }
490
+ binaryNodeContent.push({
491
+ tag: 'plaintext',
492
+ attrs: extraAttrs, // Lia@Changes 02-02-26 --- Add extraAttrs to fix media being rejected when sending to newsletter (⁠◠⁠‿⁠◕⁠)
493
+ content: bytes
494
+ });
495
+ const stanza = {
496
+ tag: 'message',
497
+ attrs: {
498
+ to: jid,
499
+ id: msgId,
500
+ type: getMessageType(innerMessage),
501
+ ...(additionalAttributes || {})
502
+ },
503
+ content: binaryNodeContent
504
+ };
505
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
506
+ await sendNode(stanza);
507
+ return;
508
+ }
509
+ // Lia@Changes 02-02-26 --- Add keepInChat, editedMessage, mediaNotifyMessage and pollUpdateMessage
510
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
511
+ // Lia@Changes 12-05-26 --- Add groupStatusMessage attributes
512
+ const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
513
+ const isPollUpdate = innerMessage?.pollUpdateMessage;
514
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
515
+ const metaAttrs = {};
516
+ if (isNeedMetaAttrs) {
517
+ metaAttrs.content_type = 'add_on';
518
+ }
519
+ if (isPollUpdate && !isGroupStatus) {
520
+ metaAttrs.polltype = 'vote';
521
+ }
522
+ if (isGroupStatus) {
523
+ metaAttrs.is_group_status = 'true';
524
+ }
525
+ binaryNodeContent.push({
526
+ tag: 'meta',
527
+ attrs: metaAttrs,
528
+ content: undefined
529
+ });
530
+ }
531
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
532
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
533
+ }
534
+ // Lia@Changes 02-02-26 --- Add native_flow_name to extraAttrs when sending interactiveResponseMessage
535
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
536
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
511
537
  }
512
-
513
- if (isGroup || isStatus) {
538
+ if (isGroupOrStatus && !isRetryResend) {
514
539
  const [groupData, senderKeyMap] = await Promise.all([
515
540
  (async () => {
516
541
  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?
517
542
  if (groupData && Array.isArray(groupData?.participants)) {
518
- logger.trace({
519
- jid,
520
- participants: groupData.participants.length
521
- }, 'using cached group metadata');
543
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
522
544
  }
523
545
  else if (!isStatus) {
524
546
  groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
@@ -535,31 +557,30 @@ export const makeMessagesSocket = (config) => {
535
557
  return {};
536
558
  })()
537
559
  ]);
538
- if (!participant) {
539
- const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
540
- if (isStatus && statusJidList) {
541
- participantsList.push(...statusJidList);
542
- }
543
- // if (!isStatus) {
544
- // additionalAttributes = {
545
- // ...additionalAttributes,
546
- // addressing_mode: groupData?.addressingMode || 'pn'
547
- // };
548
- // }
549
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
550
- devices.push(...additionalDevices);
551
- }
560
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
552
561
  if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
553
562
  additionalAttributes = {
554
563
  ...additionalAttributes,
555
564
  expiration: groupData.ephemeralDuration.toString()
556
565
  };
557
566
  }
567
+ if (isStatus && statusJidList) {
568
+ participantsList.push(...statusJidList);
569
+ }
570
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
571
+ devices.push(...additionalDevices);
572
+ if (isGroup) {
573
+ additionalAttributes = {
574
+ ...additionalAttributes,
575
+ addressing_mode: groupData?.addressingMode || 'lid'
576
+ };
577
+ }
558
578
  const patched = await patchMessageBeforeSending(message);
559
579
  if (Array.isArray(patched)) {
560
580
  throw new Boom('Per-jid patching is not supported in groups');
561
581
  }
562
582
  const bytes = encodeWAMessage(patched);
583
+ reportingMessage = patched;
563
584
  const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
564
585
  const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
565
586
  const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
@@ -595,33 +616,12 @@ export const makeMessagesSocket = (config) => {
595
616
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
596
617
  participants.push(...result.nodes);
597
618
  }
598
- if (isRetryResend) {
599
- const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
600
- data: bytes,
601
- jid: participant?.jid
602
- });
603
- binaryNodeContent.push({
604
- tag: 'enc',
605
- attrs: {
606
- v: '2',
607
- type,
608
- count: participant.count.toString()
609
- },
610
- content: encryptedContent
611
- });
612
- }
613
- else {
614
- binaryNodeContent.push({
615
- tag: 'enc',
616
- attrs: {
617
- v: '2',
618
- type: 'skmsg',
619
- ...extraAttrs
620
- },
621
- content: ciphertext
622
- });
623
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
624
- }
619
+ binaryNodeContent.push({
620
+ tag: 'enc',
621
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
622
+ content: ciphertext
623
+ });
624
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
625
625
  }
626
626
  else {
627
627
  // ADDRESSING CONSISTENCY: Match own identity to conversation context
@@ -636,6 +636,12 @@ export const makeMessagesSocket = (config) => {
636
636
  }
637
637
  const { user: ownUser } = jidDecode(ownId);
638
638
  if (!participant) {
639
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
640
+ reportingMessage = Array.isArray(patchedForReporting)
641
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
642
+ : patchedForReporting;
643
+ }
644
+ if (!isRetryResend) {
639
645
  const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
640
646
  devices.push({
641
647
  user,
@@ -696,11 +702,64 @@ export const makeMessagesSocket = (config) => {
696
702
  ]);
697
703
  participants.push(...meNodes);
698
704
  participants.push(...otherNodes);
699
- /* if (meRecipients.length > 0 || otherRecipients.length > 0) {
705
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
700
706
  extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
701
- }*/
707
+ }
702
708
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
703
709
  }
710
+ if (isRetryResend) {
711
+ const isParticipantLid = isLidUser(participant.jid);
712
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
713
+ let messageToSend = message;
714
+ if (isGroupOrStatus) {
715
+ let groupSenderIdentity;
716
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
717
+ groupSenderIdentity = meLid;
718
+ }
719
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
720
+ groupSenderIdentity = meId;
721
+ }
722
+ if (groupSenderIdentity) {
723
+ try {
724
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
725
+ group: destinationJid,
726
+ meId: groupSenderIdentity
727
+ });
728
+ messageToSend = {
729
+ ...message,
730
+ senderKeyDistributionMessage: {
731
+ groupId: destinationJid,
732
+ axolotlSenderKeyDistributionMessage: skdm
733
+ }
734
+ };
735
+ }
736
+ catch (err) {
737
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
738
+ }
739
+ }
740
+ }
741
+ const encodedMessageToSend = isMe
742
+ ? encodeWAMessage({
743
+ deviceSentMessage: {
744
+ destinationJid,
745
+ message: messageToSend
746
+ }
747
+ })
748
+ : encodeWAMessage(messageToSend);
749
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
750
+ data: encodedMessageToSend,
751
+ jid: participant.jid
752
+ });
753
+ binaryNodeContent.push({
754
+ tag: 'enc',
755
+ attrs: {
756
+ v: '2',
757
+ type,
758
+ count: (participant.count || 0).toString()
759
+ },
760
+ content: encryptedContent
761
+ });
762
+ }
704
763
  if (participants.length) {
705
764
  if (additionalAttributes?.['category'] === 'peer') {
706
765
  const peerNode = participants[0]?.content?.[0];
@@ -721,7 +780,7 @@ export const makeMessagesSocket = (config) => {
721
780
  attrs: {
722
781
  id: msgId,
723
782
  to: destinationJid,
724
- type: getTypeMessage(messages),
783
+ type: getMessageType(innerMessage),
725
784
  ...(additionalAttributes || {})
726
785
  },
727
786
  content: binaryNodeContent
@@ -754,45 +813,116 @@ export const makeMessagesSocket = (config) => {
754
813
  });
755
814
  logger.debug({ jid }, 'adding device identity');
756
815
  }
757
- if (AI && isPrivate) {
758
- const botNode = {
759
- tag: 'bot',
760
- attrs: {
761
- biz_bot: '1'
816
+ if (!isNewsletter &&
817
+ !isRetryResend &&
818
+ reportingMessage?.messageContextInfo?.messageSecret &&
819
+ shouldIncludeReportingToken(reportingMessage)) {
820
+ try {
821
+ const encoded = encodeWAMessage(reportingMessage);
822
+ const reportingKey = {
823
+ id: msgId,
824
+ fromMe: true,
825
+ remoteJid: destinationJid,
826
+ participant: participant?.jid
827
+ };
828
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
829
+ if (reportingNode) {
830
+ ;
831
+ stanza.content.push(reportingNode);
832
+ logger.trace({ jid }, 'added reporting token to message');
762
833
  }
763
834
  }
764
-
765
- const filteredBizBot = getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
766
-
767
- if (filteredBizBot) {
768
- stanza.content.push(...additionalNodes)
769
- didPushAdditional = true
770
- }
771
-
772
- else {
773
- stanza.content.push(botNode)
835
+ catch (error) {
836
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
774
837
  }
775
838
  }
776
-
777
- if(buttonType && !isStatus) {
778
- const content = getAdditionalNode(buttonType)
779
- const filteredNode = getBinaryNodeFilter(additionalNodes)
780
-
781
- if (filteredNode) {
782
- didPushAdditional = true
783
- stanza.content.push(...additionalNodes)
784
- }
785
- else {
786
- stanza.content.push(...content)
839
+ // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
840
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
841
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
842
+ // Resolve destination to LID for tctoken storage — matches Signal session key pattern
843
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
844
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
845
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
846
+ let tcTokenBuffer = existingTokenEntry?.token;
847
+ // Treat expired tokens the same as missing — clear from cache
848
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
849
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
850
+ tcTokenBuffer = undefined;
851
+ // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
852
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
853
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
854
+ : null;
855
+ try {
856
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
857
+ }
858
+ catch (err) {
859
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
787
860
  }
788
- logger.debug({ jid }, 'adding business node')
789
- }
790
-
791
- if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
861
+ }
862
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
863
+ ;
864
+ stanza.content.push({
865
+ tag: 'tctoken',
866
+ attrs: {},
867
+ content: tcTokenBuffer
868
+ });
869
+ }
870
+ let alreadyHasBizNode = false;
871
+ if (additionalNodes && additionalNodes.length > 0) {
872
+ ;
792
873
  stanza.content.push(...additionalNodes);
874
+ alreadyHasBizNode = !addBizAttributes &&
875
+ additionalNodes.some(node => node.tag === 'biz');
876
+ }
877
+ // Lia@Changes 30-01-26 --- Add Biz Binary Node to support button messages
878
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
879
+ const bizNode = getBizBinaryNode(innerMessage);
880
+ stanza.content.push(bizNode);
793
881
  }
794
882
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
795
883
  await sendNode(stanza);
884
+ // Fire-and-forget: issue our token to the contact AFTER message send.
885
+ // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
886
+ const isProtocolMsg = !!innerMessage?.protocolMessage;
887
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
888
+ if (is1on1Send &&
889
+ !isProtocolMsg &&
890
+ !isBotOrPSA &&
891
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
892
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
893
+ inFlightTcTokenIssuance.add(tcTokenJid);
894
+ const issueTimestamp = unixTimestampSeconds();
895
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
896
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
897
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
898
+ .then(async (result) => {
899
+ await storeTcTokensFromIqResult({
900
+ result,
901
+ fallbackJid: tcTokenJid,
902
+ keys: authState.keys,
903
+ getLIDForPN
904
+ });
905
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
906
+ const currentEntry = currentData[tcTokenJid];
907
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
908
+ await authState.keys.set({
909
+ tctoken: {
910
+ [tcTokenJid]: {
911
+ token: Buffer.alloc(0),
912
+ ...currentEntry,
913
+ senderTimestamp: issueTimestamp
914
+ },
915
+ ...indexWrite
916
+ }
917
+ });
918
+ })
919
+ .catch(err => {
920
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
921
+ })
922
+ .finally(() => {
923
+ inFlightTcTokenIssuance.delete(tcTokenJid);
924
+ });
925
+ }
796
926
  // Add message to retry cache if enabled
797
927
  if (messageRetryManager && !participant) {
798
928
  messageRetryManager.addRecentMessage(destinationJid, msgId, message);
@@ -800,116 +930,91 @@ export const makeMessagesSocket = (config) => {
800
930
  }, meId);
801
931
  return msgId;
802
932
  };
803
- const getTypeMessage = (msg) => {
804
- if (msg.viewOnceMessage) {
805
- return getTypeMessage(msg.viewOnceMessage.message);
806
- }
807
- else if (msg.viewOnceMessageV2) {
808
- return getTypeMessage(msg.viewOnceMessageV2.message);
809
- }
810
- else if (msg.viewOnceMessageV2Extension) {
811
- return getTypeMessage(msg.viewOnceMessageV2Extension.message);
812
- }
813
- else if (msg.ephemeralMessage) {
814
- return getTypeMessage(msg.ephemeralMessage.message);
815
- }
816
- else if (msg.documentWithCaptionMessage) {
817
- return getTypeMessage(msg.documentWithCaptionMessage.message);
818
- }
819
- else if (msg.reactionMessage) {
933
+ const getMessageType = (message) => {
934
+ if (!message)
935
+ return 'text';
936
+ if (message.reactionMessage || message.encReactionMessage) {
820
937
  return 'reaction';
821
938
  }
822
- else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
939
+ if (message.pollCreationMessage ||
940
+ message.pollCreationMessageV2 ||
941
+ message.pollCreationMessageV3 ||
942
+ message.pollCreationMessageV5 ||
943
+ message.pollCreationMessageV6 ||
944
+ message.pollUpdateMessage) {
823
945
  return 'poll';
824
946
  }
825
- else if (getMediaType(msg)) {
826
- return 'media';
947
+ if (message.eventMessage) {
948
+ return 'event';
827
949
  }
828
- else {
829
- return 'text';
950
+ if (getMediaType(message) !== '') {
951
+ return 'media';
830
952
  }
953
+ return 'text';
831
954
  };
832
955
  const getMediaType = (message) => {
833
956
  if (message.imageMessage) {
834
- return 'image'
957
+ return 'image';
835
958
  }
836
959
  else if (message.videoMessage) {
837
- return message.videoMessage.gifPlayback ? 'gif' : 'video'
960
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
961
+ }
962
+ else if (message.stickerMessage) {
963
+ return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
838
964
  }
839
965
  else if (message.audioMessage) {
840
- return message.audioMessage.ptt ? 'ptt' : 'audio'
966
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
967
+ }
968
+ else if (message.albumMessage) {
969
+ return 'collection';
841
970
  }
842
971
  else if (message.contactMessage) {
843
- return 'vcard'
972
+ return 'vcard';
844
973
  }
845
974
  else if (message.documentMessage) {
846
- return 'document'
975
+ return 'document';
847
976
  }
848
977
  else if (message.contactsArrayMessage) {
849
- return 'contact_array'
978
+ return 'contact_array';
850
979
  }
851
980
  else if (message.liveLocationMessage) {
852
- return 'livelocation'
981
+ return 'livelocation';
853
982
  }
854
- else if (message.stickerMessage) {
855
- return 'sticker'
983
+ else if (message.stickerPackMessage) {
984
+ return 'sticker_pack';
856
985
  }
857
986
  else if (message.listMessage) {
858
- return 'list'
987
+ return 'list';
859
988
  }
860
989
  else if (message.listResponseMessage) {
861
- return 'list_response'
990
+ return 'list_response';
862
991
  }
863
992
  else if (message.buttonsResponseMessage) {
864
- return 'buttons_response'
993
+ return 'buttons_response';
865
994
  }
866
995
  else if (message.orderMessage) {
867
- return 'order'
996
+ return 'order';
868
997
  }
869
998
  else if (message.productMessage) {
870
- return 'product'
999
+ return 'product';
871
1000
  }
872
1001
  else if (message.interactiveResponseMessage) {
873
- return 'native_flow_response'
874
- }
875
- else if (message.groupInviteMessage) {
876
- return 'url'
877
- }
878
- else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
879
- return 'productlink'
880
- }
881
- }
882
- const getButtonType = (message) => {
883
- if (message.listMessage) {
884
- return 'list'
885
- }
886
- else if (message.buttonsMessage) {
887
- return 'buttons'
1002
+ return 'native_flow_response';
888
1003
  }
889
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
890
- return 'review_and_pay'
1004
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1005
+ return 'url';
891
1006
  }
892
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
893
- return 'review_order'
1007
+ // Lia@Note 02-02-26 --- Add more message type here
1008
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1009
+ return 'cataloglink';
894
1010
  }
895
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
896
- return 'payment_info'
1011
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1012
+ return 'productlink';
897
1013
  }
898
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
899
- return 'payment_status'
900
- }
901
- else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
902
- return 'payment_method'
903
- }
904
- else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
905
- return 'interactive'
906
- }
907
- else if (message.interactiveMessage?.nativeFlowMessage) {
908
- return 'native_flow'
909
- }
910
- }
911
- const getPrivacyTokens = async (jids) => {
912
- const t = unixTimestampSeconds().toString();
1014
+ return '';
1015
+ };
1016
+ const issuePrivacyTokens = async (jids, timestamp) => {
1017
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
913
1018
  const result = await query({
914
1019
  tag: 'iq',
915
1020
  attrs: {
@@ -935,28 +1040,42 @@ export const makeMessagesSocket = (config) => {
935
1040
  return result;
936
1041
  };
937
1042
  const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
938
- const ourin = new Dugong(waUploadToServer, relayMessage, config, sock);
1043
+ const dugong = new Dugong(waUploadToServer, relayMessage, config, sock);
939
1044
  const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1045
+ registerSocketEndHandler(() => {
1046
+ if (!config.userDevicesCache && userDevicesCache.close) {
1047
+ userDevicesCache.close();
1048
+ }
1049
+ mediaConn = undefined;
1050
+ if (messageRetryManager) {
1051
+ messageRetryManager.clear();
1052
+ }
1053
+ });
940
1054
  return {
941
1055
  ...sock,
942
- getPrivacyTokens,
1056
+ userDevicesCache,
1057
+ devicesMutex,
1058
+ issuePrivacyTokens,
943
1059
  assertSessions,
944
1060
  relayMessage,
945
1061
  sendReceipt,
946
1062
  sendReceipts,
947
1063
  readMessages,
948
1064
  refreshMediaConn,
1065
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1066
+ getMediaHost: () => mediaHost,
949
1067
  waUploadToServer,
950
1068
  fetchPrivacySettings,
951
1069
  sendPeerDataOperationMessage,
952
1070
  createParticipantNodes,
953
1071
  getUSyncDevices,
954
1072
  messageRetryManager,
1073
+ updateMemberLabel,
955
1074
  updateMediaMessage: async (message) => {
956
1075
  const content = assertMediaContent(message.message);
957
1076
  const mediaKey = content.mediaKey;
958
1077
  const meId = authState.creds.me.id;
959
- const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
1078
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
960
1079
  let error = undefined;
961
1080
  await Promise.all([
962
1081
  sendNode(node),
@@ -968,7 +1087,7 @@ export const makeMessagesSocket = (config) => {
968
1087
  }
969
1088
  else {
970
1089
  try {
971
- const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
1090
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
972
1091
  if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
973
1092
  const resultStr = proto.MediaRetryNotification.ResultType[media.result];
974
1093
  throw new Boom(`Media re-upload failed by device (${resultStr})`, {
@@ -977,7 +1096,7 @@ export const makeMessagesSocket = (config) => {
977
1096
  });
978
1097
  }
979
1098
  content.directPath = media.directPath;
980
- content.url = getUrlFromDirectPath(content.directPath);
1099
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
981
1100
  logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
982
1101
  }
983
1102
  catch (err) {
@@ -994,14 +1113,137 @@ export const makeMessagesSocket = (config) => {
994
1113
  ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
995
1114
  return message;
996
1115
  },
1116
+ // Lia@Changes 30-01-26 --- Add support for modifying additionalNodes and additionalAttributes using "options" in sendMessage()
997
1117
  sendMessage: async (jid, content, options = {}) => {
998
- const userJid = authState.creds.me.id;
999
- const { quoted } = options;
1000
- const messageType = ourin.detectType(content);
1001
- if (typeof content === 'object' &&
1002
- 'disappearingMessagesInChat' in content &&
1003
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1004
- isJidGroup(jid)) {
1118
+ const userJid = authState.creds.me.id;
1119
+ // Tipe pesan khas baileys 8.x (payment, product, interactive, carousel, interactiveButtons, albumMessage, event, pollResult, group story)
1120
+ if (!Array.isArray(jid) && content && typeof content === 'object') {
1121
+ const dugongType = dugong.detectType(content);
1122
+ if (dugongType) {
1123
+ const quoted = options.quoted;
1124
+ const buildAndRelay = async (waContent) => {
1125
+ const msg = await generateWAMessageFromContent(jid, waContent, { quoted, userJid });
1126
+ await relayMessage(jid, msg.message, { messageId: msg.key.id });
1127
+ return msg;
1128
+ };
1129
+ switch (dugongType) {
1130
+ case 'PAYMENT':
1131
+ return relayMessage(jid, await dugong.handlePayment(content, quoted), { messageId: generateMessageIDV2(userJid) });
1132
+ case 'PRODUCT':
1133
+ return buildAndRelay(await dugong.handleProduct(content, jid, quoted));
1134
+ case 'CAROUSEL':
1135
+ return buildAndRelay(await dugong.handleCarousel(content, jid, quoted));
1136
+ case 'INTERACTIVE':
1137
+ return buildAndRelay(await dugong.handleInteractive(content, jid, quoted));
1138
+ case 'INTERACTIVE_BUTTONS':
1139
+ return buildAndRelay(await dugong.handleInteractiveButtons(content, jid, quoted));
1140
+ case 'ALBUM':
1141
+ return dugong.handleAlbum(content, jid, quoted);
1142
+ case 'EVENT':
1143
+ return dugong.handleEvent(content, jid, quoted);
1144
+ case 'POLL_RESULT':
1145
+ return dugong.handlePollResult(content, jid, quoted);
1146
+ case 'GROUP_STORY':
1147
+ return dugong.handleGroupStory(content, jid, quoted, options);
1148
+ }
1149
+ }
1150
+ }
1151
+ // Lia@Changes 13-03-26 --- Add status mentions!
1152
+ if (Array.isArray(jid)) {
1153
+ const { delayMs = 1500 } = options;
1154
+ const allUsers = new Set();
1155
+ const fullMsg = await generateWAMessage('status@broadcast', content, {
1156
+ logger,
1157
+ userJid,
1158
+ upload: waUploadToServer,
1159
+ mediaCache: config.mediaCache,
1160
+ options: config.options,
1161
+ ...options,
1162
+ messageId: generateMessageIDV2(userJid)
1163
+ });
1164
+ for (const id of jid) {
1165
+ if (isJidGroup(id)) {
1166
+ try {
1167
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1168
+ for (const participant of groupData.participants) {
1169
+ if (allUsers.has(participant.id))
1170
+ continue;
1171
+ allUsers.add(participant.id);
1172
+ }
1173
+ }
1174
+ catch (error) {
1175
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
1176
+ }
1177
+ }
1178
+ else if (!allUsers.has(id)) {
1179
+ allUsers.add(id);
1180
+ }
1181
+ }
1182
+ await relayMessage('status@broadcast', fullMsg.message, {
1183
+ messageId: fullMsg.key.id,
1184
+ statusJidList: Array.from(allUsers),
1185
+ additionalNodes: [
1186
+ {
1187
+ tag: 'meta',
1188
+ attrs: {},
1189
+ content: [
1190
+ {
1191
+ tag: 'mentioned_users',
1192
+ attrs: {},
1193
+ content: jid.map(id => ({
1194
+ tag: 'to',
1195
+ attrs: { jid: id },
1196
+ content: undefined
1197
+ }))
1198
+ }
1199
+ ]
1200
+ }
1201
+ ]
1202
+ });
1203
+ if (config.emitOwnEvents) {
1204
+ process.nextTick(async () => {
1205
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1206
+ });
1207
+ }
1208
+ for (const id of jid) {
1209
+ const isGroup = isJidGroup(id);
1210
+ const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1211
+ const mentionMsg = generateWAMessageFromContent(id, {
1212
+ messageContextInfo: {
1213
+ messageSecret: randomBytes(32)
1214
+ },
1215
+ [sendType]: {
1216
+ message: {
1217
+ protocolMessage: {
1218
+ key: fullMsg.key,
1219
+ type: 25
1220
+ }
1221
+ }
1222
+ }
1223
+ }, {
1224
+ userJid
1225
+ });
1226
+ await relayMessage(id, mentionMsg.message, {
1227
+ additionalNodes: [
1228
+ {
1229
+ tag: 'meta',
1230
+ attrs: isGroup ?
1231
+ { is_group_status_mention: 'true' } :
1232
+ { is_status_mention: 'true' },
1233
+ content: undefined
1234
+ }
1235
+ ]
1236
+ });
1237
+ if (config.emitOwnEvents) {
1238
+ process.nextTick(async () => {
1239
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1240
+ });
1241
+ }
1242
+ await delay(delayMs);
1243
+ }
1244
+ return fullMsg;
1245
+ }
1246
+ else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1005
1247
  const { disappearingMessagesInChat } = content;
1006
1248
  const value = typeof disappearingMessagesInChat === 'boolean'
1007
1249
  ? disappearingMessagesInChat
@@ -1009,83 +1251,8 @@ export const makeMessagesSocket = (config) => {
1009
1251
  : 0
1010
1252
  : disappearingMessagesInChat;
1011
1253
  await groupToggleEphemeral(jid, value);
1012
- } else if (messageType) {
1013
- switch (messageType) {
1014
- case "PAYMENT": {
1015
- const paymentContent = await ourin.handlePayment(content, quoted);
1016
- return await relayMessage(jid, paymentContent, {
1017
- messageId: generateMessageIDV2(userJid),
1018
- });
1019
- }
1020
- case "PRODUCT": {
1021
- const productContent = await ourin.handleProduct(
1022
- content,
1023
- jid,
1024
- quoted,
1025
- );
1026
- const productMsg = await generateWAMessageFromContent(
1027
- jid,
1028
- productContent,
1029
- { quoted, userJid },
1030
- );
1031
- return await relayMessage(jid, productMsg.message, {
1032
- messageId: productMsg.key.id,
1033
- });
1034
- }
1035
- case "CAROUSEL": {
1036
- const carouselContent = await ourin.handleCarousel(
1037
- content,
1038
- jid,
1039
- quoted,
1040
- );
1041
- const carouselMsg = await generateWAMessageFromContent(
1042
- jid,
1043
- carouselContent,
1044
- { quoted, userJid },
1045
- );
1046
- return await relayMessage(jid, carouselMsg.message, {
1047
- messageId: carouselMsg.key.id,
1048
- });
1049
- }
1050
- case "INTERACTIVE": {
1051
- const interactiveContent = await ourin.handleInteractive(
1052
- content,
1053
- jid,
1054
- quoted,
1055
- );
1056
- const interactiveMsg = await generateWAMessageFromContent(
1057
- jid,
1058
- interactiveContent,
1059
- { quoted, userJid },
1060
- );
1061
- return await relayMessage(jid, interactiveMsg.message, {
1062
- messageId: interactiveMsg.key.id,
1063
- });
1064
- }
1065
- case "INTERACTIVE_BUTTONS": {
1066
- const ibContent = await ourin.handleInteractiveButtons(
1067
- content,
1068
- jid,
1069
- quoted,
1070
- );
1071
- const ibMsg = await generateWAMessageFromContent(jid, ibContent, {
1072
- quoted,
1073
- userJid,
1074
- });
1075
- return await relayMessage(jid, ibMsg.message, {
1076
- messageId: ibMsg.key.id,
1077
- });
1078
- }
1079
- case "ALBUM":
1080
- return await ourin.handleAlbum(content, jid, quoted);
1081
- case "EVENT":
1082
- return await ourin.handleEvent(content, jid, quoted);
1083
- case "POLL_RESULT":
1084
- return await ourin.handlePollResult(content, jid, quoted);
1085
- case "GROUP_STORY":
1086
- return await ourin.handleGroupStory(content, jid, quoted, options);
1087
- }
1088
- } else {
1254
+ }
1255
+ else {
1089
1256
  const fullMsg = await generateWAMessage(jid, content, {
1090
1257
  logger,
1091
1258
  userJid,
@@ -1101,28 +1268,26 @@ export const makeMessagesSocket = (config) => {
1101
1268
  //TODO: CACHE
1102
1269
  getProfilePicUrl: sock.profilePictureUrl,
1103
1270
  getCallLink: sock.createCallLink,
1104
- upload: async (readStream, opts) => {
1105
- const up = await waUploadToServer(readStream, {
1106
- ...opts,
1107
- newsletter: isJidNewsletter(jid)
1108
- });
1109
- return up;
1110
- },
1271
+ upload: waUploadToServer,
1111
1272
  mediaCache: config.mediaCache,
1112
1273
  options: config.options,
1113
- messageId: generateMessageIDV2(sock.user?.id),
1114
- ...options
1274
+ ...options,
1275
+ messageId: generateMessageIDV2(userJid)
1115
1276
  });
1116
- const isAiMsg = 'ai' in content && !!content.ai;
1277
+ const isNewsletter = isJidNewsletter(jid);
1117
1278
  const isEventMsg = 'event' in content && !!content.event;
1118
1279
  const isDeleteMsg = 'delete' in content && !!content.delete;
1119
1280
  const isEditMsg = 'edit' in content && !!content.edit;
1120
1281
  const isPinMsg = 'pin' in content && !!content.pin;
1121
- const isPollMessage = 'poll' in content && !!content.poll;
1122
- const additionalAttributes = {};
1123
- const additionalNodes = [];
1282
+ const isKeepMsg = 'keep' in content && !!content.keep;
1283
+ const isPollMsg = 'poll' in content && !!content.poll;
1284
+ const isQuizMsg = 'poll' in content && !!content.poll.pollType;
1285
+ const isAiMsg = 'ai' in content && !!content.ai;
1286
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
1287
+ const additionalAttributes = options.additionalAttributes || {};
1288
+ const additionalNodes = options.additionalNodes || [];
1124
1289
  // required for delete
1125
- if (isDeleteMsg) {
1290
+ if (isDeleteMsg || isKeepMsg) {
1126
1291
  // if the chat is a group, and I am not the author, then delete the message as an admin
1127
1292
  if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1128
1293
  additionalAttributes.edit = '8';
@@ -1132,24 +1297,23 @@ export const makeMessagesSocket = (config) => {
1132
1297
  }
1133
1298
  }
1134
1299
  else if (isEditMsg) {
1135
- additionalAttributes.edit = '1';
1136
- }
1137
- else if (isAiMsg) {
1138
- additionalNodes.push({
1139
- attrs: {
1140
- biz_bot: '1'
1141
- }, tag: "bot"
1142
- });
1300
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
1143
1301
  }
1144
1302
  else if (isPinMsg) {
1145
1303
  additionalAttributes.edit = '2';
1146
1304
  }
1147
- else if (isPollMessage) {
1305
+ else if (isPollMsg) {
1306
+ if (!isNewsletter && isQuizMsg) {
1307
+ throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
1308
+ }
1148
1309
  additionalNodes.push({
1149
1310
  tag: 'meta',
1150
1311
  attrs: {
1151
- polltype: 'creation'
1152
- }
1312
+ // Lia@Note 08-02-26 --- Still a hypothesis regarding PollResult ༎ຶ⁠‿⁠༎ຶ
1313
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
1314
+ contenttype: isPollMsg && isNewsletter ? 'text' : undefined
1315
+ },
1316
+ content: undefined
1153
1317
  });
1154
1318
  }
1155
1319
  else if (isEventMsg) {
@@ -1157,23 +1321,81 @@ export const makeMessagesSocket = (config) => {
1157
1321
  tag: 'meta',
1158
1322
  attrs: {
1159
1323
  event_type: 'creation'
1160
- }
1324
+ },
1325
+ content: undefined
1161
1326
  });
1162
1327
  }
1328
+ // Lia@Changes 30-01-26 --- Add support for AI label in message when "ai" is true, but works only in private chat
1329
+ else if (isAiMsg) {
1330
+ if (!(isPnUser(jid) || isLidUser(jid))) {
1331
+ throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
1332
+ }
1333
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1334
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1335
+ }
1336
+ ;
1337
+ additionalNodes.push({
1338
+ tag: 'bot',
1339
+ attrs: {
1340
+ biz_bot: '1'
1341
+ },
1342
+ content: undefined
1343
+ });
1344
+ delete content.ai;
1345
+ }
1163
1346
  await relayMessage(jid, fullMsg.message, {
1164
1347
  messageId: fullMsg.key.id,
1165
1348
  useCachedGroupMetadata: options.useCachedGroupMetadata,
1166
- additionalAttributes,
1349
+ addBizAttributes: isNeedBizAttrs,
1167
1350
  statusJidList: options.statusJidList,
1168
- additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes
1351
+ additionalAttributes,
1352
+ additionalNodes
1169
1353
  });
1170
1354
  if (config.emitOwnEvents) {
1171
- process.nextTick(() => {
1172
- processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1355
+ process.nextTick(async () => {
1356
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1173
1357
  });
1174
1358
  }
1359
+ // Lia@Changes 31-01-26 --- Add support for album messages
1360
+ // Lia@Note 06-02-26 --- Refactored to reduce high RSS usage (⁠╥⁠﹏⁠╥⁠)
1361
+ if ('album' in content) {
1362
+ const { delayMs = 1500 } = options;
1363
+ for (const albumMedia of content.album) {
1364
+ const albumMsg = await generateWAMessage(jid, albumMedia, {
1365
+ logger,
1366
+ userJid,
1367
+ upload: waUploadToServer,
1368
+ mediaCache: config.mediaCache,
1369
+ options: config.options,
1370
+ ...options,
1371
+ messageId: generateMessageIDV2(userJid)
1372
+ });
1373
+ if (!hasValidAlbumMedia(normalizeMessageContent(albumMsg.message))) {
1374
+ throw new Boom('Invalid message type for album', { statusCode: 400 });
1375
+ }
1376
+ albumMsg.message.messageContextInfo ||= {};
1377
+ albumMsg.message.messageContextInfo.messageAssociation = {
1378
+ parentMessageKey: fullMsg.key,
1379
+ associationType: AssociationType.MEDIA_ALBUM
1380
+ };
1381
+ await relayMessage(jid, albumMsg.message, {
1382
+ messageId: albumMsg.key.id,
1383
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1384
+ addBizAttributes: isNeedBizAttrs,
1385
+ statusJidList: options.statusJidList,
1386
+ additionalAttributes,
1387
+ additionalNodes
1388
+ });
1389
+ if (config.emitOwnEvents) {
1390
+ process.nextTick(async () => {
1391
+ await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
1392
+ });
1393
+ }
1394
+ await delay(delayMs);
1395
+ }
1396
+ }
1175
1397
  return fullMsg;
1176
1398
  }
1177
1399
  }
1178
1400
  };
1179
- };
1401
+ };