@genuxofficial/baileys 3.0.0 → 4.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 (88) hide show
  1. package/WAProto/WAProto.proto +24 -206
  2. package/WAProto/index.d.ts +219 -2233
  3. package/WAProto/index.js +525 -6773
  4. package/WAProto/shizo.x +1 -0
  5. package/lib/Defaults/baileys-version.json +1 -1
  6. package/lib/Defaults/index.d.ts +231 -0
  7. package/lib/Defaults/index.js +17 -1
  8. package/lib/Defaults/phonenumber-mcc.json +223 -0
  9. package/lib/Socket/Client/index.d.ts +3 -2
  10. package/lib/Socket/Client/index.js +3 -2
  11. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  12. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  13. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +1 -1
  14. package/lib/Socket/Client/{websocket.js → web-socket-client.js} +2 -2
  15. package/lib/Socket/business.d.ts +7 -9
  16. package/lib/Socket/chats.d.ts +5 -8
  17. package/lib/Socket/chats.js +8 -38
  18. package/lib/Socket/groups.d.ts +5 -7
  19. package/lib/Socket/groups.js +2 -14
  20. package/lib/Socket/index.d.ts +9 -9
  21. package/lib/Socket/index.js +2 -2
  22. package/lib/Socket/messages-recv.d.ts +8 -10
  23. package/lib/Socket/messages-recv.js +11 -18
  24. package/lib/Socket/messages-send.d.ts +7 -14
  25. package/lib/Socket/messages-send.js +13 -36
  26. package/lib/Socket/newsletter.d.ts +7 -9
  27. package/lib/Socket/newsletter.js +3 -11
  28. package/lib/Socket/registration.d.ts +271 -0
  29. package/lib/Socket/registration.js +166 -0
  30. package/lib/Socket/socket.d.ts +4 -5
  31. package/lib/Socket/socket.js +18 -15
  32. package/lib/Socket/usync.d.ts +4 -4
  33. package/lib/Store/index.d.ts +2 -1
  34. package/lib/Store/index.js +3 -1
  35. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  36. package/lib/Store/make-cache-manager-store.js +83 -0
  37. package/lib/Store/make-in-memory-store.js +10 -8
  38. package/lib/Store/make-ordered-dictionary.js +2 -2
  39. package/lib/Types/Auth.d.ts +6 -0
  40. package/lib/Types/Chat.d.ts +0 -4
  41. package/lib/Types/Contact.d.ts +1 -1
  42. package/lib/Types/GroupMetadata.d.ts +0 -6
  43. package/lib/Types/Message.d.ts +5 -29
  44. package/lib/Types/Message.js +2 -0
  45. package/lib/Types/Socket.d.ts +4 -7
  46. package/lib/Utils/auth-utils.d.ts +1 -1
  47. package/lib/Utils/auth-utils.js +9 -2
  48. package/lib/Utils/business.js +3 -15
  49. package/lib/Utils/chat-utils.d.ts +4 -4
  50. package/lib/Utils/chat-utils.js +2 -1
  51. package/lib/Utils/decode-wa-message.d.ts +2 -4
  52. package/lib/Utils/decode-wa-message.js +24 -145
  53. package/lib/Utils/event-buffer.js +6 -4
  54. package/lib/Utils/generics.d.ts +4 -7
  55. package/lib/Utils/generics.js +17 -9
  56. package/lib/Utils/lt-hash.d.ts +3 -3
  57. package/lib/Utils/lt-hash.js +45 -11
  58. package/lib/Utils/messages-media.d.ts +4 -4
  59. package/lib/Utils/messages-media.js +57 -69
  60. package/lib/Utils/messages.js +39 -33
  61. package/lib/Utils/noise-handler.d.ts +2 -1
  62. package/lib/Utils/noise-handler.js +10 -5
  63. package/lib/Utils/use-multi-file-auth-state.js +11 -48
  64. package/lib/Utils/validate-connection.d.ts +1 -0
  65. package/lib/Utils/validate-connection.js +44 -10
  66. package/lib/WABinary/constants.js +5 -5
  67. package/lib/WABinary/encode.js +10 -23
  68. package/lib/WABinary/generic-utils.d.ts +5 -3
  69. package/lib/WABinary/generic-utils.js +19 -34
  70. package/lib/WABinary/jid-utils.d.ts +2 -11
  71. package/lib/WABinary/jid-utils.js +2 -27
  72. package/lib/WAM/BinaryInfo.d.ts +2 -2
  73. package/lib/WAM/constants.d.ts +2 -3
  74. package/lib/WAM/encode.js +2 -2
  75. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +12 -21
  76. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +3 -3
  77. package/lib/WAUSync/USyncQuery.d.ts +0 -2
  78. package/lib/WAUSync/USyncQuery.js +0 -10
  79. package/lib/WAUSync/USyncUser.d.ts +0 -2
  80. package/lib/WAUSync/USyncUser.js +0 -4
  81. package/package.json +5 -6
  82. package/LICENSE +0 -21
  83. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  84. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  85. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  86. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  87. /package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +0 -0
  88. /package/lib/Socket/Client/{types.js → abstract-socket-client.js} +0 -0
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.initAuthCreds = exports.addTransactionCapability = exports.makeCacheableSignalKeyStore = void 0;
7
7
  const crypto_1 = require("crypto");
8
8
  const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const uuid_1 = require("uuid");
9
10
  const Defaults_1 = require("../Defaults");
10
11
  const crypto_2 = require("./crypto");
11
12
  const generics_1 = require("./generics");
@@ -38,7 +39,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
38
39
  }
39
40
  }
40
41
  if (idsToFetch.length) {
41
- logger === null || logger === void 0 ? void 0 : logger.trace({ items: idsToFetch.length }, 'loading from store');
42
+ logger.trace({ items: idsToFetch.length }, 'loading from store');
42
43
  const fetched = await store.get(type, idsToFetch);
43
44
  for (const id of idsToFetch) {
44
45
  const item = fetched[id];
@@ -58,7 +59,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
58
59
  keys += 1;
59
60
  }
60
61
  }
61
- logger === null || logger === void 0 ? void 0 : logger.trace({ keys }, 'updated cache');
62
+ logger.trace({ keys }, 'updated cache');
62
63
  await store.set(data);
63
64
  },
64
65
  async clear() {
@@ -190,7 +191,13 @@ const initAuthCreds = () => {
190
191
  accountSettings: {
191
192
  unarchiveChats: false
192
193
  },
194
+ // mobile creds
195
+ deviceId: Buffer.from((0, uuid_1.v4)().replace(/-/g, ''), 'hex').toString('base64url'),
196
+ phoneId: (0, uuid_1.v4)(),
197
+ identityId: (0, crypto_1.randomBytes)(20),
193
198
  registered: false,
199
+ backupToken: (0, crypto_1.randomBytes)(20),
200
+ registration: {},
194
201
  pairingCode: undefined,
195
202
  lastPropHash: undefined,
196
203
  routingInfo: undefined,
@@ -3,13 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.uploadingNecessaryImages = exports.uploadingNecessaryImagesOfProduct = exports.parseProductNode = exports.toProductNode = exports.parseOrderDetailsNode = exports.parseCollectionsNode = exports.parseCatalogNode = void 0;
4
4
  const boom_1 = require("@hapi/boom");
5
5
  const crypto_1 = require("crypto");
6
- //new import
7
- const fs_1 = require("fs");
8
- const os_1 = require("os");
9
- const path_1 = require("path");
10
6
  const WABinary_1 = require("../WABinary");
11
- //import { getStream, getUrlFromDirectPath, toReadable } from './messages-media'
12
- const generics_1 = require("./generics");
13
7
  const messages_media_1 = require("./messages-media");
14
8
  const parseCatalogNode = (node) => {
15
9
  const catalogNode = (0, WABinary_1.getBinaryNodeChild)(node, 'product_catalog');
@@ -208,23 +202,17 @@ const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30
208
202
  }
209
203
  const { stream } = await (0, messages_media_1.getStream)(img);
210
204
  const hasher = (0, crypto_1.createHash)('sha256');
211
- //const contentBlocks: Buffer[] = []
212
- const filePath = (0, path_1.join)((0, os_1.tmpdir)(), 'img' + (0, generics_1.generateMessageIDV2)());
213
- const encFileWriteStream = (0, fs_1.createWriteStream)(filePath);
205
+ const contentBlocks = [];
214
206
  for await (const block of stream) {
215
207
  hasher.update(block);
216
- //contentBlocks.push(block)
217
- encFileWriteStream.write(block);
208
+ contentBlocks.push(block);
218
209
  }
219
210
  const sha = hasher.digest('base64');
220
- const { directPath } = await waUploadToServer(filePath, {
211
+ const { directPath } = await waUploadToServer((0, messages_media_1.toReadable)(Buffer.concat(contentBlocks)), {
221
212
  mediaType: 'product-catalog-image',
222
213
  fileEncSha256B64: sha,
223
214
  timeoutMs
224
215
  });
225
- await fs_1.promises
226
- .unlink(filePath)
227
- .catch(err => console.log('Error deleting temp file ', err));
228
216
  return { url: (0, messages_media_1.getUrlFromDirectPath)(directPath) };
229
217
  }));
230
218
  return results;
@@ -30,7 +30,7 @@ export declare const decodeSyncdPatch: (msg: proto.ISyncdPatch, name: WAPatchNam
30
30
  };
31
31
  };
32
32
  }>;
33
- export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<{}>) => Promise<{
33
+ export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<any>) => Promise<{
34
34
  critical_block: {
35
35
  patches: proto.ISyncdPatch[];
36
36
  hasMorePatches: boolean;
@@ -57,13 +57,13 @@ export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosReq
57
57
  snapshot?: proto.ISyncdSnapshot | undefined;
58
58
  };
59
59
  }>;
60
- export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<Buffer>;
61
- export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<proto.SyncdMutations>;
60
+ export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<any>) => Promise<Buffer>;
61
+ export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<any>) => Promise<proto.SyncdMutations>;
62
62
  export declare const decodeSyncdSnapshot: (name: WAPatchName, snapshot: proto.ISyncdSnapshot, getAppStateSyncKey: FetchAppStateSyncKey, minimumVersionNumber: number | undefined, validateMacs?: boolean) => Promise<{
63
63
  state: LTHashState;
64
64
  mutationMap: ChatMutationMap;
65
65
  }>;
66
- export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<{}>, minimumVersionNumber?: number, logger?: ILogger, validateMacs?: boolean) => Promise<{
66
+ export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<any>, minimumVersionNumber?: number, logger?: ILogger, validateMacs?: boolean) => Promise<{
67
67
  state: LTHashState;
68
68
  mutationMap: ChatMutationMap;
69
69
  }>;
@@ -305,7 +305,8 @@ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options,
305
305
  indexValueMap: { ...initial.indexValueMap }
306
306
  };
307
307
  const mutationMap = {};
308
- for (const syncd of syncds) {
308
+ for (let i = 0; i < syncds.length; i++) {
309
+ const syncd = syncds[i];
309
310
  const { version, keyId, snapshotMac } = syncd;
310
311
  if (syncd.externalMutations) {
311
312
  logger === null || logger === void 0 ? void 0 : logger.trace({ name, version }, 'downloading external patch');
@@ -1,6 +1,6 @@
1
1
  import { proto } from '../../WAProto';
2
2
  import { ILogger } from './logger';
3
- import { SignalRepository, WAMessageKey } from '../Types';
3
+ import { SignalRepository } from '../Types';
4
4
  import { BinaryNode } from '../WABinary';
5
5
  export declare const NO_MESSAGE_FOUND_ERROR_TEXT = "Message absent from node";
6
6
  export declare const MISSING_KEYS_ERROR_TEXT = "Key used already or never filled";
@@ -28,11 +28,9 @@ export declare function decodeMessageNode(stanza: BinaryNode, meId: string, meLi
28
28
  author: string;
29
29
  sender: string;
30
30
  };
31
- type GetMessage = (key: WAMessageKey) => Promise<proto.IMessage | undefined>;
32
- export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepository, logger: ILogger, getMessage: GetMessage) => {
31
+ export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepository, logger: ILogger) => {
33
32
  fullMessage: proto.IWebMessageInfo;
34
33
  category: string;
35
34
  author: string;
36
35
  decrypt(): Promise<void>;
37
36
  };
38
- export {};
@@ -1,19 +1,12 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.decryptMessageNode = exports.decodeMessageNode = exports.NACK_REASONS = exports.MISSING_KEYS_ERROR_TEXT = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
7
4
  const boom_1 = require("@hapi/boom");
8
5
  const WAProto_1 = require("../../WAProto");
9
6
  const WABinary_1 = require("../WABinary");
10
7
  const generics_1 = require("./generics");
11
- const crypto_1 = require("crypto");
12
- const futoin_hkdf_1 = __importDefault(require("futoin-hkdf"));
13
8
  exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
14
9
  exports.MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
15
- const BOT_MESSAGE_CONSTANT = "Bot Message";
16
- const KEY_LENGTH = 32;
17
10
  exports.NACK_REASONS = {
18
11
  ParsingError: 487,
19
12
  UnrecognizedStanza: 488,
@@ -29,85 +22,6 @@ exports.NACK_REASONS = {
29
22
  UnsupportedLIDGroup: 551,
30
23
  DBOperationFailed: 552
31
24
  };
32
- const deriveMessageSecret = async (messageSecret) => {
33
- // Always convert to Buffer to ensure compatibility
34
- const secretBuffer = Buffer.isBuffer(messageSecret)
35
- ? messageSecret
36
- : Buffer.from(messageSecret.buffer, messageSecret.byteOffset, messageSecret.length);
37
- return await (0, futoin_hkdf_1.default)(secretBuffer, KEY_LENGTH, { salt: undefined, info: BOT_MESSAGE_CONSTANT, hash: "SHA-256" });
38
- };
39
- const buildDecryptionKey = async (messageID, botJID, targetJID, messageSecret) => {
40
- const derivedSecret = await deriveMessageSecret(messageSecret);
41
- const useCaseSecret = Buffer.concat([
42
- Buffer.from(messageID),
43
- Buffer.from(targetJID),
44
- Buffer.from(botJID),
45
- Buffer.from("")
46
- ]);
47
- return await (0, futoin_hkdf_1.default)(derivedSecret, KEY_LENGTH, { salt: undefined, info: useCaseSecret, hash: "SHA-256" });
48
- };
49
- const decryptBotMessage = async (encPayload, encIv, messageID, botJID, decryptionKey) => {
50
- encPayload = Buffer.isBuffer(encPayload) ? encPayload : Buffer.from(encPayload);
51
- encIv = Buffer.isBuffer(encIv) ? encIv : Buffer.from(encIv);
52
- decryptionKey = Buffer.isBuffer(decryptionKey) ? decryptionKey : Buffer.from(decryptionKey);
53
- if (encIv.length !== 12) {
54
- throw new Error(`IV size incorrect: expected 12, got ${encIv.length}`);
55
- }
56
- const authTag = encPayload.slice(-16);
57
- const encryptedData = encPayload.slice(0, -16);
58
- if (encryptedData.length < 16) {
59
- throw new Error(`Encrypted data too short: ${encryptedData.length} bytes`);
60
- }
61
- const aad = Buffer.concat([
62
- Buffer.from(messageID),
63
- Buffer.from([0]),
64
- Buffer.from(botJID)
65
- ]);
66
- try {
67
- const decipher = (0, crypto_1.createDecipheriv)("aes-256-gcm", decryptionKey, encIv);
68
- decipher.setAAD(aad);
69
- decipher.setAuthTag(authTag);
70
- const decrypted = Buffer.concat([
71
- decipher.update(encryptedData),
72
- decipher.final()
73
- ]);
74
- return decrypted;
75
- }
76
- catch (error) {
77
- console.error("Decrypt - Failed with:", error.message);
78
- throw error;
79
- }
80
- };
81
- const decryptMsmsgBotMessage = async (messageSecret, messageKey, msMsg) => {
82
- try {
83
- const { targetId, participant: botJID, meId: targetJID } = messageKey;
84
- if (!targetId || !botJID || !targetJID || !messageSecret) {
85
- throw new Error("Missing required components for decryption");
86
- }
87
- const decryptionKey = await buildDecryptionKey(targetId, botJID, targetJID, messageSecret);
88
- if (!msMsg.encPayload) {
89
- throw new Error('Missing encPayload');
90
- }
91
- if (!msMsg.encIv) {
92
- throw new Error('Missing encIv');
93
- }
94
- return await decryptBotMessage(msMsg.encPayload, msMsg.encIv, targetId, botJID, decryptionKey);
95
- }
96
- catch (error) {
97
- console.error("Failed to decrypt bot message:", error);
98
- throw error;
99
- }
100
- };
101
- const decryptBotMsg = async (content, { messageKey, messageSecret }) => {
102
- try {
103
- const msMsg = WAProto_1.proto.MessageSecretMessage.decode(content);
104
- return await decryptMsmsgBotMessage(messageSecret, messageKey, msMsg);
105
- }
106
- catch (error) {
107
- console.error("Error in decryptBotMsg:", error);
108
- throw error;
109
- }
110
- };
111
25
  /**
112
26
  * Decode the received node as a message.
113
27
  * @note this will only parse the message, not decrypt it
@@ -119,13 +33,26 @@ function decodeMessageNode(stanza, meId, meLid) {
119
33
  let author;
120
34
  const msgId = stanza.attrs.id;
121
35
  const from = stanza.attrs.from;
122
- const participant = stanza.attrs.participant_pn || stanza.attrs.participant;
36
+ const participant = stanza.attrs.participant;
123
37
  const recipient = stanza.attrs.recipient;
124
38
  const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
125
39
  const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
126
- if ((0, WABinary_1.isJidMetaAI)(from) || (0, WABinary_1.isJidUser)(from) || (0, WABinary_1.isLidUser)(from)) {
127
- if (recipient && !(0, WABinary_1.isJidMetaAI)(recipient)) {
128
- if (!isMe(from) && !isMeLid(from)) {
40
+ if ((0, WABinary_1.isJidUser)(from)) {
41
+ if (recipient) {
42
+ if (!isMe(from)) {
43
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
44
+ }
45
+ chatId = recipient;
46
+ }
47
+ else {
48
+ chatId = from;
49
+ }
50
+ msgType = 'chat';
51
+ author = from;
52
+ }
53
+ else if ((0, WABinary_1.isLidUser)(from)) {
54
+ if (recipient) {
55
+ if (!isMeLid(from)) {
129
56
  throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
130
57
  }
131
58
  chatId = recipient;
@@ -194,39 +121,16 @@ function decodeMessageNode(stanza, meId, meLid) {
194
121
  };
195
122
  }
196
123
  exports.decodeMessageNode = decodeMessageNode;
197
- const decryptMessageNode = (stanza, meId, meLid, repository, logger, getMessage) => {
124
+ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
198
125
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
199
- let metaTargetId = null;
200
- let botEditTargetId = null;
201
- let botType = null;
202
126
  return {
203
127
  fullMessage,
204
128
  category: stanza.attrs.category,
205
129
  author,
206
130
  async decrypt() {
207
- var _a, _b;
131
+ var _a;
208
132
  let decryptables = 0;
209
133
  if (Array.isArray(stanza.content)) {
210
- let hasMsmsg = false;
211
- for (const { attrs } of stanza.content) {
212
- if ((attrs === null || attrs === void 0 ? void 0 : attrs.type) === 'msmsg') {
213
- hasMsmsg = true;
214
- break;
215
- }
216
- }
217
- if (hasMsmsg) {
218
- for (const { tag, attrs } of stanza.content) {
219
- if (tag === 'meta' && (attrs === null || attrs === void 0 ? void 0 : attrs.target_id)) {
220
- metaTargetId = attrs.target_id;
221
- }
222
- if (tag === 'bot' && (attrs === null || attrs === void 0 ? void 0 : attrs.edit_target_id)) {
223
- botEditTargetId = attrs.edit_target_id;
224
- }
225
- if (tag === 'bot' && (attrs === null || attrs === void 0 ? void 0 : attrs.edit)) {
226
- botType = attrs.edit;
227
- }
228
- }
229
- }
230
134
  for (const { tag, attrs, content } of stanza.content) {
231
135
  if (tag === 'verified_name' && content instanceof Uint8Array) {
232
136
  const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
@@ -260,42 +164,17 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger, getMessage)
260
164
  ciphertext: content
261
165
  });
262
166
  break;
263
- case 'msmsg': //Message Secret Message
264
- let msgRequestkey = {
265
- remoteJid: stanza.attrs.from,
266
- id: metaTargetId
267
- };
268
- const message = await getMessage(msgRequestkey);
269
- const messageSecret = (_a = message === null || message === void 0 ? void 0 : message.messageContextInfo) === null || _a === void 0 ? void 0 : _a.messageSecret;
270
- if (!messageSecret) {
271
- throw new Error('Message secret not found');
272
- }
273
- //Only decrypts when it is the complete message
274
- if (botType == 'last') {
275
- const newkey = {
276
- participant: stanza.attrs.from,
277
- meId: stanza.attrs.from.endsWith(`@bot`) ?
278
- `${meLid.split(`:`)[0]}@lid` :
279
- `${meId.split(`:`)[0]}@s.whatsapp.net`,
280
- targetId: botEditTargetId
281
- };
282
- msgBuffer = await decryptBotMsg(content, {
283
- messageKey: newkey,
284
- messageSecret
285
- });
286
- }
287
- else
288
- return;
289
- break;
290
167
  case 'plaintext':
291
168
  msgBuffer = content;
292
169
  break;
170
+ case undefined:
171
+ msgBuffer = content;
172
+ break;
293
173
  default:
294
174
  throw new Error(`Unknown e2e type: ${e2eType}`);
295
175
  }
296
- let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' && !hasMsmsg ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
297
- //It's necessary to save the messageContextInfo in the store to decrypt messages from bots
298
- msg = ((_b = msg.deviceSentMessage) === null || _b === void 0 ? void 0 : _b.message) ? { ...msg.deviceSentMessage.message, messageContextInfo: msg.messageContextInfo } : msg;
176
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
177
+ msg = ((_a = msg === null || msg === void 0 ? void 0 : msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
299
178
  if (msg.senderKeyDistributionMessage) {
300
179
  try {
301
180
  await repository.processSenderKeyDistributionMessage({
@@ -502,10 +502,12 @@ function consolidateEvents(data) {
502
502
  return map;
503
503
  }
504
504
  function concatChats(a, b) {
505
- if (b.unreadCount === null && // neutralize unread counter
506
- a.unreadCount < 0) {
507
- a.unreadCount = undefined;
508
- b.unreadCount = undefined;
505
+ if (b.unreadCount === null) {
506
+ // neutralize unread counter
507
+ if (a.unreadCount < 0) {
508
+ a.unreadCount = undefined;
509
+ b.unreadCount = undefined;
510
+ }
509
511
  }
510
512
  if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
511
513
  b = { ...b };
@@ -3,7 +3,7 @@
3
3
  import { AxiosRequestConfig } from 'axios';
4
4
  import { ILogger } from './logger';
5
5
  import { proto } from '../../WAProto';
6
- import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, ConnectionState, WACallUpdateType, WAVersion } from '../Types';
6
+ import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, WACallUpdateType, WAVersion } from '../Types';
7
7
  import { BinaryNode } from '../WABinary';
8
8
  export declare const Browsers: BrowsersMap;
9
9
  export declare const getPlatformId: (browser: string) => any;
@@ -35,9 +35,10 @@ export declare const delayCancellable: (ms: number) => {
35
35
  };
36
36
  export declare function promiseTimeout<T>(ms: number | undefined, promise: (resolve: (v: T) => void, reject: (error: any) => void) => void): Promise<T>;
37
37
  export declare const generateMessageIDV2: (userId?: string) => string;
38
+ export declare const generateMessageIDV3: (userId?: string) => string;
38
39
  export declare const generateMessageID: () => string;
39
40
  export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
40
- export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
41
+ export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
41
42
  export declare const printQRIfNecessaryListener: (ev: BaileysEventEmitter, logger: ILogger) => void;
42
43
  /**
43
44
  * utility that fetches latest baileys version from the master branch.
@@ -87,9 +88,5 @@ export declare const getCodeFromWSError: (error: Error) => number;
87
88
  * @param platform AuthenticationCreds.platform
88
89
  */
89
90
  export declare const isWABusinessPlatform: (platform: string) => boolean;
90
- export declare function trimUndefined(obj: {
91
- [_: string]: any;
92
- }): {
93
- [_: string]: any;
94
- };
91
+ export declare function trimUndefined(obj: any): any;
95
92
  export declare function bytesToCrockford(buffer: Buffer): string;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.bytesToCrockford = exports.trimUndefined = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.generateMessageIDV2 = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeNewsletterMessage = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
6
+ exports.bytesToCrockford = exports.trimUndefined = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.generateMessageIDV3 = exports.generateMessageIDV2 = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeNewsletterMessage = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
7
7
  const boom_1 = require("@hapi/boom");
8
8
  const axios_1 = __importDefault(require("axios"));
9
9
  const crypto_1 = require("crypto");
@@ -38,7 +38,7 @@ exports.Browsers = {
38
38
  };
39
39
  const getPlatformId = (browser) => {
40
40
  const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
41
- return platformType ? platformType.toString() : '49'; //chrome
41
+ return platformType ? platformType.toString().charCodeAt(0).toString() : '49'; // chrome
42
42
  };
43
43
  exports.getPlatformId = getPlatformId;
44
44
  exports.BufferJSON = {
@@ -97,7 +97,7 @@ const encodeBigEndian = (e, t = 4) => {
97
97
  return a;
98
98
  };
99
99
  exports.encodeBigEndian = encodeBigEndian;
100
- const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
100
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
101
101
  exports.toNumber = toNumber;
102
102
  /** unix timestamp of a date in seconds */
103
103
  const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
@@ -174,14 +174,22 @@ const generateMessageIDV2 = (userId) => {
174
174
  data.write('@c.us', 8 + id.user.length);
175
175
  }
176
176
  }
177
- const random = (0, crypto_1.randomBytes)(16);
177
+ const random = (0, crypto_1.randomBytes)(20);
178
178
  random.copy(data, 28);
179
179
  const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
180
- return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
180
+ return '3L1T3' + hash.toString('hex').toUpperCase().substring(0, 16);
181
181
  };
182
182
  exports.generateMessageIDV2 = generateMessageIDV2;
183
+ //Message ID function for Baileys Elite
184
+ //This V3 is RollBack Update to old Message ID
185
+ const generateMessageIDV3 = (userId) => {
186
+ let swebfix = '3L1T3';
187
+ let swebRandom = (0, crypto_1.randomBytes)(5).toString('hex').toUpperCase().substring(0, 10);
188
+ return swebfix + swebRandom;
189
+ };
190
+ exports.generateMessageIDV3 = generateMessageIDV3;
183
191
  // generate a random ID to attach to a message
184
- const generateMessageID = () => '3EB0' + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
192
+ const generateMessageID = () => '3L1T3' + (0, crypto_1.randomBytes)(8).toString('hex').toUpperCase();
185
193
  exports.generateMessageID = generateMessageID;
186
194
  function bindWaitForEvent(ev, event) {
187
195
  return async (check, timeoutMs) => {
@@ -229,7 +237,7 @@ exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
229
237
  * Use to ensure your WA connection is always on the latest version
230
238
  */
231
239
  const fetchLatestBaileysVersion = async (options = {}) => {
232
- const URL = 'https://raw.githubusercontent.com/nstar-y/bail/master/src/Defaults/baileys-version.json';
240
+ const URL = 'https://raw.githubusercontent.com/shizo-devs/baileys/master/src/Defaults/baileys-version.json';
233
241
  try {
234
242
  const result = await axios_1.default.get(URL, {
235
243
  ...options,
@@ -397,8 +405,8 @@ function bytesToCrockford(buffer) {
397
405
  let value = 0;
398
406
  let bitCount = 0;
399
407
  const crockford = [];
400
- for (const element of buffer) {
401
- value = (value << 8) | (element & 0xff);
408
+ for (let i = 0; i < buffer.length; i++) {
409
+ value = (value << 8) | (buffer[i] & 0xff);
402
410
  bitCount += 8;
403
411
  while (bitCount >= 5) {
404
412
  crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
@@ -4,9 +4,9 @@ declare class d {
4
4
  add(e: any, t: any): any;
5
5
  subtract(e: any, t: any): any;
6
6
  subtractThenAdd(e: any, t: any, r: any): any;
7
- _addSingle(e: any, t: any): Promise<ArrayBuffer>;
8
- _subtractSingle(e: any, t: any): Promise<ArrayBuffer>;
9
- performPointwiseWithOverflow(e: any, t: any, r: any): ArrayBuffer;
7
+ _addSingle(e: any, t: any): Promise<any>;
8
+ _subtractSingle(e: any, t: any): Promise<any>;
9
+ performPointwiseWithOverflow(e: any, t: any, r: any): any;
10
10
  }
11
11
  export declare const LT_HASH_ANTI_TAMPERING: d;
12
12
  export {};
@@ -15,37 +15,71 @@ class d {
15
15
  add(e, t) {
16
16
  var r = this;
17
17
  for (const item of t) {
18
- e = r._addSingle(e, item);
18
+ try {
19
+ e = r._addSingle(e, item);
20
+ }
21
+ catch (error) {
22
+ continue;
23
+ }
19
24
  }
20
25
  return e;
21
26
  }
22
27
  subtract(e, t) {
23
28
  var r = this;
24
29
  for (const item of t) {
25
- e = r._subtractSingle(e, item);
30
+ try {
31
+ e = r._subtractSingle(e, item);
32
+ }
33
+ catch (error) {
34
+ continue;
35
+ }
26
36
  }
27
37
  return e;
28
38
  }
29
39
  subtractThenAdd(e, t, r) {
30
40
  var n = this;
31
- return n.add(n.subtract(e, r), t);
41
+ try {
42
+ return n.add(n.subtract(e, r), t);
43
+ }
44
+ catch (error) {
45
+ return e;
46
+ }
32
47
  }
33
48
  async _addSingle(e, t) {
34
49
  var r = this;
35
- const n = new Uint8Array(await (0, crypto_1.hkdf)(Buffer.from(t), o, { info: r.salt })).buffer;
36
- return r.performPointwiseWithOverflow(await e, n, ((e, t) => e + t));
50
+ try {
51
+ const n = new Uint8Array(await (0, crypto_1.hkdf)(Buffer.from(t), o, { info: r.salt })).buffer;
52
+ return r.performPointwiseWithOverflow(await e, n, ((e, t) => e + t));
53
+ }
54
+ catch (error) {
55
+ return e;
56
+ }
37
57
  }
38
58
  async _subtractSingle(e, t) {
39
59
  var r = this;
40
- const n = new Uint8Array(await (0, crypto_1.hkdf)(Buffer.from(t), o, { info: r.salt })).buffer;
41
- return r.performPointwiseWithOverflow(await e, n, ((e, t) => e - t));
60
+ try {
61
+ const n = new Uint8Array(await (0, crypto_1.hkdf)(Buffer.from(t), o, { info: r.salt })).buffer;
62
+ return r.performPointwiseWithOverflow(e, n, ((e, t) => e - t));
63
+ }
64
+ catch (error) {
65
+ return e;
66
+ }
42
67
  }
43
68
  performPointwiseWithOverflow(e, t, r) {
44
- const n = new DataView(e), i = new DataView(t), a = new ArrayBuffer(n.byteLength), s = new DataView(a);
45
- for (let e = 0; e < n.byteLength; e += 2) {
46
- s.setUint16(e, r(n.getUint16(e, !0), i.getUint16(e, !0)), !0);
69
+ try {
70
+ const n = new DataView(e), i = new DataView(t), a = new ArrayBuffer(n.byteLength), s = new DataView(a);
71
+ for (let e = 0; e < n.byteLength; e += 2) {
72
+ try {
73
+ s.setUint16(e, r(n.getUint16(e, !0), i.getUint16(e, !0)), !0);
74
+ }
75
+ catch (error) {
76
+ }
77
+ }
78
+ return a;
79
+ }
80
+ catch (error) {
81
+ return e;
47
82
  }
48
- return a;
49
83
  }
50
84
  }
51
85
  exports.LT_HASH_ANTI_TAMPERING = new d('WhatsApp Patch Integrity');
@@ -66,8 +66,7 @@ type EncryptedStreamOptions = {
66
66
  };
67
67
  export declare const prepareStream: (media: WAMediaUpload, mediaType: MediaType, { logger, saveOriginalFileIfRequired, opts }?: EncryptedStreamOptions) => Promise<{
68
68
  mediaKey: undefined;
69
- encFilePath: string;
70
- originalFilePath: string | undefined;
69
+ encWriteStream: Buffer;
71
70
  fileLength: number;
72
71
  fileSha256: Buffer;
73
72
  fileEncSha256: undefined;
@@ -76,12 +75,13 @@ export declare const prepareStream: (media: WAMediaUpload, mediaType: MediaType,
76
75
  }>;
77
76
  export declare const encryptedStream: (media: WAMediaUpload, mediaType: MediaType, { logger, saveOriginalFileIfRequired, opts }?: EncryptedStreamOptions) => Promise<{
78
77
  mediaKey: Buffer;
79
- originalFilePath: string | undefined;
80
- encFilePath: string;
78
+ encWriteStream: Readable;
79
+ bodyPath: string | undefined;
81
80
  mac: Buffer;
82
81
  fileEncSha256: Buffer;
83
82
  fileSha256: Buffer;
84
83
  fileLength: number;
84
+ didSaveToTmpPath: boolean;
85
85
  }>;
86
86
  export type MediaDownloadOptions = {
87
87
  startByte?: number;