@neelegirl/baileys 1.5.2 → 1.5.3

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 (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +195 -187
  3. package/WAProto/WAProto.proto +537 -236
  4. package/WAProto/index.d.ts +5971 -2388
  5. package/WAProto/index.js +17298 -6513
  6. package/lib/Defaults/baileys-version.json +3 -3
  7. package/lib/Defaults/index.d.ts +77 -67
  8. package/lib/Defaults/index.js +148 -136
  9. package/lib/Defaults/phonenumber-mcc.json +223 -223
  10. package/lib/Signal/WASignalGroup/GroupProtocol.js +1908 -1908
  11. package/lib/Signal/WASignalGroup/ciphertext-message.d.ts +9 -0
  12. package/lib/Signal/WASignalGroup/ciphertext-message.js +19 -0
  13. package/lib/Signal/WASignalGroup/ciphertext_message.js +15 -15
  14. package/lib/Signal/WASignalGroup/group-session-builder.d.ts +17 -0
  15. package/lib/Signal/WASignalGroup/group-session-builder.js +72 -0
  16. package/lib/Signal/WASignalGroup/group.proto +41 -41
  17. package/lib/Signal/WASignalGroup/group_cipher.d.ts +19 -0
  18. package/lib/Signal/WASignalGroup/group_cipher.js +101 -110
  19. package/lib/Signal/WASignalGroup/group_session_builder.js +45 -45
  20. package/lib/Signal/WASignalGroup/index.d.ts +11 -0
  21. package/lib/Signal/WASignalGroup/index.js +61 -6
  22. package/lib/Signal/WASignalGroup/keyhelper.d.ts +16 -0
  23. package/lib/Signal/WASignalGroup/keyhelper.js +58 -13
  24. package/lib/Signal/WASignalGroup/protobufs.js +2 -2
  25. package/lib/Signal/WASignalGroup/queue_job.js +68 -68
  26. package/lib/Signal/WASignalGroup/readme.md +5 -5
  27. package/lib/Signal/WASignalGroup/sender-chain-key.d.ts +14 -0
  28. package/lib/Signal/WASignalGroup/sender-chain-key.js +47 -0
  29. package/lib/Signal/WASignalGroup/sender-key-distribution-message.d.ts +17 -0
  30. package/lib/Signal/WASignalGroup/sender-key-distribution-message.js +71 -0
  31. package/lib/Signal/WASignalGroup/sender-key-message.d.ts +19 -0
  32. package/lib/Signal/WASignalGroup/sender-key-message.js +73 -0
  33. package/lib/Signal/WASignalGroup/sender-key-name.d.ts +19 -0
  34. package/lib/Signal/WASignalGroup/sender-key-name.js +59 -0
  35. package/lib/Signal/WASignalGroup/sender-key-record.d.ts +32 -0
  36. package/lib/Signal/WASignalGroup/sender-key-record.js +58 -0
  37. package/lib/Signal/WASignalGroup/sender-key-state.d.ts +44 -0
  38. package/lib/Signal/WASignalGroup/sender-key-state.js +147 -0
  39. package/lib/Signal/WASignalGroup/sender-message-key.d.ts +11 -0
  40. package/lib/Signal/WASignalGroup/sender-message-key.js +33 -0
  41. package/lib/Signal/WASignalGroup/sender_chain_key.js +49 -49
  42. package/lib/Signal/WASignalGroup/sender_key_distribution_message.js +77 -77
  43. package/lib/Signal/WASignalGroup/sender_key_message.js +91 -91
  44. package/lib/Signal/WASignalGroup/sender_key_name.js +69 -69
  45. package/lib/Signal/WASignalGroup/sender_key_record.js +55 -55
  46. package/lib/Signal/WASignalGroup/sender_key_state.js +128 -128
  47. package/lib/Signal/WASignalGroup/sender_message_key.js +38 -38
  48. package/lib/Signal/libsignal.d.ts +5 -1
  49. package/lib/Signal/libsignal.js +390 -161
  50. package/lib/Signal/lid-mapping.d.ts +28 -0
  51. package/lib/Signal/lid-mapping.js +184 -0
  52. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -15
  53. package/lib/Socket/Client/abstract-socket-client.js +13 -13
  54. package/lib/Socket/Client/index.d.ts +2 -2
  55. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -12
  56. package/lib/Socket/Client/mobile-socket-client.js +65 -65
  57. package/lib/Socket/Client/types.d.ts +1 -1
  58. package/lib/Socket/Client/websocket.d.ts +1 -1
  59. package/lib/Socket/business.d.ts +6 -6
  60. package/lib/Socket/business.js +152 -5
  61. package/lib/Socket/chats.d.ts +3 -4
  62. package/lib/Socket/chats.js +31 -26
  63. package/lib/Socket/communities.d.ts +223 -223
  64. package/lib/Socket/communities.js +432 -432
  65. package/lib/Socket/groups.d.ts +2 -4
  66. package/lib/Socket/groups.js +22 -14
  67. package/lib/Socket/index.d.ts +69 -69
  68. package/lib/Socket/index.js +3 -2
  69. package/lib/Socket/messages-recv.d.ts +3 -6
  70. package/lib/Socket/messages-recv.js +1449 -1707
  71. package/lib/Socket/messages-send.d.ts +2 -4
  72. package/lib/Socket/messages-send.js +617 -126
  73. package/lib/Socket/mex.d.ts +2 -2
  74. package/lib/Socket/mex.js +46 -46
  75. package/lib/Socket/newsletter.d.ts +2 -4
  76. package/lib/Socket/newsletter.js +294 -285
  77. package/lib/Socket/socket.js +318 -132
  78. package/lib/Socket/usync.js +3 -3
  79. package/lib/Store/index.d.ts +4 -4
  80. package/lib/Store/index.js +23 -23
  81. package/lib/Store/make-cache-manager-store.d.ts +13 -13
  82. package/lib/Store/make-cache-manager-store.js +89 -89
  83. package/lib/Store/make-in-memory-store.d.ts +122 -122
  84. package/lib/Store/make-in-memory-store.js +428 -428
  85. package/lib/Store/make-ordered-dictionary.d.ts +11 -11
  86. package/lib/Store/make-ordered-dictionary.js +85 -85
  87. package/lib/Store/object-repository.d.ts +9 -9
  88. package/lib/Store/object-repository.js +30 -30
  89. package/lib/Types/Auth.d.ts +5 -4
  90. package/lib/Types/Bussines.js +3 -0
  91. package/lib/Types/Bussiness.d.ts +28 -0
  92. package/lib/Types/Chat.d.ts +13 -8
  93. package/lib/Types/Contact.d.ts +4 -1
  94. package/lib/Types/Events.d.ts +13 -16
  95. package/lib/Types/GroupMetadata.d.ts +1 -1
  96. package/lib/Types/Message.d.ts +18 -7
  97. package/lib/Types/Message.js +7 -1
  98. package/lib/Types/MexUpdates.d.ts +8 -8
  99. package/lib/Types/MexUpdates.js +17 -17
  100. package/lib/Types/Newsletter.d.ts +1 -1
  101. package/lib/Types/Product.d.ts +1 -1
  102. package/lib/Types/Signal.d.ts +31 -1
  103. package/lib/Types/Socket.d.ts +34 -13
  104. package/lib/Types/State.d.ts +1 -1
  105. package/lib/Types/USync.d.ts +2 -2
  106. package/lib/Types/index.d.ts +16 -15
  107. package/lib/Types/index.js +4 -2
  108. package/lib/Utils/auth-utils.d.ts +20 -20
  109. package/lib/Utils/auth-utils.js +527 -204
  110. package/lib/Utils/baileys-event-stream.d.ts +17 -17
  111. package/lib/Utils/baileys-event-stream.js +69 -69
  112. package/lib/Utils/business.d.ts +28 -28
  113. package/lib/Utils/business.js +254 -254
  114. package/lib/Utils/chat-utils.d.ts +81 -81
  115. package/lib/Utils/chat-utils.js +808 -780
  116. package/lib/Utils/crypto.d.ts +55 -55
  117. package/lib/Utils/crypto.js +188 -178
  118. package/lib/Utils/decode-wa-message.d.ts +52 -40
  119. package/lib/Utils/decode-wa-message.js +322 -252
  120. package/lib/Utils/event-buffer.d.ts +38 -38
  121. package/lib/Utils/event-buffer.js +594 -564
  122. package/lib/Utils/generics.d.ts +131 -129
  123. package/lib/Utils/generics.js +629 -623
  124. package/lib/Utils/history.d.ts +22 -22
  125. package/lib/Utils/history.js +103 -109
  126. package/lib/Utils/index.d.ts +20 -19
  127. package/lib/Utils/index.js +39 -38
  128. package/lib/Utils/link-preview.d.ts +22 -22
  129. package/lib/Utils/link-preview.js +119 -119
  130. package/lib/Utils/logger.d.ts +13 -13
  131. package/lib/Utils/logger.js +7 -7
  132. package/lib/Utils/lt-hash.d.ts +13 -13
  133. package/lib/Utils/lt-hash.js +57 -57
  134. package/lib/Utils/make-mutex.d.ts +8 -8
  135. package/lib/Utils/make-mutex.js +48 -48
  136. package/lib/Utils/message-retry-manager.d.ts +88 -0
  137. package/lib/Utils/message-retry-manager.js +160 -0
  138. package/lib/Utils/messages-media.d.ts +134 -128
  139. package/lib/Utils/messages-media.js +868 -805
  140. package/lib/Utils/messages.d.ts +104 -102
  141. package/lib/Utils/messages.js +1744 -1578
  142. package/lib/Utils/noise-handler.d.ts +20 -19
  143. package/lib/Utils/noise-handler.js +164 -154
  144. package/lib/Utils/process-message.d.ts +48 -48
  145. package/lib/Utils/process-message.js +427 -428
  146. package/lib/Utils/signal.d.ts +41 -41
  147. package/lib/Utils/signal.js +165 -165
  148. package/lib/Utils/use-mongo-file-auth-state.d.ts +5 -5
  149. package/lib/Utils/use-mongo-file-auth-state.js +83 -83
  150. package/lib/Utils/use-multi-file-auth-state.d.ts +17 -17
  151. package/lib/Utils/use-multi-file-auth-state.js +237 -237
  152. package/lib/Utils/use-single-file-auth-state.d.ts +12 -12
  153. package/lib/Utils/use-single-file-auth-state.js +79 -79
  154. package/lib/Utils/validate-connection.d.ts +12 -12
  155. package/lib/Utils/validate-connection.js +219 -186
  156. package/lib/WABinary/constants.d.ts +29 -29
  157. package/lib/WABinary/constants.js +1315 -1315
  158. package/lib/WABinary/decode.d.ts +8 -8
  159. package/lib/WABinary/decode.js +287 -287
  160. package/lib/WABinary/encode.d.ts +2 -2
  161. package/lib/WABinary/encode.js +264 -264
  162. package/lib/WABinary/generic-utils.d.ts +27 -27
  163. package/lib/WABinary/generic-utils.js +141 -141
  164. package/lib/WABinary/index.d.ts +5 -5
  165. package/lib/WABinary/index.js +24 -24
  166. package/lib/WABinary/jid-utils.d.ts +58 -53
  167. package/lib/WABinary/jid-utils.js +103 -91
  168. package/lib/WABinary/types.d.ts +21 -21
  169. package/lib/WABinary/types.js +2 -2
  170. package/lib/WAM/BinaryInfo.d.ts +15 -15
  171. package/lib/WAM/BinaryInfo.js +16 -16
  172. package/lib/WAM/constants.d.ts +46 -46
  173. package/lib/WAM/constants.js +15370 -15370
  174. package/lib/WAM/encode.d.ts +2 -2
  175. package/lib/WAM/encode.js +163 -164
  176. package/lib/WAM/index.d.ts +3 -3
  177. package/lib/WAM/index.js +22 -22
  178. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +27 -27
  179. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +68 -68
  180. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -3
  181. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -2
  182. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -2
  183. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -8
  184. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +37 -29
  185. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -2
  186. package/lib/WAUSync/Protocols/index.d.ts +6 -6
  187. package/lib/WAUSync/USyncQuery.d.ts +3 -3
  188. package/lib/WAUSync/index.d.ts +3 -3
  189. package/lib/index.d.ts +13 -13
  190. package/lib/index.js +33 -33
  191. package/package.json +96 -94
  192. package/lib/Socket/registration.d.ts +0 -266
  193. package/lib/Socket/registration.js +0 -166
@@ -1,253 +1,323 @@
1
- "use strict"
2
-
3
- Object.defineProperty(exports, "__esModule", { value: true })
4
-
5
- const boom_1 = require("@hapi/boom")
6
- const WAProto_1 = require("../../WAProto")
7
- const WABinary_1 = require("../WABinary")
8
- const generics_1 = require("./generics")
9
- const messages_1 = require("./messages")
10
-
11
- const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node'
12
-
13
- const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled'
14
-
15
- const NACK_REASONS = {
16
- ParsingError: 487,
17
- UnrecognizedStanza: 488,
18
- UnrecognizedStanzaClass: 489,
19
- UnrecognizedStanzaType: 490,
20
- InvalidProtobuf: 491,
21
- InvalidHostedCompanionStanza: 493,
22
- MissingMessageSecret: 495,
23
- SignalErrorOldCounter: 496,
24
- MessageDeletedOnPeer: 499,
25
- UnhandledError: 500,
26
- UnsupportedAdminRevoke: 550,
27
- UnsupportedLIDGroup: 551,
28
- DBOperationFailed: 552
29
- }
30
-
31
- /**
32
- * Decode the received node as a message.
33
- * @note this will only parse the message, not decrypt it
34
- */
35
- function decodeMessageNode(stanza, meId, meLid) {
36
- let msgType
37
- let chatId
38
- let author
39
- const msgId = stanza.attrs.id
40
- const from = stanza.attrs.from
41
- let participant = stanza.attrs.participant
42
- if (participant && participant.endsWith('@lid') && stanza.attrs.participant_pn) {
43
- participant = stanza.attrs.participant_pn;
44
- }
45
- const recipient = stanza.attrs.recipient
46
- const isMe = (jid) => WABinary_1.areJidsSameUser(jid, meId)
47
- const isMeLid = (jid) => WABinary_1.areJidsSameUser(jid, meLid)
48
- if (WABinary_1.isJidUser(from)) {
49
- if (recipient) {
50
- if (!isMe(from)) {
51
- throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza })
52
- }
53
- chatId = recipient
54
- }
55
- else {
56
- chatId = from
57
- }
58
- msgType = 'chat'
59
- author = from
60
- }
61
- else if (WABinary_1.isLidUser(from)) {
62
- if (recipient) {
63
- if (!isMeLid(from)) {
64
- throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza })
65
- }
66
- chatId = recipient
67
- }
68
- else {
69
- chatId = from
70
- }
71
- msgType = 'chat'
72
- author = from
73
- }
74
- else if (WABinary_1.isJidGroup(from)) {
75
- if (!participant) {
76
- throw new boom_1.Boom('No participant in group message')
77
- }
78
- msgType = 'group'
79
- author = participant
80
- chatId = from
81
- }
82
- else if (WABinary_1.isJidBroadcast(from)) {
83
- if (!participant) {
84
- throw new boom_1.Boom('No participant in group message')
85
- }
86
- const isParticipantMe = isMe(participant)
87
- if (WABinary_1.isJidStatusBroadcast(from)) {
88
- msgType = isParticipantMe ? 'direct_peer_status' : 'other_status'
89
- }
90
- else {
91
- msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast'
92
- }
93
- chatId = from
94
- author = participant
95
- }
96
- else if (WABinary_1.isJidNewsletter(from)) {
97
- msgType = 'newsletter'
98
- chatId = from
99
- author = from
100
- }
101
- else {
102
- throw new boom_1.Boom('Unknown message type', { data: stanza })
103
- }
104
- const senderJid = stanza.attrs.participant || stanza.attrs.from;
105
-
106
- const fromMe = WABinary_1.isJidNewsletter(stanza.attrs.from)
107
- ? !!stanza.attrs?.is_sender
108
- : WABinary_1.isLidUser(senderJid)
109
- ? (0, WABinary_1.areJidsSameUser)(senderJid, meLid)
110
- : (0, WABinary_1.areJidsSameUser)(senderJid, meId);
111
-
112
- const pushname = stanza?.attrs?.notify
113
- const key = {
114
- remoteJid: chatId,
115
- fromMe,
116
- id: msgId,
117
- ...(participant !== undefined && { participant: fromMe ? meId : participant }),
118
- ...(stanza.attrs.participant_pn !== undefined && { participant_pn: fromMe ? meId : stanza.attrs.participant_pn }),
119
- ...(stanza.attrs.participant_lid !== undefined && { participant_lid: fromMe ? meLid : stanza.attrs.participant_lid }),
120
- }
121
- const fullMessage = {
122
- key,
123
- messageTimestamp: +stanza.attrs.t,
124
- pushName: pushname,
125
- broadcast: WABinary_1.isJidBroadcast(from),
126
- newsletter: WABinary_1.isJidNewsletter(from),
127
- additionalAttributes: stanza.attrs
128
- }
129
- if (msgType === 'newsletter') {
130
- fullMessage.newsletter_server_id = +stanza.attrs?.server_id
131
- }
132
- if (key.fromMe) {
133
- fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK
134
- }
135
- if (!key.fromMe) {
136
- fullMessage.platform = messages_1.getDevice(key.id)
137
- }
138
- return {
139
- fullMessage,
140
- author,
141
- sender: msgType === 'chat' ? author : chatId
142
- }
143
- }
144
-
145
- const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
146
- const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
147
- return {
148
- fullMessage,
149
- category: stanza.attrs.category,
150
- author,
151
- async decrypt() {
152
- let decryptables = 0
153
- if (Array.isArray(stanza.content)) {
154
- for (const { tag, attrs, content } of stanza.content) {
155
- if (tag === 'verified_name' && content instanceof Uint8Array) {
156
- const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content)
157
- const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details)
158
- fullMessage.verifiedBizName = details.verifiedName
159
- }
160
- if (tag === 'multicast' && content instanceof Uint8Array) {
161
- fullMessage.multicast = true
162
- }
163
- if (tag === 'meta' && content instanceof Uint8Array) {
164
- fullMessage.metaInfo = {
165
- targetID: attrs.target_id
166
- }
167
- if (attrs.target_sender_jid) {
168
- fullMessage.metaInfo.targetSender = WABinary_1.jidNormalizedUser(attrs.target_sender_jid)
169
- }
170
- }
171
- if (tag === 'bot' && content instanceof Uint8Array) {
172
- if (attrs.edit) {
173
- fullMessage.botInfo = {
174
- editType: attrs.edit,
175
- editTargetID: attrs.edit_target_id,
176
- editSenderTimestampMS: attrs.sender_timestamp_ms
177
- }
178
- }
179
- }
180
- if (tag !== 'enc' && tag !== 'plaintext') {
181
- continue
182
- }
183
- if (!(content instanceof Uint8Array)) {
184
- continue
185
- }
186
- decryptables += 1
187
- let msgBuffer
188
- try {
189
- const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type
190
- switch (e2eType) {
191
- case 'skmsg':
192
- msgBuffer = await repository.decryptGroupMessage({
193
- group: sender,
194
- authorJid: author,
195
- msg: content
196
- })
197
- break
198
- case 'pkmsg':
199
- case 'msg':
200
- const user = WABinary_1.isJidUser(sender) ? sender : author
201
- msgBuffer = await repository.decryptMessage({
202
- jid: user,
203
- type: e2eType,
204
- ciphertext: content
205
- })
206
- break
207
- case 'plaintext':
208
- msgBuffer = content
209
- break
210
- default:
211
- throw new Error(`Unknown e2e type: ${e2eType}`)
212
- }
213
- let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? generics_1.unpadRandomMax16(msgBuffer) : msgBuffer)
214
- msg = msg.deviceSentMessage?.message || msg
215
- if (msg.senderKeyDistributionMessage) {
216
- //eslint-disable-next-line max-depth
217
- try {
218
- await repository.processSenderKeyDistributionMessage({
219
- authorJid: author,
220
- item: msg.senderKeyDistributionMessage
221
- })
222
- }
223
- catch (err) {
224
- logger.error({ key: fullMessage.key, err }, 'failed to decrypt message')
225
- }
226
- }
227
- if (fullMessage.message) {
228
- Object.assign(fullMessage.message, msg)
229
- }
230
- else {
231
- fullMessage.message = msg
232
- }
233
- }
234
- catch (err) {
235
- logger.error({ key: fullMessage.key, err }, 'failed to decrypt message')
236
- fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT
237
- fullMessage.messageStubParameters = [err.message]
238
- }
239
- }
240
- }
241
- // if nothing was found to decrypt
242
- if (!decryptables) {
243
- fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT
244
- fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT]
245
- }
246
- }
247
- }
248
- }
249
-
250
- module.exports = {
251
- decodeMessageNode,
252
- decryptMessageNode
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const boom_1 = require("@hapi/boom")
6
+ const WAProto_1 = require("../../WAProto")
7
+ const WABinary_1 = require("../WABinary")
8
+ const generics_1 = require("./generics")
9
+ const messages_1 = require("./messages")
10
+
11
+ const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node'
12
+
13
+ const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled'
14
+
15
+ // Retry configuration for failed decryption
16
+ const DECRYPTION_RETRY_CONFIG = {
17
+ maxRetries: 3,
18
+ baseDelayMs: 100,
19
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
20
+ }
21
+
22
+ const NACK_REASONS = {
23
+ ParsingError: 487,
24
+ UnrecognizedStanza: 488,
25
+ UnrecognizedStanzaClass: 489,
26
+ UnrecognizedStanzaType: 490,
27
+ InvalidProtobuf: 491,
28
+ InvalidHostedCompanionStanza: 493,
29
+ MissingMessageSecret: 495,
30
+ SignalErrorOldCounter: 496,
31
+ MessageDeletedOnPeer: 499,
32
+ UnhandledError: 500,
33
+ UnsupportedAdminRevoke: 550,
34
+ UnsupportedLIDGroup: 551,
35
+ DBOperationFailed: 552
36
+ }
37
+
38
+ const extractAddressingContext = (stanza) => {
39
+ let senderAlt
40
+ let recipientAlt
41
+
42
+ const sender = stanza.attrs.participant || stanza.attrs.from
43
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn')
44
+
45
+ if (WABinary_1.isLidUser(sender)) {
46
+ // Message is LID-addressed: sender is LID, extract corresponding PN
47
+ // without device data
48
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn
49
+ recipientAlt = stanza.attrs.recipient_pn
50
+ // with device data
51
+ if (sender && senderAlt)
52
+ senderAlt = WABinary_1.transferDevice(sender, senderAlt)
53
+ }
54
+
55
+ else if (WABinary_1.isJidUser(sender)) {
56
+ // Message is PN-addressed: sender is PN, extract corresponding LID
57
+ // without device data
58
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid
59
+ recipientAlt = stanza.attrs.recipient_lid
60
+ //with device data
61
+ if (sender && senderAlt)
62
+ senderAlt = WABinary_1.transferDevice(sender, senderAlt)
63
+ }
64
+ return {
65
+ addressingMode,
66
+ senderAlt,
67
+ recipientAlt
68
+ }
69
+ }
70
+
71
+ const getDecryptionJid = async (sender, repository) => {
72
+ if (!sender.includes('@s.whatsapp.net')) {
73
+ return sender
74
+ }
75
+ return (await repository.lidMapping.getLIDForPN(sender))
76
+ }
77
+
78
+ const storeMappingFromEnvelope = async (stanza, sender, decryptionJid, repository, logger) => {
79
+ const { senderAlt } = extractAddressingContext(stanza)
80
+
81
+ if (senderAlt && WABinary_1.isLidUser(senderAlt) && WABinary_1.isJidUser(sender) && decryptionJid === sender) {
82
+ try {
83
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }])
84
+ logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope')
85
+ }
86
+ catch (error) {
87
+ logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping')
88
+ }
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Decode the received node as a message.
94
+ * @note this will only parse the message, not decrypt it
95
+ */
96
+ function decodeMessageNode(stanza, meId, meLid) {
97
+ let msgType
98
+ let chatId
99
+ let author
100
+ const msgId = stanza.attrs.id
101
+ const from = stanza.attrs.from
102
+ const participant = stanza.attrs.participant
103
+ const recipient = stanza.attrs.recipient
104
+ const addressingContext = extractAddressingContext(stanza)
105
+ const isMe = (jid) => WABinary_1.areJidsSameUser(jid, meId)
106
+ const isMeLid = (jid) => WABinary_1.areJidsSameUser(jid, meLid)
107
+ if (WABinary_1.isJidUser(from)) {
108
+ if (recipient) {
109
+ if (!isMe(from)) {
110
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza })
111
+ }
112
+ chatId = recipient
113
+ }
114
+ else {
115
+ chatId = from
116
+ }
117
+ msgType = 'chat'
118
+ author = from
119
+ }
120
+ else if (WABinary_1.isLidUser(from)) {
121
+ if (recipient) {
122
+ if (!isMeLid(from)) {
123
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza })
124
+ }
125
+ chatId = recipient
126
+ }
127
+ else {
128
+ chatId = from
129
+ }
130
+ msgType = 'chat'
131
+ author = from
132
+ }
133
+ else if (WABinary_1.isJidGroup(from)) {
134
+ if (!participant) {
135
+ throw new boom_1.Boom('No participant in group message')
136
+ }
137
+ msgType = 'group'
138
+ author = participant
139
+ chatId = from
140
+ }
141
+ else if (WABinary_1.isJidBroadcast(from)) {
142
+ if (!participant) {
143
+ throw new boom_1.Boom('No participant in group message')
144
+ }
145
+ const isParticipantMe = isMe(participant)
146
+ if (WABinary_1.isJidStatusBroadcast(from)) {
147
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status'
148
+ }
149
+ else {
150
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast'
151
+ }
152
+ chatId = from
153
+ author = participant
154
+ }
155
+ else if (WABinary_1.isJidNewsletter(from)) {
156
+ msgType = 'newsletter'
157
+ chatId = from
158
+ author = from
159
+ }
160
+ else {
161
+ throw new boom_1.Boom('Unknown message type', { data: stanza })
162
+ }
163
+ // const fromMe = WABinary_1.isJidNewsletter(from) ? !!stanza.attrs?.is_sender : WABinary_1.isLidUser(from) ? isMeLid(stanza.attrs.participant || stanza.attrs.from) : isMe(stanza.attrs.participant || stanza.attrs.from)
164
+ const senderJid = stanza.attrs.participant || stanza.attrs.from;
165
+
166
+ const fromMe = WABinary_1.isJidNewsletter(stanza.attrs.from)
167
+ ? !!stanza.attrs?.is_sender
168
+ : WABinary_1.isLidUser(senderJid)
169
+ ? (0, WABinary_1.areJidsSameUser)(senderJid, meLid)
170
+ : (0, WABinary_1.areJidsSameUser)(senderJid, meId);
171
+ const pushname = stanza?.attrs?.notify
172
+ const key = {
173
+ remoteJid: chatId,
174
+ remoteJidAlt: !WABinary_1.isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
175
+ fromMe,
176
+ id: msgId,
177
+ participant,
178
+ participantAlt: WABinary_1.isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
179
+ }
180
+ const fullMessage = {
181
+ key,
182
+ messageTimestamp: +stanza.attrs.t,
183
+ pushName: pushname,
184
+ broadcast: WABinary_1.isJidBroadcast(from),
185
+ newsletter: WABinary_1.isJidNewsletter(from),
186
+ additionalAttributes: stanza.attrs,
187
+ Owner: "Baron" // Non-WhatsApp attribute
188
+ }
189
+ if (msgType === 'newsletter') {
190
+ fullMessage.newsletter_server_id = +stanza.attrs?.server_id
191
+ }
192
+ if (key.fromMe) {
193
+ fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK
194
+ }
195
+ if (!key.fromMe) {
196
+ fullMessage.platform = messages_1.getDevice(key.id)
197
+ }
198
+ return {
199
+ fullMessage,
200
+ author,
201
+ sender: msgType === 'chat' ? author : chatId
202
+ }
203
+ }
204
+
205
+ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
206
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
207
+ return {
208
+ fullMessage,
209
+ category: stanza.attrs.category,
210
+ author,
211
+ async decrypt() {
212
+ let decryptables = 0
213
+ if (Array.isArray(stanza.content)) {
214
+ for (const { tag, attrs, content } of stanza.content) {
215
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
216
+ const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content)
217
+ const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details)
218
+ fullMessage.verifiedBizName = details.verifiedName
219
+ }
220
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
221
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
222
+ }
223
+ if (tag !== 'enc' && tag !== 'plaintext') {
224
+ continue
225
+ }
226
+ if (!(content instanceof Uint8Array)) {
227
+ continue
228
+ }
229
+ decryptables += 1
230
+ let msgBuffer
231
+ const user = WABinary_1.isJidUser(sender) ? sender : author // TODO: flaky logic
232
+ const decryptionJid = await getDecryptionJid(user, repository)
233
+
234
+ if (tag !== 'plaintext') {
235
+ await storeMappingFromEnvelope(stanza, user, decryptionJid, repository, logger)
236
+ }
237
+ try {
238
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type
239
+ switch (e2eType) {
240
+ case 'skmsg':
241
+ msgBuffer = await repository.decryptGroupMessage({
242
+ group: sender,
243
+ authorJid: author,
244
+ msg: content
245
+ })
246
+ break
247
+ case 'pkmsg':
248
+ case 'msg':
249
+ msgBuffer = await repository.decryptMessage({
250
+ jid: decryptionJid,
251
+ type: e2eType,
252
+ ciphertext: content
253
+ })
254
+ break
255
+ case 'plaintext':
256
+ msgBuffer = content
257
+ break
258
+ default:
259
+ throw new Error(`Unknown e2e type: ${e2eType}`)
260
+ }
261
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? generics_1.unpadRandomMax16(msgBuffer) : msgBuffer)
262
+ msg = msg.deviceSentMessage?.message || msg
263
+ if (msg.senderKeyDistributionMessage) {
264
+ //eslint-disable-next-line max-depth
265
+ try {
266
+ await repository.processSenderKeyDistributionMessage({
267
+ authorJid: author,
268
+ item: msg.senderKeyDistributionMessage
269
+ })
270
+ }
271
+ catch (err) {
272
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message')
273
+ }
274
+ }
275
+ if (fullMessage.message) {
276
+ Object.assign(fullMessage.message, msg)
277
+ }
278
+ else {
279
+ fullMessage.message = msg
280
+ }
281
+ }
282
+ catch (err) {
283
+ const errorContext = {
284
+ key: fullMessage.key,
285
+ err,
286
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
287
+ sender,
288
+ author,
289
+ isSessionRecordError: isSessionRecordError(err)
290
+ }
291
+ logger.error(errorContext, 'failed to process sender key distribution message')
292
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT
293
+ fullMessage.messageStubParameters = [err.message.toString()]
294
+ }
295
+ }
296
+ }
297
+
298
+ // if nothing was found to decrypt
299
+ if (!decryptables) {
300
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT
301
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT]
302
+ }
303
+ }
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Utility function to check if an error is related to missing session record
309
+ */
310
+ function isSessionRecordError(error) {
311
+ const errorMessage = error?.message || error?.toString() || ''
312
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern))
313
+ }
314
+
315
+ module.exports = {
316
+ NACK_REASONS,
317
+ decodeMessageNode,
318
+ decryptMessageNode,
319
+ extractAddressingContext,
320
+ MISSING_KEYS_ERROR_TEXT,
321
+ DECRYPTION_RETRY_CONFIG,
322
+ NO_MESSAGE_FOUND_ERROR_TEXT
253
323
  }