@sgintokic/baileys 0.0.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 @sgintokic/baileys might be problematic. Click here for more details.

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