@zervonexx/baileys 5.0.0 → 5.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.
- package/LICENSE +22 -22
- package/README.md +4112 -4112
- package/WAProto/WAProtoCompile.js +322 -322
- package/WAProto/fetcher.js +67 -67
- package/WAProto/index.js +95 -95
- package/WAProto/parser.js +333 -333
- package/lib/Builders/AIRich.js +673 -673
- package/lib/Builders/auto.js +49 -49
- package/lib/Builders/base.js +144 -144
- package/lib/Builders/builders.js +588 -588
- package/lib/Builders/index.js +3 -3
- package/lib/Defaults/index.js +248 -248
- package/lib/Signal/index.js +2 -2
- package/lib/Signal/libsignal.js +526 -526
- package/lib/Signal/lid-mapping.js +282 -282
- package/lib/Socket/Client/index.js +1 -1
- package/lib/Socket/Client/types.js +9 -9
- package/lib/Socket/Client/websocket.js +83 -83
- package/lib/Socket/business.js +151 -151
- package/lib/Socket/chats.js +854 -854
- package/lib/Socket/communities.js +146 -146
- package/lib/Socket/groups.js +293 -293
- package/lib/Socket/index.js +14 -14
- package/lib/Socket/messages-recv.js +993 -993
- package/lib/Socket/messages-send.js +722 -722
- package/lib/Socket/mex.js +33 -33
- package/lib/Socket/newsletter.js +783 -783
- package/lib/Socket/registration.js +154 -154
- package/lib/Socket/socket.js +797 -797
- package/lib/Socket/spam-report.js +143 -143
- package/lib/Socket/username.js +81 -81
- package/lib/Socket/zervonex-handler.js +57 -57
- package/lib/Store/index.js +6 -6
- package/lib/Store/make-cache-manager-store.js +80 -80
- package/lib/Store/make-in-memory-store.js +426 -426
- package/lib/Store/make-ordered-dictionary.js +81 -81
- package/lib/Store/object-repository.js +30 -30
- package/lib/Store/reporting-info-store.js +37 -37
- package/lib/Types/Auth.js +1 -1
- package/lib/Types/Bussines.js +1 -1
- package/lib/Types/Call.js +1 -1
- package/lib/Types/Chat.js +7 -7
- package/lib/Types/Contact.js +1 -1
- package/lib/Types/Events.js +1 -1
- package/lib/Types/GroupMetadata.js +1 -1
- package/lib/Types/Label.js +24 -24
- package/lib/Types/LabelAssociation.js +6 -6
- package/lib/Types/Message.js +14 -14
- package/lib/Types/Newsletter.js +99 -99
- package/lib/Types/Product.js +1 -1
- package/lib/Types/Signal.js +1 -1
- package/lib/Types/Socket.js +14 -14
- package/lib/Types/State.js +26 -26
- package/lib/Types/USync.js +1 -1
- package/lib/Types/index.js +30 -30
- package/lib/Utils/auth-utils.js +159 -159
- package/lib/Utils/baileys-event-stream.js +32 -32
- package/lib/Utils/bot-capabilities.js +40 -40
- package/lib/Utils/bot-planning-replay.js +43 -43
- package/lib/Utils/browser-utils.js +29 -29
- package/lib/Utils/business.js +74 -74
- package/lib/Utils/chat-utils.js +316 -316
- package/lib/Utils/companion-reg-client-utils.js +19 -19
- package/lib/Utils/consumer-application.js +37 -37
- package/lib/Utils/crypto.js +52 -52
- package/lib/Utils/cstoken.js +14 -14
- package/lib/Utils/decode-wa-message.js +199 -199
- package/lib/Utils/event-buffer.js +272 -272
- package/lib/Utils/extras.js +186 -186
- package/lib/Utils/generics.js +194 -194
- package/lib/Utils/history.js +50 -50
- package/lib/Utils/identity-change-handler.js +18 -18
- package/lib/Utils/index.js +40 -40
- package/lib/Utils/link-preview.js +50 -50
- package/lib/Utils/logger.js +2 -2
- package/lib/Utils/lt-hash.js +3 -3
- package/lib/Utils/make-mutex.js +15 -15
- package/lib/Utils/message-composer.js +61 -61
- package/lib/Utils/message-retry-manager.js +47 -47
- package/lib/Utils/messages-media.js +501 -501
- package/lib/Utils/messages.js +942 -942
- package/lib/Utils/meta-ai-msmsg.js +121 -121
- package/lib/Utils/meta-compositing.js +74 -74
- package/lib/Utils/modern-messages.js +234 -234
- package/lib/Utils/native-flow.js +80 -80
- package/lib/Utils/noise-handler.js +160 -160
- package/lib/Utils/pre-key-manager.js +75 -75
- package/lib/Utils/process-message.js +400 -400
- package/lib/Utils/reporting-utils.js +170 -170
- package/lib/Utils/signal.js +166 -166
- package/lib/Utils/spam-report-utils.js +165 -165
- package/lib/Utils/sync-action-utils.js +33 -33
- package/lib/Utils/tc-token-utils.js +153 -153
- package/lib/Utils/use-keyv-auth-state.js +199 -199
- package/lib/Utils/use-multi-file-auth-state.js +83 -83
- package/lib/Utils/validate-connection.js +171 -171
- package/lib/WABinary/constants.js +1320 -1320
- package/lib/WABinary/decode.js +151 -151
- package/lib/WABinary/encode.js +139 -139
- package/lib/WABinary/generic-utils.js +202 -202
- package/lib/WABinary/index.js +6 -6
- package/lib/WABinary/jid-utils.js +235 -235
- package/lib/WABinary/types.js +4 -4
- package/lib/WAM/BinaryInfo.js +9 -9
- package/lib/WAM/constants.js +22852 -22852
- package/lib/WAM/encode.js +149 -149
- package/lib/WAM/index.js +3 -3
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
- package/lib/WAUSync/Protocols/index.js +12 -12
- package/lib/WAUSync/USyncQuery.js +88 -88
- package/lib/WAUSync/USyncUser.js +20 -20
- package/lib/WAUSync/index.js +3 -3
- package/lib/index.js +66 -66
- package/package.json +191 -192
|
@@ -1,200 +1,200 @@
|
|
|
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 } from '../WABinary/index.js'
|
|
4
|
-
import { unpadRandomMax16 } from './generics.js'
|
|
5
|
-
|
|
6
|
-
export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node'
|
|
7
|
-
export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled'
|
|
8
|
-
export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted'
|
|
9
|
-
|
|
10
|
-
export const DECRYPTION_RETRY_CONFIG = { maxRetries: 3, baseDelayMs: 100, sessionRecordErrors: ['No session record', 'SessionError: No session record'] }
|
|
11
|
-
|
|
12
|
-
export const NACK_REASONS = {
|
|
13
|
-
ParsingError: 487, UnrecognizedStanza: 488, UnrecognizedStanzaClass: 489, UnrecognizedStanzaType: 490,
|
|
14
|
-
InvalidProtobuf: 491, InvalidHostedCompanionStanza: 493, MissingMessageSecret: 495,
|
|
15
|
-
SignalErrorOldCounter: 496, MessageDeletedOnPeer: 499, UnhandledError: 500,
|
|
16
|
-
UnsupportedAdminRevoke: 550, UnsupportedLIDGroup: 551, DBOperationFailed: 552
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export const SERVER_ERROR_CODES = { MessageAccountRestriction: '463', SmaxInvalid: '479' }
|
|
20
|
-
|
|
21
|
-
export const getDecryptionJid = async (sender, repository, logger) => {
|
|
22
|
-
if (isJidNewsletter(sender) || isJidStatusBroadcast(sender) || isJidMetaAI(sender)) return sender
|
|
23
|
-
if (isLidUser(sender) || isHostedLidUser(sender)) return sender
|
|
24
|
-
return (await repository.lidMapping.getLIDForPN(sender)) || sender
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger, meId, meLid) => {
|
|
28
|
-
const { senderAlt } = extractAddressingContext(stanza)
|
|
29
|
-
if (!senderAlt) return
|
|
30
|
-
if (isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
|
|
31
|
-
if (areJidsSameUser(sender, meId) || areJidsSameUser(senderAlt, meLid)) return
|
|
32
|
-
try {
|
|
33
|
-
await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }])
|
|
34
|
-
repository.migrateSession(sender, senderAlt).catch(err => logger?.warn?.({ sender, senderAlt, err }, 'Failed to migrate session (PN→LID)'))
|
|
35
|
-
logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope (PN→LID)')
|
|
36
|
-
} catch (error) { logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping (PN→LID)') }
|
|
37
|
-
} else if (isPnUser(senderAlt) && isLidUser(sender)) {
|
|
38
|
-
if (areJidsSameUser(sender, meLid) || areJidsSameUser(senderAlt, meId)) return
|
|
39
|
-
try {
|
|
40
|
-
await repository.lidMapping.storeLIDPNMappings([{ lid: sender, pn: senderAlt }])
|
|
41
|
-
repository.migrateSession(senderAlt, sender).catch(err => logger?.warn?.({ sender, senderAlt, err }, 'Failed to migrate session (LID→PN)'))
|
|
42
|
-
logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope (LID→PN)')
|
|
43
|
-
} catch (error) { logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping (LID→PN)') }
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export const extractAddressingContext = stanza => {
|
|
48
|
-
const sender = stanza.attrs.participant || stanza.attrs.from
|
|
49
|
-
const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn')
|
|
50
|
-
let senderAlt, recipientAlt
|
|
51
|
-
if (addressingMode === 'lid') {
|
|
52
|
-
senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn
|
|
53
|
-
recipientAlt = stanza.attrs.recipient_pn
|
|
54
|
-
} else {
|
|
55
|
-
senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid
|
|
56
|
-
recipientAlt = stanza.attrs.recipient_lid
|
|
57
|
-
}
|
|
58
|
-
return { addressingMode, senderAlt, recipientAlt }
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
const findChildByTag = (node, tag) => Array.isArray(node?.content) ? node.content.find(c => c?.tag === tag) : undefined
|
|
62
|
-
|
|
63
|
-
export const extractNewsletterMessageMeta = stanza => {
|
|
64
|
-
const meta = findChildByTag(stanza, 'meta')
|
|
65
|
-
if (!meta) return undefined
|
|
66
|
-
const result = {}
|
|
67
|
-
const adminProfile = findChildByTag(meta, 'admin_profile')
|
|
68
|
-
if (adminProfile) {
|
|
69
|
-
const name = findChildByTag(adminProfile, 'name')
|
|
70
|
-
const picture = findChildByTag(adminProfile, 'picture')
|
|
71
|
-
const content = name?.content
|
|
72
|
-
result.adminProfile = {
|
|
73
|
-
id: adminProfile.attrs?.id,
|
|
74
|
-
name: typeof content === 'string' ? content : content instanceof Uint8Array ? Buffer.from(content).toString('utf-8') : undefined,
|
|
75
|
-
pictureId: picture?.attrs?.id,
|
|
76
|
-
pictureDirectPath: picture?.attrs?.direct_path
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
if (findChildByTag(meta, 'paid_partnership')) result.paidPartnership = true
|
|
80
|
-
if (findChildByTag(meta, 'ai_content')) result.aiContent = true
|
|
81
|
-
return result
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export const decodeMessageNode = (stanza, meId, meLid) => {
|
|
85
|
-
let msgType, chatId, author, fromMe = false
|
|
86
|
-
const { id: msgId, from, participant, recipient } = stanza.attrs
|
|
87
|
-
const addressingContext = extractAddressingContext(stanza)
|
|
88
|
-
const isMe = jid => areJidsSameUser(jid, meId)
|
|
89
|
-
const isMeLid = jid => areJidsSameUser(jid, meLid)
|
|
90
|
-
|
|
91
|
-
if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
|
|
92
|
-
if (isMe(from) || isMeLid(from)) fromMe = true
|
|
93
|
-
chatId = (recipient && !isJidMetaAI(recipient)) ? (fromMe ? recipient : (() => { throw new Boom('recipient present, but msg not from me', { data: stanza }) })()) : from
|
|
94
|
-
msgType = 'chat'; author = from
|
|
95
|
-
} else if (isJidGroup(from)) {
|
|
96
|
-
if (!participant) throw new Boom('No participant in group message')
|
|
97
|
-
if (isMe(participant) || isMeLid(participant)) fromMe = true
|
|
98
|
-
msgType = 'group'; author = participant; chatId = from
|
|
99
|
-
} else if (isJidBroadcast(from)) {
|
|
100
|
-
if (!participant) throw new Boom('No participant in group message')
|
|
101
|
-
const isParticipantMe = isMe(participant)
|
|
102
|
-
msgType = isJidStatusBroadcast(from) ? (isParticipantMe ? 'direct_peer_status' : 'other_status') : (isParticipantMe ? 'peer_broadcast' : 'other_broadcast')
|
|
103
|
-
fromMe = isParticipantMe; chatId = from; author = participant
|
|
104
|
-
} else if (isJidNewsletter(from)) {
|
|
105
|
-
msgType = 'newsletter'; chatId = from; author = from
|
|
106
|
-
if (isMe(from) || isMeLid(from)) fromMe = true
|
|
107
|
-
} else throw new Boom('Unknown message type', { data: stanza })
|
|
108
|
-
|
|
109
|
-
const key = {
|
|
110
|
-
remoteJid: chatId,
|
|
111
|
-
remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
|
112
|
-
fromMe, id: msgId, participant,
|
|
113
|
-
participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
|
114
|
-
addressingMode: addressingContext.addressingMode,
|
|
115
|
-
...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
|
|
116
|
-
}
|
|
117
|
-
const fullMessage = { key, messageTimestamp: +stanza.attrs.t, pushName: stanza.attrs?.notify, broadcast: isJidBroadcast(from) }
|
|
118
|
-
if (key.fromMe) fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK
|
|
119
|
-
return { fullMessage, author, sender: msgType === 'chat' ? author : chatId }
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
|
|
123
|
-
const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
|
|
124
|
-
return {
|
|
125
|
-
fullMessage,
|
|
126
|
-
category: stanza.attrs.category,
|
|
127
|
-
author,
|
|
128
|
-
async decrypt() {
|
|
129
|
-
let decryptables = 0
|
|
130
|
-
if (Array.isArray(stanza.content)) {
|
|
131
|
-
for (const { tag, attrs, content } of stanza.content) {
|
|
132
|
-
if (tag === 'verified_name' && content instanceof Uint8Array) {
|
|
133
|
-
const cert = proto.VerifiedNameCertificate.decode(content)
|
|
134
|
-
fullMessage.verifiedBizName = proto.VerifiedNameCertificate.Details.decode(cert.details).verifiedName
|
|
135
|
-
}
|
|
136
|
-
if (tag === 'unavailable' && attrs.type === 'view_once') fullMessage.key.isViewOnce = true
|
|
137
|
-
if (tag !== 'enc' && tag !== 'plaintext') continue
|
|
138
|
-
if (!(content instanceof Uint8Array)) continue
|
|
139
|
-
decryptables++
|
|
140
|
-
const decryptionJid = await getDecryptionJid(author, repository, logger)
|
|
141
|
-
const { senderAlt } = extractAddressingContext(stanza)
|
|
142
|
-
const decryptionAltJid = senderAlt ? await getDecryptionJid(senderAlt, repository, logger) : null
|
|
143
|
-
if (tag !== 'plaintext') storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger, meId, meLid).catch(err => logger?.warn?.({ err }, 'storeMappingFromEnvelope failed'))
|
|
144
|
-
try {
|
|
145
|
-
const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type
|
|
146
|
-
switch (e2eType) {
|
|
147
|
-
case 'skmsg':
|
|
148
|
-
try {
|
|
149
|
-
fullMessage._msgBuffer = await repository.decryptGroupMessage({ group: sender, authorJid: author, msg: content })
|
|
150
|
-
} catch (decryptErr) {
|
|
151
|
-
const errMsg = decryptErr?.message || decryptErr?.toString() || ''
|
|
152
|
-
if (errMsg.includes('memory access out of bounds') || errMsg.includes('too far into the future')) {
|
|
153
|
-
logger?.warn?.({ sender, author, errMsg }, '[Signal] Stale/future sender key — deleting and skipping')
|
|
154
|
-
await repository.deleteSenderKey(sender, author).catch(e => logger?.error?.('[Signal] Failed to delete sender key:', e))
|
|
155
|
-
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
|
156
|
-
fullMessage.messageStubParameters = [errMsg]
|
|
157
|
-
continue
|
|
158
|
-
}
|
|
159
|
-
throw decryptErr
|
|
160
|
-
}
|
|
161
|
-
break
|
|
162
|
-
case 'pkmsg':
|
|
163
|
-
case 'msg': {
|
|
164
|
-
const buf = await repository.decryptMessage({ jid: decryptionJid, type: e2eType, ciphertext: content })
|
|
165
|
-
if (buf === null) return // DuplicatedMessage — libsignal handled silently
|
|
166
|
-
fullMessage._msgBuffer = buf
|
|
167
|
-
break
|
|
168
|
-
}
|
|
169
|
-
case 'plaintext':
|
|
170
|
-
fullMessage._msgBuffer = content
|
|
171
|
-
break
|
|
172
|
-
case 'msmsg':
|
|
173
|
-
if (!stanza.attrs._msmsgDecrypted) throw new Error('msmsg type but no pre-decrypted message available')
|
|
174
|
-
{ let msg = stanza.attrs._msmsgDecrypted; msg = msg.deviceSentMessage?.message || msg; fullMessage.message ? Object.assign(fullMessage.message, msg) : (fullMessage.message = msg) }
|
|
175
|
-
continue
|
|
176
|
-
default:
|
|
177
|
-
throw new Error(`Unknown e2e type: ${e2eType}`)
|
|
178
|
-
}
|
|
179
|
-
let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(fullMessage._msgBuffer) : fullMessage._msgBuffer)
|
|
180
|
-
msg = msg.deviceSentMessage?.message || msg
|
|
181
|
-
if (msg.senderKeyDistributionMessage) {
|
|
182
|
-
await repository.processSenderKeyDistributionMessage({ authorJid: author, item: msg.senderKeyDistributionMessage })
|
|
183
|
-
.catch(err => logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message'))
|
|
184
|
-
}
|
|
185
|
-
fullMessage.message ? Object.assign(fullMessage.message, msg) : (fullMessage.message = msg)
|
|
186
|
-
const viewOnceInner = msg?.viewOnceMessage?.message || msg?.viewOnceMessageV2?.message || msg?.viewOnceMessageV2Extension?.message
|
|
187
|
-
if (viewOnceInner?.imageMessage?.viewOnce || viewOnceInner?.videoMessage?.viewOnce || viewOnceInner?.audioMessage?.viewOnce) fullMessage.key.isViewOnce = true
|
|
188
|
-
} catch (err) {
|
|
189
|
-
const errStr = err?.message || (typeof err === 'string' ? err : '') || ''
|
|
190
|
-
const isExpected = errStr.includes('InvalidPreKeyId') || errStr.includes('SessionNotFound') || errStr.includes('InvalidMessage') || errStr.includes('no sender key state') || errStr.includes('memory access out of bounds') || errStr.includes('old counter') || errStr.includes('DuplicatedMessage') || errStr.includes('BadMac')
|
|
191
|
-
; (isExpected ? logger?.debug?.bind(logger) : logger?.error?.bind(logger))?.({ key: fullMessage.key, err, errStr, messageType: tag === 'plaintext' ? 'plaintext' : attrs.type, sender, author }, 'failed to decrypt message')
|
|
192
|
-
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
|
193
|
-
fullMessage.messageStubParameters = [errStr]
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
if (!decryptables) { fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT; fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT] }
|
|
198
|
-
}
|
|
199
|
-
}
|
|
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 } from '../WABinary/index.js'
|
|
4
|
+
import { unpadRandomMax16 } from './generics.js'
|
|
5
|
+
|
|
6
|
+
export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node'
|
|
7
|
+
export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled'
|
|
8
|
+
export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted'
|
|
9
|
+
|
|
10
|
+
export const DECRYPTION_RETRY_CONFIG = { maxRetries: 3, baseDelayMs: 100, sessionRecordErrors: ['No session record', 'SessionError: No session record'] }
|
|
11
|
+
|
|
12
|
+
export const NACK_REASONS = {
|
|
13
|
+
ParsingError: 487, UnrecognizedStanza: 488, UnrecognizedStanzaClass: 489, UnrecognizedStanzaType: 490,
|
|
14
|
+
InvalidProtobuf: 491, InvalidHostedCompanionStanza: 493, MissingMessageSecret: 495,
|
|
15
|
+
SignalErrorOldCounter: 496, MessageDeletedOnPeer: 499, UnhandledError: 500,
|
|
16
|
+
UnsupportedAdminRevoke: 550, UnsupportedLIDGroup: 551, DBOperationFailed: 552
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const SERVER_ERROR_CODES = { MessageAccountRestriction: '463', SmaxInvalid: '479' }
|
|
20
|
+
|
|
21
|
+
export const getDecryptionJid = async (sender, repository, logger) => {
|
|
22
|
+
if (isJidNewsletter(sender) || isJidStatusBroadcast(sender) || isJidMetaAI(sender)) return sender
|
|
23
|
+
if (isLidUser(sender) || isHostedLidUser(sender)) return sender
|
|
24
|
+
return (await repository.lidMapping.getLIDForPN(sender)) || sender
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger, meId, meLid) => {
|
|
28
|
+
const { senderAlt } = extractAddressingContext(stanza)
|
|
29
|
+
if (!senderAlt) return
|
|
30
|
+
if (isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
|
|
31
|
+
if (areJidsSameUser(sender, meId) || areJidsSameUser(senderAlt, meLid)) return
|
|
32
|
+
try {
|
|
33
|
+
await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }])
|
|
34
|
+
repository.migrateSession(sender, senderAlt).catch(err => logger?.warn?.({ sender, senderAlt, err }, 'Failed to migrate session (PN→LID)'))
|
|
35
|
+
logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope (PN→LID)')
|
|
36
|
+
} catch (error) { logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping (PN→LID)') }
|
|
37
|
+
} else if (isPnUser(senderAlt) && isLidUser(sender)) {
|
|
38
|
+
if (areJidsSameUser(sender, meLid) || areJidsSameUser(senderAlt, meId)) return
|
|
39
|
+
try {
|
|
40
|
+
await repository.lidMapping.storeLIDPNMappings([{ lid: sender, pn: senderAlt }])
|
|
41
|
+
repository.migrateSession(senderAlt, sender).catch(err => logger?.warn?.({ sender, senderAlt, err }, 'Failed to migrate session (LID→PN)'))
|
|
42
|
+
logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope (LID→PN)')
|
|
43
|
+
} catch (error) { logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping (LID→PN)') }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const extractAddressingContext = stanza => {
|
|
48
|
+
const sender = stanza.attrs.participant || stanza.attrs.from
|
|
49
|
+
const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn')
|
|
50
|
+
let senderAlt, recipientAlt
|
|
51
|
+
if (addressingMode === 'lid') {
|
|
52
|
+
senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn
|
|
53
|
+
recipientAlt = stanza.attrs.recipient_pn
|
|
54
|
+
} else {
|
|
55
|
+
senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid
|
|
56
|
+
recipientAlt = stanza.attrs.recipient_lid
|
|
57
|
+
}
|
|
58
|
+
return { addressingMode, senderAlt, recipientAlt }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const findChildByTag = (node, tag) => Array.isArray(node?.content) ? node.content.find(c => c?.tag === tag) : undefined
|
|
62
|
+
|
|
63
|
+
export const extractNewsletterMessageMeta = stanza => {
|
|
64
|
+
const meta = findChildByTag(stanza, 'meta')
|
|
65
|
+
if (!meta) return undefined
|
|
66
|
+
const result = {}
|
|
67
|
+
const adminProfile = findChildByTag(meta, 'admin_profile')
|
|
68
|
+
if (adminProfile) {
|
|
69
|
+
const name = findChildByTag(adminProfile, 'name')
|
|
70
|
+
const picture = findChildByTag(adminProfile, 'picture')
|
|
71
|
+
const content = name?.content
|
|
72
|
+
result.adminProfile = {
|
|
73
|
+
id: adminProfile.attrs?.id,
|
|
74
|
+
name: typeof content === 'string' ? content : content instanceof Uint8Array ? Buffer.from(content).toString('utf-8') : undefined,
|
|
75
|
+
pictureId: picture?.attrs?.id,
|
|
76
|
+
pictureDirectPath: picture?.attrs?.direct_path
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (findChildByTag(meta, 'paid_partnership')) result.paidPartnership = true
|
|
80
|
+
if (findChildByTag(meta, 'ai_content')) result.aiContent = true
|
|
81
|
+
return result
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const decodeMessageNode = (stanza, meId, meLid) => {
|
|
85
|
+
let msgType, chatId, author, fromMe = false
|
|
86
|
+
const { id: msgId, from, participant, recipient } = stanza.attrs
|
|
87
|
+
const addressingContext = extractAddressingContext(stanza)
|
|
88
|
+
const isMe = jid => areJidsSameUser(jid, meId)
|
|
89
|
+
const isMeLid = jid => areJidsSameUser(jid, meLid)
|
|
90
|
+
|
|
91
|
+
if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
|
|
92
|
+
if (isMe(from) || isMeLid(from)) fromMe = true
|
|
93
|
+
chatId = (recipient && !isJidMetaAI(recipient)) ? (fromMe ? recipient : (() => { throw new Boom('recipient present, but msg not from me', { data: stanza }) })()) : from
|
|
94
|
+
msgType = 'chat'; author = from
|
|
95
|
+
} else if (isJidGroup(from)) {
|
|
96
|
+
if (!participant) throw new Boom('No participant in group message')
|
|
97
|
+
if (isMe(participant) || isMeLid(participant)) fromMe = true
|
|
98
|
+
msgType = 'group'; author = participant; chatId = from
|
|
99
|
+
} else if (isJidBroadcast(from)) {
|
|
100
|
+
if (!participant) throw new Boom('No participant in group message')
|
|
101
|
+
const isParticipantMe = isMe(participant)
|
|
102
|
+
msgType = isJidStatusBroadcast(from) ? (isParticipantMe ? 'direct_peer_status' : 'other_status') : (isParticipantMe ? 'peer_broadcast' : 'other_broadcast')
|
|
103
|
+
fromMe = isParticipantMe; chatId = from; author = participant
|
|
104
|
+
} else if (isJidNewsletter(from)) {
|
|
105
|
+
msgType = 'newsletter'; chatId = from; author = from
|
|
106
|
+
if (isMe(from) || isMeLid(from)) fromMe = true
|
|
107
|
+
} else throw new Boom('Unknown message type', { data: stanza })
|
|
108
|
+
|
|
109
|
+
const key = {
|
|
110
|
+
remoteJid: chatId,
|
|
111
|
+
remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
|
112
|
+
fromMe, id: msgId, participant,
|
|
113
|
+
participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
|
114
|
+
addressingMode: addressingContext.addressingMode,
|
|
115
|
+
...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
|
|
116
|
+
}
|
|
117
|
+
const fullMessage = { key, messageTimestamp: +stanza.attrs.t, pushName: stanza.attrs?.notify, broadcast: isJidBroadcast(from) }
|
|
118
|
+
if (key.fromMe) fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK
|
|
119
|
+
return { fullMessage, author, sender: msgType === 'chat' ? author : chatId }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
|
|
123
|
+
const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
|
|
124
|
+
return {
|
|
125
|
+
fullMessage,
|
|
126
|
+
category: stanza.attrs.category,
|
|
127
|
+
author,
|
|
128
|
+
async decrypt() {
|
|
129
|
+
let decryptables = 0
|
|
130
|
+
if (Array.isArray(stanza.content)) {
|
|
131
|
+
for (const { tag, attrs, content } of stanza.content) {
|
|
132
|
+
if (tag === 'verified_name' && content instanceof Uint8Array) {
|
|
133
|
+
const cert = proto.VerifiedNameCertificate.decode(content)
|
|
134
|
+
fullMessage.verifiedBizName = proto.VerifiedNameCertificate.Details.decode(cert.details).verifiedName
|
|
135
|
+
}
|
|
136
|
+
if (tag === 'unavailable' && attrs.type === 'view_once') fullMessage.key.isViewOnce = true
|
|
137
|
+
if (tag !== 'enc' && tag !== 'plaintext') continue
|
|
138
|
+
if (!(content instanceof Uint8Array)) continue
|
|
139
|
+
decryptables++
|
|
140
|
+
const decryptionJid = await getDecryptionJid(author, repository, logger)
|
|
141
|
+
const { senderAlt } = extractAddressingContext(stanza)
|
|
142
|
+
const decryptionAltJid = senderAlt ? await getDecryptionJid(senderAlt, repository, logger) : null
|
|
143
|
+
if (tag !== 'plaintext') storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger, meId, meLid).catch(err => logger?.warn?.({ err }, 'storeMappingFromEnvelope failed'))
|
|
144
|
+
try {
|
|
145
|
+
const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type
|
|
146
|
+
switch (e2eType) {
|
|
147
|
+
case 'skmsg':
|
|
148
|
+
try {
|
|
149
|
+
fullMessage._msgBuffer = await repository.decryptGroupMessage({ group: sender, authorJid: author, msg: content })
|
|
150
|
+
} catch (decryptErr) {
|
|
151
|
+
const errMsg = decryptErr?.message || decryptErr?.toString() || ''
|
|
152
|
+
if (errMsg.includes('memory access out of bounds') || errMsg.includes('too far into the future')) {
|
|
153
|
+
logger?.warn?.({ sender, author, errMsg }, '[Signal] Stale/future sender key — deleting and skipping')
|
|
154
|
+
await repository.deleteSenderKey(sender, author).catch(e => logger?.error?.('[Signal] Failed to delete sender key:', e))
|
|
155
|
+
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
|
156
|
+
fullMessage.messageStubParameters = [errMsg]
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
159
|
+
throw decryptErr
|
|
160
|
+
}
|
|
161
|
+
break
|
|
162
|
+
case 'pkmsg':
|
|
163
|
+
case 'msg': {
|
|
164
|
+
const buf = await repository.decryptMessage({ jid: decryptionJid, type: e2eType, ciphertext: content })
|
|
165
|
+
if (buf === null) return // DuplicatedMessage — libsignal handled silently
|
|
166
|
+
fullMessage._msgBuffer = buf
|
|
167
|
+
break
|
|
168
|
+
}
|
|
169
|
+
case 'plaintext':
|
|
170
|
+
fullMessage._msgBuffer = content
|
|
171
|
+
break
|
|
172
|
+
case 'msmsg':
|
|
173
|
+
if (!stanza.attrs._msmsgDecrypted) throw new Error('msmsg type but no pre-decrypted message available')
|
|
174
|
+
{ let msg = stanza.attrs._msmsgDecrypted; msg = msg.deviceSentMessage?.message || msg; fullMessage.message ? Object.assign(fullMessage.message, msg) : (fullMessage.message = msg) }
|
|
175
|
+
continue
|
|
176
|
+
default:
|
|
177
|
+
throw new Error(`Unknown e2e type: ${e2eType}`)
|
|
178
|
+
}
|
|
179
|
+
let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(fullMessage._msgBuffer) : fullMessage._msgBuffer)
|
|
180
|
+
msg = msg.deviceSentMessage?.message || msg
|
|
181
|
+
if (msg.senderKeyDistributionMessage) {
|
|
182
|
+
await repository.processSenderKeyDistributionMessage({ authorJid: author, item: msg.senderKeyDistributionMessage })
|
|
183
|
+
.catch(err => logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message'))
|
|
184
|
+
}
|
|
185
|
+
fullMessage.message ? Object.assign(fullMessage.message, msg) : (fullMessage.message = msg)
|
|
186
|
+
const viewOnceInner = msg?.viewOnceMessage?.message || msg?.viewOnceMessageV2?.message || msg?.viewOnceMessageV2Extension?.message
|
|
187
|
+
if (viewOnceInner?.imageMessage?.viewOnce || viewOnceInner?.videoMessage?.viewOnce || viewOnceInner?.audioMessage?.viewOnce) fullMessage.key.isViewOnce = true
|
|
188
|
+
} catch (err) {
|
|
189
|
+
const errStr = err?.message || (typeof err === 'string' ? err : '') || ''
|
|
190
|
+
const isExpected = errStr.includes('InvalidPreKeyId') || errStr.includes('SessionNotFound') || errStr.includes('InvalidMessage') || errStr.includes('no sender key state') || errStr.includes('memory access out of bounds') || errStr.includes('old counter') || errStr.includes('DuplicatedMessage') || errStr.includes('BadMac')
|
|
191
|
+
; (isExpected ? logger?.debug?.bind(logger) : logger?.error?.bind(logger))?.({ key: fullMessage.key, err, errStr, messageType: tag === 'plaintext' ? 'plaintext' : attrs.type, sender, author }, 'failed to decrypt message')
|
|
192
|
+
fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
|
|
193
|
+
fullMessage.messageStubParameters = [errStr]
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (!decryptables) { fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT; fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT] }
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
200
|
}
|