@genuxofficial/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 (171) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +3344 -0
  5. package/WAProto/index.d.ts +37016 -0
  6. package/WAProto/index.js +101044 -0
  7. package/WASignalGroup/GroupProtocol.js +1697 -0
  8. package/WASignalGroup/ciphertext_message.js +16 -0
  9. package/WASignalGroup/group_cipher.js +120 -0
  10. package/WASignalGroup/group_session_builder.js +46 -0
  11. package/WASignalGroup/index.js +5 -0
  12. package/WASignalGroup/keyhelper.js +21 -0
  13. package/WASignalGroup/protobufs.js +3 -0
  14. package/WASignalGroup/queue_job.js +69 -0
  15. package/WASignalGroup/sender_chain_key.js +50 -0
  16. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  17. package/WASignalGroup/sender_key_message.js +92 -0
  18. package/WASignalGroup/sender_key_name.js +70 -0
  19. package/WASignalGroup/sender_key_record.js +56 -0
  20. package/WASignalGroup/sender_key_state.js +129 -0
  21. package/WASignalGroup/sender_message_key.js +39 -0
  22. package/lib/Defaults/baileys-version.json +3 -0
  23. package/lib/Defaults/index.d.ts +53 -0
  24. package/lib/Defaults/index.js +106 -0
  25. package/lib/Signal/libsignal.d.ts +3 -0
  26. package/lib/Signal/libsignal.js +152 -0
  27. package/lib/Socket/Client/index.d.ts +2 -0
  28. package/lib/Socket/Client/index.js +18 -0
  29. package/lib/Socket/Client/types.d.ts +17 -0
  30. package/lib/Socket/Client/types.js +13 -0
  31. package/lib/Socket/Client/websocket.d.ts +12 -0
  32. package/lib/Socket/Client/websocket.js +62 -0
  33. package/lib/Socket/business.d.ts +149 -0
  34. package/lib/Socket/business.js +260 -0
  35. package/lib/Socket/chats.d.ts +85 -0
  36. package/lib/Socket/chats.js +850 -0
  37. package/lib/Socket/groups.d.ts +124 -0
  38. package/lib/Socket/groups.js +314 -0
  39. package/lib/Socket/index.d.ts +149 -0
  40. package/lib/Socket/index.js +10 -0
  41. package/lib/Socket/messages-recv.d.ts +136 -0
  42. package/lib/Socket/messages-recv.js +912 -0
  43. package/lib/Socket/messages-send.d.ts +130 -0
  44. package/lib/Socket/messages-send.js +673 -0
  45. package/lib/Socket/socket.d.ts +45 -0
  46. package/lib/Socket/socket.js +622 -0
  47. package/lib/Socket/usync.d.ts +38 -0
  48. package/lib/Socket/usync.js +70 -0
  49. package/lib/Store/index.d.ts +3 -0
  50. package/lib/Store/index.js +10 -0
  51. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  52. package/lib/Store/make-cache-manager-store.js +83 -0
  53. package/lib/Store/make-in-memory-store.d.ts +118 -0
  54. package/lib/Store/make-in-memory-store.js +420 -0
  55. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  56. package/lib/Store/make-ordered-dictionary.js +81 -0
  57. package/lib/Store/object-repository.d.ts +10 -0
  58. package/lib/Store/object-repository.js +27 -0
  59. package/lib/Types/Auth.d.ts +105 -0
  60. package/lib/Types/Auth.js +2 -0
  61. package/lib/Types/Call.d.ts +13 -0
  62. package/lib/Types/Call.js +2 -0
  63. package/lib/Types/Chat.d.ts +108 -0
  64. package/lib/Types/Chat.js +4 -0
  65. package/lib/Types/Contact.d.ts +19 -0
  66. package/lib/Types/Contact.js +2 -0
  67. package/lib/Types/Events.d.ts +172 -0
  68. package/lib/Types/Events.js +2 -0
  69. package/lib/Types/GroupMetadata.d.ts +56 -0
  70. package/lib/Types/GroupMetadata.js +2 -0
  71. package/lib/Types/Label.d.ts +46 -0
  72. package/lib/Types/Label.js +27 -0
  73. package/lib/Types/LabelAssociation.d.ts +29 -0
  74. package/lib/Types/LabelAssociation.js +9 -0
  75. package/lib/Types/Message.d.ts +271 -0
  76. package/lib/Types/Message.js +9 -0
  77. package/lib/Types/Product.d.ts +78 -0
  78. package/lib/Types/Product.js +2 -0
  79. package/lib/Types/Signal.d.ts +57 -0
  80. package/lib/Types/Signal.js +2 -0
  81. package/lib/Types/Socket.d.ts +118 -0
  82. package/lib/Types/Socket.js +2 -0
  83. package/lib/Types/State.d.ts +27 -0
  84. package/lib/Types/State.js +2 -0
  85. package/lib/Types/USync.d.ts +25 -0
  86. package/lib/Types/USync.js +2 -0
  87. package/lib/Types/index.d.ts +63 -0
  88. package/lib/Types/index.js +41 -0
  89. package/lib/Utils/auth-utils.d.ts +18 -0
  90. package/lib/Utils/auth-utils.js +200 -0
  91. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  92. package/lib/Utils/baileys-event-stream.js +63 -0
  93. package/lib/Utils/business.d.ts +22 -0
  94. package/lib/Utils/business.js +234 -0
  95. package/lib/Utils/chat-utils.d.ts +72 -0
  96. package/lib/Utils/chat-utils.js +745 -0
  97. package/lib/Utils/crypto.d.ts +42 -0
  98. package/lib/Utils/crypto.js +181 -0
  99. package/lib/Utils/decode-wa-message.d.ts +36 -0
  100. package/lib/Utils/decode-wa-message.js +205 -0
  101. package/lib/Utils/event-buffer.d.ts +35 -0
  102. package/lib/Utils/event-buffer.js +520 -0
  103. package/lib/Utils/generics.d.ts +94 -0
  104. package/lib/Utils/generics.js +433 -0
  105. package/lib/Utils/history.d.ts +19 -0
  106. package/lib/Utils/history.js +94 -0
  107. package/lib/Utils/index.d.ts +17 -0
  108. package/lib/Utils/index.js +33 -0
  109. package/lib/Utils/link-preview.d.ts +21 -0
  110. package/lib/Utils/link-preview.js +116 -0
  111. package/lib/Utils/logger.d.ts +11 -0
  112. package/lib/Utils/logger.js +7 -0
  113. package/lib/Utils/lt-hash.d.ts +12 -0
  114. package/lib/Utils/lt-hash.js +51 -0
  115. package/lib/Utils/make-mutex.d.ts +7 -0
  116. package/lib/Utils/make-mutex.js +44 -0
  117. package/lib/Utils/messages-media.d.ts +108 -0
  118. package/lib/Utils/messages-media.js +667 -0
  119. package/lib/Utils/messages.d.ts +78 -0
  120. package/lib/Utils/messages.js +760 -0
  121. package/lib/Utils/noise-handler.d.ts +21 -0
  122. package/lib/Utils/noise-handler.js +150 -0
  123. package/lib/Utils/process-message.d.ts +42 -0
  124. package/lib/Utils/process-message.js +373 -0
  125. package/lib/Utils/signal.d.ts +33 -0
  126. package/lib/Utils/signal.js +153 -0
  127. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  128. package/lib/Utils/use-multi-file-auth-state.js +94 -0
  129. package/lib/Utils/validate-connection.d.ts +10 -0
  130. package/lib/Utils/validate-connection.js +175 -0
  131. package/lib/WABinary/constants.d.ts +27 -0
  132. package/lib/WABinary/constants.js +40 -0
  133. package/lib/WABinary/decode.d.ts +8 -0
  134. package/lib/WABinary/decode.js +254 -0
  135. package/lib/WABinary/encode.d.ts +4 -0
  136. package/lib/WABinary/encode.js +234 -0
  137. package/lib/WABinary/generic-utils.d.ts +16 -0
  138. package/lib/WABinary/generic-utils.js +110 -0
  139. package/lib/WABinary/index.d.ts +5 -0
  140. package/lib/WABinary/index.js +21 -0
  141. package/lib/WABinary/jid-utils.d.ts +31 -0
  142. package/lib/WABinary/jid-utils.js +62 -0
  143. package/lib/WABinary/types.d.ts +18 -0
  144. package/lib/WABinary/types.js +2 -0
  145. package/lib/WAM/BinaryInfo.d.ts +18 -0
  146. package/lib/WAM/BinaryInfo.js +13 -0
  147. package/lib/WAM/constants.d.ts +39 -0
  148. package/lib/WAM/constants.js +15350 -0
  149. package/lib/WAM/encode.d.ts +4 -0
  150. package/lib/WAM/encode.js +155 -0
  151. package/lib/WAM/index.d.ts +3 -0
  152. package/lib/WAM/index.js +19 -0
  153. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  154. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  155. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  156. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  157. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  158. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  159. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  160. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  161. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  162. package/lib/WAUSync/Protocols/index.js +20 -0
  163. package/lib/WAUSync/USyncQuery.d.ts +26 -0
  164. package/lib/WAUSync/USyncQuery.js +79 -0
  165. package/lib/WAUSync/USyncUser.d.ts +10 -0
  166. package/lib/WAUSync/USyncUser.js +22 -0
  167. package/lib/WAUSync/index.d.ts +3 -0
  168. package/lib/WAUSync/index.js +19 -0
  169. package/lib/index.d.ts +12 -0
  170. package/lib/index.js +31 -0
  171. package/package.json +104 -0
@@ -0,0 +1,42 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { KeyPair } from '../Types';
4
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
5
+ export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array | Buffer;
6
+ export declare const Curve: {
7
+ generateKeyPair: () => KeyPair;
8
+ sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer;
9
+ sign: (privateKey: Uint8Array, buf: Uint8Array) => any;
10
+ verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean;
11
+ };
12
+ export declare const signedKeyPair: (identityKeyPair: KeyPair, keyId: number) => {
13
+ keyPair: KeyPair;
14
+ signature: any;
15
+ keyId: number;
16
+ };
17
+ /**
18
+ * encrypt AES 256 GCM;
19
+ * where the tag tag is suffixed to the ciphertext
20
+ * */
21
+ export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer;
22
+ /**
23
+ * decrypt AES 256 GCM;
24
+ * where the auth tag is suffixed to the ciphertext
25
+ * */
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;
29
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
30
+ export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer;
31
+ /** 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;
38
+ export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number, info: {
39
+ salt?: Buffer;
40
+ info?: string;
41
+ }): Promise<Buffer>;
42
+ export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;
@@ -0,0 +1,181 @@
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 (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
+ };
25
+ 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;
27
+ const crypto_1 = require("crypto");
28
+ const libsignal = __importStar(require("libsignal"));
29
+ const Defaults_1 = require("../Defaults");
30
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
31
+ const generateSignalPubKey = (pubKey) => (pubKey.length === 33
32
+ ? pubKey
33
+ : Buffer.concat([Defaults_1.KEY_BUNDLE_TYPE, pubKey]));
34
+ exports.generateSignalPubKey = generateSignalPubKey;
35
+ exports.Curve = {
36
+ generateKeyPair: () => {
37
+ const { pubKey, privKey } = libsignal.curve.generateKeyPair();
38
+ return {
39
+ private: Buffer.from(privKey),
40
+ // remove version byte
41
+ public: Buffer.from(pubKey.slice(1))
42
+ };
43
+ },
44
+ sharedKey: (privateKey, publicKey) => {
45
+ const shared = libsignal.curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
46
+ return Buffer.from(shared);
47
+ },
48
+ sign: (privateKey, buf) => (libsignal.curve.calculateSignature(privateKey, buf)),
49
+ verify: (pubKey, message, signature) => {
50
+ try {
51
+ libsignal.curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
52
+ return true;
53
+ }
54
+ catch (error) {
55
+ return false;
56
+ }
57
+ }
58
+ };
59
+ const signedKeyPair = (identityKeyPair, keyId) => {
60
+ const preKey = exports.Curve.generateKeyPair();
61
+ const pubKey = (0, exports.generateSignalPubKey)(preKey.public);
62
+ const signature = exports.Curve.sign(identityKeyPair.private, pubKey);
63
+ return { keyPair: preKey, signature, keyId };
64
+ };
65
+ exports.signedKeyPair = signedKeyPair;
66
+ const GCM_TAG_LENGTH = 128 >> 3;
67
+ /**
68
+ * encrypt AES 256 GCM;
69
+ * where the tag tag is suffixed to the ciphertext
70
+ * */
71
+ function aesEncryptGCM(plaintext, key, iv, additionalData) {
72
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
73
+ cipher.setAAD(additionalData);
74
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
75
+ }
76
+ exports.aesEncryptGCM = aesEncryptGCM;
77
+ /**
78
+ * decrypt AES 256 GCM;
79
+ * where the auth tag is suffixed to the ciphertext
80
+ * */
81
+ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
82
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
83
+ // decrypt additional adata
84
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
85
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
86
+ // set additional data
87
+ decipher.setAAD(additionalData);
88
+ decipher.setAuthTag(tag);
89
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
90
+ }
91
+ exports.aesDecryptGCM = aesDecryptGCM;
92
+ function aesEncryptCTR(plaintext, key, iv) {
93
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
94
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
95
+ }
96
+ exports.aesEncryptCTR = aesEncryptCTR;
97
+ function aesDecryptCTR(ciphertext, key, iv) {
98
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
99
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
100
+ }
101
+ exports.aesDecryptCTR = aesDecryptCTR;
102
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
103
+ function aesDecrypt(buffer, key) {
104
+ return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
105
+ }
106
+ exports.aesDecrypt = aesDecrypt;
107
+ /** decrypt AES 256 CBC */
108
+ function aesDecryptWithIV(buffer, key, IV) {
109
+ const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
110
+ return Buffer.concat([aes.update(buffer), aes.final()]);
111
+ }
112
+ exports.aesDecryptWithIV = aesDecryptWithIV;
113
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
114
+ function aesEncrypt(buffer, key) {
115
+ const IV = (0, crypto_1.randomBytes)(16);
116
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
117
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
118
+ }
119
+ exports.aesEncrypt = aesEncrypt;
120
+ // encrypt AES 256 CBC with a given IV
121
+ function aesEncrypWithIV(buffer, key, IV) {
122
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
123
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
124
+ }
125
+ exports.aesEncrypWithIV = aesEncrypWithIV;
126
+ // sign HMAC using SHA 256
127
+ function hmacSign(buffer, key, variant = 'sha256') {
128
+ return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
129
+ }
130
+ exports.hmacSign = hmacSign;
131
+ function sha256(buffer) {
132
+ return (0, crypto_1.createHash)('sha256').update(buffer).digest();
133
+ }
134
+ exports.sha256 = sha256;
135
+ function md5(buffer) {
136
+ return (0, crypto_1.createHash)('md5').update(buffer).digest();
137
+ }
138
+ exports.md5 = md5;
139
+ // HKDF key expansion
140
+ async function hkdf(buffer, expandedLength, info) {
141
+ // Ensure we have a Uint8Array for the key material
142
+ const inputKeyMaterial = buffer instanceof Uint8Array
143
+ ? buffer
144
+ : new Uint8Array(buffer);
145
+ // Set default values if not provided
146
+ const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
147
+ const infoBytes = info.info
148
+ ? new TextEncoder().encode(info.info)
149
+ : new Uint8Array(0);
150
+ // Import the input key material
151
+ const importedKey = await crypto.subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits']);
152
+ // Derive bits using HKDF
153
+ const derivedBits = await crypto.subtle.deriveBits({
154
+ name: 'HKDF',
155
+ hash: 'SHA-256',
156
+ salt: salt,
157
+ info: infoBytes
158
+ }, importedKey, expandedLength * 8 // Convert bytes to bits
159
+ );
160
+ return Buffer.from(derivedBits);
161
+ }
162
+ exports.hkdf = hkdf;
163
+ async function derivePairingCodeKey(pairingCode, salt) {
164
+ // Convert inputs to formats Web Crypto API can work with
165
+ const encoder = new TextEncoder();
166
+ const pairingCodeBuffer = encoder.encode(pairingCode);
167
+ const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
168
+ // Import the pairing code as key material
169
+ const keyMaterial = await crypto.subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits']);
170
+ // Derive bits using PBKDF2 with the same parameters
171
+ // 2 << 16 = 131,072 iterations
172
+ const derivedBits = await crypto.subtle.deriveBits({
173
+ name: 'PBKDF2',
174
+ salt: saltBuffer,
175
+ iterations: 2 << 16,
176
+ hash: 'SHA-256'
177
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
178
+ );
179
+ return Buffer.from(derivedBits);
180
+ }
181
+ exports.derivePairingCodeKey = derivePairingCodeKey;
@@ -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,205 @@
1
+ "use strict";
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;
4
+ const boom_1 = require("@hapi/boom");
5
+ const WAProto_1 = require("../../WAProto");
6
+ const WABinary_1 = require("../WABinary");
7
+ const generics_1 = require("./generics");
8
+ exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
9
+ exports.MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
10
+ exports.NACK_REASONS = {
11
+ ParsingError: 487,
12
+ UnrecognizedStanza: 488,
13
+ UnrecognizedStanzaClass: 489,
14
+ UnrecognizedStanzaType: 490,
15
+ InvalidProtobuf: 491,
16
+ InvalidHostedCompanionStanza: 493,
17
+ MissingMessageSecret: 495,
18
+ SignalErrorOldCounter: 496,
19
+ MessageDeletedOnPeer: 499,
20
+ UnhandledError: 500,
21
+ UnsupportedAdminRevoke: 550,
22
+ UnsupportedLIDGroup: 551,
23
+ DBOperationFailed: 552
24
+ };
25
+ /**
26
+ * Decode the received node as a message.
27
+ * @note this will only parse the message, not decrypt it
28
+ */
29
+ function decodeMessageNode(stanza, meId, meLid) {
30
+ var _a;
31
+ let msgType;
32
+ let chatId;
33
+ let author;
34
+ const msgId = stanza.attrs.id;
35
+ const from = stanza.attrs.from;
36
+ const participant = stanza.attrs.participant;
37
+ const recipient = stanza.attrs.recipient;
38
+ const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
39
+ 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)) {
56
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
57
+ }
58
+ chatId = recipient;
59
+ }
60
+ else {
61
+ chatId = from;
62
+ }
63
+ msgType = 'chat';
64
+ author = from;
65
+ }
66
+ else if ((0, WABinary_1.isJidGroup)(from)) {
67
+ if (!participant) {
68
+ throw new boom_1.Boom('No participant in group message');
69
+ }
70
+ msgType = 'group';
71
+ author = participant;
72
+ chatId = from;
73
+ }
74
+ else if ((0, WABinary_1.isJidBroadcast)(from)) {
75
+ if (!participant) {
76
+ throw new boom_1.Boom('No participant in group message');
77
+ }
78
+ const isParticipantMe = isMe(participant);
79
+ if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
80
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
81
+ }
82
+ else {
83
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
84
+ }
85
+ chatId = from;
86
+ author = participant;
87
+ }
88
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
89
+ msgType = 'newsletter';
90
+ chatId = from;
91
+ author = from;
92
+ }
93
+ else {
94
+ throw new boom_1.Boom('Unknown message type', { data: stanza });
95
+ }
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;
98
+ const key = {
99
+ remoteJid: chatId,
100
+ fromMe,
101
+ id: msgId,
102
+ participant
103
+ };
104
+ const fullMessage = {
105
+ key,
106
+ messageTimestamp: +stanza.attrs.t,
107
+ pushName: pushname,
108
+ broadcast: (0, WABinary_1.isJidBroadcast)(from)
109
+ };
110
+ if (key.fromMe) {
111
+ fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
112
+ }
113
+ return {
114
+ fullMessage,
115
+ author,
116
+ sender: msgType === 'chat' ? author : chatId
117
+ };
118
+ }
119
+ exports.decodeMessageNode = decodeMessageNode;
120
+ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
121
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
122
+ return {
123
+ fullMessage,
124
+ category: stanza.attrs.category,
125
+ author,
126
+ async decrypt() {
127
+ var _a;
128
+ let decryptables = 0;
129
+ if (Array.isArray(stanza.content)) {
130
+ for (const { tag, attrs, content } of stanza.content) {
131
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
132
+ const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
133
+ const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
134
+ fullMessage.verifiedBizName = details.verifiedName;
135
+ }
136
+ if (tag !== 'enc' && tag !== 'plaintext') {
137
+ continue;
138
+ }
139
+ if (!(content instanceof Uint8Array)) {
140
+ continue;
141
+ }
142
+ decryptables += 1;
143
+ let msgBuffer;
144
+ try {
145
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
146
+ switch (e2eType) {
147
+ case 'skmsg':
148
+ msgBuffer = await repository.decryptGroupMessage({
149
+ group: sender,
150
+ authorJid: author,
151
+ msg: content
152
+ });
153
+ break;
154
+ case 'pkmsg':
155
+ case 'msg':
156
+ const user = (0, WABinary_1.isJidUser)(sender) ? sender : author;
157
+ msgBuffer = await repository.decryptMessage({
158
+ jid: user,
159
+ type: e2eType,
160
+ ciphertext: content
161
+ });
162
+ break;
163
+ case 'plaintext':
164
+ msgBuffer = content;
165
+ break;
166
+ default:
167
+ throw new Error(`Unknown e2e type: ${e2eType}`);
168
+ }
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;
171
+ if (msg.senderKeyDistributionMessage) {
172
+ //eslint-disable-next-line max-depth
173
+ try {
174
+ await repository.processSenderKeyDistributionMessage({
175
+ authorJid: author,
176
+ item: msg.senderKeyDistributionMessage
177
+ });
178
+ }
179
+ catch (err) {
180
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
181
+ }
182
+ }
183
+ if (fullMessage.message) {
184
+ Object.assign(fullMessage.message, msg);
185
+ }
186
+ else {
187
+ fullMessage.message = msg;
188
+ }
189
+ }
190
+ catch (err) {
191
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
192
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
193
+ fullMessage.messageStubParameters = [err.message];
194
+ }
195
+ }
196
+ }
197
+ // if nothing was found to decrypt
198
+ if (!decryptables) {
199
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
200
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
201
+ }
202
+ }
203
+ };
204
+ };
205
+ 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 {};