xprov2baileystest 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/WAProto/GenerateStatics.sh +2 -0
  2. package/WAProto/WAProto.proto +4633 -0
  3. package/WAProto/index.js +165059 -0
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.js +105 -0
  7. package/lib/Signal/Group/ciphertext-message.js +15 -0
  8. package/lib/Signal/Group/group-session-builder.js +64 -0
  9. package/lib/Signal/Group/group_cipher.js +96 -0
  10. package/lib/Signal/Group/index.js +57 -0
  11. package/lib/Signal/Group/keyhelper.js +55 -0
  12. package/lib/Signal/Group/queue-job.js +57 -0
  13. package/lib/Signal/Group/sender-chain-key.js +34 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  15. package/lib/Signal/Group/sender-key-message.js +69 -0
  16. package/lib/Signal/Group/sender-key-name.js +51 -0
  17. package/lib/Signal/Group/sender-key-record.js +53 -0
  18. package/lib/Signal/Group/sender-key-state.js +99 -0
  19. package/lib/Signal/Group/sender-message-key.js +29 -0
  20. package/lib/Signal/libsignal.js +174 -0
  21. package/lib/Socket/Client/index.js +18 -0
  22. package/lib/Socket/Client/types.js +13 -0
  23. package/lib/Socket/Client/websocket.js +62 -0
  24. package/lib/Socket/business.js +260 -0
  25. package/lib/Socket/chats.js +880 -0
  26. package/lib/Socket/gcstatus.js +237 -0
  27. package/lib/Socket/groups.js +340 -0
  28. package/lib/Socket/index.js +10 -0
  29. package/lib/Socket/messages-recv.js +1079 -0
  30. package/lib/Socket/messages-send.js +1164 -0
  31. package/lib/Socket/mex.js +46 -0
  32. package/lib/Socket/newsletter.js +234 -0
  33. package/lib/Socket/socket.js +617 -0
  34. package/lib/Socket/usync.js +65 -0
  35. package/lib/Types/Auth.js +2 -0
  36. package/lib/Types/Call.js +2 -0
  37. package/lib/Types/Chat.js +10 -0
  38. package/lib/Types/Contact.js +2 -0
  39. package/lib/Types/Events.js +2 -0
  40. package/lib/Types/GroupMetadata.js +2 -0
  41. package/lib/Types/Label.js +27 -0
  42. package/lib/Types/LabelAssociation.js +9 -0
  43. package/lib/Types/Message.js +7 -0
  44. package/lib/Types/Newsletter.js +33 -0
  45. package/lib/Types/Product.js +2 -0
  46. package/lib/Types/Signal.js +2 -0
  47. package/lib/Types/Socket.js +2 -0
  48. package/lib/Types/State.js +2 -0
  49. package/lib/Types/USync.js +2 -0
  50. package/lib/Types/index.js +42 -0
  51. package/lib/Utils/auth-utils.js +199 -0
  52. package/lib/Utils/baileys-event-stream.js +63 -0
  53. package/lib/Utils/business.js +240 -0
  54. package/lib/Utils/chat-utils.js +741 -0
  55. package/lib/Utils/crypto.js +187 -0
  56. package/lib/Utils/decode-wa-message.js +284 -0
  57. package/lib/Utils/event-buffer.js +516 -0
  58. package/lib/Utils/generics.js +401 -0
  59. package/lib/Utils/history.js +100 -0
  60. package/lib/Utils/index.js +34 -0
  61. package/lib/Utils/lid-mapping.js +88 -0
  62. package/lib/Utils/link-preview.js +122 -0
  63. package/lib/Utils/logger.js +7 -0
  64. package/lib/Utils/lt-hash.js +51 -0
  65. package/lib/Utils/make-mutex.js +44 -0
  66. package/lib/Utils/messages-media.js +706 -0
  67. package/lib/Utils/messages.js +1192 -0
  68. package/lib/Utils/noise-handler.js +150 -0
  69. package/lib/Utils/process-message.js +381 -0
  70. package/lib/Utils/signal.js +155 -0
  71. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  72. package/lib/Utils/validate-connection.js +170 -0
  73. package/lib/WABinary/constants.js +1303 -0
  74. package/lib/WABinary/decode.js +266 -0
  75. package/lib/WABinary/encode.js +252 -0
  76. package/lib/WABinary/generic-utils.js +110 -0
  77. package/lib/WABinary/index.js +21 -0
  78. package/lib/WABinary/jid-utils.js +66 -0
  79. package/lib/WABinary/types.js +2 -0
  80. package/lib/WAM/BinaryInfo.js +13 -0
  81. package/lib/WAM/constants.js +15243 -0
  82. package/lib/WAM/encode.js +153 -0
  83. package/lib/WAM/index.js +19 -0
  84. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  85. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  86. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  87. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  88. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  89. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  90. package/lib/WAUSync/Protocols/index.js +20 -0
  91. package/lib/WAUSync/USyncQuery.js +93 -0
  92. package/lib/WAUSync/USyncUser.js +26 -0
  93. package/lib/WAUSync/index.js +19 -0
  94. package/lib/index.js +30 -0
  95. package/package.json +32 -0
@@ -0,0 +1,1164 @@
1
+ "use strict";
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.makeMessagesSocket = void 0;
9
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
10
+ const boom_1 = require("@hapi/boom");
11
+ const WAProto_1 = require("../../WAProto");
12
+ const Defaults_1 = require("../Defaults");
13
+ const Utils_1 = require("../Utils");
14
+ const link_preview_1 = require("../Utils/link-preview");
15
+ const WABinary_1 = require("../WABinary");
16
+ const WAUSync_1 = require("../WAUSync");
17
+ const groups_1 = require("./groups");
18
+ const newsletter_1 = require("./newsletter");
19
+ const GiftedStatus = require("./gcstatus");
20
+
21
+ // Permanently blacklist device JIDs that WhatsApp rejects with not-acceptable.
22
+ const _deadDeviceJids = new Set();
23
+
24
+ const makeMessagesSocket = (config) => {
25
+ const {
26
+ logger,
27
+ linkPreviewImageThumbnailWidth,
28
+ generateHighQualityLinkPreview,
29
+ options: axiosOptions,
30
+ patchMessageBeforeSending,
31
+ cachedGroupMetadata,
32
+ } = config;
33
+ const sock = (0, newsletter_1.makeNewsletterSocket)(
34
+ (0, groups_1.makeGroupsSocket)(config),
35
+ );
36
+ const {
37
+ ev,
38
+ authState,
39
+ processingMutex,
40
+ signalRepository,
41
+ upsertMessage,
42
+ query,
43
+ fetchPrivacySettings,
44
+ sendNode,
45
+ groupMetadata,
46
+ groupToggleEphemeral,
47
+ } = sock;
48
+ const userDevicesCache =
49
+ config.userDevicesCache ||
50
+ new node_cache_1.default({
51
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
52
+ useClones: false,
53
+ });
54
+ let mediaConn;
55
+
56
+ const refreshMediaConn = async (forceGet = false) => {
57
+ const media = await mediaConn;
58
+ if (
59
+ !media ||
60
+ forceGet ||
61
+ new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000
62
+ ) {
63
+ mediaConn = (async () => {
64
+ const result = await query({
65
+ tag: "iq",
66
+ attrs: {
67
+ type: "set",
68
+ xmlns: "w:m",
69
+ to: WABinary_1.S_WHATSAPP_NET,
70
+ },
71
+ content: [{ tag: "media_conn", attrs: {} }],
72
+ });
73
+ const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(
74
+ result,
75
+ "media_conn",
76
+ );
77
+ const node = {
78
+ hosts: (0, WABinary_1.getBinaryNodeChildren)(
79
+ mediaConnNode,
80
+ "host",
81
+ ).map(({ attrs }) => ({
82
+ hostname: attrs.hostname,
83
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
84
+ })),
85
+ auth: mediaConnNode.attrs.auth,
86
+ ttl: +mediaConnNode.attrs.ttl,
87
+ fetchDate: new Date(),
88
+ };
89
+ logger.debug("fetched media conn");
90
+ return node;
91
+ })();
92
+ }
93
+ return mediaConn;
94
+ };
95
+
96
+ const sendReceipt = async (jid, participant, messageIds, type) => {
97
+ const node = {
98
+ tag: "receipt",
99
+ attrs: {
100
+ id: messageIds[0],
101
+ },
102
+ };
103
+ const isReadReceipt = type === "read" || type === "read-self";
104
+ if (isReadReceipt) {
105
+ node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
106
+ }
107
+ if (type === "sender" && (0, WABinary_1.isJidUser)(jid)) {
108
+ node.attrs.recipient = jid;
109
+ node.attrs.to = participant;
110
+ } else {
111
+ node.attrs.to = jid;
112
+ if (participant) {
113
+ node.attrs.participant = participant;
114
+ }
115
+ }
116
+ if (type) {
117
+ node.attrs.type = type;
118
+ }
119
+ const remainingMessageIds = messageIds.slice(1);
120
+ if (remainingMessageIds.length) {
121
+ node.content = [
122
+ {
123
+ tag: "list",
124
+ attrs: {},
125
+ content: remainingMessageIds.map((id) => ({
126
+ tag: "item",
127
+ attrs: { id },
128
+ })),
129
+ },
130
+ ];
131
+ }
132
+ logger.debug(
133
+ { attrs: node.attrs, messageIds },
134
+ "sending receipt for messages",
135
+ );
136
+ await sendNode(node);
137
+ };
138
+
139
+ const sendReceipts = async (keys, type) => {
140
+ const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
141
+ for (const { jid, participant, messageIds } of recps) {
142
+ await sendReceipt(jid, participant, messageIds, type);
143
+ }
144
+ };
145
+
146
+ const readMessages = async (keys) => {
147
+ const privacySettings = await fetchPrivacySettings();
148
+ const readType =
149
+ privacySettings.readreceipts === "all" ? "read" : "read-self";
150
+ await sendReceipts(keys, readType);
151
+ };
152
+
153
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
154
+ var _a;
155
+ const deviceResults = [];
156
+ if (!useCache) {
157
+ logger.debug("not using cache for devices");
158
+ }
159
+ const toFetch = [];
160
+ jids = Array.from(new Set(jids));
161
+ for (let jid of jids) {
162
+ const user =
163
+ (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0
164
+ ? void 0
165
+ : _a.user;
166
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
167
+ if (useCache) {
168
+ const devices = userDevicesCache.get(user);
169
+ if (devices) {
170
+ deviceResults.push(...devices);
171
+ logger.trace({ user }, "using cache for devices");
172
+ } else {
173
+ toFetch.push(jid);
174
+ }
175
+ } else {
176
+ toFetch.push(jid);
177
+ }
178
+ }
179
+ if (!toFetch.length) {
180
+ return deviceResults;
181
+ }
182
+ const query = new WAUSync_1.USyncQuery()
183
+ .withContext("message")
184
+ .withDeviceProtocol();
185
+ for (const jid of toFetch) {
186
+ query.withUser(new WAUSync_1.USyncUser().withId(jid));
187
+ }
188
+ const result = await sock.executeUSyncQuery(query);
189
+ if (result) {
190
+ const extracted = (0, Utils_1.extractDeviceJids)(
191
+ result === null || result === void 0 ? void 0 : result.list,
192
+ authState.creds.me.id,
193
+ ignoreZeroDevices,
194
+ );
195
+ const deviceMap = {};
196
+ for (const item of extracted) {
197
+ deviceMap[item.user] = deviceMap[item.user] || [];
198
+ deviceMap[item.user].push(item);
199
+ deviceResults.push(item);
200
+ }
201
+ for (const key in deviceMap) {
202
+ userDevicesCache.set(key, deviceMap[key]);
203
+ }
204
+ }
205
+ return deviceResults;
206
+ };
207
+
208
+ const assertSessions = async (jids, force) => {
209
+ let didFetchNewSession = false;
210
+ let jidsRequiringFetch = [];
211
+ const liveJids = jids.filter(j => !_deadDeviceJids.has(j));
212
+ if (force) {
213
+ jidsRequiringFetch = liveJids;
214
+ } else {
215
+ const addrs = liveJids.map((jid) =>
216
+ signalRepository.jidToSignalProtocolAddress(jid),
217
+ );
218
+ const sessions = await authState.keys.get("session", addrs);
219
+ for (const jid of liveJids) {
220
+ const signalId =
221
+ signalRepository.jidToSignalProtocolAddress(jid);
222
+ if (!sessions[signalId]) {
223
+ jidsRequiringFetch.push(jid);
224
+ }
225
+ }
226
+ }
227
+ if (jidsRequiringFetch.length) {
228
+ logger.debug({ jidsRequiringFetch }, "fetching sessions");
229
+ const doPreKeyIQ = async (jidList) => {
230
+ return query({
231
+ tag: "iq",
232
+ attrs: {
233
+ xmlns: "encrypt",
234
+ type: "get",
235
+ to: WABinary_1.S_WHATSAPP_NET,
236
+ },
237
+ content: [
238
+ {
239
+ tag: "key",
240
+ attrs: {},
241
+ content: jidList.map((jid) => ({
242
+ tag: "user",
243
+ attrs: { jid },
244
+ })),
245
+ },
246
+ ],
247
+ });
248
+ };
249
+ let batchOk = false;
250
+ if (jidsRequiringFetch.length > 1) {
251
+ try {
252
+ const result = await doPreKeyIQ(jidsRequiringFetch);
253
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
254
+ didFetchNewSession = true;
255
+ batchOk = true;
256
+ } catch (batchErr) {
257
+ logger.debug({ batchErr: batchErr.message }, "batch prekey IQ failed, retrying per-JID");
258
+ }
259
+ }
260
+ if (!batchOk) {
261
+ for (const jid of jidsRequiringFetch) {
262
+ try {
263
+ const result = await doPreKeyIQ([jid]);
264
+ await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
265
+ didFetchNewSession = true;
266
+ } catch (singleErr) {
267
+ _deadDeviceJids.add(jid);
268
+ logger.debug({ jid, err: singleErr.message }, "blacklisting dead device");
269
+ }
270
+ }
271
+ }
272
+ }
273
+ return didFetchNewSession;
274
+ };
275
+
276
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
277
+ var _a;
278
+ if (
279
+ !((_a = authState.creds.me) === null || _a === void 0
280
+ ? void 0
281
+ : _a.id)
282
+ ) {
283
+ throw new boom_1.Boom("Not authenticated");
284
+ }
285
+ const protocolMessage = {
286
+ protocolMessage: {
287
+ peerDataOperationRequestMessage: pdoMessage,
288
+ type: WAProto_1.proto.Message.ProtocolMessage.Type
289
+ .PEER_DATA_OPERATION_REQUEST_MESSAGE,
290
+ },
291
+ };
292
+ const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
293
+ const msgId = await relayMessage(meJid, protocolMessage, {
294
+ additionalAttributes: {
295
+ category: "peer",
296
+ push_priority: "high_force",
297
+ },
298
+ });
299
+ return msgId;
300
+ };
301
+
302
+ const createParticipantNodes = async (jids, message, extraAttrs) => {
303
+ let patched = await patchMessageBeforeSending(message, jids);
304
+ if (!Array.isArray(patched)) {
305
+ patched = jids
306
+ ? jids.map((jid) => ({ recipientJid: jid, ...patched }))
307
+ : [patched];
308
+ }
309
+ let shouldIncludeDeviceIdentity = false;
310
+ const nodes = await Promise.all(
311
+ patched.map(async (patchedMessageWithJid) => {
312
+ const { recipientJid: jid, ...patchedMessage } =
313
+ patchedMessageWithJid;
314
+ if (!jid) {
315
+ return {};
316
+ }
317
+ const bytes = (0, Utils_1.encodeWAMessage)(patchedMessage);
318
+ const { type, ciphertext } =
319
+ await signalRepository.encryptMessage({ jid, data: bytes });
320
+ if (type === "pkmsg") {
321
+ shouldIncludeDeviceIdentity = true;
322
+ }
323
+ const node = {
324
+ tag: "to",
325
+ attrs: { jid },
326
+ content: [
327
+ {
328
+ tag: "enc",
329
+ attrs: {
330
+ v: "2",
331
+ type,
332
+ ...(extraAttrs || {}),
333
+ },
334
+ content: ciphertext,
335
+ },
336
+ ],
337
+ };
338
+ return node;
339
+ }),
340
+ );
341
+ return { nodes, shouldIncludeDeviceIdentity };
342
+ };
343
+
344
+ // Helper to check if message has buttons
345
+ const hasButtonContent = (message) => {
346
+ const content = (0, Utils_1.normalizeMessageContent)(message);
347
+ if (!content) return false;
348
+ return !!(content.buttonsMessage ||
349
+ content.buttonsResponseMessage ||
350
+ content.listMessage ||
351
+ content.listResponseMessage ||
352
+ content.interactiveMessage ||
353
+ content.interactiveResponseMessage ||
354
+ content.nativeFlowMessage ||
355
+ content.templateMessage);
356
+ };
357
+
358
+ // Helper to get biz node for buttons
359
+ const getBizNodeForButtons = (message) => {
360
+ const content = (0, Utils_1.normalizeMessageContent)(message);
361
+ if (!content) return null;
362
+
363
+ if (content.buttonsMessage || content.interactiveMessage || content.nativeFlowMessage) {
364
+ return {
365
+ tag: "biz",
366
+ attrs: {},
367
+ content: [{
368
+ tag: "interactive",
369
+ attrs: {
370
+ type: "native_flow",
371
+ v: "1"
372
+ },
373
+ content: [{
374
+ tag: "native_flow",
375
+ attrs: { v: "9", name: "mixed" }
376
+ }]
377
+ }]
378
+ };
379
+ }
380
+
381
+ if (content.listMessage) {
382
+ return {
383
+ tag: "biz",
384
+ attrs: {},
385
+ content: [{
386
+ tag: "list",
387
+ attrs: {
388
+ type: "product_list",
389
+ v: "2"
390
+ }
391
+ }]
392
+ };
393
+ }
394
+
395
+ return null;
396
+ };
397
+
398
+ // Helper to check if message is a group status
399
+ const isGroupStatusMessage = (message) => {
400
+ const content = (0, Utils_1.normalizeMessageContent)(message);
401
+ if (!content) return false;
402
+ return !!(content.groupStatusMessage || content.groupStatusMessageV2);
403
+ };
404
+
405
+ // CRITICAL FIX: getMessageType should check normalized content
406
+ const getMessageType = (message) => {
407
+ const normalized = (0, Utils_1.normalizeMessageContent)(message);
408
+
409
+ // Check for group status messages
410
+ if (normalized?.groupStatusMessage) return "text";
411
+ if (normalized?.groupStatusMessageV2) return "text";
412
+
413
+ // Check for poll messages
414
+ if (normalized?.pollCreationMessage ||
415
+ normalized?.pollCreationMessageV2 ||
416
+ normalized?.pollCreationMessageV3) {
417
+ return "poll";
418
+ }
419
+
420
+ // Check for media messages using normalized content
421
+ const mediaType = getMediaTypeFromNormalized(normalized);
422
+ if (mediaType) {
423
+ return "text"; // Media messages use "text" type
424
+ }
425
+
426
+ return "text";
427
+ };
428
+
429
+ // CRITICAL FIX: Media type detection from normalized content
430
+ const getMediaTypeFromNormalized = (normalized) => {
431
+ if (!normalized) return;
432
+
433
+ // Only return actual media types
434
+ if (normalized.imageMessage) return "image";
435
+ if (normalized.videoMessage) return normalized.videoMessage.gifPlayback ? "gif" : "video";
436
+ if (normalized.audioMessage) return normalized.audioMessage.ptt ? "ptt" : "audio";
437
+ if (normalized.contactMessage) return "vcard";
438
+ if (normalized.documentMessage) return "document";
439
+ if (normalized.contactsArrayMessage) return "contact_array";
440
+ if (normalized.liveLocationMessage) return "livelocation";
441
+ if (normalized.stickerMessage) return "sticker";
442
+ if (normalized.orderMessage) return "order";
443
+ if (normalized.productMessage) return "product";
444
+ if (normalized.groupInviteMessage) return "url";
445
+
446
+ // Handle group status messages with media
447
+ if (normalized.groupStatusMessageV2) {
448
+ const innerMsg = normalized.groupStatusMessageV2.message || {};
449
+ if (innerMsg.imageMessage) return "image";
450
+ if (innerMsg.videoMessage) return innerMsg.videoMessage.gifPlayback ? "gif" : "video";
451
+ if (innerMsg.audioMessage) return innerMsg.audioMessage.ptt ? "ptt" : "audio";
452
+ if (innerMsg.stickerMessage) return "sticker";
453
+ }
454
+
455
+ return;
456
+ };
457
+
458
+ // Keep original getMediaType for backward compatibility but use normalized version internally
459
+ const getMediaType = (message) => {
460
+ const normalized = (0, Utils_1.normalizeMessageContent)(message);
461
+ return getMediaTypeFromNormalized(normalized);
462
+ };
463
+
464
+ const relayMessage = async (
465
+ jid,
466
+ message,
467
+ {
468
+ messageId: msgId,
469
+ participant,
470
+ additionalAttributes,
471
+ additionalNodes,
472
+ useUserDevicesCache,
473
+ useCachedGroupMetadata,
474
+ statusJidList,
475
+ },
476
+ ) => {
477
+ var _a;
478
+ const meId = authState.creds.me.id;
479
+ let shouldIncludeDeviceIdentity = false;
480
+ const { user, server } = (0, WABinary_1.jidDecode)(jid);
481
+ const statusJid = "status@broadcast";
482
+ const isGroup = server === "g.us";
483
+ const isStatus = jid === statusJid;
484
+ const isLid = server === "lid";
485
+ const isNewsletter = server === "newsletter";
486
+ msgId =
487
+ msgId ||
488
+ (0, Utils_1.generateMessageIDV2)(
489
+ (_a = sock.user) === null || _a === void 0 ? void 0 : _a.id,
490
+ );
491
+ useUserDevicesCache = useUserDevicesCache !== false;
492
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
493
+ const participants = [];
494
+ const destinationJid = !isStatus
495
+ ? (0, WABinary_1.jidEncode)(
496
+ user,
497
+ isLid ? "lid" : isGroup ? "g.us" : "s.whatsapp.net",
498
+ )
499
+ : statusJid;
500
+ const binaryNodeContent = [];
501
+ const devices = [];
502
+ const meMsg = {
503
+ deviceSentMessage: {
504
+ destinationJid,
505
+ message,
506
+ },
507
+ messageContextInfo: message.messageContextInfo,
508
+ };
509
+ const extraAttrs = {};
510
+
511
+ if (participant) {
512
+ if (!isGroup && !isStatus) {
513
+ additionalAttributes = {
514
+ ...additionalAttributes,
515
+ device_fanout: "false",
516
+ };
517
+ }
518
+ const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
519
+ devices.push({ user, device });
520
+ }
521
+
522
+ await authState.keys.transaction(async () => {
523
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
524
+
525
+ const mediaType = getMediaType(message);
526
+ if (mediaType) {
527
+ extraAttrs["mediatype"] = mediaType;
528
+ }
529
+
530
+ if (isNewsletter) {
531
+ const patched = patchMessageBeforeSending
532
+ ? await patchMessageBeforeSending(message, [])
533
+ : message;
534
+ const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
535
+ binaryNodeContent.push({
536
+ tag: "plaintext",
537
+ attrs: {},
538
+ content: bytes,
539
+ });
540
+ const stanza = {
541
+ tag: "message",
542
+ attrs: {
543
+ to: jid,
544
+ id: msgId,
545
+ type: getMessageType(message),
546
+ ...(additionalAttributes || {}),
547
+ },
548
+ content: binaryNodeContent,
549
+ };
550
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
551
+ await sendNode(stanza);
552
+ return;
553
+ }
554
+
555
+ if (
556
+ (_a = (0, Utils_1.normalizeMessageContent)(message)) === null ||
557
+ _a === void 0
558
+ ? void 0
559
+ : _a.pinInChatMessage
560
+ ) {
561
+ extraAttrs["decrypt-fail"] = "hide";
562
+ }
563
+
564
+ if (isGroup || isStatus) {
565
+ const [groupData, senderKeyMap] = await Promise.all([
566
+ (async () => {
567
+ let groupData =
568
+ useCachedGroupMetadata && cachedGroupMetadata
569
+ ? await cachedGroupMetadata(jid)
570
+ : undefined;
571
+ if (
572
+ groupData &&
573
+ Array.isArray(
574
+ groupData === null || groupData === void 0
575
+ ? void 0
576
+ : groupData.participants,
577
+ )
578
+ ) {
579
+ logger.trace(
580
+ {
581
+ jid,
582
+ participants: groupData.participants.length,
583
+ },
584
+ "using cached group metadata",
585
+ );
586
+ } else if (!isStatus) {
587
+ groupData = await groupMetadata(jid);
588
+ }
589
+ return groupData;
590
+ })(),
591
+ (async () => {
592
+ if (!participant && !isStatus) {
593
+ const result = await authState.keys.get(
594
+ "sender-key-memory",
595
+ [jid],
596
+ );
597
+ return result[jid] || {};
598
+ }
599
+ return {};
600
+ })(),
601
+ ]);
602
+
603
+ if (!participant) {
604
+ const participantsList =
605
+ groupData && !isStatus
606
+ ? groupData.participants.map((p) => p.id)
607
+ : [];
608
+ if (isStatus) {
609
+ const normalizedMeId = (0, WABinary_1.jidNormalizedUser)(meId);
610
+ if (!participantsList.includes(normalizedMeId)) {
611
+ participantsList.push(normalizedMeId);
612
+ }
613
+ const meLid = authState.creds.me?.lid;
614
+ if (meLid) {
615
+ const normalizedMeLid = (0, WABinary_1.jidNormalizedUser)(meLid);
616
+ if (!participantsList.includes(normalizedMeLid)) {
617
+ participantsList.push(normalizedMeLid);
618
+ }
619
+ }
620
+ if (statusJidList && Array.isArray(statusJidList) && statusJidList.length > 0) {
621
+ for (const jidItem of statusJidList) {
622
+ const normalizedJid = (0, WABinary_1.jidNormalizedUser)(jidItem);
623
+ if (!participantsList.includes(normalizedJid)) {
624
+ participantsList.push(normalizedJid);
625
+ }
626
+ }
627
+ } else {
628
+ logger.warn({ meId }, 'No statusJidList provided for status message');
629
+ }
630
+ logger.debug({ participantsList, statusJidList }, 'Status message participants');
631
+ }
632
+
633
+ if (!isStatus) {
634
+ additionalAttributes = {
635
+ ...additionalAttributes,
636
+ addressing_mode:
637
+ (groupData === null || groupData === void 0
638
+ ? void 0
639
+ : groupData.addressingMode) || "pn",
640
+ };
641
+ }
642
+
643
+ const additionalDevices = await getUSyncDevices(
644
+ participantsList,
645
+ !!useUserDevicesCache,
646
+ false,
647
+ );
648
+ devices.push(...additionalDevices);
649
+ }
650
+
651
+ const patched = await patchMessageBeforeSending(message);
652
+ if (Array.isArray(patched)) {
653
+ throw new boom_1.Boom(
654
+ "Per-jid patching is not supported in groups",
655
+ );
656
+ }
657
+
658
+ const bytes = (0, Utils_1.encodeWAMessage)(patched);
659
+ const { ciphertext, senderKeyDistributionMessage } =
660
+ await signalRepository.encryptGroupMessage({
661
+ group: destinationJid,
662
+ data: bytes,
663
+ meId,
664
+ });
665
+
666
+ const senderKeyJids = [];
667
+ for (const { user, device } of devices) {
668
+ const jid = (0, WABinary_1.jidEncode)(
669
+ user,
670
+ (groupData === null || groupData === void 0
671
+ ? void 0
672
+ : groupData.addressingMode) === "lid"
673
+ ? "lid"
674
+ : "s.whatsapp.net",
675
+ device,
676
+ );
677
+ if (!senderKeyMap[jid] || !!participant) {
678
+ if (_deadDeviceJids.has(jid)) {
679
+ senderKeyMap[jid] = true;
680
+ } else {
681
+ senderKeyJids.push(jid);
682
+ senderKeyMap[jid] = true;
683
+ }
684
+ }
685
+ }
686
+
687
+ if (senderKeyJids.length) {
688
+ logger.debug({ senderKeyJids }, "sending new sender key");
689
+ const senderKeyMsg = {
690
+ senderKeyDistributionMessage: {
691
+ axolotlSenderKeyDistributionMessage:
692
+ senderKeyDistributionMessage,
693
+ groupId: destinationJid,
694
+ },
695
+ };
696
+ await assertSessions(senderKeyJids, false);
697
+
698
+ const sessionAddrs = senderKeyJids.map(sjid =>
699
+ signalRepository.jidToSignalProtocolAddress(sjid)
700
+ );
701
+ const sessCheck = await authState.keys.get('session', sessionAddrs);
702
+ const validSenderKeyJids = senderKeyJids.filter((sjid, i) =>
703
+ !!sessCheck[sessionAddrs[i]]
704
+ );
705
+
706
+ const result = await createParticipantNodes(
707
+ validSenderKeyJids,
708
+ senderKeyMsg,
709
+ extraAttrs,
710
+ );
711
+ shouldIncludeDeviceIdentity =
712
+ shouldIncludeDeviceIdentity ||
713
+ result.shouldIncludeDeviceIdentity;
714
+ participants.push(...result.nodes);
715
+ }
716
+
717
+ binaryNodeContent.push({
718
+ tag: "enc",
719
+ attrs: { v: "2", type: "skmsg" },
720
+ content: ciphertext,
721
+ });
722
+
723
+ await authState.keys.set({
724
+ "sender-key-memory": { [jid]: senderKeyMap },
725
+ });
726
+ } else {
727
+ const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
728
+ const meLid =
729
+ (_b =
730
+ (_c = authState.creds) === null || _c === void 0
731
+ ? void 0
732
+ : _c.me) === null || _b === void 0
733
+ ? void 0
734
+ : _b.lid;
735
+ const meLidUser =
736
+ meLid === null || meLid === void 0
737
+ ? void 0
738
+ : meLid.split(":")[0];
739
+ const mePhone =
740
+ meUser === null || meUser === void 0
741
+ ? void 0
742
+ : meUser.split(":")[0];
743
+
744
+ if (!participant) {
745
+ devices.push({ user });
746
+ const isSelfMessage =
747
+ user === meUser ||
748
+ user === mePhone ||
749
+ user === meLidUser;
750
+ if (!isSelfMessage) {
751
+ devices.push({ user: meUser });
752
+ }
753
+ if (
754
+ (additionalAttributes === null ||
755
+ additionalAttributes === void 0
756
+ ? void 0
757
+ : additionalAttributes["category"]) !== "peer"
758
+ ) {
759
+ const targetJid = isLid
760
+ ? jid
761
+ : (0, WABinary_1.jidNormalizedUser)(jid);
762
+ const additionalDevices = await getUSyncDevices(
763
+ [meId, targetJid],
764
+ !!useUserDevicesCache,
765
+ true,
766
+ );
767
+ devices.push(...additionalDevices);
768
+ }
769
+ }
770
+
771
+ const allJids = [];
772
+ const meJids = [];
773
+ const otherJids = [];
774
+ for (const { user: deviceUser, device } of devices) {
775
+ const isMe =
776
+ deviceUser === meUser ||
777
+ deviceUser === mePhone ||
778
+ deviceUser === meLidUser;
779
+ let encodedJid;
780
+
781
+ if (isMe) {
782
+ encodedJid = (0, WABinary_1.jidEncode)(
783
+ isLid ? meLidUser || mePhone : mePhone,
784
+ isLid ? "lid" : "s.whatsapp.net",
785
+ device,
786
+ );
787
+ } else {
788
+ encodedJid = (0, WABinary_1.jidEncode)(
789
+ deviceUser,
790
+ isLid ? "lid" : "s.whatsapp.net",
791
+ device,
792
+ );
793
+ }
794
+
795
+ if (isMe) {
796
+ meJids.push(encodedJid);
797
+ } else {
798
+ otherJids.push(encodedJid);
799
+ }
800
+ allJids.push(encodedJid);
801
+ }
802
+
803
+ await assertSessions(allJids, false);
804
+
805
+ const [
806
+ { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
807
+ { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 },
808
+ ] = await Promise.all([
809
+ createParticipantNodes(meJids, meMsg, extraAttrs),
810
+ createParticipantNodes(otherJids, message, extraAttrs),
811
+ ]);
812
+
813
+ participants.push(...meNodes);
814
+ participants.push(...otherNodes);
815
+ shouldIncludeDeviceIdentity =
816
+ shouldIncludeDeviceIdentity || s1 || s2;
817
+ }
818
+
819
+ if (participants.length) {
820
+ if (
821
+ (additionalAttributes === null ||
822
+ additionalAttributes === void 0
823
+ ? void 0
824
+ : additionalAttributes["category"]) === "peer"
825
+ ) {
826
+ const peerNode =
827
+ (_e =
828
+ (_d = participants[0]) === null || _d === void 0
829
+ ? void 0
830
+ : _d.content) === null || _e === void 0
831
+ ? void 0
832
+ : _e[0];
833
+ if (peerNode) {
834
+ binaryNodeContent.push(peerNode);
835
+ }
836
+ } else {
837
+ binaryNodeContent.push({
838
+ tag: "participants",
839
+ attrs: {},
840
+ content: participants,
841
+ });
842
+ }
843
+ }
844
+
845
+ // CRITICAL FIX: Check if this is a media message
846
+ const normalizedMsg = (0, Utils_1.normalizeMessageContent)(message);
847
+ const isMediaMessage = !!(normalizedMsg?.imageMessage ||
848
+ normalizedMsg?.videoMessage ||
849
+ normalizedMsg?.audioMessage ||
850
+ normalizedMsg?.documentMessage ||
851
+ normalizedMsg?.stickerMessage);
852
+
853
+ const isButtonMessage = hasButtonContent(message);
854
+
855
+ // IMPORTANT: Only add biz node for standalone buttons (NO media)
856
+ // Media messages with buttons should NOT get a separate biz node
857
+ if (!isNewsletter && !isGroupStatusMessage(message) && isButtonMessage && !isMediaMessage) {
858
+ const bizNode = getBizNodeForButtons(message);
859
+ if (bizNode) {
860
+ binaryNodeContent.push(bizNode);
861
+ logger.debug({ jid }, "adding biz node for standalone buttons");
862
+ }
863
+ }
864
+
865
+ const stanza = {
866
+ tag: "message",
867
+ attrs: {
868
+ id: msgId,
869
+ type: getMessageType(message),
870
+ ...(additionalAttributes || {}),
871
+ },
872
+ content: binaryNodeContent,
873
+ };
874
+
875
+ if (participant) {
876
+ if ((0, WABinary_1.isJidGroup)(destinationJid)) {
877
+ stanza.attrs.to = destinationJid;
878
+ stanza.attrs.participant = participant.jid;
879
+ } else if (
880
+ (0, WABinary_1.areJidsSameUser)(participant.jid, meId)
881
+ ) {
882
+ stanza.attrs.to = participant.jid;
883
+ stanza.attrs.recipient = destinationJid;
884
+ } else {
885
+ stanza.attrs.to = participant.jid;
886
+ }
887
+ } else {
888
+ stanza.attrs.to = destinationJid;
889
+ }
890
+
891
+ if (shouldIncludeDeviceIdentity) {
892
+ stanza.content.push({
893
+ tag: "device-identity",
894
+ attrs: {},
895
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(
896
+ authState.creds.account,
897
+ true,
898
+ ),
899
+ });
900
+ logger.debug({ jid }, "adding device identity");
901
+ }
902
+
903
+ if (additionalNodes && additionalNodes.length > 0) {
904
+ stanza.content.push(...additionalNodes);
905
+ }
906
+
907
+ logger.debug(
908
+ { msgId },
909
+ `sending message to ${participants.length} devices`,
910
+ );
911
+ await sendNode(stanza);
912
+ });
913
+ return msgId;
914
+ };
915
+
916
+ const getPrivacyTokens = async (jids) => {
917
+ const t = (0, Utils_1.unixTimestampSeconds)().toString();
918
+ const result = await query({
919
+ tag: "iq",
920
+ attrs: {
921
+ to: WABinary_1.S_WHATSAPP_NET,
922
+ type: "set",
923
+ xmlns: "privacy",
924
+ },
925
+ content: [
926
+ {
927
+ tag: "tokens",
928
+ attrs: {},
929
+ content: jids.map((jid) => ({
930
+ tag: "token",
931
+ attrs: {
932
+ jid: (0, WABinary_1.jidNormalizedUser)(jid),
933
+ t,
934
+ type: "trusted_contact",
935
+ },
936
+ })),
937
+ },
938
+ ],
939
+ });
940
+ return result;
941
+ };
942
+
943
+ const waUploadToServer = (0, Utils_1.getWAUploadToServer)(
944
+ config,
945
+ refreshMediaConn,
946
+ );
947
+
948
+ const giftedStatus = new GiftedStatus(Utils_1, waUploadToServer, relayMessage, config, sock);
949
+
950
+ const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(
951
+ ev,
952
+ "messages.media-update",
953
+ );
954
+
955
+ return {
956
+ ...sock,
957
+ getPrivacyTokens,
958
+ assertSessions,
959
+ relayMessage,
960
+ sendReceipt,
961
+ sendReceipts,
962
+ readMessages,
963
+ refreshMediaConn,
964
+ waUploadToServer,
965
+ giftedStatus,
966
+ fetchPrivacySettings,
967
+ sendPeerDataOperationMessage,
968
+ createParticipantNodes,
969
+ getUSyncDevices,
970
+ updateMediaMessage: async (message) => {
971
+ const content = (0, Utils_1.assertMediaContent)(message.message);
972
+ const mediaKey = content.mediaKey;
973
+ const meId = authState.creds.me.id;
974
+ const node = await (0, Utils_1.encryptMediaRetryRequest)(
975
+ message.key,
976
+ mediaKey,
977
+ meId,
978
+ );
979
+ let error = undefined;
980
+ await Promise.all([
981
+ sendNode(node),
982
+ waitForMsgMediaUpdate(async (update) => {
983
+ const result = update.find(
984
+ (c) => c.key.id === message.key.id,
985
+ );
986
+ if (result) {
987
+ if (result.error) {
988
+ error = result.error;
989
+ } else {
990
+ try {
991
+ const media = await (0,
992
+ Utils_1.decryptMediaRetryData)(
993
+ result.media,
994
+ mediaKey,
995
+ result.key.id,
996
+ );
997
+ if (
998
+ media.result !==
999
+ WAProto_1.proto.MediaRetryNotification
1000
+ .ResultType.SUCCESS
1001
+ ) {
1002
+ const resultStr =
1003
+ WAProto_1.proto.MediaRetryNotification
1004
+ .ResultType[media.result];
1005
+ throw new boom_1.Boom(
1006
+ `Media re-upload failed by device (${resultStr})`,
1007
+ {
1008
+ data: media,
1009
+ statusCode:
1010
+ (0,
1011
+ Utils_1.getStatusCodeForMediaRetry)(
1012
+ media.result,
1013
+ ) || 404,
1014
+ },
1015
+ );
1016
+ }
1017
+ content.directPath = media.directPath;
1018
+ content.url = (0, Utils_1.getUrlFromDirectPath)(
1019
+ content.directPath,
1020
+ );
1021
+ logger.debug(
1022
+ {
1023
+ directPath: media.directPath,
1024
+ key: result.key,
1025
+ },
1026
+ "media update successful",
1027
+ );
1028
+ } catch (err) {
1029
+ error = err;
1030
+ }
1031
+ }
1032
+ return true;
1033
+ }
1034
+ }),
1035
+ ]);
1036
+ if (error) {
1037
+ throw error;
1038
+ }
1039
+ ev.emit("messages.update", [
1040
+ { key: message.key, update: { message: message.message } },
1041
+ ]);
1042
+ return message;
1043
+ },
1044
+ sendMessage: async (jid, content, options = {}) => {
1045
+ var _a, _b, _c;
1046
+ const userJid = authState.creds.me.id;
1047
+
1048
+ // Handle group status messages FIRST
1049
+ if (typeof content === "object" && content.groupStatusMessage) {
1050
+ return await giftedStatus.handleGroupStory(content, jid, options.quoted);
1051
+ }
1052
+
1053
+ // Handle disappearing messages
1054
+ if (
1055
+ typeof content === "object" &&
1056
+ "disappearingMessagesInChat" in content &&
1057
+ typeof content["disappearingMessagesInChat"] !== "undefined" &&
1058
+ (0, WABinary_1.isJidGroup)(jid)
1059
+ ) {
1060
+ const { disappearingMessagesInChat } = content;
1061
+ const value =
1062
+ typeof disappearingMessagesInChat === "boolean"
1063
+ ? disappearingMessagesInChat
1064
+ ? Defaults_1.WA_DEFAULT_EPHEMERAL
1065
+ : 0
1066
+ : disappearingMessagesInChat;
1067
+ await groupToggleEphemeral(jid, value);
1068
+ return;
1069
+ }
1070
+
1071
+ // Handle ALL other messages (including media without buttons and buttons)
1072
+ const fullMsg = await (0, Utils_1.generateWAMessage)(
1073
+ jid,
1074
+ content,
1075
+ {
1076
+ logger,
1077
+ userJid,
1078
+ getUrlInfo: (text) =>
1079
+ (0, link_preview_1.getUrlInfo)(text, {
1080
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1081
+ fetchOpts: {
1082
+ timeout: 3000,
1083
+ ...(axiosOptions || {}),
1084
+ },
1085
+ logger,
1086
+ uploadImage: generateHighQualityLinkPreview
1087
+ ? waUploadToServer
1088
+ : undefined,
1089
+ }),
1090
+ getProfilePicUrl: sock.profilePictureUrl,
1091
+ upload: waUploadToServer,
1092
+ mediaCache: config.mediaCache,
1093
+ options: config.options,
1094
+ messageId: (0, Utils_1.generateMessageIDV2)(
1095
+ (_a = sock.user) === null || _a === void 0
1096
+ ? void 0
1097
+ : _a.id,
1098
+ ),
1099
+ ...options,
1100
+ },
1101
+ );
1102
+
1103
+ const isDeleteMsg = "delete" in content && !!content.delete;
1104
+ const isEditMsg = "edit" in content && !!content.edit;
1105
+ const isPinMsg = "pin" in content && !!content.pin;
1106
+ const isPollMessage = "poll" in content && !!content.poll;
1107
+
1108
+ const additionalAttributes = {};
1109
+ const additionalNodes = [];
1110
+
1111
+ if (isDeleteMsg) {
1112
+ if (
1113
+ (0, WABinary_1.isJidGroup)(
1114
+ (_b = content.delete) === null || _b === void 0
1115
+ ? void 0
1116
+ : _b.remoteJid,
1117
+ ) &&
1118
+ !((_c = content.delete) === null || _c === void 0
1119
+ ? void 0
1120
+ : _c.fromMe)
1121
+ ) {
1122
+ additionalAttributes.edit = "8";
1123
+ } else {
1124
+ additionalAttributes.edit = "7";
1125
+ }
1126
+ } else if (isEditMsg) {
1127
+ additionalAttributes.edit = "1";
1128
+ } else if (isPinMsg) {
1129
+ additionalAttributes.edit = "2";
1130
+ } else if (isPollMessage) {
1131
+ additionalNodes.push({
1132
+ tag: "meta",
1133
+ attrs: {
1134
+ polltype: "creation",
1135
+ },
1136
+ });
1137
+ }
1138
+
1139
+ if ("cachedGroupMetadata" in options) {
1140
+ console.warn(
1141
+ "cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.",
1142
+ );
1143
+ }
1144
+
1145
+ await relayMessage(jid, fullMsg.message, {
1146
+ messageId: fullMsg.key.id,
1147
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1148
+ additionalAttributes,
1149
+ statusJidList: options.statusJidList,
1150
+ additionalNodes,
1151
+ });
1152
+
1153
+ if (config.emitOwnEvents) {
1154
+ process.nextTick(() => {
1155
+ processingMutex.mutex(() =>
1156
+ upsertMessage(fullMsg, "append"),
1157
+ );
1158
+ });
1159
+ }
1160
+ return fullMsg;
1161
+ },
1162
+ };
1163
+ };
1164
+ exports.makeMessagesSocket = makeMessagesSocket;