@prototypevip/baileys 0.0.1

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