@nexustechpro/baileys 2.0.2 → 2.0.6

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 (108) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +924 -1299
  3. package/WAProto/index.js +22 -18
  4. package/lib/Defaults/baileys-version.json +6 -2
  5. package/lib/Defaults/index.js +173 -172
  6. package/lib/Signal/libsignal.js +395 -292
  7. package/lib/Signal/lid-mapping.js +264 -171
  8. package/lib/Socket/Client/index.js +2 -2
  9. package/lib/Socket/Client/types.js +10 -10
  10. package/lib/Socket/Client/websocket.js +45 -310
  11. package/lib/Socket/business.js +375 -375
  12. package/lib/Socket/chats.js +916 -963
  13. package/lib/Socket/communities.js +430 -430
  14. package/lib/Socket/groups.js +342 -342
  15. package/lib/Socket/index.js +21 -22
  16. package/lib/Socket/messages-recv.js +963 -743
  17. package/lib/Socket/messages-send.js +273 -321
  18. package/lib/Socket/mex.js +50 -50
  19. package/lib/Socket/newsletter.js +148 -148
  20. package/lib/Socket/nexus-handler.js +296 -247
  21. package/lib/Socket/registration.js +50 -33
  22. package/lib/Socket/socket.js +872 -1201
  23. package/lib/Store/index.js +5 -5
  24. package/lib/Store/make-cache-manager-store.js +81 -81
  25. package/lib/Store/make-in-memory-store.js +416 -416
  26. package/lib/Store/make-ordered-dictionary.js +81 -81
  27. package/lib/Store/object-repository.js +30 -30
  28. package/lib/Types/Auth.js +1 -1
  29. package/lib/Types/Bussines.js +1 -1
  30. package/lib/Types/Call.js +1 -1
  31. package/lib/Types/Chat.js +7 -7
  32. package/lib/Types/Contact.js +1 -1
  33. package/lib/Types/Events.js +1 -1
  34. package/lib/Types/GroupMetadata.js +1 -1
  35. package/lib/Types/Label.js +24 -24
  36. package/lib/Types/LabelAssociation.js +6 -6
  37. package/lib/Types/Message.js +10 -10
  38. package/lib/Types/Newsletter.js +37 -29
  39. package/lib/Types/Product.js +1 -1
  40. package/lib/Types/Signal.js +1 -1
  41. package/lib/Types/Socket.js +2 -2
  42. package/lib/Types/State.js +55 -12
  43. package/lib/Types/USync.js +1 -1
  44. package/lib/Types/index.js +25 -25
  45. package/lib/Utils/auth-utils.js +264 -256
  46. package/lib/Utils/baileys-event-stream.js +55 -55
  47. package/lib/Utils/browser-utils.js +27 -27
  48. package/lib/Utils/business.js +228 -230
  49. package/lib/Utils/chat-utils.js +726 -764
  50. package/lib/Utils/companion-reg-client-utils.js +34 -0
  51. package/lib/Utils/crypto.js +109 -135
  52. package/lib/Utils/decode-wa-message.js +342 -314
  53. package/lib/Utils/event-buffer.js +547 -547
  54. package/lib/Utils/generics.js +295 -297
  55. package/lib/Utils/history.js +91 -83
  56. package/lib/Utils/index.js +25 -20
  57. package/lib/Utils/key-store.js +17 -0
  58. package/lib/Utils/link-preview.js +107 -98
  59. package/lib/Utils/logger.js +2 -2
  60. package/lib/Utils/lt-hash.js +47 -47
  61. package/lib/Utils/make-mutex.js +39 -39
  62. package/lib/Utils/message-retry-manager.js +148 -148
  63. package/lib/Utils/messages-media.js +579 -535
  64. package/lib/Utils/messages.js +821 -706
  65. package/lib/Utils/noise-handler.js +255 -255
  66. package/lib/Utils/pre-key-manager.js +105 -105
  67. package/lib/Utils/process-message.js +430 -412
  68. package/lib/Utils/reporting-utils.js +155 -0
  69. package/lib/Utils/signal.js +191 -159
  70. package/lib/Utils/sync-action-utils.js +33 -0
  71. package/lib/Utils/tc-token-utils.js +162 -0
  72. package/lib/Utils/use-multi-file-auth-state.js +120 -120
  73. package/lib/Utils/validate-connection.js +194 -194
  74. package/lib/WABinary/constants.js +1306 -1300
  75. package/lib/WABinary/decode.js +237 -237
  76. package/lib/WABinary/encode.js +232 -232
  77. package/lib/WABinary/generic-utils.js +252 -211
  78. package/lib/WABinary/index.js +6 -5
  79. package/lib/WABinary/jid-utils.js +279 -95
  80. package/lib/WABinary/types.js +1 -1
  81. package/lib/WAM/BinaryInfo.js +9 -9
  82. package/lib/WAM/constants.js +22852 -22852
  83. package/lib/WAM/encode.js +149 -149
  84. package/lib/WAM/index.js +3 -3
  85. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -28
  86. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -53
  87. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -26
  88. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -37
  89. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
  90. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -28
  91. package/lib/WAUSync/Protocols/index.js +4 -4
  92. package/lib/WAUSync/USyncQuery.js +93 -93
  93. package/lib/WAUSync/USyncUser.js +22 -22
  94. package/lib/WAUSync/index.js +3 -3
  95. package/lib/index.js +65 -66
  96. package/package.json +172 -143
  97. package/lib/Signal/Group/ciphertext-message.js +0 -12
  98. package/lib/Signal/Group/group-session-builder.js +0 -30
  99. package/lib/Signal/Group/group_cipher.js +0 -100
  100. package/lib/Signal/Group/index.js +0 -12
  101. package/lib/Signal/Group/keyhelper.js +0 -18
  102. package/lib/Signal/Group/sender-chain-key.js +0 -26
  103. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  104. package/lib/Signal/Group/sender-key-message.js +0 -66
  105. package/lib/Signal/Group/sender-key-name.js +0 -48
  106. package/lib/Signal/Group/sender-key-record.js +0 -41
  107. package/lib/Signal/Group/sender-key-state.js +0 -84
  108. package/lib/Signal/Group/sender-message-key.js +0 -26
@@ -1,963 +1,916 @@
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, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
- import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
- import { SyncState } from '../Types/State.js';
7
- import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, extractSyncdPatches, generateProfilePicture, getHistoryMsg, newLTHashState, processSyncAction } from '../Utils/index.js';
8
- import { makeMutex } from '../Utils/make-mutex.js';
9
- import processMessage from '../Utils/process-message.js';
10
- import { getBinaryNodeChild, getBinaryNodeChildren, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
11
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
- import { makeSocket } from './socket.js';
13
- const MAX_SYNC_ATTEMPTS = 2;
14
- export const makeChatsSocket = (config) => {
15
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage } = config;
16
- const sock = makeSocket(config);
17
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError } = sock;
18
- let privacySettings;
19
- let syncState = SyncState.Connecting;
20
- /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
21
- const processingMutex = makeMutex();
22
- // Timeout for AwaitingInitialSync state
23
- let awaitingSyncTimeout;
24
- const placeholderResendCache = config.placeholderResendCache ||
25
- new NodeCache({
26
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
27
- useClones: false
28
- });
29
- if (!config.placeholderResendCache) {
30
- config.placeholderResendCache = placeholderResendCache;
31
- }
32
- /** helper function to fetch the given app state sync key */
33
- const getAppStateSyncKey = async (keyId) => {
34
- const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
35
- return key;
36
- };
37
- const fetchPrivacySettings = async (force = false) => {
38
- if (!privacySettings || force) {
39
- const { content } = await query({
40
- tag: 'iq',
41
- attrs: {
42
- xmlns: 'privacy',
43
- to: S_WHATSAPP_NET,
44
- type: 'get'
45
- },
46
- content: [{ tag: 'privacy', attrs: {} }]
47
- });
48
- privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
49
- }
50
- return privacySettings;
51
- };
52
- /** helper function to run a privacy IQ query */
53
- const privacyQuery = async (name, value) => {
54
- await query({
55
- tag: 'iq',
56
- attrs: {
57
- xmlns: 'privacy',
58
- to: S_WHATSAPP_NET,
59
- type: 'set'
60
- },
61
- content: [
62
- {
63
- tag: 'privacy',
64
- attrs: {},
65
- content: [
66
- {
67
- tag: 'category',
68
- attrs: { name, value }
69
- }
70
- ]
71
- }
72
- ]
73
- });
74
- };
75
- const updateMessagesPrivacy = async (value) => {
76
- await privacyQuery('messages', value);
77
- };
78
- const updateCallPrivacy = async (value) => {
79
- await privacyQuery('calladd', value);
80
- };
81
- const updateLastSeenPrivacy = async (value) => {
82
- await privacyQuery('last', value);
83
- };
84
- const updateOnlinePrivacy = async (value) => {
85
- await privacyQuery('online', value);
86
- };
87
- const updateProfilePicturePrivacy = async (value) => {
88
- await privacyQuery('profile', value);
89
- };
90
- const updateStatusPrivacy = async (value) => {
91
- await privacyQuery('status', value);
92
- };
93
- const updateReadReceiptsPrivacy = async (value) => {
94
- await privacyQuery('readreceipts', value);
95
- };
96
- const updateGroupsAddPrivacy = async (value) => {
97
- await privacyQuery('groupadd', value);
98
- };
99
- const updateDefaultDisappearingMode = async (duration) => {
100
- await query({
101
- tag: 'iq',
102
- attrs: {
103
- xmlns: 'disappearing_mode',
104
- to: S_WHATSAPP_NET,
105
- type: 'set'
106
- },
107
- content: [
108
- {
109
- tag: 'disappearing_mode',
110
- attrs: {
111
- duration: duration.toString()
112
- }
113
- }
114
- ]
115
- });
116
- };
117
- const getBotListV2 = async () => {
118
- const resp = await query({
119
- tag: 'iq',
120
- attrs: {
121
- xmlns: 'bot',
122
- to: S_WHATSAPP_NET,
123
- type: 'get'
124
- },
125
- content: [
126
- {
127
- tag: 'bot',
128
- attrs: {
129
- v: '2'
130
- }
131
- }
132
- ]
133
- });
134
- const botNode = getBinaryNodeChild(resp, 'bot');
135
- const botList = [];
136
- for (const section of getBinaryNodeChildren(botNode, 'section')) {
137
- if (section.attrs.type === 'all') {
138
- for (const bot of getBinaryNodeChildren(section, 'bot')) {
139
- botList.push({
140
- jid: bot.attrs.jid,
141
- personaId: bot.attrs['persona_id']
142
- });
143
- }
144
- }
145
- }
146
- return botList;
147
- };
148
- const fetchStatus = async (...jids) => {
149
- const usyncQuery = new USyncQuery().withStatusProtocol();
150
- for (const jid of jids) {
151
- usyncQuery.withUser(new USyncUser().withId(jid));
152
- }
153
- const result = await sock.executeUSyncQuery(usyncQuery);
154
- if (result) {
155
- return result.list;
156
- }
157
- };
158
- const fetchDisappearingDuration = async (...jids) => {
159
- const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
160
- for (const jid of jids) {
161
- usyncQuery.withUser(new USyncUser().withId(jid));
162
- }
163
- const result = await sock.executeUSyncQuery(usyncQuery);
164
- if (result) {
165
- return result.list;
166
- }
167
- };
168
- /** update the profile picture for yourself or a group */
169
- const updateProfilePicture = async (jid, content) => {
170
- let targetJid
171
-
172
- if (!jid) {
173
- throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
174
- }
175
-
176
- if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
177
- targetJid = jidNormalizedUser(jid) // in case it is someone other than us
178
- }
179
-
180
- const { img } = await generateProfilePicture(content)
181
-
182
- await query({
183
- tag: 'iq',
184
- attrs: {
185
- target: targetJid,
186
- to: S_WHATSAPP_NET,
187
- type: 'set',
188
- xmlns: 'w:profile:picture'
189
- },
190
- content: [
191
- {
192
- tag: 'picture',
193
- attrs: { type: 'image' },
194
- content: img
195
- }
196
- ]
197
- })
198
- }
199
- /** remove the profile picture for yourself or a group */
200
- const removeProfilePicture = async (jid) => {
201
- let targetJid;
202
- if (!jid) {
203
- throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
204
- }
205
- if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
206
- targetJid = jidNormalizedUser(jid); // in case it is someone other than us
207
- }
208
- else {
209
- targetJid = undefined;
210
- }
211
- await query({
212
- tag: 'iq',
213
- attrs: {
214
- to: S_WHATSAPP_NET,
215
- type: 'set',
216
- xmlns: 'w:profile:picture',
217
- ...(targetJid ? { target: targetJid } : {})
218
- }
219
- });
220
- };
221
- /** update the profile status for yourself */
222
- const updateProfileStatus = async (status) => {
223
- await query({
224
- tag: 'iq',
225
- attrs: {
226
- to: S_WHATSAPP_NET,
227
- type: 'set',
228
- xmlns: 'status'
229
- },
230
- content: [
231
- {
232
- tag: 'status',
233
- attrs: {},
234
- content: Buffer.from(status, 'utf-8')
235
- }
236
- ]
237
- });
238
- };
239
- const updateProfileName = async (name) => {
240
- await chatModify({ pushNameSetting: name }, '');
241
- };
242
- const fetchBlocklist = async () => {
243
- const result = await query({
244
- tag: 'iq',
245
- attrs: {
246
- xmlns: 'blocklist',
247
- to: S_WHATSAPP_NET,
248
- type: 'get'
249
- }
250
- });
251
- const listNode = getBinaryNodeChild(result, 'list');
252
- return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
253
- };
254
- const updateBlockStatus = async (jid, action) => {
255
- await query({
256
- tag: 'iq',
257
- attrs: {
258
- xmlns: 'blocklist',
259
- to: S_WHATSAPP_NET,
260
- type: 'set'
261
- },
262
- content: [
263
- {
264
- tag: 'item',
265
- attrs: {
266
- action,
267
- jid
268
- }
269
- }
270
- ]
271
- });
272
- };
273
- const getBusinessProfile = async (jid) => {
274
- const results = await query({
275
- tag: 'iq',
276
- attrs: {
277
- to: 's.whatsapp.net',
278
- xmlns: 'w:biz',
279
- type: 'get'
280
- },
281
- content: [
282
- {
283
- tag: 'business_profile',
284
- attrs: { v: '244' },
285
- content: [
286
- {
287
- tag: 'profile',
288
- attrs: { jid }
289
- }
290
- ]
291
- }
292
- ]
293
- });
294
- const profileNode = getBinaryNodeChild(results, 'business_profile');
295
- const profiles = getBinaryNodeChild(profileNode, 'profile');
296
- if (profiles) {
297
- const address = getBinaryNodeChild(profiles, 'address');
298
- const description = getBinaryNodeChild(profiles, 'description');
299
- const website = getBinaryNodeChild(profiles, 'website');
300
- const email = getBinaryNodeChild(profiles, 'email');
301
- const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
302
- const businessHours = getBinaryNodeChild(profiles, 'business_hours');
303
- const businessHoursConfig = businessHours
304
- ? getBinaryNodeChildren(businessHours, 'business_hours_config')
305
- : undefined;
306
- const websiteStr = website?.content?.toString();
307
- return {
308
- wid: profiles.attrs?.jid,
309
- address: address?.content?.toString(),
310
- description: description?.content?.toString() || '',
311
- website: websiteStr ? [websiteStr] : [],
312
- email: email?.content?.toString(),
313
- category: category?.content?.toString(),
314
- business_hours: {
315
- timezone: businessHours?.attrs?.timezone,
316
- business_config: businessHoursConfig?.map(({ attrs }) => attrs)
317
- }
318
- };
319
- }
320
- };
321
- const cleanDirtyBits = async (type, fromTimestamp) => {
322
- logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
323
- await sendNode({
324
- tag: 'iq',
325
- attrs: {
326
- to: S_WHATSAPP_NET,
327
- type: 'set',
328
- xmlns: 'urn:xmpp:whatsapp:dirty',
329
- id: generateMessageTag()
330
- },
331
- content: [
332
- {
333
- tag: 'clean',
334
- attrs: {
335
- type,
336
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
337
- }
338
- }
339
- ]
340
- });
341
- };
342
- const newAppStateChunkHandler = (isInitialSync) => {
343
- return {
344
- onMutation(mutation) {
345
- processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
346
- }
347
- };
348
- };
349
- const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
350
- // we use this to determine which events to fire
351
- // otherwise when we resync from scratch -- all notifications will fire
352
- const initialVersionMap = {};
353
- const globalMutationMap = {};
354
- await authState.keys.transaction(async () => {
355
- const collectionsToHandle = new Set(collections);
356
- // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
357
- const attemptsMap = {};
358
- // keep executing till all collections are done
359
- // sometimes a single patch request will not return all the patches (God knows why)
360
- // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
361
- while (collectionsToHandle.size) {
362
- const states = {};
363
- const nodes = [];
364
- for (const name of collectionsToHandle) {
365
- const result = await authState.keys.get('app-state-sync-version', [name]);
366
- let state = result[name];
367
- if (state) {
368
- if (typeof initialVersionMap[name] === 'undefined') {
369
- initialVersionMap[name] = state.version;
370
- }
371
- }
372
- else {
373
- state = newLTHashState();
374
- }
375
- states[name] = state;
376
- logger.info(`resyncing ${name} from v${state.version}`);
377
- nodes.push({
378
- tag: 'collection',
379
- attrs: {
380
- name,
381
- version: state.version.toString(),
382
- // return snapshot if being synced from scratch
383
- return_snapshot: (!state.version).toString()
384
- }
385
- });
386
- }
387
- const result = await query({
388
- tag: 'iq',
389
- attrs: {
390
- to: S_WHATSAPP_NET,
391
- xmlns: 'w:sync:app:state',
392
- type: 'set'
393
- },
394
- content: [
395
- {
396
- tag: 'sync',
397
- attrs: {},
398
- content: nodes
399
- }
400
- ]
401
- });
402
- // extract from binary node
403
- const decoded = await extractSyncdPatches(result, config?.options);
404
- for (const key in decoded) {
405
- const name = key;
406
- const { patches, hasMorePatches, snapshot } = decoded[name];
407
- try {
408
- if (snapshot) {
409
- const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
410
- states[name] = newState;
411
- Object.assign(globalMutationMap, mutationMap);
412
- logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
413
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
414
- }
415
- // only process if there are syncd patches
416
- if (patches.length) {
417
- const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
418
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
419
- logger.info(`synced ${name} to v${newState.version}`);
420
- initialVersionMap[name] = newState.version;
421
- Object.assign(globalMutationMap, mutationMap);
422
- }
423
- if (hasMorePatches) {
424
- logger.info(`${name} has more patches...`);
425
- }
426
- else {
427
- // collection is done with sync
428
- collectionsToHandle.delete(name);
429
- }
430
- }
431
- catch (error) {
432
- // if retry attempts overshoot
433
- // or key not found
434
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
435
- error.output?.statusCode === 404 ||
436
- error.name === 'TypeError';
437
- logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
438
- await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
439
- // increment number of retries
440
- attemptsMap[name] = (attemptsMap[name] || 0) + 1;
441
- if (isIrrecoverableError) {
442
- // stop retrying
443
- collectionsToHandle.delete(name);
444
- }
445
- }
446
- }
447
- }
448
- }, authState?.creds?.me?.id || 'resync-app-state');
449
- const { onMutation } = newAppStateChunkHandler(isInitialSync);
450
- for (const key in globalMutationMap) {
451
- onMutation(globalMutationMap[key]);
452
- }
453
- });
454
- /**
455
- * fetch the profile picture of a user/group
456
- * type = "preview" for a low res picture
457
- * type = "image for the high res picture"
458
- */
459
- const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
460
- // TOOD: Add support for tctoken, existingID, and newsletter + group options
461
- jid = jidNormalizedUser(jid);
462
- const result = await query({
463
- tag: 'iq',
464
- attrs: {
465
- target: jid,
466
- to: S_WHATSAPP_NET,
467
- type: 'get',
468
- xmlns: 'w:profile:picture'
469
- },
470
- content: [{ tag: 'picture', attrs: { type, query: 'url' } }]
471
- }, timeoutMs);
472
- const child = getBinaryNodeChild(result, 'picture');
473
- return child?.attrs?.url;
474
- };
475
- const createCallLink = async (type, event, timeoutMs) => {
476
- const result = await query({
477
- tag: 'call',
478
- attrs: {
479
- id: generateMessageTag(),
480
- to: '@call'
481
- },
482
- content: [
483
- {
484
- tag: 'link_create',
485
- attrs: { media: type },
486
- content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
487
- }
488
- ]
489
- }, timeoutMs);
490
- const child = getBinaryNodeChild(result, 'link_create');
491
- return child?.attrs?.token;
492
- };
493
- const sendPresenceUpdate = async (type, toJid) => {
494
- const me = authState.creds.me;
495
- if (type === 'available' || type === 'unavailable') {
496
- if (!me.name) {
497
- logger.warn('no name present, ignoring presence update request...');
498
- return;
499
- }
500
- ev.emit('connection.update', { isOnline: type === 'available' });
501
- await sendNode({
502
- tag: 'presence',
503
- attrs: {
504
- name: me.name.replace(/@/g, ''),
505
- type
506
- }
507
- });
508
- }
509
- else {
510
- const { server } = jidDecode(toJid);
511
- const isLid = server === 'lid';
512
- await sendNode({
513
- tag: 'chatstate',
514
- attrs: {
515
- from: isLid ? me.lid : me.id,
516
- to: toJid
517
- },
518
- content: [
519
- {
520
- tag: type === 'recording' ? 'composing' : type,
521
- attrs: type === 'recording' ? { media: 'audio' } : {}
522
- }
523
- ]
524
- });
525
- }
526
- };
527
- /**
528
- * @param toJid the jid to subscribe to
529
- * @param tcToken token for subscription, use if present
530
- */
531
- const presenceSubscribe = (toJid, tcToken) => sendNode({
532
- tag: 'presence',
533
- attrs: {
534
- to: toJid,
535
- id: generateMessageTag(),
536
- type: 'subscribe'
537
- },
538
- content: tcToken
539
- ? [
540
- {
541
- tag: 'tctoken',
542
- attrs: {},
543
- content: tcToken
544
- }
545
- ]
546
- : undefined
547
- });
548
- const handlePresenceUpdate = ({ tag, attrs, content }) => {
549
- let presence;
550
- const jid = attrs.from;
551
- const participant = attrs.participant || attrs.from;
552
- if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
553
- return;
554
- }
555
- if (tag === 'presence') {
556
- presence = {
557
- lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
558
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
559
- };
560
- }
561
- else if (Array.isArray(content)) {
562
- const [firstChild] = content;
563
- let type = firstChild.tag;
564
- if (type === 'paused') {
565
- type = 'available';
566
- }
567
- if (firstChild.attrs?.media === 'audio') {
568
- type = 'recording';
569
- }
570
- presence = { lastKnownPresence: type };
571
- }
572
- else {
573
- logger.error({ tag, attrs, content }, 'recv invalid presence node');
574
- }
575
- if (presence) {
576
- ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
577
- }
578
- };
579
- const appPatch = async (patchCreate) => {
580
- const name = patchCreate.type;
581
- const myAppStateKeyId = authState.creds.myAppStateKeyId;
582
- if (!myAppStateKeyId) {
583
- throw new Boom('App state key not present!', { statusCode: 400 });
584
- }
585
- let initial;
586
- let encodeResult;
587
- await processingMutex.mutex(async () => {
588
- await authState.keys.transaction(async () => {
589
- logger.debug({ patch: patchCreate }, 'applying app patch');
590
- await resyncAppState([name], false);
591
- const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
592
- initial = currentSyncVersion || newLTHashState();
593
- encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
594
- const { patch, state } = encodeResult;
595
- const node = {
596
- tag: 'iq',
597
- attrs: {
598
- to: S_WHATSAPP_NET,
599
- type: 'set',
600
- xmlns: 'w:sync:app:state'
601
- },
602
- content: [
603
- {
604
- tag: 'sync',
605
- attrs: {},
606
- content: [
607
- {
608
- tag: 'collection',
609
- attrs: {
610
- name,
611
- version: (state.version - 1).toString(),
612
- return_snapshot: 'false'
613
- },
614
- content: [
615
- {
616
- tag: 'patch',
617
- attrs: {},
618
- content: proto.SyncdPatch.encode(patch).finish()
619
- }
620
- ]
621
- }
622
- ]
623
- }
624
- ]
625
- };
626
- await query(node);
627
- await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
628
- }, authState?.creds?.me?.id || 'app-patch');
629
- });
630
- if (config.emitOwnEvents) {
631
- const { onMutation } = newAppStateChunkHandler(false);
632
- const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
633
- for (const key in mutationMap) {
634
- onMutation(mutationMap[key]);
635
- }
636
- }
637
- };
638
- /** sending non-abt props may fix QR scan fail if server expects */
639
- const fetchProps = async () => {
640
- //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
641
- const resultNode = await query({
642
- tag: 'iq',
643
- attrs: {
644
- to: S_WHATSAPP_NET,
645
- xmlns: 'w',
646
- type: 'get'
647
- },
648
- content: [
649
- {
650
- tag: 'props',
651
- attrs: {
652
- protocol: '2',
653
- hash: authState?.creds?.lastPropHash || ''
654
- }
655
- }
656
- ]
657
- });
658
- const propsNode = getBinaryNodeChild(resultNode, 'props');
659
- let props = {};
660
- if (propsNode) {
661
- if (propsNode.attrs?.hash) {
662
- // on some clients, the hash is returning as undefined
663
- authState.creds.lastPropHash = propsNode?.attrs?.hash;
664
- ev.emit('creds.update', authState.creds);
665
- }
666
- props = reduceBinaryNodeToDictionary(propsNode, 'prop');
667
- }
668
- logger.debug('fetched props');
669
- return props;
670
- };
671
- /**
672
- * modify a chat -- mark unread, read etc.
673
- * lastMessages must be sorted in reverse chronologically
674
- * requires the last messages till the last message received; required for archive & unread
675
- */
676
- const chatModify = (mod, jid) => {
677
- const patch = chatModificationToAppPatch(mod, jid);
678
- return appPatch(patch);
679
- };
680
- /**
681
- * Enable/Disable link preview privacy, not related to baileys link preview generation
682
- */
683
- const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
684
- return chatModify({
685
- disableLinkPreviews: { isPreviewsDisabled }
686
- }, '');
687
- };
688
- /**
689
- * Star or Unstar a message
690
- */
691
- const star = (jid, messages, star) => {
692
- return chatModify({
693
- star: {
694
- messages,
695
- star
696
- }
697
- }, jid);
698
- };
699
- /**
700
- * Add or Edit Contact
701
- */
702
- const addOrEditContact = (jid, contact) => {
703
- return chatModify({
704
- contact
705
- }, jid);
706
- };
707
- /**
708
- * Remove Contact
709
- */
710
- const removeContact = (jid) => {
711
- return chatModify({
712
- contact: null
713
- }, jid);
714
- };
715
- /**
716
- * Adds label
717
- */
718
- const addLabel = (jid, labels) => {
719
- return chatModify({
720
- addLabel: {
721
- ...labels
722
- }
723
- }, jid);
724
- };
725
- /**
726
- * Adds label for the chats
727
- */
728
- const addChatLabel = (jid, labelId) => {
729
- return chatModify({
730
- addChatLabel: {
731
- labelId
732
- }
733
- }, jid);
734
- };
735
- /**
736
- * Removes label for the chat
737
- */
738
- const removeChatLabel = (jid, labelId) => {
739
- return chatModify({
740
- removeChatLabel: {
741
- labelId
742
- }
743
- }, jid);
744
- };
745
- /**
746
- * Adds label for the message
747
- */
748
- const addMessageLabel = (jid, messageId, labelId) => {
749
- return chatModify({
750
- addMessageLabel: {
751
- messageId,
752
- labelId
753
- }
754
- }, jid);
755
- };
756
- /**
757
- * Removes label for the message
758
- */
759
- const removeMessageLabel = (jid, messageId, labelId) => {
760
- return chatModify({
761
- removeMessageLabel: {
762
- messageId,
763
- labelId
764
- }
765
- }, jid);
766
- };
767
- /**
768
- * Add or Edit Quick Reply
769
- */
770
- const addOrEditQuickReply = (quickReply) => {
771
- return chatModify({
772
- quickReply
773
- }, '');
774
- };
775
- /**
776
- * Remove Quick Reply
777
- */
778
- const removeQuickReply = (timestamp) => {
779
- return chatModify({
780
- quickReply: { timestamp, deleted: true }
781
- }, '');
782
- };
783
- /**
784
- * queries need to be fired on connection open
785
- * help ensure parity with WA Web
786
- * */
787
- const executeInitQueries = async () => {
788
- await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
789
- };
790
- const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
791
- ev.emit('messages.upsert', { messages: [msg], type });
792
- if (!!msg.pushName) {
793
- let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
794
- jid = jidNormalizedUser(jid);
795
- if (!msg.key.fromMe) {
796
- ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
797
- }
798
- // update our pushname too
799
- if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
800
- ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
801
- }
802
- }
803
- const historyMsg = getHistoryMsg(msg.message);
804
- const shouldProcessHistoryMsg = historyMsg
805
- ? shouldSyncHistoryMessage(historyMsg) && PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
806
- : false;
807
- // State machine: decide on sync and flush
808
- if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
809
- if (awaitingSyncTimeout) {
810
- clearTimeout(awaitingSyncTimeout);
811
- awaitingSyncTimeout = undefined;
812
- }
813
- if (shouldProcessHistoryMsg) {
814
- syncState = SyncState.Syncing;
815
- logger.info('Transitioned to Syncing state');
816
- // Let doAppStateSync handle the final flush after it's done
817
- }
818
- else {
819
- syncState = SyncState.Online;
820
- logger.info('History sync skipped, transitioning to Online state and flushing buffer');
821
- ev.flush();
822
- }
823
- }
824
- const doAppStateSync = async () => {
825
- if (syncState === SyncState.Syncing) {
826
- logger.info('Doing app state sync');
827
- await resyncAppState(ALL_WA_PATCH_NAMES, true);
828
- // Sync is complete, go online and flush everything
829
- syncState = SyncState.Online;
830
- logger.info('App state sync complete, transitioning to Online state and flushing buffer');
831
- ev.flush();
832
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
833
- ev.emit('creds.update', { accountSyncCounter });
834
- }
835
- };
836
- await Promise.all([
837
- (async () => {
838
- if (shouldProcessHistoryMsg) {
839
- await doAppStateSync();
840
- }
841
- })(),
842
- processMessage(msg, {
843
- signalRepository,
844
- shouldProcessHistoryMsg,
845
- placeholderResendCache,
846
- ev,
847
- creds: authState.creds,
848
- keyStore: authState.keys,
849
- logger,
850
- options: config.options
851
- })
852
- ]);
853
- // If the app state key arrives and we are waiting to sync, trigger the sync now.
854
- if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
855
- logger.info('App state sync key arrived, triggering app state sync');
856
- await doAppStateSync();
857
- }
858
- });
859
- ws.on('CB:presence', handlePresenceUpdate);
860
- ws.on('CB:chatstate', handlePresenceUpdate);
861
- ws.on('CB:ib,,dirty', async (node) => {
862
- const { attrs } = getBinaryNodeChild(node, 'dirty');
863
- const type = attrs.type;
864
- switch (type) {
865
- case 'account_sync':
866
- if (attrs.timestamp) {
867
- let { lastAccountSyncTimestamp } = authState.creds;
868
- if (lastAccountSyncTimestamp) {
869
- await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
870
- }
871
- lastAccountSyncTimestamp = +attrs.timestamp;
872
- ev.emit('creds.update', { lastAccountSyncTimestamp });
873
- }
874
- break;
875
- case 'groups':
876
- // handled in groups.ts
877
- break;
878
- default:
879
- logger.info({ node }, 'received unknown sync');
880
- break;
881
- }
882
- });
883
- ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
884
- if (connection === 'open') {
885
- if (fireInitQueries) {
886
- executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
887
- }
888
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
889
- }
890
- if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
891
- return;
892
- }
893
- syncState = SyncState.AwaitingInitialSync;
894
- logger.info('Connection is now AwaitingInitialSync, buffering events');
895
- ev.buffer();
896
- const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
897
- syncType: proto.HistorySync.HistorySyncType.RECENT
898
- }));
899
- if (!willSyncHistory) {
900
- logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
901
- syncState = SyncState.Online;
902
- setTimeout(() => ev.flush(), 0);
903
- return;
904
- }
905
- logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
906
- if (awaitingSyncTimeout) {
907
- clearTimeout(awaitingSyncTimeout);
908
- }
909
- awaitingSyncTimeout = setTimeout(() => {
910
- if (syncState === SyncState.AwaitingInitialSync) {
911
- // TODO: investigate
912
- logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
913
- syncState = SyncState.Online;
914
- ev.flush();
915
- }
916
- }, 20000);
917
- });
918
- return {
919
- ...sock,
920
- createCallLink,
921
- getBotListV2,
922
- processingMutex,
923
- fetchPrivacySettings,
924
- upsertMessage,
925
- appPatch,
926
- sendPresenceUpdate,
927
- presenceSubscribe,
928
- profilePictureUrl,
929
- fetchBlocklist,
930
- fetchStatus,
931
- fetchDisappearingDuration,
932
- updateProfilePicture,
933
- removeProfilePicture,
934
- updateProfileStatus,
935
- updateProfileName,
936
- updateBlockStatus,
937
- updateDisableLinkPreviewsPrivacy,
938
- updateCallPrivacy,
939
- updateMessagesPrivacy,
940
- updateLastSeenPrivacy,
941
- updateOnlinePrivacy,
942
- updateProfilePicturePrivacy,
943
- updateStatusPrivacy,
944
- updateReadReceiptsPrivacy,
945
- updateGroupsAddPrivacy,
946
- updateDefaultDisappearingMode,
947
- getBusinessProfile,
948
- resyncAppState,
949
- chatModify,
950
- cleanDirtyBits,
951
- addOrEditContact,
952
- removeContact,
953
- addLabel,
954
- addChatLabel,
955
- removeChatLabel,
956
- addMessageLabel,
957
- removeMessageLabel,
958
- star,
959
- addOrEditQuickReply,
960
- removeQuickReply
961
- };
962
- };
963
- //# sourceMappingURL=chats.js.map
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, PROCESSABLE_HISTORY_TYPES, PHONENUMBER_MCC, MOBILE_TOKEN, MOBILE_USERAGENT, MOBILE_REGISTRATION_ENDPOINT } from '../Defaults/index.js'
5
+ import { ALL_WA_PATCH_NAMES } from '../Types/index.js'
6
+ import { SyncState } from '../Types/State.js'
7
+ import {
8
+ chatModificationToAppPatch,
9
+ decodePatches,
10
+ decodeSyncdSnapshot,
11
+ encodeSyncdPatch,
12
+ ensureLTHashStateVersion,
13
+ extractSyncdPatches,
14
+ generateProfilePicture,
15
+ getHistoryMsg,
16
+ newLTHashState,
17
+ processSyncAction
18
+ } from '../Utils/index.js'
19
+ import { makeMutex } from '../Utils/make-mutex.js'
20
+ import processMessage from '../Utils/process-message.js'
21
+ import {
22
+ getBinaryNodeChild,
23
+ getBinaryNodeChildren,
24
+ isLidUser,
25
+ jidDecode,
26
+ jidNormalizedUser,
27
+ reduceBinaryNodeToDictionary,
28
+ S_WHATSAPP_NET,
29
+ VIOLATION_TYPES
30
+ } from '../WABinary/index.js'
31
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js'
32
+ import { makeSocket } from './socket.js'
33
+
34
+ const MAX_SYNC_ATTEMPTS = 2
35
+ const HISTORY_SYNC_PAUSED_TIMEOUT_MS = 120_000
36
+ const APP_STATE_RESYNC_COOLDOWN_MS = 60_000
37
+
38
+ export const makeChatsSocket = (config) => {
39
+ const {
40
+ logger,
41
+ markOnlineOnConnect,
42
+ fireInitQueries,
43
+ appStateMacVerification,
44
+ shouldIgnoreJid,
45
+ shouldSyncHistoryMessage,
46
+ getMessage
47
+ } = config
48
+
49
+ const sock = makeSocket(config)
50
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError } = sock
51
+
52
+ let privacySettings
53
+ let syncState = SyncState.Connecting
54
+ let awaitingSyncTimeout
55
+ let historySyncPausedTimeout
56
+
57
+ const historySyncStatus = { initialBootstrapComplete: false, recentSyncComplete: false }
58
+ const blockedCollections = new Set()
59
+
60
+ const processingMutex = makeMutex()
61
+ const messageMutex = makeMutex()
62
+ const receiptMutex = makeMutex()
63
+ const appStatePatchMutex = makeMutex()
64
+ const notificationMutex = makeMutex()
65
+
66
+ const placeholderResendCache = config.placeholderResendCache || new NodeCache({
67
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
68
+ useClones: false
69
+ })
70
+ if (!config.placeholderResendCache) config.placeholderResendCache = placeholderResendCache
71
+
72
+ const profilePictureUrlCache = config.profilePictureUrlCache || new NodeCache({
73
+ stdTTL: DEFAULT_CACHE_TTLS.PROFILE_PIC,
74
+ useClones: false
75
+ })
76
+ if (!config.profilePictureUrlCache) config.profilePictureUrlCache = profilePictureUrlCache
77
+
78
+ const inFlightProfilePictureUrl = new Map()
79
+ const appStateResyncCooldown = new Map()
80
+
81
+ // ─── Key helpers ────────────────────────────────────────────────────────────
82
+
83
+ const getAppStateSyncKey = async (keyId) => {
84
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
85
+ return key
86
+ }
87
+
88
+
89
+ const interactiveQuery = async (userNodes, queryNode) => {
90
+ const result = await query({
91
+ tag: 'iq',
92
+ attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'usync' },
93
+ content: [{
94
+ tag: 'usync',
95
+ attrs: { sid: generateMessageTag(), mode: 'query', last: 'true', index: '0', context: 'interactive' },
96
+ content: [
97
+ { tag: 'query', attrs: {}, content: [queryNode] },
98
+ { tag: 'list', attrs: {}, content: userNodes }
99
+ ]
100
+ }]
101
+ })
102
+ const usyncNode = getBinaryNodeChild(result, 'usync')
103
+ const listNode = getBinaryNodeChild(usyncNode, 'list')
104
+ return getBinaryNodeChildren(listNode, 'user')
105
+ }
106
+
107
+ // ─── Privacy ─────────────────────────────────────────────────────────────────
108
+
109
+ const fetchPrivacySettings = async (force = false) => {
110
+ if (!privacySettings || force) {
111
+ const { content } = await query({
112
+ tag: 'iq',
113
+ attrs: { xmlns: 'privacy', to: S_WHATSAPP_NET, type: 'get' },
114
+ content: [{ tag: 'privacy', attrs: {} }]
115
+ })
116
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category')
117
+ }
118
+ return privacySettings
119
+ }
120
+
121
+ const privacyQuery = async (name, value) => {
122
+ await query({
123
+ tag: 'iq',
124
+ attrs: { xmlns: 'privacy', to: S_WHATSAPP_NET, type: 'set' },
125
+ content: [{ tag: 'privacy', attrs: {}, content: [{ tag: 'category', attrs: { name, value } }] }]
126
+ })
127
+ }
128
+
129
+ const updateMessagesPrivacy = (value) => privacyQuery('messages', value)
130
+ const updateCallPrivacy = (value) => privacyQuery('calladd', value)
131
+ const updateLastSeenPrivacy = (value) => privacyQuery('last', value)
132
+ const updateOnlinePrivacy = (value) => privacyQuery('online', value)
133
+ const updateProfilePicturePrivacy = (value) => privacyQuery('profile', value)
134
+ const updateStatusPrivacy = (value) => privacyQuery('status', value)
135
+ const updateReadReceiptsPrivacy = (value) => privacyQuery('readreceipts', value)
136
+ const updateGroupsAddPrivacy = (value) => privacyQuery('groupadd', value)
137
+
138
+ const updateDefaultDisappearingMode = async (duration) => {
139
+ await query({
140
+ tag: 'iq',
141
+ attrs: { xmlns: 'disappearing_mode', to: S_WHATSAPP_NET, type: 'set' },
142
+ content: [{ tag: 'disappearing_mode', attrs: { duration: duration.toString() } }]
143
+ })
144
+ }
145
+
146
+ // ─── Queries ─────────────────────────────────────────────────────────────────
147
+
148
+ const getBotListV2 = async () => {
149
+ const resp = await query({
150
+ tag: 'iq',
151
+ attrs: { xmlns: 'bot', to: S_WHATSAPP_NET, type: 'get' },
152
+ content: [{ tag: 'bot', attrs: { v: '2' } }]
153
+ })
154
+ const botNode = getBinaryNodeChild(resp, 'bot')
155
+ const botList = []
156
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
157
+ if (section.attrs.type === 'all') {
158
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
159
+ botList.push({ jid: bot.attrs.jid, personaId: bot.attrs['persona_id'] })
160
+ }
161
+ }
162
+ }
163
+ return botList
164
+ }
165
+
166
+ const fetchStatus = async (...jids) => {
167
+ const usyncQuery = new USyncQuery().withStatusProtocol()
168
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid))
169
+ const result = await sock.executeUSyncQuery(usyncQuery)
170
+ return result?.list
171
+ }
172
+
173
+ const fetchDisappearingDuration = async (...jids) => {
174
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol()
175
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid))
176
+ const result = await sock.executeUSyncQuery(usyncQuery)
177
+ return result?.list
178
+ }
179
+
180
+ const onWhatsApp = async (...jids) => {
181
+ const usyncQuery = new USyncQuery()
182
+ let contactEnabled = false
183
+
184
+ for (const jid of jids) {
185
+ if (isLidUser(jid)) {
186
+ logger.warn('LIDs not supported with onWhatsApp')
187
+ continue
188
+ }
189
+ if (!contactEnabled) {
190
+ contactEnabled = true
191
+ usyncQuery.withContactProtocol().withLIDProtocol()
192
+ }
193
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`
194
+ usyncQuery.withUser(new USyncUser().withPhone(phone))
195
+ }
196
+
197
+ if (usyncQuery.users.length === 0) return []
198
+
199
+ const results = await sock.executeUSyncQuery(usyncQuery)
200
+ if (!results) return []
201
+
202
+ return Promise.all(
203
+ results.list
204
+ .filter(a => a.contact === true)
205
+ .map(async ({ id, lid }) => {
206
+ try {
207
+ const businessProfile = await getBusinessProfile(id)
208
+ const isBusiness = businessProfile && Object.keys(businessProfile).length > 0
209
+ if (isBusiness) {
210
+ const { wid, ...businessInfo } = businessProfile
211
+ return { jid: id, exists: true, lid, status: 'business', businessInfo }
212
+ }
213
+ return { jid: id, exists: true, lid, status: 'regular' }
214
+ } catch (error) {
215
+ return { jid: id, exists: true, lid, status: 'error', error: error?.message }
216
+ }
217
+ })
218
+ )
219
+ }
220
+
221
+ // ─── Profile ─────────────────────────────────────────────────────────────────
222
+
223
+ const updateProfilePicture = async (jid, content) => {
224
+ if (!jid) throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
225
+ let targetJid
226
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) targetJid = jidNormalizedUser(jid)
227
+ const { img } = await generateProfilePicture(content)
228
+ await query({
229
+ tag: 'iq',
230
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:profile:picture', ...(targetJid ? { target: targetJid } : {}) },
231
+ content: [{ tag: 'picture', attrs: { type: 'image' }, content: img }]
232
+ })
233
+ }
234
+
235
+ const removeProfilePicture = async (jid) => {
236
+ if (!jid) throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
237
+ let targetJid
238
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) targetJid = jidNormalizedUser(jid)
239
+ await query({
240
+ tag: 'iq',
241
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:profile:picture', ...(targetJid ? { target: targetJid } : {}) }
242
+ })
243
+ }
244
+
245
+ const updateProfileStatus = async (status) => {
246
+ await query({
247
+ tag: 'iq',
248
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'status' },
249
+ content: [{ tag: 'status', attrs: {}, content: Buffer.from(status, 'utf-8') }]
250
+ })
251
+ }
252
+
253
+ const updateProfileName = (name) => chatModify({ pushNameSetting: name }, '')
254
+
255
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
256
+ jid = jidNormalizedUser(jid)
257
+ const cacheKey = `${jid}:${type}`
258
+ const cached = profilePictureUrlCache.get(cacheKey)
259
+ if (typeof cached !== 'undefined') return cached || undefined
260
+ const inFlight = inFlightProfilePictureUrl.get(cacheKey)
261
+ if (inFlight) return inFlight
262
+ const fetchPromise = (async () => {
263
+ const result = await query({
264
+ tag: 'iq',
265
+ attrs: { target: jid, to: S_WHATSAPP_NET, type: 'get', xmlns: 'w:profile:picture' },
266
+ content: [{ tag: 'picture', attrs: { type, query: 'url' } }]
267
+ }, timeoutMs)
268
+ const child = getBinaryNodeChild(result, 'picture')
269
+ const url = child?.attrs?.url
270
+ profilePictureUrlCache.set(cacheKey, url || null)
271
+ return url
272
+ })()
273
+ inFlightProfilePictureUrl.set(cacheKey, fetchPromise)
274
+ try {
275
+ return await fetchPromise
276
+ } finally {
277
+ inFlightProfilePictureUrl.delete(cacheKey)
278
+ }
279
+ }
280
+
281
+ // ─── Blocklist ────────────────────────────────────────────────────────────────
282
+
283
+ const fetchBlocklist = async () => {
284
+ const result = await query({ tag: 'iq', attrs: { xmlns: 'blocklist', to: S_WHATSAPP_NET, type: 'get' } })
285
+ const listNode = getBinaryNodeChild(result, 'list')
286
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid)
287
+ }
288
+
289
+ const updateBlockStatus = async (jid, action) => {
290
+ await query({
291
+ tag: 'iq',
292
+ attrs: { xmlns: 'blocklist', to: S_WHATSAPP_NET, type: 'set' },
293
+ content: [{ tag: 'item', attrs: { action, jid } }]
294
+ })
295
+ }
296
+
297
+ // ─── Business ────────────────────────────────────────────────────────────────
298
+
299
+ const getBusinessProfile = async (jid) => {
300
+ const results = await query({
301
+ tag: 'iq',
302
+ attrs: { to: 's.whatsapp.net', xmlns: 'w:biz', type: 'get' },
303
+ content: [{ tag: 'business_profile', attrs: { v: '244' }, content: [{ tag: 'profile', attrs: { jid } }] }]
304
+ })
305
+ const profileNode = getBinaryNodeChild(results, 'business_profile')
306
+ const profiles = getBinaryNodeChild(profileNode, 'profile')
307
+ if (profiles) {
308
+ const address = getBinaryNodeChild(profiles, 'address')
309
+ const description = getBinaryNodeChild(profiles, 'description')
310
+ const website = getBinaryNodeChild(profiles, 'website')
311
+ const email = getBinaryNodeChild(profiles, 'email')
312
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category')
313
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours')
314
+ const businessHoursConfig = businessHours ? getBinaryNodeChildren(businessHours, 'business_hours_config') : undefined
315
+ const websiteStr = website?.content?.toString()
316
+ return {
317
+ wid: profiles.attrs?.jid,
318
+ address: address?.content?.toString(),
319
+ description: description?.content?.toString() || '',
320
+ website: websiteStr ? [websiteStr] : [],
321
+ email: email?.content?.toString(),
322
+ category: category?.content?.toString(),
323
+ business_hours: { timezone: businessHours?.attrs?.timezone, business_config: businessHoursConfig?.map(({ attrs }) => attrs) }
324
+ }
325
+ }
326
+ }
327
+
328
+ // ─── App state ────────────────────────────────────────────────────────────────
329
+
330
+ const cleanDirtyBits = async (type, fromTimestamp) => {
331
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
332
+ await sendNode({
333
+ tag: 'iq',
334
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'urn:xmpp:whatsapp:dirty', id: generateMessageTag() },
335
+ content: [{ tag: 'clean', attrs: { type, ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null) } }]
336
+ })
337
+ }
338
+
339
+ const newAppStateChunkHandler = (isInitialSync) => ({
340
+ onMutation(mutation) {
341
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
342
+ }
343
+ })
344
+
345
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
346
+ const now = Date.now()
347
+ const collectionsToSync = collections.filter(name => (appStateResyncCooldown.get(name) || 0) <= now)
348
+ if (!collectionsToSync.length) return
349
+
350
+ // Per-invocation cache to avoid redundant key fetches within a single resync
351
+ const appStateSyncKeyCache = new Map()
352
+ const getCachedAppStateSyncKey = async (keyId) => {
353
+ if (appStateSyncKeyCache.has(keyId)) return appStateSyncKeyCache.get(keyId) ?? undefined
354
+ const key = await getAppStateSyncKey(keyId)
355
+ appStateSyncKeyCache.set(keyId, key ?? null)
356
+ return key
357
+ }
358
+
359
+ const initialVersionMap = {}
360
+ const globalMutationMap = {}
361
+
362
+ await authState.keys.transaction(async () => {
363
+ const collectionsToHandle = new Set(collectionsToSync)
364
+ const attemptsMap = {}
365
+ const forceSnapshotCollections = new Set()
366
+
367
+ while (collectionsToHandle.size) {
368
+ const states = {}
369
+ const nodes = []
370
+
371
+ for (const name of collectionsToHandle) {
372
+ const result = await authState.keys.get('app-state-sync-version', [name])
373
+ let state = result[name]
374
+ if (state) {
375
+ state = ensureLTHashStateVersion(state)
376
+ if (typeof initialVersionMap[name] === 'undefined') initialVersionMap[name] = state.version
377
+ } else {
378
+ state = newLTHashState()
379
+ }
380
+ states[name] = state
381
+
382
+ const shouldForceSnapshot = forceSnapshotCollections.has(name)
383
+ if (shouldForceSnapshot) forceSnapshotCollections.delete(name)
384
+
385
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`)
386
+ nodes.push({
387
+ tag: 'collection',
388
+ attrs: { name, version: state.version.toString(), return_snapshot: (shouldForceSnapshot || !state.version).toString() }
389
+ })
390
+ }
391
+
392
+ const result = await query({
393
+ tag: 'iq',
394
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w:sync:app:state', type: 'set' },
395
+ content: [{ tag: 'sync', attrs: {}, content: nodes }]
396
+ })
397
+
398
+ const decoded = await extractSyncdPatches(result, config?.options)
399
+ for (const key in decoded) {
400
+ const name = key
401
+ const { patches, hasMorePatches, snapshot } = decoded[name]
402
+ try {
403
+ if (snapshot) {
404
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger)
405
+ states[name] = newState
406
+ Object.assign(globalMutationMap, mutationMap)
407
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
408
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
409
+ }
410
+ if (patches.length) {
411
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch)
412
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
413
+ logger.info(`synced ${name} to v${newState.version}`)
414
+ initialVersionMap[name] = newState.version
415
+ Object.assign(globalMutationMap, mutationMap)
416
+ }
417
+ if (hasMorePatches) {
418
+ logger.info(`${name} has more patches...`)
419
+ } else {
420
+ collectionsToHandle.delete(name)
421
+ }
422
+ } catch (error) {
423
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1
424
+ const isMissingKey = error.output?.statusCode === 404
425
+ const isIrrecoverable = attemptsMap[name] >= MAX_SYNC_ATTEMPTS || error.name === 'TypeError'
426
+
427
+ logger.info({ name, error: error.stack, attempt: attemptsMap[name] }, `failed to sync ${name} from v${states[name].version}`)
428
+ if (!isMissingKey) {
429
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } })
430
+ }
431
+
432
+ if (isMissingKey) appStateResyncCooldown.set(name, Date.now() + APP_STATE_RESYNC_COOLDOWN_MS)
433
+
434
+ if (isMissingKey && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
435
+ logger.warn({ name }, `${name} blocked on missing key, parking until key arrives`)
436
+ blockedCollections.add(name)
437
+ collectionsToHandle.delete(name)
438
+ } else if (isMissingKey) {
439
+ forceSnapshotCollections.add(name)
440
+ } else if (isIrrecoverable) {
441
+ collectionsToHandle.delete(name)
442
+ } else {
443
+ forceSnapshotCollections.add(name)
444
+ }
445
+ }
446
+ }
447
+ }
448
+ }, authState?.creds?.me?.id || 'resync-app-state')
449
+
450
+ const { onMutation } = newAppStateChunkHandler(isInitialSync)
451
+ for (const key in globalMutationMap) onMutation(globalMutationMap[key])
452
+ })
453
+
454
+ // ─── Presence ─────────────────────────────────────────────────────────────────
455
+
456
+ const sendPresenceUpdate = async (type, toJid) => {
457
+ const me = authState.creds.me
458
+ if (type === 'available' || type === 'unavailable') {
459
+ if (!me.name) {
460
+ logger.warn('no name present, ignoring presence update request...')
461
+ return
462
+ }
463
+ ev.emit('connection.update', { isOnline: type === 'available' })
464
+ await sendNode({ tag: 'presence', attrs: { name: me.name.replace(/@/g, ''), type } })
465
+ } else {
466
+ const { server } = jidDecode(toJid)
467
+ const isLid = server === 'lid'
468
+ await sendNode({
469
+ tag: 'chatstate',
470
+ attrs: { from: isLid ? me.lid : me.id, to: toJid },
471
+ content: [{ tag: type === 'recording' ? 'composing' : type, attrs: type === 'recording' ? { media: 'audio' } : {} }]
472
+ })
473
+ }
474
+ }
475
+
476
+ const presenceSubscribe = (toJid, tcToken) => sendNode({
477
+ tag: 'presence',
478
+ attrs: { to: toJid, id: generateMessageTag(), type: 'subscribe' },
479
+ content: tcToken ? [{ tag: 'tctoken', attrs: {}, content: tcToken }] : undefined
480
+ })
481
+
482
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
483
+ let presence
484
+ const jid = attrs.from
485
+ const participant = attrs.participant || attrs.from
486
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) return
487
+ if (tag === 'presence') {
488
+ presence = {
489
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
490
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
491
+ }
492
+ } else if (Array.isArray(content)) {
493
+ const [firstChild] = content
494
+ let type = firstChild.tag
495
+ if (type === 'paused') type = 'available'
496
+ if (firstChild.attrs?.media === 'audio') type = 'recording'
497
+ presence = { lastKnownPresence: type }
498
+ } else {
499
+ logger.error({ tag, attrs, content }, 'recv invalid presence node')
500
+ }
501
+ if (presence) ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
502
+ }
503
+
504
+ // ─── App patch ────────────────────────────────────────────────────────────────
505
+
506
+ const appPatch = async (patchCreate) => {
507
+ const name = patchCreate.type
508
+ const myAppStateKeyId = authState.creds.myAppStateKeyId
509
+ if (!myAppStateKeyId) throw new Boom('App state key not present!', { statusCode: 400 })
510
+
511
+ let initial
512
+ let encodeResult
513
+
514
+ await appStatePatchMutex.mutex(async () => {
515
+ await authState.keys.transaction(async () => {
516
+ logger.debug({ patch: patchCreate }, 'applying app patch')
517
+ await resyncAppState([name], false)
518
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
519
+ initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState()
520
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
521
+ const { patch, state } = encodeResult
522
+ await query({
523
+ tag: 'iq',
524
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:sync:app:state' },
525
+ content: [{
526
+ tag: 'sync', attrs: {}, content: [{
527
+ tag: 'collection',
528
+ attrs: { name, version: (state.version - 1).toString(), return_snapshot: 'false' },
529
+ content: [{ tag: 'patch', attrs: {}, content: proto.SyncdPatch.encode(patch).finish() }]
530
+ }]
531
+ }]
532
+ })
533
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
534
+ }, authState?.creds?.me?.id || 'app-patch')
535
+ })
536
+
537
+ if (config.emitOwnEvents) {
538
+ const { onMutation } = newAppStateChunkHandler(false)
539
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger)
540
+ for (const key in mutationMap) onMutation(mutationMap[key])
541
+ }
542
+ }
543
+
544
+ // ─── Props ────────────────────────────────────────────────────────────────────
545
+
546
+ const fetchProps = async () => {
547
+ const resultNode = await query({
548
+ tag: 'iq',
549
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w', type: 'get' },
550
+ content: [{ tag: 'props', attrs: { protocol: '2', hash: authState?.creds?.lastPropHash || '' } }]
551
+ })
552
+ const propsNode = getBinaryNodeChild(resultNode, 'props')
553
+ let props = {}
554
+ if (propsNode) {
555
+ if (propsNode.attrs?.hash) {
556
+ authState.creds.lastPropHash = propsNode?.attrs?.hash
557
+ ev.emit('creds.update', authState.creds)
558
+ }
559
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop')
560
+ }
561
+ logger.debug('fetched props')
562
+ return props
563
+ }
564
+
565
+ // ─── Chat modification helpers ────────────────────────────────────────────────
566
+
567
+ const chatModify = (mod, jid) => appPatch(chatModificationToAppPatch(mod, jid))
568
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '')
569
+ const star = (jid, messages, star) => chatModify({ star: { messages, star } }, jid)
570
+ const addOrEditContact = (jid, contact) => chatModify({ contact }, jid)
571
+ const removeContact = (jid) => chatModify({ contact: null }, jid)
572
+ const addLabel = (jid, labels) => chatModify({ addLabel: { ...labels } }, jid)
573
+ const addChatLabel = (jid, labelId) => chatModify({ addChatLabel: { labelId } }, jid)
574
+ const removeChatLabel = (jid, labelId) => chatModify({ removeChatLabel: { labelId } }, jid)
575
+ const addMessageLabel = (jid, messageId, labelId) => chatModify({ addMessageLabel: { messageId, labelId } }, jid)
576
+ const removeMessageLabel = (jid, messageId, labelId) => chatModify({ removeMessageLabel: { messageId, labelId } }, jid)
577
+ const addOrEditQuickReply = (quickReply) => chatModify({ quickReply }, '')
578
+ const removeQuickReply = (timestamp) => chatModify({ quickReply: { timestamp, deleted: true } }, '')
579
+
580
+ // ─── Call link ────────────────────────────────────────────────────────────────
581
+
582
+ const createCallLink = async (type, event, timeoutMs) => {
583
+ const result = await query({
584
+ tag: 'call',
585
+ attrs: { id: generateMessageTag(), to: '@call' },
586
+ content: [{ tag: 'link_create', attrs: { media: type }, content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined }]
587
+ }, timeoutMs)
588
+ return getBinaryNodeChild(result, 'link_create')?.attrs?.token
589
+ }
590
+
591
+ // ─── Init ─────────────────────────────────────────────────────────────────────
592
+
593
+ const executeInitQueries = () => Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()])
594
+
595
+ // ─── Message upsert ───────────────────────────────────────────────────────────
596
+
597
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
598
+ ev.emit('messages.upsert', { messages: [msg], type })
599
+
600
+ if (msg.pushName) {
601
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid
602
+ jid = jidNormalizedUser(jid)
603
+ if (!msg.key.fromMe) {
604
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
605
+ }
606
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
607
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } })
608
+ }
609
+ }
610
+
611
+ const historyMsg = getHistoryMsg(msg.message)
612
+ const shouldProcessHistoryMsg = historyMsg
613
+ ? shouldSyncHistoryMessage(historyMsg) && PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
614
+ : false
615
+
616
+ // History sync progress tracking
617
+ if (historyMsg && shouldProcessHistoryMsg) {
618
+ const syncType = historyMsg.syncType
619
+
620
+ if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP && !historySyncStatus.initialBootstrapComplete) {
621
+ historySyncStatus.initialBootstrapComplete = true
622
+ ev.emit('messaging-history.status', { syncType, status: 'complete', explicit: true })
623
+ }
624
+
625
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && historyMsg.progress === 100 && !historySyncStatus.recentSyncComplete) {
626
+ historySyncStatus.recentSyncComplete = true
627
+ clearTimeout(historySyncPausedTimeout)
628
+ historySyncPausedTimeout = undefined
629
+ ev.emit('messaging-history.status', { syncType, status: 'complete', explicit: true })
630
+ }
631
+
632
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
633
+ clearTimeout(historySyncPausedTimeout)
634
+ historySyncPausedTimeout = setTimeout(() => {
635
+ if (!historySyncStatus.recentSyncComplete) {
636
+ historySyncStatus.recentSyncComplete = true
637
+ ev.emit('messaging-history.status', { syncType: proto.HistorySync.HistorySyncType.RECENT, status: 'paused', explicit: false })
638
+ }
639
+ historySyncPausedTimeout = undefined
640
+ }, HISTORY_SYNC_PAUSED_TIMEOUT_MS)
641
+ }
642
+ }
643
+
644
+ // SyncState machine
645
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
646
+ if (awaitingSyncTimeout) {
647
+ clearTimeout(awaitingSyncTimeout)
648
+ awaitingSyncTimeout = undefined
649
+ }
650
+ if (shouldProcessHistoryMsg) {
651
+ syncState = SyncState.Syncing
652
+ logger.info('Transitioned to Syncing state')
653
+ } else {
654
+ syncState = SyncState.Online
655
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer')
656
+ ev.flush()
657
+ }
658
+ }
659
+
660
+ const doAppStateSync = async () => {
661
+ if (syncState === SyncState.Syncing) {
662
+ blockedCollections.clear()
663
+ logger.info('Doing app state sync')
664
+ await resyncAppState(ALL_WA_PATCH_NAMES, true)
665
+ syncState = SyncState.Online
666
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer')
667
+ ev.flush()
668
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
669
+ ev.emit('creds.update', { accountSyncCounter })
670
+ }
671
+ }
672
+
673
+ await Promise.all([
674
+ (async () => { if (shouldProcessHistoryMsg) await doAppStateSync() })(),
675
+ processMessage(msg, {
676
+ signalRepository,
677
+ shouldProcessHistoryMsg,
678
+ placeholderResendCache,
679
+ ev,
680
+ creds: authState.creds,
681
+ keyStore: authState.keys,
682
+ logger,
683
+ options: config.options,
684
+ getMessage
685
+ })
686
+ ])
687
+
688
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare) {
689
+ if (blockedCollections.size > 0) {
690
+ const collections = [...blockedCollections]
691
+ blockedCollections.clear()
692
+ logger.info({ collections }, 'app state sync key arrived via protocol message, re-syncing blocked collections')
693
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync on key share'))
694
+ } else if (syncState === SyncState.Syncing) {
695
+ logger.info('App state sync key arrived, triggering app state sync')
696
+ await doAppStateSync()
697
+ }
698
+ }
699
+ })
700
+
701
+ // ─── WS handlers ──────────────────────────────────────────────────────────────
702
+
703
+ ws.on('CB:presence', handlePresenceUpdate)
704
+ ws.on('CB:chatstate', handlePresenceUpdate)
705
+
706
+ ws.on('CB:ib,,dirty', async (node) => {
707
+ const { attrs } = getBinaryNodeChild(node, 'dirty')
708
+ const type = attrs.type
709
+ switch (type) {
710
+ case 'account_sync':
711
+ if (attrs.timestamp) {
712
+ let { lastAccountSyncTimestamp } = authState.creds
713
+ if (lastAccountSyncTimestamp) await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
714
+ lastAccountSyncTimestamp = +attrs.timestamp
715
+ ev.emit('creds.update', { lastAccountSyncTimestamp })
716
+ }
717
+ break
718
+ case 'groups':
719
+ break
720
+ default:
721
+ logger.info({ node }, 'received unknown sync')
722
+ break
723
+ }
724
+ })
725
+
726
+ // ─── Event listeners ──────────────────────────────────────────────────────────
727
+
728
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
729
+ if (connection === 'close') {
730
+ blockedCollections.clear()
731
+ clearTimeout(historySyncPausedTimeout)
732
+ historySyncPausedTimeout = undefined
733
+ }
734
+
735
+ if (connection === 'open') {
736
+ if (fireInitQueries) executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'))
737
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'))
738
+ }
739
+
740
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) return
741
+
742
+ historySyncStatus.initialBootstrapComplete = false
743
+ historySyncStatus.recentSyncComplete = false
744
+ clearTimeout(historySyncPausedTimeout)
745
+ historySyncPausedTimeout = undefined
746
+
747
+ syncState = SyncState.AwaitingInitialSync
748
+ logger.info('Connection is now AwaitingInitialSync, buffering events')
749
+ ev.buffer()
750
+
751
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
752
+ syncType: proto.HistorySync.HistorySyncType.RECENT
753
+ }))
754
+
755
+ if (!willSyncHistory) {
756
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
757
+ syncState = SyncState.Online
758
+ setTimeout(() => ev.flush(), 0)
759
+ return
760
+ }
761
+
762
+ // On reconnection the server won't push history sync again — skip the wait
763
+ if (authState.creds.accountSyncCounter > 0) {
764
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.')
765
+ syncState = SyncState.Online
766
+ setTimeout(() => ev.flush(), 0)
767
+ return
768
+ }
769
+
770
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.')
771
+ if (awaitingSyncTimeout) clearTimeout(awaitingSyncTimeout)
772
+ awaitingSyncTimeout = setTimeout(() => {
773
+ if (syncState === SyncState.AwaitingInitialSync) {
774
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
775
+ syncState = SyncState.Online
776
+ ev.flush()
777
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
778
+ ev.emit('creds.update', { accountSyncCounter })
779
+ }
780
+ }, 20_000)
781
+ })
782
+
783
+ // Re-sync collections that were parked due to a missing app state key
784
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
785
+ if (!myAppStateKeyId || blockedCollections.size === 0) return
786
+ if (syncState === SyncState.Syncing) {
787
+ blockedCollections.clear()
788
+ return
789
+ }
790
+ const collections = [...blockedCollections]
791
+ blockedCollections.clear()
792
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections')
793
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'))
794
+ })
795
+
796
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
797
+ try {
798
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }])
799
+ } catch (error) {
800
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping')
801
+ }
802
+ })
803
+
804
+ // ─── Return ───────────────────────────────────────────────────────────────────
805
+
806
+ return {
807
+ ...sock,
808
+ createCallLink,
809
+ getBotListV2,
810
+ processingMutex,
811
+ messageMutex,
812
+ receiptMutex,
813
+ appStatePatchMutex,
814
+ notificationMutex,
815
+ fetchPrivacySettings,
816
+ upsertMessage,
817
+ appPatch,
818
+ sendPresenceUpdate,
819
+ presenceSubscribe,
820
+ profilePictureUrl,
821
+ fetchBlocklist,
822
+ fetchStatus,
823
+ fetchDisappearingDuration,
824
+ updateProfilePicture,
825
+ removeProfilePicture,
826
+ updateProfileStatus,
827
+ updateProfileName,
828
+ updateBlockStatus,
829
+ updateDisableLinkPreviewsPrivacy,
830
+ updateCallPrivacy,
831
+ updateMessagesPrivacy,
832
+ updateLastSeenPrivacy,
833
+ updateOnlinePrivacy,
834
+ updateProfilePicturePrivacy,
835
+ updateStatusPrivacy,
836
+ updateReadReceiptsPrivacy,
837
+ updateGroupsAddPrivacy,
838
+ updateDefaultDisappearingMode,
839
+ getBusinessProfile,
840
+ resyncAppState,
841
+ chatModify,
842
+ cleanDirtyBits,
843
+ addOrEditContact,
844
+ removeContact,
845
+ addLabel,
846
+ onWhatsApp,
847
+ checkStatusWA,
848
+ addChatLabel,
849
+ removeChatLabel,
850
+ addMessageLabel,
851
+ removeMessageLabel,
852
+ star,
853
+ addOrEditQuickReply,
854
+ removeQuickReply
855
+ }
856
+ }
857
+ export const checkStatusWA = async (phoneNumber) => {
858
+ if (!phoneNumber) throw new Error('Please provide a phone number')
859
+
860
+ const formattedNumber = (() => {
861
+ let num = phoneNumber
862
+ if (num.includes('@')) num = num.split('@')[0]
863
+ if (num.includes(':')) num = num.split(':')[0]
864
+ if (!num.startsWith('+')) num = '+' + num
865
+ return num
866
+ })()
867
+
868
+ const { parsePhoneNumberWithError } = await import('libphonenumber-js')
869
+ const { countryCallingCode: countryCode, nationalNumber } = parsePhoneNumberWithError(formattedNumber)
870
+ const { mobileRegisterExists, getBanDetails } = await import('./registration.js')
871
+ const { initAuthCreds } = await import('../Utils/index.js')
872
+
873
+ const state = {
874
+ creds: initAuthCreds(),
875
+ keys: {
876
+ get: async () => ({}),
877
+ set: async () => { },
878
+ transaction: async (fn) => fn(),
879
+ }
880
+ }
881
+
882
+ const build = (status, isBanned, isNeedOfficialWa, banInfo = null) => ({
883
+ number: formattedNumber, status, isBanned, isNeedOfficialWa, banInfo
884
+ })
885
+
886
+ try {
887
+ await mobileRegisterExists({
888
+ ...state.creds,
889
+ phoneNumberCountryCode: countryCode,
890
+ phoneNumberNationalNumber: nationalNumber,
891
+ })
892
+ return build('active', false, false)
893
+ } catch (err) {
894
+ if (err?.appeal_token) {
895
+ const banDetails = await getBanDetails(err.appeal_token)
896
+ const appealStatus = banDetails?.status || null
897
+ const banType = appealStatus === 'BANNED' ? 'permanent' : 'temporary'
898
+
899
+ return build('banned', true, false, {
900
+ banType,
901
+ violationType: err.violation_type || null,
902
+ violationReason: err.violation_type ? `Type ${err.violation_type}` : 'Unknown',
903
+ canAppeal: banType !== 'permanent', // ✅ temporary = can appeal, permanent = cannot
904
+ appealToken: err.appeal_token,
905
+ banTime: banDetails?.ban_time || null,
906
+ banDate: banDetails?.ban_time ? new Date(banDetails.ban_time * 1000).toISOString() : null,
907
+ appealStatus,
908
+ appealCreatedAt: banDetails?.appeal_creation_time ? new Date(banDetails.appeal_creation_time * 1000).toISOString() : null,
909
+ })
910
+ }
911
+ if (err?.custom_block_screen) return build('blocked', false, true)
912
+ if (err?.reason === 'incorrect') return build('active', false, false)
913
+ if (err?.reason === 'temporarily_unavailable') return build('rate_limited', false, false)
914
+ return build('error', false, false)
915
+ }
916
+ }