@codexverified/baileys 2.7.5

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