@alannxd/baileys 6.0.6 → 6.0.9

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 (220) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +341 -286
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +6902 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +79257 -0
  7. package/WAProto/index.js +205861 -60565
  8. package/engine-requirements.js +1 -1
  9. package/lib/Defaults/index.js +119 -136
  10. package/lib/Signal/Group/ciphertext-message.js +2 -5
  11. package/lib/Signal/Group/group-session-builder.js +7 -41
  12. package/lib/Signal/Group/group_cipher.js +37 -51
  13. package/lib/Signal/Group/index.js +12 -57
  14. package/lib/Signal/Group/keyhelper.js +7 -44
  15. package/lib/Signal/Group/sender-chain-key.js +7 -15
  16. package/lib/Signal/Group/sender-key-distribution-message.js +8 -11
  17. package/lib/Signal/Group/sender-key-message.js +9 -12
  18. package/lib/Signal/Group/sender-key-name.js +2 -5
  19. package/lib/Signal/Group/sender-key-record.js +9 -21
  20. package/lib/Signal/Group/sender-key-state.js +27 -42
  21. package/lib/Signal/Group/sender-message-key.js +4 -7
  22. package/lib/Signal/libsignal.js +347 -90
  23. package/lib/Signal/lid-mapping.js +277 -0
  24. package/lib/Socket/Client/index.js +3 -19
  25. package/lib/Socket/Client/types.js +11 -0
  26. package/lib/Socket/Client/websocket.js +54 -0
  27. package/lib/Socket/business.js +162 -43
  28. package/lib/Socket/chats.js +627 -427
  29. package/lib/Socket/communities.js +90 -80
  30. package/lib/Socket/groups.js +154 -161
  31. package/lib/Socket/index.js +11 -10
  32. package/lib/Socket/luxu.js +315 -469
  33. package/lib/Socket/messages-recv.js +1421 -615
  34. package/lib/Socket/messages-send.js +1150 -799
  35. package/lib/Socket/mex.js +42 -0
  36. package/lib/Socket/newsletter.js +152 -204
  37. package/lib/Socket/socket.js +544 -313
  38. package/lib/Store/index.js +10 -10
  39. package/lib/Store/keyed-db.js +108 -0
  40. package/lib/Store/make-cache-manager-store.js +43 -41
  41. package/lib/Store/make-in-memory-store.js +112 -341
  42. package/lib/Store/make-ordered-dictionary.js +14 -20
  43. package/lib/Store/object-repository.js +11 -6
  44. package/lib/Types/Auth.js +2 -2
  45. package/lib/Types/Bussines.js +2 -0
  46. package/lib/Types/Call.js +2 -2
  47. package/lib/Types/Chat.js +8 -4
  48. package/lib/Types/Contact.js +2 -2
  49. package/lib/Types/Events.js +2 -2
  50. package/lib/Types/GroupMetadata.js +2 -2
  51. package/lib/Types/Label.js +3 -5
  52. package/lib/Types/LabelAssociation.js +3 -5
  53. package/lib/Types/Message.js +11 -9
  54. package/lib/Types/Mex.js +37 -0
  55. package/lib/Types/Product.js +2 -2
  56. package/lib/Types/Signal.js +2 -2
  57. package/lib/Types/Socket.js +3 -2
  58. package/lib/Types/State.js +56 -2
  59. package/lib/Types/USync.js +2 -2
  60. package/lib/Types/index.js +15 -31
  61. package/lib/Utils/auth-utils.js +239 -143
  62. package/lib/Utils/browser-utils.js +48 -0
  63. package/lib/Utils/business.js +66 -69
  64. package/lib/Utils/chat-utils.js +396 -253
  65. package/lib/Utils/companion-reg-client-utils.js +35 -0
  66. package/lib/Utils/crypto.js +57 -90
  67. package/lib/Utils/decode-wa-message.js +236 -84
  68. package/lib/Utils/event-buffer.js +185 -77
  69. package/lib/Utils/generics.js +189 -209
  70. package/lib/Utils/history.js +93 -55
  71. package/lib/Utils/identity-change-handler.js +50 -0
  72. package/lib/Utils/index.js +23 -33
  73. package/lib/Utils/link-preview.js +16 -24
  74. package/lib/Utils/logger.js +3 -7
  75. package/lib/Utils/lt-hash.js +3 -46
  76. package/lib/Utils/make-mutex.js +24 -34
  77. package/lib/Utils/message-composer.js +273 -0
  78. package/lib/Utils/message-retry-manager.js +265 -0
  79. package/lib/Utils/messages-media.js +451 -482
  80. package/lib/Utils/messages.js +795 -369
  81. package/lib/Utils/noise-handler.js +145 -99
  82. package/lib/Utils/offline-node-processor.js +40 -0
  83. package/lib/Utils/pre-key-manager.js +106 -0
  84. package/lib/Utils/process-message.js +459 -150
  85. package/lib/Utils/reporting-utils.js +258 -0
  86. package/lib/Utils/signal.js +120 -72
  87. package/lib/Utils/stanza-ack.js +38 -0
  88. package/lib/Utils/sync-action-utils.js +49 -0
  89. package/lib/Utils/tc-token-utils.js +163 -0
  90. package/lib/Utils/use-multi-file-auth-state.js +29 -27
  91. package/lib/Utils/validate-connection.js +73 -99
  92. package/lib/WABinary/constants.js +1281 -20
  93. package/lib/WABinary/decode.js +52 -42
  94. package/lib/WABinary/encode.js +110 -155
  95. package/lib/WABinary/generic-utils.js +55 -49
  96. package/lib/WABinary/index.js +6 -21
  97. package/lib/WABinary/jid-utils.js +76 -40
  98. package/lib/WABinary/types.js +2 -2
  99. package/lib/WAM/BinaryInfo.js +2 -5
  100. package/lib/WAM/constants.js +19071 -11568
  101. package/lib/WAM/encode.js +17 -22
  102. package/lib/WAM/index.js +4 -19
  103. package/lib/WAUSync/Protocols/USyncContactProtocol.js +33 -13
  104. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  105. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -12
  106. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  107. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  108. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  109. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -8
  110. package/lib/WAUSync/Protocols/index.js +6 -20
  111. package/lib/WAUSync/USyncQuery.js +44 -35
  112. package/lib/WAUSync/USyncUser.js +10 -5
  113. package/lib/WAUSync/index.js +4 -19
  114. package/lib/index.js +13 -36
  115. package/package.json +85 -51
  116. package/WAProto/fix-import.js +0 -29
  117. package/lib/Defaults/baileys-version.json +0 -3
  118. package/lib/Defaults/index.d.ts +0 -53
  119. package/lib/Defaults/phonenumber-mcc.json +0 -223
  120. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  121. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  122. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  123. package/lib/Signal/Group/index.d.ts +0 -11
  124. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  125. package/lib/Signal/Group/queue-job.d.ts +0 -1
  126. package/lib/Signal/Group/queue-job.js +0 -57
  127. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  128. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  129. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  130. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  131. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  132. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  133. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  134. package/lib/Signal/libsignal.d.ts +0 -3
  135. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  136. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  137. package/lib/Socket/Client/index.d.ts +0 -3
  138. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  139. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  140. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  141. package/lib/Socket/Client/web-socket-client.js +0 -62
  142. package/lib/Socket/business.d.ts +0 -171
  143. package/lib/Socket/chats.d.ts +0 -267
  144. package/lib/Socket/communities.d.ts +0 -180
  145. package/lib/Socket/groups.d.ts +0 -115
  146. package/lib/Socket/index.d.ts +0 -173
  147. package/lib/Socket/luxu.d.ts +0 -266
  148. package/lib/Socket/messages-recv.d.ts +0 -161
  149. package/lib/Socket/messages-send.d.ts +0 -183
  150. package/lib/Socket/newsletter.d.ts +0 -134
  151. package/lib/Socket/registration.d.ts +0 -267
  152. package/lib/Socket/registration.js +0 -166
  153. package/lib/Socket/socket.d.ts +0 -44
  154. package/lib/Socket/usync.d.ts +0 -36
  155. package/lib/Socket/usync.js +0 -70
  156. package/lib/Store/index.d.ts +0 -3
  157. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  158. package/lib/Store/make-in-memory-store.d.ts +0 -118
  159. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  160. package/lib/Store/object-repository.d.ts +0 -10
  161. package/lib/Types/Auth.d.ts +0 -110
  162. package/lib/Types/Call.d.ts +0 -13
  163. package/lib/Types/Chat.d.ts +0 -102
  164. package/lib/Types/Contact.d.ts +0 -19
  165. package/lib/Types/Events.d.ts +0 -157
  166. package/lib/Types/GroupMetadata.d.ts +0 -55
  167. package/lib/Types/Label.d.ts +0 -35
  168. package/lib/Types/LabelAssociation.d.ts +0 -29
  169. package/lib/Types/Message.d.ts +0 -273
  170. package/lib/Types/Newsletter.d.ts +0 -103
  171. package/lib/Types/Newsletter.js +0 -38
  172. package/lib/Types/Product.d.ts +0 -78
  173. package/lib/Types/Signal.d.ts +0 -57
  174. package/lib/Types/Socket.d.ts +0 -111
  175. package/lib/Types/State.d.ts +0 -27
  176. package/lib/Types/USync.d.ts +0 -25
  177. package/lib/Types/index.d.ts +0 -57
  178. package/lib/Utils/auth-utils.d.ts +0 -18
  179. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  180. package/lib/Utils/baileys-event-stream.js +0 -63
  181. package/lib/Utils/business.d.ts +0 -22
  182. package/lib/Utils/chat-utils.d.ts +0 -71
  183. package/lib/Utils/crypto.d.ts +0 -41
  184. package/lib/Utils/decode-wa-message.d.ts +0 -19
  185. package/lib/Utils/event-buffer.d.ts +0 -35
  186. package/lib/Utils/generics.d.ts +0 -92
  187. package/lib/Utils/history.d.ts +0 -15
  188. package/lib/Utils/index.d.ts +0 -17
  189. package/lib/Utils/link-preview.d.ts +0 -21
  190. package/lib/Utils/logger.d.ts +0 -4
  191. package/lib/Utils/lt-hash.d.ts +0 -12
  192. package/lib/Utils/make-mutex.d.ts +0 -7
  193. package/lib/Utils/messages-media.d.ts +0 -116
  194. package/lib/Utils/messages.d.ts +0 -77
  195. package/lib/Utils/noise-handler.d.ts +0 -21
  196. package/lib/Utils/process-message.d.ts +0 -41
  197. package/lib/Utils/signal.d.ts +0 -32
  198. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  199. package/lib/Utils/validate-connection.d.ts +0 -11
  200. package/lib/WABinary/constants.d.ts +0 -30
  201. package/lib/WABinary/decode.d.ts +0 -7
  202. package/lib/WABinary/encode.d.ts +0 -3
  203. package/lib/WABinary/generic-utils.d.ts +0 -17
  204. package/lib/WABinary/index.d.ts +0 -5
  205. package/lib/WABinary/jid-utils.d.ts +0 -31
  206. package/lib/WABinary/types.d.ts +0 -18
  207. package/lib/WAM/BinaryInfo.d.ts +0 -17
  208. package/lib/WAM/constants.d.ts +0 -38
  209. package/lib/WAM/encode.d.ts +0 -3
  210. package/lib/WAM/index.d.ts +0 -3
  211. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  212. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  213. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  214. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  215. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  216. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  217. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  218. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  219. package/lib/WAUSync/USyncUser.d.ts +0 -12
  220. package/lib/index.d.ts +0 -12
@@ -1,101 +1,236 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decryptMessageNode = exports.decodeMessageNode = void 0;
4
- const boom_1 = require("@hapi/boom");
5
- const WAProto_1 = require("../../WAProto");
6
- const WABinary_1 = require("../WABinary");
7
- const generics_1 = require("./generics");
8
- const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
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
+ export const getDecryptionJid = async (sender, repository) => {
8
+ if (isLidUser(sender) || isHostedLidUser(sender)) {
9
+ return sender;
10
+ }
11
+ const mapped = await repository.lidMapping.getLIDForPN(sender);
12
+ return mapped || sender;
13
+ };
14
+ const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger) => {
15
+ // TODO: Handle hosted IDs
16
+ const { senderAlt } = extractAddressingContext(stanza);
17
+ if (senderAlt && isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
18
+ try {
19
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }]);
20
+ await repository.migrateSession(sender, senderAlt);
21
+ logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope');
22
+ }
23
+ catch (error) {
24
+ logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping');
25
+ }
26
+ }
27
+ };
28
+ export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
29
+ export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
30
+ export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted';
31
+ // Retry configuration for failed decryption
32
+ export const DECRYPTION_RETRY_CONFIG = {
33
+ maxRetries: 3,
34
+ baseDelayMs: 100,
35
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
36
+ };
37
+ /** NACK reason codes we send to the server (client → server) */
38
+ export const NACK_REASONS = {
39
+ SenderReachoutTimelocked: 463,
40
+ ParsingError: 487,
41
+ UnrecognizedStanza: 488,
42
+ UnrecognizedStanzaClass: 489,
43
+ UnrecognizedStanzaType: 490,
44
+ InvalidProtobuf: 491,
45
+ InvalidHostedCompanionStanza: 493,
46
+ MissingMessageSecret: 495,
47
+ SignalErrorOldCounter: 496,
48
+ MessageDeletedOnPeer: 499,
49
+ UnhandledError: 500,
50
+ UnsupportedAdminRevoke: 550,
51
+ UnsupportedLIDGroup: 551,
52
+ DBOperationFailed: 552
53
+ };
54
+ /**
55
+ * Server-side error codes returned in ack stanzas (server → client) that we
56
+ * currently have dedicated handlers for. Extend as more handlers are added.
57
+ * Distinct from the client-side NackReason enum (WAWebCreateNackFromStanza).
58
+ */
59
+ export const SERVER_ERROR_CODES = {
60
+ /**
61
+ * 1:1 message missing privacy token (tctoken). Usually means the account is
62
+ * restricted: WhatsApp blocks starting new chats but preserves existing ones,
63
+ * since established chats already carry a tctoken.
64
+ */
65
+ MessageAccountRestriction: '463',
66
+ /** Stanza validation failure (SMAX_INVALID) — likely stale device session */
67
+ SmaxInvalid: '479'
68
+ };
69
+ export const extractAddressingContext = (stanza) => {
70
+ let senderAlt;
71
+ let recipientAlt;
72
+ const sender = stanza.attrs.participant || stanza.attrs.from;
73
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn');
74
+ if (addressingMode === 'lid') {
75
+ // Message is LID-addressed: sender is LID, extract corresponding PN
76
+ // without device data
77
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
78
+ recipientAlt = stanza.attrs.recipient_pn;
79
+ // with device data
80
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
81
+ }
82
+ else {
83
+ // Message is PN-addressed: sender is PN, extract corresponding LID
84
+ // without device data
85
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
86
+ recipientAlt = stanza.attrs.recipient_lid;
87
+ //with device data
88
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
89
+ }
90
+ return {
91
+ addressingMode,
92
+ senderAlt,
93
+ recipientAlt
94
+ };
95
+ };
96
+ const MAX_SECRETS_PER_CHAT = 20
97
+ // Module-level map: outgoing @bot message ID → messageSecret
98
+ // Populated when we receive the outgoing pkmsg/msg to @bot (which contains messageContextInfo.messageSecret)
99
+ // Consumed when the msmsg response from @bot arrives and needs decryption
100
+ const botMessageSecrets = new Map()
101
+ const botRecentSecretsByChat = new Map()
102
+ const pushRecentChatSecret = (chatJid, id, secretBuf) => {
103
+ if (!chatJid || !secretBuf) return
104
+ const existing = botRecentSecretsByChat.get(chatJid) || []
105
+ const filtered = existing.filter(item => item.id !== id && !item.secret.equals(secretBuf))
106
+ filtered.unshift({ id, secret: secretBuf })
107
+ if (filtered.length > MAX_SECRETS_PER_CHAT) {
108
+ filtered.length = MAX_SECRETS_PER_CHAT
109
+ }
110
+ botRecentSecretsByChat.set(chatJid, filtered)
111
+ }
112
+ export const setBotMessageSecret = (id, secret, chatJid) => {
113
+ if (!id || !secret) return
114
+ let buf
115
+ if (Buffer.isBuffer(secret)) {
116
+ buf = secret
117
+ } else if (secret instanceof Uint8Array) {
118
+ buf = Buffer.from(secret.buffer, secret.byteOffset, secret.byteLength)
119
+ } else if (typeof secret === 'string') {
120
+ buf = Buffer.from(secret, 'base64')
121
+ } else {
122
+ return
123
+ }
124
+ botMessageSecrets.set(id, buf)
125
+ if (chatJid) {
126
+ pushRecentChatSecret(chatJid, id, buf)
127
+ }
128
+ }
9
129
  /**
10
130
  * Decode the received node as a message.
11
131
  * @note this will only parse the message, not decrypt it
12
132
  */
13
- function decodeMessageNode(stanza, meId, meLid) {
14
- var _a, _b;
133
+ export function decodeMessageNode(stanza, meId, meLid) {
15
134
  let msgType;
16
135
  let chatId;
17
136
  let author;
137
+ let fromMe = false;
18
138
  const msgId = stanza.attrs.id;
19
139
  const from = stanza.attrs.from;
20
140
  const participant = stanza.attrs.participant;
21
141
  const recipient = stanza.attrs.recipient;
22
- const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
23
- const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
24
- if ((0, WABinary_1.isJidUser)(from)) {
25
- if (recipient) {
26
- if (!isMe(from)) {
27
- throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
28
- }
29
- chatId = recipient;
30
- }
31
- else {
32
- chatId = from;
33
- }
34
- msgType = 'chat';
35
- author = from;
142
+ if (!msgId) {
143
+ throw new Boom('Invalid message stanza: missing id attribute', { data: stanza });
36
144
  }
37
- else if ((0, WABinary_1.isLidUser)(from)) {
38
- if (recipient) {
39
- if (!isMeLid(from)) {
40
- throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
145
+ if (!from) {
146
+ throw new Boom('Invalid message stanza: missing from attribute', { data: stanza });
147
+ }
148
+ const addressingContext = extractAddressingContext(stanza);
149
+ const isMe = (jid) => areJidsSameUser(jid, meId);
150
+ const isMeLid = (jid) => areJidsSameUser(jid, meLid);
151
+ if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
152
+ if (recipient && !isJidMetaAI(recipient)) {
153
+ if (!isMe(from) && !isMeLid(from)) {
154
+ throw new Boom('receipient present, but msg not from me', { data: stanza });
155
+ }
156
+ if (isMe(from) || isMeLid(from)) {
157
+ fromMe = true;
41
158
  }
42
159
  chatId = recipient;
43
160
  }
44
161
  else {
162
+ // Peer-routed self stanzas (history sync, app-state sync, etc.) arrive
163
+ // with `from` set to our own device but no `recipient` attribute —
164
+ // still mark as fromMe so self-only protocolMessage handlers run.
165
+ if (isMe(from) || isMeLid(from)) {
166
+ fromMe = true;
167
+ }
45
168
  chatId = from;
46
169
  }
47
170
  msgType = 'chat';
48
171
  author = from;
49
172
  }
50
- else if ((0, WABinary_1.isJidGroup)(from)) {
173
+ else if (isJidGroup(from)) {
51
174
  if (!participant) {
52
- throw new boom_1.Boom('No participant in group message');
175
+ throw new Boom('No participant in group message');
176
+ }
177
+ if (isMe(participant) || isMeLid(participant)) {
178
+ fromMe = true;
53
179
  }
54
180
  msgType = 'group';
55
181
  author = participant;
56
182
  chatId = from;
57
183
  }
58
- else if ((0, WABinary_1.isJidBroadcast)(from)) {
184
+ else if (isJidBroadcast(from)) {
59
185
  if (!participant) {
60
- throw new boom_1.Boom('No participant in group message');
186
+ throw new Boom('No participant in group message');
61
187
  }
62
188
  const isParticipantMe = isMe(participant);
63
- if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
189
+ if (isJidStatusBroadcast(from)) {
64
190
  msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
65
191
  }
66
192
  else {
67
193
  msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
68
194
  }
195
+ fromMe = isParticipantMe;
69
196
  chatId = from;
70
197
  author = participant;
71
198
  }
72
- else if ((0, WABinary_1.isJidNewsLetter)(from)) {
199
+ else if (isJidNewsletter(from)) {
73
200
  msgType = 'newsletter';
74
- author = from;
75
201
  chatId = from;
202
+ author = from;
203
+ if (isMe(from) || isMeLid(from)) {
204
+ fromMe = true;
205
+ }
76
206
  }
77
207
  else {
78
- throw new boom_1.Boom('Unknown message type', { data: stanza });
208
+ throw new Boom('Unknown message type', { data: stanza });
79
209
  }
80
- const fromMe = (0, WABinary_1.isJidNewsLetter)(from) ? !!((_a = stanza.attrs) === null || _a === void 0 ? void 0 : _a.is_sender) : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
81
- const pushname = stanza.attrs.notify;
210
+ const pushname = stanza?.attrs?.notify;
82
211
  const key = {
83
212
  remoteJid: chatId,
213
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
214
+ remoteJidUsername: !isJidGroup(chatId)
215
+ ? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username
216
+ : undefined,
84
217
  fromMe,
85
218
  id: msgId,
86
- participant
219
+ participant,
220
+ participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
221
+ participantUsername: stanza.attrs.participant ? stanza.attrs.participant_username : undefined,
222
+ addressingMode: addressingContext.addressingMode,
223
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
87
224
  };
88
225
  const fullMessage = {
89
226
  key,
227
+ category: stanza.attrs.category,
90
228
  messageTimestamp: +stanza.attrs.t,
91
229
  pushName: pushname,
92
- broadcast: (0, WABinary_1.isJidBroadcast)(from)
230
+ broadcast: isJidBroadcast(from)
93
231
  };
94
- if (msgType === 'newsletter') {
95
- fullMessage.newsletterServerId = +((_b = stanza.attrs) === null || _b === void 0 ? void 0 : _b.server_id);
96
- }
97
232
  if (key.fromMe) {
98
- fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
233
+ fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
99
234
  }
100
235
  return {
101
236
  fullMessage,
@@ -103,44 +238,28 @@ function decodeMessageNode(stanza, meId, meLid) {
103
238
  sender: msgType === 'chat' ? author : chatId
104
239
  };
105
240
  }
106
- exports.decodeMessageNode = decodeMessageNode;
107
- const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
241
+ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
108
242
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
109
243
  return {
110
244
  fullMessage,
111
245
  category: stanza.attrs.category,
112
246
  author,
113
247
  async decrypt() {
114
- var _a;
115
248
  let decryptables = 0;
116
- async function processSenderKeyDistribution(msg) {
117
- if (msg.senderKeyDistributionMessage) {
118
- try {
119
- await repository.processSenderKeyDistributionMessage({
120
- authorJid: author,
121
- item: msg.senderKeyDistributionMessage
122
- });
123
- }
124
- catch (err) {
125
- logger.error({ key: fullMessage.key, err }, 'failed to process senderKeyDistribution');
126
- }
127
- }
128
- }
129
- if ((0, WABinary_1.isJidNewsLetter)(fullMessage.key.remoteJid)) {
130
- const node = (0, WABinary_1.getBinaryNodeChild)(stanza, 'plaintext');
131
- const msg = WAProto_1.proto.Message.decode(node === null || node === void 0 ? void 0 : node.content);
132
- await processSenderKeyDistribution(msg);
133
- fullMessage.message = msg;
134
- decryptables += 1;
135
- }
136
- else if (Array.isArray(stanza.content)) {
249
+ if (Array.isArray(stanza.content)) {
137
250
  for (const { tag, attrs, content } of stanza.content) {
138
251
  if (tag === 'verified_name' && content instanceof Uint8Array) {
139
- const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
140
- const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
252
+ const cert = proto.VerifiedNameCertificate.decode(content);
253
+ const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
141
254
  fullMessage.verifiedBizName = details.verifiedName;
142
255
  }
143
- if (tag !== 'enc') {
256
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
257
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
258
+ }
259
+ if (attrs.count && tag === 'enc') {
260
+ fullMessage.retryCount = Number(attrs.count);
261
+ }
262
+ if (tag !== 'enc' && tag !== 'plaintext') {
144
263
  continue;
145
264
  }
146
265
  if (!(content instanceof Uint8Array)) {
@@ -148,8 +267,13 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
148
267
  }
149
268
  decryptables += 1;
150
269
  let msgBuffer;
270
+ const decryptionJid = await getDecryptionJid(author, repository);
271
+ if (tag !== 'plaintext') {
272
+ // TODO: Handle hosted devices
273
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
274
+ }
151
275
  try {
152
- const e2eType = attrs.type;
276
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
153
277
  switch (e2eType) {
154
278
  case 'skmsg':
155
279
  msgBuffer = await repository.decryptGroupMessage({
@@ -160,19 +284,32 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
160
284
  break;
161
285
  case 'pkmsg':
162
286
  case 'msg':
163
- const user = (0, WABinary_1.isJidUser)(sender) ? sender : author;
164
287
  msgBuffer = await repository.decryptMessage({
165
- jid: user,
288
+ jid: decryptionJid,
166
289
  type: e2eType,
167
290
  ciphertext: content
168
291
  });
169
292
  break;
293
+ case 'plaintext':
294
+ msgBuffer = content;
295
+ break;
170
296
  default:
171
297
  throw new Error(`Unknown e2e type: ${e2eType}`);
172
298
  }
173
- let msg = WAProto_1.proto.Message.decode((0, generics_1.unpadRandomMax16)(msgBuffer));
174
- msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
175
- await processSenderKeyDistribution(msg);
299
+ let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer);
300
+ msg = msg.deviceSentMessage?.message || msg;
301
+ if (msg.senderKeyDistributionMessage) {
302
+ //eslint-disable-next-line max-depth
303
+ try {
304
+ await repository.processSenderKeyDistributionMessage({
305
+ authorJid: author,
306
+ item: msg.senderKeyDistributionMessage
307
+ });
308
+ }
309
+ catch (err) {
310
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
311
+ }
312
+ }
176
313
  if (fullMessage.message) {
177
314
  Object.assign(fullMessage.message, msg);
178
315
  }
@@ -181,18 +318,33 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
181
318
  }
182
319
  }
183
320
  catch (err) {
184
- logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
185
- fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
186
- fullMessage.messageStubParameters = [err.message];
321
+ const errorContext = {
322
+ key: fullMessage.key,
323
+ err,
324
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
325
+ sender,
326
+ author,
327
+ isSessionRecordError: isSessionRecordError(err)
328
+ };
329
+ logger.error(errorContext, 'failed to decrypt message');
330
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
331
+ fullMessage.messageStubParameters = [err.message.toString()];
187
332
  }
188
333
  }
189
334
  }
190
335
  // if nothing was found to decrypt
191
- if (!decryptables) {
192
- fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
193
- fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT, JSON.stringify(stanza, generics_1.BufferJSON.replacer)];
336
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
337
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
338
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
194
339
  }
195
340
  }
196
341
  };
197
342
  };
198
- exports.decryptMessageNode = decryptMessageNode;
343
+ /**
344
+ * Utility function to check if an error is related to missing session record
345
+ */
346
+ function isSessionRecordError(error) {
347
+ const errorMessage = error?.message || error?.toString() || '';
348
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
349
+ }
350
+ //# sourceMappingURL=decode-wa-message.js.map