@queenanya/baileys 7.5.3-0 → 8.0.0

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 (179) hide show
  1. package/package.json +13 -97
  2. package/LICENSE +0 -21
  3. package/README.md +0 -931
  4. package/WAProto/GenerateStatics.sh +0 -4
  5. package/WAProto/WAProto.proto +0 -3344
  6. package/WAProto/index.d.ts +0 -37016
  7. package/WAProto/index.js +0 -130281
  8. package/WASignalGroup/GroupProtocol.js +0 -1697
  9. package/WASignalGroup/ciphertext_message.js +0 -16
  10. package/WASignalGroup/group_cipher.js +0 -120
  11. package/WASignalGroup/group_session_builder.js +0 -46
  12. package/WASignalGroup/index.js +0 -5
  13. package/WASignalGroup/keyhelper.js +0 -21
  14. package/WASignalGroup/protobufs.js +0 -3
  15. package/WASignalGroup/queue_job.js +0 -69
  16. package/WASignalGroup/sender_chain_key.js +0 -50
  17. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  18. package/WASignalGroup/sender_key_message.js +0 -92
  19. package/WASignalGroup/sender_key_name.js +0 -70
  20. package/WASignalGroup/sender_key_record.js +0 -56
  21. package/WASignalGroup/sender_key_state.js +0 -129
  22. package/WASignalGroup/sender_message_key.js +0 -39
  23. package/lib/Defaults/baileys-version.json +0 -3
  24. package/lib/Defaults/index.d.ts +0 -53
  25. package/lib/Defaults/index.js +0 -107
  26. package/lib/Signal/libsignal.d.ts +0 -3
  27. package/lib/Signal/libsignal.js +0 -152
  28. package/lib/Socket/Client/index.d.ts +0 -2
  29. package/lib/Socket/Client/index.js +0 -18
  30. package/lib/Socket/Client/types.d.ts +0 -17
  31. package/lib/Socket/Client/types.js +0 -13
  32. package/lib/Socket/Client/websocket.d.ts +0 -12
  33. package/lib/Socket/Client/websocket.js +0 -62
  34. package/lib/Socket/business.d.ts +0 -173
  35. package/lib/Socket/business.js +0 -260
  36. package/lib/Socket/chats.d.ts +0 -88
  37. package/lib/Socket/chats.js +0 -920
  38. package/lib/Socket/communities.d.ts +0 -216
  39. package/lib/Socket/communities.js +0 -354
  40. package/lib/Socket/groups.d.ts +0 -127
  41. package/lib/Socket/groups.js +0 -314
  42. package/lib/Socket/index.d.ts +0 -203
  43. package/lib/Socket/index.js +0 -10
  44. package/lib/Socket/messages-recv.d.ts +0 -160
  45. package/lib/Socket/messages-recv.js +0 -918
  46. package/lib/Socket/messages-send.d.ts +0 -153
  47. package/lib/Socket/messages-send.js +0 -794
  48. package/lib/Socket/newsletter.d.ts +0 -139
  49. package/lib/Socket/newsletter.js +0 -249
  50. package/lib/Socket/socket.d.ts +0 -45
  51. package/lib/Socket/socket.js +0 -616
  52. package/lib/Socket/usync.d.ts +0 -38
  53. package/lib/Socket/usync.js +0 -70
  54. package/lib/Store/index.d.ts +0 -3
  55. package/lib/Store/index.js +0 -10
  56. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  57. package/lib/Store/make-cache-manager-store.js +0 -83
  58. package/lib/Store/make-in-memory-store.d.ts +0 -118
  59. package/lib/Store/make-in-memory-store.js +0 -420
  60. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  61. package/lib/Store/make-ordered-dictionary.js +0 -81
  62. package/lib/Store/object-repository.d.ts +0 -10
  63. package/lib/Store/object-repository.js +0 -27
  64. package/lib/Types/Auth.d.ts +0 -105
  65. package/lib/Types/Auth.js +0 -2
  66. package/lib/Types/Call.d.ts +0 -13
  67. package/lib/Types/Call.js +0 -2
  68. package/lib/Types/Chat.d.ts +0 -110
  69. package/lib/Types/Chat.js +0 -4
  70. package/lib/Types/Contact.d.ts +0 -24
  71. package/lib/Types/Contact.js +0 -2
  72. package/lib/Types/Events.d.ts +0 -199
  73. package/lib/Types/Events.js +0 -2
  74. package/lib/Types/GroupMetadata.d.ts +0 -56
  75. package/lib/Types/GroupMetadata.js +0 -2
  76. package/lib/Types/Label.d.ts +0 -46
  77. package/lib/Types/Label.js +0 -27
  78. package/lib/Types/LabelAssociation.d.ts +0 -29
  79. package/lib/Types/LabelAssociation.js +0 -9
  80. package/lib/Types/Message.d.ts +0 -280
  81. package/lib/Types/Message.js +0 -9
  82. package/lib/Types/Newsletter.d.ts +0 -79
  83. package/lib/Types/Newsletter.js +0 -18
  84. package/lib/Types/Product.d.ts +0 -78
  85. package/lib/Types/Product.js +0 -2
  86. package/lib/Types/Signal.d.ts +0 -57
  87. package/lib/Types/Signal.js +0 -2
  88. package/lib/Types/Socket.d.ts +0 -118
  89. package/lib/Types/Socket.js +0 -2
  90. package/lib/Types/State.d.ts +0 -27
  91. package/lib/Types/State.js +0 -2
  92. package/lib/Types/USync.d.ts +0 -25
  93. package/lib/Types/USync.js +0 -2
  94. package/lib/Types/index.d.ts +0 -65
  95. package/lib/Types/index.js +0 -42
  96. package/lib/Utils/auth-utils.d.ts +0 -18
  97. package/lib/Utils/auth-utils.js +0 -200
  98. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  99. package/lib/Utils/baileys-event-stream.js +0 -63
  100. package/lib/Utils/business.d.ts +0 -22
  101. package/lib/Utils/business.js +0 -234
  102. package/lib/Utils/chat-utils.d.ts +0 -72
  103. package/lib/Utils/chat-utils.js +0 -756
  104. package/lib/Utils/crypto.d.ts +0 -42
  105. package/lib/Utils/crypto.js +0 -153
  106. package/lib/Utils/decode-wa-message.d.ts +0 -20
  107. package/lib/Utils/decode-wa-message.js +0 -218
  108. package/lib/Utils/event-buffer.d.ts +0 -35
  109. package/lib/Utils/event-buffer.js +0 -520
  110. package/lib/Utils/generics.d.ts +0 -119
  111. package/lib/Utils/generics.js +0 -468
  112. package/lib/Utils/history.d.ts +0 -19
  113. package/lib/Utils/history.js +0 -94
  114. package/lib/Utils/index.d.ts +0 -18
  115. package/lib/Utils/index.js +0 -34
  116. package/lib/Utils/link-preview.d.ts +0 -21
  117. package/lib/Utils/link-preview.js +0 -116
  118. package/lib/Utils/logger.d.ts +0 -2
  119. package/lib/Utils/logger.js +0 -7
  120. package/lib/Utils/lt-hash.d.ts +0 -12
  121. package/lib/Utils/lt-hash.js +0 -51
  122. package/lib/Utils/make-mutex.d.ts +0 -7
  123. package/lib/Utils/make-mutex.js +0 -44
  124. package/lib/Utils/messages-media.d.ts +0 -131
  125. package/lib/Utils/messages-media.js +0 -786
  126. package/lib/Utils/messages.d.ts +0 -78
  127. package/lib/Utils/messages.js +0 -767
  128. package/lib/Utils/noise-handler.d.ts +0 -21
  129. package/lib/Utils/noise-handler.js +0 -150
  130. package/lib/Utils/process-message.d.ts +0 -42
  131. package/lib/Utils/process-message.js +0 -355
  132. package/lib/Utils/signal.d.ts +0 -32
  133. package/lib/Utils/signal.js +0 -158
  134. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  135. package/lib/Utils/use-multi-file-auth-state.js +0 -94
  136. package/lib/Utils/use-single-file-auth-state.d.ts +0 -5
  137. package/lib/Utils/use-single-file-auth-state.js +0 -66
  138. package/lib/Utils/validate-connection.d.ts +0 -10
  139. package/lib/Utils/validate-connection.js +0 -171
  140. package/lib/WABinary/constants.d.ts +0 -27
  141. package/lib/WABinary/constants.js +0 -40
  142. package/lib/WABinary/decode.d.ts +0 -8
  143. package/lib/WABinary/decode.js +0 -254
  144. package/lib/WABinary/encode.d.ts +0 -2
  145. package/lib/WABinary/encode.js +0 -230
  146. package/lib/WABinary/generic-utils.d.ts +0 -16
  147. package/lib/WABinary/generic-utils.js +0 -110
  148. package/lib/WABinary/index.d.ts +0 -5
  149. package/lib/WABinary/index.js +0 -21
  150. package/lib/WABinary/jid-utils.d.ts +0 -31
  151. package/lib/WABinary/jid-utils.js +0 -62
  152. package/lib/WABinary/types.d.ts +0 -18
  153. package/lib/WABinary/types.js +0 -2
  154. package/lib/WAM/BinaryInfo.d.ts +0 -18
  155. package/lib/WAM/BinaryInfo.js +0 -13
  156. package/lib/WAM/constants.d.ts +0 -39
  157. package/lib/WAM/constants.js +0 -15350
  158. package/lib/WAM/encode.d.ts +0 -4
  159. package/lib/WAM/encode.js +0 -155
  160. package/lib/WAM/index.d.ts +0 -3
  161. package/lib/WAM/index.js +0 -19
  162. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  163. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -32
  164. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  165. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  166. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  167. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  168. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  169. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  170. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  171. package/lib/WAUSync/Protocols/index.js +0 -20
  172. package/lib/WAUSync/USyncQuery.d.ts +0 -26
  173. package/lib/WAUSync/USyncQuery.js +0 -79
  174. package/lib/WAUSync/USyncUser.d.ts +0 -10
  175. package/lib/WAUSync/USyncUser.js +0 -22
  176. package/lib/WAUSync/index.d.ts +0 -3
  177. package/lib/WAUSync/index.js +0 -19
  178. package/lib/index.d.ts +0 -12
  179. package/lib/index.js +0 -31
@@ -1,756 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.processSyncAction = exports.chatModificationToAppPatch = exports.decodePatches = exports.decodeSyncdSnapshot = exports.downloadExternalPatch = exports.downloadExternalBlob = exports.extractSyncdPatches = exports.decodeSyncdPatch = exports.decodeSyncdMutations = exports.encodeSyncdPatch = exports.newLTHashState = void 0;
4
- const boom_1 = require("@hapi/boom");
5
- const WAProto_1 = require("../../WAProto");
6
- const LabelAssociation_1 = require("../Types/LabelAssociation");
7
- const WABinary_1 = require("../WABinary");
8
- const crypto_1 = require("./crypto");
9
- const generics_1 = require("./generics");
10
- const lt_hash_1 = require("./lt-hash");
11
- const messages_media_1 = require("./messages-media");
12
- const mutationKeys = (keydata) => {
13
- const expanded = (0, crypto_1.hkdf)(keydata, 160, { info: 'WhatsApp Mutation Keys' });
14
- return {
15
- indexKey: expanded.slice(0, 32),
16
- valueEncryptionKey: expanded.slice(32, 64),
17
- valueMacKey: expanded.slice(64, 96),
18
- snapshotMacKey: expanded.slice(96, 128),
19
- patchMacKey: expanded.slice(128, 160)
20
- };
21
- };
22
- const generateMac = (operation, data, keyId, key) => {
23
- const getKeyData = () => {
24
- let r;
25
- switch (operation) {
26
- case WAProto_1.proto.SyncdMutation.SyncdOperation.SET:
27
- r = 0x01;
28
- break;
29
- case WAProto_1.proto.SyncdMutation.SyncdOperation.REMOVE:
30
- r = 0x02;
31
- break;
32
- }
33
- const buff = Buffer.from([r]);
34
- return Buffer.concat([buff, Buffer.from(keyId, 'base64')]);
35
- };
36
- const keyData = getKeyData();
37
- const last = Buffer.alloc(8); // 8 bytes
38
- last.set([keyData.length], last.length - 1);
39
- const total = Buffer.concat([keyData, data, last]);
40
- const hmac = (0, crypto_1.hmacSign)(total, key, 'sha512');
41
- return hmac.slice(0, 32);
42
- };
43
- const to64BitNetworkOrder = (e) => {
44
- const buff = Buffer.alloc(8);
45
- buff.writeUint32BE(e, 4);
46
- return buff;
47
- };
48
- const makeLtHashGenerator = ({ indexValueMap, hash }) => {
49
- indexValueMap = { ...indexValueMap };
50
- const addBuffs = [];
51
- const subBuffs = [];
52
- return {
53
- mix: ({ indexMac, valueMac, operation }) => {
54
- const indexMacBase64 = Buffer.from(indexMac).toString('base64');
55
- const prevOp = indexValueMap[indexMacBase64];
56
- if (operation === WAProto_1.proto.SyncdMutation.SyncdOperation.REMOVE) {
57
- if (!prevOp) {
58
- throw new boom_1.Boom('tried remove, but no previous op', { data: { indexMac, valueMac } });
59
- }
60
- // remove from index value mac, since this mutation is erased
61
- delete indexValueMap[indexMacBase64];
62
- }
63
- else {
64
- addBuffs.push(new Uint8Array(valueMac).buffer);
65
- // add this index into the history map
66
- indexValueMap[indexMacBase64] = { valueMac };
67
- }
68
- if (prevOp) {
69
- subBuffs.push(new Uint8Array(prevOp.valueMac).buffer);
70
- }
71
- },
72
- finish: () => {
73
- const hashArrayBuffer = new Uint8Array(hash).buffer;
74
- const result = lt_hash_1.LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
75
- const buffer = Buffer.from(result);
76
- return {
77
- hash: buffer,
78
- indexValueMap
79
- };
80
- }
81
- };
82
- };
83
- const generateSnapshotMac = (lthash, version, name, key) => {
84
- const total = Buffer.concat([
85
- lthash,
86
- to64BitNetworkOrder(version),
87
- Buffer.from(name, 'utf-8')
88
- ]);
89
- return (0, crypto_1.hmacSign)(total, key, 'sha256');
90
- };
91
- const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
92
- const total = Buffer.concat([
93
- snapshotMac,
94
- ...valueMacs,
95
- to64BitNetworkOrder(version),
96
- Buffer.from(type, 'utf-8')
97
- ]);
98
- return (0, crypto_1.hmacSign)(total, key);
99
- };
100
- const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
101
- exports.newLTHashState = newLTHashState;
102
- const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
103
- const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
104
- if (!key) {
105
- throw new boom_1.Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 });
106
- }
107
- const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
108
- state = { ...state, indexValueMap: { ...state.indexValueMap } };
109
- const indexBuffer = Buffer.from(JSON.stringify(index));
110
- const dataProto = WAProto_1.proto.SyncActionData.fromObject({
111
- index: indexBuffer,
112
- value: syncAction,
113
- padding: new Uint8Array(0),
114
- version: apiVersion
115
- });
116
- const encoded = WAProto_1.proto.SyncActionData.encode(dataProto).finish();
117
- const keyValue = mutationKeys(key.keyData);
118
- const encValue = (0, crypto_1.aesEncrypt)(encoded, keyValue.valueEncryptionKey);
119
- const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
120
- const indexMac = (0, crypto_1.hmacSign)(indexBuffer, keyValue.indexKey);
121
- // update LT hash
122
- const generator = makeLtHashGenerator(state);
123
- generator.mix({ indexMac, valueMac, operation });
124
- Object.assign(state, generator.finish());
125
- state.version += 1;
126
- const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
127
- const patch = {
128
- patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
129
- snapshotMac: snapshotMac,
130
- keyId: { id: encKeyId },
131
- mutations: [
132
- {
133
- operation: operation,
134
- record: {
135
- index: {
136
- blob: indexMac
137
- },
138
- value: {
139
- blob: Buffer.concat([encValue, valueMac])
140
- },
141
- keyId: { id: encKeyId }
142
- }
143
- }
144
- ]
145
- };
146
- const base64Index = indexMac.toString('base64');
147
- state.indexValueMap[base64Index] = { valueMac };
148
- return { patch, state };
149
- };
150
- exports.encodeSyncdPatch = encodeSyncdPatch;
151
- const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
152
- const ltGenerator = makeLtHashGenerator(initialState);
153
- // indexKey used to HMAC sign record.index.blob
154
- // valueEncryptionKey used to AES-256-CBC encrypt record.value.blob[0:-32]
155
- // 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
156
- for (const msgMutation of msgMutations) {
157
- // if it's a syncdmutation, get the operation property
158
- // otherwise, if it's only a record -- it'll be a SET mutation
159
- const operation = 'operation' in msgMutation ? msgMutation.operation : WAProto_1.proto.SyncdMutation.SyncdOperation.SET;
160
- const record = ('record' in msgMutation && !!msgMutation.record) ? msgMutation.record : msgMutation;
161
- const key = await getKey(record.keyId.id);
162
- const content = Buffer.from(record.value.blob);
163
- const encContent = content.slice(0, -32);
164
- const ogValueMac = content.slice(-32);
165
- if (validateMacs) {
166
- const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
167
- if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
168
- throw new boom_1.Boom('HMAC content verification failed');
169
- }
170
- }
171
- const result = (0, crypto_1.aesDecrypt)(encContent, key.valueEncryptionKey);
172
- const syncAction = WAProto_1.proto.SyncActionData.decode(result);
173
- if (validateMacs) {
174
- const hmac = (0, crypto_1.hmacSign)(syncAction.index, key.indexKey);
175
- if (Buffer.compare(hmac, record.index.blob) !== 0) {
176
- throw new boom_1.Boom('HMAC index verification failed');
177
- }
178
- }
179
- const indexStr = Buffer.from(syncAction.index).toString();
180
- onMutation({ syncAction, index: JSON.parse(indexStr) });
181
- ltGenerator.mix({
182
- indexMac: record.index.blob,
183
- valueMac: ogValueMac,
184
- operation: operation
185
- });
186
- }
187
- return ltGenerator.finish();
188
- async function getKey(keyId) {
189
- const base64Key = Buffer.from(keyId).toString('base64');
190
- const keyEnc = await getAppStateSyncKey(base64Key);
191
- if (!keyEnc) {
192
- throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`, { statusCode: 404, data: { msgMutations } });
193
- }
194
- return mutationKeys(keyEnc.keyData);
195
- }
196
- };
197
- exports.decodeSyncdMutations = decodeSyncdMutations;
198
- const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
199
- if (validateMacs) {
200
- const base64Key = Buffer.from(msg.keyId.id).toString('base64');
201
- const mainKeyObj = await getAppStateSyncKey(base64Key);
202
- if (!mainKeyObj) {
203
- throw new boom_1.Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
204
- }
205
- const mainKey = mutationKeys(mainKeyObj.keyData);
206
- const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
207
- const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, (0, generics_1.toNumber)(msg.version.version), name, mainKey.patchMacKey);
208
- if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
209
- throw new boom_1.Boom('Invalid patch mac');
210
- }
211
- }
212
- const result = await (0, exports.decodeSyncdMutations)(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs);
213
- return result;
214
- };
215
- exports.decodeSyncdPatch = decodeSyncdPatch;
216
- const extractSyncdPatches = async (result, options) => {
217
- const syncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'sync');
218
- const collectionNodes = (0, WABinary_1.getBinaryNodeChildren)(syncNode, 'collection');
219
- const final = {};
220
- await Promise.all(collectionNodes.map(async (collectionNode) => {
221
- const patchesNode = (0, WABinary_1.getBinaryNodeChild)(collectionNode, 'patches');
222
- const patches = (0, WABinary_1.getBinaryNodeChildren)(patchesNode || collectionNode, 'patch');
223
- const snapshotNode = (0, WABinary_1.getBinaryNodeChild)(collectionNode, 'snapshot');
224
- const syncds = [];
225
- const name = collectionNode.attrs.name;
226
- const hasMorePatches = collectionNode.attrs.has_more_patches === 'true';
227
- let snapshot = undefined;
228
- if (snapshotNode && !!snapshotNode.content) {
229
- if (!Buffer.isBuffer(snapshotNode)) {
230
- snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
231
- }
232
- const blobRef = WAProto_1.proto.ExternalBlobReference.decode(snapshotNode.content);
233
- const data = await (0, exports.downloadExternalBlob)(blobRef, options);
234
- snapshot = WAProto_1.proto.SyncdSnapshot.decode(data);
235
- }
236
- for (let { content } of patches) {
237
- if (content) {
238
- if (!Buffer.isBuffer(content)) {
239
- content = Buffer.from(Object.values(content));
240
- }
241
- const syncd = WAProto_1.proto.SyncdPatch.decode(content);
242
- if (!syncd.version) {
243
- syncd.version = { version: +collectionNode.attrs.version + 1 };
244
- }
245
- syncds.push(syncd);
246
- }
247
- }
248
- final[name] = { patches: syncds, hasMorePatches, snapshot };
249
- }));
250
- return final;
251
- };
252
- exports.extractSyncdPatches = extractSyncdPatches;
253
- const downloadExternalBlob = async (blob, options) => {
254
- const stream = await (0, messages_media_1.downloadContentFromMessage)(blob, 'md-app-state', { options });
255
- const bufferArray = [];
256
- for await (const chunk of stream) {
257
- bufferArray.push(chunk);
258
- }
259
- return Buffer.concat(bufferArray);
260
- };
261
- exports.downloadExternalBlob = downloadExternalBlob;
262
- const downloadExternalPatch = async (blob, options) => {
263
- const buffer = await (0, exports.downloadExternalBlob)(blob, options);
264
- const syncData = WAProto_1.proto.SyncdMutations.decode(buffer);
265
- return syncData;
266
- };
267
- exports.downloadExternalPatch = downloadExternalPatch;
268
- const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true) => {
269
- const newState = (0, exports.newLTHashState)();
270
- newState.version = (0, generics_1.toNumber)(snapshot.version.version);
271
- const mutationMap = {};
272
- const areMutationsRequired = typeof minimumVersionNumber === 'undefined'
273
- || newState.version > minimumVersionNumber;
274
- const { hash, indexValueMap } = await (0, exports.decodeSyncdMutations)(snapshot.records, newState, getAppStateSyncKey, areMutationsRequired
275
- ? (mutation) => {
276
- var _a;
277
- const index = (_a = mutation.syncAction.index) === null || _a === void 0 ? void 0 : _a.toString();
278
- mutationMap[index] = mutation;
279
- }
280
- : () => { }, validateMacs);
281
- newState.hash = hash;
282
- newState.indexValueMap = indexValueMap;
283
- if (validateMacs) {
284
- const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
285
- const keyEnc = await getAppStateSyncKey(base64Key);
286
- if (!keyEnc) {
287
- throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
288
- }
289
- const result = mutationKeys(keyEnc.keyData);
290
- const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
291
- if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
292
- throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
293
- }
294
- }
295
- return {
296
- state: newState,
297
- mutationMap
298
- };
299
- };
300
- exports.decodeSyncdSnapshot = decodeSyncdSnapshot;
301
- const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
302
- var _a;
303
- const newState = {
304
- ...initial,
305
- indexValueMap: { ...initial.indexValueMap }
306
- };
307
- const mutationMap = {};
308
- for (const syncd of syncds) {
309
- const { version, keyId, snapshotMac } = syncd;
310
- if (syncd.externalMutations) {
311
- logger === null || logger === void 0 ? void 0 : logger.trace({ name, version }, 'downloading external patch');
312
- const ref = await (0, exports.downloadExternalPatch)(syncd.externalMutations, options);
313
- logger === null || logger === void 0 ? void 0 : logger.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch');
314
- (_a = syncd.mutations) === null || _a === void 0 ? void 0 : _a.push(...ref.mutations);
315
- }
316
- const patchVersion = (0, generics_1.toNumber)(version.version);
317
- newState.version = patchVersion;
318
- const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
319
- const decodeResult = await (0, exports.decodeSyncdPatch)(syncd, name, newState, getAppStateSyncKey, shouldMutate
320
- ? mutation => {
321
- var _a;
322
- const index = (_a = mutation.syncAction.index) === null || _a === void 0 ? void 0 : _a.toString();
323
- mutationMap[index] = mutation;
324
- }
325
- : (() => { }), true);
326
- newState.hash = decodeResult.hash;
327
- newState.indexValueMap = decodeResult.indexValueMap;
328
- if (validateMacs) {
329
- const base64Key = Buffer.from(keyId.id).toString('base64');
330
- const keyEnc = await getAppStateSyncKey(base64Key);
331
- if (!keyEnc) {
332
- throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
333
- }
334
- const result = mutationKeys(keyEnc.keyData);
335
- const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
336
- if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
337
- throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
338
- }
339
- }
340
- // clear memory used up by the mutations
341
- syncd.mutations = [];
342
- }
343
- return { state: newState, mutationMap };
344
- };
345
- exports.decodePatches = decodePatches;
346
- const chatModificationToAppPatch = (mod, jid) => {
347
- const OP = WAProto_1.proto.SyncdMutation.SyncdOperation;
348
- const getMessageRange = (lastMessages) => {
349
- let messageRange;
350
- if (Array.isArray(lastMessages)) {
351
- const lastMsg = lastMessages[lastMessages.length - 1];
352
- messageRange = {
353
- lastMessageTimestamp: lastMsg === null || lastMsg === void 0 ? void 0 : lastMsg.messageTimestamp,
354
- messages: (lastMessages === null || lastMessages === void 0 ? void 0 : lastMessages.length) ? lastMessages.map(m => {
355
- var _a, _b;
356
- if (!((_a = m.key) === null || _a === void 0 ? void 0 : _a.id) || !((_b = m.key) === null || _b === void 0 ? void 0 : _b.remoteJid)) {
357
- throw new boom_1.Boom('Incomplete key', { statusCode: 400, data: m });
358
- }
359
- if ((0, WABinary_1.isJidGroup)(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
360
- throw new boom_1.Boom('Expected not from me message to have participant', { statusCode: 400, data: m });
361
- }
362
- if (!m.messageTimestamp || !(0, generics_1.toNumber)(m.messageTimestamp)) {
363
- throw new boom_1.Boom('Missing timestamp in last message list', { statusCode: 400, data: m });
364
- }
365
- if (m.key.participant) {
366
- m.key.participant = (0, WABinary_1.jidNormalizedUser)(m.key.participant);
367
- }
368
- return m;
369
- }) : undefined
370
- };
371
- }
372
- else {
373
- messageRange = lastMessages;
374
- }
375
- return messageRange;
376
- };
377
- let patch;
378
- if ('mute' in mod) {
379
- patch = {
380
- syncAction: {
381
- muteAction: {
382
- muted: !!mod.mute,
383
- muteEndTimestamp: mod.mute || undefined
384
- }
385
- },
386
- index: ['mute', jid],
387
- type: 'regular_high',
388
- apiVersion: 2,
389
- operation: OP.SET
390
- };
391
- }
392
- else if ('archive' in mod) {
393
- patch = {
394
- syncAction: {
395
- archiveChatAction: {
396
- archived: !!mod.archive,
397
- messageRange: getMessageRange(mod.lastMessages)
398
- }
399
- },
400
- index: ['archive', jid],
401
- type: 'regular_low',
402
- apiVersion: 3,
403
- operation: OP.SET
404
- };
405
- }
406
- else if ('markRead' in mod) {
407
- patch = {
408
- syncAction: {
409
- markChatAsReadAction: {
410
- read: mod.markRead,
411
- messageRange: getMessageRange(mod.lastMessages)
412
- }
413
- },
414
- index: ['markChatAsRead', jid],
415
- type: 'regular_low',
416
- apiVersion: 3,
417
- operation: OP.SET
418
- };
419
- }
420
- else if ('deleteForMe' in mod) {
421
- const { timestamp, key, deleteMedia } = mod.deleteForMe;
422
- patch = {
423
- syncAction: {
424
- deleteMessageForMeAction: {
425
- deleteMedia,
426
- messageTimestamp: timestamp
427
- }
428
- },
429
- index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
430
- type: 'regular_high',
431
- apiVersion: 3,
432
- operation: OP.SET
433
- };
434
- }
435
- else if ('clear' in mod) {
436
- patch = {
437
- syncAction: {
438
- clearChatAction: {} // add message range later
439
- },
440
- index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
441
- type: 'regular_high',
442
- apiVersion: 6,
443
- operation: OP.SET
444
- };
445
- }
446
- else if ('pin' in mod) {
447
- patch = {
448
- syncAction: {
449
- pinAction: {
450
- pinned: !!mod.pin
451
- }
452
- },
453
- index: ['pin_v1', jid],
454
- type: 'regular_low',
455
- apiVersion: 5,
456
- operation: OP.SET
457
- };
458
- }
459
- else if ('contact' in mod) {
460
- patch = {
461
- syncAction: {
462
- contactAction: mod.contact || {}
463
- },
464
- index: ['contact', jid],
465
- type: 'critical_unblock_low',
466
- apiVersion: 2,
467
- operation: mod.contact ? OP.SET : OP.REMOVE
468
- };
469
- }
470
- else if ('star' in mod) {
471
- const key = mod.star.messages[0];
472
- patch = {
473
- syncAction: {
474
- starAction: {
475
- starred: !!mod.star.star
476
- }
477
- },
478
- index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
479
- type: 'regular_low',
480
- apiVersion: 2,
481
- operation: OP.SET
482
- };
483
- }
484
- else if ('delete' in mod) {
485
- patch = {
486
- syncAction: {
487
- deleteChatAction: {
488
- messageRange: getMessageRange(mod.lastMessages),
489
- }
490
- },
491
- index: ['deleteChat', jid, '1'],
492
- type: 'regular_high',
493
- apiVersion: 6,
494
- operation: OP.SET
495
- };
496
- }
497
- else if ('pushNameSetting' in mod) {
498
- patch = {
499
- syncAction: {
500
- pushNameSetting: {
501
- name: mod.pushNameSetting
502
- }
503
- },
504
- index: ['setting_pushName'],
505
- type: 'critical_block',
506
- apiVersion: 1,
507
- operation: OP.SET,
508
- };
509
- }
510
- else if ('addLabel' in mod) {
511
- patch = {
512
- syncAction: {
513
- labelEditAction: {
514
- name: mod.addLabel.name,
515
- color: mod.addLabel.color,
516
- predefinedId: mod.addLabel.predefinedId,
517
- deleted: mod.addLabel.deleted
518
- }
519
- },
520
- index: ['label_edit', mod.addLabel.id],
521
- type: 'regular',
522
- apiVersion: 3,
523
- operation: OP.SET,
524
- };
525
- }
526
- else if ('addChatLabel' in mod) {
527
- patch = {
528
- syncAction: {
529
- labelAssociationAction: {
530
- labeled: true,
531
- }
532
- },
533
- index: [LabelAssociation_1.LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
534
- type: 'regular',
535
- apiVersion: 3,
536
- operation: OP.SET,
537
- };
538
- }
539
- else if ('removeChatLabel' in mod) {
540
- patch = {
541
- syncAction: {
542
- labelAssociationAction: {
543
- labeled: false,
544
- }
545
- },
546
- index: [LabelAssociation_1.LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
547
- type: 'regular',
548
- apiVersion: 3,
549
- operation: OP.SET,
550
- };
551
- }
552
- else if ('addMessageLabel' in mod) {
553
- patch = {
554
- syncAction: {
555
- labelAssociationAction: {
556
- labeled: true,
557
- }
558
- },
559
- index: [
560
- LabelAssociation_1.LabelAssociationType.Message,
561
- mod.addMessageLabel.labelId,
562
- jid,
563
- mod.addMessageLabel.messageId,
564
- '0',
565
- '0'
566
- ],
567
- type: 'regular',
568
- apiVersion: 3,
569
- operation: OP.SET,
570
- };
571
- }
572
- else if ('removeMessageLabel' in mod) {
573
- patch = {
574
- syncAction: {
575
- labelAssociationAction: {
576
- labeled: false,
577
- }
578
- },
579
- index: [
580
- LabelAssociation_1.LabelAssociationType.Message,
581
- mod.removeMessageLabel.labelId,
582
- jid,
583
- mod.removeMessageLabel.messageId,
584
- '0',
585
- '0'
586
- ],
587
- type: 'regular',
588
- apiVersion: 3,
589
- operation: OP.SET,
590
- };
591
- }
592
- else {
593
- throw new boom_1.Boom('not supported');
594
- }
595
- patch.syncAction.timestamp = Date.now();
596
- return patch;
597
- };
598
- exports.chatModificationToAppPatch = chatModificationToAppPatch;
599
- const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
600
- var _a, _b, _c, _d;
601
- const isInitialSync = !!initialSyncOpts;
602
- const accountSettings = initialSyncOpts === null || initialSyncOpts === void 0 ? void 0 : initialSyncOpts.accountSettings;
603
- logger === null || logger === void 0 ? void 0 : logger.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action');
604
- const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction;
605
- if (action === null || action === void 0 ? void 0 : action.muteAction) {
606
- ev.emit('chats.update', [
607
- {
608
- id,
609
- muteEndTime: ((_a = action.muteAction) === null || _a === void 0 ? void 0 : _a.muted)
610
- ? (0, generics_1.toNumber)(action.muteAction.muteEndTimestamp)
611
- : null,
612
- conditional: getChatUpdateConditional(id, undefined)
613
- }
614
- ]);
615
- }
616
- else if ((action === null || action === void 0 ? void 0 : action.archiveChatAction) || type === 'archive' || type === 'unarchive') {
617
- // okay so we've to do some annoying computation here
618
- // when we're initially syncing the app state
619
- // there are a few cases we need to handle
620
- // 1. if the account unarchiveChats setting is true
621
- // a. if the chat is archived, and no further messages have been received -- simple, keep archived
622
- // b. if the chat was archived, and the user received messages from the other person afterwards
623
- // then the chat should be marked unarchved --
624
- // we compare the timestamp of latest message from the other person to determine this
625
- // 2. if the account unarchiveChats setting is false -- then it doesn't matter,
626
- // it'll always take an app state action to mark in unarchived -- which we'll get anyway
627
- const archiveAction = action === null || action === void 0 ? void 0 : action.archiveChatAction;
628
- const isArchived = archiveAction
629
- ? archiveAction.archived
630
- : type === 'archive';
631
- // // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
632
- // // this only applies for the initial sync
633
- // if(isInitialSync && !isArchived) {
634
- // isArchived = false
635
- // }
636
- const msgRange = !(accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats) ? undefined : archiveAction === null || archiveAction === void 0 ? void 0 : archiveAction.messageRange;
637
- // logger?.debug({ chat: id, syncAction }, 'message range archive')
638
- ev.emit('chats.update', [{
639
- id,
640
- archived: isArchived,
641
- conditional: getChatUpdateConditional(id, msgRange)
642
- }]);
643
- }
644
- else if (action === null || action === void 0 ? void 0 : action.markChatAsReadAction) {
645
- const markReadAction = action.markChatAsReadAction;
646
- // basically we don't need to fire an "read" update if the chat is being marked as read
647
- // because the chat is read by default
648
- // this only applies for the initial sync
649
- const isNullUpdate = isInitialSync && markReadAction.read;
650
- ev.emit('chats.update', [{
651
- id,
652
- unreadCount: isNullUpdate ? null : !!(markReadAction === null || markReadAction === void 0 ? void 0 : markReadAction.read) ? 0 : -1,
653
- conditional: getChatUpdateConditional(id, markReadAction === null || markReadAction === void 0 ? void 0 : markReadAction.messageRange)
654
- }]);
655
- }
656
- else if ((action === null || action === void 0 ? void 0 : action.deleteMessageForMeAction) || type === 'deleteMessageForMe') {
657
- ev.emit('messages.delete', {
658
- keys: [
659
- {
660
- remoteJid: id,
661
- id: msgId,
662
- fromMe: fromMe === '1'
663
- }
664
- ]
665
- });
666
- }
667
- else if (action === null || action === void 0 ? void 0 : action.contactAction) {
668
- ev.emit('contacts.upsert', [{ id, name: action.contactAction.fullName }]);
669
- }
670
- else if (action === null || action === void 0 ? void 0 : action.pushNameSetting) {
671
- const name = (_b = action === null || action === void 0 ? void 0 : action.pushNameSetting) === null || _b === void 0 ? void 0 : _b.name;
672
- if (name && (me === null || me === void 0 ? void 0 : me.name) !== name) {
673
- ev.emit('creds.update', { me: { ...me, name } });
674
- }
675
- }
676
- else if (action === null || action === void 0 ? void 0 : action.pinAction) {
677
- ev.emit('chats.update', [{
678
- id,
679
- pinned: ((_c = action.pinAction) === null || _c === void 0 ? void 0 : _c.pinned) ? (0, generics_1.toNumber)(action.timestamp) : null,
680
- conditional: getChatUpdateConditional(id, undefined)
681
- }]);
682
- }
683
- else if (action === null || action === void 0 ? void 0 : action.unarchiveChatsSetting) {
684
- const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
685
- ev.emit('creds.update', { accountSettings: { unarchiveChats } });
686
- logger === null || logger === void 0 ? void 0 : logger.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
687
- if (accountSettings) {
688
- accountSettings.unarchiveChats = unarchiveChats;
689
- }
690
- }
691
- else if ((action === null || action === void 0 ? void 0 : action.starAction) || type === 'star') {
692
- let starred = (_d = action === null || action === void 0 ? void 0 : action.starAction) === null || _d === void 0 ? void 0 : _d.starred;
693
- if (typeof starred !== 'boolean') {
694
- starred = syncAction.index[syncAction.index.length - 1] === '1';
695
- }
696
- ev.emit('messages.update', [
697
- {
698
- key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
699
- update: { starred }
700
- }
701
- ]);
702
- }
703
- else if ((action === null || action === void 0 ? void 0 : action.deleteChatAction) || type === 'deleteChat') {
704
- if (!isInitialSync) {
705
- ev.emit('chats.delete', [id]);
706
- }
707
- }
708
- else if (action === null || action === void 0 ? void 0 : action.labelEditAction) {
709
- const { name, color, deleted, predefinedId } = action.labelEditAction;
710
- ev.emit('labels.edit', {
711
- id,
712
- name: name,
713
- color: color,
714
- deleted: deleted,
715
- predefinedId: predefinedId ? String(predefinedId) : undefined
716
- });
717
- }
718
- else if (action === null || action === void 0 ? void 0 : action.labelAssociationAction) {
719
- ev.emit('labels.association', {
720
- type: action.labelAssociationAction.labeled
721
- ? 'add'
722
- : 'remove',
723
- association: type === LabelAssociation_1.LabelAssociationType.Chat
724
- ? {
725
- type: LabelAssociation_1.LabelAssociationType.Chat,
726
- chatId: syncAction.index[2],
727
- labelId: syncAction.index[1]
728
- }
729
- : {
730
- type: LabelAssociation_1.LabelAssociationType.Message,
731
- chatId: syncAction.index[2],
732
- messageId: syncAction.index[3],
733
- labelId: syncAction.index[1]
734
- }
735
- });
736
- }
737
- else {
738
- logger === null || logger === void 0 ? void 0 : logger.debug({ syncAction, id }, 'unprocessable update');
739
- }
740
- function getChatUpdateConditional(id, msgRange) {
741
- return isInitialSync
742
- ? (data) => {
743
- const chat = data.historySets.chats[id] || data.chatUpserts[id];
744
- if (chat) {
745
- return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
746
- }
747
- }
748
- : undefined;
749
- }
750
- function isValidPatchBasedOnMessageRange(chat, msgRange) {
751
- const lastMsgTimestamp = Number((msgRange === null || msgRange === void 0 ? void 0 : msgRange.lastMessageTimestamp) || (msgRange === null || msgRange === void 0 ? void 0 : msgRange.lastSystemMessageTimestamp) || 0);
752
- const chatLastMsgTimestamp = Number((chat === null || chat === void 0 ? void 0 : chat.lastMessageRecvTimestamp) || 0);
753
- return lastMsgTimestamp >= chatLastMsgTimestamp;
754
- }
755
- };
756
- exports.processSyncAction = processSyncAction;