@fanzxnothuman/baileys 2.0.17

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