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