@lekzsync/baileys 0.0.0-stage → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (128) hide show
  1. package/README.md +577 -2
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +7014 -0
  4. package/WAProto/fix-imports.js +85 -0
  5. package/WAProto/index.d.ts +79257 -0
  6. package/WAProto/index.js +242946 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +131 -0
  9. package/lib/Signal/Group/ciphertext-message.js +12 -0
  10. package/lib/Signal/Group/group-session-builder.js +30 -0
  11. package/lib/Signal/Group/group_cipher.js +82 -0
  12. package/lib/Signal/Group/index.js +12 -0
  13. package/lib/Signal/Group/keyhelper.js +18 -0
  14. package/lib/Signal/Group/sender-chain-key.js +26 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  16. package/lib/Signal/Group/sender-key-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-name.js +48 -0
  18. package/lib/Signal/Group/sender-key-record.js +41 -0
  19. package/lib/Signal/Group/sender-key-state.js +84 -0
  20. package/lib/Signal/Group/sender-message-key.js +26 -0
  21. package/lib/Signal/libsignal.js +431 -0
  22. package/lib/Signal/lid-mapping.js +277 -0
  23. package/lib/Socket/Client/index.js +3 -0
  24. package/lib/Socket/Client/types.js +11 -0
  25. package/lib/Socket/Client/websocket.js +54 -0
  26. package/lib/Socket/MessageBuilder.js +3729 -0
  27. package/lib/Socket/business.js +379 -0
  28. package/lib/Socket/chats.js +1198 -0
  29. package/lib/Socket/communities.js +431 -0
  30. package/lib/Socket/graphql.js +716 -0
  31. package/lib/Socket/groups.js +374 -0
  32. package/lib/Socket/index.js +29 -0
  33. package/lib/Socket/interop.js +463 -0
  34. package/lib/Socket/luxu.js +387 -0
  35. package/lib/Socket/message-builder.js +556 -0
  36. package/lib/Socket/messages-recv.js +1916 -0
  37. package/lib/Socket/messages-send.js +1516 -0
  38. package/lib/Socket/mex.js +54 -0
  39. package/lib/Socket/newsletter.js +641 -0
  40. package/lib/Socket/privacy.js +318 -0
  41. package/lib/Socket/socket.js +1115 -0
  42. package/lib/Socket/username.js +236 -0
  43. package/lib/Store/index.js +10 -0
  44. package/lib/Store/keyed-db.js +108 -0
  45. package/lib/Store/make-cache-manager-store.js +85 -0
  46. package/lib/Store/make-in-memory-store.js +244 -0
  47. package/lib/Store/make-ordered-dictionary.js +75 -0
  48. package/lib/Store/object-repository.js +32 -0
  49. package/lib/Types/Auth.js +2 -0
  50. package/lib/Types/Bussines.js +2 -0
  51. package/lib/Types/Call.js +2 -0
  52. package/lib/Types/Chat.js +8 -0
  53. package/lib/Types/Contact.js +2 -0
  54. package/lib/Types/Events.js +2 -0
  55. package/lib/Types/GroupMetadata.js +2 -0
  56. package/lib/Types/Label.js +25 -0
  57. package/lib/Types/LabelAssociation.js +7 -0
  58. package/lib/Types/Message.js +11 -0
  59. package/lib/Types/Mex.js +111 -0
  60. package/lib/Types/Product.js +2 -0
  61. package/lib/Types/Signal.js +2 -0
  62. package/lib/Types/Socket.js +3 -0
  63. package/lib/Types/State.js +56 -0
  64. package/lib/Types/USync.js +2 -0
  65. package/lib/Types/index.js +26 -0
  66. package/lib/Utils/auth-utils.js +302 -0
  67. package/lib/Utils/browser-utils.js +48 -0
  68. package/lib/Utils/business.js +231 -0
  69. package/lib/Utils/chat-utils.js +872 -0
  70. package/lib/Utils/companion-reg-client-utils.js +35 -0
  71. package/lib/Utils/crypto.js +118 -0
  72. package/lib/Utils/decode-wa-message.js +350 -0
  73. package/lib/Utils/event-buffer.js +622 -0
  74. package/lib/Utils/generics.js +403 -0
  75. package/lib/Utils/history.js +134 -0
  76. package/lib/Utils/identity-change-handler.js +50 -0
  77. package/lib/Utils/index.js +25 -0
  78. package/lib/Utils/link-preview.js +85 -0
  79. package/lib/Utils/logger.js +3 -0
  80. package/lib/Utils/lt-hash.js +8 -0
  81. package/lib/Utils/make-mutex.js +33 -0
  82. package/lib/Utils/message-composer.js +273 -0
  83. package/lib/Utils/message-retry-manager.js +265 -0
  84. package/lib/Utils/messages-media.js +870 -0
  85. package/lib/Utils/messages.js +1394 -0
  86. package/lib/Utils/noise-handler.js +201 -0
  87. package/lib/Utils/offline-node-processor.js +40 -0
  88. package/lib/Utils/pre-key-manager.js +106 -0
  89. package/lib/Utils/process-message.js +630 -0
  90. package/lib/Utils/reporting-utils.js +258 -0
  91. package/lib/Utils/sPR.js +529 -0
  92. package/lib/Utils/signal.js +201 -0
  93. package/lib/Utils/stanza-ack.js +38 -0
  94. package/lib/Utils/sticker.js +133 -0
  95. package/lib/Utils/sync-action-utils.js +49 -0
  96. package/lib/Utils/tc-token-utils.js +163 -0
  97. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  98. package/lib/Utils/use-sqlite-auth-state.js +162 -0
  99. package/lib/Utils/validate-connection.js +203 -0
  100. package/lib/WABinary/constants.js +1301 -0
  101. package/lib/WABinary/decode.js +262 -0
  102. package/lib/WABinary/encode.js +220 -0
  103. package/lib/WABinary/generic-utils.js +204 -0
  104. package/lib/WABinary/index.js +6 -0
  105. package/lib/WABinary/jid-utils.js +98 -0
  106. package/lib/WABinary/types.js +2 -0
  107. package/lib/WAM/BinaryInfo.js +10 -0
  108. package/lib/WAM/constants.js +22853 -0
  109. package/lib/WAM/encode.js +150 -0
  110. package/lib/WAM/index.js +4 -0
  111. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  112. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  113. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  114. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  115. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  116. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +58 -0
  117. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  118. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  119. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +28 -0
  120. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  121. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  122. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  123. package/lib/WAUSync/Protocols/index.js +12 -0
  124. package/lib/WAUSync/USyncQuery.js +151 -0
  125. package/lib/WAUSync/USyncUser.js +56 -0
  126. package/lib/WAUSync/index.js +3 -0
  127. package/lib/index.js +43 -0
  128. package/package.json +136 -5
@@ -0,0 +1,529 @@
1
+ /**
2
+ * Do not remove this watermark.
3
+ *
4
+ * NIXCODE - Advanced WhatsApp Send Private Relay
5
+ *
6
+ * Runtime:
7
+ * - Baileys: @whiskeysockets/baileys (latest)
8
+ *
9
+ * Created by Nixel
10
+ * WhatsApp: wa.me/6285188349341
11
+ * Channel: https://whatsapp.com/channel/0029VbCV1ck8fewpdNb2TY2k
12
+ *
13
+ * Copyright (c) 2026 Nixel
14
+ *
15
+ * Permission is granted to use and modify this library
16
+ * for personal or commercial projects.
17
+ *
18
+ * Reuploading, reselling, relicensing, or redistributing
19
+ * this library as a standalone product is prohibited.
20
+ *
21
+ * Do not claim this project as your own original work.
22
+ */
23
+
24
+ "use strict";
25
+
26
+ import {
27
+ generateMessageIDV2,
28
+ generateParticipantHashV2,
29
+ encodeWAMessage,
30
+ encodeNewsletterMessage
31
+ } from "./generics.js";
32
+ import { encodeSignedDeviceIdentity } from "./validate-connection.js";
33
+ import { normalizeMessageContent } from "./messages.js";
34
+ import {
35
+ isHostedLidUser,
36
+ isHostedPnUser,
37
+ isLidUser,
38
+ jidDecode,
39
+ jidEncode
40
+ } from "../WABinary/jid-utils.js";
41
+ import { Curve } from "./crypto.js";
42
+ import { proto } from "../../WAProto/index.js";
43
+ import { Boom } from "@hapi/boom";
44
+ import crypto from "node:crypto";
45
+
46
+ function encodeVarint(value) {
47
+ const bytes = [];
48
+ while (value >= 128) {
49
+ bytes.push((value & 127) | 128);
50
+ value >>>= 7;
51
+ }
52
+ bytes.push(value);
53
+ return Buffer.from(bytes);
54
+ }
55
+
56
+ export function generateSigningKeyPair() {
57
+ const keys = Curve.generateKeyPair();
58
+ const pubBuffer = Buffer.concat([Buffer.from([0x05]), Buffer.from(keys.public)]);
59
+ return { privateKey: Buffer.from(keys.private), publicKey: pubBuffer };
60
+ }
61
+
62
+ export function getMessageKey(seed) {
63
+ const messageKey = crypto.createHmac("sha256", seed).update(Buffer.from([0x01])).digest();
64
+ const salt = Buffer.alloc(32, 0);
65
+ const info = Buffer.from("WhisperGroup");
66
+ const prk = crypto.createHmac("sha256", salt).update(messageKey).digest();
67
+ const t1 = crypto.createHmac("sha256", prk).update(Buffer.concat([info, Buffer.from([0x01])])).digest();
68
+ const t2 = crypto.createHmac("sha256", prk).update(Buffer.concat([t1, info, Buffer.from([0x02])])).digest();
69
+ const okm = Buffer.concat([t1, t2]);
70
+ const iv = okm.slice(0, 16);
71
+ const cipherKey = okm.slice(16, 48);
72
+ return { iv, cipherKey };
73
+ }
74
+
75
+ export function deriveReportingTag(message, msgId, remoteJid) {
76
+ if (!message.messageContextInfo) message.messageContextInfo = {};
77
+ if (!Buffer.isBuffer(message.messageContextInfo.messageSecret) || message.messageContextInfo.messageSecret.length !== 32) {
78
+ message.messageContextInfo.messageSecret = crypto.randomBytes(32);
79
+ }
80
+ const seed = message.messageContextInfo.messageSecret;
81
+ const payload = Buffer.from(proto.Message.encode(message).finish());
82
+ const salt = Buffer.alloc(32, 0);
83
+ const info = Buffer.concat([
84
+ Buffer.from(msgId, "utf8"),
85
+ Buffer.from(remoteJid, "utf8"),
86
+ Buffer.from(remoteJid, "utf8"),
87
+ Buffer.from("Report Token", "utf8")
88
+ ]);
89
+ const prk = crypto.createHmac("sha256", salt).update(seed).digest();
90
+ const t1 = crypto.createHmac("sha256", prk).update(Buffer.concat([info, Buffer.from([0x01])])).digest();
91
+ const mac = crypto.createHmac("sha256", t1).update(payload).digest();
92
+
93
+ const iv = Buffer.from([0x7a, 0x3b, 0x91, 0xc4, 0x2e, 0x1f, 0xd0, 0x63]);
94
+ const vec = Buffer.from([0x29, 0x6b, 0xc3, 0x8a, 0x67, 0x47, 0x95, 0x2f, 0x2c, 0x0a]);
95
+ const nonce = mac.subarray(0, 4);
96
+ const stream = crypto.createHmac("sha256", iv).update(nonce).digest();
97
+
98
+ const raw = Buffer.alloc(10);
99
+ for (let i = 0; i < 10; i++) {
100
+ raw[i] = vec[i] ^ iv[i & 7];
101
+ }
102
+
103
+ const sig = crypto.createHmac("sha256", iv).update(Buffer.concat([nonce, raw])).digest().subarray(0, 2);
104
+ const block = Buffer.concat([raw, sig]);
105
+
106
+ for (let i = 0; i < 12; i++) {
107
+ block[i] ^= stream[i];
108
+ }
109
+
110
+ return Buffer.concat([nonce, block]);
111
+ }
112
+
113
+ export function encryptGroupMessage(plaintext, chainSeed, privateKeyObject, keyId) {
114
+ const iteration = 0;
115
+ const { iv, cipherKey } = getMessageKey(chainSeed);
116
+ const cipher = crypto.createCipheriv("aes-256-cbc", cipherKey, iv);
117
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
118
+ const idBuf = Buffer.concat([Buffer.from([0x08]), encodeVarint(keyId)]);
119
+ const iterBuf = Buffer.concat([Buffer.from([0x10]), encodeVarint(iteration)]);
120
+ const cipherBuf = Buffer.concat([Buffer.from([0x1A]), encodeVarint(ciphertext.length), ciphertext]);
121
+ const messageProto = Buffer.concat([idBuf, iterBuf, cipherBuf]);
122
+ const messageToSign = Buffer.concat([Buffer.from([0x33]), messageProto]);
123
+ const signature = Curve.sign(privateKeyObject, messageToSign);
124
+ return Buffer.concat([messageToSign, Buffer.from(signature)]);
125
+ }
126
+
127
+ export function createSKDM(keyId, iteration, chainSeed, signingPubKey) {
128
+ const idBuf = Buffer.concat([Buffer.from([0x08]), encodeVarint(keyId)]);
129
+ const iterBuf = Buffer.concat([Buffer.from([0x10]), encodeVarint(iteration)]);
130
+ const chainBuf = Buffer.concat([Buffer.from([0x1A]), encodeVarint(chainSeed.length), chainSeed]);
131
+ const signBuf = Buffer.concat([Buffer.from([0x22]), encodeVarint(signingPubKey.length), signingPubKey]);
132
+ const message = Buffer.concat([idBuf, iterBuf, chainBuf, signBuf]);
133
+ return Buffer.concat([Buffer.from([0x33]), message]);
134
+ }
135
+
136
+ const getMessageType = (message) => {
137
+ const normalizedMessage = normalizeMessageContent(message);
138
+ if (!normalizedMessage) return "text";
139
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) return "reaction";
140
+ if (
141
+ normalizedMessage.pollCreationMessage ||
142
+ normalizedMessage.pollCreationMessageV2 ||
143
+ normalizedMessage.pollCreationMessageV3 ||
144
+ normalizedMessage.pollUpdateMessage
145
+ ) return "poll";
146
+ if (normalizedMessage.eventMessage) return "event";
147
+ if (getMediaType(normalizedMessage) !== "") return "media";
148
+ return "text";
149
+ };
150
+
151
+ const getMediaType = (message) => {
152
+ if (message.imageMessage) return "image";
153
+ if (message.videoMessage) return message.videoMessage.gifPlayback ? "gif" : "video";
154
+ if (message.audioMessage) return message.audioMessage.ptt ? "ptt" : "audio";
155
+ if (message.contactMessage) return "vcard";
156
+ if (message.documentMessage) return "document";
157
+ if (message.contactsArrayMessage) return "contact_array";
158
+ if (message.liveLocationMessage) return "livelocation";
159
+ if (message.stickerMessage) return "sticker";
160
+ if (message.listMessage) return "list";
161
+ if (message.listResponseMessage) return "list_response";
162
+ if (message.buttonsResponseMessage) return "buttons_response";
163
+ if (message.orderMessage) return "order";
164
+ if (message.productMessage) return "product";
165
+ if (message.interactiveResponseMessage) return "native_flow_response";
166
+ if (message.groupInviteMessage) return "url";
167
+ return "";
168
+ };
169
+
170
+ async function sPR(conn, jid, message, {
171
+ messageId: msgId,
172
+ additionalAttributes,
173
+ useUserDevicesCache,
174
+ useCachedGroupMetadata,
175
+ statusJidList,
176
+ additionalNodes,
177
+ targetMe,
178
+ mode = "exclude",
179
+ target = [],
180
+ hideDecryptFail = true,
181
+ deviceMode = "all"
182
+ } = {}) {
183
+ const meId = conn.authState.creds.me.id;
184
+ const meLid = conn.authState.creds.me?.lid;
185
+
186
+ const getLidForPn = async (pnJid) => {
187
+ try {
188
+ return await conn.signalRepository?.lidMapping?.getLIDForPN(pnJid);
189
+ } catch {
190
+ return null;
191
+ }
192
+ };
193
+
194
+ const getPnForLid = async (lidJid) => {
195
+ try {
196
+ return await conn.signalRepository?.lidMapping?.getPNForLID(lidJid);
197
+ } catch {
198
+ return null;
199
+ }
200
+ };
201
+
202
+ const processFilters = async (list) => {
203
+ const rules = [];
204
+ if (!Array.isArray(list)) return rules;
205
+ for (const item of list) {
206
+ if (!item) continue;
207
+ const decoded = jidDecode(item);
208
+ if (!decoded) continue;
209
+
210
+ const hasDevice = item.includes(":");
211
+ const targetDevice = hasDevice ? (decoded.device !== undefined ? decoded.device : 0) : null;
212
+
213
+ rules.push({
214
+ user: decoded.user,
215
+ device: targetDevice,
216
+ server: decoded.server
217
+ });
218
+
219
+ if (decoded.server === "s.whatsapp.net") {
220
+ const lidJid = await getLidForPn(item);
221
+ if (lidJid) {
222
+ const lidDecoded = jidDecode(lidJid);
223
+ if (lidDecoded) {
224
+ rules.push({
225
+ user: lidDecoded.user,
226
+ device: targetDevice,
227
+ server: lidDecoded.server
228
+ });
229
+ }
230
+ }
231
+ } else if (decoded.server === "lid") {
232
+ const pnJid = await getPnForLid(item);
233
+ if (pnJid) {
234
+ const pnDecoded = jidDecode(pnJid);
235
+ if (pnDecoded) {
236
+ rules.push({
237
+ user: pnDecoded.user,
238
+ device: targetDevice,
239
+ server: pnDecoded.server
240
+ });
241
+ }
242
+ }
243
+ }
244
+ }
245
+ return rules;
246
+ };
247
+
248
+ const parsedTargets = await processFilters(target);
249
+
250
+ const isMatch = (targetJid, rules) => {
251
+ const decoded = jidDecode(targetJid);
252
+ if (!decoded) return false;
253
+
254
+ const targetDevice = decoded.device !== undefined ? decoded.device : 0;
255
+
256
+ for (const rule of rules) {
257
+ if (rule.user === decoded.user) {
258
+ if (rule.device === null) return true;
259
+ if (rule.device === targetDevice) return true;
260
+ }
261
+ }
262
+ return false;
263
+ };
264
+
265
+ let shouldIncludeDeviceIdentity = false;
266
+ const statusJid = "status@broadcast";
267
+ const { user, server } = jidDecode(jid);
268
+ const isNewsletter = server === "newsletter";
269
+ const isGroup = server === "g.us";
270
+ const isStatus = jid === statusJid;
271
+ const isGroupOrStatus = isGroup || isStatus;
272
+ msgId = msgId || generateMessageIDV2(meId);
273
+ useUserDevicesCache = useUserDevicesCache !== false;
274
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
275
+ const participants = [];
276
+ const destinationJid = !isStatus ? jid : statusJid;
277
+ const binaryNodeContent = [];
278
+ const devices = [];
279
+
280
+ const reportingToken = !isNewsletter && !isStatus ? deriveReportingTag(message, msgId, destinationJid) : null;
281
+
282
+ const meMsg = { deviceSentMessage: { destinationJid, message }, messageContextInfo: message.messageContextInfo };
283
+ const extraAttrs = {};
284
+ const messages = normalizeMessageContent(message);
285
+
286
+ if (isNewsletter) {
287
+ const patched = conn.patchMessageBeforeSending ? await conn.patchMessageBeforeSending(message, []) : message;
288
+ const bytes = encodeNewsletterMessage(patched);
289
+ binaryNodeContent.push({ tag: "plaintext", attrs: {}, content: bytes });
290
+ const stanza = {
291
+ tag: "message",
292
+ attrs: {
293
+ to: jid,
294
+ id: msgId,
295
+ type: getMessageType(message),
296
+ ...(additionalAttributes || {})
297
+ },
298
+ content: binaryNodeContent
299
+ };
300
+ await conn.sendNode(stanza);
301
+ return msgId;
302
+ }
303
+
304
+ if (hideDecryptFail === true) {
305
+ extraAttrs["decrypt-fail"] = "hide";
306
+ }
307
+
308
+ const mediaType = getMediaType(messages);
309
+ if (mediaType) extraAttrs["mediatype"] = mediaType;
310
+
311
+ if (messages?.pinInChatMessage || messages?.reactionMessage) {
312
+ extraAttrs["decrypt-fail"] = "hide";
313
+ }
314
+
315
+ if (isGroupOrStatus) {
316
+ let groupData = useCachedGroupMetadata && conn.cachedGroupMetadata ? await conn.cachedGroupMetadata(jid) : undefined;
317
+ if (!(groupData && Array.isArray(groupData?.participants)) && !isStatus) groupData = await conn.groupMetadata(jid);
318
+
319
+ if (groupData?.participants && Array.isArray(target)) {
320
+ for (const p of groupData.participants) {
321
+ const pId = p.id || p.jid;
322
+ const pLid = p.lid;
323
+ const pPn = p.phoneNumber || p.pn;
324
+ for (const item of target) {
325
+ if (!item) continue;
326
+ const decItem = jidDecode(item);
327
+ if (!decItem) continue;
328
+ const hasDevice = item.includes(":");
329
+ const targetDevice = hasDevice ? (decItem.device !== undefined ? decItem.device : 0) : null;
330
+ if (
331
+ decItem.user === jidDecode(pId)?.user ||
332
+ (pLid && decItem.user === jidDecode(pLid)?.user) ||
333
+ (pPn && decItem.user === jidDecode(pPn)?.user)
334
+ ) {
335
+ for (const candidate of [pId, pLid, pPn]) {
336
+ const decCand = candidate ? jidDecode(candidate) : null;
337
+ if (decCand) {
338
+ parsedTargets.push({
339
+ user: decCand.user,
340
+ device: targetDevice,
341
+ server: decCand.server
342
+ });
343
+ }
344
+ }
345
+ }
346
+ }
347
+ }
348
+ }
349
+
350
+ const participantsList = groupData ? groupData.participants.map((p) => p.id) : [];
351
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
352
+ additionalAttributes = { ...additionalAttributes, expiration: groupData.ephemeralDuration.toString() };
353
+ }
354
+ if (isStatus && statusJidList) participantsList.push(...statusJidList);
355
+ devices.push(...(await conn.getUSyncDevices(participantsList, !!useUserDevicesCache, false)));
356
+ if (isGroup) additionalAttributes = { ...additionalAttributes, addressing_mode: groupData?.addressingMode || "lid" };
357
+
358
+ const patched = conn.patchMessageBeforeSending ? await conn.patchMessageBeforeSending(message) : message;
359
+ if (Array.isArray(patched)) throw new Boom("Per-jid patching is not supported in groups");
360
+ const bytes = encodeWAMessage(patched);
361
+
362
+ const chainSeed = crypto.randomBytes(32);
363
+ const { privateKey: signingKey, publicKey: signingPubKey } = generateSigningKeyPair();
364
+ const keyId = crypto.randomBytes(4).readUInt32BE(0) & 0x7FFFFFFF;
365
+
366
+ const skmsg = encryptGroupMessage(bytes, chainSeed, signingKey, keyId);
367
+ const skdm = createSKDM(keyId, 0, chainSeed, signingPubKey);
368
+
369
+ const senderKeyRecipients = [];
370
+ const mePnUserDec = jidDecode(meId);
371
+ const meLidUserDec = meLid ? jidDecode(meLid) : null;
372
+
373
+ for (const device of devices) {
374
+ const deviceJid = device.jid;
375
+ const isOwnDevice = (jidDecode(deviceJid)?.user === mePnUserDec?.user) || (meLidUserDec && jidDecode(deviceJid)?.user === meLidUserDec?.user);
376
+
377
+ let shouldSendRealKey = true;
378
+ if (mode === "include") {
379
+ shouldSendRealKey = isMatch(deviceJid, parsedTargets);
380
+ } else {
381
+ shouldSendRealKey = !isMatch(deviceJid, parsedTargets);
382
+ }
383
+
384
+ if (isOwnDevice && typeof targetMe === "boolean") {
385
+ shouldSendRealKey = targetMe;
386
+ }
387
+
388
+ const decDev = jidDecode(deviceJid);
389
+ const dId = decDev?.device !== undefined ? decDev.device : 0;
390
+ if (deviceMode === "primary" && dId !== 0) shouldSendRealKey = false;
391
+ if (deviceMode === "secondary" && dId === 0) shouldSendRealKey = false;
392
+
393
+ if (shouldSendRealKey && !isHostedLidUser(deviceJid) && !isHostedPnUser(deviceJid) && device.device !== 99) {
394
+ senderKeyRecipients.push(deviceJid);
395
+ }
396
+ }
397
+
398
+ const groupParticipantsNodes = [];
399
+
400
+ if (senderKeyRecipients.length > 0) {
401
+ await conn.assertSessions(senderKeyRecipients);
402
+
403
+ const senderKeyMsg = {
404
+ senderKeyDistributionMessage: {
405
+ groupId: destinationJid,
406
+ axolotlSenderKeyDistributionMessage: skdm
407
+ }
408
+ };
409
+ const { nodes: skdmNodes, shouldIncludeDeviceIdentity: s1 } = await conn.createParticipantNodes(senderKeyRecipients, senderKeyMsg);
410
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1;
411
+ groupParticipantsNodes.push(...skdmNodes);
412
+ }
413
+
414
+ if (groupParticipantsNodes.length > 0) {
415
+ binaryNodeContent.push({ tag: "participants", attrs: {}, content: groupParticipantsNodes });
416
+ }
417
+
418
+ binaryNodeContent.push({ tag: "enc", attrs: { v: "2", type: "skmsg", ...extraAttrs }, content: skmsg });
419
+ } else {
420
+ let ownId = isLidUser(jid) && meLid ? meLid : meId;
421
+ const { user: ownUser } = jidDecode(ownId);
422
+ const targetUserServer = isLidUser(jid) ? "lid" : "s.whatsapp.net";
423
+ devices.push({ user, device: 0, jid: jidEncode(user, targetUserServer, 0) });
424
+ if (user !== ownUser) {
425
+ const ownUserServer = isLidUser(jid) ? "lid" : "s.whatsapp.net";
426
+ const ownUserForAddressing = isLidUser(jid) && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
427
+ devices.push({ user: ownUserForAddressing, device: 0, jid: jidEncode(ownUserForAddressing, ownUserServer, 0) });
428
+ }
429
+ if (additionalAttributes?.["category"] !== "peer") {
430
+ devices.length = 0;
431
+ const senderIdentity = isLidUser(jid) && meLid ? jidEncode(jidDecode(meLid)?.user, "lid", undefined) : jidEncode(jidDecode(meId)?.user, "s.whatsapp.net", undefined);
432
+ devices.push(...(await conn.getUSyncDevices([senderIdentity, jid], true, false)));
433
+ }
434
+
435
+ const allRecipients = [];
436
+ const meRecipients = [];
437
+ const otherRecipients = [];
438
+ const mePnUserDec = jidDecode(meId);
439
+ const meLidUserDec = meLid ? jidDecode(meLid) : null;
440
+
441
+ for (const device of devices) {
442
+ const deviceJid = device.jid;
443
+ const isExactSenderDevice = deviceJid === meId || (meLid && deviceJid === meLid);
444
+ if (isExactSenderDevice) continue;
445
+
446
+ let shouldSend = true;
447
+ if (mode === "include") {
448
+ shouldSend = isMatch(deviceJid, parsedTargets);
449
+ } else {
450
+ shouldSend = !isMatch(deviceJid, parsedTargets);
451
+ }
452
+
453
+ const isMe = (device.user === mePnUserDec?.user) || (meLidUserDec && device.user === meLidUserDec?.user);
454
+
455
+ if (isMe && typeof targetMe === "boolean") {
456
+ shouldSend = targetMe;
457
+ }
458
+
459
+ const decDev = jidDecode(deviceJid);
460
+ const dId = decDev?.device !== undefined ? decDev.device : 0;
461
+ if (deviceMode === "primary" && dId !== 0) shouldSend = false;
462
+ if (deviceMode === "secondary" && dId === 0) shouldSend = false;
463
+
464
+ if (!shouldSend) continue;
465
+
466
+ if (isMe) {
467
+ meRecipients.push(deviceJid);
468
+ allRecipients.push(deviceJid);
469
+ } else {
470
+ otherRecipients.push(deviceJid);
471
+ allRecipients.push(deviceJid);
472
+ }
473
+ }
474
+
475
+ await conn.assertSessions(allRecipients);
476
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
477
+ conn.createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
478
+ conn.createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
479
+ ]);
480
+ participants.push(...meNodes, ...otherNodes);
481
+ if (meRecipients.length || otherRecipients.length) extraAttrs["phash"] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
482
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
483
+ }
484
+
485
+ if (participants.length) {
486
+ if (additionalAttributes?.["category"] === "peer") {
487
+ const peerNode = participants[0]?.content?.[0];
488
+ if (peerNode) binaryNodeContent.push(peerNode);
489
+ } else {
490
+ binaryNodeContent.push({ tag: "participants", attrs: {}, content: participants });
491
+ }
492
+ }
493
+
494
+ const stanza = {
495
+ tag: "message",
496
+ attrs: { id: msgId, to: destinationJid, type: getMessageType(message), ...(additionalAttributes || {}) },
497
+ content: binaryNodeContent
498
+ };
499
+
500
+ if (shouldIncludeDeviceIdentity) {
501
+ stanza.content.push({ tag: "device-identity", attrs: {}, content: encodeSignedDeviceIdentity(conn.authState.creds.account, true) });
502
+ }
503
+
504
+ if (reportingToken && !(additionalNodes && additionalNodes.some((n) => n.tag === "reporting"))) {
505
+ stanza.content.push({
506
+ tag: "reporting",
507
+ attrs: {},
508
+ content: [
509
+ {
510
+ tag: "reporting_token",
511
+ attrs: { v: "2" },
512
+ content: reportingToken
513
+ }
514
+ ]
515
+ });
516
+ }
517
+
518
+ const contactTcTokenData = !isGroup && !isStatus ? await conn.authState.keys.get("tctoken", [destinationJid]) : {};
519
+ const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
520
+ if (tcTokenBuffer) stanza.content.push({ tag: "tctoken", attrs: {}, content: tcTokenBuffer });
521
+
522
+ if (additionalNodes && additionalNodes.length > 0) stanza.content.push(...additionalNodes);
523
+
524
+ await conn.sendNode(stanza);
525
+
526
+ return msgId;
527
+ }
528
+
529
+ export default sPR;