@sgintokic/baileys 0.0.2

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.

Potentially problematic release.


This version of @sgintokic/baileys might be problematic. Click here for more details.

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