@hbmodsofc/baileys 1.5.0 → 1.7.6

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