@vanzxy/baileys 1.4.0 → 1.4.2

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.

Potentially problematic release.


This version of @vanzxy/baileys might be problematic. Click here for more details.

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