@nexustechpro/baileys 2.0.2 → 2.0.5

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