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