@vanzxy/baileys 1.4.1 → 1.4.3

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 @vanzxy/baileys might be problematic. Click here for more details.

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