libzapitu 1.0.0-alpha.3

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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1294 -0
  3. package/WAProto/GenerateStatics.sh +2 -0
  4. package/WAProto/WAProto.proto +4633 -0
  5. package/WAProto/index.d.ts +53473 -0
  6. package/WAProto/index.js +165029 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/baileys-version.json +3 -0
  9. package/lib/Defaults/index.d.ts +51 -0
  10. package/lib/Defaults/index.js +105 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  14. package/lib/Signal/Group/group-session-builder.js +64 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  16. package/lib/Signal/Group/group_cipher.js +96 -0
  17. package/lib/Signal/Group/index.d.ts +11 -0
  18. package/lib/Signal/Group/index.js +57 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  20. package/lib/Signal/Group/keyhelper.js +55 -0
  21. package/lib/Signal/Group/queue-job.d.ts +1 -0
  22. package/lib/Signal/Group/queue-job.js +57 -0
  23. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  24. package/lib/Signal/Group/sender-chain-key.js +34 -0
  25. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  27. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  28. package/lib/Signal/Group/sender-key-message.js +69 -0
  29. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  30. package/lib/Signal/Group/sender-key-name.js +51 -0
  31. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  32. package/lib/Signal/Group/sender-key-record.js +53 -0
  33. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  34. package/lib/Signal/Group/sender-key-state.js +99 -0
  35. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  36. package/lib/Signal/Group/sender-message-key.js +29 -0
  37. package/lib/Signal/libsignal.d.ts +3 -0
  38. package/lib/Signal/libsignal.js +174 -0
  39. package/lib/Socket/Client/index.d.ts +2 -0
  40. package/lib/Socket/Client/index.js +18 -0
  41. package/lib/Socket/Client/types.d.ts +15 -0
  42. package/lib/Socket/Client/types.js +13 -0
  43. package/lib/Socket/Client/websocket.d.ts +12 -0
  44. package/lib/Socket/Client/websocket.js +62 -0
  45. package/lib/Socket/business.d.ts +153 -0
  46. package/lib/Socket/business.js +260 -0
  47. package/lib/Socket/chats.d.ts +90 -0
  48. package/lib/Socket/chats.js +898 -0
  49. package/lib/Socket/groups.d.ts +132 -0
  50. package/lib/Socket/groups.js +331 -0
  51. package/lib/Socket/index.d.ts +153 -0
  52. package/lib/Socket/index.js +10 -0
  53. package/lib/Socket/messages-recv.d.ts +142 -0
  54. package/lib/Socket/messages-recv.js +1089 -0
  55. package/lib/Socket/messages-send.d.ts +137 -0
  56. package/lib/Socket/messages-send.js +818 -0
  57. package/lib/Socket/mex.d.ts +2 -0
  58. package/lib/Socket/mex.js +46 -0
  59. package/lib/Socket/newsletter.d.ts +143 -0
  60. package/lib/Socket/newsletter.js +183 -0
  61. package/lib/Socket/socket.d.ts +42 -0
  62. package/lib/Socket/socket.js +616 -0
  63. package/lib/Socket/usync.d.ts +36 -0
  64. package/lib/Socket/usync.js +65 -0
  65. package/lib/Types/Auth.d.ts +103 -0
  66. package/lib/Types/Auth.js +2 -0
  67. package/lib/Types/Call.d.ts +13 -0
  68. package/lib/Types/Call.js +2 -0
  69. package/lib/Types/Chat.d.ts +115 -0
  70. package/lib/Types/Chat.js +10 -0
  71. package/lib/Types/Contact.d.ts +23 -0
  72. package/lib/Types/Contact.js +2 -0
  73. package/lib/Types/Events.d.ts +198 -0
  74. package/lib/Types/Events.js +2 -0
  75. package/lib/Types/GroupMetadata.d.ts +63 -0
  76. package/lib/Types/GroupMetadata.js +2 -0
  77. package/lib/Types/Label.d.ts +46 -0
  78. package/lib/Types/Label.js +27 -0
  79. package/lib/Types/LabelAssociation.d.ts +29 -0
  80. package/lib/Types/LabelAssociation.js +9 -0
  81. package/lib/Types/Message.d.ts +279 -0
  82. package/lib/Types/Message.js +7 -0
  83. package/lib/Types/Newsletter.d.ts +134 -0
  84. package/lib/Types/Newsletter.js +33 -0
  85. package/lib/Types/Product.d.ts +78 -0
  86. package/lib/Types/Product.js +2 -0
  87. package/lib/Types/Signal.d.ts +57 -0
  88. package/lib/Types/Signal.js +2 -0
  89. package/lib/Types/Socket.d.ts +121 -0
  90. package/lib/Types/Socket.js +2 -0
  91. package/lib/Types/State.d.ts +27 -0
  92. package/lib/Types/State.js +2 -0
  93. package/lib/Types/USync.d.ts +25 -0
  94. package/lib/Types/USync.js +2 -0
  95. package/lib/Types/index.d.ts +64 -0
  96. package/lib/Types/index.js +42 -0
  97. package/lib/Utils/auth-utils.d.ts +18 -0
  98. package/lib/Utils/auth-utils.js +199 -0
  99. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  100. package/lib/Utils/baileys-event-stream.js +63 -0
  101. package/lib/Utils/business.d.ts +22 -0
  102. package/lib/Utils/business.js +240 -0
  103. package/lib/Utils/chat-utils.d.ts +70 -0
  104. package/lib/Utils/chat-utils.js +753 -0
  105. package/lib/Utils/crypto.d.ts +40 -0
  106. package/lib/Utils/crypto.js +187 -0
  107. package/lib/Utils/decode-wa-message.d.ts +36 -0
  108. package/lib/Utils/decode-wa-message.js +236 -0
  109. package/lib/Utils/event-buffer.d.ts +35 -0
  110. package/lib/Utils/event-buffer.js +516 -0
  111. package/lib/Utils/generics.d.ts +91 -0
  112. package/lib/Utils/generics.js +397 -0
  113. package/lib/Utils/history.d.ts +19 -0
  114. package/lib/Utils/history.js +93 -0
  115. package/lib/Utils/index.d.ts +17 -0
  116. package/lib/Utils/index.js +33 -0
  117. package/lib/Utils/link-preview.d.ts +21 -0
  118. package/lib/Utils/link-preview.js +122 -0
  119. package/lib/Utils/logger.d.ts +11 -0
  120. package/lib/Utils/logger.js +7 -0
  121. package/lib/Utils/lt-hash.d.ts +12 -0
  122. package/lib/Utils/lt-hash.js +51 -0
  123. package/lib/Utils/make-mutex.d.ts +7 -0
  124. package/lib/Utils/make-mutex.js +44 -0
  125. package/lib/Utils/messages-media.d.ts +111 -0
  126. package/lib/Utils/messages-media.js +701 -0
  127. package/lib/Utils/messages.d.ts +76 -0
  128. package/lib/Utils/messages.js +816 -0
  129. package/lib/Utils/noise-handler.d.ts +19 -0
  130. package/lib/Utils/noise-handler.js +150 -0
  131. package/lib/Utils/process-message.d.ts +41 -0
  132. package/lib/Utils/process-message.js +377 -0
  133. package/lib/Utils/signal.d.ts +33 -0
  134. package/lib/Utils/signal.js +159 -0
  135. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  136. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  137. package/lib/Utils/validate-connection.d.ts +10 -0
  138. package/lib/Utils/validate-connection.js +170 -0
  139. package/lib/WABinary/constants.d.ts +27 -0
  140. package/lib/WABinary/constants.js +1303 -0
  141. package/lib/WABinary/decode.d.ts +6 -0
  142. package/lib/WABinary/decode.js +266 -0
  143. package/lib/WABinary/encode.d.ts +2 -0
  144. package/lib/WABinary/encode.js +252 -0
  145. package/lib/WABinary/generic-utils.d.ts +14 -0
  146. package/lib/WABinary/generic-utils.js +110 -0
  147. package/lib/WABinary/index.d.ts +5 -0
  148. package/lib/WABinary/index.js +21 -0
  149. package/lib/WABinary/jid-utils.d.ts +36 -0
  150. package/lib/WABinary/jid-utils.js +66 -0
  151. package/lib/WABinary/types.d.ts +18 -0
  152. package/lib/WABinary/types.js +2 -0
  153. package/lib/WAM/BinaryInfo.d.ts +8 -0
  154. package/lib/WAM/BinaryInfo.js +13 -0
  155. package/lib/WAM/constants.d.ts +39 -0
  156. package/lib/WAM/constants.js +15243 -0
  157. package/lib/WAM/encode.d.ts +2 -0
  158. package/lib/WAM/encode.js +153 -0
  159. package/lib/WAM/index.d.ts +3 -0
  160. package/lib/WAM/index.js +19 -0
  161. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  162. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  163. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  164. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  165. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  166. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  167. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  168. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  169. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  170. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  171. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  172. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  173. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  174. package/lib/WAUSync/Protocols/index.js +20 -0
  175. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  176. package/lib/WAUSync/USyncQuery.js +93 -0
  177. package/lib/WAUSync/USyncUser.d.ts +12 -0
  178. package/lib/WAUSync/USyncUser.js +26 -0
  179. package/lib/WAUSync/index.d.ts +3 -0
  180. package/lib/WAUSync/index.js +19 -0
  181. package/lib/index.d.ts +11 -0
  182. package/lib/index.js +30 -0
  183. package/package.json +102 -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) => Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike>;
4
+ export declare const Curve: {
5
+ generateKeyPair: () => KeyPair;
6
+ sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer<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): Buffer<ArrayBuffer>;
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): 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>;
27
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
28
+ export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer<ArrayBuffer>;
29
+ /** decrypt AES 256 CBC */
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>;
36
+ export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number, info: {
37
+ salt?: Buffer;
38
+ info?: string;
39
+ }): Promise<Buffer>;
40
+ export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;
@@ -0,0 +1,187 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
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;
50
+ const crypto_1 = require("crypto");
51
+ const libsignal = __importStar(require("libsignal"));
52
+ const Defaults_1 = require("../Defaults");
53
+ // insure browser & node compatibility
54
+ const { subtle } = globalThis.crypto;
55
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
56
+ const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([Defaults_1.KEY_BUNDLE_TYPE, pubKey]);
57
+ exports.generateSignalPubKey = generateSignalPubKey;
58
+ exports.Curve = {
59
+ generateKeyPair: () => {
60
+ const { pubKey, privKey } = libsignal.curve.generateKeyPair();
61
+ return {
62
+ private: Buffer.from(privKey),
63
+ // remove version byte
64
+ public: Buffer.from(pubKey.slice(1))
65
+ };
66
+ },
67
+ sharedKey: (privateKey, publicKey) => {
68
+ const shared = libsignal.curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
69
+ return Buffer.from(shared);
70
+ },
71
+ sign: (privateKey, buf) => libsignal.curve.calculateSignature(privateKey, buf),
72
+ verify: (pubKey, message, signature) => {
73
+ try {
74
+ libsignal.curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
75
+ return true;
76
+ }
77
+ catch (error) {
78
+ return false;
79
+ }
80
+ }
81
+ };
82
+ const signedKeyPair = (identityKeyPair, keyId) => {
83
+ const preKey = exports.Curve.generateKeyPair();
84
+ const pubKey = (0, exports.generateSignalPubKey)(preKey.public);
85
+ const signature = exports.Curve.sign(identityKeyPair.private, pubKey);
86
+ return { keyPair: preKey, signature, keyId };
87
+ };
88
+ exports.signedKeyPair = signedKeyPair;
89
+ const GCM_TAG_LENGTH = 128 >> 3;
90
+ /**
91
+ * encrypt AES 256 GCM;
92
+ * where the tag tag is suffixed to the ciphertext
93
+ * */
94
+ function aesEncryptGCM(plaintext, key, iv, additionalData) {
95
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
96
+ cipher.setAAD(additionalData);
97
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
98
+ }
99
+ /**
100
+ * decrypt AES 256 GCM;
101
+ * where the auth tag is suffixed to the ciphertext
102
+ * */
103
+ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
104
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
105
+ // decrypt additional adata
106
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
107
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
108
+ // set additional data
109
+ decipher.setAAD(additionalData);
110
+ decipher.setAuthTag(tag);
111
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
112
+ }
113
+ function aesEncryptCTR(plaintext, key, iv) {
114
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
115
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
116
+ }
117
+ function aesDecryptCTR(ciphertext, key, iv) {
118
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
119
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
120
+ }
121
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
122
+ function aesDecrypt(buffer, key) {
123
+ return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
124
+ }
125
+ /** decrypt AES 256 CBC */
126
+ function aesDecryptWithIV(buffer, key, IV) {
127
+ const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
128
+ return Buffer.concat([aes.update(buffer), aes.final()]);
129
+ }
130
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
131
+ function aesEncrypt(buffer, key) {
132
+ const IV = (0, crypto_1.randomBytes)(16);
133
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
134
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
135
+ }
136
+ // encrypt AES 256 CBC with a given IV
137
+ function aesEncrypWithIV(buffer, key, IV) {
138
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
139
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
140
+ }
141
+ // sign HMAC using SHA 256
142
+ function hmacSign(buffer, key, variant = 'sha256') {
143
+ return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
144
+ }
145
+ function sha256(buffer) {
146
+ return (0, crypto_1.createHash)('sha256').update(buffer).digest();
147
+ }
148
+ function md5(buffer) {
149
+ return (0, crypto_1.createHash)('md5').update(buffer).digest();
150
+ }
151
+ // HKDF key expansion
152
+ async function hkdf(buffer, expandedLength, info) {
153
+ // Ensure we have a Uint8Array for the key material
154
+ const inputKeyMaterial = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
155
+ // Set default values if not provided
156
+ const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
157
+ const infoBytes = info.info ? new TextEncoder().encode(info.info) : new Uint8Array(0);
158
+ // Import the input key material
159
+ const importedKey = await subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits']);
160
+ // Derive bits using HKDF
161
+ const derivedBits = await subtle.deriveBits({
162
+ name: 'HKDF',
163
+ hash: 'SHA-256',
164
+ salt: salt,
165
+ info: infoBytes
166
+ }, importedKey, expandedLength * 8 // Convert bytes to bits
167
+ );
168
+ return Buffer.from(derivedBits);
169
+ }
170
+ async function derivePairingCodeKey(pairingCode, salt) {
171
+ // Convert inputs to formats Web Crypto API can work with
172
+ const encoder = new TextEncoder();
173
+ const pairingCodeBuffer = encoder.encode(pairingCode);
174
+ const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
175
+ // Import the pairing code as key material
176
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits']);
177
+ // Derive bits using PBKDF2 with the same parameters
178
+ // 2 << 16 = 131,072 iterations
179
+ const derivedBits = await subtle.deriveBits({
180
+ name: 'PBKDF2',
181
+ salt: saltBuffer,
182
+ iterations: 2 << 16,
183
+ hash: 'SHA-256'
184
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
185
+ );
186
+ return Buffer.from(derivedBits);
187
+ }
@@ -0,0 +1,36 @@
1
+ import { proto } from '../../WAProto';
2
+ import { SignalRepository } from '../Types';
3
+ import { BinaryNode } from '../WABinary';
4
+ import { ILogger } from './logger';
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: ILogger) => {
32
+ fullMessage: proto.IWebMessageInfo;
33
+ category: string;
34
+ author: string;
35
+ decrypt(): Promise<void>;
36
+ };
@@ -0,0 +1,236 @@
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, _c, _d, _e, _f, _g, _h, _j, _k;
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 isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
39
+ const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
40
+ const participant_lid = stanza.attrs.participant_lid;
41
+ const participant_pn = (_a = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _a === void 0 ? void 0 : _a.participant_pn;
42
+ const sender_lid = stanza.attrs.sender_lid;
43
+ const recipient = stanza.attrs.recipient;
44
+ const sender_pn = (_b = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _b === void 0 ? void 0 : _b.sender_pn;
45
+ const peer_recipient_pn = (_c = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _c === void 0 ? void 0 : _c.peer_recipient_pn;
46
+ const fromMe = ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
47
+ if ((0, WABinary_1.isJidUser)(from) || (0, WABinary_1.isLidUser)(from)) {
48
+ if (recipient && !(0, WABinary_1.isJidMetaIa)(recipient)) {
49
+ if (!isMe(from) && !isMeLid(from)) {
50
+ throw new boom_1.Boom('recipient present, but msg not from me', { data: stanza });
51
+ }
52
+ chatId = recipient;
53
+ }
54
+ else {
55
+ chatId = from || sender_lid;
56
+ }
57
+ msgType = 'chat';
58
+ const deviceOrigem = (_d = (0, WABinary_1.jidDecode)(from)) === null || _d === void 0 ? void 0 : _d.device;
59
+ if (fromMe) {
60
+ const userDestino = (_e = (0, WABinary_1.jidDecode)((0, WABinary_1.jidNormalizedUser)(meLid))) === null || _e === void 0 ? void 0 : _e.user;
61
+ author = deviceOrigem
62
+ ? `${userDestino}:${deviceOrigem}@lid`
63
+ : `${userDestino}@lid`;
64
+ }
65
+ else {
66
+ if (!sender_lid) {
67
+ author = from;
68
+ }
69
+ else {
70
+ const userDestino = (_f = (0, WABinary_1.jidDecode)(sender_lid)) === null || _f === void 0 ? void 0 : _f.user;
71
+ author = deviceOrigem
72
+ ? `${userDestino}:${deviceOrigem}@lid`
73
+ : `${userDestino}@lid`;
74
+ }
75
+ }
76
+ }
77
+ else if ((0, WABinary_1.isJidGroup)(from)) {
78
+ if (!participant) {
79
+ throw new boom_1.Boom('No participant in group message');
80
+ }
81
+ msgType = 'group';
82
+ chatId = from || sender_lid;
83
+ const deviceOrigem = (_g = (0, WABinary_1.jidDecode)(participant)) === null || _g === void 0 ? void 0 : _g.device;
84
+ if (fromMe) {
85
+ const userDestino = (_h = (0, WABinary_1.jidDecode)((0, WABinary_1.jidNormalizedUser)(meLid))) === null || _h === void 0 ? void 0 : _h.user;
86
+ author = deviceOrigem
87
+ ? `${userDestino}:${deviceOrigem}@lid`
88
+ : `${userDestino}@lid`;
89
+ }
90
+ else {
91
+ if (!participant_lid) {
92
+ author = participant;
93
+ }
94
+ else {
95
+ const userDestino = (_j = (0, WABinary_1.jidDecode)(participant_lid)) === null || _j === void 0 ? void 0 : _j.user;
96
+ author = deviceOrigem
97
+ ? `${userDestino}:${deviceOrigem}@lid`
98
+ : `${userDestino}@lid`;
99
+ }
100
+ }
101
+ }
102
+ else if ((0, WABinary_1.isJidBroadcast)(from)) {
103
+ if (!participant && participant_lid) {
104
+ throw new boom_1.Boom('No participant in group message');
105
+ }
106
+ const isParticipantMe = isMe(participant);
107
+ if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
108
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
109
+ }
110
+ else {
111
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
112
+ }
113
+ chatId = from;
114
+ author = participant_lid || participant;
115
+ }
116
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
117
+ msgType = 'newsletter';
118
+ chatId = from;
119
+ author = from;
120
+ }
121
+ else {
122
+ throw new boom_1.Boom('Unknown message type', { data: stanza });
123
+ }
124
+ const pushname = (_k = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _k === void 0 ? void 0 : _k.notify;
125
+ const key = {
126
+ remoteJid: chatId,
127
+ fromMe,
128
+ id: msgId,
129
+ ...(sender_lid && { sender_lid }),
130
+ ...(participant && { participant }),
131
+ ...(participant_pn && { participant_pn }),
132
+ ...(participant_lid && { participant_lid }),
133
+ ...(sender_pn && { sender_pn }),
134
+ ...(peer_recipient_pn && { peer_recipient_pn }),
135
+ };
136
+ const fullMessage = {
137
+ key,
138
+ messageTimestamp: +stanza.attrs.t,
139
+ pushName: pushname,
140
+ broadcast: (0, WABinary_1.isJidBroadcast)(from)
141
+ };
142
+ if (key.fromMe) {
143
+ fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
144
+ }
145
+ return {
146
+ fullMessage,
147
+ author,
148
+ sender: msgType === 'chat' ? author : chatId
149
+ };
150
+ }
151
+ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
152
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
153
+ return {
154
+ fullMessage,
155
+ category: stanza.attrs.category,
156
+ author,
157
+ async decrypt() {
158
+ var _a;
159
+ let decryptables = 0;
160
+ if (Array.isArray(stanza.content)) {
161
+ for (const { tag, attrs, content } of stanza.content) {
162
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
163
+ const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
164
+ const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
165
+ fullMessage.verifiedBizName = details.verifiedName;
166
+ }
167
+ if (tag !== 'enc' && tag !== 'plaintext') {
168
+ continue;
169
+ }
170
+ if (!(content instanceof Uint8Array)) {
171
+ continue;
172
+ }
173
+ decryptables += 1;
174
+ let msgBuffer;
175
+ try {
176
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
177
+ switch (e2eType) {
178
+ case 'skmsg':
179
+ msgBuffer = await repository.decryptGroupMessage({
180
+ group: sender,
181
+ authorJid: author,
182
+ msg: content
183
+ });
184
+ break;
185
+ case 'pkmsg':
186
+ case 'msg':
187
+ const user = (0, WABinary_1.isJidUser)(sender) ? sender : author;
188
+ msgBuffer = await repository.decryptMessage({
189
+ jid: user,
190
+ type: e2eType,
191
+ ciphertext: content
192
+ });
193
+ break;
194
+ case 'plaintext':
195
+ msgBuffer = content;
196
+ break;
197
+ default:
198
+ throw new Error(`Unknown e2e type: ${e2eType}`);
199
+ }
200
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
201
+ msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
202
+ if (msg.senderKeyDistributionMessage) {
203
+ //eslint-disable-next-line max-depth
204
+ try {
205
+ await repository.processSenderKeyDistributionMessage({
206
+ authorJid: author,
207
+ item: msg.senderKeyDistributionMessage
208
+ });
209
+ }
210
+ catch (err) {
211
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
212
+ }
213
+ }
214
+ if (fullMessage.message) {
215
+ Object.assign(fullMessage.message, msg);
216
+ }
217
+ else {
218
+ fullMessage.message = msg;
219
+ }
220
+ }
221
+ catch (err) {
222
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
223
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
224
+ fullMessage.messageStubParameters = [err.message];
225
+ }
226
+ }
227
+ }
228
+ // if nothing was found to decrypt
229
+ if (!decryptables) {
230
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
231
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
232
+ }
233
+ }
234
+ };
235
+ };
236
+ exports.decryptMessageNode = decryptMessageNode;
@@ -0,0 +1,35 @@
1
+ import { BaileysEventEmitter, BaileysEventMap } from '../Types';
2
+ import { ILogger } from './logger';
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: ILogger) => BaileysBufferableEventEmitter;
35
+ export {};