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