@ikyyjee/ikyysinggle 1.7.7

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 (142) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +8083 -0
  3. package/WAProto/fix-imports.js +85 -0
  4. package/WAProto/index.d.ts +29095 -0
  5. package/WAProto/index.js +172336 -0
  6. package/engine-requirements.js +10 -0
  7. package/lib/Defaults/index.js +194 -0
  8. package/lib/Signal/Group/ciphertext-message.js +12 -0
  9. package/lib/Signal/Group/group-session-builder.js +30 -0
  10. package/lib/Signal/Group/group_cipher.js +82 -0
  11. package/lib/Signal/Group/index.js +12 -0
  12. package/lib/Signal/Group/keyhelper.js +18 -0
  13. package/lib/Signal/Group/sender-chain-key.js +26 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  15. package/lib/Signal/Group/sender-key-message.js +66 -0
  16. package/lib/Signal/Group/sender-key-name.js +48 -0
  17. package/lib/Signal/Group/sender-key-record.js +41 -0
  18. package/lib/Signal/Group/sender-key-state.js +84 -0
  19. package/lib/Signal/Group/sender-message-key.js +26 -0
  20. package/lib/Signal/libsignal.js +431 -0
  21. package/lib/Signal/lid-mapping.js +277 -0
  22. package/lib/Socket/Client/index.js +3 -0
  23. package/lib/Socket/Client/types.js +11 -0
  24. package/lib/Socket/Client/websocket.js +102 -0
  25. package/lib/Socket/aigroups.js +221 -0
  26. package/lib/Socket/business.js +379 -0
  27. package/lib/Socket/chats.js +1193 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +524 -0
  30. package/lib/Socket/groups.js +408 -0
  31. package/lib/Socket/index.js +49 -0
  32. package/lib/Socket/interop.js +341 -0
  33. package/lib/Socket/luxu.js +510 -0
  34. package/lib/Socket/managed-account.js +99 -0
  35. package/lib/Socket/messages-recv.js +2009 -0
  36. package/lib/Socket/messages-send.js +1608 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +399 -0
  39. package/lib/Socket/privacy.js +128 -0
  40. package/lib/Socket/registration.js +238 -0
  41. package/lib/Socket/socket.js +1000 -0
  42. package/lib/Socket/text-router.js +67 -0
  43. package/lib/Socket/username.js +234 -0
  44. package/lib/Store/index.js +10 -0
  45. package/lib/Store/keyed-db.js +108 -0
  46. package/lib/Store/make-cache-manager-store.js +85 -0
  47. package/lib/Store/make-in-memory-store.js +198 -0
  48. package/lib/Store/make-ordered-dictionary.js +75 -0
  49. package/lib/Store/object-repository.js +32 -0
  50. package/lib/Types/Auth.js +2 -0
  51. package/lib/Types/Bussines.js +2 -0
  52. package/lib/Types/Call.js +2 -0
  53. package/lib/Types/Chat.js +8 -0
  54. package/lib/Types/Contact.js +2 -0
  55. package/lib/Types/Events.js +2 -0
  56. package/lib/Types/GroupMetadata.js +2 -0
  57. package/lib/Types/Label.js +25 -0
  58. package/lib/Types/LabelAssociation.js +7 -0
  59. package/lib/Types/Message.js +11 -0
  60. package/lib/Types/Mex.js +114 -0
  61. package/lib/Types/Product.js +2 -0
  62. package/lib/Types/Signal.js +2 -0
  63. package/lib/Types/Socket.js +3 -0
  64. package/lib/Types/State.js +56 -0
  65. package/lib/Types/USync.js +2 -0
  66. package/lib/Types/index.js +26 -0
  67. package/lib/Utils/adaptive-healing.js +53 -0
  68. package/lib/Utils/auth-utils.js +302 -0
  69. package/lib/Utils/browser-utils.js +50 -0
  70. package/lib/Utils/business.js +231 -0
  71. package/lib/Utils/chat-utils.js +872 -0
  72. package/lib/Utils/command-loader.js +108 -0
  73. package/lib/Utils/companion-reg-client-utils.js +35 -0
  74. package/lib/Utils/consumer-application.js +106 -0
  75. package/lib/Utils/crypto.js +137 -0
  76. package/lib/Utils/curve25519-js.js +262 -0
  77. package/lib/Utils/decode-wa-message.js +498 -0
  78. package/lib/Utils/event-buffer.js +622 -0
  79. package/lib/Utils/generics.js +403 -0
  80. package/lib/Utils/group-history.js +47 -0
  81. package/lib/Utils/history.js +134 -0
  82. package/lib/Utils/identity-change-handler.js +50 -0
  83. package/lib/Utils/index.js +38 -0
  84. package/lib/Utils/jid-display-normalization.js +198 -0
  85. package/lib/Utils/link-preview.js +85 -0
  86. package/lib/Utils/logger.js +3 -0
  87. package/lib/Utils/lt-hash.js +8 -0
  88. package/lib/Utils/make-mutex.js +33 -0
  89. package/lib/Utils/message-composer.js +273 -0
  90. package/lib/Utils/message-retry-manager.js +267 -0
  91. package/lib/Utils/messages-media.js +791 -0
  92. package/lib/Utils/messages.js +1260 -0
  93. package/lib/Utils/meta-ai-msmsg.js +271 -0
  94. package/lib/Utils/native-bridge.js +77 -0
  95. package/lib/Utils/noise-handler.js +201 -0
  96. package/lib/Utils/offline-node-processor.js +40 -0
  97. package/lib/Utils/optimizer.js +90 -0
  98. package/lib/Utils/pre-key-manager.js +106 -0
  99. package/lib/Utils/process-message.js +630 -0
  100. package/lib/Utils/reporting-utils.js +258 -0
  101. package/lib/Utils/session-pool.js +73 -0
  102. package/lib/Utils/signal.js +207 -0
  103. package/lib/Utils/stanza-ack.js +38 -0
  104. package/lib/Utils/sticker.js +139 -0
  105. package/lib/Utils/sync-action-utils.js +49 -0
  106. package/lib/Utils/tc-token-utils.js +163 -0
  107. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  108. package/lib/Utils/use-sqlite-auth-state.js +168 -0
  109. package/lib/Utils/validate-connection.js +203 -0
  110. package/lib/Utils/view-once-cache.js +79 -0
  111. package/lib/Utils/voip-rekey.js +25 -0
  112. package/lib/Utils/warmup.js +117 -0
  113. package/lib/WABinary/constants.js +1301 -0
  114. package/lib/WABinary/decode.js +262 -0
  115. package/lib/WABinary/encode.js +220 -0
  116. package/lib/WABinary/generic-utils.js +204 -0
  117. package/lib/WABinary/index.js +6 -0
  118. package/lib/WABinary/jid-utils.js +98 -0
  119. package/lib/WABinary/types.js +2 -0
  120. package/lib/WAM/BinaryInfo.js +10 -0
  121. package/lib/WAM/constants.js +22853 -0
  122. package/lib/WAM/encode.js +150 -0
  123. package/lib/WAM/index.js +4 -0
  124. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +41 -0
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  126. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  128. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +52 -0
  129. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +31 -0
  130. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +26 -0
  131. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  132. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +35 -0
  133. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  134. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  135. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  136. package/lib/WAUSync/Protocols/index.js +13 -0
  137. package/lib/WAUSync/USyncQuery.js +127 -0
  138. package/lib/WAUSync/USyncUser.js +31 -0
  139. package/lib/WAUSync/index.js +4 -0
  140. package/lib/antiban.js +4083 -0
  141. package/lib/index.js +24 -0
  142. package/package.json +147 -0
@@ -0,0 +1,498 @@
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
+ import { decodeDecryptedMsmsgMessage, decryptMsmsgBotMessage } from './meta-ai-msmsg.js';
8
+ export const getDecryptionJid = async (sender, repository) => {
9
+ if (isLidUser(sender) || isHostedLidUser(sender)) {
10
+ return sender;
11
+ }
12
+ const mapped = await repository.lidMapping.getLIDForPN(sender);
13
+ return mapped || sender;
14
+ };
15
+ const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger) => {
16
+ // TODO: Handle hosted IDs
17
+ const { senderAlt } = extractAddressingContext(stanza);
18
+ if (senderAlt && isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
19
+ try {
20
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }]);
21
+ await repository.migrateSession(sender, senderAlt);
22
+ logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope');
23
+ }
24
+ catch (error) {
25
+ logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping');
26
+ }
27
+ }
28
+ };
29
+ export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
30
+ export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
31
+ export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted';
32
+ // Retry configuration for failed decryption
33
+ export const DECRYPTION_RETRY_CONFIG = {
34
+ maxRetries: 3,
35
+ baseDelayMs: 100,
36
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
37
+ };
38
+ /** NACK reason codes we send to the server (client → server) */
39
+ export const NACK_REASONS = {
40
+ SenderReachoutTimelocked: 463,
41
+ ParsingError: 487,
42
+ UnrecognizedStanza: 488,
43
+ UnrecognizedStanzaClass: 489,
44
+ UnrecognizedStanzaType: 490,
45
+ InvalidProtobuf: 491,
46
+ InvalidHostedCompanionStanza: 493,
47
+ MissingMessageSecret: 495,
48
+ SignalErrorOldCounter: 496,
49
+ MessageDeletedOnPeer: 499,
50
+ UnhandledError: 500,
51
+ UnsupportedAdminRevoke: 550,
52
+ UnsupportedLIDGroup: 551,
53
+ DBOperationFailed: 552
54
+ };
55
+ /**
56
+ * Server-side error codes returned in ack stanzas (server → client) that we
57
+ * currently have dedicated handlers for. Extend as more handlers are added.
58
+ * Distinct from the client-side NackReason enum (WAWebCreateNackFromStanza).
59
+ */
60
+ export const SERVER_ERROR_CODES = {
61
+ /**
62
+ * 1:1 message missing privacy token (tctoken). Usually means the account is
63
+ * restricted: WhatsApp blocks starting new chats but preserves existing ones,
64
+ * since established chats already carry a tctoken.
65
+ */
66
+ MessageAccountRestriction: '463',
67
+ /** Stanza validation failure (SMAX_INVALID) — likely stale device session */
68
+ SmaxInvalid: '479'
69
+ };
70
+ /**
71
+ * Best-effort classification of an ack-error code into a human label, for the
72
+ * console-facing ACK monitor (see lib/Socket/messages-recv.js handleBadAck).
73
+ *
74
+ * IMPORTANT: WhatsApp does not publicly document what these codes mean or
75
+ * guarantee they indicate account health — this mapping reflects widely
76
+ * discussed, but unofficial, community observations from the WA bot/userbot
77
+ * ecosystem. Treat every label here as a hint worth investigating, not a
78
+ * confirmed diagnosis. `errorCode` may be `undefined` (a bare status-0 ack
79
+ * with no `error` attribute at all), which is reported as 'possible-soft-ban'
80
+ * since that's the "ACK 0, no further detail" case.
81
+ */
82
+ export const classifyAckIssue = (errorCode) => {
83
+ if (!errorCode) {
84
+ return { label: 'Possible soft-ban', severity: 'warn' };
85
+ }
86
+ const code = String(errorCode);
87
+ switch (code) {
88
+ case '401':
89
+ return { label: 'Possible ban (401)', severity: 'error' };
90
+ case SERVER_ERROR_CODES.MessageAccountRestriction: // 463 — see handleBadAck, this is the branch that actually fires for 463
91
+ return { label: 'Restricted (463)', severity: 'warn' };
92
+ case '405':
93
+ case '429':
94
+ return { label: 'Rate-limited / Limit', severity: 'warn' };
95
+ case SERVER_ERROR_CODES.SmaxInvalid: // 479
96
+ return { label: 'Restricted (stale session / rejected stanza)', severity: 'warn' };
97
+ default:
98
+ // Any ack-error code we don't have a specific mapping for. Community
99
+ // ecosystem convention calls this pattern "soft-banned" — a message
100
+ // silently failed to deliver with no clearly-identified reason.
101
+ return { label: `Possible soft-ban (ack error ${code})`, severity: 'warn' };
102
+ }
103
+ };
104
+ export const extractAddressingContext = (stanza) => {
105
+ let senderAlt;
106
+ let recipientAlt;
107
+ const sender = stanza.attrs.participant || stanza.attrs.from;
108
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn');
109
+ if (addressingMode === 'lid') {
110
+ // Message is LID-addressed: sender is LID, extract corresponding PN
111
+ // without device data
112
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
113
+ recipientAlt = stanza.attrs.recipient_pn;
114
+ // with device data
115
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
116
+ }
117
+ else {
118
+ // Message is PN-addressed: sender is PN, extract corresponding LID
119
+ // without device data
120
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
121
+ recipientAlt = stanza.attrs.recipient_lid;
122
+ //with device data
123
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
124
+ }
125
+ return {
126
+ addressingMode,
127
+ senderAlt,
128
+ recipientAlt
129
+ };
130
+ };
131
+ const MAX_SECRETS_PER_CHAT = 20
132
+ // Module-level map: outgoing @bot message ID → messageSecret
133
+ // Populated when we receive the outgoing pkmsg/msg to @bot (which contains messageContextInfo.messageSecret)
134
+ // Consumed when the msmsg response from @bot arrives and needs decryption
135
+ const botMessageSecrets = new Map()
136
+ const botRecentSecretsByChat = new Map()
137
+ const pushRecentChatSecret = (chatJid, id, secretBuf) => {
138
+ if (!chatJid || !secretBuf) return
139
+ const existing = botRecentSecretsByChat.get(chatJid) || []
140
+ const filtered = existing.filter(item => item.id !== id && !item.secret.equals(secretBuf))
141
+ filtered.unshift({ id, secret: secretBuf })
142
+ if (filtered.length > MAX_SECRETS_PER_CHAT) {
143
+ filtered.length = MAX_SECRETS_PER_CHAT
144
+ }
145
+ botRecentSecretsByChat.set(chatJid, filtered)
146
+ }
147
+ export const setBotMessageSecret = (id, secret, chatJid) => {
148
+ if (!id || !secret) return
149
+ let buf
150
+ if (Buffer.isBuffer(secret)) {
151
+ buf = secret
152
+ } else if (secret instanceof Uint8Array) {
153
+ buf = Buffer.from(secret.buffer, secret.byteOffset, secret.byteLength)
154
+ } else if (typeof secret === 'string') {
155
+ buf = Buffer.from(secret, 'base64')
156
+ } else {
157
+ return
158
+ }
159
+ botMessageSecrets.set(id, buf)
160
+ if (chatJid) {
161
+ pushRecentChatSecret(chatJid, id, buf)
162
+ }
163
+ }
164
+ /**
165
+ * Decode the received node as a message.
166
+ * @note this will only parse the message, not decrypt it
167
+ */
168
+ export function decodeMessageNode(stanza, meId, meLid) {
169
+ let msgType;
170
+ let chatId;
171
+ let author;
172
+ let fromMe = false;
173
+ const msgId = stanza.attrs.id;
174
+ const from = stanza.attrs.from;
175
+ const participant = stanza.attrs.participant;
176
+ const recipient = stanza.attrs.recipient;
177
+ if (!msgId) {
178
+ throw new Boom('Invalid message stanza: missing id attribute', { data: stanza });
179
+ }
180
+ if (!from) {
181
+ throw new Boom('Invalid message stanza: missing from attribute', { data: stanza });
182
+ }
183
+ const addressingContext = extractAddressingContext(stanza);
184
+ const isMe = (jid) => areJidsSameUser(jid, meId);
185
+ const isMeLid = (jid) => areJidsSameUser(jid, meLid);
186
+ if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
187
+ if (recipient && !isJidMetaAI(recipient)) {
188
+ if (!isMe(from) && !isMeLid(from)) {
189
+ throw new Boom('receipient present, but msg not from me', { data: stanza });
190
+ }
191
+ if (isMe(from) || isMeLid(from)) {
192
+ fromMe = true;
193
+ }
194
+ chatId = recipient;
195
+ }
196
+ else {
197
+ // Peer-routed self stanzas (history sync, app-state sync, etc.) arrive
198
+ // with `from` set to our own device but no `recipient` attribute —
199
+ // still mark as fromMe so self-only protocolMessage handlers run.
200
+ if (isMe(from) || isMeLid(from)) {
201
+ fromMe = true;
202
+ }
203
+ chatId = from;
204
+ }
205
+ msgType = 'chat';
206
+ author = from;
207
+ }
208
+ else if (isJidGroup(from)) {
209
+ if (!participant) {
210
+ throw new Boom('No participant in group message');
211
+ }
212
+ if (isMe(participant) || isMeLid(participant)) {
213
+ fromMe = true;
214
+ }
215
+ msgType = 'group';
216
+ author = participant;
217
+ chatId = from;
218
+ }
219
+ else if (isJidBroadcast(from)) {
220
+ if (!participant) {
221
+ throw new Boom('No participant in group message');
222
+ }
223
+ const isParticipantMe = isMe(participant);
224
+ if (isJidStatusBroadcast(from)) {
225
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
226
+ }
227
+ else {
228
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
229
+ }
230
+ fromMe = isParticipantMe;
231
+ chatId = from;
232
+ author = participant;
233
+ }
234
+ else if (isJidNewsletter(from)) {
235
+ msgType = 'newsletter';
236
+ chatId = from;
237
+ author = from;
238
+ if (isMe(from) || isMeLid(from)) {
239
+ fromMe = true;
240
+ }
241
+ }
242
+ else {
243
+ throw new Boom('Unknown message type', { data: stanza });
244
+ }
245
+ const pushname = stanza?.attrs?.notify;
246
+ const key = {
247
+ remoteJid: chatId,
248
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
249
+ remoteJidUsername: !isJidGroup(chatId)
250
+ ? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username
251
+ : undefined,
252
+ fromMe,
253
+ id: msgId,
254
+ participant,
255
+ participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
256
+ participantUsername: stanza.attrs.participant ? stanza.attrs.participant_username : undefined,
257
+ addressingMode: addressingContext.addressingMode,
258
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
259
+ };
260
+ const fullMessage = {
261
+ key,
262
+ category: stanza.attrs.category,
263
+ messageTimestamp: +stanza.attrs.t,
264
+ pushName: pushname,
265
+ broadcast: isJidBroadcast(from)
266
+ };
267
+ if (key.fromMe) {
268
+ fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
269
+ }
270
+ return {
271
+ fullMessage,
272
+ author,
273
+ sender: msgType === 'chat' ? author : chatId
274
+ };
275
+ }
276
+ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
277
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
278
+ // Support for the "msmsg" envelope (bot responses, e.g. Meta AI in a
279
+ // chat/group) — these fields are only populated when the stanza actually
280
+ // carries a msmsg part, via the <meta>/<bot> sibling tags WhatsApp sends
281
+ // alongside it.
282
+ let metaTargetId = null;
283
+ let botEditTargetId = null;
284
+ let botType = null;
285
+ let metaTargetSenderJid = null;
286
+ return {
287
+ fullMessage,
288
+ category: stanza.attrs.category,
289
+ author,
290
+ async decrypt() {
291
+ let decryptables = 0;
292
+ if (Array.isArray(stanza.content)) {
293
+ let hasMsmsg = false;
294
+ for (const { attrs } of stanza.content) {
295
+ if (attrs?.type === 'msmsg') {
296
+ hasMsmsg = true;
297
+ break;
298
+ }
299
+ }
300
+ if (hasMsmsg) {
301
+ for (const { tag, attrs } of stanza.content) {
302
+ if (tag === 'meta' && attrs?.target_id) {
303
+ metaTargetId = attrs.target_id;
304
+ }
305
+ if (tag === 'meta' && attrs?.target_sender_jid) {
306
+ metaTargetSenderJid = attrs.target_sender_jid;
307
+ }
308
+ if (tag === 'bot' && attrs && 'edit_target_id' in attrs) {
309
+ botEditTargetId = attrs.edit_target_id;
310
+ }
311
+ if (tag === 'bot' && attrs?.edit) {
312
+ botType = attrs.edit;
313
+ }
314
+ }
315
+ }
316
+ for (const { tag, attrs, content } of stanza.content) {
317
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
318
+ const cert = proto.VerifiedNameCertificate.decode(content);
319
+ const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
320
+ fullMessage.verifiedBizName = details.verifiedName;
321
+ }
322
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
323
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
324
+ }
325
+ if (attrs.count && tag === 'enc') {
326
+ fullMessage.retryCount = Number(attrs.count);
327
+ }
328
+ if (tag !== 'enc' && tag !== 'plaintext') {
329
+ continue;
330
+ }
331
+ if (!(content instanceof Uint8Array)) {
332
+ continue;
333
+ }
334
+ decryptables += 1;
335
+ let msgBuffer;
336
+ const decryptionJid = await getDecryptionJid(author, repository);
337
+ if (tag !== 'plaintext') {
338
+ // TODO: Handle hosted devices
339
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
340
+ }
341
+ try {
342
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
343
+ switch (e2eType) {
344
+ case 'skmsg':
345
+ msgBuffer = await repository.decryptGroupMessage({
346
+ group: sender,
347
+ authorJid: author,
348
+ msg: content
349
+ });
350
+ break;
351
+ case 'pkmsg':
352
+ case 'msg':
353
+ msgBuffer = await repository.decryptMessage({
354
+ jid: decryptionJid,
355
+ type: e2eType,
356
+ ciphertext: content
357
+ });
358
+ break;
359
+ case 'plaintext':
360
+ msgBuffer = content;
361
+ break;
362
+ case 'msmsg':
363
+ {
364
+ if (botType !== null && !['full', 'last'].includes(botType)) {
365
+ break;
366
+ }
367
+ const secretIdCandidates = [botEditTargetId, metaTargetId, fullMessage.key?.id].filter(Boolean);
368
+ const secretCandidates = [];
369
+ const seenSecrets = new Set();
370
+ for (const idCandidate of secretIdCandidates) {
371
+ const byId = botMessageSecrets.get(idCandidate);
372
+ if (!byId) {
373
+ continue;
374
+ }
375
+ const fp = byId.toString('hex');
376
+ if (!seenSecrets.has(fp)) {
377
+ seenSecrets.add(fp);
378
+ secretCandidates.push({ source: `id:${idCandidate}`, secret: byId });
379
+ }
380
+ }
381
+ const chatRecent = botRecentSecretsByChat.get(sender) || [];
382
+ for (const item of chatRecent) {
383
+ const fp = item.secret.toString('hex');
384
+ if (!seenSecrets.has(fp)) {
385
+ seenSecrets.add(fp);
386
+ secretCandidates.push({ source: `chat:${item.id}`, secret: item.secret });
387
+ }
388
+ if (secretCandidates.length >= 6) {
389
+ break;
390
+ }
391
+ }
392
+ if (!secretCandidates.length) {
393
+ logger.warn({ metaTargetId, botType, secretIdCandidates }, 'msmsg: no candidate messageSecret found, skipping');
394
+ break;
395
+ }
396
+ const msMsg = proto.MessageSecretMessage.decode(content);
397
+ const helperKey = {
398
+ participant: author,
399
+ meId: metaTargetSenderJid || `${meLid.split(':')[0]}@lid`,
400
+ meLid,
401
+ conversationJid: sender,
402
+ senderJid: metaTargetSenderJid,
403
+ botType,
404
+ botEditTargetId,
405
+ metaTargetId,
406
+ stanzaId: stanza.attrs?.id,
407
+ targetId: botEditTargetId || metaTargetId || stanza.attrs?.id,
408
+ targetIdCandidates: secretIdCandidates
409
+ };
410
+ let decryptErr;
411
+ const candidateAttemptSummaries = [];
412
+ for (const candidate of secretCandidates) {
413
+ try {
414
+ msgBuffer = await decryptMsmsgBotMessage(candidate.secret, helperKey, msMsg);
415
+ logger.debug({ source: candidate.source }, 'msmsg: decrypted with candidate secret');
416
+ break;
417
+ }
418
+ catch (e) {
419
+ decryptErr = e;
420
+ if (Array.isArray(e?.attemptedStrategies) && e.attemptedStrategies.length) {
421
+ candidateAttemptSummaries.push({
422
+ secretSource: candidate.source,
423
+ attemptedStrategies: e.attemptedStrategies
424
+ });
425
+ }
426
+ }
427
+ }
428
+ if (!msgBuffer && candidateAttemptSummaries.length) {
429
+ logger.warn({
430
+ secretCandidateSources: secretCandidates.map((candidate) => candidate.source),
431
+ attemptsBySecret: candidateAttemptSummaries
432
+ }, 'msmsg: helper decryption failed for all candidate secrets');
433
+ }
434
+ if (!msgBuffer && decryptErr) {
435
+ throw decryptErr;
436
+ }
437
+ }
438
+ break;
439
+ default:
440
+ throw new Error(`Unknown e2e type: ${e2eType}`);
441
+ }
442
+ if (!msgBuffer) {
443
+ continue;
444
+ }
445
+ let msg = e2eType === 'msmsg'
446
+ ? decodeDecryptedMsmsgMessage(msgBuffer)
447
+ : proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer);
448
+ msg = msg.deviceSentMessage?.message || msg;
449
+ if (msg.senderKeyDistributionMessage) {
450
+ //eslint-disable-next-line max-depth
451
+ try {
452
+ await repository.processSenderKeyDistributionMessage({
453
+ authorJid: author,
454
+ item: msg.senderKeyDistributionMessage
455
+ });
456
+ }
457
+ catch (err) {
458
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
459
+ }
460
+ }
461
+ if (fullMessage.message) {
462
+ Object.assign(fullMessage.message, msg);
463
+ }
464
+ else {
465
+ fullMessage.message = msg;
466
+ }
467
+ }
468
+ catch (err) {
469
+ const errorContext = {
470
+ key: fullMessage.key,
471
+ err,
472
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
473
+ sender,
474
+ author,
475
+ isSessionRecordError: isSessionRecordError(err)
476
+ };
477
+ logger.error(errorContext, 'failed to decrypt message');
478
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
479
+ fullMessage.messageStubParameters = [err.message.toString()];
480
+ }
481
+ }
482
+ }
483
+ // if nothing was found to decrypt
484
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
485
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
486
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
487
+ }
488
+ }
489
+ };
490
+ };
491
+ /**
492
+ * Utility function to check if an error is related to missing session record
493
+ */
494
+ function isSessionRecordError(error) {
495
+ const errorMessage = error?.message || error?.toString() || '';
496
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
497
+ }
498
+ //# sourceMappingURL=decode-wa-message.js.map