keith-baileys 1.0.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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/WAProto/GenerateStatics.sh +2 -0
  4. package/WAProto/WAProto.proto +4633 -0
  5. package/WAProto/index.js +165029 -0
  6. package/WAProto/keith +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/Keith +1 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.js +105 -0
  11. package/lib/Signal/Group/Keith +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.js +34 -0
  19. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  20. package/lib/Signal/Group/sender-key-message.js +69 -0
  21. package/lib/Signal/Group/sender-key-name.js +51 -0
  22. package/lib/Signal/Group/sender-key-record.js +53 -0
  23. package/lib/Signal/Group/sender-key-state.js +99 -0
  24. package/lib/Signal/Group/sender-message-key.js +29 -0
  25. package/lib/Signal/Keith +1 -0
  26. package/lib/Signal/libsignal.js +174 -0
  27. package/lib/Socket/Client/Keith +1 -0
  28. package/lib/Socket/Client/index.js +18 -0
  29. package/lib/Socket/Client/types.js +13 -0
  30. package/lib/Socket/Client/websocket.js +62 -0
  31. package/lib/Socket/Keith +1 -0
  32. package/lib/Socket/business.js +260 -0
  33. package/lib/Socket/chats.js +880 -0
  34. package/lib/Socket/groups.js +340 -0
  35. package/lib/Socket/groupstatus.js +237 -0
  36. package/lib/Socket/index.js +10 -0
  37. package/lib/Socket/messages-recv.js +1077 -0
  38. package/lib/Socket/messages-send.js +988 -0
  39. package/lib/Socket/mex.js +46 -0
  40. package/lib/Socket/newsletter.js +233 -0
  41. package/lib/Socket/socket.js +617 -0
  42. package/lib/Socket/usync.js +65 -0
  43. package/lib/Types/Auth.js +2 -0
  44. package/lib/Types/Call.js +2 -0
  45. package/lib/Types/Chat.js +10 -0
  46. package/lib/Types/Contact.js +2 -0
  47. package/lib/Types/Events.js +2 -0
  48. package/lib/Types/GroupMetadata.js +2 -0
  49. package/lib/Types/Keith +1 -0
  50. package/lib/Types/Label.js +27 -0
  51. package/lib/Types/LabelAssociation.js +9 -0
  52. package/lib/Types/Message.js +7 -0
  53. package/lib/Types/Newsletter.js +33 -0
  54. package/lib/Types/Product.js +2 -0
  55. package/lib/Types/Signal.js +2 -0
  56. package/lib/Types/Socket.js +2 -0
  57. package/lib/Types/State.js +2 -0
  58. package/lib/Types/USync.js +2 -0
  59. package/lib/Types/index.js +42 -0
  60. package/lib/Utils/Keith +1 -0
  61. package/lib/Utils/auth-utils.js +199 -0
  62. package/lib/Utils/baileys-event-stream.js +63 -0
  63. package/lib/Utils/business.js +240 -0
  64. package/lib/Utils/chat-utils.js +741 -0
  65. package/lib/Utils/crypto.js +187 -0
  66. package/lib/Utils/decode-wa-message.js +283 -0
  67. package/lib/Utils/event-buffer.js +516 -0
  68. package/lib/Utils/generics.js +400 -0
  69. package/lib/Utils/history.js +100 -0
  70. package/lib/Utils/index.js +34 -0
  71. package/lib/Utils/lid-mapping.js +88 -0
  72. package/lib/Utils/link-preview.js +122 -0
  73. package/lib/Utils/logger.js +7 -0
  74. package/lib/Utils/lt-hash.js +51 -0
  75. package/lib/Utils/make-mutex.js +44 -0
  76. package/lib/Utils/messages-media.js +706 -0
  77. package/lib/Utils/messages.js +797 -0
  78. package/lib/Utils/noise-handler.js +150 -0
  79. package/lib/Utils/process-message.js +381 -0
  80. package/lib/Utils/signal.js +155 -0
  81. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  82. package/lib/Utils/validate-connection.js +170 -0
  83. package/lib/WABinary/Keith +1 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +266 -0
  86. package/lib/WABinary/encode.js +252 -0
  87. package/lib/WABinary/generic-utils.js +110 -0
  88. package/lib/WABinary/index.js +21 -0
  89. package/lib/WABinary/jid-utils.js +66 -0
  90. package/lib/WABinary/types.js +2 -0
  91. package/lib/WAM/BinaryInfo.js +13 -0
  92. package/lib/WAM/constants.js +15243 -0
  93. package/lib/WAM/encode.js +153 -0
  94. package/lib/WAM/index.js +19 -0
  95. package/lib/WAM/keith +1 -0
  96. package/lib/WAUSync/Keith +1 -0
  97. package/lib/WAUSync/Protocols/Keith +1 -0
  98. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  99. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  100. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  103. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  104. package/lib/WAUSync/Protocols/index.js +20 -0
  105. package/lib/WAUSync/USyncQuery.js +93 -0
  106. package/lib/WAUSync/USyncUser.js +26 -0
  107. package/lib/WAUSync/index.js +19 -0
  108. package/lib/index.js +30 -0
  109. package/package.json +32 -0
@@ -0,0 +1,187 @@
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 = 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.md5 = md5;
48
+ exports.hkdf = hkdf;
49
+ exports.derivePairingCodeKey = derivePairingCodeKey;
50
+ const crypto_1 = require("crypto");
51
+ const libsignal = __importStar(require("libsignal"));
52
+ const Defaults_1 = require("../Defaults");
53
+ // insure browser & node compatibility
54
+ const { subtle } = globalThis.crypto;
55
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
56
+ const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([Defaults_1.KEY_BUNDLE_TYPE, pubKey]);
57
+ exports.generateSignalPubKey = generateSignalPubKey;
58
+ exports.Curve = {
59
+ generateKeyPair: () => {
60
+ const { pubKey, privKey } = libsignal.curve.generateKeyPair();
61
+ return {
62
+ private: Buffer.from(privKey),
63
+ // remove version byte
64
+ public: Buffer.from(pubKey.slice(1))
65
+ };
66
+ },
67
+ sharedKey: (privateKey, publicKey) => {
68
+ const shared = libsignal.curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
69
+ return Buffer.from(shared);
70
+ },
71
+ sign: (privateKey, buf) => libsignal.curve.calculateSignature(privateKey, buf),
72
+ verify: (pubKey, message, signature) => {
73
+ try {
74
+ libsignal.curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
75
+ return true;
76
+ }
77
+ catch (error) {
78
+ return false;
79
+ }
80
+ }
81
+ };
82
+ const signedKeyPair = (identityKeyPair, keyId) => {
83
+ const preKey = exports.Curve.generateKeyPair();
84
+ const pubKey = (0, exports.generateSignalPubKey)(preKey.public);
85
+ const signature = exports.Curve.sign(identityKeyPair.private, pubKey);
86
+ return { keyPair: preKey, signature, keyId };
87
+ };
88
+ exports.signedKeyPair = signedKeyPair;
89
+ const GCM_TAG_LENGTH = 128 >> 3;
90
+ /**
91
+ * encrypt AES 256 GCM;
92
+ * where the tag tag is suffixed to the ciphertext
93
+ * */
94
+ function aesEncryptGCM(plaintext, key, iv, additionalData) {
95
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
96
+ cipher.setAAD(additionalData);
97
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
98
+ }
99
+ /**
100
+ * decrypt AES 256 GCM;
101
+ * where the auth tag is suffixed to the ciphertext
102
+ * */
103
+ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
104
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
105
+ // decrypt additional adata
106
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
107
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
108
+ // set additional data
109
+ decipher.setAAD(additionalData);
110
+ decipher.setAuthTag(tag);
111
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
112
+ }
113
+ function aesEncryptCTR(plaintext, key, iv) {
114
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
115
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
116
+ }
117
+ function aesDecryptCTR(ciphertext, key, iv) {
118
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
119
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
120
+ }
121
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
122
+ function aesDecrypt(buffer, key) {
123
+ return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
124
+ }
125
+ /** decrypt AES 256 CBC */
126
+ function aesDecryptWithIV(buffer, key, IV) {
127
+ const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
128
+ return Buffer.concat([aes.update(buffer), aes.final()]);
129
+ }
130
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
131
+ function aesEncrypt(buffer, key) {
132
+ const IV = (0, crypto_1.randomBytes)(16);
133
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
134
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
135
+ }
136
+ // encrypt AES 256 CBC with a given IV
137
+ function aesEncrypWithIV(buffer, key, IV) {
138
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
139
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
140
+ }
141
+ // sign HMAC using SHA 256
142
+ function hmacSign(buffer, key, variant = 'sha256') {
143
+ return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
144
+ }
145
+ function sha256(buffer) {
146
+ return (0, crypto_1.createHash)('sha256').update(buffer).digest();
147
+ }
148
+ function md5(buffer) {
149
+ return (0, crypto_1.createHash)('md5').update(buffer).digest();
150
+ }
151
+ // HKDF key expansion
152
+ async function hkdf(buffer, expandedLength, info) {
153
+ // Ensure we have a Uint8Array for the key material
154
+ const inputKeyMaterial = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
155
+ // Set default values if not provided
156
+ const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
157
+ const infoBytes = info.info ? new TextEncoder().encode(info.info) : new Uint8Array(0);
158
+ // Import the input key material
159
+ const importedKey = await subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits']);
160
+ // Derive bits using HKDF
161
+ const derivedBits = await subtle.deriveBits({
162
+ name: 'HKDF',
163
+ hash: 'SHA-256',
164
+ salt: salt,
165
+ info: infoBytes
166
+ }, importedKey, expandedLength * 8 // Convert bytes to bits
167
+ );
168
+ return Buffer.from(derivedBits);
169
+ }
170
+ async function derivePairingCodeKey(pairingCode, salt) {
171
+ // Convert inputs to formats Web Crypto API can work with
172
+ const encoder = new TextEncoder();
173
+ const pairingCodeBuffer = encoder.encode(pairingCode);
174
+ const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
175
+ // Import the pairing code as key material
176
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits']);
177
+ // Derive bits using PBKDF2 with the same parameters
178
+ // 2 << 16 = 131,072 iterations
179
+ const derivedBits = await subtle.deriveBits({
180
+ name: 'PBKDF2',
181
+ salt: saltBuffer,
182
+ iterations: 2 << 16,
183
+ hash: 'SHA-256'
184
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
185
+ );
186
+ return Buffer.from(derivedBits);
187
+ }
@@ -0,0 +1,283 @@
1
+ "use strict";
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;
4
+ exports.decodeMessageNode = decodeMessageNode;
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");
9
+ const lid_mapping_1 = require("./lid-mapping");
10
+ exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
11
+ exports.MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
12
+ exports.NACK_REASONS = {
13
+ ParsingError: 487,
14
+ UnrecognizedStanza: 488,
15
+ UnrecognizedStanzaClass: 489,
16
+ UnrecognizedStanzaType: 490,
17
+ InvalidProtobuf: 491,
18
+ InvalidHostedCompanionStanza: 493,
19
+ MissingMessageSecret: 495,
20
+ SignalErrorOldCounter: 496,
21
+ MessageDeletedOnPeer: 499,
22
+ UnhandledError: 500,
23
+ UnsupportedAdminRevoke: 550,
24
+ UnsupportedLIDGroup: 551,
25
+ DBOperationFailed: 552
26
+ };
27
+ /**
28
+ * Decode the received node as a message.
29
+ * @note this will only parse the message, not decrypt it
30
+ */
31
+ function decodeMessageNode(stanza, meId, meLid) {
32
+ var _a, _b, _c, _d, _e;
33
+ let msgType;
34
+ let chatId;
35
+ let author;
36
+ const msgId = stanza.attrs.id;
37
+ const from = stanza.attrs.from;
38
+ const participant = stanza.attrs.participant;
39
+ const recipient = stanza.attrs.recipient;
40
+ const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
41
+ const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
42
+ if ((0, WABinary_1.isJidUser)(from) || (0, WABinary_1.isLidUser)(from)) {
43
+ if (recipient && !(0, WABinary_1.isJidMetaIa)(recipient)) {
44
+ if (!isMe(from) && !isMeLid(from)) {
45
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
46
+ }
47
+ chatId = recipient;
48
+ }
49
+ else {
50
+ chatId = from;
51
+ }
52
+ msgType = 'chat';
53
+ author = from;
54
+ }
55
+ else if ((0, WABinary_1.isJidGroup)(from)) {
56
+ if (!participant) {
57
+ throw new boom_1.Boom('No participant in group message');
58
+ }
59
+ msgType = 'group';
60
+ author = participant;
61
+ chatId = from;
62
+ }
63
+ else if ((0, WABinary_1.isJidBroadcast)(from)) {
64
+ if (!participant) {
65
+ throw new boom_1.Boom('No participant in group message');
66
+ }
67
+ const isParticipantMe = isMe(participant);
68
+ if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
69
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
70
+ }
71
+ else {
72
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
73
+ }
74
+ chatId = from;
75
+ author = participant;
76
+ }
77
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
78
+ msgType = 'newsletter';
79
+ chatId = from;
80
+ author = from;
81
+ }
82
+ else {
83
+ throw new boom_1.Boom('Unknown message type', { data: stanza });
84
+ }
85
+ const fromMe = ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
86
+ const pushname = (_a = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _a === void 0 ? void 0 : _a.notify;
87
+ let senderLidValue = (_b = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _b === void 0 ? void 0 : _b.sender_lid;
88
+ let senderPnValue = (_c = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _c === void 0 ? void 0 : _c.sender_pn;
89
+ if (fromMe && !senderPnValue && meId) {
90
+ const mePhone = meId.split(':')[0];
91
+ if (mePhone && /^\d+$/.test(mePhone)) {
92
+ senderPnValue = mePhone + '@s.whatsapp.net';
93
+ }
94
+ }
95
+ if (fromMe && !senderLidValue && meLid) {
96
+ senderLidValue = meLid;
97
+ }
98
+ if (msgType === 'chat') {
99
+ if (!fromMe) {
100
+ if ((0, WABinary_1.isJidUser)(chatId) && !senderPnValue) {
101
+ senderPnValue = (0, WABinary_1.jidNormalizedUser)(chatId);
102
+ }
103
+ if ((0, WABinary_1.isJidUser)(chatId) && !senderLidValue) {
104
+ const normalizedChatId = (0, WABinary_1.jidNormalizedUser)(chatId);
105
+ const possibleLid = lid_mapping_1.globalLidMapping.getLidFromPn(normalizedChatId);
106
+ if (possibleLid) {
107
+ senderLidValue = possibleLid;
108
+ }
109
+ }
110
+ if ((0, WABinary_1.isLidUser)(chatId) && !senderLidValue) {
111
+ senderLidValue = chatId;
112
+ }
113
+ if (senderLidValue && !senderPnValue) {
114
+ senderPnValue = lid_mapping_1.globalLidMapping.getPnFromLid(senderLidValue);
115
+ }
116
+ if (senderLidValue) {
117
+ chatId = senderLidValue;
118
+ }
119
+ } else {
120
+ if ((0, WABinary_1.isJidUser)(chatId) && !senderLidValue) {
121
+ const normalizedChatId = (0, WABinary_1.jidNormalizedUser)(chatId);
122
+ const possibleLid = lid_mapping_1.globalLidMapping.getLidFromPn(normalizedChatId);
123
+ if (possibleLid) {
124
+ senderLidValue = possibleLid;
125
+ }
126
+ }
127
+ if (senderLidValue && !senderPnValue) {
128
+ senderPnValue = lid_mapping_1.globalLidMapping.getPnFromLid(senderLidValue);
129
+ }
130
+ if ((0, WABinary_1.isLidUser)(chatId) && !senderPnValue) {
131
+ senderPnValue = lid_mapping_1.globalLidMapping.getPnFromLid(chatId);
132
+ }
133
+ }
134
+ }
135
+ if (senderPnValue) {
136
+ senderPnValue = (0, WABinary_1.jidNormalizedUser)(senderPnValue);
137
+ }
138
+ if (senderLidValue && senderPnValue) {
139
+ lid_mapping_1.globalLidMapping.set(senderLidValue, senderPnValue);
140
+ }
141
+ let participantPnValue = (_d = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _d === void 0 ? void 0 : _d.participant_pn;
142
+ let participantLidValue = (_e = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _e === void 0 ? void 0 : _e.participant_lid;
143
+ if (msgType === 'group' || msgType === 'peer_broadcast' || msgType === 'other_broadcast') {
144
+ if (!participantPnValue) {
145
+ participantPnValue = senderPnValue || (stanza === null || stanza === void 0 ? void 0 : stanza.attrs.sender_pn) || (stanza === null || stanza === void 0 ? void 0 : stanza.attrs.peer_recipient_pn);
146
+ }
147
+ if (!participantLidValue) {
148
+ participantLidValue = senderLidValue || (stanza === null || stanza === void 0 ? void 0 : stanza.attrs.sender_lid) || (stanza === null || stanza === void 0 ? void 0 : stanza.attrs.peer_recipient_lid);
149
+ }
150
+ if (!participantLidValue && participant && (0, WABinary_1.isLidUser)(participant)) {
151
+ participantLidValue = participant;
152
+ }
153
+ if (!participantPnValue && participantLidValue) {
154
+ participantPnValue = lid_mapping_1.globalLidMapping.getPnFromLid(participantLidValue);
155
+ }
156
+ if (!participantPnValue && participant && (0, WABinary_1.isLidUser)(participant)) {
157
+ participantPnValue = lid_mapping_1.globalLidMapping.getPnFromLid(participant);
158
+ }
159
+ if (fromMe && !participantPnValue && meId) {
160
+ const mePhone = meId.split(':')[0];
161
+ if (mePhone && /^\d+$/.test(mePhone)) {
162
+ participantPnValue = mePhone + '@s.whatsapp.net';
163
+ }
164
+ }
165
+ if (fromMe && !participantLidValue && meLid) {
166
+ participantLidValue = meLid;
167
+ }
168
+ if (participantLidValue && participantPnValue) {
169
+ lid_mapping_1.globalLidMapping.set(participantLidValue, participantPnValue);
170
+ }
171
+ }
172
+ const key = {
173
+ remoteJid: chatId,
174
+ fromMe,
175
+ id: msgId,
176
+ ...(senderLidValue ? { senderLid: senderLidValue } : {}),
177
+ ...(senderPnValue ? { senderPn: senderPnValue } : {}),
178
+ ...(participant ? { participant } : {}),
179
+ ...(participantPnValue ? { participantPn: participantPnValue } : {}),
180
+ ...(participantLidValue ? { participantLid: participantLidValue } : {}),
181
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
182
+ };
183
+ const fullMessage = {
184
+ key,
185
+ messageTimestamp: +stanza.attrs.t,
186
+ pushName: pushname,
187
+ broadcast: (0, WABinary_1.isJidBroadcast)(from)
188
+ };
189
+ if (key.fromMe) {
190
+ fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
191
+ }
192
+ return {
193
+ fullMessage,
194
+ author,
195
+ sender: msgType === 'chat' ? author : chatId
196
+ };
197
+ }
198
+ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
199
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
200
+ return {
201
+ fullMessage,
202
+ category: stanza.attrs.category,
203
+ author,
204
+ async decrypt() {
205
+ var _a;
206
+ let decryptables = 0;
207
+ if (Array.isArray(stanza.content)) {
208
+ for (const { tag, attrs, content } of stanza.content) {
209
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
210
+ const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
211
+ const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
212
+ fullMessage.verifiedBizName = details.verifiedName;
213
+ }
214
+ if (tag !== 'enc' && tag !== 'plaintext') {
215
+ continue;
216
+ }
217
+ if (!(content instanceof Uint8Array)) {
218
+ continue;
219
+ }
220
+ decryptables += 1;
221
+ let msgBuffer;
222
+ try {
223
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
224
+ switch (e2eType) {
225
+ case 'skmsg':
226
+ msgBuffer = await repository.decryptGroupMessage({
227
+ group: sender,
228
+ authorJid: author,
229
+ msg: content
230
+ });
231
+ break;
232
+ case 'pkmsg':
233
+ case 'msg':
234
+ const user = (0, WABinary_1.isJidUser)(sender) ? sender : author;
235
+ msgBuffer = await repository.decryptMessage({
236
+ jid: user,
237
+ type: e2eType,
238
+ ciphertext: content
239
+ });
240
+ break;
241
+ case 'plaintext':
242
+ msgBuffer = content;
243
+ break;
244
+ default:
245
+ throw new Error(`Unknown e2e type: ${e2eType}`);
246
+ }
247
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
248
+ msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
249
+ if (msg.senderKeyDistributionMessage) {
250
+ //eslint-disable-next-line max-depth
251
+ try {
252
+ await repository.processSenderKeyDistributionMessage({
253
+ authorJid: author,
254
+ item: msg.senderKeyDistributionMessage
255
+ });
256
+ }
257
+ catch (err) {
258
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
259
+ }
260
+ }
261
+ if (fullMessage.message) {
262
+ Object.assign(fullMessage.message, msg);
263
+ }
264
+ else {
265
+ fullMessage.message = msg;
266
+ }
267
+ }
268
+ catch (err) {
269
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
270
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
271
+ fullMessage.messageStubParameters = [err.message];
272
+ }
273
+ }
274
+ }
275
+ // if nothing was found to decrypt
276
+ if (!decryptables) {
277
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
278
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
279
+ }
280
+ }
281
+ };
282
+ };
283
+ exports.decryptMessageNode = decryptMessageNode;