@genuxofficial/baileys 1.0.0 → 2.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 (99) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +5 -1
  3. package/WAProto/index.d.ts +19244 -2787
  4. package/WAProto/index.js +138202 -74217
  5. package/engine-requirements.js +10 -0
  6. package/lib/Defaults/baileys-version.json +1 -1
  7. package/lib/Defaults/index.d.ts +3 -5
  8. package/lib/Defaults/index.js +7 -6
  9. package/lib/Signal/libsignal.js +18 -9
  10. package/lib/Socket/Client/types.d.ts +0 -2
  11. package/lib/Socket/Client/websocket.js +1 -1
  12. package/lib/Socket/business.d.ts +65 -37
  13. package/lib/Socket/chats.d.ts +22 -18
  14. package/lib/Socket/chats.js +110 -6
  15. package/lib/Socket/groups.d.ts +30 -26
  16. package/lib/Socket/groups.js +20 -6
  17. package/lib/Socket/index.d.ts +66 -38
  18. package/lib/Socket/messages-recv.d.ts +63 -33
  19. package/lib/Socket/messages-recv.js +174 -27
  20. package/lib/Socket/messages-send.d.ts +55 -29
  21. package/lib/Socket/messages-send.js +190 -26
  22. package/lib/Socket/newsletter.d.ts +140 -0
  23. package/lib/Socket/newsletter.js +252 -0
  24. package/lib/Socket/socket.d.ts +8 -10
  25. package/lib/Socket/socket.js +26 -13
  26. package/lib/Socket/usync.d.ts +10 -12
  27. package/lib/Socket/usync.js +10 -15
  28. package/lib/Store/index.d.ts +1 -2
  29. package/lib/Store/index.js +1 -3
  30. package/lib/Store/make-in-memory-store.d.ts +1 -1
  31. package/lib/Store/make-in-memory-store.js +14 -5
  32. package/lib/Store/make-ordered-dictionary.d.ts +1 -1
  33. package/lib/Types/Auth.d.ts +0 -2
  34. package/lib/Types/Chat.d.ts +7 -0
  35. package/lib/Types/Contact.d.ts +5 -0
  36. package/lib/Types/Events.d.ts +27 -0
  37. package/lib/Types/GroupMetadata.d.ts +7 -0
  38. package/lib/Types/Label.js +1 -1
  39. package/lib/Types/LabelAssociation.js +1 -1
  40. package/lib/Types/Message.d.ts +129 -16
  41. package/lib/Types/Message.js +0 -2
  42. package/lib/Types/Newsletter.d.ts +79 -0
  43. package/lib/Types/Newsletter.js +18 -0
  44. package/lib/Types/Socket.d.ts +8 -5
  45. package/lib/Types/index.d.ts +1 -0
  46. package/lib/Types/index.js +2 -1
  47. package/lib/Utils/auth-utils.d.ts +1 -1
  48. package/lib/Utils/auth-utils.js +6 -7
  49. package/lib/Utils/business.js +2 -2
  50. package/lib/Utils/chat-utils.d.ts +8 -10
  51. package/lib/Utils/chat-utils.js +11 -0
  52. package/lib/Utils/crypto.d.ts +14 -16
  53. package/lib/Utils/crypto.js +40 -26
  54. package/lib/Utils/decode-wa-message.d.ts +5 -3
  55. package/lib/Utils/decode-wa-message.js +171 -29
  56. package/lib/Utils/event-buffer.js +1 -3
  57. package/lib/Utils/generics.d.ts +35 -9
  58. package/lib/Utils/generics.js +93 -27
  59. package/lib/Utils/history.d.ts +2 -2
  60. package/lib/Utils/link-preview.d.ts +1 -1
  61. package/lib/Utils/link-preview.js +17 -7
  62. package/lib/Utils/make-mutex.d.ts +2 -2
  63. package/lib/Utils/make-mutex.js +0 -1
  64. package/lib/Utils/messages-media.d.ts +35 -16
  65. package/lib/Utils/messages-media.js +168 -43
  66. package/lib/Utils/messages.d.ts +6 -9
  67. package/lib/Utils/messages.js +297 -37
  68. package/lib/Utils/noise-handler.d.ts +5 -7
  69. package/lib/Utils/process-message.js +2 -3
  70. package/lib/Utils/use-multi-file-auth-state.js +44 -13
  71. package/lib/Utils/validate-connection.d.ts +2 -2
  72. package/lib/Utils/validate-connection.js +1 -3
  73. package/lib/WABinary/decode.d.ts +2 -4
  74. package/lib/WABinary/decode.js +20 -9
  75. package/lib/WABinary/encode.d.ts +1 -3
  76. package/lib/WABinary/encode.js +30 -12
  77. package/lib/WABinary/generic-utils.d.ts +1 -3
  78. package/lib/WABinary/generic-utils.js +2 -2
  79. package/lib/WABinary/jid-utils.d.ts +9 -4
  80. package/lib/WABinary/jid-utils.js +25 -4
  81. package/lib/WAM/BinaryInfo.d.ts +2 -12
  82. package/lib/WAM/encode.d.ts +1 -3
  83. package/lib/WAUSync/Protocols/USyncContactProtocol.js +2 -2
  84. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +2 -2
  85. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +2 -2
  86. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +5 -5
  87. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  88. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  89. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  90. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  91. package/lib/WAUSync/USyncQuery.d.ts +2 -0
  92. package/lib/WAUSync/USyncQuery.js +27 -13
  93. package/lib/WAUSync/USyncUser.d.ts +2 -0
  94. package/lib/WAUSync/USyncUser.js +4 -0
  95. package/lib/index.d.ts +2 -1
  96. package/lib/index.js +3 -1
  97. package/package.json +59 -57
  98. package/WAProto/GenerateStatics.sh +0 -4
  99. package/WAProto/WAProto.proto +0 -3344
@@ -1,11 +1,9 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  import { KeyPair } from '../Types';
4
2
  /** prefix version byte to the pub keys, required for some curve crypto functions */
5
- export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array | Buffer;
3
+ export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike>;
6
4
  export declare const Curve: {
7
5
  generateKeyPair: () => KeyPair;
8
- sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer;
6
+ sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer<any>;
9
7
  sign: (privateKey: Uint8Array, buf: Uint8Array) => any;
10
8
  verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean;
11
9
  };
@@ -18,25 +16,25 @@ export declare const signedKeyPair: (identityKeyPair: KeyPair, keyId: number) =>
18
16
  * encrypt AES 256 GCM;
19
17
  * where the tag tag is suffixed to the ciphertext
20
18
  * */
21
- export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer;
19
+ export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
22
20
  /**
23
21
  * decrypt AES 256 GCM;
24
22
  * where the auth tag is suffixed to the ciphertext
25
23
  * */
26
- export declare function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer;
27
- export declare function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer;
28
- export declare function aesDecryptCTR(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer;
24
+ export declare function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
25
+ export declare function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
26
+ export declare function aesDecryptCTR(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
29
27
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
30
- export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer;
28
+ export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer<ArrayBuffer>;
31
29
  /** decrypt AES 256 CBC */
32
- export declare function aesDecryptWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer;
33
- export declare function aesEncrypt(buffer: Buffer | Uint8Array, key: Buffer): Buffer;
34
- export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer;
35
- export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): Buffer;
36
- export declare function sha256(buffer: Buffer): Buffer;
37
- export declare function md5(buffer: Buffer): Buffer;
30
+ export declare function aesDecryptWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
31
+ export declare function aesEncrypt(buffer: Buffer | Uint8Array, key: Buffer): Buffer<ArrayBuffer>;
32
+ export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
33
+ export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): Buffer<ArrayBufferLike>;
34
+ export declare function sha256(buffer: Buffer): Buffer<ArrayBufferLike>;
35
+ export declare function md5(buffer: Buffer): Buffer<ArrayBufferLike>;
38
36
  export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number, info: {
39
37
  salt?: Buffer;
40
- info?: string;
38
+ info?: string | Buffer;
41
39
  }): Promise<Buffer>;
42
40
  export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;
@@ -15,18 +15,43 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.derivePairingCodeKey = exports.hkdf = exports.md5 = exports.sha256 = exports.hmacSign = exports.aesEncrypWithIV = exports.aesEncrypt = exports.aesDecryptWithIV = exports.aesDecrypt = exports.aesDecryptCTR = exports.aesEncryptCTR = exports.aesDecryptGCM = exports.aesEncryptGCM = exports.signedKeyPair = exports.Curve = exports.generateSignalPubKey = void 0;
36
+ exports.signedKeyPair = exports.Curve = exports.generateSignalPubKey = void 0;
37
+ exports.aesEncryptGCM = aesEncryptGCM;
38
+ exports.aesDecryptGCM = aesDecryptGCM;
39
+ exports.aesEncryptCTR = aesEncryptCTR;
40
+ exports.aesDecryptCTR = aesDecryptCTR;
41
+ exports.aesDecrypt = aesDecrypt;
42
+ exports.aesDecryptWithIV = aesDecryptWithIV;
43
+ exports.aesEncrypt = aesEncrypt;
44
+ exports.aesEncrypWithIV = aesEncrypWithIV;
45
+ exports.hmacSign = hmacSign;
46
+ exports.sha256 = sha256;
47
+ exports.md5 = md5;
48
+ exports.hkdf = hkdf;
49
+ exports.derivePairingCodeKey = derivePairingCodeKey;
27
50
  const crypto_1 = require("crypto");
28
51
  const libsignal = __importStar(require("libsignal"));
29
52
  const Defaults_1 = require("../Defaults");
53
+ // insure browser & node compatibility
54
+ const { subtle } = globalThis.crypto;
30
55
  /** prefix version byte to the pub keys, required for some curve crypto functions */
31
56
  const generateSignalPubKey = (pubKey) => (pubKey.length === 33
32
57
  ? pubKey
@@ -73,7 +98,6 @@ function aesEncryptGCM(plaintext, key, iv, additionalData) {
73
98
  cipher.setAAD(additionalData);
74
99
  return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
75
100
  }
76
- exports.aesEncryptGCM = aesEncryptGCM;
77
101
  /**
78
102
  * decrypt AES 256 GCM;
79
103
  * where the auth tag is suffixed to the ciphertext
@@ -88,54 +112,44 @@ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
88
112
  decipher.setAuthTag(tag);
89
113
  return Buffer.concat([decipher.update(enc), decipher.final()]);
90
114
  }
91
- exports.aesDecryptGCM = aesDecryptGCM;
92
115
  function aesEncryptCTR(plaintext, key, iv) {
93
116
  const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
94
117
  return Buffer.concat([cipher.update(plaintext), cipher.final()]);
95
118
  }
96
- exports.aesEncryptCTR = aesEncryptCTR;
97
119
  function aesDecryptCTR(ciphertext, key, iv) {
98
120
  const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
99
121
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
100
122
  }
101
- exports.aesDecryptCTR = aesDecryptCTR;
102
123
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
103
124
  function aesDecrypt(buffer, key) {
104
125
  return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
105
126
  }
106
- exports.aesDecrypt = aesDecrypt;
107
127
  /** decrypt AES 256 CBC */
108
128
  function aesDecryptWithIV(buffer, key, IV) {
109
129
  const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
110
130
  return Buffer.concat([aes.update(buffer), aes.final()]);
111
131
  }
112
- exports.aesDecryptWithIV = aesDecryptWithIV;
113
132
  // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
114
133
  function aesEncrypt(buffer, key) {
115
134
  const IV = (0, crypto_1.randomBytes)(16);
116
135
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
117
136
  return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
118
137
  }
119
- exports.aesEncrypt = aesEncrypt;
120
138
  // encrypt AES 256 CBC with a given IV
121
139
  function aesEncrypWithIV(buffer, key, IV) {
122
140
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
123
141
  return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
124
142
  }
125
- exports.aesEncrypWithIV = aesEncrypWithIV;
126
143
  // sign HMAC using SHA 256
127
144
  function hmacSign(buffer, key, variant = 'sha256') {
128
145
  return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
129
146
  }
130
- exports.hmacSign = hmacSign;
131
147
  function sha256(buffer) {
132
148
  return (0, crypto_1.createHash)('sha256').update(buffer).digest();
133
149
  }
134
- exports.sha256 = sha256;
135
150
  function md5(buffer) {
136
151
  return (0, crypto_1.createHash)('md5').update(buffer).digest();
137
152
  }
138
- exports.md5 = md5;
139
153
  // HKDF key expansion
140
154
  async function hkdf(buffer, expandedLength, info) {
141
155
  // Ensure we have a Uint8Array for the key material
@@ -145,12 +159,14 @@ async function hkdf(buffer, expandedLength, info) {
145
159
  // Set default values if not provided
146
160
  const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
147
161
  const infoBytes = info.info
148
- ? new TextEncoder().encode(info.info)
162
+ ? (typeof info.info === 'string'
163
+ ? new TextEncoder().encode(info.info)
164
+ : new Uint8Array(info.info))
149
165
  : new Uint8Array(0);
150
166
  // Import the input key material
151
- const importedKey = await crypto.subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits']);
167
+ const importedKey = await subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits']);
152
168
  // Derive bits using HKDF
153
- const derivedBits = await crypto.subtle.deriveBits({
169
+ const derivedBits = await subtle.deriveBits({
154
170
  name: 'HKDF',
155
171
  hash: 'SHA-256',
156
172
  salt: salt,
@@ -159,17 +175,16 @@ async function hkdf(buffer, expandedLength, info) {
159
175
  );
160
176
  return Buffer.from(derivedBits);
161
177
  }
162
- exports.hkdf = hkdf;
163
178
  async function derivePairingCodeKey(pairingCode, salt) {
164
179
  // Convert inputs to formats Web Crypto API can work with
165
180
  const encoder = new TextEncoder();
166
181
  const pairingCodeBuffer = encoder.encode(pairingCode);
167
182
  const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
168
183
  // Import the pairing code as key material
169
- const keyMaterial = await crypto.subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits']);
184
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits']);
170
185
  // Derive bits using PBKDF2 with the same parameters
171
186
  // 2 << 16 = 131,072 iterations
172
- const derivedBits = await crypto.subtle.deriveBits({
187
+ const derivedBits = await subtle.deriveBits({
173
188
  name: 'PBKDF2',
174
189
  salt: saltBuffer,
175
190
  iterations: 2 << 16,
@@ -178,4 +193,3 @@ async function derivePairingCodeKey(pairingCode, salt) {
178
193
  );
179
194
  return Buffer.from(derivedBits);
180
195
  }
181
- exports.derivePairingCodeKey = derivePairingCodeKey;
@@ -1,7 +1,7 @@
1
1
  import { proto } from '../../WAProto';
2
- import { SignalRepository } from '../Types';
3
- import { BinaryNode } from '../WABinary';
4
2
  import { ILogger } from './logger';
3
+ import { SignalRepository, WAMessageKey } from '../Types';
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";
7
7
  export declare const NACK_REASONS: {
@@ -19,6 +19,7 @@ export declare const NACK_REASONS: {
19
19
  UnsupportedLIDGroup: number;
20
20
  DBOperationFailed: number;
21
21
  };
22
+ type GetMessage = (key: WAMessageKey) => Promise<proto.IMessage | undefined>;
22
23
  /**
23
24
  * Decode the received node as a message.
24
25
  * @note this will only parse the message, not decrypt it
@@ -28,9 +29,10 @@ export declare function decodeMessageNode(stanza: BinaryNode, meId: string, meLi
28
29
  author: string;
29
30
  sender: string;
30
31
  };
31
- export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepository, logger: ILogger) => {
32
+ export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepository, logger: ILogger, getMessage: GetMessage) => {
32
33
  fullMessage: proto.IWebMessageInfo;
33
34
  category: string;
34
35
  author: string;
35
36
  decrypt(): Promise<void>;
36
37
  };
38
+ export {};
@@ -1,12 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decryptMessageNode = exports.decodeMessageNode = exports.NACK_REASONS = exports.MISSING_KEYS_ERROR_TEXT = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
3
+ exports.decryptMessageNode = exports.NACK_REASONS = exports.MISSING_KEYS_ERROR_TEXT = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
4
+ exports.decodeMessageNode = decodeMessageNode;
4
5
  const boom_1 = require("@hapi/boom");
5
6
  const WAProto_1 = require("../../WAProto");
6
7
  const WABinary_1 = require("../WABinary");
7
8
  const generics_1 = require("./generics");
9
+ const crypto_1 = require("./crypto");
10
+ const crypto_2 = require("crypto");
8
11
  exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
9
12
  exports.MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
13
+ const BOT_MESSAGE_CONSTANT = "Bot Message";
14
+ const KEY_LENGTH = 32;
10
15
  exports.NACK_REASONS = {
11
16
  ParsingError: 487,
12
17
  UnrecognizedStanza: 488,
@@ -22,43 +27,115 @@ exports.NACK_REASONS = {
22
27
  UnsupportedLIDGroup: 551,
23
28
  DBOperationFailed: 552
24
29
  };
30
+ const deriveMessageSecret = async (messageSecret) => {
31
+ // Always convert to Buffer to ensure compatibility
32
+ const secretBuffer = Buffer.isBuffer(messageSecret)
33
+ ? messageSecret
34
+ : Buffer.from(messageSecret.buffer, messageSecret.byteOffset, messageSecret.length);
35
+ return await (0, crypto_1.hkdf)(secretBuffer, KEY_LENGTH, { info: BOT_MESSAGE_CONSTANT });
36
+ };
37
+ const buildDecryptionKey = async (messageID, botJID, targetJID, messageSecret) => {
38
+ const derivedSecret = await deriveMessageSecret(messageSecret);
39
+ const useCaseSecret = Buffer.concat([
40
+ Buffer.from(messageID),
41
+ Buffer.from(targetJID),
42
+ Buffer.from(botJID),
43
+ Buffer.from("")
44
+ ]);
45
+ return await (0, crypto_1.hkdf)(derivedSecret, KEY_LENGTH, { info: useCaseSecret });
46
+ };
47
+ const decryptBotMessage = async (encPayload, encIv, messageID, botJID, decryptionKey) => {
48
+ encPayload = Buffer.isBuffer(encPayload) ? encPayload : Buffer.from(encPayload);
49
+ encIv = Buffer.isBuffer(encIv) ? encIv : Buffer.from(encIv);
50
+ decryptionKey = Buffer.isBuffer(decryptionKey) ? decryptionKey : Buffer.from(decryptionKey);
51
+ if (encIv.length !== 12) {
52
+ throw new Error(`IV size incorrect: expected 12, got ${encIv.length}`);
53
+ }
54
+ const authTag = encPayload.slice(-16);
55
+ const encryptedData = encPayload.slice(0, -16);
56
+ if (encryptedData.length < 16) {
57
+ throw new Error(`Encrypted data too short: ${encryptedData.length} bytes`);
58
+ }
59
+ const aad = Buffer.concat([
60
+ Buffer.from(messageID),
61
+ Buffer.from([0]),
62
+ Buffer.from(botJID)
63
+ ]);
64
+ try {
65
+ const decipher = (0, crypto_2.createDecipheriv)("aes-256-gcm", decryptionKey, encIv);
66
+ decipher.setAAD(aad);
67
+ decipher.setAuthTag(authTag);
68
+ const decrypted = Buffer.concat([
69
+ decipher.update(encryptedData),
70
+ decipher.final()
71
+ ]);
72
+ return decrypted;
73
+ }
74
+ catch (error) {
75
+ console.error("Decrypt - Failed with:", error.message);
76
+ throw error;
77
+ }
78
+ };
79
+ const decryptMsmsgBotMessage = async (messageSecret, messageKey, msMsg) => {
80
+ try {
81
+ const { targetId, participant: botJID, meId: targetJID } = messageKey;
82
+ if (!targetId || !botJID || !targetJID || !messageSecret) {
83
+ throw new Error("Missing required components for decryption");
84
+ }
85
+ const decryptionKey = await buildDecryptionKey(targetId, botJID, targetJID, messageSecret);
86
+ if (!msMsg.encPayload) {
87
+ throw new Error('Missing encPayload');
88
+ }
89
+ if (!msMsg.encIv) {
90
+ throw new Error('Missing encIv');
91
+ }
92
+ return await decryptBotMessage(msMsg.encPayload, msMsg.encIv, targetId, botJID, decryptionKey);
93
+ }
94
+ catch (error) {
95
+ console.error("Failed to decrypt bot message:", error);
96
+ throw error;
97
+ }
98
+ };
99
+ const decryptBotMsg = async (content, { messageKey, messageSecret }) => {
100
+ try {
101
+ const msMsg = WAProto_1.proto.MessageSecretMessage.decode(content);
102
+ return await decryptMsmsgBotMessage(messageSecret, messageKey, msMsg);
103
+ }
104
+ catch (error) {
105
+ console.error("Error in decryptBotMsg:", error);
106
+ throw error;
107
+ }
108
+ };
25
109
  /**
26
110
  * Decode the received node as a message.
27
111
  * @note this will only parse the message, not decrypt it
28
112
  */
29
113
  function decodeMessageNode(stanza, meId, meLid) {
30
- var _a;
114
+ var _a, _b, _c, _d;
31
115
  let msgType;
32
116
  let chatId;
33
117
  let author;
118
+ let userLid;
34
119
  const msgId = stanza.attrs.id;
35
120
  const from = stanza.attrs.from;
36
121
  const participant = stanza.attrs.participant;
122
+ const participantLid = stanza.attrs.participant_lid;
37
123
  const recipient = stanza.attrs.recipient;
124
+ const peerRecipientLid = stanza.attrs.peer_recipient_lid;
125
+ const senderLid = stanza.attrs.sender_lid;
38
126
  const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
39
127
  const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
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)) {
128
+ if ((0, WABinary_1.isJidMetaAI)(from) || (0, WABinary_1.isJidUser)(from) || (0, WABinary_1.isLidUser)(from)) {
129
+ if (recipient && !(0, WABinary_1.isJidMetaAI)(recipient)) {
130
+ if (!isMe(from) && !isMeLid(from)) {
56
131
  throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
57
132
  }
58
133
  chatId = recipient;
134
+ userLid = peerRecipientLid;
59
135
  }
60
136
  else {
61
137
  chatId = from;
138
+ userLid = senderLid;
62
139
  }
63
140
  msgType = 'chat';
64
141
  author = from;
@@ -70,10 +147,16 @@ function decodeMessageNode(stanza, meId, meLid) {
70
147
  msgType = 'group';
71
148
  author = participant;
72
149
  chatId = from;
150
+ userLid = participantLid;
151
+ }
152
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
153
+ msgType = 'newsletter';
154
+ author = from;
155
+ chatId = from;
73
156
  }
74
157
  else if ((0, WABinary_1.isJidBroadcast)(from)) {
75
158
  if (!participant) {
76
- throw new boom_1.Boom('No participant in group message');
159
+ throw new boom_1.Boom('No participant in broadcast message');
77
160
  }
78
161
  const isParticipantMe = isMe(participant);
79
162
  if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
@@ -84,22 +167,26 @@ function decodeMessageNode(stanza, meId, meLid) {
84
167
  }
85
168
  chatId = from;
86
169
  author = participant;
170
+ userLid = participantLid;
87
171
  }
88
172
  else if ((0, WABinary_1.isJidNewsletter)(from)) {
89
173
  msgType = 'newsletter';
90
- chatId = from;
91
174
  author = from;
175
+ chatId = from;
176
+ userLid = participantLid;
92
177
  }
93
178
  else {
94
179
  throw new boom_1.Boom('Unknown message type', { data: stanza });
95
180
  }
96
- const fromMe = ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
97
- const pushname = (_a = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _a === void 0 ? void 0 : _a.notify;
181
+ const fromMe = (0, WABinary_1.isJidNewsletter)(from) ? !!((_a = stanza.attrs) === null || _a === void 0 ? void 0 : _a.is_sender) || false : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
182
+ const pushname = (_b = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _b === void 0 ? void 0 : _b.notify;
98
183
  const key = {
99
184
  remoteJid: chatId,
100
185
  fromMe,
101
186
  id: msgId,
102
- participant
187
+ participant,
188
+ lid: userLid,
189
+ 'server_id': (_c = stanza.attrs) === null || _c === void 0 ? void 0 : _c.server_id
103
190
  };
104
191
  const fullMessage = {
105
192
  key,
@@ -107,6 +194,9 @@ function decodeMessageNode(stanza, meId, meLid) {
107
194
  pushName: pushname,
108
195
  broadcast: (0, WABinary_1.isJidBroadcast)(from)
109
196
  };
197
+ if (msgType === 'newsletter') {
198
+ fullMessage.newsletterServerId = +((_d = stanza.attrs) === null || _d === void 0 ? void 0 : _d.server_id);
199
+ }
110
200
  if (key.fromMe) {
111
201
  fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
112
202
  }
@@ -116,17 +206,39 @@ function decodeMessageNode(stanza, meId, meLid) {
116
206
  sender: msgType === 'chat' ? author : chatId
117
207
  };
118
208
  }
119
- exports.decodeMessageNode = decodeMessageNode;
120
- const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
209
+ const decryptMessageNode = (stanza, meId, meLid, repository, logger, getMessage) => {
121
210
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
211
+ let metaTargetId = null;
212
+ let botEditTargetId = null;
213
+ let botType = null;
122
214
  return {
123
215
  fullMessage,
124
216
  category: stanza.attrs.category,
125
217
  author,
126
218
  async decrypt() {
127
- var _a;
219
+ var _a, _b;
128
220
  let decryptables = 0;
129
221
  if (Array.isArray(stanza.content)) {
222
+ let hasMsmsg = false;
223
+ for (const { attrs } of stanza.content) {
224
+ if ((attrs === null || attrs === void 0 ? void 0 : attrs.type) === 'msmsg') {
225
+ hasMsmsg = true;
226
+ break;
227
+ }
228
+ }
229
+ if (hasMsmsg) {
230
+ for (const { tag, attrs } of stanza.content) {
231
+ if (tag === 'meta' && (attrs === null || attrs === void 0 ? void 0 : attrs.target_id)) {
232
+ metaTargetId = attrs.target_id;
233
+ }
234
+ if (tag === 'bot' && (attrs === null || attrs === void 0 ? void 0 : attrs.edit_target_id)) {
235
+ botEditTargetId = attrs.edit_target_id;
236
+ }
237
+ if (tag === 'bot' && (attrs === null || attrs === void 0 ? void 0 : attrs.edit)) {
238
+ botType = attrs.edit;
239
+ }
240
+ }
241
+ }
130
242
  for (const { tag, attrs, content } of stanza.content) {
131
243
  if (tag === 'verified_name' && content instanceof Uint8Array) {
132
244
  const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
@@ -160,16 +272,46 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
160
272
  ciphertext: content
161
273
  });
162
274
  break;
275
+ case 'msmsg':
276
+ let msgRequestkey = {
277
+ remoteJid: stanza.attrs.from,
278
+ id: metaTargetId
279
+ };
280
+ const message = await getMessage(msgRequestkey);
281
+ const messageSecret = (_a = message === null || message === void 0 ? void 0 : message.messageContextInfo) === null || _a === void 0 ? void 0 : _a.messageSecret;
282
+ if (!messageSecret) {
283
+ throw new Error('Message secret not found');
284
+ }
285
+ // Only decrypts when it is the complete message
286
+ if (botType == 'last') {
287
+ const newkey = {
288
+ participant: stanza.attrs.from,
289
+ meId: stanza.attrs.from.endsWith(`@bot`) ?
290
+ `${meLid.split(`:`)[0]}@lid` :
291
+ `${meId.split(`:`)[0]}@s.whatsapp.net`,
292
+ targetId: botEditTargetId
293
+ };
294
+ msgBuffer = await decryptBotMsg(content, {
295
+ messageKey: newkey,
296
+ messageSecret
297
+ });
298
+ }
299
+ else
300
+ return;
301
+ break;
163
302
  case 'plaintext':
164
303
  msgBuffer = content;
165
304
  break;
305
+ case undefined:
306
+ msgBuffer = content;
307
+ break;
166
308
  default:
167
309
  throw new Error(`Unknown e2e type: ${e2eType}`);
168
310
  }
169
- let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
170
- msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
311
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' && !hasMsmsg ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
312
+ // It's necessary to save the messageContextInfo in the store to decrypt messages from bots
313
+ msg = ((_b = msg.deviceSentMessage) === null || _b === void 0 ? void 0 : _b.message) ? { ...msg.deviceSentMessage.message, messageContextInfo: msg.messageContextInfo } : msg;
171
314
  if (msg.senderKeyDistributionMessage) {
172
- //eslint-disable-next-line max-depth
173
315
  try {
174
316
  await repository.processSenderKeyDistributionMessage({
175
317
  authorJid: author,
@@ -138,9 +138,7 @@ const makeBufferData = () => {
138
138
  groupUpdates: {}
139
139
  };
140
140
  };
141
- function append(data, historyCache, event,
142
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
143
- eventData, logger) {
141
+ function append(data, historyCache, event, eventData, logger) {
144
142
  var _a, _b, _c;
145
143
  switch (event) {
146
144
  case 'messaging-history.set':
@@ -1,22 +1,22 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  import { AxiosRequestConfig } from 'axios';
2
+ import { ILogger } from './logger';
4
3
  import { proto } from '../../WAProto';
5
4
  import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, ConnectionState, WACallUpdateType, WAVersion } from '../Types';
6
5
  import { BinaryNode } from '../WABinary';
7
- import { ILogger } from './logger';
8
6
  export declare const Browsers: BrowsersMap;
7
+ /** Other Browser Support for Paircode */
9
8
  export declare const getPlatformId: (browser: string) => any;
10
9
  export declare const BufferJSON: {
11
10
  replacer: (k: any, value: any) => any;
12
11
  reviver: (_: any, value: any) => any;
13
12
  };
14
13
  export declare const getKeyAuthor: (key: proto.IMessageKey | undefined | null, meId?: string) => string;
15
- export declare const writeRandomPadMax16: (msg: Uint8Array) => Buffer;
16
- export declare const unpadRandomMax16: (e: Uint8Array | Buffer) => Uint8Array;
17
- export declare const encodeWAMessage: (message: proto.IMessage) => Buffer;
14
+ export declare const writeRandomPadMax16: (msg: Uint8Array) => Buffer<ArrayBuffer>;
15
+ export declare const unpadRandomMax16: (e: Uint8Array | Buffer) => Uint8Array<ArrayBuffer>;
16
+ export declare const encodeWAMessage: (message: proto.IMessage) => Buffer<ArrayBuffer>;
17
+ export declare const encodeNewsletterMessage: (message: proto.IMessage) => Uint8Array<ArrayBufferLike>;
18
18
  export declare const generateRegistrationId: () => number;
19
- export declare const encodeBigEndian: (e: number, t?: number) => Uint8Array;
19
+ export declare const encodeBigEndian: (e: number, t?: number) => Uint8Array<ArrayBuffer>;
20
20
  export declare const toNumber: (t: Long | number | null | undefined) => number;
21
21
  /** unix timestamp of a date in seconds */
22
22
  export declare const unixTimestampSeconds: (date?: Date) => number;
@@ -42,7 +42,33 @@ export declare const printQRIfNecessaryListener: (ev: BaileysEventEmitter, logge
42
42
  * utility that fetches latest baileys version from the master branch.
43
43
  * Use to ensure your WA connection is always on the latest version
44
44
  */
45
- export declare const fetchLatestBaileysVersion: (options?: AxiosRequestConfig<{}>) => Promise<{
45
+ export declare const fetchLatestBaileysVersion: (options?: AxiosRequestConfig<any>) => Promise<{
46
+ version: WAVersion;
47
+ isLatest: boolean;
48
+ error?: undefined;
49
+ } | {
50
+ version: WAVersion;
51
+ isLatest: boolean;
52
+ error: any;
53
+ }>;
54
+ /**
55
+ * utility that fetches latest baileys version from the main branch.
56
+ * Use to ensure your WA connection is always on the latest version
57
+ */
58
+ export declare const fetchLatestBaileysVersion3: (options?: AxiosRequestConfig<any>) => Promise<{
59
+ version: number[];
60
+ isLatest: boolean;
61
+ error?: undefined;
62
+ } | {
63
+ version: WAVersion;
64
+ isLatest: boolean;
65
+ error: any;
66
+ }>;
67
+ /**
68
+ * utility that fetches latest baileys version from the master branch.
69
+ * Use to ensure your WA connection is always on the latest version
70
+ */
71
+ export declare const fetchLatestBaileysVersion2: (options?: AxiosRequestConfig<any>) => Promise<{
46
72
  version: WAVersion;
47
73
  isLatest: boolean;
48
74
  error?: undefined;
@@ -85,7 +111,7 @@ export declare const getCodeFromWSError: (error: Error) => number;
85
111
  * Is the given platform WA business
86
112
  * @param platform AuthenticationCreds.platform
87
113
  */
88
- export declare const isWABusinessPlatform: (platform: string) => boolean;
114
+ export declare const isWABusinessPlatform: (platform: string) => platform is "smbi" | "smba";
89
115
  export declare function trimUndefined(obj: {
90
116
  [_: string]: any;
91
117
  }): {