@vanzxy/baileys 1.4.1 → 1.4.2

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.

Potentially problematic release.


This version of @vanzxy/baileys might be problematic. Click here for more details.

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