supunmd-bail 2.0.1

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 (196) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +5519 -0
  4. package/WAProto/fix-imports.js +29 -0
  5. package/WAProto/index.d.ts +11969 -0
  6. package/WAProto/index.js +84368 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/baileys-version.json +3 -0
  9. package/lib/Defaults/index.d.ts +62 -0
  10. package/lib/Defaults/index.js +115 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/ciphertext-message.js +12 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  14. package/lib/Signal/Group/group-session-builder.js +30 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  16. package/lib/Signal/Group/group_cipher.js +82 -0
  17. package/lib/Signal/Group/index.d.ts +12 -0
  18. package/lib/Signal/Group/index.js +12 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  20. package/lib/Signal/Group/keyhelper.js +18 -0
  21. package/lib/Signal/Group/queue-job.d.ts +2 -0
  22. package/lib/Signal/Group/queue-job.js +54 -0
  23. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  24. package/lib/Signal/Group/sender-chain-key.js +26 -0
  25. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  27. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  28. package/lib/Signal/Group/sender-key-message.js +66 -0
  29. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  30. package/lib/Signal/Group/sender-key-name.js +48 -0
  31. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  32. package/lib/Signal/Group/sender-key-record.js +41 -0
  33. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  34. package/lib/Signal/Group/sender-key-state.js +84 -0
  35. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  36. package/lib/Signal/Group/sender-message-key.js +26 -0
  37. package/lib/Signal/libsignal.d.ts +5 -0
  38. package/lib/Signal/libsignal.js +342 -0
  39. package/lib/Signal/lid-mapping.d.ts +23 -0
  40. package/lib/Signal/lid-mapping.js +171 -0
  41. package/lib/Socket/Client/index.d.ts +3 -0
  42. package/lib/Socket/Client/index.js +3 -0
  43. package/lib/Socket/Client/types.d.ts +16 -0
  44. package/lib/Socket/Client/types.js +11 -0
  45. package/lib/Socket/Client/websocket.d.ts +13 -0
  46. package/lib/Socket/Client/websocket.js +50 -0
  47. package/lib/Socket/business.d.ts +188 -0
  48. package/lib/Socket/business.js +376 -0
  49. package/lib/Socket/chats.d.ts +98 -0
  50. package/lib/Socket/chats.js +962 -0
  51. package/lib/Socket/communities.d.ts +244 -0
  52. package/lib/Socket/communities.js +431 -0
  53. package/lib/Socket/groups.d.ts +137 -0
  54. package/lib/Socket/groups.js +327 -0
  55. package/lib/Socket/index.d.ts +231 -0
  56. package/lib/Socket/index.js +18 -0
  57. package/lib/Socket/messages-recv.d.ts +173 -0
  58. package/lib/Socket/messages-recv.js +1228 -0
  59. package/lib/Socket/messages-send.d.ts +169 -0
  60. package/lib/Socket/messages-send.js +1070 -0
  61. package/lib/Socket/mex.d.ts +3 -0
  62. package/lib/Socket/mex.js +42 -0
  63. package/lib/Socket/newsletter.d.ts +147 -0
  64. package/lib/Socket/newsletter.js +181 -0
  65. package/lib/Socket/socket.d.ts +51 -0
  66. package/lib/Socket/socket.js +883 -0
  67. package/lib/Socket/usync.d.ts +37 -0
  68. package/lib/Socket/usync.js +63 -0
  69. package/lib/Types/Auth.d.ts +111 -0
  70. package/lib/Types/Auth.js +2 -0
  71. package/lib/Types/Bussines.d.ts +25 -0
  72. package/lib/Types/Bussines.js +2 -0
  73. package/lib/Types/Call.d.ts +14 -0
  74. package/lib/Types/Call.js +2 -0
  75. package/lib/Types/Chat.d.ts +123 -0
  76. package/lib/Types/Chat.js +8 -0
  77. package/lib/Types/Contact.d.ts +24 -0
  78. package/lib/Types/Contact.js +2 -0
  79. package/lib/Types/Events.d.ts +202 -0
  80. package/lib/Types/Events.js +2 -0
  81. package/lib/Types/GroupMetadata.d.ts +67 -0
  82. package/lib/Types/GroupMetadata.js +2 -0
  83. package/lib/Types/Label.d.ts +47 -0
  84. package/lib/Types/Label.js +25 -0
  85. package/lib/Types/LabelAssociation.d.ts +30 -0
  86. package/lib/Types/LabelAssociation.js +7 -0
  87. package/lib/Types/Message.d.ts +303 -0
  88. package/lib/Types/Message.js +11 -0
  89. package/lib/Types/Newsletter.d.ts +135 -0
  90. package/lib/Types/Newsletter.js +31 -0
  91. package/lib/Types/Product.d.ts +79 -0
  92. package/lib/Types/Product.js +2 -0
  93. package/lib/Types/Signal.d.ts +76 -0
  94. package/lib/Types/Signal.js +2 -0
  95. package/lib/Types/Socket.d.ts +133 -0
  96. package/lib/Types/Socket.js +3 -0
  97. package/lib/Types/State.d.ts +39 -0
  98. package/lib/Types/State.js +13 -0
  99. package/lib/Types/USync.d.ts +26 -0
  100. package/lib/Types/USync.js +2 -0
  101. package/lib/Types/index.d.ts +65 -0
  102. package/lib/Types/index.js +26 -0
  103. package/lib/Utils/auth-utils.d.ts +19 -0
  104. package/lib/Utils/auth-utils.js +257 -0
  105. package/lib/Utils/baileys-event-stream.d.ts +17 -0
  106. package/lib/Utils/baileys-event-stream.js +56 -0
  107. package/lib/Utils/browser-utils.d.ts +4 -0
  108. package/lib/Utils/browser-utils.js +28 -0
  109. package/lib/Utils/business.d.ts +23 -0
  110. package/lib/Utils/business.js +231 -0
  111. package/lib/Utils/chat-utils.d.ts +70 -0
  112. package/lib/Utils/chat-utils.js +763 -0
  113. package/lib/Utils/crypto.d.ts +41 -0
  114. package/lib/Utils/crypto.js +142 -0
  115. package/lib/Utils/decode-wa-message.d.ts +48 -0
  116. package/lib/Utils/decode-wa-message.js +279 -0
  117. package/lib/Utils/event-buffer.d.ts +34 -0
  118. package/lib/Utils/event-buffer.js +548 -0
  119. package/lib/Utils/generics.d.ts +90 -0
  120. package/lib/Utils/generics.js +381 -0
  121. package/lib/Utils/history.d.ts +19 -0
  122. package/lib/Utils/history.js +84 -0
  123. package/lib/Utils/index.d.ts +20 -0
  124. package/lib/Utils/index.js +20 -0
  125. package/lib/Utils/link-preview.d.ts +21 -0
  126. package/lib/Utils/link-preview.js +85 -0
  127. package/lib/Utils/logger.d.ts +12 -0
  128. package/lib/Utils/logger.js +3 -0
  129. package/lib/Utils/lt-hash.d.ts +13 -0
  130. package/lib/Utils/lt-hash.js +48 -0
  131. package/lib/Utils/make-mutex.d.ts +8 -0
  132. package/lib/Utils/make-mutex.js +40 -0
  133. package/lib/Utils/message-retry-manager.d.ts +82 -0
  134. package/lib/Utils/message-retry-manager.js +149 -0
  135. package/lib/Utils/messages-media.d.ts +114 -0
  136. package/lib/Utils/messages-media.js +663 -0
  137. package/lib/Utils/messages.d.ts +76 -0
  138. package/lib/Utils/messages.js +908 -0
  139. package/lib/Utils/noise-handler.d.ts +20 -0
  140. package/lib/Utils/noise-handler.js +147 -0
  141. package/lib/Utils/pre-key-manager.d.ts +28 -0
  142. package/lib/Utils/pre-key-manager.js +106 -0
  143. package/lib/Utils/process-message.d.ts +42 -0
  144. package/lib/Utils/process-message.js +413 -0
  145. package/lib/Utils/signal.d.ts +34 -0
  146. package/lib/Utils/signal.js +159 -0
  147. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  148. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  149. package/lib/Utils/validate-connection.d.ts +11 -0
  150. package/lib/Utils/validate-connection.js +195 -0
  151. package/lib/WABinary/constants.d.ts +28 -0
  152. package/lib/WABinary/constants.js +1301 -0
  153. package/lib/WABinary/decode.d.ts +7 -0
  154. package/lib/WABinary/decode.js +238 -0
  155. package/lib/WABinary/encode.d.ts +3 -0
  156. package/lib/WABinary/encode.js +216 -0
  157. package/lib/WABinary/generic-utils.d.ts +15 -0
  158. package/lib/WABinary/generic-utils.js +191 -0
  159. package/lib/WABinary/index.d.ts +6 -0
  160. package/lib/WABinary/index.js +6 -0
  161. package/lib/WABinary/jid-utils.d.ts +48 -0
  162. package/lib/WABinary/jid-utils.js +96 -0
  163. package/lib/WABinary/types.d.ts +19 -0
  164. package/lib/WABinary/types.js +2 -0
  165. package/lib/WAM/BinaryInfo.d.ts +9 -0
  166. package/lib/WAM/BinaryInfo.js +10 -0
  167. package/lib/WAM/constants.d.ts +40 -0
  168. package/lib/WAM/constants.js +22853 -0
  169. package/lib/WAM/encode.d.ts +3 -0
  170. package/lib/WAM/encode.js +150 -0
  171. package/lib/WAM/index.d.ts +4 -0
  172. package/lib/WAM/index.js +4 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  174. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  175. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  176. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  177. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  178. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  179. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  180. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  181. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  182. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  183. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  184. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  185. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  186. package/lib/WAUSync/Protocols/index.js +5 -0
  187. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  188. package/lib/WAUSync/USyncQuery.js +94 -0
  189. package/lib/WAUSync/USyncUser.d.ts +13 -0
  190. package/lib/WAUSync/USyncUser.js +23 -0
  191. package/lib/WAUSync/index.d.ts +4 -0
  192. package/lib/WAUSync/index.js +4 -0
  193. package/lib/index.d.ts +22 -0
  194. package/lib/index.js +36 -0
  195. package/lib/supun +1 -0
  196. package/package.json +104 -0
@@ -0,0 +1,41 @@
1
+ import type { KeyPair } from '../Types/index.js';
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<ArrayBuffer>;
7
+ sign: (privateKey: Uint8Array, buf: Uint8Array) => Uint8Array<ArrayBufferLike>;
8
+ verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean;
9
+ };
10
+ export declare const signedKeyPair: (identityKeyPair: KeyPair, keyId: number) => {
11
+ keyPair: KeyPair;
12
+ signature: Uint8Array<ArrayBufferLike>;
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>;
41
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1,142 @@
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from 'crypto';
2
+ import * as curve from 'libsignal/src/curve.js';
3
+ import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
4
+ // insure browser & node compatibility
5
+ const { subtle } = globalThis.crypto;
6
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
7
+ export const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]);
8
+ export const Curve = {
9
+ generateKeyPair: () => {
10
+ const { pubKey, privKey } = curve.generateKeyPair();
11
+ return {
12
+ private: Buffer.from(privKey),
13
+ // remove version byte
14
+ public: Buffer.from(pubKey.slice(1))
15
+ };
16
+ },
17
+ sharedKey: (privateKey, publicKey) => {
18
+ const shared = curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey);
19
+ return Buffer.from(shared);
20
+ },
21
+ sign: (privateKey, buf) => curve.calculateSignature(privateKey, buf),
22
+ verify: (pubKey, message, signature) => {
23
+ try {
24
+ curve.verifySignature(generateSignalPubKey(pubKey), message, signature);
25
+ return true;
26
+ }
27
+ catch (error) {
28
+ return false;
29
+ }
30
+ }
31
+ };
32
+ export const signedKeyPair = (identityKeyPair, keyId) => {
33
+ const preKey = Curve.generateKeyPair();
34
+ const pubKey = generateSignalPubKey(preKey.public);
35
+ const signature = Curve.sign(identityKeyPair.private, pubKey);
36
+ return { keyPair: preKey, signature, keyId };
37
+ };
38
+ const GCM_TAG_LENGTH = 128 >> 3;
39
+ /**
40
+ * encrypt AES 256 GCM;
41
+ * where the tag tag is suffixed to the ciphertext
42
+ * */
43
+ export function aesEncryptGCM(plaintext, key, iv, additionalData) {
44
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
45
+ cipher.setAAD(additionalData);
46
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
47
+ }
48
+ /**
49
+ * decrypt AES 256 GCM;
50
+ * where the auth tag is suffixed to the ciphertext
51
+ * */
52
+ export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
53
+ const decipher = createDecipheriv('aes-256-gcm', key, iv);
54
+ // decrypt additional adata
55
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
56
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
57
+ // set additional data
58
+ decipher.setAAD(additionalData);
59
+ decipher.setAuthTag(tag);
60
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
61
+ }
62
+ export function aesEncryptCTR(plaintext, key, iv) {
63
+ const cipher = createCipheriv('aes-256-ctr', key, iv);
64
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
65
+ }
66
+ export function aesDecryptCTR(ciphertext, key, iv) {
67
+ const decipher = createDecipheriv('aes-256-ctr', key, iv);
68
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
69
+ }
70
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
71
+ export function aesDecrypt(buffer, key) {
72
+ return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
73
+ }
74
+ /** decrypt AES 256 CBC */
75
+ export function aesDecryptWithIV(buffer, key, IV) {
76
+ const aes = createDecipheriv('aes-256-cbc', key, IV);
77
+ return Buffer.concat([aes.update(buffer), aes.final()]);
78
+ }
79
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
80
+ export function aesEncrypt(buffer, key) {
81
+ const IV = randomBytes(16);
82
+ const aes = createCipheriv('aes-256-cbc', key, IV);
83
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
84
+ }
85
+ // encrypt AES 256 CBC with a given IV
86
+ export function aesEncrypWithIV(buffer, key, IV) {
87
+ const aes = createCipheriv('aes-256-cbc', key, IV);
88
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
89
+ }
90
+ // sign HMAC using SHA 256
91
+ export function hmacSign(buffer, key, variant = 'sha256') {
92
+ return createHmac(variant, key).update(buffer).digest();
93
+ }
94
+ export function sha256(buffer) {
95
+ return createHash('sha256').update(buffer).digest();
96
+ }
97
+ export function md5(buffer) {
98
+ return createHash('md5').update(buffer).digest();
99
+ }
100
+ // HKDF key expansion
101
+ export async function hkdf(buffer, expandedLength, info) {
102
+ // Normalize to a Uint8Array whose underlying buffer is a regular ArrayBuffer (not ArrayBufferLike)
103
+ // Cloning via new Uint8Array(...) guarantees the generic parameter is ArrayBuffer which satisfies WebCrypto types.
104
+ const inputKeyMaterial = new Uint8Array(buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer));
105
+ // Set default values if not provided
106
+ const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
107
+ const infoBytes = info.info ? new TextEncoder().encode(info.info) : new Uint8Array(0);
108
+ // Import the input key material (cast to BufferSource to appease TS DOM typings)
109
+ const importedKey = await subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, [
110
+ 'deriveBits'
111
+ ]);
112
+ // Derive bits using HKDF
113
+ const derivedBits = await subtle.deriveBits({
114
+ name: 'HKDF',
115
+ hash: 'SHA-256',
116
+ salt: salt,
117
+ info: infoBytes
118
+ }, importedKey, expandedLength * 8 // Convert bytes to bits
119
+ );
120
+ return Buffer.from(derivedBits);
121
+ }
122
+ export async function derivePairingCodeKey(pairingCode, salt) {
123
+ // Convert inputs to formats Web Crypto API can work with
124
+ const encoder = new TextEncoder();
125
+ const pairingCodeBuffer = encoder.encode(pairingCode);
126
+ const saltBuffer = new Uint8Array(salt instanceof Uint8Array ? salt : new Uint8Array(salt));
127
+ // Import the pairing code as key material
128
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, [
129
+ 'deriveBits'
130
+ ]);
131
+ // Derive bits using PBKDF2 with the same parameters
132
+ // 2 << 16 = 131,072 iterations
133
+ const derivedBits = await subtle.deriveBits({
134
+ name: 'PBKDF2',
135
+ salt: saltBuffer,
136
+ iterations: 2 << 16,
137
+ hash: 'SHA-256'
138
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
139
+ );
140
+ return Buffer.from(derivedBits);
141
+ }
142
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1,48 @@
1
+ import type { WAMessage } from '../Types/index.js';
2
+ import type { SignalRepositoryWithLIDStore } from '../Types/Signal.js';
3
+ import { type BinaryNode } from '../WABinary/index.js';
4
+ import type { ILogger } from './logger.js';
5
+ export declare const getDecryptionJid: (sender: string, repository: SignalRepositoryWithLIDStore) => Promise<string>;
6
+ export declare const NO_MESSAGE_FOUND_ERROR_TEXT = "Message absent from node";
7
+ export declare const MISSING_KEYS_ERROR_TEXT = "Key used already or never filled";
8
+ export declare const DECRYPTION_RETRY_CONFIG: {
9
+ maxRetries: number;
10
+ baseDelayMs: number;
11
+ sessionRecordErrors: string[];
12
+ };
13
+ export declare const NACK_REASONS: {
14
+ ParsingError: number;
15
+ UnrecognizedStanza: number;
16
+ UnrecognizedStanzaClass: number;
17
+ UnrecognizedStanzaType: number;
18
+ InvalidProtobuf: number;
19
+ InvalidHostedCompanionStanza: number;
20
+ MissingMessageSecret: number;
21
+ SignalErrorOldCounter: number;
22
+ MessageDeletedOnPeer: number;
23
+ UnhandledError: number;
24
+ UnsupportedAdminRevoke: number;
25
+ UnsupportedLIDGroup: number;
26
+ DBOperationFailed: number;
27
+ };
28
+ export declare const extractAddressingContext: (stanza: BinaryNode) => {
29
+ addressingMode: string;
30
+ senderAlt: string | undefined;
31
+ recipientAlt: string | undefined;
32
+ };
33
+ /**
34
+ * Decode the received node as a message.
35
+ * @note this will only parse the message, not decrypt it
36
+ */
37
+ export declare function decodeMessageNode(stanza: BinaryNode, meId: string, meLid: string): {
38
+ fullMessage: WAMessage;
39
+ author: string;
40
+ sender: string;
41
+ };
42
+ export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepositoryWithLIDStore, logger: ILogger) => {
43
+ fullMessage: WAMessage;
44
+ category: string | undefined;
45
+ author: string;
46
+ decrypt(): Promise<void>;
47
+ };
48
+ //# sourceMappingURL=decode-wa-message.d.ts.map
@@ -0,0 +1,279 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidGroup, isJidMetaAI, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser
4
+ // transferDevice
5
+ } from '../WABinary/index.js';
6
+ import { unpadRandomMax16 } from './generics.js';
7
+ export const getDecryptionJid = async (sender, repository) => {
8
+ if (isLidUser(sender) || isHostedLidUser(sender)) {
9
+ return sender;
10
+ }
11
+ const mapped = await repository.lidMapping.getLIDForPN(sender);
12
+ return mapped || sender;
13
+ };
14
+ const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger) => {
15
+ // TODO: Handle hosted IDs
16
+ const { senderAlt } = extractAddressingContext(stanza);
17
+ if (senderAlt && isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
18
+ try {
19
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }]);
20
+ await repository.migrateSession(sender, senderAlt);
21
+ logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope');
22
+ }
23
+ catch (error) {
24
+ logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping');
25
+ }
26
+ }
27
+ };
28
+ export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
29
+ export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
30
+ // Retry configuration for failed decryption
31
+ export const DECRYPTION_RETRY_CONFIG = {
32
+ maxRetries: 3,
33
+ baseDelayMs: 100,
34
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
35
+ };
36
+ export const NACK_REASONS = {
37
+ ParsingError: 487,
38
+ UnrecognizedStanza: 488,
39
+ UnrecognizedStanzaClass: 489,
40
+ UnrecognizedStanzaType: 490,
41
+ InvalidProtobuf: 491,
42
+ InvalidHostedCompanionStanza: 493,
43
+ MissingMessageSecret: 495,
44
+ SignalErrorOldCounter: 496,
45
+ MessageDeletedOnPeer: 499,
46
+ UnhandledError: 500,
47
+ UnsupportedAdminRevoke: 550,
48
+ UnsupportedLIDGroup: 551,
49
+ DBOperationFailed: 552
50
+ };
51
+ export const extractAddressingContext = (stanza) => {
52
+ let senderAlt;
53
+ let recipientAlt;
54
+ const sender = stanza.attrs.participant || stanza.attrs.from;
55
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn');
56
+ if (addressingMode === 'lid') {
57
+ // Message is LID-addressed: sender is LID, extract corresponding PN
58
+ // without device data
59
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
60
+ recipientAlt = stanza.attrs.recipient_pn;
61
+ // with device data
62
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
63
+ }
64
+ else {
65
+ // Message is PN-addressed: sender is PN, extract corresponding LID
66
+ // without device data
67
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
68
+ recipientAlt = stanza.attrs.recipient_lid;
69
+ //with device data
70
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
71
+ }
72
+ return {
73
+ addressingMode,
74
+ senderAlt,
75
+ recipientAlt
76
+ };
77
+ };
78
+ /**
79
+ * Decode the received node as a message.
80
+ * @note this will only parse the message, not decrypt it
81
+ */
82
+ export function decodeMessageNode(stanza, meId, meLid) {
83
+ let msgType;
84
+ let chatId;
85
+ let author;
86
+ let fromMe = false;
87
+ const msgId = stanza.attrs.id;
88
+ const from = stanza.attrs.from;
89
+ const participant = stanza.attrs.participant;
90
+ const recipient = stanza.attrs.recipient;
91
+ const addressingContext = extractAddressingContext(stanza);
92
+ const isMe = (jid) => areJidsSameUser(jid, meId);
93
+ const isMeLid = (jid) => areJidsSameUser(jid, meLid);
94
+ if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
95
+ if (recipient && !isJidMetaAI(recipient)) {
96
+ if (!isMe(from) && !isMeLid(from)) {
97
+ throw new Boom('receipient present, but msg not from me', { data: stanza });
98
+ }
99
+ if (isMe(from) || isMeLid(from)) {
100
+ fromMe = true;
101
+ }
102
+ chatId = recipient;
103
+ }
104
+ else {
105
+ chatId = from;
106
+ }
107
+ msgType = 'chat';
108
+ author = from;
109
+ }
110
+ else if (isJidGroup(from)) {
111
+ if (!participant) {
112
+ throw new Boom('No participant in group message');
113
+ }
114
+ if (isMe(participant) || isMeLid(participant)) {
115
+ fromMe = true;
116
+ }
117
+ msgType = 'group';
118
+ author = participant;
119
+ chatId = from;
120
+ }
121
+ else if (isJidBroadcast(from)) {
122
+ if (!participant) {
123
+ throw new Boom('No participant in group message');
124
+ }
125
+ const isParticipantMe = isMe(participant);
126
+ if (isJidStatusBroadcast(from)) {
127
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
128
+ }
129
+ else {
130
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
131
+ }
132
+ fromMe = isParticipantMe;
133
+ chatId = from;
134
+ author = participant;
135
+ }
136
+ else if (isJidNewsletter(from)) {
137
+ msgType = 'newsletter';
138
+ chatId = from;
139
+ author = from;
140
+ if (isMe(from) || isMeLid(from)) {
141
+ fromMe = true;
142
+ }
143
+ }
144
+ else {
145
+ throw new Boom('Unknown message type', { data: stanza });
146
+ }
147
+ const pushname = stanza?.attrs?.notify;
148
+ const key = {
149
+ remoteJid: chatId,
150
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
151
+ fromMe,
152
+ id: msgId,
153
+ participant,
154
+ participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
155
+ addressingMode: addressingContext.addressingMode,
156
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
157
+ };
158
+ const fullMessage = {
159
+ key,
160
+ messageTimestamp: +stanza.attrs.t,
161
+ pushName: pushname,
162
+ broadcast: isJidBroadcast(from)
163
+ };
164
+ if (key.fromMe) {
165
+ fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
166
+ }
167
+ return {
168
+ fullMessage,
169
+ author,
170
+ sender: msgType === 'chat' ? author : chatId
171
+ };
172
+ }
173
+ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
174
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
175
+ return {
176
+ fullMessage,
177
+ category: stanza.attrs.category,
178
+ author,
179
+ async decrypt() {
180
+ let decryptables = 0;
181
+ if (Array.isArray(stanza.content)) {
182
+ for (const { tag, attrs, content } of stanza.content) {
183
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
184
+ const cert = proto.VerifiedNameCertificate.decode(content);
185
+ const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
186
+ fullMessage.verifiedBizName = details.verifiedName;
187
+ }
188
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
189
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
190
+ }
191
+ if (tag !== 'enc' && tag !== 'plaintext') {
192
+ continue;
193
+ }
194
+ if (!(content instanceof Uint8Array)) {
195
+ continue;
196
+ }
197
+ decryptables += 1;
198
+ let msgBuffer;
199
+ const decryptionJid = await getDecryptionJid(author, repository);
200
+ if (tag !== 'plaintext') {
201
+ // TODO: Handle hosted devices
202
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
203
+ }
204
+ try {
205
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
206
+ switch (e2eType) {
207
+ case 'skmsg':
208
+ msgBuffer = await repository.decryptGroupMessage({
209
+ group: sender,
210
+ authorJid: author,
211
+ msg: content
212
+ });
213
+ break;
214
+ case 'pkmsg':
215
+ case 'msg':
216
+ msgBuffer = await repository.decryptMessage({
217
+ jid: decryptionJid,
218
+ type: e2eType,
219
+ ciphertext: content
220
+ });
221
+ break;
222
+ case 'plaintext':
223
+ msgBuffer = content;
224
+ break;
225
+ default:
226
+ throw new Error(`Unknown e2e type: ${e2eType}`);
227
+ }
228
+ let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer);
229
+ msg = msg.deviceSentMessage?.message || msg;
230
+ if (msg.senderKeyDistributionMessage) {
231
+ //eslint-disable-next-line max-depth
232
+ try {
233
+ await repository.processSenderKeyDistributionMessage({
234
+ authorJid: author,
235
+ item: msg.senderKeyDistributionMessage
236
+ });
237
+ }
238
+ catch (err) {
239
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
240
+ }
241
+ }
242
+ if (fullMessage.message) {
243
+ Object.assign(fullMessage.message, msg);
244
+ }
245
+ else {
246
+ fullMessage.message = msg;
247
+ }
248
+ }
249
+ catch (err) {
250
+ const errorContext = {
251
+ key: fullMessage.key,
252
+ err,
253
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
254
+ sender,
255
+ author,
256
+ isSessionRecordError: isSessionRecordError(err)
257
+ };
258
+ logger.error(errorContext, 'failed to decrypt message');
259
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
260
+ fullMessage.messageStubParameters = [err.message.toString()];
261
+ }
262
+ }
263
+ }
264
+ // if nothing was found to decrypt
265
+ if (!decryptables) {
266
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
267
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
268
+ }
269
+ }
270
+ };
271
+ };
272
+ /**
273
+ * Utility function to check if an error is related to missing session record
274
+ */
275
+ function isSessionRecordError(error) {
276
+ const errorMessage = error?.message || error?.toString() || '';
277
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
278
+ }
279
+ //# sourceMappingURL=decode-wa-message.js.map
@@ -0,0 +1,34 @@
1
+ import type { BaileysEventEmitter, BaileysEventMap } from '../Types/index.js';
2
+ import type { ILogger } from './logger.js';
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
+ * @returns returns true if the flush actually happened, otherwise false
23
+ */
24
+ flush(): boolean;
25
+ /** is there an ongoing buffer */
26
+ isBuffering(): boolean;
27
+ };
28
+ /**
29
+ * The event buffer logically consolidates different events into a single event
30
+ * making the data processing more efficient.
31
+ */
32
+ export declare const makeEventBuffer: (logger: ILogger) => BaileysBufferableEventEmitter;
33
+ export {};
34
+ //# sourceMappingURL=event-buffer.d.ts.map