@sgintokic/baileys 0.0.2

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.

Potentially problematic release.


This version of @sgintokic/baileys might be problematic. Click here for more details.

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