@badzz88/baileys 8.5.6 → 8.5.8

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 (225) hide show
  1. package/README.md +337 -1055
  2. package/WAProto/WAProto.proto +28 -1189
  3. package/WAProto/fix-imports.js +79 -69
  4. package/WAProto/index.d.ts +71491 -15254
  5. package/WAProto/index.js +126436 -19814
  6. package/engine-requirements.js +8 -15
  7. package/lib/Defaults/index.js +130 -0
  8. package/{src → lib}/Signal/Group/ciphertext-message.js +2 -5
  9. package/lib/Signal/Group/group-session-builder.js +30 -0
  10. package/{src → lib}/Signal/Group/group_cipher.js +11 -11
  11. package/lib/Signal/Group/index.js +12 -0
  12. package/lib/Signal/Group/keyhelper.js +18 -0
  13. package/{src → lib}/Signal/Group/sender-chain-key.js +6 -9
  14. package/{src → lib}/Signal/Group/sender-key-distribution-message.js +6 -9
  15. package/{src → lib}/Signal/Group/sender-key-message.js +9 -12
  16. package/{src → lib}/Signal/Group/sender-key-name.js +2 -5
  17. package/{src → lib}/Signal/Group/sender-key-record.js +8 -11
  18. package/{src → lib}/Signal/Group/sender-key-state.js +6 -9
  19. package/lib/Signal/Group/sender-message-key.js +26 -0
  20. package/{src → lib}/Signal/libsignal.js +131 -155
  21. package/{src → lib}/Signal/lid-mapping.js +27 -23
  22. package/lib/Socket/Client/index.js +3 -0
  23. package/lib/Socket/Client/types.js +11 -0
  24. package/{src → lib}/Socket/Client/websocket.js +11 -18
  25. package/{src → lib}/Socket/business.js +35 -67
  26. package/{src → lib}/Socket/chats.js +294 -550
  27. package/{src → lib}/Socket/communities.js +82 -114
  28. package/lib/Socket/graphql.js +716 -0
  29. package/lib/Socket/groups.js +374 -0
  30. package/lib/Socket/index.js +18 -0
  31. package/lib/Socket/interop.js +463 -0
  32. package/{src → lib}/Socket/luxu.js +120 -82
  33. package/lib/Socket/messages-recv.js +1916 -0
  34. package/lib/Socket/messages-send.js +1436 -0
  35. package/lib/Socket/mex.js +54 -0
  36. package/lib/Socket/newsletter.js +757 -0
  37. package/lib/Socket/privacy.js +318 -0
  38. package/{src → lib}/Socket/socket.js +356 -244
  39. package/lib/Socket/username.js +236 -0
  40. package/lib/Store/index.js +10 -0
  41. package/{src → lib}/Store/keyed-db.js +11 -21
  42. package/lib/Store/make-cache-manager-store.js +85 -0
  43. package/lib/Store/make-in-memory-store.js +244 -0
  44. package/{src → lib}/Store/make-ordered-dictionary.js +19 -25
  45. package/{src → lib}/Store/object-repository.js +11 -5
  46. package/lib/Types/Auth.js +2 -0
  47. package/lib/Types/Bussines.js +2 -0
  48. package/lib/Types/Call.js +2 -0
  49. package/lib/Types/Chat.js +8 -0
  50. package/lib/Types/Contact.js +2 -0
  51. package/lib/Types/Events.js +2 -0
  52. package/lib/Types/GroupMetadata.js +2 -0
  53. package/lib/Types/Label.js +25 -0
  54. package/lib/Types/LabelAssociation.js +7 -0
  55. package/lib/Types/Message.js +11 -0
  56. package/lib/Types/Mex.js +111 -0
  57. package/lib/Types/Product.js +2 -0
  58. package/lib/Types/Signal.js +2 -0
  59. package/lib/Types/Socket.js +3 -0
  60. package/lib/Types/State.js +56 -0
  61. package/lib/Types/USync.js +2 -0
  62. package/lib/Types/index.js +26 -0
  63. package/{src → lib}/Utils/auth-utils.js +91 -43
  64. package/lib/Utils/browser-utils.js +48 -0
  65. package/lib/Utils/business.js +231 -0
  66. package/lib/Utils/chat-utils.js +872 -0
  67. package/lib/Utils/companion-reg-client-utils.js +35 -0
  68. package/lib/Utils/crypto.js +118 -0
  69. package/lib/Utils/decode-wa-message.js +350 -0
  70. package/{src → lib}/Utils/event-buffer.js +81 -39
  71. package/lib/Utils/generics.js +403 -0
  72. package/lib/Utils/history.js +134 -0
  73. package/{src → lib}/Utils/identity-change-handler.js +9 -11
  74. package/lib/Utils/index.js +23 -0
  75. package/lib/Utils/link-preview.js +85 -0
  76. package/lib/Utils/logger.js +3 -0
  77. package/lib/Utils/lt-hash.js +8 -0
  78. package/{src → lib}/Utils/make-mutex.js +7 -10
  79. package/lib/Utils/message-composer.js +273 -0
  80. package/{src → lib}/Utils/message-retry-manager.js +76 -28
  81. package/lib/Utils/messages-media.js +870 -0
  82. package/lib/Utils/messages.js +1337 -0
  83. package/lib/Utils/noise-handler.js +201 -0
  84. package/{src → lib}/Utils/offline-node-processor.js +10 -4
  85. package/{src → lib}/Utils/pre-key-manager.js +27 -11
  86. package/lib/Utils/process-message.js +630 -0
  87. package/{src → lib}/Utils/reporting-utils.js +12 -15
  88. package/lib/Utils/signal.js +201 -0
  89. package/{src → lib}/Utils/stanza-ack.js +12 -4
  90. package/lib/Utils/sticker.js +110 -0
  91. package/{src → lib}/Utils/sync-action-utils.js +14 -10
  92. package/{src → lib}/Utils/tc-token-utils.js +48 -43
  93. package/{src → lib}/Utils/use-multi-file-auth-state.js +35 -25
  94. package/lib/Utils/validate-connection.js +203 -0
  95. package/{src → lib}/WABinary/constants.js +9 -12
  96. package/{src → lib}/WABinary/decode.js +38 -118
  97. package/{src → lib}/WABinary/encode.js +6 -11
  98. package/lib/WABinary/generic-utils.js +204 -0
  99. package/lib/WABinary/index.js +6 -0
  100. package/lib/WABinary/jid-utils.js +98 -0
  101. package/lib/WABinary/types.js +2 -0
  102. package/{src → lib}/WAM/BinaryInfo.js +2 -5
  103. package/{src → lib}/WAM/constants.js +4 -16635
  104. package/{src → lib}/WAM/encode.js +18 -17
  105. package/lib/WAM/index.js +4 -0
  106. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  107. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  108. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  109. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  110. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  111. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +58 -0
  112. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  113. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  114. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +28 -0
  115. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  116. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  117. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  118. package/lib/WAUSync/Protocols/index.js +12 -0
  119. package/lib/WAUSync/USyncQuery.js +151 -0
  120. package/lib/WAUSync/USyncUser.js +56 -0
  121. package/lib/WAUSync/index.js +3 -0
  122. package/{src → lib}/index.js +16 -51
  123. package/package.json +129 -99
  124. package/LICENSE +0 -21
  125. package/src/Defaults/index.js +0 -186
  126. package/src/Defaults/phonenumber-mcc.json +0 -223
  127. package/src/Signal/Group/group-session-builder.js +0 -86
  128. package/src/Signal/Group/index.js +0 -140
  129. package/src/Signal/Group/keyhelper.js +0 -77
  130. package/src/Signal/Group/sender-message-key.js +0 -29
  131. package/src/Socket/Client/index.js +0 -31
  132. package/src/Socket/Client/types.js +0 -13
  133. package/src/Socket/aigroups.js +0 -221
  134. package/src/Socket/graphql.js +0 -523
  135. package/src/Socket/groups.js +0 -516
  136. package/src/Socket/index.js +0 -31
  137. package/src/Socket/interactive-handler.js +0 -527
  138. package/src/Socket/interop.js +0 -339
  139. package/src/Socket/managed-account.js +0 -98
  140. package/src/Socket/messages-recv.js +0 -2685
  141. package/src/Socket/messages-send.js +0 -2047
  142. package/src/Socket/mex.js +0 -57
  143. package/src/Socket/newsletter.js +0 -455
  144. package/src/Socket/privacy.js +0 -125
  145. package/src/Socket/registration.js +0 -236
  146. package/src/Socket/text-router.js +0 -65
  147. package/src/Socket/username.js +0 -130
  148. package/src/Store/index.js +0 -33
  149. package/src/Store/make-cache-manager-store.js +0 -84
  150. package/src/Store/make-in-memory-store.js +0 -551
  151. package/src/Types/Auth.js +0 -31
  152. package/src/Types/Bussines.js +0 -2
  153. package/src/Types/Call.js +0 -2
  154. package/src/Types/Chat.js +0 -4
  155. package/src/Types/Contact.js +0 -2
  156. package/src/Types/Events.js +0 -2
  157. package/src/Types/GroupMetadata.js +0 -2
  158. package/src/Types/Label.js +0 -26
  159. package/src/Types/LabelAssociation.js +0 -8
  160. package/src/Types/Message.js +0 -93
  161. package/src/Types/Mex.js +0 -112
  162. package/src/Types/Newsletter.js +0 -109
  163. package/src/Types/Product.js +0 -2
  164. package/src/Types/Signal.js +0 -2
  165. package/src/Types/Socket.js +0 -2
  166. package/src/Types/State.js +0 -62
  167. package/src/Types/USync.js +0 -2
  168. package/src/Types/index.js +0 -56
  169. package/src/Utils/browser-utils.js +0 -112
  170. package/src/Utils/business.js +0 -240
  171. package/src/Utils/chat-utils.js +0 -1230
  172. package/src/Utils/command-loader.d.ts +0 -27
  173. package/src/Utils/command-loader.js +0 -89
  174. package/src/Utils/companion-reg-client-utils.js +0 -40
  175. package/src/Utils/consumer-application.js +0 -105
  176. package/src/Utils/crypto.js +0 -118
  177. package/src/Utils/curve25519-js.js +0 -242
  178. package/src/Utils/decode-wa-message.js +0 -529
  179. package/src/Utils/generics.js +0 -483
  180. package/src/Utils/group-history.js +0 -44
  181. package/src/Utils/history.js +0 -232
  182. package/src/Utils/index.js +0 -58
  183. package/src/Utils/jid-display-normalization.js +0 -195
  184. package/src/Utils/link-preview.js +0 -135
  185. package/src/Utils/logger.js +0 -8
  186. package/src/Utils/lt-hash.js +0 -25
  187. package/src/Utils/message-composer.js +0 -471
  188. package/src/Utils/messages-media.js +0 -843
  189. package/src/Utils/messages.js +0 -2817
  190. package/src/Utils/meta-ai-msmsg.js +0 -222
  191. package/src/Utils/native-bridge.js +0 -68
  192. package/src/Utils/noise-handler.js +0 -169
  193. package/src/Utils/process-message.js +0 -950
  194. package/src/Utils/session-pool.d.ts +0 -14
  195. package/src/Utils/session-pool.js +0 -70
  196. package/src/Utils/signal.js +0 -217
  197. package/src/Utils/sticker.d.ts +0 -13
  198. package/src/Utils/sticker.js +0 -123
  199. package/src/Utils/validate-connection.js +0 -209
  200. package/src/Utils/view-once-cache.d.ts +0 -12
  201. package/src/Utils/view-once-cache.js +0 -63
  202. package/src/Utils/voip-rekey.js +0 -22
  203. package/src/WABinary/generic-utils.js +0 -238
  204. package/src/WABinary/index.js +0 -34
  205. package/src/WABinary/jid-utils.js +0 -351
  206. package/src/WABinary/types.js +0 -2
  207. package/src/WAM/index.js +0 -32
  208. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -53
  209. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +0 -44
  210. package/src/WAUSync/Protocols/USyncContactProtocol.js +0 -55
  211. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +0 -55
  212. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -31
  213. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +0 -54
  214. package/src/WAUSync/Protocols/USyncLIDProtocol.js +0 -32
  215. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -473
  216. package/src/WAUSync/Protocols/USyncPictureProtocol.js +0 -34
  217. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
  218. package/src/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  219. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
  220. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +0 -28
  221. package/src/WAUSync/Protocols/index.js +0 -40
  222. package/src/WAUSync/USyncQuery.js +0 -126
  223. package/src/WAUSync/USyncUser.js +0 -50
  224. package/src/WAUSync/index.js +0 -32
  225. package/src/antiban.js +0 -4152
@@ -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,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,350 @@
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
+ const MAX_SECRETS_PER_CHAT = 20
97
+ // Module-level map: outgoing @bot message ID → messageSecret
98
+ // Populated when we receive the outgoing pkmsg/msg to @bot (which contains messageContextInfo.messageSecret)
99
+ // Consumed when the msmsg response from @bot arrives and needs decryption
100
+ const botMessageSecrets = new Map()
101
+ const botRecentSecretsByChat = new Map()
102
+ const pushRecentChatSecret = (chatJid, id, secretBuf) => {
103
+ if (!chatJid || !secretBuf) return
104
+ const existing = botRecentSecretsByChat.get(chatJid) || []
105
+ const filtered = existing.filter(item => item.id !== id && !item.secret.equals(secretBuf))
106
+ filtered.unshift({ id, secret: secretBuf })
107
+ if (filtered.length > MAX_SECRETS_PER_CHAT) {
108
+ filtered.length = MAX_SECRETS_PER_CHAT
109
+ }
110
+ botRecentSecretsByChat.set(chatJid, filtered)
111
+ }
112
+ export const setBotMessageSecret = (id, secret, chatJid) => {
113
+ if (!id || !secret) return
114
+ let buf
115
+ if (Buffer.isBuffer(secret)) {
116
+ buf = secret
117
+ } else if (secret instanceof Uint8Array) {
118
+ buf = Buffer.from(secret.buffer, secret.byteOffset, secret.byteLength)
119
+ } else if (typeof secret === 'string') {
120
+ buf = Buffer.from(secret, 'base64')
121
+ } else {
122
+ return
123
+ }
124
+ botMessageSecrets.set(id, buf)
125
+ if (chatJid) {
126
+ pushRecentChatSecret(chatJid, id, buf)
127
+ }
128
+ }
129
+ /**
130
+ * Decode the received node as a message.
131
+ * @note this will only parse the message, not decrypt it
132
+ */
133
+ export function decodeMessageNode(stanza, meId, meLid) {
134
+ let msgType;
135
+ let chatId;
136
+ let author;
137
+ let fromMe = false;
138
+ const msgId = stanza.attrs.id;
139
+ const from = stanza.attrs.from;
140
+ const participant = stanza.attrs.participant;
141
+ const recipient = stanza.attrs.recipient;
142
+ if (!msgId) {
143
+ throw new Boom('Invalid message stanza: missing id attribute', { data: stanza });
144
+ }
145
+ if (!from) {
146
+ throw new Boom('Invalid message stanza: missing from attribute', { data: stanza });
147
+ }
148
+ const addressingContext = extractAddressingContext(stanza);
149
+ const isMe = (jid) => areJidsSameUser(jid, meId);
150
+ const isMeLid = (jid) => areJidsSameUser(jid, meLid);
151
+ if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
152
+ if (recipient && !isJidMetaAI(recipient)) {
153
+ if (!isMe(from) && !isMeLid(from)) {
154
+ throw new Boom('receipient present, but msg not from me', { data: stanza });
155
+ }
156
+ if (isMe(from) || isMeLid(from)) {
157
+ fromMe = true;
158
+ }
159
+ chatId = recipient;
160
+ }
161
+ else {
162
+ // Peer-routed self stanzas (history sync, app-state sync, etc.) arrive
163
+ // with `from` set to our own device but no `recipient` attribute —
164
+ // still mark as fromMe so self-only protocolMessage handlers run.
165
+ if (isMe(from) || isMeLid(from)) {
166
+ fromMe = true;
167
+ }
168
+ chatId = from;
169
+ }
170
+ msgType = 'chat';
171
+ author = from;
172
+ }
173
+ else if (isJidGroup(from)) {
174
+ if (!participant) {
175
+ throw new Boom('No participant in group message');
176
+ }
177
+ if (isMe(participant) || isMeLid(participant)) {
178
+ fromMe = true;
179
+ }
180
+ msgType = 'group';
181
+ author = participant;
182
+ chatId = from;
183
+ }
184
+ else if (isJidBroadcast(from)) {
185
+ if (!participant) {
186
+ throw new Boom('No participant in group message');
187
+ }
188
+ const isParticipantMe = isMe(participant);
189
+ if (isJidStatusBroadcast(from)) {
190
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
191
+ }
192
+ else {
193
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
194
+ }
195
+ fromMe = isParticipantMe;
196
+ chatId = from;
197
+ author = participant;
198
+ }
199
+ else if (isJidNewsletter(from)) {
200
+ msgType = 'newsletter';
201
+ chatId = from;
202
+ author = from;
203
+ if (isMe(from) || isMeLid(from)) {
204
+ fromMe = true;
205
+ }
206
+ }
207
+ else {
208
+ throw new Boom('Unknown message type', { data: stanza });
209
+ }
210
+ const pushname = stanza?.attrs?.notify;
211
+ const key = {
212
+ remoteJid: chatId,
213
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
214
+ remoteJidUsername: !isJidGroup(chatId)
215
+ ? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username
216
+ : undefined,
217
+ fromMe,
218
+ id: msgId,
219
+ participant,
220
+ participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
221
+ participantUsername: stanza.attrs.participant ? stanza.attrs.participant_username : undefined,
222
+ addressingMode: addressingContext.addressingMode,
223
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
224
+ };
225
+ const fullMessage = {
226
+ key,
227
+ category: stanza.attrs.category,
228
+ messageTimestamp: +stanza.attrs.t,
229
+ pushName: pushname,
230
+ broadcast: isJidBroadcast(from)
231
+ };
232
+ if (key.fromMe) {
233
+ fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
234
+ }
235
+ return {
236
+ fullMessage,
237
+ author,
238
+ sender: msgType === 'chat' ? author : chatId
239
+ };
240
+ }
241
+ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
242
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
243
+ return {
244
+ fullMessage,
245
+ category: stanza.attrs.category,
246
+ author,
247
+ async decrypt() {
248
+ let decryptables = 0;
249
+ if (Array.isArray(stanza.content)) {
250
+ for (const { tag, attrs, content } of stanza.content) {
251
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
252
+ const cert = proto.VerifiedNameCertificate.decode(content);
253
+ const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
254
+ fullMessage.verifiedBizName = details.verifiedName;
255
+ }
256
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
257
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
258
+ }
259
+ if (attrs.count && tag === 'enc') {
260
+ fullMessage.retryCount = Number(attrs.count);
261
+ }
262
+ if (tag !== 'enc' && tag !== 'plaintext') {
263
+ continue;
264
+ }
265
+ if (!(content instanceof Uint8Array)) {
266
+ continue;
267
+ }
268
+ decryptables += 1;
269
+ let msgBuffer;
270
+ const decryptionJid = await getDecryptionJid(author, repository);
271
+ if (tag !== 'plaintext') {
272
+ // TODO: Handle hosted devices
273
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
274
+ }
275
+ try {
276
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
277
+ switch (e2eType) {
278
+ case 'skmsg':
279
+ msgBuffer = await repository.decryptGroupMessage({
280
+ group: sender,
281
+ authorJid: author,
282
+ msg: content
283
+ });
284
+ break;
285
+ case 'pkmsg':
286
+ case 'msg':
287
+ msgBuffer = await repository.decryptMessage({
288
+ jid: decryptionJid,
289
+ type: e2eType,
290
+ ciphertext: content
291
+ });
292
+ break;
293
+ case 'plaintext':
294
+ msgBuffer = content;
295
+ break;
296
+ default:
297
+ throw new Error(`Unknown e2e type: ${e2eType}`);
298
+ }
299
+ let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer);
300
+ msg = msg.deviceSentMessage?.message || msg;
301
+ if (msg.senderKeyDistributionMessage) {
302
+ //eslint-disable-next-line max-depth
303
+ try {
304
+ await repository.processSenderKeyDistributionMessage({
305
+ authorJid: author,
306
+ item: msg.senderKeyDistributionMessage
307
+ });
308
+ }
309
+ catch (err) {
310
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
311
+ }
312
+ }
313
+ if (fullMessage.message) {
314
+ Object.assign(fullMessage.message, msg);
315
+ }
316
+ else {
317
+ fullMessage.message = msg;
318
+ }
319
+ }
320
+ catch (err) {
321
+ const errorContext = {
322
+ key: fullMessage.key,
323
+ err,
324
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
325
+ sender,
326
+ author,
327
+ isSessionRecordError: isSessionRecordError(err)
328
+ };
329
+ logger.error(errorContext, 'failed to decrypt message');
330
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
331
+ fullMessage.messageStubParameters = [err.message.toString()];
332
+ }
333
+ }
334
+ }
335
+ // if nothing was found to decrypt
336
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
337
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
338
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
339
+ }
340
+ }
341
+ };
342
+ };
343
+ /**
344
+ * Utility function to check if an error is related to missing session record
345
+ */
346
+ function isSessionRecordError(error) {
347
+ const errorMessage = error?.message || error?.toString() || '';
348
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
349
+ }
350
+ //# sourceMappingURL=decode-wa-message.js.map