@badzz88/baileys 8.5.6 → 8.5.8

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 (225) hide show
  1. package/README.md +337 -1055
  2. package/WAProto/WAProto.proto +28 -1189
  3. package/WAProto/fix-imports.js +79 -69
  4. package/WAProto/index.d.ts +71491 -15254
  5. package/WAProto/index.js +126436 -19814
  6. package/engine-requirements.js +8 -15
  7. package/lib/Defaults/index.js +130 -0
  8. package/{src → lib}/Signal/Group/ciphertext-message.js +2 -5
  9. package/lib/Signal/Group/group-session-builder.js +30 -0
  10. package/{src → lib}/Signal/Group/group_cipher.js +11 -11
  11. package/lib/Signal/Group/index.js +12 -0
  12. package/lib/Signal/Group/keyhelper.js +18 -0
  13. package/{src → lib}/Signal/Group/sender-chain-key.js +6 -9
  14. package/{src → lib}/Signal/Group/sender-key-distribution-message.js +6 -9
  15. package/{src → lib}/Signal/Group/sender-key-message.js +9 -12
  16. package/{src → lib}/Signal/Group/sender-key-name.js +2 -5
  17. package/{src → lib}/Signal/Group/sender-key-record.js +8 -11
  18. package/{src → lib}/Signal/Group/sender-key-state.js +6 -9
  19. package/lib/Signal/Group/sender-message-key.js +26 -0
  20. package/{src → lib}/Signal/libsignal.js +131 -155
  21. package/{src → lib}/Signal/lid-mapping.js +27 -23
  22. package/lib/Socket/Client/index.js +3 -0
  23. package/lib/Socket/Client/types.js +11 -0
  24. package/{src → lib}/Socket/Client/websocket.js +11 -18
  25. package/{src → lib}/Socket/business.js +35 -67
  26. package/{src → lib}/Socket/chats.js +294 -550
  27. package/{src → lib}/Socket/communities.js +82 -114
  28. package/lib/Socket/graphql.js +716 -0
  29. package/lib/Socket/groups.js +374 -0
  30. package/lib/Socket/index.js +18 -0
  31. package/lib/Socket/interop.js +463 -0
  32. package/{src → lib}/Socket/luxu.js +120 -82
  33. package/lib/Socket/messages-recv.js +1916 -0
  34. package/lib/Socket/messages-send.js +1436 -0
  35. package/lib/Socket/mex.js +54 -0
  36. package/lib/Socket/newsletter.js +757 -0
  37. package/lib/Socket/privacy.js +318 -0
  38. package/{src → lib}/Socket/socket.js +356 -244
  39. package/lib/Socket/username.js +236 -0
  40. package/lib/Store/index.js +10 -0
  41. package/{src → lib}/Store/keyed-db.js +11 -21
  42. package/lib/Store/make-cache-manager-store.js +85 -0
  43. package/lib/Store/make-in-memory-store.js +244 -0
  44. package/{src → lib}/Store/make-ordered-dictionary.js +19 -25
  45. package/{src → lib}/Store/object-repository.js +11 -5
  46. package/lib/Types/Auth.js +2 -0
  47. package/lib/Types/Bussines.js +2 -0
  48. package/lib/Types/Call.js +2 -0
  49. package/lib/Types/Chat.js +8 -0
  50. package/lib/Types/Contact.js +2 -0
  51. package/lib/Types/Events.js +2 -0
  52. package/lib/Types/GroupMetadata.js +2 -0
  53. package/lib/Types/Label.js +25 -0
  54. package/lib/Types/LabelAssociation.js +7 -0
  55. package/lib/Types/Message.js +11 -0
  56. package/lib/Types/Mex.js +111 -0
  57. package/lib/Types/Product.js +2 -0
  58. package/lib/Types/Signal.js +2 -0
  59. package/lib/Types/Socket.js +3 -0
  60. package/lib/Types/State.js +56 -0
  61. package/lib/Types/USync.js +2 -0
  62. package/lib/Types/index.js +26 -0
  63. package/{src → lib}/Utils/auth-utils.js +91 -43
  64. package/lib/Utils/browser-utils.js +48 -0
  65. package/lib/Utils/business.js +231 -0
  66. package/lib/Utils/chat-utils.js +872 -0
  67. package/lib/Utils/companion-reg-client-utils.js +35 -0
  68. package/lib/Utils/crypto.js +118 -0
  69. package/lib/Utils/decode-wa-message.js +350 -0
  70. package/{src → lib}/Utils/event-buffer.js +81 -39
  71. package/lib/Utils/generics.js +403 -0
  72. package/lib/Utils/history.js +134 -0
  73. package/{src → lib}/Utils/identity-change-handler.js +9 -11
  74. package/lib/Utils/index.js +23 -0
  75. package/lib/Utils/link-preview.js +85 -0
  76. package/lib/Utils/logger.js +3 -0
  77. package/lib/Utils/lt-hash.js +8 -0
  78. package/{src → lib}/Utils/make-mutex.js +7 -10
  79. package/lib/Utils/message-composer.js +273 -0
  80. package/{src → lib}/Utils/message-retry-manager.js +76 -28
  81. package/lib/Utils/messages-media.js +870 -0
  82. package/lib/Utils/messages.js +1337 -0
  83. package/lib/Utils/noise-handler.js +201 -0
  84. package/{src → lib}/Utils/offline-node-processor.js +10 -4
  85. package/{src → lib}/Utils/pre-key-manager.js +27 -11
  86. package/lib/Utils/process-message.js +630 -0
  87. package/{src → lib}/Utils/reporting-utils.js +12 -15
  88. package/lib/Utils/signal.js +201 -0
  89. package/{src → lib}/Utils/stanza-ack.js +12 -4
  90. package/lib/Utils/sticker.js +110 -0
  91. package/{src → lib}/Utils/sync-action-utils.js +14 -10
  92. package/{src → lib}/Utils/tc-token-utils.js +48 -43
  93. package/{src → lib}/Utils/use-multi-file-auth-state.js +35 -25
  94. package/lib/Utils/validate-connection.js +203 -0
  95. package/{src → lib}/WABinary/constants.js +9 -12
  96. package/{src → lib}/WABinary/decode.js +38 -118
  97. package/{src → lib}/WABinary/encode.js +6 -11
  98. package/lib/WABinary/generic-utils.js +204 -0
  99. package/lib/WABinary/index.js +6 -0
  100. package/lib/WABinary/jid-utils.js +98 -0
  101. package/lib/WABinary/types.js +2 -0
  102. package/{src → lib}/WAM/BinaryInfo.js +2 -5
  103. package/{src → lib}/WAM/constants.js +4 -16635
  104. package/{src → lib}/WAM/encode.js +18 -17
  105. package/lib/WAM/index.js +4 -0
  106. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  107. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  108. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  109. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  110. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  111. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +58 -0
  112. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  113. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  114. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +28 -0
  115. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  116. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  117. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  118. package/lib/WAUSync/Protocols/index.js +12 -0
  119. package/lib/WAUSync/USyncQuery.js +151 -0
  120. package/lib/WAUSync/USyncUser.js +56 -0
  121. package/lib/WAUSync/index.js +3 -0
  122. package/{src → lib}/index.js +16 -51
  123. package/package.json +129 -99
  124. package/LICENSE +0 -21
  125. package/src/Defaults/index.js +0 -186
  126. package/src/Defaults/phonenumber-mcc.json +0 -223
  127. package/src/Signal/Group/group-session-builder.js +0 -86
  128. package/src/Signal/Group/index.js +0 -140
  129. package/src/Signal/Group/keyhelper.js +0 -77
  130. package/src/Signal/Group/sender-message-key.js +0 -29
  131. package/src/Socket/Client/index.js +0 -31
  132. package/src/Socket/Client/types.js +0 -13
  133. package/src/Socket/aigroups.js +0 -221
  134. package/src/Socket/graphql.js +0 -523
  135. package/src/Socket/groups.js +0 -516
  136. package/src/Socket/index.js +0 -31
  137. package/src/Socket/interactive-handler.js +0 -527
  138. package/src/Socket/interop.js +0 -339
  139. package/src/Socket/managed-account.js +0 -98
  140. package/src/Socket/messages-recv.js +0 -2685
  141. package/src/Socket/messages-send.js +0 -2047
  142. package/src/Socket/mex.js +0 -57
  143. package/src/Socket/newsletter.js +0 -455
  144. package/src/Socket/privacy.js +0 -125
  145. package/src/Socket/registration.js +0 -236
  146. package/src/Socket/text-router.js +0 -65
  147. package/src/Socket/username.js +0 -130
  148. package/src/Store/index.js +0 -33
  149. package/src/Store/make-cache-manager-store.js +0 -84
  150. package/src/Store/make-in-memory-store.js +0 -551
  151. package/src/Types/Auth.js +0 -31
  152. package/src/Types/Bussines.js +0 -2
  153. package/src/Types/Call.js +0 -2
  154. package/src/Types/Chat.js +0 -4
  155. package/src/Types/Contact.js +0 -2
  156. package/src/Types/Events.js +0 -2
  157. package/src/Types/GroupMetadata.js +0 -2
  158. package/src/Types/Label.js +0 -26
  159. package/src/Types/LabelAssociation.js +0 -8
  160. package/src/Types/Message.js +0 -93
  161. package/src/Types/Mex.js +0 -112
  162. package/src/Types/Newsletter.js +0 -109
  163. package/src/Types/Product.js +0 -2
  164. package/src/Types/Signal.js +0 -2
  165. package/src/Types/Socket.js +0 -2
  166. package/src/Types/State.js +0 -62
  167. package/src/Types/USync.js +0 -2
  168. package/src/Types/index.js +0 -56
  169. package/src/Utils/browser-utils.js +0 -112
  170. package/src/Utils/business.js +0 -240
  171. package/src/Utils/chat-utils.js +0 -1230
  172. package/src/Utils/command-loader.d.ts +0 -27
  173. package/src/Utils/command-loader.js +0 -89
  174. package/src/Utils/companion-reg-client-utils.js +0 -40
  175. package/src/Utils/consumer-application.js +0 -105
  176. package/src/Utils/crypto.js +0 -118
  177. package/src/Utils/curve25519-js.js +0 -242
  178. package/src/Utils/decode-wa-message.js +0 -529
  179. package/src/Utils/generics.js +0 -483
  180. package/src/Utils/group-history.js +0 -44
  181. package/src/Utils/history.js +0 -232
  182. package/src/Utils/index.js +0 -58
  183. package/src/Utils/jid-display-normalization.js +0 -195
  184. package/src/Utils/link-preview.js +0 -135
  185. package/src/Utils/logger.js +0 -8
  186. package/src/Utils/lt-hash.js +0 -25
  187. package/src/Utils/message-composer.js +0 -471
  188. package/src/Utils/messages-media.js +0 -843
  189. package/src/Utils/messages.js +0 -2817
  190. package/src/Utils/meta-ai-msmsg.js +0 -222
  191. package/src/Utils/native-bridge.js +0 -68
  192. package/src/Utils/noise-handler.js +0 -169
  193. package/src/Utils/process-message.js +0 -950
  194. package/src/Utils/session-pool.d.ts +0 -14
  195. package/src/Utils/session-pool.js +0 -70
  196. package/src/Utils/signal.js +0 -217
  197. package/src/Utils/sticker.d.ts +0 -13
  198. package/src/Utils/sticker.js +0 -123
  199. package/src/Utils/validate-connection.js +0 -209
  200. package/src/Utils/view-once-cache.d.ts +0 -12
  201. package/src/Utils/view-once-cache.js +0 -63
  202. package/src/Utils/voip-rekey.js +0 -22
  203. package/src/WABinary/generic-utils.js +0 -238
  204. package/src/WABinary/index.js +0 -34
  205. package/src/WABinary/jid-utils.js +0 -351
  206. package/src/WABinary/types.js +0 -2
  207. package/src/WAM/index.js +0 -32
  208. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -53
  209. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +0 -44
  210. package/src/WAUSync/Protocols/USyncContactProtocol.js +0 -55
  211. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +0 -55
  212. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -31
  213. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +0 -54
  214. package/src/WAUSync/Protocols/USyncLIDProtocol.js +0 -32
  215. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -473
  216. package/src/WAUSync/Protocols/USyncPictureProtocol.js +0 -34
  217. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
  218. package/src/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  219. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
  220. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +0 -28
  221. package/src/WAUSync/Protocols/index.js +0 -40
  222. package/src/WAUSync/USyncQuery.js +0 -126
  223. package/src/WAUSync/USyncUser.js +0 -50
  224. package/src/WAUSync/index.js +0 -32
  225. package/src/antiban.js +0 -4152
@@ -1,1230 +0,0 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', { value: true });
3
- exports.processSyncAction =
4
- exports.chatModificationToAppPatch =
5
- exports.decodePatches =
6
- exports.decodeSyncdSnapshot =
7
- exports.downloadExternalPatch =
8
- exports.downloadExternalBlob =
9
- exports.extractSyncdPatches =
10
- exports.decodeSyncdPatch =
11
- exports.decodeSyncdMutations =
12
- exports.encodeSyncdPatch =
13
- exports.newLTHashState =
14
- void 0;
15
- const boom_1 = require('@hapi/boom');
16
- const index_js_1 = require('../../WAProto/index.js');
17
- const LabelAssociation_1 = require('../Types/LabelAssociation');
18
- const WABinary_1 = require('../WABinary');
19
- const crypto_1 = require('./crypto');
20
- const generics_1 = require('./generics');
21
- const lt_hash_1 = require('./lt-hash');
22
- const messages_media_1 = require('./messages-media');
23
- const sync_action_utils_1 = require('./sync-action-utils');
24
- const mutationKeys = keydata => {
25
- const expanded = (0, crypto_1.hkdf)(keydata, 160, { info: 'WhatsApp Mutation Keys' });
26
- return {
27
- indexKey: expanded.subarray(0, 32),
28
- valueEncryptionKey: expanded.subarray(32, 64),
29
- valueMacKey: expanded.subarray(64, 96),
30
- snapshotMacKey: expanded.subarray(96, 128),
31
- patchMacKey: expanded.subarray(128, 160)
32
- };
33
- };
34
- const generateMac = (operation, data, keyId, key) => {
35
- const opByte = operation === index_js_1.proto.SyncdMutation.SyncdOperation.SET ? 0x01 : 0x02;
36
- const keyIdBuffer = typeof keyId === 'string' ? Buffer.from(keyId, 'base64') : keyId;
37
- const keyData = new Uint8Array(1 + keyIdBuffer.length);
38
- keyData[0] = opByte;
39
- keyData.set(keyIdBuffer, 1);
40
- const last = new Uint8Array(8);
41
- last[7] = keyData.length;
42
- const total = new Uint8Array(keyData.length + data.length + last.length);
43
- total.set(keyData, 0);
44
- total.set(data, keyData.length);
45
- total.set(last, keyData.length + data.length);
46
- const hmac = (0, crypto_1.hmacSign)(total, key, 'sha512');
47
- return hmac.subarray(0, 32);
48
- };
49
- const to64BitNetworkOrder = e => {
50
- const buff = Buffer.alloc(8);
51
- buff.writeUint32BE(e, 4);
52
- return buff;
53
- };
54
- const makeLtHashGenerator = ({ indexValueMap, hash }) => {
55
- indexValueMap = { ...indexValueMap };
56
- const addBuffs = [];
57
- const subBuffs = [];
58
- return {
59
- mix: ({ indexMac, valueMac, operation }) => {
60
- const indexMacBase64 = Buffer.from(indexMac).toString('base64');
61
- const prevOp = indexValueMap[indexMacBase64];
62
- if (operation === index_js_1.proto.SyncdMutation.SyncdOperation.REMOVE) {
63
- if (!prevOp) {
64
- throw new boom_1.Boom('tried remove, but no previous op', { data: { indexMac, valueMac } });
65
- }
66
- delete indexValueMap[indexMacBase64];
67
- }
68
- else {
69
- addBuffs.push(valueMac);
70
- indexValueMap[indexMacBase64] = { valueMac };
71
- }
72
- if (prevOp) {
73
- subBuffs.push(prevOp.valueMac);
74
- }
75
- },
76
- finish: () => {
77
- const result = lt_hash_1.LT_HASH_ANTI_TAMPERING.subtractThenAdd(hash, subBuffs, addBuffs);
78
- return {
79
- hash: Buffer.from(result),
80
- indexValueMap
81
- };
82
- }
83
- };
84
- };
85
- const generateSnapshotMac = (lthash, version, name, key) => {
86
- const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]);
87
- return (0, crypto_1.hmacSign)(total, key, 'sha256');
88
- };
89
- const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
90
- const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]);
91
- return (0, crypto_1.hmacSign)(total, key);
92
- };
93
- const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
94
- exports.newLTHashState = newLTHashState;
95
- exports.makeLtHashGenerator = makeLtHashGenerator;
96
- const ensureLTHashStateVersion = state => {
97
- if (typeof state.version !== 'number' || isNaN(state.version)) {
98
- state.version = 0;
99
- }
100
- return state;
101
- };
102
- exports.ensureLTHashStateVersion = ensureLTHashStateVersion;
103
- exports.MAX_SYNC_ATTEMPTS = 2;
104
- const isMissingKeyError = error => {
105
- return error?.data?.isMissingKey === true;
106
- };
107
- exports.isMissingKeyError = isMissingKeyError;
108
- const isAppStateSyncIrrecoverable = (error, attempts) => {
109
- return attempts >= exports.MAX_SYNC_ATTEMPTS || error?.name === 'TypeError';
110
- };
111
- exports.isAppStateSyncIrrecoverable = isAppStateSyncIrrecoverable;
112
- const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
113
- const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
114
- if (!key) {
115
- throw new boom_1.Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 });
116
- }
117
- const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
118
- state = { ...state, indexValueMap: { ...state.indexValueMap } };
119
- const indexBuffer = Buffer.from(JSON.stringify(index));
120
- const dataProto = index_js_1.proto.SyncActionData.fromObject({
121
- index: indexBuffer,
122
- value: syncAction,
123
- padding: new Uint8Array(0),
124
- version: apiVersion
125
- });
126
- const encoded = index_js_1.proto.SyncActionData.encode(dataProto).finish();
127
- const keyValue = mutationKeys(key.keyData);
128
- const encValue = (0, crypto_1.aesEncrypt)(encoded, keyValue.valueEncryptionKey);
129
- const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
130
- const indexMac = (0, crypto_1.hmacSign)(indexBuffer, keyValue.indexKey);
131
- const generator = makeLtHashGenerator(state);
132
- generator.mix({ indexMac, valueMac, operation });
133
- Object.assign(state, generator.finish());
134
- state.version += 1;
135
- const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
136
- const patch = {
137
- patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
138
- snapshotMac: snapshotMac,
139
- keyId: { id: encKeyId },
140
- mutations: [
141
- {
142
- operation: operation,
143
- record: {
144
- index: {
145
- blob: indexMac
146
- },
147
- value: {
148
- blob: Buffer.concat([encValue, valueMac])
149
- },
150
- keyId: { id: encKeyId }
151
- }
152
- }
153
- ]
154
- };
155
- const base64Index = indexMac.toString('base64');
156
- state.indexValueMap[base64Index] = { valueMac };
157
- return { patch, state };
158
- };
159
- exports.encodeSyncdPatch = encodeSyncdPatch;
160
- const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
161
- const ltGenerator = makeLtHashGenerator(initialState);
162
- const derivedKeyCache = new Map();
163
- for (const msgMutation of msgMutations) {
164
- const operation = 'operation' in msgMutation ? msgMutation.operation : index_js_1.proto.SyncdMutation.SyncdOperation.SET;
165
- const record = 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
166
- const key = await getKey(record.keyId.id);
167
- const content = record.value.blob;
168
- const encContent = content.subarray(0, -32);
169
- const ogValueMac = content.subarray(-32);
170
- if (validateMacs) {
171
- const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
172
- if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
173
- throw new boom_1.Boom('HMAC content verification failed');
174
- }
175
- }
176
- const result = (0, crypto_1.aesDecrypt)(encContent, key.valueEncryptionKey);
177
- const syncAction = index_js_1.proto.SyncActionData.decode(result);
178
- if (validateMacs) {
179
- const hmac = (0, crypto_1.hmacSign)(syncAction.index, key.indexKey);
180
- if (Buffer.compare(hmac, record.index.blob) !== 0) {
181
- throw new boom_1.Boom('HMAC index verification failed');
182
- }
183
- }
184
- const indexStr = Buffer.from(syncAction.index).toString();
185
- onMutation({ syncAction, index: JSON.parse(indexStr) });
186
- ltGenerator.mix({
187
- indexMac: record.index.blob,
188
- valueMac: ogValueMac,
189
- operation: operation
190
- });
191
- }
192
- return ltGenerator.finish();
193
- async function getKey(keyId) {
194
- const base64Key = Buffer.from(keyId).toString('base64');
195
- const cached = derivedKeyCache.get(base64Key);
196
- if (cached) {
197
- return cached;
198
- }
199
- const keyEnc = await getAppStateSyncKey(base64Key);
200
- if (!keyEnc) {
201
- throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`, {
202
- statusCode: 404,
203
- data: { msgMutations }
204
- });
205
- }
206
- const keys = mutationKeys(keyEnc.keyData);
207
- derivedKeyCache.set(base64Key, keys);
208
- return keys;
209
- }
210
- };
211
- exports.decodeSyncdMutations = decodeSyncdMutations;
212
- const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
213
- if (validateMacs) {
214
- const base64Key = Buffer.from(msg.keyId.id).toString('base64');
215
- const mainKeyObj = await getAppStateSyncKey(base64Key);
216
- if (!mainKeyObj) {
217
- throw new boom_1.Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
218
- }
219
- const mainKey = mutationKeys(mainKeyObj.keyData);
220
- const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
221
- const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, (0, generics_1.toNumber)(msg.version.version), name, mainKey.patchMacKey);
222
- if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
223
- throw new boom_1.Boom('Invalid patch mac');
224
- }
225
- }
226
- const result = await (0, exports.decodeSyncdMutations)(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs);
227
- return result;
228
- };
229
- exports.decodeSyncdPatch = decodeSyncdPatch;
230
- const extractSyncdPatches = async (result, options) => {
231
- const syncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'sync');
232
- const collectionNodes = (0, WABinary_1.getBinaryNodeChildren)(syncNode, 'collection');
233
- const final = {};
234
- await Promise.all(collectionNodes.map(async (collectionNode) => {
235
- const patchesNode = (0, WABinary_1.getBinaryNodeChild)(collectionNode, 'patches');
236
- const patches = (0, WABinary_1.getBinaryNodeChildren)(patchesNode || collectionNode, 'patch');
237
- const snapshotNode = (0, WABinary_1.getBinaryNodeChild)(collectionNode, 'snapshot');
238
- const syncds = [];
239
- const name = collectionNode.attrs.name;
240
- const hasMorePatches = collectionNode.attrs.has_more_patches === 'true';
241
- let snapshot = undefined;
242
- if (snapshotNode && !!snapshotNode.content) {
243
- if (!Buffer.isBuffer(snapshotNode)) {
244
- snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
245
- }
246
- const blobRef = index_js_1.proto.ExternalBlobReference.decode(snapshotNode.content);
247
- const data = await (0, exports.downloadExternalBlob)(blobRef, options);
248
- snapshot = index_js_1.proto.SyncdSnapshot.decode(data);
249
- }
250
- for (let { content } of patches) {
251
- if (content) {
252
- if (!Buffer.isBuffer(content)) {
253
- content = Buffer.from(Object.values(content));
254
- }
255
- const syncd = index_js_1.proto.SyncdPatch.decode(content);
256
- if (!syncd.version) {
257
- syncd.version = { version: +collectionNode.attrs.version + 1 };
258
- }
259
- syncds.push(syncd);
260
- }
261
- }
262
- final[name] = { patches: syncds, hasMorePatches, snapshot };
263
- }));
264
- return final;
265
- };
266
- exports.extractSyncdPatches = extractSyncdPatches;
267
- const downloadExternalBlob = async (blob, options) => {
268
- const stream = await (0, messages_media_1.downloadContentFromMessage)(blob, 'md-app-state', { options });
269
- const bufferArray = [];
270
- for await (const chunk of stream) {
271
- bufferArray.push(chunk);
272
- }
273
- return Buffer.concat(bufferArray);
274
- };
275
- exports.downloadExternalBlob = downloadExternalBlob;
276
- const downloadExternalPatch = async (blob, options) => {
277
- const buffer = await (0, exports.downloadExternalBlob)(blob, options);
278
- const syncData = index_js_1.proto.SyncdMutations.decode(buffer);
279
- return syncData;
280
- };
281
- exports.downloadExternalPatch = downloadExternalPatch;
282
- const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true) => {
283
- const newState = (0, exports.newLTHashState)();
284
- newState.version = (0, generics_1.toNumber)(snapshot.version.version);
285
- const mutationMap = {};
286
- const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber;
287
- const { hash, indexValueMap } = await (0, exports.decodeSyncdMutations)(snapshot.records, newState, getAppStateSyncKey, areMutationsRequired
288
- ? mutation => {
289
- const index = mutation.syncAction.index?.toString();
290
- mutationMap[index] = mutation;
291
- }
292
- : () => { }, validateMacs);
293
- newState.hash = hash;
294
- newState.indexValueMap = indexValueMap;
295
- if (validateMacs) {
296
- const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
297
- const keyEnc = await getAppStateSyncKey(base64Key);
298
- if (!keyEnc) {
299
- throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
300
- }
301
- const result = mutationKeys(keyEnc.keyData);
302
- const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
303
- if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
304
- throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
305
- }
306
- }
307
- return {
308
- state: newState,
309
- mutationMap
310
- };
311
- };
312
- exports.decodeSyncdSnapshot = decodeSyncdSnapshot;
313
- const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
314
- const newState = {
315
- ...initial,
316
- indexValueMap: { ...initial.indexValueMap }
317
- };
318
- const mutationMap = {};
319
- for (const syncd of syncds) {
320
- const { version, keyId, snapshotMac } = syncd;
321
- if (syncd.externalMutations) {
322
- logger?.trace({ name, version }, 'downloading external patch');
323
- const ref = await (0, exports.downloadExternalPatch)(syncd.externalMutations, options);
324
- logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch');
325
- syncd.mutations?.push(...ref.mutations);
326
- }
327
- const patchVersion = (0, generics_1.toNumber)(version.version);
328
- newState.version = patchVersion;
329
- const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
330
- const decodeResult = await (0, exports.decodeSyncdPatch)(syncd, name, newState, getAppStateSyncKey, shouldMutate
331
- ? mutation => {
332
- const index = mutation.syncAction.index?.toString();
333
- mutationMap[index] = mutation;
334
- }
335
- : () => { }, true);
336
- newState.hash = decodeResult.hash;
337
- newState.indexValueMap = decodeResult.indexValueMap;
338
- if (validateMacs) {
339
- const base64Key = Buffer.from(keyId.id).toString('base64');
340
- const keyEnc = await getAppStateSyncKey(base64Key);
341
- if (!keyEnc) {
342
- throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
343
- }
344
- const result = mutationKeys(keyEnc.keyData);
345
- const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
346
- if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
347
- throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
348
- }
349
- }
350
- syncd.mutations = [];
351
- }
352
- return { state: newState, mutationMap };
353
- };
354
- exports.decodePatches = decodePatches;
355
- const chatModificationToAppPatch = (mod, jid) => {
356
- const OP = index_js_1.proto.SyncdMutation.SyncdOperation;
357
- const getMessageRange = lastMessages => {
358
- let messageRange;
359
- if (Array.isArray(lastMessages)) {
360
- const lastMsg = lastMessages[lastMessages.length - 1];
361
- messageRange = {
362
- lastMessageTimestamp: lastMsg?.messageTimestamp,
363
- messages: lastMessages?.length
364
- ? lastMessages.map(m => {
365
- if (!m.key?.id || !m.key?.remoteJid) {
366
- throw new boom_1.Boom('Incomplete key', { statusCode: 400, data: m });
367
- }
368
- if ((0, WABinary_1.isJidGroup)(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
369
- throw new boom_1.Boom('Expected not from me message to have participant', { statusCode: 400, data: m });
370
- }
371
- if (!m.messageTimestamp || !(0, generics_1.toNumber)(m.messageTimestamp)) {
372
- throw new boom_1.Boom('Missing timestamp in last message list', { statusCode: 400, data: m });
373
- }
374
- if (m.key.participant) {
375
- m.key.participant = (0, WABinary_1.jidNormalizedUser)(m.key.participant);
376
- }
377
- return m;
378
- })
379
- : undefined
380
- };
381
- }
382
- else {
383
- messageRange = lastMessages;
384
- }
385
- return messageRange;
386
- };
387
- let patch;
388
- if ('mute' in mod) {
389
- patch = {
390
- syncAction: {
391
- muteAction: {
392
- muted: !!mod.mute,
393
- muteEndTimestamp: mod.mute || undefined
394
- }
395
- },
396
- index: ['mute', jid],
397
- type: 'regular_high',
398
- apiVersion: 2,
399
- operation: OP.SET
400
- };
401
- }
402
- else if ('archive' in mod) {
403
- patch = {
404
- syncAction: {
405
- archiveChatAction: {
406
- archived: !!mod.archive,
407
- messageRange: getMessageRange(mod.lastMessages)
408
- }
409
- },
410
- index: ['archive', jid],
411
- type: 'regular_low',
412
- apiVersion: 3,
413
- operation: OP.SET
414
- };
415
- }
416
- else if ('markRead' in mod) {
417
- patch = {
418
- syncAction: {
419
- markChatAsReadAction: {
420
- read: mod.markRead,
421
- messageRange: getMessageRange(mod.lastMessages)
422
- }
423
- },
424
- index: ['markChatAsRead', jid],
425
- type: 'regular_low',
426
- apiVersion: 3,
427
- operation: OP.SET
428
- };
429
- }
430
- else if ('deleteForMe' in mod) {
431
- const { timestamp, key, deleteMedia } = mod.deleteForMe;
432
- patch = {
433
- syncAction: {
434
- deleteMessageForMeAction: {
435
- deleteMedia,
436
- messageTimestamp: timestamp
437
- }
438
- },
439
- index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
440
- type: 'regular_high',
441
- apiVersion: 3,
442
- operation: OP.SET
443
- };
444
- }
445
- else if ('clear' in mod) {
446
- patch = {
447
- syncAction: {
448
- clearChatAction: {
449
- messageRange: getMessageRange(mod.lastMessages)
450
- }
451
- },
452
- index: ['clearChat', jid, '1', '0'],
453
- type: 'regular_high',
454
- apiVersion: 6,
455
- operation: OP.SET
456
- };
457
- }
458
- else if ('pin' in mod) {
459
- patch = {
460
- syncAction: {
461
- pinAction: {
462
- pinned: !!mod.pin
463
- }
464
- },
465
- index: ['pin_v1', jid],
466
- type: 'regular_low',
467
- apiVersion: 5,
468
- operation: OP.SET
469
- };
470
- }
471
- else if ('contact' in mod) {
472
- patch = {
473
- syncAction: {
474
- contactAction: mod.contact || {}
475
- },
476
- index: ['contact', jid],
477
- type: 'critical_unblock_low',
478
- apiVersion: 2,
479
- operation: mod.contact ? OP.SET : OP.REMOVE
480
- };
481
- }
482
- else if ('disableLinkPreviews' in mod) {
483
- patch = {
484
- syncAction: {
485
- privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {}
486
- },
487
- index: ['setting_disableLinkPreviews'],
488
- type: 'regular',
489
- apiVersion: 8,
490
- operation: OP.SET
491
- };
492
- }
493
- else if ('star' in mod) {
494
- const key = mod.star.messages[0];
495
- patch = {
496
- syncAction: {
497
- starAction: {
498
- starred: !!mod.star.star
499
- }
500
- },
501
- index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
502
- type: 'regular_low',
503
- apiVersion: 2,
504
- operation: OP.SET
505
- };
506
- }
507
- else if ('delete' in mod) {
508
- patch = {
509
- syncAction: {
510
- deleteChatAction: {
511
- messageRange: getMessageRange(mod.lastMessages)
512
- }
513
- },
514
- index: ['deleteChat', jid, '1'],
515
- type: 'regular_high',
516
- apiVersion: 6,
517
- operation: OP.SET
518
- };
519
- }
520
- else if ('pushNameSetting' in mod) {
521
- patch = {
522
- syncAction: {
523
- pushNameSetting: {
524
- name: mod.pushNameSetting
525
- }
526
- },
527
- index: ['setting_pushName'],
528
- type: 'critical_block',
529
- apiVersion: 1,
530
- operation: OP.SET
531
- };
532
- }
533
- else if ('quickReply' in mod) {
534
- patch = {
535
- syncAction: {
536
- quickReplyAction: {
537
- count: 0,
538
- deleted: mod.quickReply.deleted || false,
539
- keywords: [],
540
- message: mod.quickReply.message || '',
541
- shortcut: mod.quickReply.shortcut || ''
542
- }
543
- },
544
- index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
545
- type: 'regular',
546
- apiVersion: 2,
547
- operation: OP.SET
548
- };
549
- }
550
- else if ('addLabel' in mod) {
551
- patch = {
552
- syncAction: {
553
- labelEditAction: {
554
- name: mod.addLabel.name,
555
- color: mod.addLabel.color,
556
- predefinedId: mod.addLabel.predefinedId,
557
- deleted: mod.addLabel.deleted
558
- }
559
- },
560
- index: ['label_edit', mod.addLabel.id],
561
- type: 'regular',
562
- apiVersion: 3,
563
- operation: OP.SET
564
- };
565
- }
566
- else if ('addChatLabel' in mod) {
567
- patch = {
568
- syncAction: {
569
- labelAssociationAction: {
570
- labeled: true
571
- }
572
- },
573
- index: [LabelAssociation_1.LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
574
- type: 'regular',
575
- apiVersion: 3,
576
- operation: OP.SET
577
- };
578
- }
579
- else if ('removeChatLabel' in mod) {
580
- patch = {
581
- syncAction: {
582
- labelAssociationAction: {
583
- labeled: false
584
- }
585
- },
586
- index: [LabelAssociation_1.LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
587
- type: 'regular',
588
- apiVersion: 3,
589
- operation: OP.SET
590
- };
591
- }
592
- else if ('addMessageLabel' in mod) {
593
- patch = {
594
- syncAction: {
595
- labelAssociationAction: {
596
- labeled: true
597
- }
598
- },
599
- index: [
600
- LabelAssociation_1.LabelAssociationType.Message,
601
- mod.addMessageLabel.labelId,
602
- jid,
603
- mod.addMessageLabel.messageId,
604
- '0',
605
- '0'
606
- ],
607
- type: 'regular',
608
- apiVersion: 3,
609
- operation: OP.SET
610
- };
611
- }
612
- else if ('removeMessageLabel' in mod) {
613
- patch = {
614
- syncAction: {
615
- labelAssociationAction: {
616
- labeled: false
617
- }
618
- },
619
- index: [
620
- LabelAssociation_1.LabelAssociationType.Message,
621
- mod.removeMessageLabel.labelId,
622
- jid,
623
- mod.removeMessageLabel.messageId,
624
- '0',
625
- '0'
626
- ],
627
- type: 'regular',
628
- apiVersion: 3,
629
- operation: OP.SET
630
- };
631
- }
632
- else if ('markAsUnread' in mod) {
633
- patch = {
634
- syncAction: {
635
- markChatAsReadAction: {
636
- read: false,
637
- messageRange: getMessageRange(mod.lastMessages)
638
- }
639
- },
640
- index: ['markChatAsRead', jid],
641
- type: 'regular_low',
642
- apiVersion: 3,
643
- operation: OP.SET
644
- };
645
- }
646
- else if ('setChatEphemeral' in mod) {
647
- const duration = typeof mod.setChatEphemeral === 'number' ? mod.setChatEphemeral : (mod.setChatEphemeral?.duration ?? 0);
648
- patch = {
649
- syncAction: {
650
- chatEphemeralAction: {
651
- ephemeralExpiration: duration,
652
- ephemeralSettingTimestamp: Date.now()
653
- }
654
- },
655
- index: ['ephemeral', jid],
656
- type: 'regular',
657
- apiVersion: 1,
658
- operation: OP.SET
659
- };
660
- }
661
- else if ('silenceChat' in mod) {
662
- patch = {
663
- syncAction: {
664
- muteAction: {
665
- muted: mod.silenceChat.silent !== false,
666
- muteEndTimestamp: mod.silenceChat.until ?? null
667
- }
668
- },
669
- index: ['mute', jid],
670
- type: 'regular_high',
671
- apiVersion: 2,
672
- operation: OP.SET
673
- };
674
- }
675
- else if ('muteStatus' in mod) {
676
- patch = {
677
- syncAction: {
678
- userStatusMuteAction: { muted: mod.muteStatus.muted !== false }
679
- },
680
- index: ['user_status_mute', jid],
681
- type: 'regular',
682
- apiVersion: 1,
683
- operation: OP.SET
684
- };
685
- }
686
- else if ('favorite' in mod) {
687
- patch = {
688
- syncAction: {
689
- favoritesAction: { isFavorite: !!mod.favorite.isFavorite }
690
- },
691
- index: ['favorites', jid],
692
- type: 'regular',
693
- apiVersion: 1,
694
- operation: OP.SET
695
- };
696
- }
697
- else if ('reorderLabel' in mod) {
698
- patch = {
699
- syncAction: {
700
- labelReorderingAction: { sortedLabelIds: mod.reorderLabel.sortedLabelIds || [] }
701
- },
702
- index: ['label_reordering'],
703
- type: 'regular',
704
- apiVersion: 1,
705
- operation: OP.SET
706
- };
707
- }
708
- else if ('deleteCallLog' in mod) {
709
- patch = {
710
- syncAction: {
711
- deleteIndividualCallLog: { callId: mod.deleteCallLog.callId || mod.deleteCallLog }
712
- },
713
- index: ['delete_call_log', jid],
714
- type: 'regular',
715
- apiVersion: 1,
716
- operation: OP.SET
717
- };
718
- }
719
- else if ('noteEdit' in mod) {
720
- patch = {
721
- syncAction: {
722
- noteEditAction: { note: mod.noteEdit.note || mod.noteEdit, deleted: mod.noteEdit.deleted ?? false }
723
- },
724
- index: ['note_edit', jid],
725
- type: 'regular',
726
- apiVersion: 1,
727
- operation: OP.SET
728
- };
729
- }
730
- else if ('aiThreadRename' in mod) {
731
- patch = {
732
- syncAction: {
733
- aiThreadRenameAction: {
734
- newTitle: mod.aiThreadRename.title || mod.aiThreadRename
735
- }
736
- },
737
- index: ['ai_thread_rename', jid],
738
- type: 'regular_high',
739
- apiVersion: 1,
740
- operation: OP.SET
741
- };
742
- }
743
- else if ('threadPin' in mod) {
744
- patch = {
745
- syncAction: {
746
- threadPinAction: {
747
- pinned: !!mod.threadPin.pinned
748
- }
749
- },
750
- index: ['thread_pin', jid, mod.threadPin.messageId || ''],
751
- type: 'regular_low',
752
- apiVersion: 1,
753
- operation: OP.SET
754
- };
755
- }
756
- else if ('chatLock' in mod) {
757
- patch = {
758
- syncAction: {
759
- lockChatAction: {
760
- locked: mod.chatLock.locked !== false
761
- }
762
- },
763
- index: ['lock_chat', jid],
764
- type: 'regular_high',
765
- apiVersion: 1,
766
- operation: OP.SET
767
- };
768
- }
769
- else if ('wallpaper' in mod) {
770
- const wallpaperData = mod.wallpaper || {};
771
- patch = {
772
- syncAction: {
773
- chatCustomImageWallpaper: wallpaperData.remove
774
- ? {}
775
- : {
776
- directPath: wallpaperData.directPath,
777
- mediaKey: wallpaperData.mediaKey,
778
- fileEncSha256: wallpaperData.fileEncSha256,
779
- fileSha256: wallpaperData.fileSha256,
780
- dimLevel: wallpaperData.dimLevel ?? 0
781
- }
782
- },
783
- index: ['chat_custom_image_wallpaper', jid],
784
- type: 'regular',
785
- apiVersion: 1,
786
- operation: wallpaperData.remove ? OP.REMOVE : OP.SET
787
- };
788
- }
789
- else if ('mediaVisibility' in mod) {
790
- const visibilityEnum = index_js_1.proto.MediaVisibility;
791
- const visMap = { default: visibilityEnum.DEFAULT, off: visibilityEnum.OFF, on: visibilityEnum.ON };
792
- const visibility = typeof mod.mediaVisibility === 'string'
793
- ? (visMap[mod.mediaVisibility.toLowerCase()] ?? visibilityEnum.DEFAULT)
794
- : (mod.mediaVisibility ?? visibilityEnum.DEFAULT);
795
- patch = {
796
- syncAction: {
797
- mediaVisibilityAction: { visibility }
798
- },
799
- index: ['media_visibility', jid],
800
- type: 'regular',
801
- apiVersion: 1,
802
- operation: OP.SET
803
- };
804
- }
805
- else if ('privateProcessingSetting' in mod) {
806
- const statusEnum = index_js_1.proto.SyncActionValue.PrivateProcessingSettingAction.PrivateProcessingStatus;
807
- const statusMap = { enabled: statusEnum.ENABLED, disabled: statusEnum.DISABLED };
808
- const status = typeof mod.privateProcessingSetting === 'string'
809
- ? (statusMap[mod.privateProcessingSetting.toLowerCase()] ?? statusEnum.ENABLED)
810
- : (mod.privateProcessingSetting.status ??
811
- (mod.privateProcessingSetting.enabled ? statusEnum.ENABLED : statusEnum.DISABLED));
812
- patch = {
813
- syncAction: {
814
- privateProcessingSettingAction: { privateProcessingStatus: status }
815
- },
816
- index: ['setting_private_processing'],
817
- type: 'regular',
818
- apiVersion: 1,
819
- operation: OP.SET
820
- };
821
- }
822
- else {
823
- throw new boom_1.Boom('not supported');
824
- }
825
- patch.syncAction.timestamp = Date.now();
826
- return patch;
827
- };
828
- exports.chatModificationToAppPatch = chatModificationToAppPatch;
829
- const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
830
- const isInitialSync = !!initialSyncOpts;
831
- const accountSettings = initialSyncOpts?.accountSettings;
832
- logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action');
833
- const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction;
834
- if (action?.muteAction) {
835
- ev.emit('chats.update', [
836
- {
837
- id,
838
- muteEndTime: action.muteAction?.muted ? (0, generics_1.toNumber)(action.muteAction.muteEndTimestamp) : null,
839
- conditional: getChatUpdateConditional(id, undefined)
840
- }
841
- ]);
842
- }
843
- else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
844
- const archiveAction = action?.archiveChatAction;
845
- const isArchived = archiveAction ? archiveAction.archived : type === 'archive';
846
- const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange;
847
- ev.emit('chats.update', [
848
- {
849
- id,
850
- archived: isArchived,
851
- conditional: getChatUpdateConditional(id, msgRange)
852
- }
853
- ]);
854
- }
855
- else if (action?.markChatAsReadAction) {
856
- const markReadAction = action.markChatAsReadAction;
857
- const isNullUpdate = isInitialSync && markReadAction.read;
858
- ev.emit('chats.update', [
859
- {
860
- id,
861
- unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
862
- conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
863
- }
864
- ]);
865
- }
866
- else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
867
- ev.emit('messages.delete', {
868
- keys: [
869
- {
870
- remoteJid: id,
871
- id: msgId,
872
- fromMe: fromMe === '1'
873
- }
874
- ]
875
- });
876
- }
877
- else if (action?.contactAction) {
878
- const results = (0, sync_action_utils_1.processContactAction)(action.contactAction, id, logger);
879
- (0, sync_action_utils_1.emitSyncActionResults)(ev, results);
880
- }
881
- else if (action?.pushNameSetting) {
882
- const name = action?.pushNameSetting?.name;
883
- if (name && me?.name !== name) {
884
- ev.emit('creds.update', { me: { ...me, name } });
885
- }
886
- }
887
- else if (action?.pinAction) {
888
- ev.emit('chats.update', [
889
- {
890
- id,
891
- pinned: action.pinAction?.pinned ? (0, generics_1.toNumber)(action.timestamp) : null,
892
- conditional: getChatUpdateConditional(id, undefined)
893
- }
894
- ]);
895
- }
896
- else if (action?.unarchiveChatsSetting) {
897
- const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
898
- ev.emit('creds.update', { accountSettings: { unarchiveChats } });
899
- logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
900
- if (accountSettings) {
901
- accountSettings.unarchiveChats = unarchiveChats;
902
- }
903
- }
904
- else if (action?.starAction || type === 'star') {
905
- let starred = action?.starAction?.starred;
906
- if (typeof starred !== 'boolean') {
907
- starred = syncAction.index[syncAction.index.length - 1] === '1';
908
- }
909
- ev.emit('messages.update', [
910
- {
911
- key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
912
- update: { starred }
913
- }
914
- ]);
915
- }
916
- else if (action?.deleteChatAction || type === 'deleteChat') {
917
- if (!isInitialSync) {
918
- ev.emit('chats.delete', [id]);
919
- }
920
- }
921
- else if (action?.labelEditAction) {
922
- const { name, color, deleted, predefinedId } = action.labelEditAction;
923
- ev.emit('labels.edit', {
924
- id: id,
925
- name: name,
926
- color: color,
927
- deleted: deleted,
928
- predefinedId: predefinedId ? String(predefinedId) : undefined
929
- });
930
- }
931
- else if (action?.labelAssociationAction) {
932
- ev.emit('labels.association', {
933
- type: action.labelAssociationAction.labeled ? 'add' : 'remove',
934
- association: type === LabelAssociation_1.LabelAssociationType.Chat
935
- ? {
936
- type: LabelAssociation_1.LabelAssociationType.Chat,
937
- chatId: syncAction.index[2],
938
- labelId: syncAction.index[1]
939
- }
940
- : {
941
- type: LabelAssociation_1.LabelAssociationType.Message,
942
- chatId: syncAction.index[2],
943
- messageId: syncAction.index[3],
944
- labelId: syncAction.index[1]
945
- }
946
- });
947
- }
948
- else if (action?.localeSetting?.locale) {
949
- ev.emit('settings.update', { setting: 'locale', value: action.localeSetting.locale });
950
- }
951
- else if (action?.timeFormatAction) {
952
- ev.emit('settings.update', { setting: 'timeFormat', value: action.timeFormatAction });
953
- }
954
- else if (action?.pnForLidChatAction) {
955
- if (action.pnForLidChatAction.pnJid) {
956
- ev.emit('lid-mapping.update', { lid: id, pn: action.pnForLidChatAction.pnJid });
957
- }
958
- }
959
- else if (action?.privacySettingRelayAllCalls) {
960
- ev.emit('settings.update', {
961
- setting: 'privacySettingRelayAllCalls',
962
- value: action.privacySettingRelayAllCalls
963
- });
964
- }
965
- else if (action?.statusPrivacy) {
966
- ev.emit('settings.update', { setting: 'statusPrivacy', value: action.statusPrivacy });
967
- }
968
- else if (action?.lockChatAction) {
969
- ev.emit('chats.lock', { id: id, locked: !!action.lockChatAction.locked });
970
- }
971
- else if (action?.privacySettingDisableLinkPreviewsAction) {
972
- ev.emit('settings.update', {
973
- setting: 'disableLinkPreviews',
974
- value: action.privacySettingDisableLinkPreviewsAction
975
- });
976
- }
977
- else if (action?.notificationActivitySettingAction?.notificationActivitySetting) {
978
- ev.emit('settings.update', {
979
- setting: 'notificationActivitySetting',
980
- value: action.notificationActivitySettingAction.notificationActivitySetting
981
- });
982
- }
983
- else if (action?.lidContactAction) {
984
- ev.emit('contacts.upsert', [
985
- {
986
- id: id,
987
- name: action.lidContactAction.fullName ||
988
- action.lidContactAction.firstName ||
989
- action.lidContactAction.username ||
990
- undefined,
991
- username: action.lidContactAction.username || undefined,
992
- lid: id,
993
- phoneNumber: undefined
994
- }
995
- ]);
996
- }
997
- else if (action?.privacySettingChannelsPersonalisedRecommendationAction) {
998
- ev.emit('settings.update', {
999
- setting: 'channelsPersonalisedRecommendation',
1000
- value: action.privacySettingChannelsPersonalisedRecommendationAction
1001
- });
1002
- }
1003
- else if (action?.aiThreadRenameAction) {
1004
- ev.emit('chats.update', [
1005
- {
1006
- id,
1007
- name: action.aiThreadRenameAction.newTitle,
1008
- conditional: getChatUpdateConditional(id, undefined)
1009
- }
1010
- ]);
1011
- }
1012
- else if (action?.threadPinAction) {
1013
- ev.emit('chats.update', [
1014
- {
1015
- id,
1016
- pinned: action.threadPinAction.pinned ? (0, generics_1.toNumber)(action.timestamp) : null,
1017
- conditional: getChatUpdateConditional(id, undefined)
1018
- }
1019
- ]);
1020
- }
1021
- else if (action?.privateProcessingSettingAction) {
1022
- ev.emit('settings.update', {
1023
- setting: 'privateProcessing',
1024
- value: action.privateProcessingSettingAction
1025
- });
1026
- }
1027
- else if (action?.settingsSyncAction) {
1028
- ev.emit('settings.update', {
1029
- setting: 'clientSettings',
1030
- value: action.settingsSyncAction
1031
- });
1032
- }
1033
- else if (action?.musicUserIdAction) {
1034
- ev.emit('settings.update', {
1035
- setting: 'musicUserId',
1036
- value: action.musicUserIdAction
1037
- });
1038
- }
1039
- else if (action?.avatarUpdatedAction) {
1040
- ev.emit('settings.update', {
1041
- setting: 'avatarUpdated',
1042
- value: action.avatarUpdatedAction
1043
- });
1044
- }
1045
- else if (action?.recentEmojiWeightsAction) {
1046
- ev.emit('settings.update', {
1047
- setting: 'recentEmojiWeights',
1048
- value: action.recentEmojiWeightsAction?.weights || []
1049
- });
1050
- }
1051
- else if (action?.stickerAction) {
1052
- ev.emit('settings.update', { setting: 'stickerSync', value: action.stickerAction });
1053
- }
1054
- else if (action?.removeRecentStickerAction) {
1055
- ev.emit('settings.update', { setting: 'removedRecentSticker', value: action.removeRecentStickerAction });
1056
- }
1057
- else if (action?.userStatusMuteAction) {
1058
- ev.emit('contacts.update', [{ id, statusMuted: !!action.userStatusMuteAction.muted }]);
1059
- }
1060
- else if (action?.chatAssignment) {
1061
- ev.emit('chats.update', [
1062
- {
1063
- id,
1064
- chatAssignment: action.chatAssignment,
1065
- conditional: getChatUpdateConditional(id, undefined)
1066
- }
1067
- ]);
1068
- }
1069
- else if (action?.chatAssignmentOpenedStatus) {
1070
- ev.emit('chats.update', [
1071
- {
1072
- id,
1073
- chatAssignmentOpened: !!action.chatAssignmentOpenedStatus.opened,
1074
- conditional: getChatUpdateConditional(id, undefined)
1075
- }
1076
- ]);
1077
- }
1078
- else if (action?.callLogAction) {
1079
- ev.emit('settings.update', { setting: 'callLog', value: action.callLogAction });
1080
- }
1081
- else if (action?.deleteIndividualCallLog) {
1082
- ev.emit('settings.update', { setting: 'callLogDeleted', value: action.deleteIndividualCallLog });
1083
- }
1084
- else if (action?.labelReorderingAction) {
1085
- ev.emit('labels.reorder', { labelIds: action.labelReorderingAction.sortedLabelIds || [] });
1086
- }
1087
- else if (action?.paymentInfoAction) {
1088
- ev.emit('settings.update', { setting: 'paymentInfo', value: action.paymentInfoAction });
1089
- }
1090
- else if (action?.noteEditAction) {
1091
- ev.emit('chats.update', [
1092
- { id, draftNote: action.noteEditAction, conditional: getChatUpdateConditional(id, undefined) }
1093
- ]);
1094
- }
1095
- else if (action?.favoritesAction) {
1096
- ev.emit('contacts.update', [{ id, favorite: !!action.favoritesAction.isFavorite }]);
1097
- }
1098
- else if (action?.usernameChatStartMode) {
1099
- ev.emit('settings.update', { setting: 'usernameChatStartMode', value: action.usernameChatStartMode });
1100
- }
1101
- else if (action?.maibaAiFeaturesControlAction) {
1102
- ev.emit('settings.update', { setting: 'aiFeatures', value: action.maibaAiFeaturesControlAction });
1103
- }
1104
- else if (action?.statusPostOptInNotificationPreferencesAction) {
1105
- ev.emit('settings.update', {
1106
- setting: 'statusPostOptInNotifications',
1107
- value: action.statusPostOptInNotificationPreferencesAction
1108
- });
1109
- }
1110
- else if (action?.subscriptionsSyncV2Action) {
1111
- ev.emit('settings.update', { setting: 'subscriptions', value: action.subscriptionsSyncV2Action });
1112
- }
1113
- else if (action?.newsletterSavedInterestsAction) {
1114
- ev.emit('settings.update', { setting: 'newsletterSavedInterests', value: action.newsletterSavedInterestsAction });
1115
- }
1116
- else if (action?.interactiveMessageAction) {
1117
- ev.emit('settings.update', { setting: 'interactiveMessageAction', value: action.interactiveMessageAction });
1118
- }
1119
- else if (action?.outContactAction) {
1120
- const results = (0, sync_action_utils_1.processContactAction)({
1121
- fullName: action.outContactAction.fullName,
1122
- firstName: action.outContactAction.firstName
1123
- }, id, logger);
1124
- (0, sync_action_utils_1.emitSyncActionResults)(ev, results);
1125
- }
1126
- else if (action?.businessBroadcastListAction) {
1127
- ev.emit('settings.update', { setting: 'broadcastList', value: action.businessBroadcastListAction });
1128
- }
1129
- else if (action?.customerDataAction) {
1130
- ev.emit('chats.update', [
1131
- { id, customerData: action.customerDataAction, conditional: getChatUpdateConditional(id, undefined) }
1132
- ]);
1133
- }
1134
- else if (action?.autoOrganizeBusinessChatSetting) {
1135
- ev.emit('settings.update', { setting: 'autoOrganizeBusinessChat', value: action.autoOrganizeBusinessChatSetting });
1136
- }
1137
- else if (action?.chatLockSettings) {
1138
- ev.emit('chats.update', [
1139
- { id, chatLockSettings: action.chatLockSettings, conditional: getChatUpdateConditional(id, undefined) }
1140
- ]);
1141
- }
1142
- else if (action?.agentAction) {
1143
- ev.emit('settings.update', { setting: 'agentAction', value: action.agentAction });
1144
- }
1145
- else if (action?.nuxAction) {
1146
- ev.emit('settings.update', { setting: 'nux', value: action.nuxAction });
1147
- }
1148
- else if (action?.quickReplyAction) {
1149
- ev.emit('settings.update', { setting: 'quickReply', value: action.quickReplyAction });
1150
- }
1151
- else if (action?.keyExpiration) {
1152
- ev.emit('settings.update', { setting: 'keyExpiration', value: action.keyExpiration });
1153
- }
1154
- else if (action?.primaryFeature) {
1155
- ev.emit('settings.update', { setting: 'primaryFeature', value: action.primaryFeature });
1156
- }
1157
- else if (action?.androidUnsupportedActions) {
1158
- ev.emit('settings.update', { setting: 'androidUnsupported', value: action.androidUnsupportedActions });
1159
- }
1160
- else if (action?.subscriptionAction) {
1161
- ev.emit('settings.update', { setting: 'subscription', value: action.subscriptionAction });
1162
- }
1163
- else if (action?.primaryVersionAction) {
1164
- ev.emit('settings.update', { setting: 'primaryVersion', value: action.primaryVersionAction });
1165
- }
1166
- else if (action?.marketingMessageAction) {
1167
- ev.emit('settings.update', { setting: 'marketingMessage', value: action.marketingMessageAction });
1168
- }
1169
- else if (action?.marketingMessageBroadcastAction) {
1170
- ev.emit('settings.update', { setting: 'marketingMessageBroadcast', value: action.marketingMessageBroadcastAction });
1171
- }
1172
- else if (action?.externalWebBetaAction) {
1173
- ev.emit('settings.update', { setting: 'externalWebBeta', value: action.externalWebBetaAction });
1174
- }
1175
- else if (action?.botWelcomeRequestAction) {
1176
- ev.emit('settings.update', { setting: 'botWelcomeRequest', value: action.botWelcomeRequestAction });
1177
- }
1178
- else if (action?.customPaymentMethodsAction) {
1179
- ev.emit('settings.update', { setting: 'customPaymentMethods', value: action.customPaymentMethodsAction });
1180
- }
1181
- else if (action?.wamoUserIdentifierAction) {
1182
- ev.emit('settings.update', { setting: 'wamoUserIdentifier', value: action.wamoUserIdentifierAction });
1183
- }
1184
- else if (action?.merchantPaymentPartnerAction) {
1185
- ev.emit('settings.update', { setting: 'merchantPaymentPartner', value: action.merchantPaymentPartnerAction });
1186
- }
1187
- else if (action?.waffleAccountLinkStateAction) {
1188
- ev.emit('settings.update', { setting: 'waffleAccountLinkState', value: action.waffleAccountLinkStateAction });
1189
- }
1190
- else if (action?.ctwaPerCustomerDataSharingAction) {
1191
- ev.emit('settings.update', { setting: 'ctwaDataSharing', value: action.ctwaPerCustomerDataSharingAction });
1192
- }
1193
- else if (action?.paymentTosAction) {
1194
- ev.emit('settings.update', { setting: 'paymentTos', value: action.paymentTosAction });
1195
- }
1196
- else if (action?.detectedOutcomesStatusAction) {
1197
- ev.emit('settings.update', { setting: 'detectedOutcomesStatus', value: action.detectedOutcomesStatusAction });
1198
- }
1199
- else if (action?.nctSaltSyncAction) {
1200
- ev.emit('settings.update', { setting: 'nctSaltSync', value: action.nctSaltSyncAction });
1201
- }
1202
- else if (action?.businessBroadcastCampaignAction) {
1203
- ev.emit('settings.update', { setting: 'businessBroadcastCampaign', value: action.businessBroadcastCampaignAction });
1204
- }
1205
- else if (action?.businessBroadcastInsightsAction) {
1206
- ev.emit('settings.update', { setting: 'businessBroadcastInsights', value: action.businessBroadcastInsightsAction });
1207
- }
1208
- else if (action?.bizAiSettingsNudgeAction) {
1209
- ev.emit('settings.update', { setting: 'bizAiSettingsNudge', value: action.bizAiSettingsNudgeAction });
1210
- }
1211
- else {
1212
- logger?.debug({ syncAction, id }, 'unprocessable update');
1213
- }
1214
- function getChatUpdateConditional(id, msgRange) {
1215
- return isInitialSync
1216
- ? data => {
1217
- const chat = data.historySets.chats[id] || data.chatUpserts[id];
1218
- if (chat) {
1219
- return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
1220
- }
1221
- }
1222
- : undefined;
1223
- }
1224
- function isValidPatchBasedOnMessageRange(chat, msgRange) {
1225
- const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0);
1226
- const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0);
1227
- return lastMsgTimestamp >= chatLastMsgTimestamp;
1228
- }
1229
- };
1230
- exports.processSyncAction = processSyncAction;