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