astrabail 1.0.6

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 (224) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +5479 -0
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +89351 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +7 -0
  8. package/lib/Defaults/astrabail-version.json +8 -0
  9. package/lib/Defaults/index.d.ts +74 -0
  10. package/lib/Defaults/index.js +166 -0
  11. package/lib/Defaults/phonenumber-mcc.json +223 -0
  12. package/lib/Defaults/update-wa-version.js +75 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.js +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  16. package/lib/Signal/Group/group-session-builder.js +66 -0
  17. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  18. package/lib/Signal/Group/group_cipher.js +85 -0
  19. package/lib/Signal/Group/index.d.ts +12 -0
  20. package/lib/Signal/Group/index.js +57 -0
  21. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  22. package/lib/Signal/Group/keyhelper.js +55 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  25. package/lib/Signal/Group/sender-chain-key.js +29 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  33. package/lib/Signal/Group/sender-key-record.js +44 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  35. package/lib/Signal/Group/sender-key-state.js +87 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +5 -0
  39. package/lib/Signal/libsignal.js +478 -0
  40. package/lib/Signal/lid-mapping.d.ts +19 -0
  41. package/lib/Signal/lid-mapping.js +274 -0
  42. package/lib/Socket/Client/index.d.ts +3 -0
  43. package/lib/Socket/Client/index.js +18 -0
  44. package/lib/Socket/Client/types.d.ts +16 -0
  45. package/lib/Socket/Client/types.js +14 -0
  46. package/lib/Socket/Client/websocket.d.ts +13 -0
  47. package/lib/Socket/Client/websocket.js +60 -0
  48. package/lib/Socket/business.d.ts +202 -0
  49. package/lib/Socket/business.js +382 -0
  50. package/lib/Socket/chats.d.ts +111 -0
  51. package/lib/Socket/chats.js +1155 -0
  52. package/lib/Socket/communities.d.ts +258 -0
  53. package/lib/Socket/communities.js +438 -0
  54. package/lib/Socket/community.js +333 -0
  55. package/lib/Socket/groups.d.ts +150 -0
  56. package/lib/Socket/groups.js +470 -0
  57. package/lib/Socket/index.d.ts +245 -0
  58. package/lib/Socket/index.js +13 -0
  59. package/lib/Socket/messages-recv.d.ts +187 -0
  60. package/lib/Socket/messages-recv.js +1708 -0
  61. package/lib/Socket/messages-send.d.ts +183 -0
  62. package/lib/Socket/messages-send.js +1692 -0
  63. package/lib/Socket/mex.d.ts +3 -0
  64. package/lib/Socket/mex.js +45 -0
  65. package/lib/Socket/newsletter.d.ts +160 -0
  66. package/lib/Socket/newsletter.js +293 -0
  67. package/lib/Socket/socket.d.ts +55 -0
  68. package/lib/Socket/socket.js +947 -0
  69. package/lib/Socket/usync.js +70 -0
  70. package/lib/Store/index.js +20 -0
  71. package/lib/Store/make-cache-manager-store.js +83 -0
  72. package/lib/Store/make-in-memory-store.js +398 -0
  73. package/lib/Store/make-ordered-dictionary.js +81 -0
  74. package/lib/Store/object-repository.js +27 -0
  75. package/lib/Types/Auth.d.ts +116 -0
  76. package/lib/Types/Auth.js +2 -0
  77. package/lib/Types/Bussines.d.ts +25 -0
  78. package/lib/Types/Bussines.js +2 -0
  79. package/lib/Types/Call.d.ts +15 -0
  80. package/lib/Types/Call.js +2 -0
  81. package/lib/Types/Chat.d.ts +123 -0
  82. package/lib/Types/Chat.js +10 -0
  83. package/lib/Types/Contact.d.ts +24 -0
  84. package/lib/Types/Contact.js +2 -0
  85. package/lib/Types/Events.d.ts +237 -0
  86. package/lib/Types/Events.js +3 -0
  87. package/lib/Types/GroupMetadata.d.ts +67 -0
  88. package/lib/Types/GroupMetadata.js +2 -0
  89. package/lib/Types/Label.d.ts +47 -0
  90. package/lib/Types/Label.js +25 -0
  91. package/lib/Types/LabelAssociation.d.ts +30 -0
  92. package/lib/Types/LabelAssociation.js +7 -0
  93. package/lib/Types/Message.d.ts +305 -0
  94. package/lib/Types/Message.js +11 -0
  95. package/lib/Types/MexUpdates.js +11 -0
  96. package/lib/Types/Newsletter.d.ts +135 -0
  97. package/lib/Types/Newsletter.js +43 -0
  98. package/lib/Types/Product.d.ts +79 -0
  99. package/lib/Types/Product.js +2 -0
  100. package/lib/Types/Signal.d.ts +76 -0
  101. package/lib/Types/Signal.js +3 -0
  102. package/lib/Types/Socket.d.ts +133 -0
  103. package/lib/Types/Socket.js +3 -0
  104. package/lib/Types/State.d.ts +39 -0
  105. package/lib/Types/State.js +14 -0
  106. package/lib/Types/USync.d.ts +26 -0
  107. package/lib/Types/USync.js +3 -0
  108. package/lib/Types/index.d.ts +65 -0
  109. package/lib/Types/index.js +42 -0
  110. package/lib/Utils/astrabail-event-stream.js +3 -0
  111. package/lib/Utils/audioToBuffer.js +31 -0
  112. package/lib/Utils/auth-utils.d.ts +19 -0
  113. package/lib/Utils/auth-utils.js +298 -0
  114. package/lib/Utils/baileys-event-stream.js +60 -0
  115. package/lib/Utils/bridge-runtime.d.ts +1 -0
  116. package/lib/Utils/bridge-runtime.js +14 -0
  117. package/lib/Utils/browser-utils.d.ts +4 -0
  118. package/lib/Utils/browser-utils.js +44 -0
  119. package/lib/Utils/business.d.ts +23 -0
  120. package/lib/Utils/business.js +240 -0
  121. package/lib/Utils/chat-utils.d.ts +70 -0
  122. package/lib/Utils/chat-utils.js +825 -0
  123. package/lib/Utils/crypto.d.ts +37 -0
  124. package/lib/Utils/crypto.js +168 -0
  125. package/lib/Utils/decode-wa-message.d.ts +48 -0
  126. package/lib/Utils/decode-wa-message.js +287 -0
  127. package/lib/Utils/event-buffer.d.ts +34 -0
  128. package/lib/Utils/event-buffer.js +580 -0
  129. package/lib/Utils/generics.d.ts +91 -0
  130. package/lib/Utils/generics.js +483 -0
  131. package/lib/Utils/history.d.ts +22 -0
  132. package/lib/Utils/history.js +137 -0
  133. package/lib/Utils/identity-change-handler.d.ts +37 -0
  134. package/lib/Utils/identity-change-handler.js +54 -0
  135. package/lib/Utils/index.d.ts +22 -0
  136. package/lib/Utils/index.js +48 -0
  137. package/lib/Utils/link-preview.d.ts +21 -0
  138. package/lib/Utils/link-preview.js +121 -0
  139. package/lib/Utils/logger.d.ts +13 -0
  140. package/lib/Utils/logger.js +7 -0
  141. package/lib/Utils/lt-hash.d.ts +8 -0
  142. package/lib/Utils/lt-hash.js +10 -0
  143. package/lib/Utils/make-mutex.d.ts +9 -0
  144. package/lib/Utils/make-mutex.js +37 -0
  145. package/lib/Utils/message-retry-manager.d.ts +110 -0
  146. package/lib/Utils/message-retry-manager.js +226 -0
  147. package/lib/Utils/messages-media.d.ts +130 -0
  148. package/lib/Utils/messages-media.js +887 -0
  149. package/lib/Utils/messages-newsletter.d.ts +84 -0
  150. package/lib/Utils/messages-newsletter.js +295 -0
  151. package/lib/Utils/messages.d.ts +92 -0
  152. package/lib/Utils/messages.js +1752 -0
  153. package/lib/Utils/noise-handler.d.ts +20 -0
  154. package/lib/Utils/noise-handler.js +204 -0
  155. package/lib/Utils/pre-key-manager.d.ts +28 -0
  156. package/lib/Utils/pre-key-manager.js +112 -0
  157. package/lib/Utils/process-message.d.ts +60 -0
  158. package/lib/Utils/process-message.js +536 -0
  159. package/lib/Utils/reporting-utils.d.ts +11 -0
  160. package/lib/Utils/reporting-utils.js +262 -0
  161. package/lib/Utils/resolve-jid.d.ts +43 -0
  162. package/lib/Utils/resolve-jid.js +95 -0
  163. package/lib/Utils/rust-bridge-shim.d.ts +22 -0
  164. package/lib/Utils/rust-bridge-shim.js +70 -0
  165. package/lib/Utils/serial-task-queue.js +29 -0
  166. package/lib/Utils/signal.d.ts +34 -0
  167. package/lib/Utils/signal.js +170 -0
  168. package/lib/Utils/streamToBuffer.js +17 -0
  169. package/lib/Utils/sync-action-utils.d.ts +19 -0
  170. package/lib/Utils/sync-action-utils.js +52 -0
  171. package/lib/Utils/tc-token-utils.d.ts +12 -0
  172. package/lib/Utils/tc-token-utils.js +20 -0
  173. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  174. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  175. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  176. package/lib/Utils/use-single-file-auth-state.js +73 -0
  177. package/lib/Utils/validate-connection.d.ts +11 -0
  178. package/lib/Utils/validate-connection.js +206 -0
  179. package/lib/WABinary/constants.d.ts +28 -0
  180. package/lib/WABinary/constants.js +1303 -0
  181. package/lib/WABinary/decode.d.ts +7 -0
  182. package/lib/WABinary/decode.js +300 -0
  183. package/lib/WABinary/encode.d.ts +3 -0
  184. package/lib/WABinary/encode.js +256 -0
  185. package/lib/WABinary/generic-utils.d.ts +15 -0
  186. package/lib/WABinary/generic-utils.js +138 -0
  187. package/lib/WABinary/index.d.ts +6 -0
  188. package/lib/WABinary/index.js +25 -0
  189. package/lib/WABinary/jid-utils.d.ts +48 -0
  190. package/lib/WABinary/jid-utils.js +115 -0
  191. package/lib/WABinary/types.d.ts +19 -0
  192. package/lib/WABinary/types.js +36 -0
  193. package/lib/WAM/BinaryInfo.d.ts +9 -0
  194. package/lib/WAM/BinaryInfo.js +13 -0
  195. package/lib/WAM/constants.d.ts +40 -0
  196. package/lib/WAM/constants.js +22855 -0
  197. package/lib/WAM/encode.d.ts +3 -0
  198. package/lib/WAM/encode.js +153 -0
  199. package/lib/WAM/index.d.ts +4 -0
  200. package/lib/WAM/index.js +19 -0
  201. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  202. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  203. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  204. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  205. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  206. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  207. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  208. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +41 -0
  209. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  210. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +54 -0
  211. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  212. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +32 -0
  213. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  214. package/lib/WAUSync/Protocols/index.js +22 -0
  215. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  216. package/lib/WAUSync/USyncQuery.js +97 -0
  217. package/lib/WAUSync/USyncUser.d.ts +13 -0
  218. package/lib/WAUSync/USyncUser.js +26 -0
  219. package/lib/WAUSync/index.d.ts +4 -0
  220. package/lib/WAUSync/index.js +19 -0
  221. package/lib/index.d.ts +12 -0
  222. package/lib/index.js +124 -0
  223. package/package.json +120 -0
  224. package/readme.md +1956 -0
@@ -0,0 +1,37 @@
1
+ import type { KeyPair } from '../Types/index.js';
2
+ export { md5, hkdf } from './bridge-runtime.js';
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'): NonSharedBuffer;
35
+ export declare function sha256(buffer: Buffer): NonSharedBuffer;
36
+ export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;
37
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.signedKeyPair = exports.Curve = exports.generateSignalPubKey = exports.hkdf = exports.md5 = void 0;
37
+ exports.aesEncryptGCM = aesEncryptGCM;
38
+ exports.aesDecryptGCM = aesDecryptGCM;
39
+ exports.aesEncryptCTR = aesEncryptCTR;
40
+ exports.aesDecryptCTR = aesDecryptCTR;
41
+ exports.aesDecrypt = aesDecrypt;
42
+ exports.aesDecryptWithIV = aesDecryptWithIV;
43
+ exports.aesEncrypt = aesEncrypt;
44
+ exports.aesEncrypWithIV = aesEncrypWithIV;
45
+ exports.hmacSign = hmacSign;
46
+ exports.sha256 = sha256;
47
+ exports.derivePairingCodeKey = derivePairingCodeKey;
48
+ const crypto_1 = require("crypto");
49
+ const curve = __importStar(require("libsignal/src/curve.js"));
50
+ const index_js_1 = require("../Defaults/index.js");
51
+ var bridge_runtime_js_1 = require("./bridge-runtime.js");
52
+ Object.defineProperty(exports, "md5", { enumerable: true, get: function () { return bridge_runtime_js_1.md5; } });
53
+ Object.defineProperty(exports, "hkdf", { enumerable: true, get: function () { return bridge_runtime_js_1.hkdf; } });
54
+ // insure browser & node compatibility
55
+ const { subtle } = globalThis.crypto;
56
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
57
+ const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([index_js_1.KEY_BUNDLE_TYPE, pubKey]);
58
+ exports.generateSignalPubKey = generateSignalPubKey;
59
+ exports.Curve = {
60
+ generateKeyPair: () => {
61
+ const { pubKey, privKey } = curve.generateKeyPair();
62
+ return {
63
+ private: Buffer.from(privKey),
64
+ // remove version byte
65
+ public: Buffer.from(pubKey.slice(1))
66
+ };
67
+ },
68
+ sharedKey: (privateKey, publicKey) => {
69
+ const shared = curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
70
+ return Buffer.from(shared);
71
+ },
72
+ sign: (privateKey, buf) => curve.calculateSignature(privateKey, buf),
73
+ verify: (pubKey, message, signature) => {
74
+ try {
75
+ curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
76
+ return true;
77
+ }
78
+ catch (error) {
79
+ return false;
80
+ }
81
+ }
82
+ };
83
+ const signedKeyPair = (identityKeyPair, keyId) => {
84
+ const preKey = exports.Curve.generateKeyPair();
85
+ const pubKey = (0, exports.generateSignalPubKey)(preKey.public);
86
+ const signature = exports.Curve.sign(identityKeyPair.private, pubKey);
87
+ return { keyPair: preKey, signature, keyId };
88
+ };
89
+ exports.signedKeyPair = signedKeyPair;
90
+ const GCM_TAG_LENGTH = 128 >> 3;
91
+ /**
92
+ * encrypt AES 256 GCM;
93
+ * where the tag tag is suffixed to the ciphertext
94
+ * */
95
+ function aesEncryptGCM(plaintext, key, iv, additionalData) {
96
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
97
+ cipher.setAAD(additionalData);
98
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
99
+ }
100
+ /**
101
+ * decrypt AES 256 GCM;
102
+ * where the auth tag is suffixed to the ciphertext
103
+ * */
104
+ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
105
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
106
+ // decrypt additional adata
107
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
108
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
109
+ // set additional data
110
+ decipher.setAAD(additionalData);
111
+ decipher.setAuthTag(tag);
112
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
113
+ }
114
+ function aesEncryptCTR(plaintext, key, iv) {
115
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
116
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
117
+ }
118
+ function aesDecryptCTR(ciphertext, key, iv) {
119
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
120
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
121
+ }
122
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
123
+ function aesDecrypt(buffer, key) {
124
+ return aesDecryptWithIV(buffer.subarray(16), key, buffer.subarray(0, 16));
125
+ }
126
+ /** decrypt AES 256 CBC */
127
+ function aesDecryptWithIV(buffer, key, IV) {
128
+ const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
129
+ return Buffer.concat([aes.update(buffer), aes.final()]);
130
+ }
131
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
132
+ function aesEncrypt(buffer, key) {
133
+ const IV = (0, crypto_1.randomBytes)(16);
134
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
135
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
136
+ }
137
+ // encrypt AES 256 CBC with a given IV
138
+ function aesEncrypWithIV(buffer, key, IV) {
139
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
140
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
141
+ }
142
+ // sign HMAC using SHA 256
143
+ function hmacSign(buffer, key, variant = 'sha256') {
144
+ return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
145
+ }
146
+ function sha256(buffer) {
147
+ return (0, crypto_1.createHash)('sha256').update(buffer).digest();
148
+ }
149
+ async function derivePairingCodeKey(pairingCode, salt) {
150
+ // Convert inputs to formats Web Crypto API can work with
151
+ const encoder = new TextEncoder();
152
+ const pairingCodeBuffer = encoder.encode(pairingCode);
153
+ const saltBuffer = new Uint8Array(salt instanceof Uint8Array ? salt : new Uint8Array(salt));
154
+ // Import the pairing code as key material
155
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, [
156
+ 'deriveBits'
157
+ ]);
158
+ // Derive bits using PBKDF2 with the same parameters
159
+ // 2 << 16 = 131,072 iterations
160
+ const derivedBits = await subtle.deriveBits({
161
+ name: 'PBKDF2',
162
+ salt: saltBuffer,
163
+ iterations: 2 << 16,
164
+ hash: 'SHA-256'
165
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
166
+ );
167
+ return Buffer.from(derivedBits);
168
+ }
@@ -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,287 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decryptMessageNode = exports.extractAddressingContext = exports.NACK_REASONS = exports.DECRYPTION_RETRY_CONFIG = exports.MISSING_KEYS_ERROR_TEXT = exports.NO_MESSAGE_FOUND_ERROR_TEXT = exports.getDecryptionJid = void 0;
4
+ exports.decodeMessageNode = decodeMessageNode;
5
+ const boom_1 = require("@hapi/boom");
6
+ const index_js_1 = require("../../WAProto/index.js");
7
+ const index_js_2 = require("../WABinary/index.js");
8
+ const generics_js_1 = require("./generics.js");
9
+ const getDecryptionJid = async (sender, repository) => {
10
+ if ((0, index_js_2.isLidUser)(sender) || (0, index_js_2.isHostedLidUser)(sender)) {
11
+ return sender;
12
+ }
13
+ const mapped = await repository.lidMapping.getLIDForPN(sender);
14
+ return mapped || sender;
15
+ };
16
+ exports.getDecryptionJid = getDecryptionJid;
17
+ const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger) => {
18
+ // TODO: Handle hosted IDs
19
+ const { senderAlt } = (0, exports.extractAddressingContext)(stanza);
20
+ if (senderAlt && (0, index_js_2.isLidUser)(senderAlt) && (0, index_js_2.isPnUser)(sender) && decryptionJid === sender) {
21
+ try {
22
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }]);
23
+ await repository.migrateSession(sender, senderAlt);
24
+ logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope');
25
+ }
26
+ catch (error) {
27
+ logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping');
28
+ }
29
+ }
30
+ };
31
+ exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
32
+ exports.MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
33
+ // Retry configuration for failed decryption
34
+ exports.DECRYPTION_RETRY_CONFIG = {
35
+ maxRetries: 3,
36
+ baseDelayMs: 100,
37
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
38
+ };
39
+ exports.NACK_REASONS = {
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
+ const extractAddressingContext = (stanza) => {
55
+ let senderAlt;
56
+ let recipientAlt;
57
+ const sender = stanza.attrs.participant || stanza.attrs.from;
58
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn');
59
+ if (addressingMode === 'lid') {
60
+ // Message is LID-addressed: sender is LID, extract corresponding PN
61
+ // without device data
62
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
63
+ recipientAlt = stanza.attrs.recipient_pn;
64
+ // with device data
65
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
66
+ }
67
+ else {
68
+ // Message is PN-addressed: sender is PN, extract corresponding LID
69
+ // without device data
70
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
71
+ recipientAlt = stanza.attrs.recipient_lid;
72
+ //with device data
73
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
74
+ }
75
+ return {
76
+ addressingMode,
77
+ senderAlt,
78
+ recipientAlt
79
+ };
80
+ };
81
+ exports.extractAddressingContext = extractAddressingContext;
82
+ /**
83
+ * Decode the received node as a message.
84
+ * @note this will only parse the message, not decrypt it
85
+ */
86
+ function decodeMessageNode(stanza, meId, meLid) {
87
+ let msgType;
88
+ let chatId;
89
+ let author;
90
+ let fromMe = false;
91
+ const msgId = stanza.attrs.id;
92
+ const from = stanza.attrs.from;
93
+ const participant = stanza.attrs.participant;
94
+ const recipient = stanza.attrs.recipient;
95
+ const addressingContext = (0, exports.extractAddressingContext)(stanza);
96
+ const isMe = (jid) => (0, index_js_2.areJidsSameUser)(jid, meId);
97
+ const isMeLid = (jid) => (0, index_js_2.areJidsSameUser)(jid, meLid);
98
+ if ((0, index_js_2.isPnUser)(from) || (0, index_js_2.isLidUser)(from) || (0, index_js_2.isHostedLidUser)(from) || (0, index_js_2.isHostedPnUser)(from)) {
99
+ if (recipient && !(0, index_js_2.isJidMetaAI)(recipient)) {
100
+ if (!isMe(from) && !isMeLid(from)) {
101
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
102
+ }
103
+ if (isMe(from) || isMeLid(from)) {
104
+ fromMe = true;
105
+ }
106
+ chatId = recipient;
107
+ }
108
+ else {
109
+ chatId = from;
110
+ }
111
+ msgType = 'chat';
112
+ author = from;
113
+ }
114
+ else if ((0, index_js_2.isJidGroup)(from)) {
115
+ if (!participant) {
116
+ throw new boom_1.Boom('No participant in group message');
117
+ }
118
+ if (isMe(participant) || isMeLid(participant)) {
119
+ fromMe = true;
120
+ }
121
+ msgType = 'group';
122
+ author = participant;
123
+ chatId = from;
124
+ }
125
+ else if ((0, index_js_2.isJidBroadcast)(from)) {
126
+ if (!participant) {
127
+ throw new boom_1.Boom('No participant in group message');
128
+ }
129
+ const isParticipantMe = isMe(participant);
130
+ if ((0, index_js_2.isJidStatusBroadcast)(from)) {
131
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
132
+ }
133
+ else {
134
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
135
+ }
136
+ fromMe = isParticipantMe;
137
+ chatId = from;
138
+ author = participant;
139
+ }
140
+ else if ((0, index_js_2.isJidNewsletter)(from)) {
141
+ msgType = 'newsletter';
142
+ chatId = from;
143
+ author = from;
144
+ if (isMe(from) || isMeLid(from)) {
145
+ fromMe = true;
146
+ }
147
+ }
148
+ else {
149
+ throw new boom_1.Boom('Unknown message type', { data: stanza });
150
+ }
151
+ const pushname = stanza?.attrs?.notify;
152
+ const key = {
153
+ remoteJid: chatId,
154
+ remoteJidAlt: !(0, index_js_2.isJidGroup)(chatId) ? addressingContext.senderAlt : undefined,
155
+ fromMe,
156
+ id: msgId,
157
+ participant,
158
+ participantAlt: (0, index_js_2.isJidGroup)(chatId) ? addressingContext.senderAlt : undefined,
159
+ addressingMode: addressingContext.addressingMode,
160
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
161
+ };
162
+ const fullMessage = {
163
+ key,
164
+ category: stanza.attrs.category,
165
+ messageTimestamp: +stanza.attrs.t,
166
+ pushName: pushname,
167
+ broadcast: (0, index_js_2.isJidBroadcast)(from)
168
+ };
169
+ if (key.fromMe) {
170
+ fullMessage.status = index_js_1.proto.WebMessageInfo.Status.SERVER_ACK;
171
+ }
172
+ return {
173
+ fullMessage,
174
+ author,
175
+ sender: msgType === 'chat' ? author : chatId
176
+ };
177
+ }
178
+ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
179
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
180
+ return {
181
+ fullMessage,
182
+ category: stanza.attrs.category,
183
+ author,
184
+ async decrypt() {
185
+ let decryptables = 0;
186
+ if (Array.isArray(stanza.content)) {
187
+ for (const { tag, attrs, content } of stanza.content) {
188
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
189
+ const cert = index_js_1.proto.VerifiedNameCertificate.decode(content);
190
+ const details = index_js_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
191
+ fullMessage.verifiedBizName = details.verifiedName;
192
+ }
193
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
194
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
195
+ }
196
+ if (attrs.count && tag === 'enc') {
197
+ fullMessage.retryCount = Number(attrs.count);
198
+ }
199
+ if (tag !== 'enc' && tag !== 'plaintext') {
200
+ continue;
201
+ }
202
+ if (!(content instanceof Uint8Array)) {
203
+ continue;
204
+ }
205
+ decryptables += 1;
206
+ let msgBuffer;
207
+ const decryptionJid = await (0, exports.getDecryptionJid)(author, repository);
208
+ if (tag !== 'plaintext') {
209
+ // TODO: Handle hosted devices
210
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
211
+ }
212
+ try {
213
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
214
+ switch (e2eType) {
215
+ case 'skmsg':
216
+ msgBuffer = await repository.decryptGroupMessage({
217
+ group: sender,
218
+ authorJid: author,
219
+ msg: content
220
+ });
221
+ break;
222
+ case 'pkmsg':
223
+ case 'msg':
224
+ msgBuffer = await repository.decryptMessage({
225
+ jid: decryptionJid,
226
+ type: e2eType,
227
+ ciphertext: content
228
+ });
229
+ break;
230
+ case 'plaintext':
231
+ msgBuffer = content;
232
+ break;
233
+ default:
234
+ throw new Error(`Unknown e2e type: ${e2eType}`);
235
+ }
236
+ let msg = index_js_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_js_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
237
+ msg = msg.deviceSentMessage?.message || msg;
238
+ if (msg.senderKeyDistributionMessage) {
239
+ //eslint-disable-next-line max-depth
240
+ try {
241
+ await repository.processSenderKeyDistributionMessage({
242
+ authorJid: author,
243
+ item: msg.senderKeyDistributionMessage
244
+ });
245
+ }
246
+ catch (err) {
247
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
248
+ }
249
+ }
250
+ if (fullMessage.message) {
251
+ Object.assign(fullMessage.message, msg);
252
+ }
253
+ else {
254
+ fullMessage.message = msg;
255
+ }
256
+ }
257
+ catch (err) {
258
+ const errorContext = {
259
+ key: fullMessage.key,
260
+ err,
261
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
262
+ sender,
263
+ author,
264
+ isSessionRecordError: isSessionRecordError(err)
265
+ };
266
+ logger.error(errorContext, 'failed to decrypt message');
267
+ fullMessage.messageStubType = index_js_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
268
+ fullMessage.messageStubParameters = [err.message.toString()];
269
+ }
270
+ }
271
+ }
272
+ // if nothing was found to decrypt
273
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
274
+ fullMessage.messageStubType = index_js_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
275
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
276
+ }
277
+ }
278
+ };
279
+ };
280
+ exports.decryptMessageNode = decryptMessageNode;
281
+ /**
282
+ * Utility function to check if an error is related to missing session record
283
+ */
284
+ function isSessionRecordError(error) {
285
+ const errorMessage = error?.message || error?.toString() || '';
286
+ return exports.DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
287
+ }
@@ -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