wertybailz 1.0.5

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