keith-baileys 1.0.26

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