@gara31/void-baileys 7.0.0-rc.10

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