@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.
Files changed (125) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4112 -4112
  3. package/WAProto/WAProtoCompile.js +322 -322
  4. package/WAProto/fetcher.js +67 -67
  5. package/WAProto/index.js +95 -95
  6. package/WAProto/parser.js +333 -333
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +248 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +14 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +194 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +2 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +942 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. 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
  }