@prototypevip/baileys 0.0.1

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 (118) hide show
  1. package/LICENSE +23 -0
  2. package/WAProto/index.js +131118 -0
  3. package/engine-requirements.js +1 -0
  4. package/lib/Defaults/index.js +187 -0
  5. package/lib/Signal/Group/ciphertext-message.js +11 -0
  6. package/lib/Signal/Group/group-session-builder.js +41 -0
  7. package/lib/Signal/Group/group_cipher.js +108 -0
  8. package/lib/Signal/Group/index.js +11 -0
  9. package/lib/Signal/Group/keyhelper.js +14 -0
  10. package/lib/Signal/Group/sender-chain-key.js +31 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  12. package/lib/Signal/Group/sender-key-message.js +79 -0
  13. package/lib/Signal/Group/sender-key-name.js +49 -0
  14. package/lib/Signal/Group/sender-key-record.js +46 -0
  15. package/lib/Signal/Group/sender-key-state.js +104 -0
  16. package/lib/Signal/Group/sender-message-key.js +29 -0
  17. package/lib/Signal/libsignal.js +532 -0
  18. package/lib/Signal/lid-mapping.js +312 -0
  19. package/lib/Socket/Client/index.js +2 -0
  20. package/lib/Socket/Client/types.js +10 -0
  21. package/lib/Socket/Client/websocket.js +64 -0
  22. package/lib/Socket/business.js +293 -0
  23. package/lib/Socket/chats.js +1124 -0
  24. package/lib/Socket/communities.js +528 -0
  25. package/lib/Socket/groups.js +465 -0
  26. package/lib/Socket/index.js +14 -0
  27. package/lib/Socket/messages-recv.js +2325 -0
  28. package/lib/Socket/messages-send.js +1746 -0
  29. package/lib/Socket/mex.js +55 -0
  30. package/lib/Socket/newsletter.js +317 -0
  31. package/lib/Socket/socket.js +1185 -0
  32. package/lib/Store/cache-factory.js +20 -0
  33. package/lib/Store/index.js +5 -0
  34. package/lib/Store/make-in-memory-store.js +523 -0
  35. package/lib/Store/make-ordered-dictionary.js +203 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Store/prototype-store.js +958 -0
  38. package/lib/Types/Auth.js +1 -0
  39. package/lib/Types/Bussines.js +1 -0
  40. package/lib/Types/Call.js +1 -0
  41. package/lib/Types/Chat.js +7 -0
  42. package/lib/Types/Contact.js +1 -0
  43. package/lib/Types/Events.js +1 -0
  44. package/lib/Types/GroupMetadata.js +1 -0
  45. package/lib/Types/Label.js +24 -0
  46. package/lib/Types/LabelAssociation.js +6 -0
  47. package/lib/Types/Message.js +18 -0
  48. package/lib/Types/Mex.js +37 -0
  49. package/lib/Types/Newsletter.js +36 -0
  50. package/lib/Types/Product.js +1 -0
  51. package/lib/Types/RichType.js +25 -0
  52. package/lib/Types/Signal.js +1 -0
  53. package/lib/Types/Socket.js +2 -0
  54. package/lib/Types/State.js +78 -0
  55. package/lib/Types/USync.js +1 -0
  56. package/lib/Types/index.js +33 -0
  57. package/lib/Utils/auth-utils.js +303 -0
  58. package/lib/Utils/browser-utils.js +32 -0
  59. package/lib/Utils/business.js +245 -0
  60. package/lib/Utils/chat-utils.js +971 -0
  61. package/lib/Utils/companion-reg-client-utils.js +54 -0
  62. package/lib/Utils/constants.js +24 -0
  63. package/lib/Utils/crypto.js +133 -0
  64. package/lib/Utils/cstoken-utils.js +41 -0
  65. package/lib/Utils/decode-wa-message.js +406 -0
  66. package/lib/Utils/event-buffer.js +616 -0
  67. package/lib/Utils/generics.js +438 -0
  68. package/lib/Utils/history.js +147 -0
  69. package/lib/Utils/identity-change-handler.js +63 -0
  70. package/lib/Utils/index.js +29 -0
  71. package/lib/Utils/interactive-message-handler.js +478 -0
  72. package/lib/Utils/link-preview.js +91 -0
  73. package/lib/Utils/logger.js +2 -0
  74. package/lib/Utils/lt-hash.js +6 -0
  75. package/lib/Utils/make-mutex.js +31 -0
  76. package/lib/Utils/message-retry-manager.js +291 -0
  77. package/lib/Utils/messages-media.js +881 -0
  78. package/lib/Utils/messages.js +1434 -0
  79. package/lib/Utils/noise-handler.js +229 -0
  80. package/lib/Utils/normalize-message-identity.js +73 -0
  81. package/lib/Utils/offline-node-processor.js +50 -0
  82. package/lib/Utils/pre-key-manager.js +119 -0
  83. package/lib/Utils/process-message.js +648 -0
  84. package/lib/Utils/reporting-utils.js +355 -0
  85. package/lib/Utils/rich-message-utils.js +264 -0
  86. package/lib/Utils/signal.js +233 -0
  87. package/lib/Utils/stanza-ack.js +33 -0
  88. package/lib/Utils/sticker-utils.js +221 -0
  89. package/lib/Utils/sync-action-utils.js +53 -0
  90. package/lib/Utils/tc-token-utils.js +182 -0
  91. package/lib/Utils/use-multi-file-auth-state.js +118 -0
  92. package/lib/Utils/use-prototype-auth-state.js +217 -0
  93. package/lib/Utils/use-single-file-auth-state.js +94 -0
  94. package/lib/Utils/validate-connection.js +235 -0
  95. package/lib/WABinary/constants.js +1468 -0
  96. package/lib/WABinary/decode.js +258 -0
  97. package/lib/WABinary/encode.js +219 -0
  98. package/lib/WABinary/generic-utils.js +202 -0
  99. package/lib/WABinary/index.js +5 -0
  100. package/lib/WABinary/jid-utils.js +94 -0
  101. package/lib/WABinary/types.js +1 -0
  102. package/lib/WAM/BinaryInfo.js +9 -0
  103. package/lib/WAM/constants.js +20669 -0
  104. package/lib/WAM/encode.js +151 -0
  105. package/lib/WAM/index.js +3 -0
  106. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  107. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -0
  108. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -0
  109. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +29 -0
  110. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  111. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +59 -0
  112. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +21 -0
  113. package/lib/WAUSync/Protocols/index.js +4 -0
  114. package/lib/WAUSync/USyncQuery.js +133 -0
  115. package/lib/WAUSync/USyncUser.js +22 -0
  116. package/lib/WAUSync/index.js +3 -0
  117. package/lib/index.js +12 -0
  118. package/package.json +78 -0
@@ -0,0 +1,54 @@
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)] =
13
+ "OTHER_WEB_CLIENT";
14
+ })(CompanionWebClientType || (CompanionWebClientType = {}));
15
+ const BROWSER_TO_COMPANION_WEB_CLIENT = {
16
+ Chrome: CompanionWebClientType.CHROME,
17
+ Edge: CompanionWebClientType.EDGE,
18
+ Firefox: CompanionWebClientType.FIREFOX,
19
+ IE: CompanionWebClientType.IE,
20
+ Opera: CompanionWebClientType.OPERA,
21
+ Safari: CompanionWebClientType.SAFARI,
22
+ };
23
+ export const getCompanionWebClientType = ([os, browserName]) => {
24
+ if (browserName === "Desktop") {
25
+ return os === "Windows"
26
+ ? CompanionWebClientType.UWP
27
+ : CompanionWebClientType.ELECTRON;
28
+ }
29
+ return (
30
+ BROWSER_TO_COMPANION_WEB_CLIENT[browserName] ||
31
+ CompanionWebClientType.OTHER_WEB_CLIENT
32
+ );
33
+ };
34
+ export const getCompanionPlatformId = (browser) => {
35
+ return getCompanionWebClientType(browser).toString();
36
+ };
37
+ export const buildPairingQRData = (
38
+ ref,
39
+ noiseKeyB64,
40
+ identityKeyB64,
41
+ advB64,
42
+ browser,
43
+ ) => {
44
+ return (
45
+ "https://wa.me/settings/linked_devices#" +
46
+ [
47
+ ref,
48
+ noiseKeyB64,
49
+ identityKeyB64,
50
+ advB64,
51
+ getCompanionPlatformId(browser),
52
+ ].join(",")
53
+ );
54
+ };
@@ -0,0 +1,24 @@
1
+ export const NO_MESSAGE_FOUND_ERROR_TEXT = "Message absent from node";
2
+ export const MISSING_KEYS_ERROR_TEXT = "Key used already or never filled";
3
+
4
+ export const NACK_REASONS = {
5
+ ParsingError: 487,
6
+ UnrecognizedStanza: 488,
7
+ UnrecognizedStanzaClass: 489,
8
+ UnrecognizedStanzaType: 490,
9
+ InvalidProtobuf: 491,
10
+ InvalidHostedCompanionStanza: 493,
11
+ MissingMessageSecret: 495,
12
+ SignalErrorOldCounter: 496,
13
+ MessageDeletedOnPeer: 499,
14
+ UnhandledError: 500,
15
+ UnsupportedAdminRevoke: 550,
16
+ UnsupportedLIDGroup: 551,
17
+ DBOperationFailed: 552,
18
+ };
19
+ export const ACCOUNT_RESTRICTED_TEXT = "Your account has been restricted";
20
+ export const SERVER_ERROR_CODES = {
21
+ MessageAccountRestriction: "463",
22
+ SmaxInvalid: "479",
23
+ };
24
+ export const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
@@ -0,0 +1,133 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ createHash,
5
+ createHmac,
6
+ randomBytes,
7
+ } from "crypto";
8
+ import * as curve from "libsignal/src/curve.js";
9
+ import { KEY_BUNDLE_TYPE } from "../Defaults/index.js";
10
+ export { md5, hkdf } from "whatsapp-rust-bridge";
11
+ // insure browser & node compatibility
12
+ const { subtle } = globalThis.crypto;
13
+ /** prefix version byte to the pub keys, required for some curve crypto functions */ export const generateSignalPubKey =
14
+ (pubKey) =>
15
+ pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]);
16
+ export const Curve = {
17
+ generateKeyPair: () => {
18
+ const { pubKey, privKey } = curve.generateKeyPair();
19
+ return {
20
+ private: Buffer.from(privKey),
21
+ // remove version byte
22
+ public: Buffer.from(pubKey.slice(1)),
23
+ };
24
+ },
25
+ sharedKey: (privateKey, publicKey) => {
26
+ const shared = curve.calculateAgreement(
27
+ generateSignalPubKey(publicKey),
28
+ privateKey,
29
+ );
30
+ return Buffer.from(shared);
31
+ },
32
+ sign: (privateKey, buf) => curve.calculateSignature(privateKey, buf),
33
+ verify: (pubKey, message, signature) => {
34
+ try {
35
+ curve.verifySignature(generateSignalPubKey(pubKey), message, signature);
36
+ return true;
37
+ } catch (error) {
38
+ return false;
39
+ }
40
+ },
41
+ };
42
+ export const signedKeyPair = (identityKeyPair, keyId) => {
43
+ const preKey = Curve.generateKeyPair();
44
+ const pubKey = generateSignalPubKey(preKey.public);
45
+ const signature = Curve.sign(identityKeyPair.private, pubKey);
46
+ return { keyPair: preKey, signature: signature, keyId: keyId };
47
+ };
48
+ const GCM_TAG_LENGTH = 128 >> 3;
49
+ /**
50
+ * encrypt AES 256 GCM;
51
+ * where the tag tag is suffixed to the ciphertext
52
+ * */ export function aesEncryptGCM(plaintext, key, iv, additionalData) {
53
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
54
+ cipher.setAAD(additionalData);
55
+ return Buffer.concat([
56
+ cipher.update(plaintext),
57
+ cipher.final(),
58
+ cipher.getAuthTag(),
59
+ ]);
60
+ }
61
+ /**
62
+ * decrypt AES 256 GCM;
63
+ * where the auth tag is suffixed to the ciphertext
64
+ * */ export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
65
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
66
+ // decrypt additional adata
67
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
68
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
69
+ // set additional data
70
+ decipher.setAAD(additionalData);
71
+ decipher.setAuthTag(tag);
72
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
73
+ }
74
+ export function aesEncryptCTR(plaintext, key, iv) {
75
+ const cipher = createCipheriv("aes-256-ctr", key, iv);
76
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
77
+ }
78
+ export function aesDecryptCTR(ciphertext, key, iv) {
79
+ const decipher = createDecipheriv("aes-256-ctr", key, iv);
80
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
81
+ }
82
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */ export function aesDecrypt(
83
+ buffer,
84
+ key,
85
+ ) {
86
+ return aesDecryptWithIV(buffer.subarray(16), key, buffer.subarray(0, 16));
87
+ }
88
+ /** decrypt AES 256 CBC */ export function aesDecryptWithIV(buffer, key, IV) {
89
+ const aes = createDecipheriv("aes-256-cbc", key, IV);
90
+ return Buffer.concat([aes.update(buffer), aes.final()]);
91
+ }
92
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
93
+ export function aesEncrypt(buffer, key) {
94
+ const IV = randomBytes(16);
95
+ const aes = createCipheriv("aes-256-cbc", key, IV);
96
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
97
+ }
98
+ // encrypt AES 256 CBC with a given IV
99
+ export function aesEncrypWithIV(buffer, key, IV) {
100
+ const aes = createCipheriv("aes-256-cbc", key, IV);
101
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
102
+ }
103
+ // sign HMAC using SHA 256
104
+ export function hmacSign(buffer, key, variant = "sha256") {
105
+ return createHmac(variant, key).update(buffer).digest();
106
+ }
107
+ export function sha256(buffer) {
108
+ return createHash("sha256").update(buffer).digest();
109
+ }
110
+ export async function derivePairingCodeKey(pairingCode, salt) {
111
+ // Convert inputs to formats Web Crypto API can work with
112
+ const encoder = new TextEncoder();
113
+ const pairingCodeBuffer = encoder.encode(pairingCode);
114
+ const saltBuffer = new Uint8Array(
115
+ salt instanceof Uint8Array ? salt : new Uint8Array(salt),
116
+ );
117
+ // Import the pairing code as key material
118
+ const keyMaterial = await subtle.importKey(
119
+ "raw",
120
+ pairingCodeBuffer,
121
+ { name: "PBKDF2" },
122
+ false,
123
+ ["deriveBits"],
124
+ );
125
+ // Derive bits using PBKDF2 with the same parameters
126
+ // 2 << 16 = 131,072 iterations
127
+ const derivedBits = await subtle.deriveBits(
128
+ { name: "PBKDF2", salt: saltBuffer, iterations: 2 << 16, hash: "SHA-256" },
129
+ keyMaterial,
130
+ 32 * 8,
131
+ );
132
+ return Buffer.from(derivedBits);
133
+ }
@@ -0,0 +1,41 @@
1
+ import { createHmac } from "crypto";
2
+ import {
3
+ isJidBot,
4
+ isLidUser,
5
+ isPnUser,
6
+ jidDecode,
7
+ S_WHATSAPP_NET,
8
+ } from "../WABinary/index.js";
9
+
10
+ const PSA_USER = "0";
11
+
12
+ export const shouldSendCsToken = (jid) => {
13
+ const decoded = jidDecode(jid);
14
+ if (!decoded) return false;
15
+
16
+ const { user, server } = decoded;
17
+ return (
18
+ (server === "s.whatsapp.net" || server === "c.us" || server === "lid") &&
19
+ user !== PSA_USER &&
20
+ !isJidBot(jid)
21
+ );
22
+ };
23
+
24
+ export const generateCsToken = (jid, salt) => {
25
+ if (!salt) return null;
26
+ if (!shouldSendCsToken(jid)) return null;
27
+
28
+ const decoded = jidDecode(jid);
29
+ if (
30
+ !decoded ||
31
+ (decoded.server !== "lid" &&
32
+ decoded.server !== "s.whatsapp.net" &&
33
+ decoded.server !== "c.us")
34
+ ) {
35
+ return null;
36
+ }
37
+
38
+ const hmac = createHmac("sha256", salt);
39
+ hmac.update(jid);
40
+ return hmac.digest();
41
+ };
@@ -0,0 +1,406 @@
1
+ import { Boom } from "@hapi/boom";
2
+ import { proto } from "../../WAProto/index.js";
3
+ import {
4
+ areJidsSameUser,
5
+ isHostedLidUser,
6
+ isHostedPnUser,
7
+ isJidBroadcast,
8
+ isJidGroup,
9
+ isJidMetaAI,
10
+ isJidNewsletter,
11
+ isJidStatusBroadcast,
12
+ isLidUser,
13
+ isPnUser,
14
+ jidNormalizedUser,
15
+ } from "../WABinary/index.js";
16
+ import { NO_MESSAGE_FOUND_ERROR_TEXT } from "./constants.js";
17
+ import { unpadRandomMax16 } from "./generics.js";
18
+
19
+ // === مضافة من الرسمية: إعدادات إعادة محاولة فك التشفير عند أخطاء الـ session ===
20
+ export const DECRYPTION_RETRY_CONFIG = {
21
+ maxRetries: 3,
22
+ baseDelayMs: 100,
23
+ sessionRecordErrors: [
24
+ "No session record",
25
+ "SessionError: No session record",
26
+ ],
27
+ };
28
+ /**
29
+ * تتحقق هل الخطأ سببه فقدان سجل جلسة (session record) عشان نقدر نميّزه
30
+ * عن أي فشل فك تشفير تاني في اللوج.
31
+ */
32
+ function isSessionRecordError(error) {
33
+ const errorMessage = error?.message || error?.toString() || "";
34
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some((errorPattern) =>
35
+ errorMessage.includes(errorPattern),
36
+ );
37
+ }
38
+
39
+ export const getDecryptionJid = async (sender, repository) => {
40
+ if (isLidUser(sender) || isHostedLidUser(sender)) return sender;
41
+ return (await repository.lidMapping.getLIDForPN(sender)) || sender;
42
+ };
43
+
44
+ const storeMappingFromEnvelope = async (
45
+ stanza,
46
+ sender,
47
+ repository,
48
+ decryptionJid,
49
+ logger,
50
+ ) => {
51
+ const senderPn =
52
+ stanza.attrs.participant_pn ||
53
+ stanza.attrs.sender_pn ||
54
+ stanza.attrs.peer_recipient_pn;
55
+
56
+ const senderLid =
57
+ stanza.attrs.participant_lid ||
58
+ stanza.attrs.sender_lid ||
59
+ stanza.attrs.peer_recipient_lid;
60
+
61
+ if (senderLid && isPnUser(sender) && decryptionJid === sender) {
62
+ try {
63
+ await repository.lidMapping.storeLIDPNMappings([
64
+ { lid: senderLid, pn: sender },
65
+ ]);
66
+
67
+ logger.debug({ sender, senderLid }, "Stored LID mapping from envelope");
68
+ } catch (error) {
69
+ logger.warn({ sender, senderLid, error }, "Failed to store LID mapping");
70
+ }
71
+ }
72
+ };
73
+
74
+ export const extractAddressingContext = (stanza) => {
75
+ let senderAlt;
76
+ let recipientAlt;
77
+ const sender = stanza.attrs.participant || stanza.attrs.from;
78
+ const addressingMode =
79
+ stanza.attrs.addressing_mode || (sender?.endsWith("lid") ? "lid" : "pn");
80
+ if (addressingMode === "lid") {
81
+ senderAlt =
82
+ stanza.attrs.participant_pn ||
83
+ stanza.attrs.sender_pn ||
84
+ stanza.attrs.peer_recipient_pn;
85
+ recipientAlt = stanza.attrs.recipient_pn;
86
+ } else {
87
+ senderAlt =
88
+ stanza.attrs.participant_lid ||
89
+ stanza.attrs.sender_lid ||
90
+ stanza.attrs.peer_recipient_lid;
91
+ recipientAlt = stanza.attrs.recipient_lid;
92
+ }
93
+ return {
94
+ addressingMode,
95
+ senderAlt,
96
+ recipientAlt,
97
+ };
98
+ };
99
+ export function decodeMessageNode(stanza, meId, meLid) {
100
+ let msgType;
101
+ let chatId;
102
+ let author;
103
+ let fromMe = false;
104
+
105
+ const msgId = stanza.attrs.id;
106
+ const from = stanza.attrs.from;
107
+ if (!msgId) {
108
+ throw new Boom("Invalid message stanza: missing id", {
109
+ data: stanza,
110
+ });
111
+ }
112
+ if (!from) {
113
+ throw new Boom("Invalid message stanza: missing from", {
114
+ data: stanza,
115
+ });
116
+ }
117
+ const participant = stanza.attrs.participant;
118
+ const recipient = stanza.attrs.recipient;
119
+
120
+ const addressingContext = extractAddressingContext(stanza);
121
+ const isMe = (jid) => areJidsSameUser(jid, meId);
122
+ const isMeLid = (jid) => areJidsSameUser(jid, meLid);
123
+ if (
124
+ isPnUser(from) ||
125
+ isLidUser(from) ||
126
+ isHostedLidUser(from) ||
127
+ isHostedPnUser(from)
128
+ ) {
129
+ if (recipient && !isJidMetaAI(recipient)) {
130
+ if (!isMe(from) && !isMeLid(from)) {
131
+ throw new Boom("receipient present, but msg not from me", {
132
+ data: stanza,
133
+ });
134
+ }
135
+ if (isMe(from) || isMeLid(from)) {
136
+ fromMe = true;
137
+ }
138
+ chatId = recipient;
139
+ } else {
140
+ if (isMe(from) || isMeLid(from)) {
141
+ fromMe = true;
142
+ }
143
+ chatId = from;
144
+ }
145
+ msgType = "chat";
146
+ author = from;
147
+ } else if (isJidGroup(from)) {
148
+ if (!participant) {
149
+ throw new Boom("No participant in group message");
150
+ }
151
+ if (isMe(participant) || isMeLid(participant)) {
152
+ fromMe = true;
153
+ }
154
+ msgType = "group";
155
+ author = participant;
156
+ chatId = from;
157
+ } else if (isJidBroadcast(from)) {
158
+ if (!participant) {
159
+ throw new Boom("No participant in group message");
160
+ }
161
+ const isParticipantMe = isMe(participant);
162
+ if (isJidStatusBroadcast(from)) {
163
+ msgType = isParticipantMe ? "direct_peer_status" : "other_status";
164
+ } else {
165
+ msgType = isParticipantMe ? "peer_broadcast" : "other_broadcast";
166
+ }
167
+ fromMe = isParticipantMe;
168
+ chatId = from;
169
+ author = participant;
170
+ } else if (isJidNewsletter(from)) {
171
+ msgType = "newsletter";
172
+ chatId = from;
173
+ author = from;
174
+ if (isMe(from) || isMeLid(from)) {
175
+ fromMe = true;
176
+ }
177
+ } else {
178
+ throw new Boom("Unknown message type", { data: stanza });
179
+ }
180
+
181
+ const pushname = stanza?.attrs?.notify;
182
+ const key = {
183
+ remoteJid: chatId,
184
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
185
+ remoteJidUsername: !isJidGroup(chatId)
186
+ ? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username
187
+ : undefined,
188
+ fromMe,
189
+ id: msgId,
190
+ participant: fromMe
191
+ ? isPnUser(participant)
192
+ ? jidNormalizedUser(meId)
193
+ : isLidUser(participant)
194
+ ? jidNormalizedUser(meLid)
195
+ : jidNormalizedUser(participant)
196
+ : jidNormalizedUser(participant),
197
+ participantAlt: fromMe
198
+ ? jidNormalizedUser(participant) === jidNormalizedUser(meLid)
199
+ ? jidNormalizedUser(meId)
200
+ : jidNormalizedUser(meLid)
201
+ : addressingContext.senderAlt,
202
+ participantUsername: stanza.attrs.participant
203
+ ? stanza.attrs.participant_username
204
+ : undefined,
205
+ addressingMode: addressingContext.addressingMode,
206
+ ...(msgType === "newsletter" && stanza.attrs.server_id
207
+ ? { server_id: stanza.attrs.server_id }
208
+ : {}),
209
+ };
210
+
211
+ const fullMessage = {
212
+ key,
213
+ category: stanza.attrs.category,
214
+ messageTimestamp: +stanza.attrs.t,
215
+ pushName: pushname,
216
+ broadcast: isJidBroadcast(from),
217
+ };
218
+
219
+ if (key.fromMe) {
220
+ fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
221
+ }
222
+
223
+ return {
224
+ fullMessage,
225
+ author,
226
+ sender: msgType === "chat" ? author : chatId,
227
+ };
228
+ }
229
+
230
+ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
231
+ const { fullMessage, author, sender } = decodeMessageNode(
232
+ stanza,
233
+ meId,
234
+ meLid,
235
+ );
236
+
237
+ return {
238
+ fullMessage,
239
+ category: stanza.attrs.category,
240
+ author,
241
+
242
+ async decrypt() {
243
+ let decryptables = 0;
244
+
245
+ if (Array.isArray(stanza.content)) {
246
+ for (const { tag, attrs, content } of stanza.content) {
247
+ if (tag !== "enc" && tag !== "plaintext") continue;
248
+ if (!(content instanceof Uint8Array)) continue;
249
+ if (tag === "unavailable" && attrs.type === "view_once") {
250
+ fullMessage.key.isViewOnce = true;
251
+ }
252
+ if (tag === "verified_name" && content instanceof Uint8Array) {
253
+ const cert = proto.VerifiedNameCertificate.decode(content);
254
+
255
+ const details = proto.VerifiedNameCertificate.Details.decode(
256
+ cert.details,
257
+ );
258
+
259
+ fullMessage.verifiedBizName = details.verifiedName;
260
+ }
261
+ if (attrs.count && tag === "enc") {
262
+ fullMessage.retryCount = Number(attrs.count);
263
+ }
264
+ decryptables++;
265
+
266
+ const decryptionJid = await getDecryptionJid(author, repository);
267
+
268
+ if (tag !== "plaintext") {
269
+ await storeMappingFromEnvelope(
270
+ stanza,
271
+ author,
272
+ repository,
273
+ decryptionJid,
274
+ logger,
275
+ );
276
+ }
277
+
278
+ try {
279
+ const e2eType = tag === "plaintext" ? "plaintext" : attrs.type;
280
+
281
+ let msgBuffer;
282
+
283
+ switch (e2eType) {
284
+ case "skmsg":
285
+ msgBuffer = await repository.decryptGroupMessage({
286
+ group: sender,
287
+ authorJid: author,
288
+ msg: content,
289
+ });
290
+ break;
291
+
292
+ case "pkmsg":
293
+ case "msg":
294
+ msgBuffer = await repository.decryptMessage({
295
+ jid: decryptionJid,
296
+ type: e2eType,
297
+ ciphertext: content,
298
+ });
299
+ break;
300
+
301
+ case "plaintext":
302
+ msgBuffer = content;
303
+ break;
304
+
305
+ default:
306
+ throw new Error(`Unknown e2e type: ${e2eType}`);
307
+ }
308
+
309
+ let msg = proto.Message.decode(
310
+ e2eType !== "plaintext" ? unpadRandomMax16(msgBuffer) : msgBuffer,
311
+ );
312
+
313
+ msg = msg.deviceSentMessage?.message || msg;
314
+ if (msg.senderKeyDistributionMessage) {
315
+ try {
316
+ await repository.processSenderKeyDistributionMessage({
317
+ authorJid: author,
318
+ item: msg.senderKeyDistributionMessage,
319
+ });
320
+ } catch (err) {
321
+ logger.error(
322
+ {
323
+ key: fullMessage.key,
324
+ err,
325
+ sender,
326
+ author,
327
+ stanzaType: attrs.type,
328
+ },
329
+ "failed to decrypt message",
330
+ );
331
+ }
332
+ }
333
+ await normalizeQuoted(msg, repository);
334
+
335
+ if (fullMessage.message) {
336
+ Object.assign(fullMessage.message, msg);
337
+ } else {
338
+ fullMessage.message = msg;
339
+ }
340
+ } catch (err) {
341
+ logger.error(
342
+ {
343
+ key: fullMessage.key,
344
+ err,
345
+ messageType: tag === "plaintext" ? "plaintext" : attrs.type,
346
+ sender,
347
+ author,
348
+ isSessionRecordError: isSessionRecordError(err),
349
+ },
350
+ "failed to decrypt message",
351
+ );
352
+
353
+ fullMessage.messageStubType =
354
+ proto.WebMessageInfo.StubType.CIPHERTEXT;
355
+
356
+ fullMessage.messageStubParameters = [err.message.toString()];
357
+ }
358
+ }
359
+ }
360
+
361
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
362
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
363
+
364
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
365
+ }
366
+ },
367
+ };
368
+ };
369
+
370
+ async function normalizeQuoted(msg, repo) {
371
+ const CONTEXT_TYPES = [
372
+ "extendedTextMessage",
373
+ "imageMessage",
374
+ "videoMessage",
375
+ "documentMessage",
376
+ "audioMessage",
377
+ "stickerMessage",
378
+ "contactMessage",
379
+ "contactsArrayMessage",
380
+ "liveLocationMessage",
381
+ "buttonsMessage",
382
+ "buttonsResponseMessage",
383
+ "listMessage",
384
+ "listResponseMessage",
385
+ "templateMessage",
386
+ "templateButtonReplyMessage",
387
+ "interactiveMessage",
388
+ "interactiveResponseMessage",
389
+ "pollCreationMessage",
390
+ "pollCreationMessageV2",
391
+ "reactionMessage",
392
+ ];
393
+ let ctx = null;
394
+ for (const type of CONTEXT_TYPES) {
395
+ const contextInfo = msg?.[type]?.contextInfo;
396
+ if (contextInfo) {
397
+ ctx = contextInfo;
398
+ break;
399
+ }
400
+ }
401
+ if (!ctx?.participant) return;
402
+ if (typeof ctx.participant === "string" && ctx.participant.endsWith("@lid")) {
403
+ const pn = await repo.lidMapping.getPNForLID(ctx.participant);
404
+ if (pn) ctx.participant = pn;
405
+ }
406
+ }