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