queenruva-sockets 5.6.23

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 (205) hide show
  1. package/LICENSE +31 -0
  2. package/README.md +1082 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97691 -0
  8. package/engine-requirements.js +11 -0
  9. package/lib/Defaults/index.d.ts +75 -0
  10. package/lib/Defaults/index.js +129 -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/sender-chain-key.d.ts +14 -0
  22. package/lib/Signal/Group/sender-chain-key.js +26 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  24. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  25. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  26. package/lib/Signal/Group/sender-key-message.js +66 -0
  27. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  28. package/lib/Signal/Group/sender-key-name.js +48 -0
  29. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  30. package/lib/Signal/Group/sender-key-record.js +41 -0
  31. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  32. package/lib/Signal/Group/sender-key-state.js +84 -0
  33. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  34. package/lib/Signal/Group/sender-message-key.js +26 -0
  35. package/lib/Signal/libsignal.d.ts +5 -0
  36. package/lib/Signal/libsignal.js +431 -0
  37. package/lib/Signal/lid-mapping.d.ts +23 -0
  38. package/lib/Signal/lid-mapping.js +277 -0
  39. package/lib/Socket/Client/index.d.ts +3 -0
  40. package/lib/Socket/Client/index.js +3 -0
  41. package/lib/Socket/Client/types.d.ts +16 -0
  42. package/lib/Socket/Client/types.js +11 -0
  43. package/lib/Socket/Client/websocket.d.ts +13 -0
  44. package/lib/Socket/Client/websocket.js +54 -0
  45. package/lib/Socket/business.d.ts +217 -0
  46. package/lib/Socket/business.js +379 -0
  47. package/lib/Socket/chats.d.ts +124 -0
  48. package/lib/Socket/chats.js +1193 -0
  49. package/lib/Socket/communities.d.ts +273 -0
  50. package/lib/Socket/communities.js +431 -0
  51. package/lib/Socket/groups.d.ts +161 -0
  52. package/lib/Socket/groups.js +347 -0
  53. package/lib/Socket/index.d.ts +260 -0
  54. package/lib/Socket/index.js +12 -0
  55. package/lib/Socket/messages-recv.d.ts +203 -0
  56. package/lib/Socket/messages-recv.js +1772 -0
  57. package/lib/Socket/messages-send.d.ts +199 -0
  58. package/lib/Socket/messages-send.js +1160 -0
  59. package/lib/Socket/mex.d.ts +3 -0
  60. package/lib/Socket/mex.js +42 -0
  61. package/lib/Socket/newsletter.d.ts +170 -0
  62. package/lib/Socket/newsletter.js +181 -0
  63. package/lib/Socket/socket.d.ts +59 -0
  64. package/lib/Socket/socket.js +1029 -0
  65. package/lib/Types/Auth.d.ts +117 -0
  66. package/lib/Types/Auth.js +2 -0
  67. package/lib/Types/Bussines.d.ts +25 -0
  68. package/lib/Types/Bussines.js +2 -0
  69. package/lib/Types/Call.d.ts +15 -0
  70. package/lib/Types/Call.js +2 -0
  71. package/lib/Types/Chat.d.ts +124 -0
  72. package/lib/Types/Chat.js +8 -0
  73. package/lib/Types/Contact.d.ts +26 -0
  74. package/lib/Types/Contact.js +2 -0
  75. package/lib/Types/Events.d.ts +256 -0
  76. package/lib/Types/Events.js +2 -0
  77. package/lib/Types/GroupMetadata.d.ts +71 -0
  78. package/lib/Types/GroupMetadata.js +2 -0
  79. package/lib/Types/Label.d.ts +47 -0
  80. package/lib/Types/Label.js +25 -0
  81. package/lib/Types/LabelAssociation.d.ts +30 -0
  82. package/lib/Types/LabelAssociation.js +7 -0
  83. package/lib/Types/Message.d.ts +320 -0
  84. package/lib/Types/Message.js +11 -0
  85. package/lib/Types/Mex.d.ts +141 -0
  86. package/lib/Types/Mex.js +37 -0
  87. package/lib/Types/Product.d.ts +79 -0
  88. package/lib/Types/Product.js +2 -0
  89. package/lib/Types/Signal.d.ts +87 -0
  90. package/lib/Types/Signal.js +2 -0
  91. package/lib/Types/Socket.d.ts +136 -0
  92. package/lib/Types/Socket.js +3 -0
  93. package/lib/Types/State.d.ts +97 -0
  94. package/lib/Types/State.js +56 -0
  95. package/lib/Types/USync.d.ts +26 -0
  96. package/lib/Types/USync.js +2 -0
  97. package/lib/Types/index.d.ts +65 -0
  98. package/lib/Types/index.js +26 -0
  99. package/lib/Utils/auth-utils.d.ts +24 -0
  100. package/lib/Utils/auth-utils.js +302 -0
  101. package/lib/Utils/browser-utils.d.ts +4 -0
  102. package/lib/Utils/browser-utils.js +28 -0
  103. package/lib/Utils/business.d.ts +23 -0
  104. package/lib/Utils/business.js +231 -0
  105. package/lib/Utils/chat-utils.d.ts +100 -0
  106. package/lib/Utils/chat-utils.js +872 -0
  107. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  108. package/lib/Utils/companion-reg-client-utils.js +35 -0
  109. package/lib/Utils/crypto.d.ts +37 -0
  110. package/lib/Utils/crypto.js +118 -0
  111. package/lib/Utils/decode-wa-message.d.ts +66 -0
  112. package/lib/Utils/decode-wa-message.js +311 -0
  113. package/lib/Utils/event-buffer.d.ts +36 -0
  114. package/lib/Utils/event-buffer.js +622 -0
  115. package/lib/Utils/generics.d.ts +91 -0
  116. package/lib/Utils/generics.js +378 -0
  117. package/lib/Utils/history.d.ts +24 -0
  118. package/lib/Utils/history.js +134 -0
  119. package/lib/Utils/identity-change-handler.d.ts +44 -0
  120. package/lib/Utils/identity-change-handler.js +50 -0
  121. package/lib/Utils/index.d.ts +22 -0
  122. package/lib/Utils/index.js +22 -0
  123. package/lib/Utils/link-preview.d.ts +21 -0
  124. package/lib/Utils/link-preview.js +85 -0
  125. package/lib/Utils/logger.d.ts +12 -0
  126. package/lib/Utils/logger.js +3 -0
  127. package/lib/Utils/lt-hash.d.ts +8 -0
  128. package/lib/Utils/lt-hash.js +8 -0
  129. package/lib/Utils/make-mutex.d.ts +9 -0
  130. package/lib/Utils/make-mutex.js +33 -0
  131. package/lib/Utils/message-retry-manager.d.ts +115 -0
  132. package/lib/Utils/message-retry-manager.js +265 -0
  133. package/lib/Utils/messages-media.d.ts +133 -0
  134. package/lib/Utils/messages-media.js +786 -0
  135. package/lib/Utils/messages.d.ts +91 -0
  136. package/lib/Utils/messages.js +893 -0
  137. package/lib/Utils/noise-handler.d.ts +20 -0
  138. package/lib/Utils/noise-handler.js +201 -0
  139. package/lib/Utils/offline-node-processor.d.ts +17 -0
  140. package/lib/Utils/offline-node-processor.js +40 -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 +60 -0
  144. package/lib/Utils/process-message.js +597 -0
  145. package/lib/Utils/reporting-utils.d.ts +11 -0
  146. package/lib/Utils/reporting-utils.js +258 -0
  147. package/lib/Utils/signal.d.ts +47 -0
  148. package/lib/Utils/signal.js +201 -0
  149. package/lib/Utils/stanza-ack.d.ts +11 -0
  150. package/lib/Utils/stanza-ack.js +38 -0
  151. package/lib/Utils/sync-action-utils.d.ts +19 -0
  152. package/lib/Utils/sync-action-utils.js +49 -0
  153. package/lib/Utils/tc-token-utils.d.ts +37 -0
  154. package/lib/Utils/tc-token-utils.js +163 -0
  155. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  156. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  157. package/lib/Utils/validate-connection.d.ts +11 -0
  158. package/lib/Utils/validate-connection.js +203 -0
  159. package/lib/WABinary/constants.d.ts +28 -0
  160. package/lib/WABinary/constants.js +1301 -0
  161. package/lib/WABinary/decode.d.ts +7 -0
  162. package/lib/WABinary/decode.js +262 -0
  163. package/lib/WABinary/encode.d.ts +3 -0
  164. package/lib/WABinary/encode.js +220 -0
  165. package/lib/WABinary/generic-utils.d.ts +15 -0
  166. package/lib/WABinary/generic-utils.js +113 -0
  167. package/lib/WABinary/index.d.ts +6 -0
  168. package/lib/WABinary/index.js +6 -0
  169. package/lib/WABinary/jid-utils.d.ts +48 -0
  170. package/lib/WABinary/jid-utils.js +96 -0
  171. package/lib/WABinary/types.d.ts +19 -0
  172. package/lib/WABinary/types.js +2 -0
  173. package/lib/WAM/BinaryInfo.d.ts +9 -0
  174. package/lib/WAM/BinaryInfo.js +10 -0
  175. package/lib/WAM/constants.d.ts +40 -0
  176. package/lib/WAM/constants.js +22853 -0
  177. package/lib/WAM/encode.d.ts +3 -0
  178. package/lib/WAM/encode.js +150 -0
  179. package/lib/WAM/index.d.ts +4 -0
  180. package/lib/WAM/index.js +4 -0
  181. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  182. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  183. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  184. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  185. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  186. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  187. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  188. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  189. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  190. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  191. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  192. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  193. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  194. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  195. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  196. package/lib/WAUSync/Protocols/index.js +6 -0
  197. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  198. package/lib/WAUSync/USyncQuery.js +98 -0
  199. package/lib/WAUSync/USyncUser.d.ts +17 -0
  200. package/lib/WAUSync/USyncUser.js +31 -0
  201. package/lib/WAUSync/index.d.ts +4 -0
  202. package/lib/WAUSync/index.js +4 -0
  203. package/lib/index.d.ts +12 -0
  204. package/lib/index.js +11 -0
  205. package/package.json +160 -0
@@ -0,0 +1,17 @@
1
+ import type { WABrowserDescription } from '../Types/index.js';
2
+ export declare enum CompanionWebClientType {
3
+ UNKNOWN = 0,
4
+ CHROME = 1,
5
+ EDGE = 2,
6
+ FIREFOX = 3,
7
+ IE = 4,
8
+ OPERA = 5,
9
+ SAFARI = 6,
10
+ ELECTRON = 7,
11
+ UWP = 8,
12
+ OTHER_WEB_CLIENT = 9
13
+ }
14
+ export declare const getCompanionWebClientType: ([os, browserName]: WABrowserDescription) => CompanionWebClientType;
15
+ export declare const getCompanionPlatformId: (browser: WABrowserDescription) => string;
16
+ export declare const buildPairingQRData: (ref: string, noiseKeyB64: string, identityKeyB64: string, advB64: string, browser: WABrowserDescription) => string;
17
+ //# sourceMappingURL=companion-reg-client-utils.d.ts.map
@@ -0,0 +1,35 @@
1
+ export var CompanionWebClientType;
2
+ (function (CompanionWebClientType) {
3
+ CompanionWebClientType[CompanionWebClientType["UNKNOWN"] = 0] = "UNKNOWN";
4
+ CompanionWebClientType[CompanionWebClientType["CHROME"] = 1] = "CHROME";
5
+ CompanionWebClientType[CompanionWebClientType["EDGE"] = 2] = "EDGE";
6
+ CompanionWebClientType[CompanionWebClientType["FIREFOX"] = 3] = "FIREFOX";
7
+ CompanionWebClientType[CompanionWebClientType["IE"] = 4] = "IE";
8
+ CompanionWebClientType[CompanionWebClientType["OPERA"] = 5] = "OPERA";
9
+ CompanionWebClientType[CompanionWebClientType["SAFARI"] = 6] = "SAFARI";
10
+ CompanionWebClientType[CompanionWebClientType["ELECTRON"] = 7] = "ELECTRON";
11
+ CompanionWebClientType[CompanionWebClientType["UWP"] = 8] = "UWP";
12
+ CompanionWebClientType[CompanionWebClientType["OTHER_WEB_CLIENT"] = 9] = "OTHER_WEB_CLIENT";
13
+ })(CompanionWebClientType || (CompanionWebClientType = {}));
14
+ const BROWSER_TO_COMPANION_WEB_CLIENT = {
15
+ Chrome: CompanionWebClientType.CHROME,
16
+ Edge: CompanionWebClientType.EDGE,
17
+ Firefox: CompanionWebClientType.FIREFOX,
18
+ IE: CompanionWebClientType.IE,
19
+ Opera: CompanionWebClientType.OPERA,
20
+ Safari: CompanionWebClientType.SAFARI
21
+ };
22
+ export const getCompanionWebClientType = ([os, browserName]) => {
23
+ if (browserName === 'Desktop') {
24
+ return os === 'Windows' ? CompanionWebClientType.UWP : CompanionWebClientType.ELECTRON;
25
+ }
26
+ return BROWSER_TO_COMPANION_WEB_CLIENT[browserName] || CompanionWebClientType.OTHER_WEB_CLIENT;
27
+ };
28
+ export const getCompanionPlatformId = (browser) => {
29
+ return getCompanionWebClientType(browser).toString();
30
+ };
31
+ export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) => {
32
+ return ('https://wa.me/settings/linked_devices#' +
33
+ [ref, noiseKeyB64, identityKeyB64, advB64, getCompanionPlatformId(browser)].join(','));
34
+ };
35
+ //# sourceMappingURL=companion-reg-client-utils.js.map
@@ -0,0 +1,37 @@
1
+ import type { KeyPair } from '../Types/index.js';
2
+ export { md5, hkdf } from 'whatsapp-rust-bridge';
3
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
4
+ export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike>;
5
+ export declare const Curve: {
6
+ generateKeyPair: () => KeyPair;
7
+ sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer<ArrayBuffer>;
8
+ sign: (privateKey: Uint8Array, buf: Uint8Array) => Uint8Array<ArrayBufferLike>;
9
+ verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean;
10
+ };
11
+ export declare const signedKeyPair: (identityKeyPair: KeyPair, keyId: number) => {
12
+ keyPair: KeyPair;
13
+ signature: Uint8Array<ArrayBufferLike>;
14
+ keyId: number;
15
+ };
16
+ /**
17
+ * encrypt AES 256 GCM;
18
+ * where the tag tag is suffixed to the ciphertext
19
+ * */
20
+ export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
21
+ /**
22
+ * decrypt AES 256 GCM;
23
+ * where the auth tag is suffixed to the ciphertext
24
+ * */
25
+ export declare function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
26
+ export declare function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
27
+ export declare function aesDecryptCTR(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
28
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
29
+ export declare function aesDecrypt(buffer: Uint8Array, key: Uint8Array): Buffer<ArrayBuffer>;
30
+ /** decrypt AES 256 CBC */
31
+ export declare function aesDecryptWithIV(buffer: Uint8Array, key: Uint8Array, IV: Uint8Array): Buffer<ArrayBuffer>;
32
+ export declare function aesEncrypt(buffer: Uint8Array, key: Uint8Array): Buffer<ArrayBuffer>;
33
+ export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
34
+ export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): Buffer<ArrayBufferLike>;
35
+ export declare function sha256(buffer: Buffer): Buffer<ArrayBufferLike>;
36
+ export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;
37
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1,118 @@
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
+ export { md5, hkdf } from 'whatsapp-rust-bridge';
5
+ // insure browser & node compatibility
6
+ const { subtle } = globalThis.crypto;
7
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
8
+ export const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]);
9
+ export const Curve = {
10
+ generateKeyPair: () => {
11
+ const { pubKey, privKey } = curve.generateKeyPair();
12
+ return {
13
+ private: Buffer.from(privKey),
14
+ // remove version byte
15
+ public: Buffer.from(pubKey.slice(1))
16
+ };
17
+ },
18
+ sharedKey: (privateKey, publicKey) => {
19
+ const shared = curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey);
20
+ return Buffer.from(shared);
21
+ },
22
+ sign: (privateKey, buf) => curve.calculateSignature(privateKey, buf),
23
+ verify: (pubKey, message, signature) => {
24
+ try {
25
+ curve.verifySignature(generateSignalPubKey(pubKey), message, signature);
26
+ return true;
27
+ }
28
+ catch (error) {
29
+ return false;
30
+ }
31
+ }
32
+ };
33
+ export const signedKeyPair = (identityKeyPair, keyId) => {
34
+ const preKey = Curve.generateKeyPair();
35
+ const pubKey = generateSignalPubKey(preKey.public);
36
+ const signature = Curve.sign(identityKeyPair.private, pubKey);
37
+ return { keyPair: preKey, signature, keyId };
38
+ };
39
+ const GCM_TAG_LENGTH = 128 >> 3;
40
+ /**
41
+ * encrypt AES 256 GCM;
42
+ * where the tag tag is suffixed to the ciphertext
43
+ * */
44
+ export function aesEncryptGCM(plaintext, key, iv, additionalData) {
45
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
46
+ cipher.setAAD(additionalData);
47
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
48
+ }
49
+ /**
50
+ * decrypt AES 256 GCM;
51
+ * where the auth tag is suffixed to the ciphertext
52
+ * */
53
+ export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
54
+ const decipher = createDecipheriv('aes-256-gcm', key, iv);
55
+ // decrypt additional adata
56
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
57
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
58
+ // set additional data
59
+ decipher.setAAD(additionalData);
60
+ decipher.setAuthTag(tag);
61
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
62
+ }
63
+ export function aesEncryptCTR(plaintext, key, iv) {
64
+ const cipher = createCipheriv('aes-256-ctr', key, iv);
65
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
66
+ }
67
+ export function aesDecryptCTR(ciphertext, key, iv) {
68
+ const decipher = createDecipheriv('aes-256-ctr', key, iv);
69
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
70
+ }
71
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
72
+ export function aesDecrypt(buffer, key) {
73
+ return aesDecryptWithIV(buffer.subarray(16), key, buffer.subarray(0, 16));
74
+ }
75
+ /** decrypt AES 256 CBC */
76
+ export function aesDecryptWithIV(buffer, key, IV) {
77
+ const aes = createDecipheriv('aes-256-cbc', key, IV);
78
+ return Buffer.concat([aes.update(buffer), aes.final()]);
79
+ }
80
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
81
+ export function aesEncrypt(buffer, key) {
82
+ const IV = randomBytes(16);
83
+ const aes = createCipheriv('aes-256-cbc', key, IV);
84
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
85
+ }
86
+ // encrypt AES 256 CBC with a given IV
87
+ export function aesEncrypWithIV(buffer, key, IV) {
88
+ const aes = createCipheriv('aes-256-cbc', key, IV);
89
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
90
+ }
91
+ // sign HMAC using SHA 256
92
+ export function hmacSign(buffer, key, variant = 'sha256') {
93
+ return createHmac(variant, key).update(buffer).digest();
94
+ }
95
+ export function sha256(buffer) {
96
+ return createHash('sha256').update(buffer).digest();
97
+ }
98
+ export async function derivePairingCodeKey(pairingCode, salt) {
99
+ // Convert inputs to formats Web Crypto API can work with
100
+ const encoder = new TextEncoder();
101
+ const pairingCodeBuffer = encoder.encode(pairingCode);
102
+ const saltBuffer = new Uint8Array(salt instanceof Uint8Array ? salt : new Uint8Array(salt));
103
+ // Import the pairing code as key material
104
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, [
105
+ 'deriveBits'
106
+ ]);
107
+ // Derive bits using PBKDF2 with the same parameters
108
+ // 2 << 16 = 131,072 iterations
109
+ const derivedBits = await subtle.deriveBits({
110
+ name: 'PBKDF2',
111
+ salt: saltBuffer,
112
+ iterations: 2 << 16,
113
+ hash: 'SHA-256'
114
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
115
+ );
116
+ return Buffer.from(derivedBits);
117
+ }
118
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1,66 @@
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 ACCOUNT_RESTRICTED_TEXT = "Your account has been restricted";
9
+ export declare const DECRYPTION_RETRY_CONFIG: {
10
+ maxRetries: number;
11
+ baseDelayMs: number;
12
+ sessionRecordErrors: string[];
13
+ };
14
+ /** NACK reason codes we send to the server (client → server) */
15
+ export declare const NACK_REASONS: {
16
+ SenderReachoutTimelocked: number;
17
+ ParsingError: number;
18
+ UnrecognizedStanza: number;
19
+ UnrecognizedStanzaClass: number;
20
+ UnrecognizedStanzaType: number;
21
+ InvalidProtobuf: number;
22
+ InvalidHostedCompanionStanza: number;
23
+ MissingMessageSecret: number;
24
+ SignalErrorOldCounter: number;
25
+ MessageDeletedOnPeer: number;
26
+ UnhandledError: number;
27
+ UnsupportedAdminRevoke: number;
28
+ UnsupportedLIDGroup: number;
29
+ DBOperationFailed: number;
30
+ };
31
+ /**
32
+ * Server-side error codes returned in ack stanzas (server → client) that we
33
+ * currently have dedicated handlers for. Extend as more handlers are added.
34
+ * Distinct from the client-side NackReason enum (WAWebCreateNackFromStanza).
35
+ */
36
+ export declare const SERVER_ERROR_CODES: {
37
+ /**
38
+ * 1:1 message missing privacy token (tctoken). Usually means the account is
39
+ * restricted: WhatsApp blocks starting new chats but preserves existing ones,
40
+ * since established chats already carry a tctoken.
41
+ */
42
+ readonly MessageAccountRestriction: "463";
43
+ /** Stanza validation failure (SMAX_INVALID) — likely stale device session */
44
+ readonly SmaxInvalid: "479";
45
+ };
46
+ export declare const extractAddressingContext: (stanza: BinaryNode) => {
47
+ addressingMode: string;
48
+ senderAlt: string | undefined;
49
+ recipientAlt: string | undefined;
50
+ };
51
+ /**
52
+ * Decode the received node as a message.
53
+ * @note this will only parse the message, not decrypt it
54
+ */
55
+ export declare function decodeMessageNode(stanza: BinaryNode, meId: string, meLid: string): {
56
+ fullMessage: WAMessage;
57
+ author: string;
58
+ sender: string;
59
+ };
60
+ export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepositoryWithLIDStore, logger: ILogger) => {
61
+ fullMessage: WAMessage;
62
+ category: string | undefined;
63
+ author: string;
64
+ decrypt(): Promise<void>;
65
+ };
66
+ //# sourceMappingURL=decode-wa-message.d.ts.map
@@ -0,0 +1,311 @@
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
+ export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted';
31
+ // Retry configuration for failed decryption
32
+ export const DECRYPTION_RETRY_CONFIG = {
33
+ maxRetries: 3,
34
+ baseDelayMs: 100,
35
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
36
+ };
37
+ /** NACK reason codes we send to the server (client → server) */
38
+ export const NACK_REASONS = {
39
+ SenderReachoutTimelocked: 463,
40
+ ParsingError: 487,
41
+ UnrecognizedStanza: 488,
42
+ UnrecognizedStanzaClass: 489,
43
+ UnrecognizedStanzaType: 490,
44
+ InvalidProtobuf: 491,
45
+ InvalidHostedCompanionStanza: 493,
46
+ MissingMessageSecret: 495,
47
+ SignalErrorOldCounter: 496,
48
+ MessageDeletedOnPeer: 499,
49
+ UnhandledError: 500,
50
+ UnsupportedAdminRevoke: 550,
51
+ UnsupportedLIDGroup: 551,
52
+ DBOperationFailed: 552
53
+ };
54
+ /**
55
+ * Server-side error codes returned in ack stanzas (server → client) that we
56
+ * currently have dedicated handlers for. Extend as more handlers are added.
57
+ * Distinct from the client-side NackReason enum (WAWebCreateNackFromStanza).
58
+ */
59
+ export const SERVER_ERROR_CODES = {
60
+ /**
61
+ * 1:1 message missing privacy token (tctoken). Usually means the account is
62
+ * restricted: WhatsApp blocks starting new chats but preserves existing ones,
63
+ * since established chats already carry a tctoken.
64
+ */
65
+ MessageAccountRestriction: '463',
66
+ /** Stanza validation failure (SMAX_INVALID) — likely stale device session */
67
+ SmaxInvalid: '479'
68
+ };
69
+ export const extractAddressingContext = (stanza) => {
70
+ let senderAlt;
71
+ let recipientAlt;
72
+ const sender = stanza.attrs.participant || stanza.attrs.from;
73
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn');
74
+ if (addressingMode === 'lid') {
75
+ // Message is LID-addressed: sender is LID, extract corresponding PN
76
+ // without device data
77
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
78
+ recipientAlt = stanza.attrs.recipient_pn;
79
+ // with device data
80
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
81
+ }
82
+ else {
83
+ // Message is PN-addressed: sender is PN, extract corresponding LID
84
+ // without device data
85
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
86
+ recipientAlt = stanza.attrs.recipient_lid;
87
+ //with device data
88
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
89
+ }
90
+ return {
91
+ addressingMode,
92
+ senderAlt,
93
+ recipientAlt
94
+ };
95
+ };
96
+ /**
97
+ * Decode the received node as a message.
98
+ * @note this will only parse the message, not decrypt it
99
+ */
100
+ export function decodeMessageNode(stanza, meId, meLid) {
101
+ let msgType;
102
+ let chatId;
103
+ let author;
104
+ let fromMe = false;
105
+ const msgId = stanza.attrs.id;
106
+ const from = stanza.attrs.from;
107
+ const participant = stanza.attrs.participant;
108
+ const recipient = stanza.attrs.recipient;
109
+ if (!msgId) {
110
+ throw new Boom('Invalid message stanza: missing id attribute', { data: stanza });
111
+ }
112
+ if (!from) {
113
+ throw new Boom('Invalid message stanza: missing from attribute', { data: stanza });
114
+ }
115
+ const addressingContext = extractAddressingContext(stanza);
116
+ const isMe = (jid) => areJidsSameUser(jid, meId);
117
+ const isMeLid = (jid) => areJidsSameUser(jid, meLid);
118
+ if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
119
+ if (recipient && !isJidMetaAI(recipient)) {
120
+ if (!isMe(from) && !isMeLid(from)) {
121
+ throw new Boom('receipient present, but msg not from me', { data: stanza });
122
+ }
123
+ if (isMe(from) || isMeLid(from)) {
124
+ fromMe = true;
125
+ }
126
+ chatId = recipient;
127
+ }
128
+ else {
129
+ chatId = from;
130
+ }
131
+ msgType = 'chat';
132
+ author = from;
133
+ }
134
+ else if (isJidGroup(from)) {
135
+ if (!participant) {
136
+ throw new Boom('No participant in group message');
137
+ }
138
+ if (isMe(participant) || isMeLid(participant)) {
139
+ fromMe = true;
140
+ }
141
+ msgType = 'group';
142
+ author = participant;
143
+ chatId = from;
144
+ }
145
+ else if (isJidBroadcast(from)) {
146
+ if (!participant) {
147
+ throw new Boom('No participant in group message');
148
+ }
149
+ const isParticipantMe = isMe(participant);
150
+ if (isJidStatusBroadcast(from)) {
151
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
152
+ }
153
+ else {
154
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
155
+ }
156
+ fromMe = isParticipantMe;
157
+ chatId = from;
158
+ author = participant;
159
+ }
160
+ else if (isJidNewsletter(from)) {
161
+ msgType = 'newsletter';
162
+ chatId = from;
163
+ author = from;
164
+ if (isMe(from) || isMeLid(from)) {
165
+ fromMe = true;
166
+ }
167
+ }
168
+ else {
169
+ throw new Boom('Unknown message type', { data: stanza });
170
+ }
171
+ const pushname = stanza?.attrs?.notify;
172
+ const key = {
173
+ remoteJid: chatId,
174
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
175
+ remoteJidUsername: !isJidGroup(chatId)
176
+ ? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username
177
+ : undefined,
178
+ fromMe,
179
+ id: msgId,
180
+ participant,
181
+ participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
182
+ participantUsername: stanza.attrs.participant ? stanza.attrs.participant_username : undefined,
183
+ addressingMode: addressingContext.addressingMode,
184
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
185
+ };
186
+ const fullMessage = {
187
+ key,
188
+ category: stanza.attrs.category,
189
+ messageTimestamp: +stanza.attrs.t,
190
+ pushName: pushname,
191
+ broadcast: isJidBroadcast(from)
192
+ };
193
+ if (key.fromMe) {
194
+ fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
195
+ }
196
+ return {
197
+ fullMessage,
198
+ author,
199
+ sender: msgType === 'chat' ? author : chatId
200
+ };
201
+ }
202
+ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
203
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
204
+ return {
205
+ fullMessage,
206
+ category: stanza.attrs.category,
207
+ author,
208
+ async decrypt() {
209
+ let decryptables = 0;
210
+ if (Array.isArray(stanza.content)) {
211
+ for (const { tag, attrs, content } of stanza.content) {
212
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
213
+ const cert = proto.VerifiedNameCertificate.decode(content);
214
+ const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
215
+ fullMessage.verifiedBizName = details.verifiedName;
216
+ }
217
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
218
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
219
+ }
220
+ if (attrs.count && tag === 'enc') {
221
+ fullMessage.retryCount = Number(attrs.count);
222
+ }
223
+ if (tag !== 'enc' && tag !== 'plaintext') {
224
+ continue;
225
+ }
226
+ if (!(content instanceof Uint8Array)) {
227
+ continue;
228
+ }
229
+ decryptables += 1;
230
+ let msgBuffer;
231
+ const decryptionJid = await getDecryptionJid(author, repository);
232
+ if (tag !== 'plaintext') {
233
+ // TODO: Handle hosted devices
234
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
235
+ }
236
+ try {
237
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
238
+ switch (e2eType) {
239
+ case 'skmsg':
240
+ msgBuffer = await repository.decryptGroupMessage({
241
+ group: sender,
242
+ authorJid: author,
243
+ msg: content
244
+ });
245
+ break;
246
+ case 'pkmsg':
247
+ case 'msg':
248
+ msgBuffer = await repository.decryptMessage({
249
+ jid: decryptionJid,
250
+ type: e2eType,
251
+ ciphertext: content
252
+ });
253
+ break;
254
+ case 'plaintext':
255
+ msgBuffer = content;
256
+ break;
257
+ default:
258
+ throw new Error(`Unknown e2e type: ${e2eType}`);
259
+ }
260
+ let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer);
261
+ msg = msg.deviceSentMessage?.message || msg;
262
+ if (msg.senderKeyDistributionMessage) {
263
+ //eslint-disable-next-line max-depth
264
+ try {
265
+ await repository.processSenderKeyDistributionMessage({
266
+ authorJid: author,
267
+ item: msg.senderKeyDistributionMessage
268
+ });
269
+ }
270
+ catch (err) {
271
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
272
+ }
273
+ }
274
+ if (fullMessage.message) {
275
+ Object.assign(fullMessage.message, msg);
276
+ }
277
+ else {
278
+ fullMessage.message = msg;
279
+ }
280
+ }
281
+ catch (err) {
282
+ const errorContext = {
283
+ key: fullMessage.key,
284
+ err,
285
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
286
+ sender,
287
+ author,
288
+ isSessionRecordError: isSessionRecordError(err)
289
+ };
290
+ logger.error(errorContext, 'failed to decrypt message');
291
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
292
+ fullMessage.messageStubParameters = [err.message.toString()];
293
+ }
294
+ }
295
+ }
296
+ // if nothing was found to decrypt
297
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
298
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
299
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
300
+ }
301
+ }
302
+ };
303
+ };
304
+ /**
305
+ * Utility function to check if an error is related to missing session record
306
+ */
307
+ function isSessionRecordError(error) {
308
+ const errorMessage = error?.message || error?.toString() || '';
309
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
310
+ }
311
+ //# sourceMappingURL=decode-wa-message.js.map
@@ -0,0 +1,36 @@
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
+ /** destroy the event buffer, clearing all resources */
28
+ destroy(): void;
29
+ };
30
+ /**
31
+ * The event buffer logically consolidates different events into a single event
32
+ * making the data processing more efficient.
33
+ */
34
+ export declare const makeEventBuffer: (logger: ILogger) => BaileysBufferableEventEmitter;
35
+ export {};
36
+ //# sourceMappingURL=event-buffer.d.ts.map