jagproject 26.3.23 → 26.3.26

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 (209) hide show
  1. package/WAProto/GenerateStatics.sh +3 -4
  2. package/WAProto/WAProto.proto +1215 -511
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +64857 -145167
  6. package/engine-requirements.js +4 -7
  7. package/lib/Defaults/index.d.ts +74 -0
  8. package/lib/Defaults/index.js +49 -35
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Defaults/wileys-version.json +2 -2
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +5 -3
  14. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  15. package/lib/Signal/Group/group_cipher.js +35 -46
  16. package/lib/Signal/Group/index.d.ts +12 -0
  17. package/lib/Signal/Group/index.js +21 -21
  18. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  19. package/lib/Signal/Group/keyhelper.js +2 -2
  20. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  21. package/lib/Signal/Group/sender-chain-key.js +5 -10
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.js +7 -7
  24. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  25. package/lib/Signal/Group/sender-key-message.js +8 -8
  26. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  27. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  28. package/lib/Signal/Group/sender-key-record.js +7 -16
  29. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  30. package/lib/Signal/Group/sender-key-state.js +25 -37
  31. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  32. package/lib/Signal/Group/sender-message-key.js +2 -2
  33. package/lib/Signal/libsignal.d.ts +5 -0
  34. package/lib/Signal/libsignal.js +358 -54
  35. package/lib/Signal/lid-mapping.d.ts +19 -0
  36. package/lib/Signal/lid-mapping.js +274 -0
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +2 -2
  39. package/lib/Socket/Client/types.d.ts +16 -0
  40. package/lib/Socket/Client/types.js +1 -0
  41. package/lib/Socket/Client/websocket.d.ts +13 -0
  42. package/lib/Socket/Client/websocket.js +18 -30
  43. package/lib/Socket/business.d.ts +202 -0
  44. package/lib/Socket/business.js +160 -38
  45. package/lib/Socket/chats.d.ts +111 -0
  46. package/lib/Socket/chats.js +497 -314
  47. package/lib/Socket/communities.d.ts +258 -0
  48. package/lib/Socket/communities.js +438 -0
  49. package/lib/Socket/community.js +333 -0
  50. package/lib/Socket/groups.d.ts +150 -0
  51. package/lib/Socket/groups.js +229 -91
  52. package/lib/Socket/index.d.ts +245 -0
  53. package/lib/Socket/index.js +9 -6
  54. package/lib/Socket/messages-recv.d.ts +187 -0
  55. package/lib/Socket/messages-recv.js +1105 -501
  56. package/lib/Socket/messages-send.d.ts +183 -0
  57. package/lib/Socket/messages-send.js +1181 -501
  58. package/lib/Socket/mex.d.ts +3 -0
  59. package/lib/Socket/mex.js +45 -0
  60. package/lib/Socket/newsletter.d.ts +160 -0
  61. package/lib/Socket/newsletter.js +227 -200
  62. package/lib/Socket/socket.d.ts +55 -0
  63. package/lib/Socket/socket.js +507 -206
  64. package/lib/Socket/usync.js +6 -6
  65. package/lib/Store/index.js +17 -5
  66. package/lib/Store/make-cache-manager-store.js +83 -0
  67. package/lib/Store/make-in-memory-store.js +48 -89
  68. package/lib/Store/make-ordered-dictionary.js +1 -1
  69. package/lib/Types/Auth.d.ts +116 -0
  70. package/lib/Types/Bussines.d.ts +25 -0
  71. package/lib/Types/Bussines.js +2 -0
  72. package/lib/Types/Call.d.ts +15 -0
  73. package/lib/Types/Chat.d.ts +123 -0
  74. package/lib/Types/Chat.js +7 -1
  75. package/lib/Types/Contact.d.ts +24 -0
  76. package/lib/Types/Events.d.ts +237 -0
  77. package/lib/Types/Events.js +1 -0
  78. package/lib/Types/GroupMetadata.d.ts +67 -0
  79. package/lib/Types/Label.d.ts +47 -0
  80. package/lib/Types/Label.js +1 -3
  81. package/lib/Types/LabelAssociation.d.ts +30 -0
  82. package/lib/Types/LabelAssociation.js +1 -3
  83. package/lib/Types/Message.d.ts +305 -0
  84. package/lib/Types/Message.js +9 -5
  85. package/lib/Types/MexUpdates.js +11 -0
  86. package/lib/Types/Newsletter.d.ts +135 -0
  87. package/lib/Types/Newsletter.js +36 -11
  88. package/lib/Types/Product.d.ts +79 -0
  89. package/lib/Types/Signal.d.ts +76 -0
  90. package/lib/Types/Signal.js +1 -0
  91. package/lib/Types/Socket.d.ts +133 -0
  92. package/lib/Types/Socket.js +1 -0
  93. package/lib/Types/State.d.ts +39 -0
  94. package/lib/Types/State.js +12 -0
  95. package/lib/Types/USync.d.ts +26 -0
  96. package/lib/Types/USync.js +1 -0
  97. package/lib/Types/index.d.ts +65 -0
  98. package/lib/Types/index.js +14 -14
  99. package/lib/Utils/audioToBuffer.js +31 -0
  100. package/lib/Utils/auth-utils.d.ts +19 -0
  101. package/lib/Utils/auth-utils.js +222 -123
  102. package/lib/Utils/baileys-event-stream.js +60 -0
  103. package/lib/Utils/bridge-runtime.d.ts +1 -0
  104. package/lib/Utils/bridge-runtime.js +14 -0
  105. package/lib/Utils/browser-utils.d.ts +4 -0
  106. package/lib/Utils/browser-utils.js +38 -29
  107. package/lib/Utils/business.d.ts +23 -0
  108. package/lib/Utils/business.js +54 -48
  109. package/lib/Utils/chat-utils.d.ts +70 -0
  110. package/lib/Utils/chat-utils.js +284 -189
  111. package/lib/Utils/crypto.d.ts +37 -0
  112. package/lib/Utils/crypto.js +16 -41
  113. package/lib/Utils/decode-wa-message.d.ts +48 -0
  114. package/lib/Utils/decode-wa-message.js +128 -48
  115. package/lib/Utils/event-buffer.d.ts +34 -0
  116. package/lib/Utils/event-buffer.js +124 -62
  117. package/lib/Utils/generics.d.ts +91 -0
  118. package/lib/Utils/generics.js +154 -138
  119. package/lib/Utils/history.d.ts +22 -0
  120. package/lib/Utils/history.js +77 -34
  121. package/lib/Utils/identity-change-handler.d.ts +37 -0
  122. package/lib/Utils/identity-change-handler.js +54 -0
  123. package/lib/Utils/index.d.ts +22 -0
  124. package/lib/Utils/index.js +32 -19
  125. package/lib/Utils/link-preview.d.ts +21 -0
  126. package/lib/Utils/link-preview.js +12 -17
  127. package/lib/Utils/logger.d.ts +13 -0
  128. package/lib/Utils/lt-hash.d.ts +8 -0
  129. package/lib/Utils/lt-hash.js +2 -43
  130. package/lib/Utils/make-mutex.d.ts +9 -0
  131. package/lib/Utils/make-mutex.js +21 -27
  132. package/lib/Utils/message-retry-manager.d.ts +110 -0
  133. package/lib/Utils/message-retry-manager.js +143 -45
  134. package/lib/Utils/messages-media.d.ts +130 -0
  135. package/lib/Utils/messages-media.js +429 -502
  136. package/lib/Utils/messages-newsletter.d.ts +84 -0
  137. package/lib/Utils/messages-newsletter.js +295 -0
  138. package/lib/Utils/messages.d.ts +92 -0
  139. package/lib/Utils/messages.js +1025 -674
  140. package/lib/Utils/noise-handler.d.ts +20 -0
  141. package/lib/Utils/noise-handler.js +145 -91
  142. package/lib/Utils/pre-key-manager.d.ts +28 -0
  143. package/lib/Utils/pre-key-manager.js +112 -0
  144. package/lib/Utils/process-message.d.ts +60 -0
  145. package/lib/Utils/process-message.js +316 -184
  146. package/lib/Utils/reporting-utils.d.ts +11 -0
  147. package/lib/Utils/reporting-utils.js +262 -0
  148. package/lib/Utils/resolve-jid.d.ts +43 -0
  149. package/lib/Utils/resolve-jid.js +95 -0
  150. package/lib/Utils/rust-bridge-shim.d.ts +22 -0
  151. package/lib/Utils/rust-bridge-shim.js +70 -0
  152. package/lib/Utils/serial-task-queue.js +29 -0
  153. package/lib/Utils/signal.d.ts +34 -0
  154. package/lib/Utils/signal.js +56 -39
  155. package/lib/Utils/streamToBuffer.js +17 -0
  156. package/lib/Utils/sync-action-utils.d.ts +19 -0
  157. package/lib/Utils/sync-action-utils.js +52 -0
  158. package/lib/Utils/tc-token-utils.d.ts +12 -0
  159. package/lib/Utils/tc-token-utils.js +20 -0
  160. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  161. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  162. package/lib/Utils/use-multi-file-auth-state.js +11 -12
  163. package/lib/Utils/use-single-file-auth-state.js +73 -0
  164. package/lib/Utils/validate-connection.d.ts +11 -0
  165. package/lib/Utils/validate-connection.js +59 -82
  166. package/lib/Utils/wileys-event-stream.js +1 -61
  167. package/lib/WABinary/constants.d.ts +28 -0
  168. package/lib/WABinary/decode.d.ts +7 -0
  169. package/lib/WABinary/decode.js +39 -4
  170. package/lib/WABinary/encode.d.ts +3 -0
  171. package/lib/WABinary/encode.js +17 -11
  172. package/lib/WABinary/generic-utils.d.ts +15 -0
  173. package/lib/WABinary/generic-utils.js +46 -18
  174. package/lib/WABinary/index.d.ts +6 -0
  175. package/lib/WABinary/index.js +9 -5
  176. package/lib/WABinary/jid-utils.d.ts +48 -0
  177. package/lib/WABinary/jid-utils.js +67 -37
  178. package/lib/WABinary/types.d.ts +19 -0
  179. package/lib/WABinary/types.js +34 -0
  180. package/lib/WAM/BinaryInfo.d.ts +9 -0
  181. package/lib/WAM/constants.d.ts +40 -0
  182. package/lib/WAM/constants.js +19183 -11678
  183. package/lib/WAM/encode.d.ts +3 -0
  184. package/lib/WAM/encode.js +15 -17
  185. package/lib/WAM/index.d.ts +4 -0
  186. package/lib/WAM/index.js +3 -3
  187. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  188. package/lib/WAUSync/Protocols/USyncContactProtocol.js +6 -6
  189. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  190. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +9 -9
  191. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  192. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +6 -6
  193. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  194. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -8
  195. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  196. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +18 -17
  197. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  198. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +11 -3
  199. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  200. package/lib/WAUSync/Protocols/index.js +6 -4
  201. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  202. package/lib/WAUSync/USyncQuery.js +38 -30
  203. package/lib/WAUSync/USyncUser.d.ts +13 -0
  204. package/lib/WAUSync/index.d.ts +4 -0
  205. package/lib/WAUSync/index.js +3 -3
  206. package/lib/index.d.ts +12 -0
  207. package/lib/index.js +3 -5
  208. package/package.json +7 -4
  209. package/LICENSE +0 -21
@@ -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
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.signedKeyPair = exports.Curve = exports.generateSignalPubKey = void 0;
36
+ exports.signedKeyPair = exports.Curve = exports.generateSignalPubKey = exports.hkdf = exports.md5 = void 0;
37
37
  exports.aesEncryptGCM = aesEncryptGCM;
38
38
  exports.aesDecryptGCM = aesDecryptGCM;
39
39
  exports.aesEncryptCTR = aesEncryptCTR;
@@ -44,22 +44,21 @@ exports.aesEncrypt = aesEncrypt;
44
44
  exports.aesEncrypWithIV = aesEncrypWithIV;
45
45
  exports.hmacSign = hmacSign;
46
46
  exports.sha256 = sha256;
47
- exports.md5 = md5;
48
- exports.hkdf = hkdf;
49
47
  exports.derivePairingCodeKey = derivePairingCodeKey;
50
48
  const crypto_1 = require("crypto");
51
- const libsignal = __importStar(require("libsignal"));
52
- const Defaults_1 = require("../Defaults");
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; } });
53
54
  // insure browser & node compatibility
54
55
  const { subtle } = globalThis.crypto;
55
56
  /** prefix version byte to the pub keys, required for some curve crypto functions */
56
- const generateSignalPubKey = (pubKey) => (pubKey.length === 33
57
- ? pubKey
58
- : Buffer.concat([Defaults_1.KEY_BUNDLE_TYPE, pubKey]));
57
+ const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([index_js_1.KEY_BUNDLE_TYPE, pubKey]);
59
58
  exports.generateSignalPubKey = generateSignalPubKey;
60
59
  exports.Curve = {
61
60
  generateKeyPair: () => {
62
- const { pubKey, privKey } = libsignal.curve.generateKeyPair();
61
+ const { pubKey, privKey } = curve.generateKeyPair();
63
62
  return {
64
63
  private: Buffer.from(privKey),
65
64
  // remove version byte
@@ -67,13 +66,13 @@ exports.Curve = {
67
66
  };
68
67
  },
69
68
  sharedKey: (privateKey, publicKey) => {
70
- const shared = libsignal.curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
69
+ const shared = curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
71
70
  return Buffer.from(shared);
72
71
  },
73
- sign: (privateKey, buf) => (libsignal.curve.calculateSignature(privateKey, buf)),
72
+ sign: (privateKey, buf) => curve.calculateSignature(privateKey, buf),
74
73
  verify: (pubKey, message, signature) => {
75
74
  try {
76
- libsignal.curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
75
+ curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
77
76
  return true;
78
77
  }
79
78
  catch (error) {
@@ -122,7 +121,7 @@ function aesDecryptCTR(ciphertext, key, iv) {
122
121
  }
123
122
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
124
123
  function aesDecrypt(buffer, key) {
125
- return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
124
+ return aesDecryptWithIV(buffer.subarray(16), key, buffer.subarray(0, 16));
126
125
  }
127
126
  /** decrypt AES 256 CBC */
128
127
  function aesDecryptWithIV(buffer, key, IV) {
@@ -147,39 +146,15 @@ function hmacSign(buffer, key, variant = 'sha256') {
147
146
  function sha256(buffer) {
148
147
  return (0, crypto_1.createHash)('sha256').update(buffer).digest();
149
148
  }
150
- function md5(buffer) {
151
- return (0, crypto_1.createHash)('md5').update(buffer).digest();
152
- }
153
- // HKDF key expansion
154
- async function hkdf(buffer, expandedLength, info) {
155
- // Ensure we have a Uint8Array for the key material
156
- const inputKeyMaterial = buffer instanceof Uint8Array
157
- ? buffer
158
- : new Uint8Array(buffer);
159
- // Set default values if not provided
160
- const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
161
- const infoBytes = info.info
162
- ? new TextEncoder().encode(info.info)
163
- : new Uint8Array(0);
164
- // Import the input key material
165
- const importedKey = await subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits']);
166
- // Derive bits using HKDF
167
- const derivedBits = await subtle.deriveBits({
168
- name: 'HKDF',
169
- hash: 'SHA-256',
170
- salt: salt,
171
- info: infoBytes
172
- }, importedKey, expandedLength * 8 // Convert bytes to bits
173
- );
174
- return Buffer.from(derivedBits);
175
- }
176
149
  async function derivePairingCodeKey(pairingCode, salt) {
177
150
  // Convert inputs to formats Web Crypto API can work with
178
151
  const encoder = new TextEncoder();
179
152
  const pairingCodeBuffer = encoder.encode(pairingCode);
180
- const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
153
+ const saltBuffer = new Uint8Array(salt instanceof Uint8Array ? salt : new Uint8Array(salt));
181
154
  // Import the pairing code as key material
182
- const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits']);
155
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, [
156
+ 'deriveBits'
157
+ ]);
183
158
  // Derive bits using PBKDF2 with the same parameters
184
159
  // 2 << 16 = 131,072 iterations
185
160
  const derivedBits = await subtle.deriveBits({
@@ -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
@@ -1,13 +1,41 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decryptMessageNode = exports.NACK_REASONS = exports.MISSING_KEYS_ERROR_TEXT = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
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
4
  exports.decodeMessageNode = decodeMessageNode;
5
5
  const boom_1 = require("@hapi/boom");
6
- const WAProto_1 = require("../../WAProto");
7
- const WABinary_1 = require("../WABinary");
8
- const generics_1 = require("./generics");
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
+ };
9
31
  exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
10
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
+ };
11
39
  exports.NACK_REASONS = {
12
40
  ParsingError: 487,
13
41
  UnrecognizedStanza: 488,
@@ -23,29 +51,58 @@ exports.NACK_REASONS = {
23
51
  UnsupportedLIDGroup: 551,
24
52
  DBOperationFailed: 552
25
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;
26
82
  /**
27
83
  * Decode the received node as a message.
28
84
  * @note this will only parse the message, not decrypt it
29
85
  */
30
86
  function decodeMessageNode(stanza, meId, meLid) {
31
- var _a, _b, _c, _d, _e, _f, _g;
32
87
  let msgType;
33
88
  let chatId;
34
89
  let author;
90
+ let fromMe = false;
35
91
  const msgId = stanza.attrs.id;
36
92
  const from = stanza.attrs.from;
37
- const senderPn = (_a = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _a === void 0 ? void 0 : _a.sender_pn;
38
- const senderLid = (_b = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _b === void 0 ? void 0 : _b.sender_lid;
39
93
  const participant = stanza.attrs.participant;
40
- const participantLid = (_c = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _c === void 0 ? void 0 : _c.participant_lid;
41
94
  const recipient = stanza.attrs.recipient;
42
- const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
43
- const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
44
- if ((0, WABinary_1.isJidUser)(from) || (0, WABinary_1.isLidUser)(from)) {
45
- if (recipient && !(0, WABinary_1.isJidMetaAi)(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)) {
46
100
  if (!isMe(from) && !isMeLid(from)) {
47
101
  throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
48
102
  }
103
+ if (isMe(from) || isMeLid(from)) {
104
+ fromMe = true;
105
+ }
49
106
  chatId = recipient;
50
107
  }
51
108
  else {
@@ -54,59 +111,63 @@ function decodeMessageNode(stanza, meId, meLid) {
54
111
  msgType = 'chat';
55
112
  author = from;
56
113
  }
57
- else if ((0, WABinary_1.isJidGroup)(from)) {
114
+ else if ((0, index_js_2.isJidGroup)(from)) {
58
115
  if (!participant) {
59
116
  throw new boom_1.Boom('No participant in group message');
60
117
  }
118
+ if (isMe(participant) || isMeLid(participant)) {
119
+ fromMe = true;
120
+ }
61
121
  msgType = 'group';
62
122
  author = participant;
63
123
  chatId = from;
64
124
  }
65
- else if ((0, WABinary_1.isJidNewsletter)(from)) {
66
- msgType = 'newsletter';
67
- author = from;
68
- chatId = from;
69
- }
70
- else if ((0, WABinary_1.isJidBroadcast)(from)) {
125
+ else if ((0, index_js_2.isJidBroadcast)(from)) {
71
126
  if (!participant) {
72
127
  throw new boom_1.Boom('No participant in group message');
73
128
  }
74
129
  const isParticipantMe = isMe(participant);
75
- if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
130
+ if ((0, index_js_2.isJidStatusBroadcast)(from)) {
76
131
  msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
77
132
  }
78
133
  else {
79
134
  msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
80
135
  }
136
+ fromMe = isParticipantMe;
81
137
  chatId = from;
82
138
  author = participant;
83
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
+ }
84
148
  else {
85
149
  throw new boom_1.Boom('Unknown message type', { data: stanza });
86
150
  }
87
- const fromMe = (0, WABinary_1.isJidNewsletter)(from) ? !!((_d = stanza.attrs) === null || _d === void 0 ? void 0 : _d.is_sender) || false : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
88
- const pushname = (_e = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _e === void 0 ? void 0 : _e.notify;
151
+ const pushname = stanza?.attrs?.notify;
89
152
  const key = {
90
153
  remoteJid: chatId,
154
+ remoteJidAlt: !(0, index_js_2.isJidGroup)(chatId) ? addressingContext.senderAlt : undefined,
91
155
  fromMe,
92
156
  id: msgId,
93
- senderPn,
94
- senderLid,
95
157
  participant,
96
- participantLid,
97
- 'server_id': (_f = stanza.attrs) === null || _f === void 0 ? void 0 : _f.server_id
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 } : {})
98
161
  };
99
162
  const fullMessage = {
100
163
  key,
164
+ category: stanza.attrs.category,
101
165
  messageTimestamp: +stanza.attrs.t,
102
166
  pushName: pushname,
103
- broadcast: (0, WABinary_1.isJidBroadcast)(from)
167
+ broadcast: (0, index_js_2.isJidBroadcast)(from)
104
168
  };
105
- if (msgType === 'newsletter') {
106
- fullMessage.newsletterServerId = +((_g = stanza.attrs) === null || _g === void 0 ? void 0 : _g.server_id);
107
- }
108
169
  if (key.fromMe) {
109
- fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
170
+ fullMessage.status = index_js_1.proto.WebMessageInfo.Status.SERVER_ACK;
110
171
  }
111
172
  return {
112
173
  fullMessage,
@@ -121,17 +182,19 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
121
182
  category: stanza.attrs.category,
122
183
  author,
123
184
  async decrypt() {
124
- var _a;
125
185
  let decryptables = 0;
126
186
  if (Array.isArray(stanza.content)) {
127
187
  for (const { tag, attrs, content } of stanza.content) {
128
188
  if (tag === 'verified_name' && content instanceof Uint8Array) {
129
- const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
130
- const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
189
+ const cert = index_js_1.proto.VerifiedNameCertificate.decode(content);
190
+ const details = index_js_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
131
191
  fullMessage.verifiedBizName = details.verifiedName;
132
192
  }
133
193
  if (tag === 'unavailable' && attrs.type === 'view_once') {
134
- fullMessage.key.isViewOnce = true;
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);
135
198
  }
136
199
  if (tag !== 'enc' && tag !== 'plaintext') {
137
200
  continue;
@@ -141,6 +204,11 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
141
204
  }
142
205
  decryptables += 1;
143
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
+ }
144
212
  try {
145
213
  const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
146
214
  switch (e2eType) {
@@ -153,9 +221,8 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
153
221
  break;
154
222
  case 'pkmsg':
155
223
  case 'msg':
156
- const user = (0, WABinary_1.isJidUser)(sender) ? sender : author;
157
224
  msgBuffer = await repository.decryptMessage({
158
- jid: user,
225
+ jid: decryptionJid,
159
226
  type: e2eType,
160
227
  ciphertext: content
161
228
  });
@@ -163,15 +230,13 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
163
230
  case 'plaintext':
164
231
  msgBuffer = content;
165
232
  break;
166
- case undefined:
167
- msgBuffer = content;
168
- break;
169
233
  default:
170
234
  throw new Error(`Unknown e2e type: ${e2eType}`);
171
235
  }
172
- let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
173
- msg = ((_a = msg === null || msg === void 0 ? void 0 : msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
236
+ let msg = index_js_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_js_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
237
+ msg = msg.deviceSentMessage?.message || msg;
174
238
  if (msg.senderKeyDistributionMessage) {
239
+ //eslint-disable-next-line max-depth
175
240
  try {
176
241
  await repository.processSenderKeyDistributionMessage({
177
242
  authorJid: author,
@@ -179,7 +244,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
179
244
  });
180
245
  }
181
246
  catch (err) {
182
- logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
247
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
183
248
  }
184
249
  }
185
250
  if (fullMessage.message) {
@@ -190,18 +255,33 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
190
255
  }
191
256
  }
192
257
  catch (err) {
193
- logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
194
- fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
195
- fullMessage.messageStubParameters = [err.message];
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()];
196
269
  }
197
270
  }
198
271
  }
199
272
  // if nothing was found to decrypt
200
- if (!decryptables) {
201
- fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
273
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
274
+ fullMessage.messageStubType = index_js_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
202
275
  fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
203
276
  }
204
277
  }
205
278
  };
206
279
  };
207
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