@x4r1s3/baileys 0.0.0-stage → 1.0.0

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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1262 -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/audio-feeder.mjs +179 -0
  18. package/lib/Call/audio-recorder.mjs +250 -0
  19. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  20. package/lib/Call/index.mjs +680 -0
  21. package/lib/Call/relay-transport.mjs +563 -0
  22. package/lib/Call/signaling.mjs +641 -0
  23. package/lib/Call/types.mjs +17 -0
  24. package/lib/Call/video-feeder.mjs +94 -0
  25. package/lib/Call/wasm-engine.mjs +1372 -0
  26. package/lib/Call/worker-bootstrap.mjs +1042 -0
  27. package/lib/Defaults/ban-checker.js +56 -0
  28. package/lib/Defaults/index.js +170 -0
  29. package/lib/Signal/Group/ciphertext-message.js +23 -0
  30. package/lib/Signal/Group/group-session-builder.js +41 -0
  31. package/lib/Signal/Group/group_cipher.js +93 -0
  32. package/lib/Signal/Group/index.js +23 -0
  33. package/lib/Signal/Group/keyhelper.js +29 -0
  34. package/lib/Signal/Group/sender-chain-key.js +37 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  36. package/lib/Signal/Group/sender-key-message.js +77 -0
  37. package/lib/Signal/Group/sender-key-name.js +59 -0
  38. package/lib/Signal/Group/sender-key-record.js +52 -0
  39. package/lib/Signal/Group/sender-key-state.js +95 -0
  40. package/lib/Signal/Group/sender-message-key.js +37 -0
  41. package/lib/Signal/libsignal.js +440 -0
  42. package/lib/Signal/lid-mapping.js +292 -0
  43. package/lib/Socket/Client/index.js +14 -0
  44. package/lib/Socket/Client/types.js +22 -0
  45. package/lib/Socket/Client/websocket.js +65 -0
  46. package/lib/Socket/aigroups.js +327 -0
  47. package/lib/Socket/ban-checker.js +165 -0
  48. package/lib/Socket/business.js +419 -0
  49. package/lib/Socket/chats.js +1921 -0
  50. package/lib/Socket/communities.js +443 -0
  51. package/lib/Socket/graphql.js +911 -0
  52. package/lib/Socket/groups.js +561 -0
  53. package/lib/Socket/index.js +49 -0
  54. package/lib/Socket/interactive-handler.js +612 -0
  55. package/lib/Socket/interop.js +575 -0
  56. package/lib/Socket/managed-account.js +220 -0
  57. package/lib/Socket/messages-recv.js +2191 -0
  58. package/lib/Socket/messages-send.js +4104 -0
  59. package/lib/Socket/mex.js +53 -0
  60. package/lib/Socket/newsletter.js +291 -0
  61. package/lib/Socket/privacy.js +458 -0
  62. package/lib/Socket/registration.js +440 -0
  63. package/lib/Socket/socket.js +1029 -0
  64. package/lib/Socket/status-actions.js +287 -0
  65. package/lib/Socket/username.js +241 -0
  66. package/lib/Store/index.js +16 -0
  67. package/lib/Store/make-cache-manager-store.js +101 -0
  68. package/lib/Store/make-in-memory-store.js +432 -0
  69. package/lib/Store/make-ordered-dictionary.js +90 -0
  70. package/lib/Store/object-repository.js +35 -0
  71. package/lib/Types/Auth.js +13 -0
  72. package/lib/Types/Bussines.js +13 -0
  73. package/lib/Types/Call.js +13 -0
  74. package/lib/Types/Chat.js +19 -0
  75. package/lib/Types/Contact.js +13 -0
  76. package/lib/Types/Events.js +13 -0
  77. package/lib/Types/GroupMetadata.js +13 -0
  78. package/lib/Types/Label.js +36 -0
  79. package/lib/Types/LabelAssociation.js +18 -0
  80. package/lib/Types/Message.js +30 -0
  81. package/lib/Types/Mex.js +53 -0
  82. package/lib/Types/Product.js +13 -0
  83. package/lib/Types/RichType.js +34 -0
  84. package/lib/Types/Signal.js +13 -0
  85. package/lib/Types/Socket.js +14 -0
  86. package/lib/Types/State.js +60 -0
  87. package/lib/Types/USync.js +13 -0
  88. package/lib/Types/index.js +37 -0
  89. package/lib/Utils/auth-utils.js +313 -0
  90. package/lib/Utils/ban-checker.js +48 -0
  91. package/lib/Utils/bot-capabilities.js +96 -0
  92. package/lib/Utils/bot-planning-replay.js +177 -0
  93. package/lib/Utils/browser-utils.js +40 -0
  94. package/lib/Utils/business.js +242 -0
  95. package/lib/Utils/c2582.js +147 -0
  96. package/lib/Utils/chat-utils.js +905 -0
  97. package/lib/Utils/companion-reg-client-utils.js +44 -0
  98. package/lib/Utils/consumer-application.js +114 -0
  99. package/lib/Utils/crypto.js +129 -0
  100. package/lib/Utils/decode-wa-message.js +496 -0
  101. package/lib/Utils/direct-chat-theme.js +164 -0
  102. package/lib/Utils/event-buffer.js +601 -0
  103. package/lib/Utils/experimental-proto.js +206 -0
  104. package/lib/Utils/games/miniapp.js +17 -0
  105. package/lib/Utils/games/slot-machine.js +270 -0
  106. package/lib/Utils/games/website-preview.js +306 -0
  107. package/lib/Utils/generics.js +402 -0
  108. package/lib/Utils/group-history.js +68 -0
  109. package/lib/Utils/group-wallpaper.js +168 -0
  110. package/lib/Utils/history.js +162 -0
  111. package/lib/Utils/identity-change-handler.js +60 -0
  112. package/lib/Utils/index.js +61 -0
  113. package/lib/Utils/jid-display-normalization.js +221 -0
  114. package/lib/Utils/link-preview.js +96 -0
  115. package/lib/Utils/logger.js +14 -0
  116. package/lib/Utils/lt-hash.js +19 -0
  117. package/lib/Utils/make-mutex.js +44 -0
  118. package/lib/Utils/message-composer.js +709 -0
  119. package/lib/Utils/message-inspect.js +79 -0
  120. package/lib/Utils/message-retry-manager.js +253 -0
  121. package/lib/Utils/message-security.js +167 -0
  122. package/lib/Utils/messages-media.js +1027 -0
  123. package/lib/Utils/messages.js +2467 -0
  124. package/lib/Utils/meta-ai-msmsg.js +215 -0
  125. package/lib/Utils/meta-compositing.js +239 -0
  126. package/lib/Utils/native-flow.js +158 -0
  127. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  128. package/lib/Utils/newsletter-status-utils.js +152 -0
  129. package/lib/Utils/noise-handler.js +212 -0
  130. package/lib/Utils/offline-node-processor.js +51 -0
  131. package/lib/Utils/poll-manager.js +206 -0
  132. package/lib/Utils/portable-compat.js +12 -0
  133. package/lib/Utils/pre-key-manager.js +117 -0
  134. package/lib/Utils/process-message.js +610 -0
  135. package/lib/Utils/reporting-utils.js +269 -0
  136. package/lib/Utils/rich-message-utils.js +2841 -0
  137. package/lib/Utils/scheduled-message.js +107 -0
  138. package/lib/Utils/signal.js +212 -0
  139. package/lib/Utils/source-grep.js +57 -0
  140. package/lib/Utils/stanza-ack.js +49 -0
  141. package/lib/Utils/sticker-annotation.js +87 -0
  142. package/lib/Utils/sync-action-utils.js +59 -0
  143. package/lib/Utils/tc-token-utils.js +174 -0
  144. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  145. package/lib/Utils/use-single-file-auth-state.js +108 -0
  146. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  147. package/lib/Utils/validate-connection.js +220 -0
  148. package/lib/Utils/view-once-utils.js +218 -0
  149. package/lib/Utils/voip-rekey.js +32 -0
  150. package/lib/Utils/website-preview.js +27 -0
  151. package/lib/Utils/welcome-flow.js +228 -0
  152. package/lib/Utils/x4r1s3.js +144 -0
  153. package/lib/WABinary/constants.js +1475 -0
  154. package/lib/WABinary/decode.js +273 -0
  155. package/lib/WABinary/encode.js +231 -0
  156. package/lib/WABinary/generic-utils.js +242 -0
  157. package/lib/WABinary/index.js +17 -0
  158. package/lib/WABinary/jid-utils.js +107 -0
  159. package/lib/WABinary/types.js +13 -0
  160. package/lib/WAM/BinaryInfo.js +21 -0
  161. package/lib/WAM/constants.js +22864 -0
  162. package/lib/WAM/encode.js +161 -0
  163. package/lib/WAM/index.js +15 -0
  164. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  167. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  168. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  169. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  170. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  172. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  173. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  174. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  176. package/lib/WAUSync/Protocols/index.js +24 -0
  177. package/lib/WAUSync/USyncQuery.js +213 -0
  178. package/lib/WAUSync/USyncUser.js +66 -0
  179. package/lib/WAUSync/index.js +15 -0
  180. package/lib/antiban.cjs +4726 -0
  181. package/lib/index.d.ts +1285 -0
  182. package/lib/index.js +30 -0
  183. package/package.json +125 -4
@@ -0,0 +1,1921 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Socket/chats.js
5
+ * About: Chats module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: makeChatsSocket
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 NodeCache from '@cacheable/node-cache';
14
+ import { Boom } from '@hapi/boom';
15
+ import { proto } from '../../WAProto/index.js';
16
+ import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES, WA_ADV_HOSTED_KEY_INDEX_LIST_SIG_PREFIX, WA_ADV_KEY_INDEX_LIST_SIG_PREFIX } from '../Defaults/index.js';
17
+ import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
18
+ import { SyncState } from '../Types/State.js';
19
+ import { chatModificationToAppPatch, Curve, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
20
+ import { generateProfilePictureHD } from '../Utils/messages-media.js';
21
+ import { makeMutex } from '../Utils/make-mutex.js';
22
+ import processMessage from '../Utils/process-message.js';
23
+ import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
24
+ import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
25
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
26
+ import { makeSocket } from './socket.js';
27
+ export const makeChatsSocket = (config) => {
28
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
29
+ const sock = makeSocket(config);
30
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
31
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
32
+ // Cache newsletter messageId → server_id so quoted posts can be enriched later
33
+ const _nlServerIdCache = new Map();
34
+ let privacySettings;
35
+ /** Server-assigned AB props for protocol behavior. */
36
+ const serverProps = {
37
+ /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
38
+ privacyTokenOn1to1: true,
39
+ /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
40
+ profilePicPrivacyToken: true,
41
+ /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
42
+ lidTrustedTokenIssueToLid: false
43
+ };
44
+ let syncState = SyncState.Connecting;
45
+ /** this mutex ensures that messages are processed in order */
46
+ const messageMutex = makeMutex();
47
+ /** this mutex ensures that receipts are processed in order */
48
+ const receiptMutex = makeMutex();
49
+ /** this mutex ensures that app state patches are processed in order */
50
+ const appStatePatchMutex = makeMutex();
51
+ /** this mutex ensures that notifications are processed in order */
52
+ const notificationMutex = makeMutex();
53
+ // Timeout for AwaitingInitialSync state
54
+ let awaitingSyncTimeout;
55
+ // In-memory history sync completion tracking (resets on reconnection)
56
+ const historySyncStatus = {
57
+ initialBootstrapComplete: false,
58
+ recentSyncComplete: false
59
+ };
60
+ let historySyncPausedTimeout;
61
+ // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
62
+ // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
63
+ const blockedCollections = new Set();
64
+ const placeholderResendCache = config.placeholderResendCache ||
65
+ new NodeCache({
66
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
67
+ useClones: false
68
+ });
69
+ /** helper function to fetch the given app state sync key */
70
+ const getAppStateSyncKey = async (keyId) => {
71
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
72
+ return key;
73
+ };
74
+ const fetchPrivacySettings = async (force = false) => {
75
+ if (!privacySettings || force) {
76
+ const { content } = await query({
77
+ tag: 'iq',
78
+ attrs: {
79
+ xmlns: 'privacy',
80
+ to: S_WHATSAPP_NET,
81
+ type: 'get'
82
+ },
83
+ content: [{ tag: 'privacy', attrs: {} }]
84
+ });
85
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
86
+ }
87
+ return privacySettings;
88
+ };
89
+ /** helper function to run a privacy IQ query */
90
+ const privacyQuery = async (name, value) => {
91
+ await query({
92
+ tag: 'iq',
93
+ attrs: {
94
+ xmlns: 'privacy',
95
+ to: S_WHATSAPP_NET,
96
+ type: 'set'
97
+ },
98
+ content: [
99
+ {
100
+ tag: 'privacy',
101
+ attrs: {},
102
+ content: [
103
+ {
104
+ tag: 'category',
105
+ attrs: { name, value }
106
+ }
107
+ ]
108
+ }
109
+ ]
110
+ });
111
+ };
112
+ const updateMessagesPrivacy = async (value) => {
113
+ await privacyQuery('messages', value);
114
+ };
115
+ const updateCallPrivacy = async (value) => {
116
+ await privacyQuery('calladd', value);
117
+ };
118
+ const updateLastSeenPrivacy = async (value) => {
119
+ await privacyQuery('last', value);
120
+ };
121
+ const updateOnlinePrivacy = async (value) => {
122
+ await privacyQuery('online', value);
123
+ };
124
+ const updateProfilePicturePrivacy = async (value) => {
125
+ await privacyQuery('profile', value);
126
+ };
127
+ const updateStatusPrivacy = async (value) => {
128
+ await privacyQuery('status', value);
129
+ };
130
+ const updateReadReceiptsPrivacy = async (value) => {
131
+ await privacyQuery('readreceipts', value);
132
+ };
133
+ const updateGroupsAddPrivacy = async (value) => {
134
+ await privacyQuery('groupadd', value);
135
+ };
136
+ const updateDefaultDisappearingMode = async (duration) => {
137
+ await query({
138
+ tag: 'iq',
139
+ attrs: {
140
+ xmlns: 'disappearing_mode',
141
+ to: S_WHATSAPP_NET,
142
+ type: 'set'
143
+ },
144
+ content: [
145
+ {
146
+ tag: 'disappearing_mode',
147
+ attrs: {
148
+ duration: duration.toString()
149
+ }
150
+ }
151
+ ]
152
+ });
153
+ };
154
+ const getStatusPrivacy = async () => {
155
+ const result = await query({
156
+ tag: 'iq',
157
+ attrs: {
158
+ xmlns: 'status',
159
+ to: S_WHATSAPP_NET,
160
+ type: 'get'
161
+ },
162
+ content: [{ tag: 'privacy', attrs: {} }]
163
+ });
164
+ const privacyNode = result?.content?.[0];
165
+ if (!privacyNode)
166
+ return null;
167
+ const lists = [];
168
+ for (const listNode of privacyNode.content || []) {
169
+ const { type, id, listname, emoji, selected, deleted } = listNode.attrs || {};
170
+ const members = (listNode.content || []).map(u => u.attrs?.jid).filter(Boolean);
171
+ lists.push({ type, id, listname, emoji, selected: selected === 'true', deleted: deleted === 'true', members });
172
+ }
173
+ return lists;
174
+ };
175
+ /**
176
+ * Set status privacy via `xmlns="status"` IQ SET.
177
+ * Supports simple distribution types and contact-level whitelist/blacklist/customlist.
178
+ *
179
+ * @param {'contacts'|'whitelist'|'blacklist'|'null'} type - Distribution type
180
+ * @param {string[]} [jids] - JIDs for the list (whitelist/blacklist)
181
+ * @param {Array<{id: string, listname: string, emoji?: string, selected?: boolean, deleted?: boolean, members?: string[]}>} [customLists]
182
+ */
183
+ const setStatusPrivacy = async (type, jids = [], customLists = []) => {
184
+ const content = [];
185
+ // main distribution list
186
+ const mainList = {
187
+ tag: 'list',
188
+ attrs: { type },
189
+ content: jids.map(jid => ({ tag: 'user', attrs: { jid }, content: [] }))
190
+ };
191
+ content.push(mainList);
192
+ // custom named lists
193
+ for (const cl of customLists) {
194
+ const attrs = { type: 'customlist', id: cl.id, listname: cl.listname };
195
+ if (cl.emoji)
196
+ attrs.emoji = cl.emoji;
197
+ if (cl.selected)
198
+ attrs.selected = 'true';
199
+ if (cl.deleted)
200
+ attrs.deleted = 'true';
201
+ content.push({
202
+ tag: 'list',
203
+ attrs,
204
+ content: (cl.members || []).map(jid => ({ tag: 'user', attrs: { jid }, content: [] }))
205
+ });
206
+ }
207
+ await query({
208
+ tag: 'iq',
209
+ attrs: {
210
+ xmlns: 'status',
211
+ to: S_WHATSAPP_NET,
212
+ type: 'set'
213
+ },
214
+ content: [{ tag: 'privacy', attrs: {}, content }]
215
+ });
216
+ };
217
+ /**
218
+ * Fetch broadcast list quota from the server (xmlns="w:biz").
219
+ *
220
+ * Returns: { messagesLeft, totalLimit, isHeavySender, startTs, endTs, resetTs }
221
+ */
222
+ const fetchBroadcastListQuota = async () => {
223
+ const result = await query({
224
+ tag: 'iq',
225
+ attrs: {
226
+ xmlns: 'w:biz',
227
+ to: S_WHATSAPP_NET,
228
+ type: 'get'
229
+ },
230
+ content: [{ tag: 'broadcast_list_quota', attrs: {}, content: [] }]
231
+ }, 32000);
232
+ const limitsNode = getBinaryNodeChild(result, 'limits');
233
+ const timeframeNode = getBinaryNodeChild(result, 'timeframe');
234
+ if (!limitsNode)
235
+ return null;
236
+ return {
237
+ messagesLeft: parseInt(limitsNode.attrs?.messages_left ?? getBinaryNodeChild(limitsNode, 'messages_left')?.content ?? '0', 10),
238
+ totalLimit: parseInt(limitsNode.attrs?.total_limit ?? getBinaryNodeChild(limitsNode, 'total_limit')?.content ?? '0', 10),
239
+ isHeavySender: (limitsNode.attrs?.is_heavy_sender ?? getBinaryNodeChild(limitsNode, 'is_heavy_sender')?.content) === 'true',
240
+ startTs: parseInt(timeframeNode?.attrs?.start_ts_s ?? getBinaryNodeChild(timeframeNode, 'start_ts_s')?.content ?? '0', 10),
241
+ endTs: parseInt(timeframeNode?.attrs?.end_ts_s ?? getBinaryNodeChild(timeframeNode, 'end_ts_s')?.content ?? '0', 10),
242
+ resetTs: parseInt(timeframeNode?.attrs?.reset_ts_s ?? getBinaryNodeChild(timeframeNode, 'reset_ts_s')?.content ?? '0', 10)
243
+ };
244
+ };
245
+ /**
246
+ * Get the global chat-blocking status (block messages from unknown accounts).
247
+ * Ported from WhatsApp Web's WASmaxPsaChatBlockGetRPC (xmlns `w:comms:chat`).
248
+ * @returns {Promise<'blocked' | 'unblocked' | undefined>}
249
+ */
250
+ const getChatBlockingStatus = async () => {
251
+ const result = await query({
252
+ tag: 'iq',
253
+ attrs: {
254
+ to: S_WHATSAPP_NET,
255
+ xmlns: 'w:comms:chat',
256
+ type: 'get'
257
+ },
258
+ content: [{ tag: 'query', attrs: {}, content: [{ tag: 'blocking_status', attrs: {} }] }]
259
+ });
260
+ const blocking = getBinaryNodeChild(result, 'blocking') ||
261
+ getBinaryNodeChild(getBinaryNodeChild(result, 'query'), 'blocking');
262
+ return blocking?.attrs?.status;
263
+ };
264
+ /**
265
+ * Set the global chat-blocking status (block messages from unknown accounts).
266
+ * Ported from WhatsApp Web's WASmaxPsaChatBlockSetRPC (xmlns `w:comms:chat`).
267
+ * @param {'block' | 'unblock'} action
268
+ * @returns {Promise<'blocked' | 'unblocked' | undefined>} the resulting status
269
+ */
270
+ const updateChatBlockingStatus = async (action) => {
271
+ const result = await query({
272
+ tag: 'iq',
273
+ attrs: {
274
+ to: S_WHATSAPP_NET,
275
+ xmlns: 'w:comms:chat',
276
+ type: 'set'
277
+ },
278
+ content: [{ tag: 'blocking', attrs: { action } }]
279
+ });
280
+ const blocking = getBinaryNodeChild(result, 'blocking');
281
+ return blocking?.attrs?.status;
282
+ };
283
+ /**
284
+ * Get the user's pending TOS disclosures / notices (xmlns="tos").
285
+ * @param {number} [t] last-seen disclosure timestamp
286
+ * @returns {Promise<Array<Record<string, string>>>} the `<notice>` attributes
287
+ */
288
+ const getUserDisclosures = async (t = 0) => {
289
+ const result = await query({
290
+ tag: 'iq',
291
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'tos', type: 'get' },
292
+ content: [{ tag: 'get_user_disclosures', attrs: { t: String(t) } }]
293
+ });
294
+ return getBinaryNodeChildren(result, 'notice').map(n => ({ ...n.attrs }));
295
+ };
296
+ /**
297
+ * Accept a TOS/disclosure notice (`xmlns="tos"` set with `<trackable>`).
298
+ * @param {string} noticeId the notice id (e.g. "20250211")
299
+ * @param {string|number} result the result code (e.g. "105")
300
+ */
301
+ const acceptTosNotice = async (noticeId, result = '105') => {
302
+ await query({
303
+ tag: 'iq',
304
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'tos', type: 'set' },
305
+ content: [{ tag: 'trackable', attrs: { id: String(noticeId), result: String(result) } }]
306
+ });
307
+ };
308
+ /**
309
+ * Report spam for a chat/group with sample messages (xmlns="spam").
310
+ * @param {string} jid the JID of the chat or group being reported
311
+ * @param {Array<{id:string, from:string, t:number}>} messages up to ~5 recent messages as evidence
312
+ * @param {string} [spamFlow] e.g. "group_info_report" or "contact_info_report"
313
+ * @param {string} [subject] human-readable subject string (group name or contact name)
314
+ */
315
+ const reportSpam = async (jid, messages, spamFlow = 'contact_info_report', subject) => {
316
+ const msgNodes = (messages || []).map(m => ({
317
+ tag: 'message',
318
+ attrs: {
319
+ from: String(jid),
320
+ t: String(m.t),
321
+ id: String(m.id)
322
+ }
323
+ }));
324
+ await query({
325
+ tag: 'iq',
326
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'spam', type: 'set' },
327
+ content: [
328
+ {
329
+ tag: 'spam_list',
330
+ attrs: {
331
+ jid: String(jid),
332
+ spam_flow: String(spamFlow),
333
+ ...(subject ? { subject: String(subject) } : {})
334
+ },
335
+ content: msgNodes
336
+ }
337
+ ]
338
+ });
339
+ };
340
+ /** Report a user through WhatsApp's w:report IQ endpoint. */
341
+ const reportUser = async (jid, reason = 'spam', waitForAckMs = 5000) => {
342
+ const resolvedJid = jidNormalizedUser(jid);
343
+ const reasonCodes = { spam: 1, harassment: 2, impersonation: 3, scam: 4, other: 5 };
344
+ const node = {
345
+ tag: 'iq',
346
+ attrs: { id: generateMessageTag(), xmlns: 'w:report', to: S_WHATSAPP_NET.replace(/^@/, ''), type: 'set' },
347
+ content: [{ tag: 'user', attrs: { jid: resolvedJid, reason: String(reasonCodes[reason] || 1) } }]
348
+ };
349
+ try {
350
+ await query(node, waitForAckMs);
351
+ logger.info({ jid: resolvedJid, reason }, 'reported user (ack received)');
352
+ return true;
353
+ }
354
+ catch (error) {
355
+ const statusCode = error?.output?.statusCode || error?.statusCode;
356
+ if (statusCode === 408 || error?.message?.toLowerCase?.().includes('timed out')) {
357
+ logger.warn({ jid: resolvedJid, reason }, 'reported user (no ack; request likely sent)');
358
+ return false;
359
+ }
360
+ throw error;
361
+ }
362
+ };
363
+ /** Report one message through WhatsApp's w:report IQ endpoint. */
364
+ const reportMessage = async (jid, messageId, reason = 'spam', participantJid, waitForAckMs = 5000) => {
365
+ const resolvedJid = jidNormalizedUser(jid);
366
+ const participant = participantJid ? jidNormalizedUser(participantJid) : undefined;
367
+ const reasonCodes = { spam: 1, harassment: 2, impersonation: 3, scam: 4, other: 5 };
368
+ const attrs = { id: String(messageId), reason: String(reasonCodes[reason] || 1) };
369
+ if (participant) attrs.participant = participant;
370
+ const node = {
371
+ tag: 'iq',
372
+ attrs: { id: generateMessageTag(), xmlns: 'w:report', to: S_WHATSAPP_NET.replace(/^@/, ''), type: 'set' },
373
+ content: [{ tag: 'message', attrs }]
374
+ };
375
+ try {
376
+ await query(node, waitForAckMs);
377
+ logger.info({ jid: resolvedJid, messageId, reason, participant }, 'reported message (ack received)');
378
+ return true;
379
+ }
380
+ catch (error) {
381
+ const statusCode = error?.output?.statusCode || error?.statusCode;
382
+ if (statusCode === 408 || error?.message?.toLowerCase?.().includes('timed out')) {
383
+ logger.warn({ jid: resolvedJid, messageId, reason, participant }, 'reported message (no ack; request likely sent)');
384
+ return false;
385
+ }
386
+ throw error;
387
+ }
388
+ };
389
+ const reportAndBlockUser = async (jid, reason = 'spam', waitForAckMs = 5000) => {
390
+ const resolvedJid = jidNormalizedUser(jid);
391
+ const acknowledged = await reportUser(resolvedJid, reason, waitForAckMs);
392
+ await updateBlockStatus(resolvedJid, 'block');
393
+ return acknowledged;
394
+ };
395
+ /** Toggle group member-share-history mode through the MEX endpoint. */
396
+ const toggleGroupHistory = async (jid, enable = true) => {
397
+ if (!jid) throw new Boom('toggleGroupHistory requires a group JID', { statusCode: 400 });
398
+ return query({
399
+ tag: 'iq',
400
+ attrs: { type: 'get', to: S_WHATSAPP_NET, xmlns: 'w:mex' },
401
+ content: [{
402
+ tag: 'query',
403
+ attrs: { query_id: '24688994337458819' },
404
+ content: Buffer.from(JSON.stringify({
405
+ variables: {
406
+ group_id: jid,
407
+ input: { member_share_group_history_mode: enable ? 'ALL_MEMBER_SHARE' : 'ADMIN_SHARE' }
408
+ }
409
+ }), 'utf-8')
410
+ }]
411
+ });
412
+ };
413
+ /**
414
+ * Get the account opt-out list (`optoutlist` IQ). Returns the raw result node.
415
+ */
416
+ const getOptOutList = async () => {
417
+ return query({
418
+ tag: 'iq',
419
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'optoutlist', type: 'get' }
420
+ });
421
+ };
422
+ /**
423
+ * Sign a blinded credential for privacy-preserving anonymous stats (xmlns `privatestats`).
424
+ * @param {Buffer} blindedCredential 32-byte blinded credential
425
+ * @returns {Promise<Buffer|undefined>} signed credential bytes from server
426
+ */
427
+ const signPrivateCredential = async (blindedCredential) => {
428
+ const result = await query({
429
+ tag: 'iq',
430
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'privatestats', type: 'get' },
431
+ content: [
432
+ {
433
+ tag: 'sign_credential',
434
+ attrs: { version: '1' },
435
+ content: [{ tag: 'blinded_credential', attrs: {}, content: blindedCredential }]
436
+ }
437
+ ]
438
+ });
439
+ const signedNode = getBinaryNodeChild(result, 'sign_credential');
440
+ const signedBytes = getBinaryNodeChild(signedNode, 'signed_credential');
441
+ return signedBytes?.content instanceof Uint8Array ? Buffer.from(signedBytes.content) : undefined;
442
+ };
443
+ /**
444
+ * Get push-notification settings (`urn:xmpp:whatsapp:push`).
445
+ */
446
+ const getPushConfig = async () => {
447
+ const result = await query({
448
+ tag: 'iq',
449
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'urn:xmpp:whatsapp:push', type: 'get' },
450
+ content: [{ tag: 'settings', attrs: {} }]
451
+ });
452
+ return getBinaryNodeChild(result, 'settings');
453
+ };
454
+ /**
455
+ * Set push-notification config (`urn:xmpp:whatsapp:push`). Mainly web push —
456
+ * pass the FCM-style config (platform / endpoint / auth / p256dh).
457
+ * @param {Record<string, string>} config
458
+ */
459
+ const setPushConfig = async (config) => {
460
+ await query({
461
+ tag: 'iq',
462
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'urn:xmpp:whatsapp:push', type: 'set' },
463
+ content: [{ tag: 'config', attrs: config }]
464
+ });
465
+ };
466
+ /**
467
+ * Toggle the waiting room for a call link.
468
+ * @param {string} linkToken call-link token
469
+ * @param {boolean} enabled whether the waiting room is on
470
+ * @param {string} [media] "audio" | "video"
471
+ */
472
+ const toggleCallLinkWaitingRoom = async (linkToken, enabled, media = 'audio') => {
473
+ const result = await query({
474
+ tag: 'call',
475
+ attrs: { id: generateMessageTag(), to: '@call' },
476
+ content: [
477
+ {
478
+ tag: 'waiting_room_toggle',
479
+ attrs: { enabled: enabled ? '1' : '0', 'link-token': linkToken, media }
480
+ }
481
+ ]
482
+ });
483
+ const child = getBinaryNodeChild(result, 'waiting_room_toggle');
484
+ return child?.attrs;
485
+ };
486
+ /**
487
+ * Store privacy tokens received from a usync response per-contact.
488
+ * @param {Array<{jid: string, privacyToken: Buffer, privacyModeTs: number|string}>} entries
489
+ */
490
+ const storePrivacyTokens = async (entries) => {
491
+ if (!entries?.length)
492
+ return;
493
+ const write = {};
494
+ for (const { jid, privacyToken, privacyModeTs } of entries) {
495
+ if (!jid || !privacyToken?.length)
496
+ continue;
497
+ write[jid] = {
498
+ token: Buffer.isBuffer(privacyToken) ? privacyToken : Buffer.from(privacyToken),
499
+ ts: String(privacyModeTs || '')
500
+ };
501
+ }
502
+ if (Object.keys(write).length) {
503
+ await authState.keys.set({ 'privacy-token': write });
504
+ }
505
+ };
506
+ /**
507
+ * Wrapper around sock.executeUSyncQuery that automatically persists any per-contact
508
+ * privacy tokens (privacy_mode_ts + privacy_token) present in the usync result list,
509
+ * and emits contacts.update for any entries flagged isBlockedByContact.
510
+ * @param {import('../WAUSync/USyncQuery.js').USyncQuery} usyncQuery
511
+ */
512
+ const executeUSyncQuery = async (usyncQuery) => {
513
+ const result = await sock.executeUSyncQuery(usyncQuery);
514
+ if (!result)
515
+ return result;
516
+ // auto-persist privacy tokens found in any usync response
517
+ const privacyEntries = [];
518
+ const blockedContacts = [];
519
+ for (const entry of [...(result.list || []), ...(result.sideList || [])]) {
520
+ if (entry.privacy?.token) {
521
+ privacyEntries.push({
522
+ jid: entry.id,
523
+ privacyToken: entry.privacy.token,
524
+ privacyModeTs: entry.privacy.modeTs
525
+ });
526
+ }
527
+ // emit contacts.update for contacts that blocked us
528
+ if (entry.isBlockedByContact) {
529
+ blockedContacts.push({ id: entry.id, isBlockedByContact: true });
530
+ }
531
+ }
532
+ if (privacyEntries.length) {
533
+ storePrivacyTokens(privacyEntries).catch(err => logger.warn({ err }, 'failed to store privacy tokens from usync'));
534
+ }
535
+ if (blockedContacts.length) {
536
+ ev.emit('contacts.update', blockedContacts);
537
+ }
538
+ return result;
539
+ };
540
+ const updateBioPrivacy = async (value) => {
541
+ await privacyQuery('about', value);
542
+ };
543
+ /**
544
+ * Block a bot JID
545
+ */
546
+ const blockBot = async (botJid) => {
547
+ await query({
548
+ tag: 'iq',
549
+ attrs: {
550
+ xmlns: 'disappearing_mode',
551
+ to: S_WHATSAPP_NET,
552
+ type: 'set'
553
+ },
554
+ content: [
555
+ {
556
+ tag: 'block',
557
+ attrs: { jid: botJid }
558
+ }
559
+ ]
560
+ });
561
+ };
562
+ /**
563
+ * Unblock a bot JID
564
+ */
565
+ const unblockBot = async (botJid) => {
566
+ await updateBlockStatus(botJid, 'unblock');
567
+ };
568
+ const getBotProfile = async (botJid) => {
569
+ const resp = await query({
570
+ tag: 'iq',
571
+ attrs: {
572
+ xmlns: 'bot',
573
+ to: S_WHATSAPP_NET,
574
+ type: 'get'
575
+ },
576
+ content: [
577
+ {
578
+ tag: 'bot',
579
+ attrs: { v: '2', jid: botJid }
580
+ }
581
+ ]
582
+ });
583
+ const botNode = getBinaryNodeChild(resp, 'bot');
584
+ if (!botNode)
585
+ return null;
586
+ return {
587
+ jid: botNode.attrs.jid,
588
+ personaId: botNode.attrs['persona_id'],
589
+ name: botNode.attrs.name,
590
+ description: botNode.attrs.description
591
+ };
592
+ };
593
+ /**
594
+ * Fetch AB-test (abt) props from server (xmlns="abt").
595
+ * @param {string} [protocol] e.g. "1" or "2"
596
+ * @param {string} [hash]
597
+ * @param {string|null} [refreshId]
598
+ * @param {string|null} [group] group-scoped query when set
599
+ */
600
+ const fetchABProps = async (protocol = '1', hash = '', refreshId = null, group = null) => {
601
+ const propAttrs = group != null
602
+ ? { group: String(group) }
603
+ : {
604
+ protocol,
605
+ ...(hash ? { hash } : {}),
606
+ ...(refreshId != null ? { refresh_id: String(refreshId) } : {})
607
+ };
608
+ const result = await query({
609
+ tag: 'iq',
610
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'abt', type: 'get' },
611
+ content: [{ tag: 'props', attrs: propAttrs }]
612
+ });
613
+ const propsNode = getBinaryNodeChild(result, 'props');
614
+ if (!propsNode)
615
+ return {};
616
+ return reduceBinaryNodeToDictionary(propsNode, 'prop');
617
+ };
618
+ /**
619
+ * Remove a companion (linked) device from the account (xmlns="md").
620
+ * @param {string} jid full device JID of the companion to remove
621
+ * @param {string} [reason] e.g. "user_initiated" | "unknown_companion"
622
+ */
623
+ const removeCompanionDevice = async (jid, reason = 'user_initiated') => {
624
+ await query({
625
+ tag: 'iq',
626
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'md', type: 'set' },
627
+ content: [
628
+ {
629
+ tag: 'remove-companion-device',
630
+ attrs: { jid, reason }
631
+ }
632
+ ]
633
+ });
634
+ };
635
+ /**
636
+ * Push an updated key-index-list to the server (xmlns="md", child "key-index-list").
637
+ * @param {number|string} ts unix timestamp seconds
638
+ * @param {Buffer} content serialized proto KeyIndexList
639
+ */
640
+ const updateKeyIndexList = async (ts, content) => {
641
+ await query({
642
+ tag: 'iq',
643
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'md', type: 'set' },
644
+ content: [
645
+ {
646
+ tag: 'key-index-list',
647
+ attrs: { ts: String(ts) },
648
+ content
649
+ }
650
+ ]
651
+ });
652
+ };
653
+ /**
654
+ * Build and push the companion's signed key-index-list on (re)connect (xmlns="md").
655
+ * Mirrors CompanionDeviceAdvUtil.A02 from the APK: the details proto is signed with
656
+ * our own device identity key (the same key that produces the ADV deviceSignature).
657
+ */
658
+ const sendKeyIndexList = async () => {
659
+ const account = authState.creds.account;
660
+ const signedIdentityKey = authState.creds.signedIdentityKey;
661
+ if (!account?.details || !signedIdentityKey?.private) {
662
+ logger.debug('no ADV account / signed identity key, skipping key-index-list');
663
+ return;
664
+ }
665
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(account.details);
666
+ const keyIndex = deviceIdentity.keyIndex || 0;
667
+ const accountType = deviceIdentity.accountType ?? proto.ADVEncryptionType.E2EE;
668
+ const isHosted = accountType === proto.ADVEncryptionType.HOSTED;
669
+ const ts = Math.floor(Date.now() / 1000);
670
+ const details = proto.ADVKeyIndexList.encode({
671
+ rawId: deviceIdentity.rawId || 0,
672
+ timestamp: ts,
673
+ currentIndex: keyIndex,
674
+ validIndexes: [keyIndex],
675
+ accountType
676
+ }).finish();
677
+ const sigPrefix = isHosted ? WA_ADV_HOSTED_KEY_INDEX_LIST_SIG_PREFIX : WA_ADV_KEY_INDEX_LIST_SIG_PREFIX;
678
+ const accountSignature = Curve.sign(signedIdentityKey.private, Buffer.concat([sigPrefix, details]));
679
+ const signedKeyIndexList = { details, accountSignature };
680
+ if (isHosted && account.accountSignatureKey?.length) {
681
+ signedKeyIndexList.accountSignatureKey = account.accountSignatureKey;
682
+ }
683
+ const content = proto.ADVSignedKeyIndexList.encode(signedKeyIndexList).finish();
684
+ await updateKeyIndexList(ts, Buffer.from(content));
685
+ logger.info({ ts, keyIndex }, 'sent key-index-list');
686
+ };
687
+ /**
688
+ * Request a media upload connection token from the server (xmlns="w:m").
689
+ * @param {string|null} [lastId]
690
+ */
691
+ const fetchMediaConn = async (lastId = null) => {
692
+ const attrs = {};
693
+ if (lastId != null)
694
+ attrs.last_id = String(lastId);
695
+ const result = await query({
696
+ tag: 'iq',
697
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w:m', type: 'set' },
698
+ content: [{ tag: 'media_conn', attrs }]
699
+ });
700
+ return getBinaryNodeChild(result, 'media_conn') || null;
701
+ };
702
+ /**
703
+ * Delete a broadcast list by ID (xmlns="w:b").
704
+ */
705
+ const deleteBroadcastList = async (listId) => {
706
+ await query({
707
+ tag: 'iq',
708
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w:b', type: 'set' },
709
+ content: [
710
+ {
711
+ tag: 'delete',
712
+ attrs: {},
713
+ content: [{ tag: 'list', attrs: { id: String(listId) } }]
714
+ }
715
+ ]
716
+ });
717
+ };
718
+ /**
719
+ * Fetch a QR code from the server (e.g. for linked-device linking) (xmlns="w:qr").
720
+ * @param {string} code
721
+ * @param {'lid'|null} [addressingMode] set to "lid" for LID-addressed QR
722
+ */
723
+ const fetchQRCode = async (code, addressingMode = null) => {
724
+ const attrs = { code };
725
+ if (addressingMode)
726
+ attrs.addressing_mode = addressingMode;
727
+ const result = await query({
728
+ tag: 'iq',
729
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w:qr', type: 'get' },
730
+ content: [{ tag: 'qr', attrs }]
731
+ });
732
+ return getBinaryNodeChild(result, 'qr') || null;
733
+ };
734
+ /**
735
+ * Confirm or deny a device-logout request from the server (xmlns="w:account_defence").
736
+ * @param {string|number} id the challenge id
737
+ * @param {boolean} [approve] true to confirm the logout, false to deny
738
+ */
739
+ const confirmDeviceLogout = async (id, approve = true) => {
740
+ await query({
741
+ tag: 'iq',
742
+ attrs: {
743
+ id: String(id),
744
+ to: S_WHATSAPP_NET,
745
+ xmlns: 'w:account_defence',
746
+ type: 'set',
747
+ smax_id: '87'
748
+ },
749
+ content: [
750
+ {
751
+ tag: 'device_logout',
752
+ attrs: { approve: approve ? 'true' : 'false', id: String(id) }
753
+ }
754
+ ]
755
+ });
756
+ };
757
+ const getBotListV2 = async () => {
758
+ const resp = await query({
759
+ tag: 'iq',
760
+ attrs: {
761
+ xmlns: 'bot',
762
+ to: S_WHATSAPP_NET,
763
+ type: 'get'
764
+ },
765
+ content: [
766
+ {
767
+ tag: 'bot',
768
+ attrs: {
769
+ v: '2'
770
+ }
771
+ }
772
+ ]
773
+ });
774
+ const botNode = getBinaryNodeChild(resp, 'bot');
775
+ const botList = [];
776
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
777
+ if (section.attrs.type === 'all') {
778
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
779
+ botList.push({
780
+ jid: bot.attrs.jid,
781
+ personaId: bot.attrs['persona_id']
782
+ });
783
+ }
784
+ }
785
+ }
786
+ return botList;
787
+ };
788
+ const fetchStatus = async (...jids) => {
789
+ const usyncQuery = new USyncQuery().withStatusProtocol();
790
+ for (const jid of jids) {
791
+ usyncQuery.withUser(new USyncUser().withId(jid));
792
+ }
793
+ const result = await sock.executeUSyncQuery(usyncQuery);
794
+ if (result) {
795
+ return result.list;
796
+ }
797
+ };
798
+ const fetchDisappearingDuration = async (...jids) => {
799
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
800
+ for (const jid of jids) {
801
+ usyncQuery.withUser(new USyncUser().withId(jid));
802
+ }
803
+ const result = await sock.executeUSyncQuery(usyncQuery);
804
+ if (result) {
805
+ return result.list;
806
+ }
807
+ };
808
+ // Lia@Note 06-02-26 --- Quick helper only. This function exists solely for faster lookup with caching.
809
+ const findUserId = async (pnLid) => {
810
+ const normalizedJid = jidNormalizedUser(pnLid);
811
+ const userId = {
812
+ lid: undefined,
813
+ phoneNumber: undefined
814
+ };
815
+ if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
816
+ userId.phoneNumber = normalizedJid;
817
+ const resolvedLid = (await signalRepository.lidMapping.getLIDsForPNs([normalizedJid]))?.[0]?.lid;
818
+ userId.lid = resolvedLid ? jidNormalizedUser(resolvedLid) : undefined;
819
+ }
820
+ else if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
821
+ userId.lid = normalizedJid;
822
+ const resolvedPhoneNumber = (await signalRepository.lidMapping.getPNsForLIDs([normalizedJid]))?.[0]?.pn;
823
+ userId.phoneNumber = resolvedPhoneNumber ? jidNormalizedUser(resolvedPhoneNumber) : undefined;
824
+ }
825
+ else {
826
+ throw new Boom('Invalid id input to find user ids', { statusCode: 400 });
827
+ }
828
+ return userId;
829
+ };
830
+ /** update the profile picture for yourself or a group
831
+ *
832
+ * Standard (crop + resize to 720×720):
833
+ * sock.updateProfilePicture(jid, content)
834
+ * sock.updateProfilePicture(jid, content, { width: 640, height: 640 })
835
+ *
836
+ * HD (full-size, no crop, no resize):
837
+ * sock.updateProfilePicture(jid, content, { hd: true })
838
+ */
839
+ const updateProfilePicture = async (jid, content, dimensions) => {
840
+ let targetJid;
841
+ if (!jid) {
842
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
843
+ }
844
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
845
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
846
+ }
847
+ else {
848
+ targetJid = undefined;
849
+ }
850
+ // X4R1S3@HD-Profile --- Dual mode:
851
+ // hd:true → generateProfilePictureHD (preserves aspect ratio, caps at 1920, manages file size)
852
+ // standard → generateProfilePicture (720×720 square crop, or custom dimensions)
853
+ const { img } = dimensions?.hd
854
+ ? await generateProfilePictureHD(content)
855
+ : await generateProfilePicture(content, dimensions);
856
+ await query({
857
+ tag: 'iq',
858
+ attrs: {
859
+ to: S_WHATSAPP_NET,
860
+ type: 'set',
861
+ xmlns: 'w:profile:picture',
862
+ ...(targetJid ? { target: targetJid } : {})
863
+ },
864
+ content: [
865
+ {
866
+ tag: 'picture',
867
+ attrs: { type: 'image' },
868
+ content: img
869
+ }
870
+ ]
871
+ });
872
+ };
873
+ /** remove the profile picture for yourself or a group */
874
+ const removeProfilePicture = async (jid) => {
875
+ let targetJid;
876
+ if (!jid) {
877
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
878
+ }
879
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
880
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
881
+ }
882
+ else {
883
+ targetJid = undefined;
884
+ }
885
+ await query({
886
+ tag: 'iq',
887
+ attrs: {
888
+ to: S_WHATSAPP_NET,
889
+ type: 'set',
890
+ xmlns: 'w:profile:picture',
891
+ ...(targetJid ? { target: targetJid } : {})
892
+ }
893
+ });
894
+ };
895
+ /** update the profile status for yourself */
896
+ const updateProfileStatus = async (status) => {
897
+ if (typeof status !== 'string') {
898
+ throw new TypeError('Profile status must be a string');
899
+ }
900
+ await query({
901
+ tag: 'iq',
902
+ attrs: {
903
+ to: S_WHATSAPP_NET,
904
+ type: 'set',
905
+ xmlns: 'status'
906
+ },
907
+ content: [
908
+ {
909
+ tag: 'status',
910
+ attrs: {},
911
+ content: Buffer.from(status, 'utf-8')
912
+ }
913
+ ]
914
+ });
915
+ };
916
+ const updateProfileName = async (name) => {
917
+ if (typeof name !== 'string') {
918
+ throw new TypeError('Profile name must be a string');
919
+ }
920
+ await chatModify({ pushNameSetting: name }, '');
921
+ };
922
+ const fetchBlocklist = async () => {
923
+ const result = await query({
924
+ tag: 'iq',
925
+ attrs: {
926
+ xmlns: 'blocklist',
927
+ to: S_WHATSAPP_NET,
928
+ type: 'get'
929
+ }
930
+ });
931
+ const listNode = getBinaryNodeChild(result, 'list');
932
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
933
+ };
934
+ const updateBlockStatus = async (jid, action) => {
935
+ const normalizedJid = jidNormalizedUser(jid);
936
+ let lid;
937
+ let pn_jid;
938
+ if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
939
+ lid = normalizedJid;
940
+ if (action === 'block') {
941
+ const pn = (await findUserId(normalizedJid)).phoneNumber;
942
+ if (!pn) {
943
+ throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
944
+ }
945
+ pn_jid = jidNormalizedUser(pn);
946
+ }
947
+ }
948
+ else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
949
+ const mapped = (await findUserId(normalizedJid)).lid;
950
+ if (!mapped) {
951
+ throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
952
+ }
953
+ lid = mapped;
954
+ if (action === 'block') {
955
+ pn_jid = jidNormalizedUser(normalizedJid);
956
+ }
957
+ }
958
+ else {
959
+ throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
960
+ }
961
+ const itemAttrs = {
962
+ action,
963
+ jid: lid
964
+ };
965
+ if (action === 'block') {
966
+ if (!pn_jid) {
967
+ throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
968
+ }
969
+ itemAttrs.pn_jid = pn_jid;
970
+ }
971
+ await query({
972
+ tag: 'iq',
973
+ attrs: {
974
+ xmlns: 'blocklist',
975
+ to: S_WHATSAPP_NET,
976
+ type: 'set'
977
+ },
978
+ content: [
979
+ {
980
+ tag: 'item',
981
+ attrs: itemAttrs
982
+ }
983
+ ]
984
+ });
985
+ };
986
+ const getBusinessProfile = async (jid) => {
987
+ const results = await query({
988
+ tag: 'iq',
989
+ attrs: {
990
+ to: 's.whatsapp.net',
991
+ xmlns: 'w:biz',
992
+ type: 'get'
993
+ },
994
+ content: [
995
+ {
996
+ tag: 'business_profile',
997
+ attrs: { v: '244' },
998
+ content: [
999
+ {
1000
+ tag: 'profile',
1001
+ attrs: { jid }
1002
+ }
1003
+ ]
1004
+ }
1005
+ ]
1006
+ });
1007
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
1008
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
1009
+ if (profiles) {
1010
+ const address = getBinaryNodeChild(profiles, 'address');
1011
+ const description = getBinaryNodeChild(profiles, 'description');
1012
+ const website = getBinaryNodeChild(profiles, 'website');
1013
+ const email = getBinaryNodeChild(profiles, 'email');
1014
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
1015
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours');
1016
+ const businessHoursConfig = businessHours
1017
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
1018
+ : undefined;
1019
+ const websiteStr = website?.content?.toString();
1020
+ return {
1021
+ wid: profiles.attrs?.jid,
1022
+ address: address?.content?.toString(),
1023
+ description: description?.content?.toString() || '',
1024
+ website: websiteStr ? [websiteStr] : [],
1025
+ email: email?.content?.toString(),
1026
+ category: category?.content?.toString(),
1027
+ business_hours: {
1028
+ timezone: businessHours?.attrs?.timezone,
1029
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
1030
+ }
1031
+ };
1032
+ }
1033
+ };
1034
+ const cleanDirtyBits = async (type, fromTimestamp) => {
1035
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
1036
+ await sendNode({
1037
+ tag: 'iq',
1038
+ attrs: {
1039
+ to: S_WHATSAPP_NET,
1040
+ type: 'set',
1041
+ xmlns: 'urn:xmpp:whatsapp:dirty',
1042
+ id: generateMessageTag()
1043
+ },
1044
+ content: [
1045
+ {
1046
+ tag: 'clean',
1047
+ attrs: {
1048
+ type,
1049
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
1050
+ }
1051
+ }
1052
+ ]
1053
+ });
1054
+ };
1055
+ const newAppStateChunkHandler = (isInitialSync) => {
1056
+ return {
1057
+ onMutation(mutation) {
1058
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
1059
+ }
1060
+ };
1061
+ };
1062
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
1063
+ const appStateSyncKeyCache = new Map();
1064
+ const getCachedAppStateSyncKey = async (keyId) => {
1065
+ if (appStateSyncKeyCache.has(keyId)) {
1066
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
1067
+ }
1068
+ const key = await getAppStateSyncKey(keyId);
1069
+ appStateSyncKeyCache.set(keyId, key ?? null);
1070
+ return key;
1071
+ };
1072
+ // we use this to determine which events to fire
1073
+ // otherwise when we resync from scratch -- all notifications will fire
1074
+ const initialVersionMap = {};
1075
+ const globalMutationMap = {};
1076
+ await authState.keys.transaction(async () => {
1077
+ const collectionsToHandle = new Set(collections);
1078
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
1079
+ const attemptsMap = {};
1080
+ // collections that failed and need a full snapshot on retry
1081
+ // mirrors WA Web's ErrorFatal -> force snapshot behavior
1082
+ const forceSnapshotCollections = new Set();
1083
+ // keep executing till all collections are done
1084
+ // sometimes a single patch request will not return all the patches (God knows why)
1085
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
1086
+ while (collectionsToHandle.size) {
1087
+ const states = {};
1088
+ const nodes = [];
1089
+ for (const name of collectionsToHandle) {
1090
+ const result = await authState.keys.get('app-state-sync-version', [name]);
1091
+ let state = result[name];
1092
+ if (state) {
1093
+ state = ensureLTHashStateVersion(state);
1094
+ if (typeof initialVersionMap[name] === 'undefined') {
1095
+ initialVersionMap[name] = state.version;
1096
+ }
1097
+ }
1098
+ else {
1099
+ state = newLTHashState();
1100
+ }
1101
+ states[name] = state;
1102
+ const shouldForceSnapshot = forceSnapshotCollections.has(name);
1103
+ if (shouldForceSnapshot) {
1104
+ forceSnapshotCollections.delete(name);
1105
+ }
1106
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
1107
+ nodes.push({
1108
+ tag: 'collection',
1109
+ attrs: {
1110
+ name,
1111
+ version: state.version.toString(),
1112
+ // return snapshot if syncing from scratch or forcing after a failed attempt
1113
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
1114
+ }
1115
+ });
1116
+ }
1117
+ const result = await query({
1118
+ tag: 'iq',
1119
+ attrs: {
1120
+ to: S_WHATSAPP_NET,
1121
+ xmlns: 'w:sync:app:state',
1122
+ type: 'set'
1123
+ },
1124
+ content: [
1125
+ {
1126
+ tag: 'sync',
1127
+ attrs: {},
1128
+ content: nodes
1129
+ }
1130
+ ]
1131
+ });
1132
+ // extract from binary node
1133
+ const decoded = await extractSyncdPatches(result, config?.options);
1134
+ for (const key in decoded) {
1135
+ const name = key;
1136
+ const { patches, hasMorePatches, snapshot } = decoded[name];
1137
+ try {
1138
+ if (snapshot) {
1139
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
1140
+ states[name] = newState;
1141
+ Object.assign(globalMutationMap, mutationMap);
1142
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
1143
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
1144
+ }
1145
+ // only process if there are syncd patches
1146
+ if (patches.length) {
1147
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
1148
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
1149
+ logger.info(`synced ${name} to v${newState.version}`);
1150
+ initialVersionMap[name] = newState.version;
1151
+ Object.assign(globalMutationMap, mutationMap);
1152
+ }
1153
+ if (hasMorePatches) {
1154
+ logger.info(`${name} has more patches...`);
1155
+ }
1156
+ else {
1157
+ // collection is done with sync
1158
+ collectionsToHandle.delete(name);
1159
+ }
1160
+ }
1161
+ catch (error) {
1162
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
1163
+ const logData = {
1164
+ name,
1165
+ attempt: attemptsMap[name],
1166
+ version: states[name].version,
1167
+ statusCode: error.output?.statusCode,
1168
+ errorType: error.name,
1169
+ error: error.stack
1170
+ };
1171
+ if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
1172
+ // WA Web treats missing keys as "Blocked" — park the collection
1173
+ // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
1174
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
1175
+ blockedCollections.add(name);
1176
+ collectionsToHandle.delete(name);
1177
+ }
1178
+ else if (isMissingKeyError(error)) {
1179
+ // Retry with a snapshot which may use a different key.
1180
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
1181
+ forceSnapshotCollections.add(name);
1182
+ }
1183
+ else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
1184
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
1185
+ collectionsToHandle.delete(name);
1186
+ }
1187
+ else {
1188
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
1189
+ // force a full snapshot on retry to recover from
1190
+ // corrupted local state (e.g. LTHash MAC mismatch)
1191
+ forceSnapshotCollections.add(name);
1192
+ }
1193
+ }
1194
+ }
1195
+ }
1196
+ }, authState?.creds?.me?.id || 'resync-app-state');
1197
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
1198
+ for (const key in globalMutationMap) {
1199
+ onMutation(globalMutationMap[key]);
1200
+ }
1201
+ });
1202
+ /**
1203
+ * fetch the profile picture of a user/group
1204
+ * type = "preview" for a low res picture
1205
+ * type = "image for the high res picture"
1206
+ */
1207
+ const profilePictureUrl = async (jid, type = 'image', timeoutMs = 5000, shouldIncludeTcToken = false) => {
1208
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
1209
+ // WA Web only includes tctoken for user JIDs (not groups/newsletters)
1210
+ // and never for own profile pic (Chat model for self has no tcToken).
1211
+ // Including tctoken for own JID causes the server to never respond.
1212
+ const normalizedJid = jidNormalizedUser(jid);
1213
+ const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
1214
+ const me = authState.creds.me;
1215
+ const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
1216
+ let content = baseContent;
1217
+ if (shouldIncludeTcToken && serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
1218
+ content = await buildTcTokenFromJid({
1219
+ authState,
1220
+ jid: normalizedJid,
1221
+ baseContent,
1222
+ getLIDForPN
1223
+ });
1224
+ }
1225
+ jid = jidNormalizedUser(jid);
1226
+ const result = await query({
1227
+ tag: 'iq',
1228
+ attrs: {
1229
+ target: jid,
1230
+ to: S_WHATSAPP_NET,
1231
+ type: 'get',
1232
+ xmlns: 'w:profile:picture'
1233
+ },
1234
+ content
1235
+ }, timeoutMs);
1236
+ const child = getBinaryNodeChild(result, 'picture');
1237
+ return child?.attrs?.url;
1238
+ };
1239
+ const createCallLink = async (type, event, timeoutMs) => {
1240
+ const result = await query({
1241
+ tag: 'call',
1242
+ attrs: {
1243
+ id: generateMessageTag(),
1244
+ to: '@call'
1245
+ },
1246
+ content: [
1247
+ {
1248
+ tag: 'link_create',
1249
+ attrs: { media: type },
1250
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
1251
+ }
1252
+ ]
1253
+ }, timeoutMs);
1254
+ const child = getBinaryNodeChild(result, 'link_create');
1255
+ return child?.attrs?.token;
1256
+ };
1257
+ const sendPresenceUpdate = async (type, toJid) => {
1258
+ const me = authState.creds.me;
1259
+ const isAvailableType = type === 'available';
1260
+ if (isAvailableType || type === 'unavailable') {
1261
+ if (!me.name) {
1262
+ logger.warn('no name present, ignoring presence update request...');
1263
+ return;
1264
+ }
1265
+ ev.emit('connection.update', { isOnline: isAvailableType });
1266
+ if (isAvailableType) {
1267
+ void sendUnifiedSession();
1268
+ }
1269
+ await sendNode({
1270
+ tag: 'presence',
1271
+ attrs: {
1272
+ name: me.name.replace(/@/g, ''),
1273
+ type
1274
+ }
1275
+ });
1276
+ }
1277
+ else {
1278
+ const { server } = jidDecode(toJid);
1279
+ const isLid = server === 'lid';
1280
+ await sendNode({
1281
+ tag: 'chatstate',
1282
+ attrs: {
1283
+ from: isLid ? me.lid : me.id,
1284
+ to: toJid
1285
+ },
1286
+ content: [
1287
+ {
1288
+ tag: type === 'recording' ? 'composing' : type,
1289
+ attrs: type === 'recording' ? { media: 'audio' } : {}
1290
+ }
1291
+ ]
1292
+ });
1293
+ }
1294
+ };
1295
+ /**
1296
+ * @param toJid the jid to subscribe to
1297
+ * @param tcToken token for subscription, use if present
1298
+ */
1299
+ const presenceSubscribe = async (toJid) => {
1300
+ // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
1301
+ const normalizedToJid = jidNormalizedUser(toJid);
1302
+ const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid);
1303
+ const tcTokenContent = isUserJid
1304
+ ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN })
1305
+ : undefined;
1306
+ return sendNode({
1307
+ tag: 'presence',
1308
+ attrs: {
1309
+ to: toJid,
1310
+ id: generateMessageTag(),
1311
+ type: 'subscribe'
1312
+ },
1313
+ content: tcTokenContent
1314
+ });
1315
+ };
1316
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
1317
+ let presence;
1318
+ const jid = attrs.from;
1319
+ const participant = attrs.participant || attrs.from;
1320
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
1321
+ return;
1322
+ }
1323
+ if (tag === 'presence') {
1324
+ presence = {
1325
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
1326
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
1327
+ groupOnlineCount: attrs.count ? +attrs.count : undefined
1328
+ };
1329
+ }
1330
+ else if (Array.isArray(content)) {
1331
+ const [firstChild] = content;
1332
+ let type = firstChild.tag;
1333
+ if (type === 'paused') {
1334
+ type = 'available';
1335
+ }
1336
+ if (firstChild.attrs?.media === 'audio') {
1337
+ type = 'recording';
1338
+ }
1339
+ presence = { lastKnownPresence: type };
1340
+ }
1341
+ else {
1342
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
1343
+ }
1344
+ if (presence) {
1345
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
1346
+ }
1347
+ };
1348
+ const appPatch = async (patchCreate) => {
1349
+ const name = patchCreate.type;
1350
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
1351
+ if (!myAppStateKeyId) {
1352
+ throw new Boom('App state key not present!', { statusCode: 400 });
1353
+ }
1354
+ let initial;
1355
+ let encodeResult;
1356
+ await appStatePatchMutex.mutex(async () => {
1357
+ await authState.keys.transaction(async () => {
1358
+ logger.debug({ patch: patchCreate }, 'applying app patch');
1359
+ await resyncAppState([name], false);
1360
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
1361
+ initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
1362
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
1363
+ const { patch, state } = encodeResult;
1364
+ const node = {
1365
+ tag: 'iq',
1366
+ attrs: {
1367
+ to: S_WHATSAPP_NET,
1368
+ type: 'set',
1369
+ xmlns: 'w:sync:app:state'
1370
+ },
1371
+ content: [
1372
+ {
1373
+ tag: 'sync',
1374
+ attrs: {},
1375
+ content: [
1376
+ {
1377
+ tag: 'collection',
1378
+ attrs: {
1379
+ name,
1380
+ version: (state.version - 1).toString(),
1381
+ return_snapshot: 'false'
1382
+ },
1383
+ content: [
1384
+ {
1385
+ tag: 'patch',
1386
+ attrs: {},
1387
+ content: proto.SyncdPatch.encode(patch).finish()
1388
+ }
1389
+ ]
1390
+ }
1391
+ ]
1392
+ }
1393
+ ]
1394
+ };
1395
+ await query(node);
1396
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
1397
+ }, authState?.creds?.me?.id || 'app-patch');
1398
+ });
1399
+ if (config.emitOwnEvents) {
1400
+ const { onMutation } = newAppStateChunkHandler(false);
1401
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
1402
+ for (const key in mutationMap) {
1403
+ onMutation(mutationMap[key]);
1404
+ }
1405
+ }
1406
+ };
1407
+ /** fetch AB props */
1408
+ const fetchProps = async () => {
1409
+ const resultNode = await query({
1410
+ tag: 'iq',
1411
+ attrs: {
1412
+ to: S_WHATSAPP_NET,
1413
+ xmlns: 'abt',
1414
+ type: 'get'
1415
+ },
1416
+ content: [
1417
+ {
1418
+ tag: 'props',
1419
+ attrs: {
1420
+ protocol: '1',
1421
+ ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
1422
+ }
1423
+ }
1424
+ ]
1425
+ });
1426
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
1427
+ let props = {};
1428
+ if (propsNode) {
1429
+ if (propsNode.attrs?.hash) {
1430
+ // on some clients, the hash is returning as undefined
1431
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
1432
+ ev.emit('creds.update', authState.creds);
1433
+ }
1434
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop');
1435
+ }
1436
+ // Extract protocol-relevant AB props (only the ones we need)
1437
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
1438
+ if (privacyTokenProp !== undefined) {
1439
+ serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
1440
+ }
1441
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
1442
+ if (profilePicProp !== undefined) {
1443
+ serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
1444
+ }
1445
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
1446
+ if (lidIssueProp !== undefined) {
1447
+ serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
1448
+ }
1449
+ logger.debug({ serverProps }, 'fetched props');
1450
+ return props;
1451
+ };
1452
+ /**
1453
+ * modify a chat -- mark unread, read etc.
1454
+ * lastMessages must be sorted in reverse chronologically
1455
+ * requires the last messages till the last message received; required for archive & unread
1456
+ */
1457
+ const chatModify = (mod, jid) => {
1458
+ const patch = chatModificationToAppPatch(mod, jid);
1459
+ return appPatch(patch);
1460
+ };
1461
+ /**
1462
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
1463
+ */
1464
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
1465
+ return chatModify({
1466
+ disableLinkPreviews: { isPreviewsDisabled }
1467
+ }, '');
1468
+ };
1469
+ /**
1470
+ * Star or Unstar a message
1471
+ */
1472
+ const star = (jid, messages, star) => {
1473
+ return chatModify({
1474
+ star: {
1475
+ messages,
1476
+ star
1477
+ }
1478
+ }, jid);
1479
+ };
1480
+ /**
1481
+ * Add or Edit Contact
1482
+ */
1483
+ const addOrEditContact = (jid, contact) => {
1484
+ return chatModify({
1485
+ contact
1486
+ }, jid);
1487
+ };
1488
+ /**
1489
+ * Remove Contact
1490
+ */
1491
+ const removeContact = (jid) => {
1492
+ return chatModify({
1493
+ contact: null
1494
+ }, jid);
1495
+ };
1496
+ /**
1497
+ * Adds label
1498
+ */
1499
+ const addLabel = (jid, labels) => {
1500
+ return chatModify({
1501
+ addLabel: {
1502
+ ...labels
1503
+ }
1504
+ }, jid);
1505
+ };
1506
+ /**
1507
+ * Adds label for the chats
1508
+ */
1509
+ const addChatLabel = (jid, labelId) => {
1510
+ return chatModify({
1511
+ addChatLabel: {
1512
+ labelId
1513
+ }
1514
+ }, jid);
1515
+ };
1516
+ /**
1517
+ * Removes label for the chat
1518
+ */
1519
+ const removeChatLabel = (jid, labelId) => {
1520
+ return chatModify({
1521
+ removeChatLabel: {
1522
+ labelId
1523
+ }
1524
+ }, jid);
1525
+ };
1526
+ /**
1527
+ * Adds label for the message
1528
+ */
1529
+ const addMessageLabel = (jid, messageId, labelId) => {
1530
+ return chatModify({
1531
+ addMessageLabel: {
1532
+ messageId,
1533
+ labelId
1534
+ }
1535
+ }, jid);
1536
+ };
1537
+ /**
1538
+ * Removes label for the message
1539
+ */
1540
+ const removeMessageLabel = (jid, messageId, labelId) => {
1541
+ return chatModify({
1542
+ removeMessageLabel: {
1543
+ messageId,
1544
+ labelId
1545
+ }
1546
+ }, jid);
1547
+ };
1548
+ /**
1549
+ * Add or Edit Quick Reply
1550
+ */
1551
+ const addOrEditQuickReply = (quickReply) => {
1552
+ return chatModify({
1553
+ quickReply
1554
+ }, '');
1555
+ };
1556
+ /**
1557
+ * Remove Quick Reply
1558
+ */
1559
+ const removeQuickReply = (timestamp) => {
1560
+ return chatModify({
1561
+ quickReply: { timestamp, deleted: true }
1562
+ }, '');
1563
+ };
1564
+ /**
1565
+ * X4R1S3@Favorites --- Set complete WhatsApp Favorites list.
1566
+ * Replaces server-side list with the provided array (merging is handled by caller).
1567
+ * @param jids — complete array of JIDs to set as favorites
1568
+ */
1569
+ const addToFavorites = (jids) => {
1570
+ return chatModify({
1571
+ favorites: { jids, add: true }
1572
+ }, '');
1573
+ };
1574
+ /**
1575
+ * X4R1S3@Favorites --- Remove all favorites (clear list).
1576
+ */
1577
+ const removeFromFavorites = (jids) => {
1578
+ // For single removal, caller must pass remaining list to addToFavorites
1579
+ // This sends the provided jids array (should be remaining items after filter)
1580
+ return chatModify({
1581
+ favorites: { jids, add: true }
1582
+ }, '');
1583
+ };
1584
+ /**
1585
+ * queries need to be fired on connection open
1586
+ * help ensure parity with WA Web
1587
+ * */
1588
+ const executeInitQueries = async () => {
1589
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
1590
+ };
1591
+
1592
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
1593
+ // Cache newsletter server_id for use when this message is later quoted
1594
+ if (msg.newsletter && msg.newsletter_server_id && msg.key?.id) {
1595
+ _nlServerIdCache.set(msg.key.id, msg.newsletter_server_id);
1596
+ }
1597
+ // If this message quotes a newsletter post, enrich it with the cached server_id
1598
+ if (msg.message) {
1599
+ const ci = Object.values(msg.message).find(v => v?.contextInfo)?.contextInfo;
1600
+ if (ci?.stanzaId && isJidNewsletter(ci.remoteJid)) {
1601
+ const sid = _nlServerIdCache.get(ci.stanzaId);
1602
+ if (sid != null)
1603
+ msg.quotedNewsletterServerId = sid;
1604
+ }
1605
+ }
1606
+ ev.emit('messages.upsert', { messages: [msg], type });
1607
+ if (!!msg.pushName) {
1608
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
1609
+ jid = jidNormalizedUser(jid);
1610
+ if (!msg.key.fromMe) {
1611
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
1612
+ }
1613
+ // update our pushname too
1614
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
1615
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
1616
+ }
1617
+ }
1618
+ const historyMsg = getHistoryMsg(msg.message);
1619
+ const shouldProcessHistoryMsg = historyMsg
1620
+ ? shouldSyncHistoryMessage(historyMsg) &&
1621
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
1622
+ : false;
1623
+ if (historyMsg && shouldProcessHistoryMsg) {
1624
+ const syncType = historyMsg.syncType;
1625
+ // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
1626
+ if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
1627
+ !historySyncStatus.initialBootstrapComplete) {
1628
+ historySyncStatus.initialBootstrapComplete = true;
1629
+ ev.emit('messaging-history.status', {
1630
+ syncType,
1631
+ status: 'complete',
1632
+ explicit: true
1633
+ });
1634
+ }
1635
+ // RECENT with progress === 100 — explicit completion
1636
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT &&
1637
+ historyMsg.progress === 100 &&
1638
+ !historySyncStatus.recentSyncComplete) {
1639
+ historySyncStatus.recentSyncComplete = true;
1640
+ clearTimeout(historySyncPausedTimeout);
1641
+ historySyncPausedTimeout = undefined;
1642
+ ev.emit('messaging-history.status', {
1643
+ syncType,
1644
+ status: 'complete',
1645
+ explicit: true
1646
+ });
1647
+ }
1648
+ // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
1649
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
1650
+ clearTimeout(historySyncPausedTimeout);
1651
+ historySyncPausedTimeout = setTimeout(() => {
1652
+ if (!historySyncStatus.recentSyncComplete) {
1653
+ historySyncStatus.recentSyncComplete = true;
1654
+ ev.emit('messaging-history.status', {
1655
+ syncType: proto.HistorySync.HistorySyncType.RECENT,
1656
+ status: 'paused',
1657
+ explicit: false
1658
+ });
1659
+ }
1660
+ historySyncPausedTimeout = undefined;
1661
+ }, HISTORY_SYNC_PAUSED_TIMEOUT_MS);
1662
+ }
1663
+ }
1664
+ // State machine: decide on sync and flush
1665
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
1666
+ if (awaitingSyncTimeout) {
1667
+ clearTimeout(awaitingSyncTimeout);
1668
+ awaitingSyncTimeout = undefined;
1669
+ }
1670
+ if (shouldProcessHistoryMsg) {
1671
+ syncState = SyncState.Syncing;
1672
+ logger.info('Transitioned to Syncing state');
1673
+ // Let doAppStateSync handle the final flush after it's done
1674
+ }
1675
+ else {
1676
+ syncState = SyncState.Online;
1677
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
1678
+ ev.flush();
1679
+ }
1680
+ }
1681
+ const doAppStateSync = async () => {
1682
+ if (syncState === SyncState.Syncing) {
1683
+ // All collections will be synced, so clear any blocked ones
1684
+ blockedCollections.clear();
1685
+ logger.info('Doing app state sync');
1686
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
1687
+ // Sync is complete, go online and flush everything
1688
+ syncState = SyncState.Online;
1689
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
1690
+ ev.flush();
1691
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1692
+ ev.emit('creds.update', { accountSyncCounter });
1693
+ }
1694
+ };
1695
+ await Promise.all([
1696
+ (async () => {
1697
+ if (shouldProcessHistoryMsg) {
1698
+ await doAppStateSync();
1699
+ }
1700
+ })(),
1701
+ processMessage(msg, {
1702
+ signalRepository,
1703
+ shouldProcessHistoryMsg,
1704
+ placeholderResendCache,
1705
+ ev,
1706
+ creds: authState.creds,
1707
+ keyStore: authState.keys,
1708
+ logger,
1709
+ options: config.options,
1710
+ getMessage,
1711
+ messageSecurityStore: config.messageSecurityStore
1712
+ })
1713
+ ]);
1714
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
1715
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
1716
+ logger.info('App state sync key arrived, triggering app state sync');
1717
+ await doAppStateSync();
1718
+ }
1719
+ });
1720
+ ws.on('CB:presence', handlePresenceUpdate);
1721
+ ws.on('CB:chatstate', handlePresenceUpdate);
1722
+ ws.on('CB:ib,,dirty', async (node) => {
1723
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
1724
+ const type = attrs.type;
1725
+ switch (type) {
1726
+ case 'account_sync':
1727
+ if (attrs.timestamp) {
1728
+ let { lastAccountSyncTimestamp } = authState.creds;
1729
+ if (lastAccountSyncTimestamp) {
1730
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
1731
+ }
1732
+ lastAccountSyncTimestamp = +attrs.timestamp;
1733
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
1734
+ }
1735
+ break;
1736
+ case 'groups':
1737
+ // handled in groups.ts
1738
+ break;
1739
+ default:
1740
+ logger.info({ node }, 'received unknown sync');
1741
+ break;
1742
+ }
1743
+ });
1744
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1745
+ if (connection === 'close') {
1746
+ blockedCollections.clear();
1747
+ clearTimeout(historySyncPausedTimeout);
1748
+ historySyncPausedTimeout = undefined;
1749
+ }
1750
+ if (connection === 'open') {
1751
+ if (fireInitQueries) {
1752
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
1753
+ }
1754
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
1755
+ }
1756
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1757
+ return;
1758
+ }
1759
+ historySyncStatus.initialBootstrapComplete = false;
1760
+ historySyncStatus.recentSyncComplete = false;
1761
+ clearTimeout(historySyncPausedTimeout);
1762
+ historySyncPausedTimeout = undefined;
1763
+ syncState = SyncState.AwaitingInitialSync;
1764
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
1765
+ ev.buffer();
1766
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
1767
+ syncType: proto.HistorySync.HistorySyncType.RECENT
1768
+ }));
1769
+ if (!willSyncHistory) {
1770
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1771
+ syncState = SyncState.Online;
1772
+ setTimeout(() => ev.flush(), 0);
1773
+ return;
1774
+ }
1775
+ // On reconnection (accountSyncCounter > 0), the server does not push
1776
+ // history sync notifications — the device already has its data.
1777
+ // Skip the 20s wait and go online immediately.
1778
+ if (authState.creds.accountSyncCounter > 0) {
1779
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
1780
+ syncState = SyncState.Online;
1781
+ setTimeout(() => ev.flush(), 0);
1782
+ return;
1783
+ }
1784
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.');
1785
+ if (awaitingSyncTimeout) {
1786
+ clearTimeout(awaitingSyncTimeout);
1787
+ }
1788
+ awaitingSyncTimeout = setTimeout(() => {
1789
+ if (syncState === SyncState.AwaitingInitialSync) {
1790
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1791
+ syncState = SyncState.Online;
1792
+ ev.flush();
1793
+ // Increment so subsequent reconnections skip the 20s wait.
1794
+ // Late-arriving history is still processed via processMessage
1795
+ // regardless of the state machine phase.
1796
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1797
+ ev.emit('creds.update', { accountSyncCounter });
1798
+ }
1799
+ }, 20000);
1800
+ });
1801
+ // When an app state sync key arrives (myAppStateKeyId is set) and there are
1802
+ // collections blocked on a missing key, trigger a re-sync for just those collections.
1803
+ // This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
1804
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
1805
+ if (!myAppStateKeyId || blockedCollections.size === 0) {
1806
+ return;
1807
+ }
1808
+ // If we're in the middle of a full sync, doAppStateSync handles all collections
1809
+ if (syncState === SyncState.Syncing) {
1810
+ blockedCollections.clear();
1811
+ return;
1812
+ }
1813
+ const collections = [...blockedCollections];
1814
+ blockedCollections.clear();
1815
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
1816
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
1817
+ });
1818
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
1819
+ try {
1820
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1821
+ }
1822
+ catch (error) {
1823
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1824
+ }
1825
+ });
1826
+ registerSocketEndHandler(() => {
1827
+ if (awaitingSyncTimeout) {
1828
+ clearTimeout(awaitingSyncTimeout);
1829
+ awaitingSyncTimeout = undefined;
1830
+ }
1831
+ if (!config.placeholderResendCache && placeholderResendCache.close) {
1832
+ placeholderResendCache.close();
1833
+ }
1834
+ syncState = SyncState.Connecting;
1835
+ privacySettings = undefined;
1836
+ });
1837
+ return {
1838
+ ...sock,
1839
+ findUserId,
1840
+ serverProps,
1841
+ createCallLink,
1842
+ getBotListV2,
1843
+ messageMutex,
1844
+ receiptMutex,
1845
+ appStatePatchMutex,
1846
+ notificationMutex,
1847
+ fetchPrivacySettings,
1848
+ upsertMessage,
1849
+ appPatch,
1850
+ sendPresenceUpdate,
1851
+ presenceSubscribe,
1852
+ profilePictureUrl,
1853
+ fetchBlocklist,
1854
+ fetchStatus,
1855
+ fetchDisappearingDuration,
1856
+ updateProfilePicture,
1857
+ removeProfilePicture,
1858
+ updateProfileStatus,
1859
+ updateProfileName,
1860
+ updateBlockStatus,
1861
+ updateDisableLinkPreviewsPrivacy,
1862
+ updateCallPrivacy,
1863
+ updateMessagesPrivacy,
1864
+ updateLastSeenPrivacy,
1865
+ updateOnlinePrivacy,
1866
+ updateProfilePicturePrivacy,
1867
+ updateStatusPrivacy,
1868
+ updateReadReceiptsPrivacy,
1869
+ updateGroupsAddPrivacy,
1870
+ updateDefaultDisappearingMode,
1871
+ getStatusPrivacy,
1872
+ setStatusPrivacy,
1873
+ fetchBroadcastListQuota,
1874
+ getChatBlockingStatus,
1875
+ updateChatBlockingStatus,
1876
+ getUserDisclosures,
1877
+ acceptTosNotice,
1878
+ reportSpam,
1879
+ reportUser,
1880
+ reportMessage,
1881
+ reportAndBlockUser,
1882
+ toggleGroupHistory,
1883
+ getOptOutList,
1884
+ signPrivateCredential,
1885
+ getPushConfig,
1886
+ setPushConfig,
1887
+ toggleCallLinkWaitingRoom,
1888
+ storePrivacyTokens,
1889
+ executeUSyncQuery,
1890
+ updateBioPrivacy,
1891
+ blockBot,
1892
+ unblockBot,
1893
+ getBotProfile,
1894
+ fetchABProps,
1895
+ removeCompanionDevice,
1896
+ updateKeyIndexList,
1897
+ sendKeyIndexList,
1898
+ fetchMediaConn,
1899
+ deleteBroadcastList,
1900
+ fetchQRCode,
1901
+ confirmDeviceLogout,
1902
+ getBusinessProfile,
1903
+ resyncAppState,
1904
+ chatModify,
1905
+ cleanDirtyBits,
1906
+ addOrEditContact,
1907
+ removeContact,
1908
+ placeholderResendCache,
1909
+ addLabel,
1910
+ addChatLabel,
1911
+ removeChatLabel,
1912
+ addMessageLabel,
1913
+ removeMessageLabel,
1914
+ star,
1915
+ addOrEditQuickReply,
1916
+ removeQuickReply,
1917
+ addToFavorites,
1918
+ removeFromFavorites,
1919
+ newsletterServerIdCache: _nlServerIdCache
1920
+ };
1921
+ };