@itsliaaa/baileys 0.1.0

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