alisaaai-baileys 1.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 (104) hide show
  1. package/WAProto/WAProto.proto +5311 -0
  2. package/WAProto/index.js +94091 -0
  3. package/lib/Defaults/index.js +121 -0
  4. package/lib/KeyDB/BinarySearch.js +18 -0
  5. package/lib/KeyDB/KeyedDB.js +165 -0
  6. package/lib/KeyDB/index.js +2 -0
  7. package/lib/Signal/Group/ciphertext-message.js +11 -0
  8. package/lib/Signal/Group/group-session-builder.js +31 -0
  9. package/lib/Signal/Group/group_cipher.js +82 -0
  10. package/lib/Signal/Group/index.js +11 -0
  11. package/lib/Signal/Group/keyhelper.js +19 -0
  12. package/lib/Signal/Group/sender-chain-key.js +26 -0
  13. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  14. package/lib/Signal/Group/sender-key-message.js +66 -0
  15. package/lib/Signal/Group/sender-key-name.js +50 -0
  16. package/lib/Signal/Group/sender-key-record.js +41 -0
  17. package/lib/Signal/Group/sender-key-state.js +84 -0
  18. package/lib/Signal/Group/sender-message-key.js +26 -0
  19. package/lib/Signal/libsignal.js +322 -0
  20. package/lib/Signal/lid-mapping.js +153 -0
  21. package/lib/Socket/Client/index.js +3 -0
  22. package/lib/Socket/Client/types.js +12 -0
  23. package/lib/Socket/Client/websocket.js +51 -0
  24. package/lib/Socket/Client/websocket.js.bak +52 -0
  25. package/lib/Socket/business.js +376 -0
  26. package/lib/Socket/chats.js +880 -0
  27. package/lib/Socket/communities.js +412 -0
  28. package/lib/Socket/groups.js +311 -0
  29. package/lib/Socket/index.js +15 -0
  30. package/lib/Socket/messages-recv.js +1162 -0
  31. package/lib/Socket/messages-send.js +1160 -0
  32. package/lib/Socket/mex.js +44 -0
  33. package/lib/Socket/newsletter.js +248 -0
  34. package/lib/Socket/setup.js +465 -0
  35. package/lib/Socket/socket.js +778 -0
  36. package/lib/Store/index.js +5 -0
  37. package/lib/Store/make-cache-manager-store.js +74 -0
  38. package/lib/Store/make-in-memory-store.js +289 -0
  39. package/lib/Store/make-ordered-dictionary.js +78 -0
  40. package/lib/Store/object-repository.js +23 -0
  41. package/lib/Types/Auth.js +3 -0
  42. package/lib/Types/Bussines.js +1 -0
  43. package/lib/Types/Call.js +1 -0
  44. package/lib/Types/Chat.js +7 -0
  45. package/lib/Types/Contact.js +1 -0
  46. package/lib/Types/Events.js +1 -0
  47. package/lib/Types/GroupMetadata.js +1 -0
  48. package/lib/Types/Label.js +23 -0
  49. package/lib/Types/LabelAssociation.js +5 -0
  50. package/lib/Types/Message.js +10 -0
  51. package/lib/Types/Newsletter.js +31 -0
  52. package/lib/Types/Product.js +1 -0
  53. package/lib/Types/Signal.js +1 -0
  54. package/lib/Types/Socket.js +2 -0
  55. package/lib/Types/State.js +9 -0
  56. package/lib/Types/USync.js +1 -0
  57. package/lib/Types/index.js +26 -0
  58. package/lib/Utils/auth-utils.js +217 -0
  59. package/lib/Utils/baileys-event-stream.js +42 -0
  60. package/lib/Utils/browser-utils.js +23 -0
  61. package/lib/Utils/business.js +231 -0
  62. package/lib/Utils/chat-utils.js +750 -0
  63. package/lib/Utils/crypto.js +128 -0
  64. package/lib/Utils/decode-wa-message.js +265 -0
  65. package/lib/Utils/event-buffer.js +526 -0
  66. package/lib/Utils/generics.js +353 -0
  67. package/lib/Utils/history.js +85 -0
  68. package/lib/Utils/index.js +19 -0
  69. package/lib/Utils/link-preview.js +79 -0
  70. package/lib/Utils/logger.js +3 -0
  71. package/lib/Utils/lt-hash.js +44 -0
  72. package/lib/Utils/make-mutex.js +34 -0
  73. package/lib/Utils/message-retry-manager.js +111 -0
  74. package/lib/Utils/messages-media.js +740 -0
  75. package/lib/Utils/messages.js +893 -0
  76. package/lib/Utils/noise-handler.js +142 -0
  77. package/lib/Utils/pre-key-manager.js +83 -0
  78. package/lib/Utils/process-message.js +339 -0
  79. package/lib/Utils/signal.js +159 -0
  80. package/lib/Utils/use-multi-file-auth-state.js +109 -0
  81. package/lib/Utils/validate-connection.js +198 -0
  82. package/lib/WABinary/constants.js +1301 -0
  83. package/lib/WABinary/decode.js +238 -0
  84. package/lib/WABinary/encode.js +216 -0
  85. package/lib/WABinary/generic-utils.js +189 -0
  86. package/lib/WABinary/index.js +5 -0
  87. package/lib/WABinary/jid-utils.js +91 -0
  88. package/lib/WABinary/types.js +1 -0
  89. package/lib/WAM/BinaryInfo.js +9 -0
  90. package/lib/WAM/constants.js +22853 -0
  91. package/lib/WAM/encode.js +154 -0
  92. package/lib/WAM/index.js +5 -0
  93. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  94. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  95. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  96. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  97. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  98. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  99. package/lib/WAUSync/Protocols/index.js +6 -0
  100. package/lib/WAUSync/USyncQuery.js +90 -0
  101. package/lib/WAUSync/USyncUser.js +24 -0
  102. package/lib/WAUSync/index.js +5 -0
  103. package/lib/index.js +16 -0
  104. package/package.json +93 -0
@@ -0,0 +1,750 @@
1
+ import { getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from "../WABinary/index.js";
2
+ import { aesDecrypt, aesEncrypt, hkdf, hmacSign } from "./crypto.js";
3
+ import { LabelAssociationType } from "../Types/LabelAssociation.js";
4
+ import { downloadContentFromMessage } from "./messages-media.js";
5
+ import { LT_HASH_ANTI_TAMPERING } from "./lt-hash.js";
6
+ import { proto } from "../../WAProto/index.js";
7
+ import { toNumber } from "./generics.js";
8
+ import { Boom } from "@hapi/boom";
9
+
10
+ const mutationKeys = async (keydata) => {
11
+ const expanded = await hkdf(keydata, 160, { info: "WhatsApp Mutation Keys" });
12
+ return {
13
+ indexKey: expanded.slice(0, 32),
14
+ valueEncryptionKey: expanded.slice(32, 64),
15
+ valueMacKey: expanded.slice(64, 96),
16
+ snapshotMacKey: expanded.slice(96, 128),
17
+ patchMacKey: expanded.slice(128, 160)
18
+ };
19
+ };
20
+
21
+ const generateMac = (operation, data, keyId, key) => {
22
+ const getKeyData = () => {
23
+ let r;
24
+ switch (operation) {
25
+ case proto.SyncdMutation.SyncdOperation.SET:
26
+ r = 0x01;
27
+ break;
28
+ case proto.SyncdMutation.SyncdOperation.REMOVE:
29
+ r = 0x02;
30
+ break;
31
+ }
32
+ const buff = Buffer.from([r]);
33
+ return Buffer.concat([buff, Buffer.from(keyId, "base64")]);
34
+ };
35
+ const keyData = getKeyData();
36
+ const last = Buffer.alloc(8);
37
+ last.set([keyData.length], last.length - 1);
38
+ const total = Buffer.concat([keyData, data, last]);
39
+ const hmac = hmacSign(total, key, "sha512");
40
+ return hmac.slice(0, 32);
41
+ };
42
+
43
+ const to64BitNetworkOrder = (e) => {
44
+ const buff = Buffer.alloc(8);
45
+ buff.writeUint32BE(e, 4);
46
+ return buff;
47
+ };
48
+
49
+ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
50
+ indexValueMap = { ...indexValueMap };
51
+ const addBuffs = [];
52
+ const subBuffs = [];
53
+ return {
54
+ mix: ({ indexMac, valueMac, operation }) => {
55
+ const indexMacBase64 = Buffer.from(indexMac).toString("base64");
56
+ const prevOp = indexValueMap[indexMacBase64];
57
+ if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
58
+ if (!prevOp) {
59
+ throw new Boom("tried remove, but no previous op", { data: { indexMac, valueMac } });
60
+ }
61
+ delete indexValueMap[indexMacBase64];
62
+ }
63
+ else {
64
+ addBuffs.push(new Uint8Array(valueMac).buffer);
65
+ indexValueMap[indexMacBase64] = { valueMac };
66
+ }
67
+ if (prevOp) {
68
+ subBuffs.push(new Uint8Array(prevOp.valueMac).buffer);
69
+ }
70
+ },
71
+ finish: async () => {
72
+ const hashArrayBuffer = new Uint8Array(hash).buffer;
73
+ const result = await LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
74
+ const buffer = Buffer.from(result);
75
+ return {
76
+ hash: buffer,
77
+ indexValueMap
78
+ };
79
+ }
80
+ };
81
+ };
82
+
83
+ const generateSnapshotMac = (lthash, version, name, key) => {
84
+ const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, "utf-8")]);
85
+ return hmacSign(total, key, "sha256");
86
+ };
87
+
88
+ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
89
+ const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, "utf-8")]);
90
+ return hmacSign(total, key);
91
+ };
92
+
93
+ export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
94
+ export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
95
+ const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
96
+ if (!key) {
97
+ throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 });
98
+ }
99
+ const encKeyId = Buffer.from(myAppStateKeyId, "base64");
100
+ state = { ...state, indexValueMap: { ...state.indexValueMap } };
101
+ const indexBuffer = Buffer.from(JSON.stringify(index));
102
+ const dataProto = proto.SyncActionData.fromObject({
103
+ index: indexBuffer,
104
+ value: syncAction,
105
+ padding: new Uint8Array(0),
106
+ version: apiVersion
107
+ });
108
+ const encoded = proto.SyncActionData.encode(dataProto).finish();
109
+ const keyValue = await mutationKeys(key.keyData);
110
+ const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey);
111
+ const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
112
+ const indexMac = hmacSign(indexBuffer, keyValue.indexKey);
113
+ const generator = makeLtHashGenerator(state);
114
+ generator.mix({ indexMac, valueMac, operation });
115
+ Object.assign(state, await generator.finish());
116
+ state.version += 1;
117
+ const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
118
+ const patch = {
119
+ patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
120
+ snapshotMac: snapshotMac,
121
+ keyId: { id: encKeyId },
122
+ mutations: [
123
+ {
124
+ operation: operation,
125
+ record: {
126
+ index: {
127
+ blob: indexMac
128
+ },
129
+ value: {
130
+ blob: Buffer.concat([encValue, valueMac])
131
+ },
132
+ keyId: { id: encKeyId }
133
+ }
134
+ }
135
+ ]
136
+ };
137
+ const base64Index = indexMac.toString("base64");
138
+ state.indexValueMap[base64Index] = { valueMac };
139
+ return { patch, state };
140
+ };
141
+
142
+ export const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
143
+ const ltGenerator = makeLtHashGenerator(initialState);
144
+ for (const msgMutation of msgMutations) {
145
+ const operation = "operation" in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET;
146
+ const record = "record" in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
147
+ const key = await getKey(record.keyId.id);
148
+ const content = Buffer.from(record.value.blob);
149
+ const encContent = content.slice(0, -32);
150
+ const ogValueMac = content.slice(-32);
151
+ if (validateMacs) {
152
+ const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
153
+ if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
154
+ throw new Boom("HMAC content verification failed");
155
+ }
156
+ }
157
+ const result = aesDecrypt(encContent, key.valueEncryptionKey);
158
+ const syncAction = proto.SyncActionData.decode(result);
159
+ if (validateMacs) {
160
+ const hmac = hmacSign(syncAction.index, key.indexKey);
161
+ if (Buffer.compare(hmac, record.index.blob) !== 0) {
162
+ throw new Boom("HMAC index verification failed");
163
+ }
164
+ }
165
+ const indexStr = Buffer.from(syncAction.index).toString();
166
+ onMutation({ syncAction, index: JSON.parse(indexStr) });
167
+ ltGenerator.mix({
168
+ indexMac: record.index.blob,
169
+ valueMac: ogValueMac,
170
+ operation: operation
171
+ });
172
+ }
173
+ return await ltGenerator.finish();
174
+ async function getKey(keyId) {
175
+ const base64Key = Buffer.from(keyId).toString("base64");
176
+ const keyEnc = await getAppStateSyncKey(base64Key);
177
+ if (!keyEnc) {
178
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
179
+ statusCode: 404,
180
+ data: { msgMutations }
181
+ });
182
+ }
183
+ return mutationKeys(keyEnc.keyData);
184
+ }
185
+ };
186
+
187
+ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
188
+ if (validateMacs) {
189
+ const base64Key = Buffer.from(msg.keyId.id).toString("base64");
190
+ const mainKeyObj = await getAppStateSyncKey(base64Key);
191
+ if (!mainKeyObj) {
192
+ throw new Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
193
+ }
194
+ const mainKey = await mutationKeys(mainKeyObj.keyData);
195
+ const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
196
+ const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, toNumber(msg.version.version), name, mainKey.patchMacKey);
197
+ if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
198
+ throw new Boom("Invalid patch mac");
199
+ }
200
+ }
201
+ const result = await decodeSyncdMutations(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs);
202
+ return result;
203
+ };
204
+
205
+ export const extractSyncdPatches = async (result, options) => {
206
+ const syncNode = getBinaryNodeChild(result, "sync");
207
+ const collectionNodes = getBinaryNodeChildren(syncNode, "collection");
208
+ const final = {};
209
+ await Promise.all(collectionNodes.map(async (collectionNode) => {
210
+ const patchesNode = getBinaryNodeChild(collectionNode, "patches");
211
+ const patches = getBinaryNodeChildren(patchesNode || collectionNode, "patch");
212
+ const snapshotNode = getBinaryNodeChild(collectionNode, "snapshot");
213
+ const syncds = [];
214
+ const name = collectionNode.attrs.name;
215
+ const hasMorePatches = collectionNode.attrs.has_more_patches === "true";
216
+ let snapshot = undefined;
217
+ if (snapshotNode && !!snapshotNode.content) {
218
+ if (!Buffer.isBuffer(snapshotNode)) {
219
+ snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
220
+ }
221
+ const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content);
222
+ const data = await downloadExternalBlob(blobRef, options);
223
+ snapshot = proto.SyncdSnapshot.decode(data);
224
+ }
225
+ for (let { content } of patches) {
226
+ if (content) {
227
+ if (!Buffer.isBuffer(content)) {
228
+ content = Buffer.from(Object.values(content));
229
+ }
230
+ const syncd = proto.SyncdPatch.decode(content);
231
+ if (!syncd.version) {
232
+ syncd.version = { version: +collectionNode.attrs.version + 1 };
233
+ }
234
+ syncds.push(syncd);
235
+ }
236
+ }
237
+ final[name] = { patches: syncds, hasMorePatches, snapshot };
238
+ }));
239
+ return final;
240
+ };
241
+
242
+ export const downloadExternalBlob = async (blob, options) => {
243
+ const stream = await downloadContentFromMessage(blob, "md-app-state", { options });
244
+ const bufferArray = [];
245
+ for await (const chunk of stream) {
246
+ bufferArray.push(chunk);
247
+ }
248
+ return Buffer.concat(bufferArray);
249
+ };
250
+
251
+ export const downloadExternalPatch = async (blob, options) => {
252
+ const buffer = await downloadExternalBlob(blob, options);
253
+ const syncData = proto.SyncdMutations.decode(buffer);
254
+ return syncData;
255
+ };
256
+
257
+ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true) => {
258
+ const newState = newLTHashState();
259
+ newState.version = toNumber(snapshot.version.version);
260
+ const mutationMap = {};
261
+ const areMutationsRequired = typeof minimumVersionNumber === "undefined" || newState.version > minimumVersionNumber;
262
+ const { hash, indexValueMap } = await decodeSyncdMutations(snapshot.records, newState, getAppStateSyncKey, areMutationsRequired
263
+ ? mutation => {
264
+ const index = mutation.syncAction.index?.toString();
265
+ mutationMap[index] = mutation;
266
+ }
267
+ : () => { }, validateMacs);
268
+ newState.hash = hash;
269
+ newState.indexValueMap = indexValueMap;
270
+ if (validateMacs) {
271
+ const base64Key = Buffer.from(snapshot.keyId.id).toString("base64");
272
+ const keyEnc = await getAppStateSyncKey(base64Key);
273
+ if (!keyEnc) {
274
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
275
+ }
276
+ const result = await mutationKeys(keyEnc.keyData);
277
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
278
+ if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
279
+ throw new Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
280
+ }
281
+ }
282
+ return {
283
+ state: newState,
284
+ mutationMap
285
+ };
286
+ };
287
+
288
+ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
289
+ const newState = {
290
+ ...initial,
291
+ indexValueMap: { ...initial.indexValueMap }
292
+ };
293
+ const mutationMap = {};
294
+ for (const syncd of syncds) {
295
+ const { version, keyId, snapshotMac } = syncd;
296
+ if (syncd.externalMutations) {
297
+ logger?.trace({ name, version }, "downloading external patch");
298
+ const ref = await downloadExternalPatch(syncd.externalMutations, options);
299
+ logger?.debug({ name, version, mutations: ref.mutations.length }, "downloaded external patch");
300
+ syncd.mutations?.push(...ref.mutations);
301
+ }
302
+ const patchVersion = toNumber(version.version);
303
+ newState.version = patchVersion;
304
+ const shouldMutate = typeof minimumVersionNumber === "undefined" || patchVersion > minimumVersionNumber;
305
+ const decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, shouldMutate
306
+ ? mutation => {
307
+ const index = mutation.syncAction.index?.toString();
308
+ mutationMap[index] = mutation;
309
+ }
310
+ : () => { }, true);
311
+ newState.hash = decodeResult.hash;
312
+ newState.indexValueMap = decodeResult.indexValueMap;
313
+ if (validateMacs) {
314
+ const base64Key = Buffer.from(keyId.id).toString("base64");
315
+ const keyEnc = await getAppStateSyncKey(base64Key);
316
+ if (!keyEnc) {
317
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
318
+ }
319
+ const result = await mutationKeys(keyEnc.keyData);
320
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
321
+ if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
322
+ throw new Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
323
+ }
324
+ }
325
+ syncd.mutations = [];
326
+ }
327
+ return { state: newState, mutationMap };
328
+ };
329
+
330
+ export const chatModificationToAppPatch = (mod, jid) => {
331
+ const OP = proto.SyncdMutation.SyncdOperation;
332
+ const getMessageRange = (lastMessages) => {
333
+ let messageRange;
334
+ if (Array.isArray(lastMessages)) {
335
+ const lastMsg = lastMessages[lastMessages.length - 1];
336
+ messageRange = {
337
+ lastMessageTimestamp: lastMsg?.messageTimestamp,
338
+ messages: lastMessages?.length
339
+ ? lastMessages.map(m => {
340
+ if (!m.key?.id || !m.key?.remoteJid) {
341
+ throw new Boom("Incomplete key", { statusCode: 400, data: m });
342
+ }
343
+ if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
344
+ throw new Boom("Expected not from me message to have participant", { statusCode: 400, data: m });
345
+ }
346
+ if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
347
+ throw new Boom("Missing timestamp in last message list", { statusCode: 400, data: m });
348
+ }
349
+ if (m.key.participant) {
350
+ m.key.participant = jidNormalizedUser(m.key.participant);
351
+ }
352
+ return m;
353
+ })
354
+ : undefined
355
+ };
356
+ }
357
+ else {
358
+ messageRange = lastMessages;
359
+ }
360
+ return messageRange;
361
+ };
362
+ let patch;
363
+ if ("mute" in mod) {
364
+ patch = {
365
+ syncAction: {
366
+ muteAction: {
367
+ muted: !!mod.mute,
368
+ muteEndTimestamp: mod.mute || undefined
369
+ }
370
+ },
371
+ index: ["mute", jid],
372
+ type: "regular_high",
373
+ apiVersion: 2,
374
+ operation: OP.SET
375
+ };
376
+ }
377
+ else if ("archive" in mod) {
378
+ patch = {
379
+ syncAction: {
380
+ archiveChatAction: {
381
+ archived: !!mod.archive,
382
+ messageRange: getMessageRange(mod.lastMessages)
383
+ }
384
+ },
385
+ index: ["archive", jid],
386
+ type: "regular_low",
387
+ apiVersion: 3,
388
+ operation: OP.SET
389
+ };
390
+ }
391
+ else if ("markRead" in mod) {
392
+ patch = {
393
+ syncAction: {
394
+ markChatAsReadAction: {
395
+ read: mod.markRead,
396
+ messageRange: getMessageRange(mod.lastMessages)
397
+ }
398
+ },
399
+ index: ["markChatAsRead", jid],
400
+ type: "regular_low",
401
+ apiVersion: 3,
402
+ operation: OP.SET
403
+ };
404
+ }
405
+ else if ("deleteForMe" in mod) {
406
+ const { timestamp, key, deleteMedia } = mod.deleteForMe;
407
+ patch = {
408
+ syncAction: {
409
+ deleteMessageForMeAction: {
410
+ deleteMedia,
411
+ messageTimestamp: timestamp
412
+ }
413
+ },
414
+ index: ["deleteMessageForMe", jid, key.id, key.fromMe ? "1" : "0", "0"],
415
+ type: "regular_high",
416
+ apiVersion: 3,
417
+ operation: OP.SET
418
+ };
419
+ }
420
+ else if ("clear" in mod) {
421
+ patch = {
422
+ syncAction: {
423
+ clearChatAction: {
424
+ messageRange: getMessageRange(mod.lastMessages)
425
+ }
426
+ },
427
+ index: ["clearChat", jid, "1", "0"],
428
+ type: "regular_high",
429
+ apiVersion: 6,
430
+ operation: OP.SET
431
+ };
432
+ }
433
+ else if ("pin" in mod) {
434
+ patch = {
435
+ syncAction: {
436
+ pinAction: {
437
+ pinned: !!mod.pin
438
+ }
439
+ },
440
+ index: ["pin_v1", jid],
441
+ type: "regular_low",
442
+ apiVersion: 5,
443
+ operation: OP.SET
444
+ };
445
+ }
446
+ else if ("contact" in mod) {
447
+ patch = {
448
+ syncAction: {
449
+ contactAction: mod.contact || {}
450
+ },
451
+ index: ["contact", jid],
452
+ type: "critical_unblock_low",
453
+ apiVersion: 2,
454
+ operation: mod.contact ? OP.SET : OP.REMOVE
455
+ };
456
+ }
457
+ else if ("disableLinkPreviews" in mod) {
458
+ patch = {
459
+ syncAction: {
460
+ privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {}
461
+ },
462
+ index: ["setting_disableLinkPreviews"],
463
+ type: "regular",
464
+ apiVersion: 8,
465
+ operation: OP.SET
466
+ };
467
+ }
468
+ else if ("star" in mod) {
469
+ const key = mod.star.messages[0];
470
+ patch = {
471
+ syncAction: {
472
+ starAction: {
473
+ starred: !!mod.star.star
474
+ }
475
+ },
476
+ index: ["star", jid, key.id, key.fromMe ? "1" : "0", "0"],
477
+ type: "regular_low",
478
+ apiVersion: 2,
479
+ operation: OP.SET
480
+ };
481
+ }
482
+ else if ("delete" in mod) {
483
+ patch = {
484
+ syncAction: {
485
+ deleteChatAction: {
486
+ messageRange: getMessageRange(mod.lastMessages)
487
+ }
488
+ },
489
+ index: ["deleteChat", jid, "1"],
490
+ type: "regular_high",
491
+ apiVersion: 6,
492
+ operation: OP.SET
493
+ };
494
+ }
495
+ else if ("pushNameSetting" in mod) {
496
+ patch = {
497
+ syncAction: {
498
+ pushNameSetting: {
499
+ name: mod.pushNameSetting
500
+ }
501
+ },
502
+ index: ["setting_pushName"],
503
+ type: "critical_block",
504
+ apiVersion: 1,
505
+ operation: OP.SET
506
+ };
507
+ }
508
+ else if ("quickReply" in mod) {
509
+ patch = {
510
+ syncAction: {
511
+ quickReplyAction: {
512
+ count: 0,
513
+ deleted: mod.quickReply.deleted || false,
514
+ keywords: [],
515
+ message: mod.quickReply.message || "",
516
+ shortcut: mod.quickReply.shortcut || ""
517
+ }
518
+ },
519
+ index: ["quick_reply", mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
520
+ type: "regular",
521
+ apiVersion: 2,
522
+ operation: OP.SET
523
+ };
524
+ }
525
+ else if ("addLabel" in mod) {
526
+ patch = {
527
+ syncAction: {
528
+ labelEditAction: {
529
+ name: mod.addLabel.name,
530
+ color: mod.addLabel.color,
531
+ predefinedId: mod.addLabel.predefinedId,
532
+ deleted: mod.addLabel.deleted
533
+ }
534
+ },
535
+ index: ["label_edit", mod.addLabel.id],
536
+ type: "regular",
537
+ apiVersion: 3,
538
+ operation: OP.SET
539
+ };
540
+ }
541
+ else if ("addChatLabel" in mod) {
542
+ patch = {
543
+ syncAction: {
544
+ labelAssociationAction: {
545
+ labeled: true
546
+ }
547
+ },
548
+ index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
549
+ type: "regular",
550
+ apiVersion: 3,
551
+ operation: OP.SET
552
+ };
553
+ }
554
+ else if ("removeChatLabel" in mod) {
555
+ patch = {
556
+ syncAction: {
557
+ labelAssociationAction: {
558
+ labeled: false
559
+ }
560
+ },
561
+ index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
562
+ type: "regular",
563
+ apiVersion: 3,
564
+ operation: OP.SET
565
+ };
566
+ }
567
+ else if ("addMessageLabel" in mod) {
568
+ patch = {
569
+ syncAction: {
570
+ labelAssociationAction: {
571
+ labeled: true
572
+ }
573
+ },
574
+ index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, "0", "0"],
575
+ type: "regular",
576
+ apiVersion: 3,
577
+ operation: OP.SET
578
+ };
579
+ }
580
+ else if ("removeMessageLabel" in mod) {
581
+ patch = {
582
+ syncAction: {
583
+ labelAssociationAction: {
584
+ labeled: false
585
+ }
586
+ },
587
+ index: [
588
+ LabelAssociationType.Message,
589
+ mod.removeMessageLabel.labelId,
590
+ jid,
591
+ mod.removeMessageLabel.messageId,
592
+ "0",
593
+ "0"
594
+ ],
595
+ type: "regular",
596
+ apiVersion: 3,
597
+ operation: OP.SET
598
+ };
599
+ }
600
+ else {
601
+ throw new Boom("not supported");
602
+ }
603
+ patch.syncAction.timestamp = Date.now();
604
+ return patch;
605
+ };
606
+
607
+ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
608
+ const isInitialSync = !!initialSyncOpts;
609
+ const accountSettings = initialSyncOpts?.accountSettings;
610
+ logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, "processing sync action");
611
+ const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction;
612
+ if (action?.muteAction) {
613
+ ev.emit("chats.update", [
614
+ {
615
+ id,
616
+ muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
617
+ conditional: getChatUpdateConditional(id, undefined)
618
+ }
619
+ ]);
620
+ }
621
+ else if (action?.archiveChatAction || type === "archive" || type === "unarchive") {
622
+ const archiveAction = action?.archiveChatAction;
623
+ const isArchived = archiveAction ? archiveAction.archived : type === "archive";
624
+ const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange;
625
+ ev.emit("chats.update", [
626
+ {
627
+ id,
628
+ archived: isArchived,
629
+ conditional: getChatUpdateConditional(id, msgRange)
630
+ }
631
+ ]);
632
+ }
633
+ else if (action?.markChatAsReadAction) {
634
+ const markReadAction = action.markChatAsReadAction;
635
+ const isNullUpdate = isInitialSync && markReadAction.read;
636
+ ev.emit("chats.update", [
637
+ {
638
+ id,
639
+ unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
640
+ conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
641
+ }
642
+ ]);
643
+ }
644
+ else if (action?.deleteMessageForMeAction || type === "deleteMessageForMe") {
645
+ ev.emit("messages.delete", {
646
+ keys: [
647
+ {
648
+ remoteJid: id,
649
+ id: msgId,
650
+ fromMe: fromMe === "1"
651
+ }
652
+ ]
653
+ });
654
+ }
655
+ else if (action?.contactAction) {
656
+ ev.emit("contacts.upsert", [
657
+ {
658
+ id: id,
659
+ name: action.contactAction.fullName,
660
+ lid: action.contactAction.lidJid || undefined,
661
+ phoneNumber: action.contactAction.pnJid || undefined
662
+ }
663
+ ]);
664
+ }
665
+ else if (action?.pushNameSetting) {
666
+ const name = action?.pushNameSetting?.name;
667
+ if (name && me?.name !== name) {
668
+ ev.emit("creds.update", { me: { ...me, name } });
669
+ }
670
+ }
671
+ else if (action?.pinAction) {
672
+ ev.emit("chats.update", [
673
+ {
674
+ id,
675
+ pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
676
+ conditional: getChatUpdateConditional(id, undefined)
677
+ }
678
+ ]);
679
+ }
680
+ else if (action?.unarchiveChatsSetting) {
681
+ const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
682
+ ev.emit("creds.update", { accountSettings: { unarchiveChats } });
683
+ logger?.info(`archive setting updated => "${action.unarchiveChatsSetting.unarchiveChats}"`);
684
+ if (accountSettings) {
685
+ accountSettings.unarchiveChats = unarchiveChats;
686
+ }
687
+ }
688
+ else if (action?.starAction || type === "star") {
689
+ let starred = action?.starAction?.starred;
690
+ if (typeof starred !== "boolean") {
691
+ starred = syncAction.index[syncAction.index.length - 1] === "1";
692
+ }
693
+ ev.emit("messages.update", [
694
+ {
695
+ key: { remoteJid: id, id: msgId, fromMe: fromMe === "1" },
696
+ update: { starred }
697
+ }
698
+ ]);
699
+ }
700
+ else if (action?.deleteChatAction || type === "deleteChat") {
701
+ if (!isInitialSync) {
702
+ ev.emit("chats.delete", [id]);
703
+ }
704
+ }
705
+ else if (action?.labelEditAction) {
706
+ const { name, color, deleted, predefinedId } = action.labelEditAction;
707
+ ev.emit("labels.edit", {
708
+ id: id,
709
+ name: name,
710
+ color: color,
711
+ deleted: deleted,
712
+ predefinedId: predefinedId ? String(predefinedId) : undefined
713
+ });
714
+ }
715
+ else if (action?.labelAssociationAction) {
716
+ ev.emit("labels.association", {
717
+ type: action.labelAssociationAction.labeled ? "add" : "remove",
718
+ association: type === LabelAssociationType.Chat
719
+ ? {
720
+ type: LabelAssociationType.Chat,
721
+ chatId: syncAction.index[2],
722
+ labelId: syncAction.index[1]
723
+ }
724
+ : {
725
+ type: LabelAssociationType.Message,
726
+ chatId: syncAction.index[2],
727
+ messageId: syncAction.index[3],
728
+ labelId: syncAction.index[1]
729
+ }
730
+ });
731
+ }
732
+ else {
733
+ logger?.debug({ syncAction, id }, "unprocessable update");
734
+ }
735
+ function getChatUpdateConditional(id, msgRange) {
736
+ return isInitialSync
737
+ ? data => {
738
+ const chat = data.historySets.chats[id] || data.chatUpserts[id];
739
+ if (chat) {
740
+ return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
741
+ }
742
+ }
743
+ : undefined;
744
+ }
745
+ function isValidPatchBasedOnMessageRange(chat, msgRange) {
746
+ const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0);
747
+ const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0);
748
+ return lastMsgTimestamp >= chatLastMsgTimestamp;
749
+ }
750
+ };