queenruva-sockets 5.6.23

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