@yemo-dev/yebail 1.0.0

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 (106) hide show
  1. package/EXAMPLES.md +641 -0
  2. package/LICENSE +21 -0
  3. package/README.md +141 -0
  4. package/WAProto/GenerateStatics.sh +4 -0
  5. package/WAProto/WAProto.proto +4775 -0
  6. package/WAProto/index.js +116311 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +142 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Defaults/yebail-version.json +7 -0
  11. package/lib/Signal/Group/ciphertext-message.js +15 -0
  12. package/lib/Signal/Group/group-session-builder.js +64 -0
  13. package/lib/Signal/Group/group_cipher.js +96 -0
  14. package/lib/Signal/Group/index.js +57 -0
  15. package/lib/Signal/Group/keyhelper.js +55 -0
  16. package/lib/Signal/Group/queue-job.js +57 -0
  17. package/lib/Signal/Group/sender-chain-key.js +34 -0
  18. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  19. package/lib/Signal/Group/sender-key-message.js +69 -0
  20. package/lib/Signal/Group/sender-key-name.js +51 -0
  21. package/lib/Signal/Group/sender-key-record.js +53 -0
  22. package/lib/Signal/Group/sender-key-state.js +99 -0
  23. package/lib/Signal/Group/sender-message-key.js +29 -0
  24. package/lib/Signal/libsignal.js +196 -0
  25. package/lib/Signal/lid-mapping.js +148 -0
  26. package/lib/Socket/Client/index.js +18 -0
  27. package/lib/Socket/Client/types.js +13 -0
  28. package/lib/Socket/Client/websocket.js +72 -0
  29. package/lib/Socket/business.js +368 -0
  30. package/lib/Socket/chats.js +992 -0
  31. package/lib/Socket/communities.js +430 -0
  32. package/lib/Socket/groups.js +323 -0
  33. package/lib/Socket/index.js +10 -0
  34. package/lib/Socket/messages-recv.js +1133 -0
  35. package/lib/Socket/messages-send.js +992 -0
  36. package/lib/Socket/newsletter.js +250 -0
  37. package/lib/Socket/socket.js +631 -0
  38. package/lib/Socket/usync.js +70 -0
  39. package/lib/Store/index.js +8 -0
  40. package/lib/Store/make-in-memory-store.js +421 -0
  41. package/lib/Store/make-ordered-dictionary.js +81 -0
  42. package/lib/Store/object-repository.js +27 -0
  43. package/lib/Types/Auth.js +2 -0
  44. package/lib/Types/Call.js +2 -0
  45. package/lib/Types/Chat.js +4 -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/Label.js +27 -0
  50. package/lib/Types/LabelAssociation.js +9 -0
  51. package/lib/Types/Message.js +7 -0
  52. package/lib/Types/Newsletter.js +18 -0
  53. package/lib/Types/Product.js +2 -0
  54. package/lib/Types/Signal.js +2 -0
  55. package/lib/Types/Socket.js +2 -0
  56. package/lib/Types/State.js +2 -0
  57. package/lib/Types/USync.js +2 -0
  58. package/lib/Types/index.js +42 -0
  59. package/lib/Utils/auth-utils.js +188 -0
  60. package/lib/Utils/browser-utils.js +35 -0
  61. package/lib/Utils/business.js +230 -0
  62. package/lib/Utils/chat-utils.js +763 -0
  63. package/lib/Utils/crypto.js +187 -0
  64. package/lib/Utils/decode-wa-message.js +293 -0
  65. package/lib/Utils/event-buffer.js +514 -0
  66. package/lib/Utils/generics.js +453 -0
  67. package/lib/Utils/history.js +94 -0
  68. package/lib/Utils/index.js +37 -0
  69. package/lib/Utils/link-preview.js +121 -0
  70. package/lib/Utils/logger.js +7 -0
  71. package/lib/Utils/lt-hash.js +47 -0
  72. package/lib/Utils/make-mutex.js +43 -0
  73. package/lib/Utils/message-retry-manager.js +128 -0
  74. package/lib/Utils/messages-media.js +910 -0
  75. package/lib/Utils/messages.js +1129 -0
  76. package/lib/Utils/noise-handler.js +150 -0
  77. package/lib/Utils/process-message.js +448 -0
  78. package/lib/Utils/signal.js +150 -0
  79. package/lib/Utils/use-custom-auth-state.js +110 -0
  80. package/lib/Utils/use-multi-file-auth-state.js +43 -0
  81. package/lib/Utils/use-sqlite-auth-state.js +39 -0
  82. package/lib/Utils/validate-connection.js +237 -0
  83. package/lib/Utils/yebail-event-stream.js +55 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +275 -0
  86. package/lib/WABinary/encode.js +250 -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 +136 -0
  90. package/lib/WABinary/types.js +2 -0
  91. package/lib/WAM/BinaryInfo.js +13 -0
  92. package/lib/WAM/constants.js +15350 -0
  93. package/lib/WAM/encode.js +155 -0
  94. package/lib/WAM/index.js +19 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  101. package/lib/WAUSync/Protocols/index.js +20 -0
  102. package/lib/WAUSync/USyncQuery.js +89 -0
  103. package/lib/WAUSync/USyncUser.js +26 -0
  104. package/lib/WAUSync/index.js +19 -0
  105. package/lib/index.js +46 -0
  106. package/package.json +114 -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
+
56
+ const generateSignalPubKey = (pubKey) => (pubKey.length === 33
57
+ ? pubKey
58
+ : Buffer.concat([Defaults_1.KEY_BUNDLE_TYPE, pubKey]));
59
+ exports.generateSignalPubKey = generateSignalPubKey;
60
+ exports.Curve = {
61
+ generateKeyPair: () => {
62
+ const { pubKey, privKey } = libsignal.curve.generateKeyPair();
63
+ return {
64
+ private: Buffer.from(privKey),
65
+ // remove version byte
66
+ public: Buffer.from(pubKey.slice(1))
67
+ };
68
+ },
69
+ sharedKey: (privateKey, publicKey) => {
70
+ const shared = libsignal.curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
71
+ return Buffer.from(shared);
72
+ },
73
+ sign: (privateKey, buf) => (libsignal.curve.calculateSignature(privateKey, buf)),
74
+ verify: (pubKey, message, signature) => {
75
+ try {
76
+ libsignal.curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
77
+ return true;
78
+ }
79
+ catch (error) {
80
+ return false;
81
+ }
82
+ }
83
+ };
84
+ const signedKeyPair = (identityKeyPair, keyId) => {
85
+ const preKey = exports.Curve.generateKeyPair();
86
+ const pubKey = (0, exports.generateSignalPubKey)(preKey.public);
87
+ const signature = exports.Curve.sign(identityKeyPair.private, pubKey);
88
+ return { keyPair: preKey, signature, keyId };
89
+ };
90
+ exports.signedKeyPair = signedKeyPair;
91
+ const GCM_TAG_LENGTH = 128 >> 3;
92
+
93
+ function aesEncryptGCM(plaintext, key, iv, additionalData) {
94
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
95
+ cipher.setAAD(additionalData);
96
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
97
+ }
98
+
99
+ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
100
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
101
+ // decrypt additional adata
102
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
103
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
104
+ // set additional data
105
+ decipher.setAAD(additionalData);
106
+ decipher.setAuthTag(tag);
107
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
108
+ }
109
+ function aesEncryptCTR(plaintext, key, iv) {
110
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
111
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
112
+ }
113
+ function aesDecryptCTR(ciphertext, key, iv) {
114
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
115
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
116
+ }
117
+
118
+ function aesDecrypt(buffer, key) {
119
+ return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
120
+ }
121
+
122
+ function aesDecryptWithIV(buffer, key, IV) {
123
+ const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
124
+ return Buffer.concat([aes.update(buffer), aes.final()]);
125
+ }
126
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
127
+ function aesEncrypt(buffer, key) {
128
+ const IV = (0, crypto_1.randomBytes)(16);
129
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
130
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
131
+ }
132
+ // encrypt AES 256 CBC with a given IV
133
+ function aesEncrypWithIV(buffer, key, IV) {
134
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
135
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
136
+ }
137
+ // sign HMAC using SHA 256
138
+ function hmacSign(buffer, key, variant = 'sha256') {
139
+ return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
140
+ }
141
+ function sha256(buffer) {
142
+ return (0, crypto_1.createHash)('sha256').update(buffer).digest();
143
+ }
144
+ function md5(buffer) {
145
+ return (0, crypto_1.createHash)('md5').update(buffer).digest();
146
+ }
147
+ // HKDF key expansion
148
+ async function hkdf(buffer, expandedLength, info) {
149
+ // Ensure we have a Uint8Array for the key material
150
+ const inputKeyMaterial = buffer instanceof Uint8Array
151
+ ? buffer
152
+ : new Uint8Array(buffer);
153
+ // Set default values if not provided
154
+ const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
155
+ const infoBytes = info.info
156
+ ? new TextEncoder().encode(info.info)
157
+ : 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,293 @@
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
+ exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
10
+ exports.MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
11
+ exports.NACK_REASONS = {
12
+ ParsingError: 487,
13
+ UnrecognizedStanza: 488,
14
+ UnrecognizedStanzaClass: 489,
15
+ UnrecognizedStanzaType: 490,
16
+ InvalidProtobuf: 491,
17
+ InvalidHostedCompanionStanza: 493,
18
+ MissingMessageSecret: 495,
19
+ SignalErrorOldCounter: 496,
20
+ MessageDeletedOnPeer: 499,
21
+ UnhandledError: 500,
22
+ UnsupportedAdminRevoke: 550,
23
+ UnsupportedLIDGroup: 551,
24
+ DBOperationFailed: 552
25
+ };
26
+ /**
27
+ * Derives PN/LID alternates from stanza attrs (same rules as WhiskeySockets Baileys).
28
+ */
29
+ function extractAddressingContext(stanza) {
30
+ let senderAlt;
31
+ let recipientAlt;
32
+ const sender = stanza.attrs.participant || stanza.attrs.from;
33
+ const isLidAddr = typeof sender === 'string' && (sender.endsWith('@lid') || sender.endsWith('@hosted.lid'));
34
+ const addressingMode = stanza.attrs.addressing_mode || (isLidAddr ? 'lid' : 'pn');
35
+ if (addressingMode === 'lid') {
36
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
37
+ recipientAlt = stanza.attrs.recipient_pn;
38
+ }
39
+ else {
40
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
41
+ recipientAlt = stanza.attrs.recipient_lid;
42
+ }
43
+ return { addressingMode, senderAlt, recipientAlt };
44
+ }
45
+ async function getDecryptionJid(sender, repository) {
46
+ if ((0, WABinary_1.isLidUser)(sender) || (0, WABinary_1.isHostedLidUser)(sender)) {
47
+ return sender;
48
+ }
49
+ const mapped = repository.lidMapping ? await repository.lidMapping.getLIDForPN(sender) : null;
50
+ return mapped || sender;
51
+ }
52
+ exports.getDecryptionJid = getDecryptionJid;
53
+ async function storeMappingFromEnvelope(stanza, sender, repository, decryptionJid, logger) {
54
+ const { senderAlt } = extractAddressingContext(stanza);
55
+ if (senderAlt && (0, WABinary_1.isLidUser)(senderAlt) && (0, WABinary_1.isPnUser)(sender) && decryptionJid === sender && repository.lidMapping) {
56
+ try {
57
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }]);
58
+ await repository.migrateSession(sender, senderAlt);
59
+ logger.debug({ sender, senderAlt }, 'stored LID mapping from envelope');
60
+ }
61
+ catch (error) {
62
+ logger.warn({ sender, senderAlt, error }, 'failed to store LID mapping');
63
+ }
64
+ }
65
+ }
66
+ /**
67
+ * Parses the inbound node. When WhatsApp sends both PN and LID, keys use LID as the primary
68
+ * address (remoteJid / participant) and put PN on *Alt fields, consistent with lidMapping LID↔PN storage.
69
+ */
70
+ function decodeMessageNode(stanza, meId, meLid) {
71
+ var _a, _b, _c, _d, _e, _f, _g, _h;
72
+ let msgType;
73
+ let chatId;
74
+ let author;
75
+ const msgId = stanza.attrs.id;
76
+ const from = stanza.attrs.from;
77
+ const senderPn = (_a = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _a === void 0 ? void 0 : _a.sender_pn;
78
+ const senderLid = (_b = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _b === void 0 ? void 0 : _b.sender_lid;
79
+ const participant = stanza.attrs.participant;
80
+ const participantLid = (_c = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _c === void 0 ? void 0 : _c.participant_lid;
81
+ const recipientLidAttr = (_h = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _h === void 0 ? void 0 : _h.recipient_lid;
82
+ const recipient = stanza.attrs.recipient;
83
+ const addressingContext = extractAddressingContext(stanza);
84
+ const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
85
+ const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
86
+ if ((0, WABinary_1.isPnUser)(from) || (0, WABinary_1.isLidUser)(from) || (0, WABinary_1.isHostedLidUser)(from) || (0, WABinary_1.isHostedPnUser)(from)) {
87
+ if (recipient && !(0, WABinary_1.isJidMetaAi)(recipient)) {
88
+ if (!isMe(from) && !isMeLid(from)) {
89
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
90
+ }
91
+ chatId = recipient;
92
+ }
93
+ else {
94
+ chatId = from;
95
+ }
96
+ msgType = 'chat';
97
+ author = from;
98
+ }
99
+ else if ((0, WABinary_1.isJidGroup)(from)) {
100
+ if (!participant) {
101
+ throw new boom_1.Boom('No participant in group message');
102
+ }
103
+ msgType = 'group';
104
+ author = participant;
105
+ chatId = from;
106
+ }
107
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
108
+ msgType = 'newsletter';
109
+ author = from;
110
+ chatId = from;
111
+ }
112
+ else if ((0, WABinary_1.isJidBroadcast)(from)) {
113
+ if (!participant) {
114
+ throw new boom_1.Boom('No participant in group message');
115
+ }
116
+ const isParticipantMe = isMe(participant);
117
+ if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
118
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
119
+ }
120
+ else {
121
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
122
+ }
123
+ chatId = from;
124
+ author = participant;
125
+ }
126
+ else {
127
+ throw new boom_1.Boom('Unknown message type', { data: stanza });
128
+ }
129
+ 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);
130
+ const pushname = (_e = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _e === void 0 ? void 0 : _e.notify;
131
+ let resolvedRemoteJid = chatId;
132
+ let resolvedRemoteJidAlt = !(0, WABinary_1.isJidGroup)(chatId) ? addressingContext.senderAlt : undefined;
133
+ let resolvedParticipant = participant;
134
+ let resolvedParticipantAlt = (0, WABinary_1.isJidGroup)(chatId) ? addressingContext.senderAlt : undefined;
135
+ if (msgType === 'chat' && !(0, WABinary_1.isJidGroup)(chatId) && !(0, WABinary_1.isJidNewsletter)(chatId) && !(0, WABinary_1.isJidBroadcast)(chatId)) {
136
+ if ((0, WABinary_1.isPnUser)(chatId) && senderLid && (0, WABinary_1.isLidUser)(senderLid)) {
137
+ resolvedRemoteJid = senderLid;
138
+ resolvedRemoteJidAlt = chatId;
139
+ }
140
+ else if ((0, WABinary_1.isPnUser)(chatId) && recipientLidAttr && (0, WABinary_1.isLidUser)(recipientLidAttr)) {
141
+ resolvedRemoteJid = recipientLidAttr;
142
+ resolvedRemoteJidAlt = chatId;
143
+ }
144
+ else if (addressingContext.addressingMode === 'lid' && ((0, WABinary_1.isLidUser)(chatId) || (0, WABinary_1.isHostedLidUser)(chatId))) {
145
+ resolvedRemoteJid = chatId;
146
+ resolvedRemoteJidAlt = addressingContext.senderAlt;
147
+ }
148
+ }
149
+ if (msgType === 'group' && (0, WABinary_1.isJidGroup)(chatId) && participant) {
150
+ if (participantLid && (0, WABinary_1.isLidUser)(participantLid)) {
151
+ resolvedParticipant = participantLid;
152
+ resolvedParticipantAlt = (0, WABinary_1.isPnUser)(participant) ? participant : addressingContext.senderAlt;
153
+ }
154
+ else if (addressingContext.addressingMode === 'lid' && ((0, WABinary_1.isLidUser)(participant) || (0, WABinary_1.isHostedLidUser)(participant))) {
155
+ resolvedParticipant = participant;
156
+ resolvedParticipantAlt = addressingContext.senderAlt;
157
+ }
158
+ }
159
+ let resolvedLidKey = senderLid || participantLid;
160
+ if (msgType === 'group' && resolvedParticipant && (0, WABinary_1.isLidUser)(resolvedParticipant)) {
161
+ resolvedLidKey = resolvedParticipant;
162
+ }
163
+ else if (msgType === 'chat' && (0, WABinary_1.isLidUser)(resolvedRemoteJid)) {
164
+ resolvedLidKey = resolvedRemoteJid;
165
+ }
166
+ const key = {
167
+ remoteJid: resolvedRemoteJid,
168
+ remoteJidAlt: !(0, WABinary_1.isJidGroup)(resolvedRemoteJid) ? resolvedRemoteJidAlt : undefined,
169
+ fromMe,
170
+ id: msgId,
171
+ senderPn,
172
+ senderLid,
173
+ lid: resolvedLidKey,
174
+ participant: resolvedParticipant,
175
+ participantAlt: (0, WABinary_1.isJidGroup)(resolvedRemoteJid) ? resolvedParticipantAlt : undefined,
176
+ participantLid,
177
+ addressingMode: addressingContext.addressingMode,
178
+ 'server_id': (_f = stanza.attrs) === null || _f === void 0 ? void 0 : _f.server_id
179
+ };
180
+ const fullMessage = {
181
+ key,
182
+ messageTimestamp: +stanza.attrs.t,
183
+ pushName: pushname,
184
+ broadcast: (0, WABinary_1.isJidBroadcast)(from)
185
+ };
186
+ if (msgType === 'newsletter') {
187
+ fullMessage.newsletterServerId = +((_g = stanza.attrs) === null || _g === void 0 ? void 0 : _g.server_id);
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 === 'unavailable' && attrs.type === 'view_once') {
215
+ fullMessage.key.isViewOnce = true;
216
+ }
217
+ if (tag !== 'enc' && tag !== 'plaintext') {
218
+ continue;
219
+ }
220
+ if (!(content instanceof Uint8Array)) {
221
+ continue;
222
+ }
223
+ decryptables += 1;
224
+ let msgBuffer;
225
+ try {
226
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
227
+ switch (e2eType) {
228
+ case 'skmsg':
229
+ msgBuffer = await repository.decryptGroupMessage({
230
+ group: sender,
231
+ authorJid: author,
232
+ msg: content
233
+ });
234
+ break;
235
+ case 'pkmsg':
236
+ case 'msg': {
237
+ const decryptionJid = await getDecryptionJid(author, repository);
238
+ if (tag !== 'plaintext') {
239
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
240
+ }
241
+ msgBuffer = await repository.decryptMessage({
242
+ jid: decryptionJid,
243
+ type: e2eType,
244
+ ciphertext: content
245
+ });
246
+ break;
247
+ }
248
+ case 'plaintext':
249
+ msgBuffer = content;
250
+ break;
251
+ case undefined:
252
+ msgBuffer = content;
253
+ break;
254
+ default:
255
+ throw new Error(`Unknown e2e type: ${e2eType}`);
256
+ }
257
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
258
+ msg = ((_a = msg === null || msg === void 0 ? void 0 : msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
259
+ if (msg.senderKeyDistributionMessage) {
260
+ try {
261
+ await repository.processSenderKeyDistributionMessage({
262
+ authorJid: author,
263
+ item: msg.senderKeyDistributionMessage
264
+ });
265
+ }
266
+ catch (err) {
267
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
268
+ }
269
+ }
270
+ if (fullMessage.message) {
271
+ Object.assign(fullMessage.message, msg);
272
+ }
273
+ else {
274
+ fullMessage.message = msg;
275
+ }
276
+ }
277
+ catch (err) {
278
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
279
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
280
+ fullMessage.messageStubParameters = [err.message];
281
+ }
282
+ }
283
+ }
284
+ // if nothing was found to decrypt
285
+ if (!decryptables) {
286
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
287
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
288
+ }
289
+ }
290
+ };
291
+ };
292
+ exports.decryptMessageNode = decryptMessageNode;
293
+ exports.extractAddressingContext = extractAddressingContext;