@heavstaltech/baileys 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +200 -0
  2. package/WAProto/index.d.ts +50383 -0
  3. package/WAProto/index.js +155693 -0
  4. package/WASignalGroup/GroupProtocol.js +1697 -0
  5. package/WASignalGroup/ciphertext_message.js +16 -0
  6. package/WASignalGroup/group_cipher.js +120 -0
  7. package/WASignalGroup/group_session_builder.js +46 -0
  8. package/WASignalGroup/index.js +5 -0
  9. package/WASignalGroup/keyhelper.js +21 -0
  10. package/WASignalGroup/protobufs.js +3 -0
  11. package/WASignalGroup/queue_job.js +69 -0
  12. package/WASignalGroup/sender_chain_key.js +50 -0
  13. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  14. package/WASignalGroup/sender_key_message.js +92 -0
  15. package/WASignalGroup/sender_key_name.js +70 -0
  16. package/WASignalGroup/sender_key_record.js +56 -0
  17. package/WASignalGroup/sender_key_state.js +129 -0
  18. package/WASignalGroup/sender_message_key.js +39 -0
  19. package/lib/Defaults/baileys-version.json +3 -0
  20. package/lib/Defaults/index.d.ts +53 -0
  21. package/lib/Defaults/index.js +108 -0
  22. package/lib/Signal/libsignal.d.ts +3 -0
  23. package/lib/Signal/libsignal.js +152 -0
  24. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  25. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  26. package/lib/Socket/Client/index.d.ts +3 -0
  27. package/lib/Socket/Client/index.js +19 -0
  28. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  29. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  30. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  31. package/lib/Socket/Client/web-socket-client.js +62 -0
  32. package/lib/Socket/business.d.ts +170 -0
  33. package/lib/Socket/business.js +260 -0
  34. package/lib/Socket/chats.d.ts +81 -0
  35. package/lib/Socket/chats.js +950 -0
  36. package/lib/Socket/groups.d.ts +115 -0
  37. package/lib/Socket/groups.js +315 -0
  38. package/lib/Socket/index.d.ts +172 -0
  39. package/lib/Socket/index.js +10 -0
  40. package/lib/Socket/messages-recv.d.ts +158 -0
  41. package/lib/Socket/messages-recv.js +972 -0
  42. package/lib/Socket/messages-send.d.ts +155 -0
  43. package/lib/Socket/messages-send.js +1087 -0
  44. package/lib/Socket/newsletter.d.ts +132 -0
  45. package/lib/Socket/newsletter.js +236 -0
  46. package/lib/Socket/registration.d.ts +264 -0
  47. package/lib/Socket/registration.js +166 -0
  48. package/lib/Socket/socket.d.ts +44 -0
  49. package/lib/Socket/socket.js +643 -0
  50. package/lib/Socket/usync.d.ts +37 -0
  51. package/lib/Socket/usync.js +70 -0
  52. package/lib/Store/index.d.ts +3 -0
  53. package/lib/Store/index.js +10 -0
  54. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  55. package/lib/Store/make-cache-manager-store.js +83 -0
  56. package/lib/Store/make-in-memory-store.d.ts +118 -0
  57. package/lib/Store/make-in-memory-store.js +431 -0
  58. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  59. package/lib/Store/make-ordered-dictionary.js +81 -0
  60. package/lib/Store/object-repository.d.ts +10 -0
  61. package/lib/Store/object-repository.js +27 -0
  62. package/lib/Types/Auth.d.ts +109 -0
  63. package/lib/Types/Auth.js +2 -0
  64. package/lib/Types/Call.d.ts +13 -0
  65. package/lib/Types/Call.js +2 -0
  66. package/lib/Types/Chat.d.ts +107 -0
  67. package/lib/Types/Chat.js +4 -0
  68. package/lib/Types/Contact.d.ts +19 -0
  69. package/lib/Types/Contact.js +2 -0
  70. package/lib/Types/Events.d.ts +172 -0
  71. package/lib/Types/Events.js +2 -0
  72. package/lib/Types/GroupMetadata.d.ts +56 -0
  73. package/lib/Types/GroupMetadata.js +2 -0
  74. package/lib/Types/Label.d.ts +46 -0
  75. package/lib/Types/Label.js +27 -0
  76. package/lib/Types/LabelAssociation.d.ts +29 -0
  77. package/lib/Types/LabelAssociation.js +9 -0
  78. package/lib/Types/Message.d.ts +433 -0
  79. package/lib/Types/Message.js +9 -0
  80. package/lib/Types/Newsletter.d.ts +92 -0
  81. package/lib/Types/Newsletter.js +32 -0
  82. package/lib/Types/Product.d.ts +78 -0
  83. package/lib/Types/Product.js +2 -0
  84. package/lib/Types/Signal.d.ts +57 -0
  85. package/lib/Types/Signal.js +2 -0
  86. package/lib/Types/Socket.d.ts +116 -0
  87. package/lib/Types/Socket.js +2 -0
  88. package/lib/Types/State.d.ts +27 -0
  89. package/lib/Types/State.js +2 -0
  90. package/lib/Types/USync.d.ts +25 -0
  91. package/lib/Types/USync.js +2 -0
  92. package/lib/Types/index.d.ts +66 -0
  93. package/lib/Types/index.js +42 -0
  94. package/lib/Utils/auth-utils.d.ts +18 -0
  95. package/lib/Utils/auth-utils.js +227 -0
  96. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  97. package/lib/Utils/baileys-event-stream.js +63 -0
  98. package/lib/Utils/business.d.ts +22 -0
  99. package/lib/Utils/business.js +234 -0
  100. package/lib/Utils/chat-utils.d.ts +70 -0
  101. package/lib/Utils/chat-utils.js +745 -0
  102. package/lib/Utils/crypto.d.ts +40 -0
  103. package/lib/Utils/crypto.js +199 -0
  104. package/lib/Utils/decode-wa-message.d.ts +36 -0
  105. package/lib/Utils/decode-wa-message.js +234 -0
  106. package/lib/Utils/event-buffer.d.ts +35 -0
  107. package/lib/Utils/event-buffer.js +517 -0
  108. package/lib/Utils/generics.d.ts +88 -0
  109. package/lib/Utils/generics.js +402 -0
  110. package/lib/Utils/history.d.ts +19 -0
  111. package/lib/Utils/history.js +94 -0
  112. package/lib/Utils/index.d.ts +17 -0
  113. package/lib/Utils/index.js +33 -0
  114. package/lib/Utils/link-preview.d.ts +21 -0
  115. package/lib/Utils/link-preview.js +93 -0
  116. package/lib/Utils/logger.d.ts +2 -0
  117. package/lib/Utils/logger.js +7 -0
  118. package/lib/Utils/lt-hash.d.ts +12 -0
  119. package/lib/Utils/lt-hash.js +51 -0
  120. package/lib/Utils/make-mutex.d.ts +7 -0
  121. package/lib/Utils/make-mutex.js +43 -0
  122. package/lib/Utils/messages-media.d.ts +113 -0
  123. package/lib/Utils/messages-media.js +721 -0
  124. package/lib/Utils/messages.d.ts +77 -0
  125. package/lib/Utils/messages.js +1221 -0
  126. package/lib/Utils/noise-handler.d.ts +20 -0
  127. package/lib/Utils/noise-handler.js +160 -0
  128. package/lib/Utils/process-message.d.ts +41 -0
  129. package/lib/Utils/process-message.js +373 -0
  130. package/lib/Utils/signal.d.ts +33 -0
  131. package/lib/Utils/signal.js +159 -0
  132. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  133. package/lib/Utils/use-multi-file-auth-state.js +295 -0
  134. package/lib/Utils/use-single-file-auth-state.d.ts +12 -0
  135. package/lib/Utils/use-single-file-auth-state.js +75 -0
  136. package/lib/Utils/validate-connection.d.ts +11 -0
  137. package/lib/Utils/validate-connection.js +205 -0
  138. package/lib/WABinary/constants.d.ts +27 -0
  139. package/lib/WABinary/constants.js +40 -0
  140. package/lib/WABinary/decode.d.ts +6 -0
  141. package/lib/WABinary/decode.js +264 -0
  142. package/lib/WABinary/encode.d.ts +2 -0
  143. package/lib/WABinary/encode.js +252 -0
  144. package/lib/WABinary/generic-utils.d.ts +14 -0
  145. package/lib/WABinary/generic-utils.js +110 -0
  146. package/lib/WABinary/index.d.ts +5 -0
  147. package/lib/WABinary/index.js +21 -0
  148. package/lib/WABinary/jid-utils.d.ts +31 -0
  149. package/lib/WABinary/jid-utils.js +62 -0
  150. package/lib/WABinary/types.d.ts +18 -0
  151. package/lib/WABinary/types.js +2 -0
  152. package/lib/WAM/BinaryInfo.d.ts +8 -0
  153. package/lib/WAM/BinaryInfo.js +13 -0
  154. package/lib/WAM/constants.d.ts +38 -0
  155. package/lib/WAM/constants.js +15350 -0
  156. package/lib/WAM/encode.d.ts +2 -0
  157. package/lib/WAM/encode.js +155 -0
  158. package/lib/WAM/index.d.ts +3 -0
  159. package/lib/WAM/index.js +19 -0
  160. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  161. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  162. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  163. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  164. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  165. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  166. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  167. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  168. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  169. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  170. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  171. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  172. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  173. package/lib/WAUSync/Protocols/index.js +20 -0
  174. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  175. package/lib/WAUSync/USyncQuery.js +89 -0
  176. package/lib/WAUSync/USyncUser.d.ts +10 -0
  177. package/lib/WAUSync/USyncUser.js +26 -0
  178. package/lib/WAUSync/index.d.ts +3 -0
  179. package/lib/WAUSync/index.js +19 -0
  180. package/lib/index.js +31 -0
  181. package/package.json +103 -0
@@ -0,0 +1,40 @@
1
+ import { KeyPair } from '../Types';
2
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
3
+ export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => any;
4
+ export declare const Curve: {
5
+ generateKeyPair: () => KeyPair;
6
+ sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => any;
7
+ sign: (privateKey: Uint8Array, buf: Uint8Array) => any;
8
+ verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean;
9
+ };
10
+ export declare const signedKeyPair: (identityKeyPair: KeyPair, keyId: number) => {
11
+ keyPair: KeyPair;
12
+ signature: any;
13
+ keyId: number;
14
+ };
15
+ /**
16
+ * encrypt AES 256 GCM;
17
+ * where the tag tag is suffixed to the ciphertext
18
+ * */
19
+ export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): any;
20
+ /**
21
+ * decrypt AES 256 GCM;
22
+ * where the auth tag is suffixed to the ciphertext
23
+ * */
24
+ export declare function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): any;
25
+ export declare function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): any;
26
+ export declare function aesDecryptCTR(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array): any;
27
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
28
+ export declare function aesDecrypt(buffer: Buffer, key: Buffer): any;
29
+ /** decrypt AES 256 CBC */
30
+ export declare function aesDecryptWithIV(buffer: Buffer, key: Buffer, IV: Buffer): any;
31
+ export declare function aesEncrypt(buffer: Buffer | Uint8Array, key: Buffer): any;
32
+ export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): any;
33
+ export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): any;
34
+ export declare function sha256(buffer: Buffer): any;
35
+ export declare function md5(buffer: Buffer): any;
36
+ export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number, info: {
37
+ salt?: Buffer;
38
+ info?: string;
39
+ }): any;
40
+ export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<any>;
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
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
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.signedKeyPair = exports.Curve = exports.generateSignalPubKey = void 0;
40
+ exports.aesEncryptGCM = aesEncryptGCM;
41
+ exports.aesDecryptGCM = aesDecryptGCM;
42
+ exports.aesEncryptCTR = aesEncryptCTR;
43
+ exports.aesDecryptCTR = aesDecryptCTR;
44
+ exports.aesDecrypt = aesDecrypt;
45
+ exports.aesDecryptWithIV = aesDecryptWithIV;
46
+ exports.aesEncrypt = aesEncrypt;
47
+ exports.aesEncrypWithIV = aesEncrypWithIV;
48
+ exports.hmacSign = hmacSign;
49
+ exports.sha256 = sha256;
50
+ exports.md5 = md5;
51
+ exports.hkdf = hkdf;
52
+ exports.derivePairingCodeKey = derivePairingCodeKey;
53
+ const crypto_1 = require("crypto");
54
+ const crypto_2 = globalThis.crypto ?? crypto_1.webcrypto ?? crypto_1;
55
+ //const futoin_hkdf_1 = __importDefault(require("futoin-hkdf"));
56
+ const libsignal = __importStar(require("libsignal"));
57
+ const util_1 = require("util");
58
+ const Defaults_1 = require("../Defaults");
59
+ //const pbkdf2Promise = (0, util_1.promisify)(crypto_1.pbkdf2);
60
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
61
+ const generateSignalPubKey = (pubKey) => (pubKey.length === 33
62
+ ? pubKey
63
+ : Buffer.concat([Defaults_1.KEY_BUNDLE_TYPE, pubKey]));
64
+ exports.generateSignalPubKey = generateSignalPubKey;
65
+ exports.Curve = {
66
+ generateKeyPair: () => {
67
+ const { pubKey, privKey } = libsignal.curve.generateKeyPair();
68
+ return {
69
+ private: Buffer.from(privKey),
70
+ // remove version byte
71
+ public: Buffer.from(pubKey.slice(1))
72
+ };
73
+ },
74
+ sharedKey: (privateKey, publicKey) => {
75
+ const shared = libsignal.curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
76
+ return Buffer.from(shared);
77
+ },
78
+ sign: (privateKey, buf) => (libsignal.curve.calculateSignature(privateKey, buf)),
79
+ verify: (pubKey, message, signature) => {
80
+ try {
81
+ libsignal.curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
82
+ return true;
83
+ }
84
+ catch (error) {
85
+ return false;
86
+ }
87
+ }
88
+ };
89
+ const signedKeyPair = (identityKeyPair, keyId) => {
90
+ const preKey = exports.Curve.generateKeyPair();
91
+ const pubKey = (0, exports.generateSignalPubKey)(preKey.public);
92
+ const signature = exports.Curve.sign(identityKeyPair.private, pubKey);
93
+ return { keyPair: preKey, signature, keyId };
94
+ };
95
+ exports.signedKeyPair = signedKeyPair;
96
+ const GCM_TAG_LENGTH = 128 >> 3;
97
+ /**
98
+ * encrypt AES 256 GCM;
99
+ * where the tag tag is suffixed to the ciphertext
100
+ * */
101
+ function aesEncryptGCM(plaintext, key, iv, additionalData) {
102
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
103
+ cipher.setAAD(additionalData);
104
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
105
+ }
106
+ /**
107
+ * decrypt AES 256 GCM;
108
+ * where the auth tag is suffixed to the ciphertext
109
+ * */
110
+ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
111
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
112
+ // decrypt additional adata
113
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
114
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
115
+ // set additional data
116
+ decipher.setAAD(additionalData);
117
+ decipher.setAuthTag(tag);
118
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
119
+ }
120
+ function aesEncryptCTR(plaintext, key, iv) {
121
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
122
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
123
+ }
124
+ function aesDecryptCTR(ciphertext, key, iv) {
125
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
126
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
127
+ }
128
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
129
+ function aesDecrypt(buffer, key) {
130
+ return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
131
+ }
132
+ /** decrypt AES 256 CBC */
133
+ function aesDecryptWithIV(buffer, key, IV) {
134
+ const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
135
+ return Buffer.concat([aes.update(buffer), aes.final()]);
136
+ }
137
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
138
+ function aesEncrypt(buffer, key) {
139
+ const IV = (0, crypto_1.randomBytes)(16);
140
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
141
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
142
+ }
143
+ // encrypt AES 256 CBC with a given IV
144
+ function aesEncrypWithIV(buffer, key, IV) {
145
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
146
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
147
+ }
148
+ // sign HMAC using SHA 256
149
+ function hmacSign(buffer, key, variant = 'sha256') {
150
+ return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
151
+ }
152
+ function sha256(buffer) {
153
+ return (0, crypto_1.createHash)('sha256').update(buffer).digest();
154
+ }
155
+ function md5(buffer) {
156
+ return (0, crypto_1.createHash)('md5').update(buffer).digest();
157
+ }
158
+ // HKDF key expansion
159
+ async function hkdf(buffer, expandedLength, info) {
160
+ // Ensure we have a Uint8Array for the key material
161
+ const inputKeyMaterial = buffer instanceof Uint8Array
162
+ ? buffer
163
+ : new Uint8Array(buffer);
164
+ // Set default values if not provided
165
+ const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
166
+ const infoBytes = info.info
167
+ ? new TextEncoder().encode(info.info)
168
+ : new Uint8Array(0);
169
+ // Import the input key material
170
+ const importedKey = await crypto_2.subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits']);
171
+ // Derive bits using HKDF
172
+ const derivedBits = await crypto_2.subtle.deriveBits({
173
+ name: 'HKDF',
174
+ hash: 'SHA-256',
175
+ salt: salt,
176
+ info: infoBytes
177
+ }, importedKey, expandedLength * 8 // Convert bytes to bits
178
+ );
179
+ return Buffer.from(derivedBits);
180
+ }
181
+ async function derivePairingCodeKey(pairingCode, salt) {
182
+ // Convert inputs to formats Web Crypto API can work with
183
+ const encoder = new TextEncoder();
184
+ const pairingCodeBuffer = encoder.encode(pairingCode);
185
+ const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
186
+ // Import the pairing code as key material
187
+ const keyMaterial = await crypto_2.subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits']);
188
+ // Derive bits using PBKDF2 with the same parameters
189
+ // 2 << 16 = 131,072 iterations
190
+ const derivedBits = await crypto_2.subtle.deriveBits({
191
+ name: 'PBKDF2',
192
+ salt: saltBuffer,
193
+ iterations: 2 << 16,
194
+ hash: 'SHA-256'
195
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
196
+ );
197
+ return Buffer.from(derivedBits);
198
+ }
199
+
@@ -0,0 +1,36 @@
1
+ import { Logger } from 'pino';
2
+ import { proto } from '../../WAProto';
3
+ import { SignalRepository } from '../Types';
4
+ import { BinaryNode } from '../WABinary';
5
+ export declare const NO_MESSAGE_FOUND_ERROR_TEXT = "Message absent from node";
6
+ export declare const MISSING_KEYS_ERROR_TEXT = "Key used already or never filled";
7
+ export declare const NACK_REASONS: {
8
+ ParsingError: number;
9
+ UnrecognizedStanza: number;
10
+ UnrecognizedStanzaClass: number;
11
+ UnrecognizedStanzaType: number;
12
+ InvalidProtobuf: number;
13
+ InvalidHostedCompanionStanza: number;
14
+ MissingMessageSecret: number;
15
+ SignalErrorOldCounter: number;
16
+ MessageDeletedOnPeer: number;
17
+ UnhandledError: number;
18
+ UnsupportedAdminRevoke: number;
19
+ UnsupportedLIDGroup: number;
20
+ DBOperationFailed: number;
21
+ };
22
+ /**
23
+ * Decode the received node as a message.
24
+ * @note this will only parse the message, not decrypt it
25
+ */
26
+ export declare function decodeMessageNode(stanza: BinaryNode, meId: string, meLid: string): {
27
+ fullMessage: proto.IWebMessageInfo;
28
+ author: string;
29
+ sender: string;
30
+ };
31
+ export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepository, logger: Logger) => {
32
+ fullMessage: proto.IWebMessageInfo;
33
+ category: string;
34
+ author: string;
35
+ decrypt(): Promise<void>;
36
+ };
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decryptMessageNode = exports.NACK_REASONS = exports.MISSING_KEYS_ERROR_TEXT = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
4
+ exports.decodeMessageNode = decodeMessageNode;
5
+ const boom_1 = require("@hapi/boom");
6
+ const WAProto_1 = require("../../WAProto");
7
+ const WABinary_1 = require("../WABinary");
8
+ const generics_1 = require("./generics");
9
+ exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
10
+ exports.MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
11
+ exports.NACK_REASONS = {
12
+ ParsingError: 487,
13
+ UnrecognizedStanza: 488,
14
+ UnrecognizedStanzaClass: 489,
15
+ UnrecognizedStanzaType: 490,
16
+ InvalidProtobuf: 491,
17
+ InvalidHostedCompanionStanza: 493,
18
+ MissingMessageSecret: 495,
19
+ SignalErrorOldCounter: 496,
20
+ MessageDeletedOnPeer: 499,
21
+ UnhandledError: 500,
22
+ UnsupportedAdminRevoke: 550,
23
+ UnsupportedLIDGroup: 551,
24
+ DBOperationFailed: 552
25
+ };
26
+ /**
27
+ * Decode the received node as a message.
28
+ * @note this will only parse the message, not decrypt it
29
+ */
30
+ function decodeMessageNode(stanza, meId, meLid) {
31
+ var _a, _b;
32
+ let msgType;
33
+ let chatId;
34
+ let author;
35
+ const msgId = stanza.attrs.id;
36
+ const from = stanza.attrs.from;
37
+ const participant = stanza.attrs.participant;
38
+ const recipient = stanza.attrs.recipient;
39
+ const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
40
+ const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
41
+ if ((0, WABinary_1.isJidUser)(from)) {
42
+ if (recipient) {
43
+ if (!isMe(from)) {
44
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
45
+ }
46
+ chatId = recipient;
47
+ }
48
+ else {
49
+ chatId = from;
50
+ }
51
+ msgType = 'chat';
52
+ author = from;
53
+ }
54
+ else if ((0, WABinary_1.isLidUser)(from)) {
55
+ if (recipient) {
56
+ if (!isMeLid(from)) {
57
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
58
+ }
59
+ chatId = recipient;
60
+ }
61
+ else {
62
+ chatId = from;
63
+ }
64
+ msgType = 'chat';
65
+ author = from;
66
+ }
67
+ else if ((0, WABinary_1.isJidGroup)(from)) {
68
+ if (!participant) {
69
+ throw new boom_1.Boom('No participant in group message');
70
+ }
71
+ msgType = 'group';
72
+ author = participant;
73
+ chatId = from;
74
+ }
75
+ else if ((0, WABinary_1.isJidBroadcast)(from)) {
76
+ if (!participant) {
77
+ throw new boom_1.Boom('No participant in group message');
78
+ }
79
+ const isParticipantMe = isMe(participant);
80
+ if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
81
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
82
+ }
83
+ else {
84
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
85
+ }
86
+ chatId = from;
87
+ author = participant;
88
+ }
89
+ else if ((0, WABinary_1.isJidNewsLetter)(from)) {
90
+ msgType = 'newsletter';
91
+ author = from;
92
+ chatId = from;
93
+ }
94
+ else {
95
+ throw new boom_1.Boom('Unknown message type', { data: stanza });
96
+ }
97
+ const fromMe = (0, WABinary_1.isJidNewsLetter)(from) ? !!((_a = stanza.attrs) === null || _a === void 0 ? void 0 : _a.is_sender) : ((0, WABinary_1.isLidUser)(participant || from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
98
+ const pushname = stanza.attrs.notify;
99
+ const key = {
100
+ remoteJid: chatId,
101
+ fromMe,
102
+ id: msgId,
103
+ ...(stanza.attrs.participant_pn ?? participant) !== undefined && {
104
+ participant: fromMe ? meId : stanza.attrs.participant_pn ?? participant
105
+ },
106
+ ...(stanza.attrs.participant_pn ?? participant) !== undefined && {
107
+ participant_pn: fromMe ? meId : stanza.attrs.participant_pn ?? participant
108
+ },
109
+ ...(stanza.attrs.participant_lid ?? participant) !== undefined && {
110
+ participant_lid: fromMe ? meLid : stanza.attrs.participant_lid ?? participant
111
+ }
112
+ };
113
+ const fullMessage = {
114
+ key,
115
+ messageTimestamp: +stanza.attrs.t,
116
+ pushName: pushname,
117
+ broadcast: (0, WABinary_1.isJidBroadcast)(from)
118
+ };
119
+ if (msgType === 'newsletter') {
120
+ fullMessage.newsletterServerId = +((_b = stanza.attrs) === null || _b === void 0 ? void 0 : _b.server_id);
121
+ }
122
+ if (key.fromMe) {
123
+ fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
124
+ }
125
+ return {
126
+ fullMessage,
127
+ author,
128
+ sender: msgType === 'chat' ? author : chatId
129
+ };
130
+ }
131
+ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
132
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
133
+ return {
134
+ fullMessage,
135
+ category: stanza.attrs.category,
136
+ author,
137
+ async decrypt() {
138
+ var _a;
139
+ let decryptables = 0;
140
+ if ((0, WABinary_1.isJidNewsLetter)(fullMessage.key.remoteJid)) {
141
+ const node = (0, WABinary_1.getBinaryNodeChild)(stanza, 'plaintext');
142
+ const msg = WAProto_1.proto.Message.decode(node === null || node === void 0 ? void 0 : node.content);
143
+ if (msg.senderKeyDistributionMessage) {
144
+ //eslint-disable-next-line max-depth
145
+ try {
146
+ await repository.processSenderKeyDistributionMessage({
147
+ authorJid: author,
148
+ item: msg.senderKeyDistributionMessage
149
+ });
150
+ }
151
+ catch (err) {
152
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
153
+ }
154
+ }
155
+ fullMessage.message = msg;
156
+ decryptables += 1;
157
+ }
158
+ else if (Array.isArray(stanza.content)) {
159
+ for (const { tag, attrs, content } of stanza.content) {
160
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
161
+ const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
162
+ const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
163
+ fullMessage.verifiedBizName = details.verifiedName;
164
+ }
165
+ if (tag !== 'enc' && tag !== 'plaintext') {
166
+ continue;
167
+ }
168
+ if (!(content instanceof Uint8Array)) {
169
+ continue;
170
+ }
171
+ decryptables += 1;
172
+ let msgBuffer;
173
+ try {
174
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
175
+ switch (e2eType) {
176
+ case 'skmsg':
177
+ msgBuffer = await repository.decryptGroupMessage({
178
+ group: sender,
179
+ authorJid: author,
180
+ msg: content
181
+ });
182
+ break;
183
+ case 'pkmsg':
184
+ case 'msg':
185
+ const user = (0, WABinary_1.isJidUser)(sender) ? sender : author;
186
+ msgBuffer = await repository.decryptMessage({
187
+ jid: user,
188
+ type: e2eType,
189
+ ciphertext: content
190
+ });
191
+ break;
192
+ case 'plaintext':
193
+ msgBuffer = content;
194
+ break;
195
+ default:
196
+ throw new Error(`Unknown e2e type: ${e2eType}`);
197
+ }
198
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
199
+ msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
200
+ if (msg.senderKeyDistributionMessage) {
201
+ //eslint-disable-next-line max-depth
202
+ try {
203
+ await repository.processSenderKeyDistributionMessage({
204
+ authorJid: author,
205
+ item: msg.senderKeyDistributionMessage
206
+ });
207
+ }
208
+ catch (err) {
209
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
210
+ }
211
+ }
212
+ if (fullMessage.message) {
213
+ Object.assign(fullMessage.message, msg);
214
+ }
215
+ else {
216
+ fullMessage.message = msg;
217
+ }
218
+ }
219
+ catch (err) {
220
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
221
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
222
+ fullMessage.messageStubParameters = [err.message];
223
+ }
224
+ }
225
+ }
226
+ // if nothing was found to decrypt
227
+ if (!decryptables) {
228
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
229
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
230
+ }
231
+ }
232
+ };
233
+ };
234
+ exports.decryptMessageNode = decryptMessageNode;
@@ -0,0 +1,35 @@
1
+ import { Logger } from 'pino';
2
+ import { BaileysEventEmitter, BaileysEventMap } from '../Types';
3
+ /**
4
+ * A map that contains a list of all events that have been triggered
5
+ *
6
+ * Note, this can contain different type of events
7
+ * this can make processing events extremely efficient -- since everything
8
+ * can be done in a single transaction
9
+ */
10
+ type BaileysEventData = Partial<BaileysEventMap>;
11
+ type BaileysBufferableEventEmitter = BaileysEventEmitter & {
12
+ /** Use to process events in a batch */
13
+ process(handler: (events: BaileysEventData) => void | Promise<void>): (() => void);
14
+ /**
15
+ * starts buffering events, call flush() to release them
16
+ * */
17
+ buffer(): void;
18
+ /** buffers all events till the promise completes */
19
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): ((...args: A) => Promise<T>);
20
+ /**
21
+ * flushes all buffered events
22
+ * @param force if true, will flush all data regardless of any pending buffers
23
+ * @returns returns true if the flush actually happened, otherwise false
24
+ */
25
+ flush(force?: boolean): boolean;
26
+ /** is there an ongoing buffer */
27
+ isBuffering(): boolean;
28
+ };
29
+ /**
30
+ * The event buffer logically consolidates different events into a single event
31
+ * making the data processing more efficient.
32
+ * @param ev the baileys event emitter
33
+ */
34
+ export declare const makeEventBuffer: (logger: Logger) => BaileysBufferableEventEmitter;
35
+ export {};