@vinzsocket/baileys 2.8.30 → 3.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 (102) hide show
  1. package/WAProto/fix-imports.js +7 -16
  2. package/WAProto/index.js +1 -37306
  3. package/lib/Defaults/index.js +37 -33
  4. package/lib/Signal/Group/ciphertext-message.js +6 -2
  5. package/lib/Signal/Group/group-session-builder.js +12 -7
  6. package/lib/Signal/Group/group_cipher.js +18 -13
  7. package/lib/Signal/Group/index.js +77 -12
  8. package/lib/Signal/Group/keyhelper.js +15 -8
  9. package/lib/Signal/Group/queue-job.js +7 -2
  10. package/lib/Signal/Group/sender-chain-key.js +11 -6
  11. package/lib/Signal/Group/sender-key-distribution-message.js +10 -6
  12. package/lib/Signal/Group/sender-key-message.js +14 -9
  13. package/lib/Signal/Group/sender-key-name.js +6 -2
  14. package/lib/Signal/Group/sender-key-record.js +13 -9
  15. package/lib/Signal/Group/sender-key-state.js +10 -6
  16. package/lib/Signal/Group/sender-message-key.js +9 -4
  17. package/lib/Signal/libsignal.js +34 -28
  18. package/lib/Signal/lid-mapping.js +24 -19
  19. package/lib/Socket/Client/index.js +25 -3
  20. package/lib/Socket/Client/types.js +8 -4
  21. package/lib/Socket/Client/websocket.js +16 -11
  22. package/lib/Socket/business.js +38 -34
  23. package/lib/Socket/chats.js +100 -95
  24. package/lib/Socket/communities.js +55 -49
  25. package/lib/Socket/groups.js +56 -51
  26. package/lib/Socket/index.js +9 -6
  27. package/lib/Socket/messages-recv.js +150 -145
  28. package/lib/Socket/messages-send.js +109 -104
  29. package/lib/Socket/mex.js +12 -8
  30. package/lib/Socket/newsletter.js +27 -23
  31. package/lib/Socket/socket.js +111 -107
  32. package/lib/Store/index.js +47 -4
  33. package/lib/Store/make-cache-manager-store.js +17 -11
  34. package/lib/Store/make-in-memory-store.js +31 -29
  35. package/lib/Store/make-ordered-dictionary.js +7 -2
  36. package/lib/Store/object-repository.js +7 -2
  37. package/lib/Types/Auth.js +3 -2
  38. package/lib/Types/Bussines.js +3 -2
  39. package/lib/Types/Call.js +3 -2
  40. package/lib/Types/Chat.js +5 -2
  41. package/lib/Types/Contact.js +3 -2
  42. package/lib/Types/Events.js +1 -2
  43. package/lib/Types/GroupMetadata.js +3 -2
  44. package/lib/Types/Label.js +6 -3
  45. package/lib/Types/LabelAssociation.js +6 -3
  46. package/lib/Types/Message.js +16 -7
  47. package/lib/Types/Newsletter.js +8 -5
  48. package/lib/Types/Product.js +3 -2
  49. package/lib/Types/Signal.js +1 -2
  50. package/lib/Types/Socket.js +2 -3
  51. package/lib/Types/State.js +7 -4
  52. package/lib/Types/USync.js +1 -2
  53. package/lib/Types/index.js +153 -15
  54. package/lib/Utils/auth-utils.js +32 -25
  55. package/lib/Utils/baileys-event-stream.js +21 -15
  56. package/lib/Utils/business.js +71 -61
  57. package/lib/Utils/chat-utils.js +91 -77
  58. package/lib/Utils/crypto.js +54 -32
  59. package/lib/Utils/decode-wa-message.js +46 -39
  60. package/lib/Utils/event-buffer.js +24 -19
  61. package/lib/Utils/extended-messages.js +14 -9
  62. package/lib/Utils/generics.js +100 -64
  63. package/lib/Utils/history.js +30 -23
  64. package/lib/Utils/index.js +234 -22
  65. package/lib/Utils/lid-resolver.js +12 -5
  66. package/lib/Utils/link-preview.js +11 -7
  67. package/lib/Utils/logger.js +8 -4
  68. package/lib/Utils/lt-hash.js +8 -5
  69. package/lib/Utils/make-mutex.js +8 -3
  70. package/lib/Utils/mention.js +12 -4
  71. package/lib/Utils/message-retry-manager.js +10 -6
  72. package/lib/Utils/messages-media.js +127 -95
  73. package/lib/Utils/messages.js +122 -98
  74. package/lib/Utils/noise-handler.js +25 -21
  75. package/lib/Utils/process-message.js +72 -63
  76. package/lib/Utils/signal.js +45 -33
  77. package/lib/Utils/use-multi-file-auth-state.js +24 -20
  78. package/lib/Utils/validate-connection.js +54 -47
  79. package/lib/WABinary/constants.js +9 -6
  80. package/lib/WABinary/decode.js +17 -10
  81. package/lib/WABinary/encode.js +11 -6
  82. package/lib/WABinary/generic-utils.js +31 -17
  83. package/lib/WABinary/index.js +58 -6
  84. package/lib/WABinary/jid-utils.js +36 -20
  85. package/lib/WABinary/types.js +2 -2
  86. package/lib/WAM/BinaryInfo.js +6 -2
  87. package/lib/WAM/constants.js +1 -1
  88. package/lib/WAM/encode.js +16 -12
  89. package/lib/WAM/index.js +36 -4
  90. package/lib/WAUSync/Protocols/USyncContactProtocol.js +9 -5
  91. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +10 -6
  92. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +8 -4
  93. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +8 -4
  94. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +9 -4
  95. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +23 -19
  96. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +6 -2
  97. package/lib/WAUSync/Protocols/index.js +58 -6
  98. package/lib/WAUSync/USyncQuery.js +21 -17
  99. package/lib/WAUSync/USyncUser.js +6 -2
  100. package/lib/WAUSync/index.js +36 -4
  101. package/lib/index.js +112 -12
  102. package/package.json +8 -6
@@ -1,13 +1,17 @@
1
- import { Boom } from '@hapi/boom';
2
- import { proto } from '../../WAProto/index.js';
3
- import { LabelAssociationType } from '../Types/LabelAssociation.js';
4
- import { getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary/index.js';
5
- import { aesDecrypt, aesEncrypt, hkdf, hmacSign } from './crypto.js';
6
- import { toNumber } from './generics.js';
7
- import { LT_HASH_ANTI_TAMPERING } from './lt-hash.js';
8
- import { downloadContentFromMessage } from './messages-media.js';
1
+ Object.defineProperty(exports, "__esModule", {
2
+ value: true
3
+ });
4
+ exports.processSyncAction = exports.newLTHashState = exports.extractSyncdPatches = exports.encodeSyncdPatch = exports.downloadExternalPatch = exports.downloadExternalBlob = exports.decodeSyncdSnapshot = exports.decodeSyncdPatch = exports.decodeSyncdMutations = exports.decodePatches = exports.chatModificationToAppPatch = void 0;
5
+ var _boom = require("@hapi/boom");
6
+ var _index = require("../../WAProto/index.js");
7
+ var _LabelAssociation = require("../Types/LabelAssociation.js");
8
+ var _index2 = require("../WABinary/index.js");
9
+ var _crypto = require("./crypto.js");
10
+ var _generics = require("./generics.js");
11
+ var _ltHash = require("./lt-hash.js");
12
+ var _messagesMedia = require("./messages-media.js");
9
13
  const mutationKeys = async keydata => {
10
- const expanded = await hkdf(keydata, 160, {
14
+ const expanded = await (0, _crypto.hkdf)(keydata, 160, {
11
15
  info: 'WhatsApp Mutation Keys'
12
16
  });
13
17
  return {
@@ -22,10 +26,10 @@ const generateMac = (operation, data, keyId, key) => {
22
26
  const getKeyData = () => {
23
27
  let r;
24
28
  switch (operation) {
25
- case proto.SyncdMutation.SyncdOperation.SET:
29
+ case _index.proto.SyncdMutation.SyncdOperation.SET:
26
30
  r = 0x01;
27
31
  break;
28
- case proto.SyncdMutation.SyncdOperation.REMOVE:
32
+ case _index.proto.SyncdMutation.SyncdOperation.REMOVE:
29
33
  r = 0x02;
30
34
  break;
31
35
  }
@@ -36,7 +40,7 @@ const generateMac = (operation, data, keyId, key) => {
36
40
  const last = Buffer.alloc(8); // 8 bytes
37
41
  last.set([keyData.length], last.length - 1);
38
42
  const total = Buffer.concat([keyData, data, last]);
39
- const hmac = hmacSign(total, key, 'sha512');
43
+ const hmac = (0, _crypto.hmacSign)(total, key, 'sha512');
40
44
  return hmac.slice(0, 32);
41
45
  };
42
46
  const to64BitNetworkOrder = e => {
@@ -61,9 +65,9 @@ const makeLtHashGenerator = ({
61
65
  }) => {
62
66
  const indexMacBase64 = Buffer.from(indexMac).toString('base64');
63
67
  const prevOp = indexValueMap[indexMacBase64];
64
- if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
68
+ if (operation === _index.proto.SyncdMutation.SyncdOperation.REMOVE) {
65
69
  if (!prevOp) {
66
- throw new Boom('tried remove, but no previous op', {
70
+ throw new _boom.Boom('tried remove, but no previous op', {
67
71
  data: {
68
72
  indexMac,
69
73
  valueMac
@@ -85,7 +89,7 @@ const makeLtHashGenerator = ({
85
89
  },
86
90
  finish: async () => {
87
91
  const hashArrayBuffer = new Uint8Array(hash).buffer;
88
- const result = await LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
92
+ const result = await _ltHash.LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
89
93
  const buffer = Buffer.from(result);
90
94
  return {
91
95
  hash: buffer,
@@ -96,18 +100,19 @@ const makeLtHashGenerator = ({
96
100
  };
97
101
  const generateSnapshotMac = (lthash, version, name, key) => {
98
102
  const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]);
99
- return hmacSign(total, key, 'sha256');
103
+ return (0, _crypto.hmacSign)(total, key, 'sha256');
100
104
  };
101
105
  const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
102
106
  const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]);
103
- return hmacSign(total, key);
107
+ return (0, _crypto.hmacSign)(total, key);
104
108
  };
105
- export const newLTHashState = () => ({
109
+ const newLTHashState = () => ({
106
110
  version: 0,
107
111
  hash: Buffer.alloc(128),
108
112
  indexValueMap: {}
109
113
  });
110
- export const encodeSyncdPatch = async ({
114
+ exports.newLTHashState = newLTHashState;
115
+ const encodeSyncdPatch = async ({
111
116
  type,
112
117
  index,
113
118
  syncAction,
@@ -116,7 +121,7 @@ export const encodeSyncdPatch = async ({
116
121
  }, myAppStateKeyId, state, getAppStateSyncKey) => {
117
122
  const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
118
123
  if (!key) {
119
- throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, {
124
+ throw new _boom.Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, {
120
125
  statusCode: 404
121
126
  });
122
127
  }
@@ -128,17 +133,17 @@ export const encodeSyncdPatch = async ({
128
133
  }
129
134
  };
130
135
  const indexBuffer = Buffer.from(JSON.stringify(index));
131
- const dataProto = proto.SyncActionData.create({
136
+ const dataProto = _index.proto.SyncActionData.create({
132
137
  index: indexBuffer,
133
138
  value: syncAction,
134
139
  padding: new Uint8Array(0),
135
140
  version: apiVersion
136
141
  });
137
- const encoded = proto.SyncActionData.encode(dataProto).finish();
142
+ const encoded = _index.proto.SyncActionData.encode(dataProto).finish();
138
143
  const keyValue = await mutationKeys(key.keyData);
139
- const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey);
144
+ const encValue = (0, _crypto.aesEncrypt)(encoded, keyValue.valueEncryptionKey);
140
145
  const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
141
- const indexMac = hmacSign(indexBuffer, keyValue.indexKey);
146
+ const indexMac = (0, _crypto.hmacSign)(indexBuffer, keyValue.indexKey);
142
147
  // update LT hash
143
148
  const generator = makeLtHashGenerator(state);
144
149
  generator.mix({
@@ -179,7 +184,8 @@ export const encodeSyncdPatch = async ({
179
184
  state
180
185
  };
181
186
  };
182
- export const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
187
+ exports.encodeSyncdPatch = encodeSyncdPatch;
188
+ const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
183
189
  const ltGenerator = makeLtHashGenerator(initialState);
184
190
  // indexKey used to HMAC sign record.index.blob
185
191
  // valueEncryptionKey used to AES-256-CBC encrypt record.value.blob[0:-32]
@@ -187,7 +193,7 @@ export const decodeSyncdMutations = async (msgMutations, initialState, getAppSta
187
193
  for (const msgMutation of msgMutations) {
188
194
  // if it's a syncdmutation, get the operation property
189
195
  // otherwise, if it's only a record -- it'll be a SET mutation
190
- const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET;
196
+ const operation = 'operation' in msgMutation ? msgMutation.operation : _index.proto.SyncdMutation.SyncdOperation.SET;
191
197
  const record = 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
192
198
  const key = await getKey(record.keyId.id);
193
199
  const content = Buffer.from(record.value.blob);
@@ -196,15 +202,15 @@ export const decodeSyncdMutations = async (msgMutations, initialState, getAppSta
196
202
  if (validateMacs) {
197
203
  const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
198
204
  if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
199
- throw new Boom('HMAC content verification failed');
205
+ throw new _boom.Boom('HMAC content verification failed');
200
206
  }
201
207
  }
202
- const result = aesDecrypt(encContent, key.valueEncryptionKey);
203
- const syncAction = proto.SyncActionData.decode(result);
208
+ const result = (0, _crypto.aesDecrypt)(encContent, key.valueEncryptionKey);
209
+ const syncAction = _index.proto.SyncActionData.decode(result);
204
210
  if (validateMacs) {
205
- const hmac = hmacSign(syncAction.index, key.indexKey);
211
+ const hmac = (0, _crypto.hmacSign)(syncAction.index, key.indexKey);
206
212
  if (Buffer.compare(hmac, record.index.blob) !== 0) {
207
- throw new Boom('HMAC index verification failed');
213
+ throw new _boom.Boom('HMAC index verification failed');
208
214
  }
209
215
  }
210
216
  const indexStr = Buffer.from(syncAction.index).toString();
@@ -223,7 +229,7 @@ export const decodeSyncdMutations = async (msgMutations, initialState, getAppSta
223
229
  const base64Key = Buffer.from(keyId).toString('base64');
224
230
  const keyEnc = await getAppStateSyncKey(base64Key);
225
231
  if (!keyEnc) {
226
- throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
232
+ throw new _boom.Boom(`failed to find key "${base64Key}" to decode mutation`, {
227
233
  statusCode: 404,
228
234
  data: {
229
235
  msgMutations
@@ -233,12 +239,13 @@ export const decodeSyncdMutations = async (msgMutations, initialState, getAppSta
233
239
  return mutationKeys(keyEnc.keyData);
234
240
  }
235
241
  };
236
- export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
242
+ exports.decodeSyncdMutations = decodeSyncdMutations;
243
+ const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
237
244
  if (validateMacs) {
238
245
  const base64Key = Buffer.from(msg.keyId.id).toString('base64');
239
246
  const mainKeyObj = await getAppStateSyncKey(base64Key);
240
247
  if (!mainKeyObj) {
241
- throw new Boom(`failed to find key "${base64Key}" to decode patch`, {
248
+ throw new _boom.Boom(`failed to find key "${base64Key}" to decode patch`, {
242
249
  statusCode: 404,
243
250
  data: {
244
251
  msg
@@ -247,22 +254,23 @@ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncK
247
254
  }
248
255
  const mainKey = await mutationKeys(mainKeyObj.keyData);
249
256
  const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
250
- const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, toNumber(msg.version.version), name, mainKey.patchMacKey);
257
+ const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, (0, _generics.toNumber)(msg.version.version), name, mainKey.patchMacKey);
251
258
  if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
252
- throw new Boom('Invalid patch mac');
259
+ throw new _boom.Boom('Invalid patch mac');
253
260
  }
254
261
  }
255
262
  const result = await decodeSyncdMutations(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs);
256
263
  return result;
257
264
  };
258
- export const extractSyncdPatches = async (result, options) => {
259
- const syncNode = getBinaryNodeChild(result, 'sync');
260
- const collectionNodes = getBinaryNodeChildren(syncNode, 'collection');
265
+ exports.decodeSyncdPatch = decodeSyncdPatch;
266
+ const extractSyncdPatches = async (result, options) => {
267
+ const syncNode = (0, _index2.getBinaryNodeChild)(result, 'sync');
268
+ const collectionNodes = (0, _index2.getBinaryNodeChildren)(syncNode, 'collection');
261
269
  const final = {};
262
270
  await Promise.all(collectionNodes.map(async collectionNode => {
263
- const patchesNode = getBinaryNodeChild(collectionNode, 'patches');
264
- const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch');
265
- const snapshotNode = getBinaryNodeChild(collectionNode, 'snapshot');
271
+ const patchesNode = (0, _index2.getBinaryNodeChild)(collectionNode, 'patches');
272
+ const patches = (0, _index2.getBinaryNodeChildren)(patchesNode || collectionNode, 'patch');
273
+ const snapshotNode = (0, _index2.getBinaryNodeChild)(collectionNode, 'snapshot');
266
274
  const syncds = [];
267
275
  const name = collectionNode.attrs.name;
268
276
  const hasMorePatches = collectionNode.attrs.has_more_patches === 'true';
@@ -271,9 +279,9 @@ export const extractSyncdPatches = async (result, options) => {
271
279
  if (!Buffer.isBuffer(snapshotNode)) {
272
280
  snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
273
281
  }
274
- const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content);
282
+ const blobRef = _index.proto.ExternalBlobReference.decode(snapshotNode.content);
275
283
  const data = await downloadExternalBlob(blobRef, options);
276
- snapshot = proto.SyncdSnapshot.decode(data);
284
+ snapshot = _index.proto.SyncdSnapshot.decode(data);
277
285
  }
278
286
  for (let {
279
287
  content
@@ -282,7 +290,7 @@ export const extractSyncdPatches = async (result, options) => {
282
290
  if (!Buffer.isBuffer(content)) {
283
291
  content = Buffer.from(Object.values(content));
284
292
  }
285
- const syncd = proto.SyncdPatch.decode(content);
293
+ const syncd = _index.proto.SyncdPatch.decode(content);
286
294
  if (!syncd.version) {
287
295
  syncd.version = {
288
296
  version: +collectionNode.attrs.version + 1
@@ -299,8 +307,9 @@ export const extractSyncdPatches = async (result, options) => {
299
307
  }));
300
308
  return final;
301
309
  };
302
- export const downloadExternalBlob = async (blob, options) => {
303
- const stream = await downloadContentFromMessage(blob, 'md-app-state', {
310
+ exports.extractSyncdPatches = extractSyncdPatches;
311
+ const downloadExternalBlob = async (blob, options) => {
312
+ const stream = await (0, _messagesMedia.downloadContentFromMessage)(blob, 'md-app-state', {
304
313
  options
305
314
  });
306
315
  const bufferArray = [];
@@ -309,14 +318,16 @@ export const downloadExternalBlob = async (blob, options) => {
309
318
  }
310
319
  return Buffer.concat(bufferArray);
311
320
  };
312
- export const downloadExternalPatch = async (blob, options) => {
321
+ exports.downloadExternalBlob = downloadExternalBlob;
322
+ const downloadExternalPatch = async (blob, options) => {
313
323
  const buffer = await downloadExternalBlob(blob, options);
314
- const syncData = proto.SyncdMutations.decode(buffer);
324
+ const syncData = _index.proto.SyncdMutations.decode(buffer);
315
325
  return syncData;
316
326
  };
317
- export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true) => {
327
+ exports.downloadExternalPatch = downloadExternalPatch;
328
+ const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true) => {
318
329
  const newState = newLTHashState();
319
- newState.version = toNumber(snapshot.version.version);
330
+ newState.version = (0, _generics.toNumber)(snapshot.version.version);
320
331
  const mutationMap = {};
321
332
  const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber;
322
333
  const {
@@ -332,12 +343,12 @@ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, mi
332
343
  const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
333
344
  const keyEnc = await getAppStateSyncKey(base64Key);
334
345
  if (!keyEnc) {
335
- throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
346
+ throw new _boom.Boom(`failed to find key "${base64Key}" to decode mutation`);
336
347
  }
337
348
  const result = await mutationKeys(keyEnc.keyData);
338
349
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
339
350
  if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
340
- throw new Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
351
+ throw new _boom.Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
341
352
  }
342
353
  }
343
354
  return {
@@ -345,7 +356,8 @@ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, mi
345
356
  mutationMap
346
357
  };
347
358
  };
348
- export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
359
+ exports.decodeSyncdSnapshot = decodeSyncdSnapshot;
360
+ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
349
361
  const newState = {
350
362
  ...initial,
351
363
  indexValueMap: {
@@ -372,7 +384,7 @@ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, o
372
384
  }, 'downloaded external patch');
373
385
  syncd.mutations?.push(...ref.mutations);
374
386
  }
375
- const patchVersion = toNumber(version.version);
387
+ const patchVersion = (0, _generics.toNumber)(version.version);
376
388
  newState.version = patchVersion;
377
389
  const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
378
390
  const decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, shouldMutate ? mutation => {
@@ -385,12 +397,12 @@ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, o
385
397
  const base64Key = Buffer.from(keyId.id).toString('base64');
386
398
  const keyEnc = await getAppStateSyncKey(base64Key);
387
399
  if (!keyEnc) {
388
- throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
400
+ throw new _boom.Boom(`failed to find key "${base64Key}" to decode mutation`);
389
401
  }
390
402
  const result = await mutationKeys(keyEnc.keyData);
391
403
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
392
404
  if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
393
- throw new Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
405
+ throw new _boom.Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
394
406
  }
395
407
  }
396
408
  // clear memory used up by the mutations
@@ -401,8 +413,9 @@ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, o
401
413
  mutationMap
402
414
  };
403
415
  };
404
- export const chatModificationToAppPatch = (mod, jid) => {
405
- const OP = proto.SyncdMutation.SyncdOperation;
416
+ exports.decodePatches = decodePatches;
417
+ const chatModificationToAppPatch = (mod, jid) => {
418
+ const OP = _index.proto.SyncdMutation.SyncdOperation;
406
419
  const getMessageRange = lastMessages => {
407
420
  let messageRange;
408
421
  if (Array.isArray(lastMessages)) {
@@ -411,25 +424,25 @@ export const chatModificationToAppPatch = (mod, jid) => {
411
424
  lastMessageTimestamp: lastMsg?.messageTimestamp,
412
425
  messages: lastMessages?.length ? lastMessages.map(m => {
413
426
  if (!m.key?.id || !m.key?.remoteJid) {
414
- throw new Boom('Incomplete key', {
427
+ throw new _boom.Boom('Incomplete key', {
415
428
  statusCode: 400,
416
429
  data: m
417
430
  });
418
431
  }
419
- if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
420
- throw new Boom('Expected not from me message to have participant', {
432
+ if ((0, _index2.isJidGroup)(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
433
+ throw new _boom.Boom('Expected not from me message to have participant', {
421
434
  statusCode: 400,
422
435
  data: m
423
436
  });
424
437
  }
425
- if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
426
- throw new Boom('Missing timestamp in last message list', {
438
+ if (!m.messageTimestamp || !(0, _generics.toNumber)(m.messageTimestamp)) {
439
+ throw new _boom.Boom('Missing timestamp in last message list', {
427
440
  statusCode: 400,
428
441
  data: m
429
442
  });
430
443
  }
431
444
  if (m.key.participant) {
432
- m.key.participant = jidNormalizedUser(m.key.participant);
445
+ m.key.participant = (0, _index2.jidNormalizedUser)(m.key.participant);
433
446
  }
434
447
  return m;
435
448
  }) : undefined
@@ -616,7 +629,7 @@ export const chatModificationToAppPatch = (mod, jid) => {
616
629
  labeled: true
617
630
  }
618
631
  },
619
- index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
632
+ index: [_LabelAssociation.LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
620
633
  type: 'regular',
621
634
  apiVersion: 3,
622
635
  operation: OP.SET
@@ -628,7 +641,7 @@ export const chatModificationToAppPatch = (mod, jid) => {
628
641
  labeled: false
629
642
  }
630
643
  },
631
- index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
644
+ index: [_LabelAssociation.LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
632
645
  type: 'regular',
633
646
  apiVersion: 3,
634
647
  operation: OP.SET
@@ -640,7 +653,7 @@ export const chatModificationToAppPatch = (mod, jid) => {
640
653
  labeled: true
641
654
  }
642
655
  },
643
- index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
656
+ index: [_LabelAssociation.LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
644
657
  type: 'regular',
645
658
  apiVersion: 3,
646
659
  operation: OP.SET
@@ -652,18 +665,19 @@ export const chatModificationToAppPatch = (mod, jid) => {
652
665
  labeled: false
653
666
  }
654
667
  },
655
- index: [LabelAssociationType.Message, mod.removeMessageLabel.labelId, jid, mod.removeMessageLabel.messageId, '0', '0'],
668
+ index: [_LabelAssociation.LabelAssociationType.Message, mod.removeMessageLabel.labelId, jid, mod.removeMessageLabel.messageId, '0', '0'],
656
669
  type: 'regular',
657
670
  apiVersion: 3,
658
671
  operation: OP.SET
659
672
  };
660
673
  } else {
661
- throw new Boom('not supported');
674
+ throw new _boom.Boom('not supported');
662
675
  }
663
676
  patch.syncAction.timestamp = Date.now();
664
677
  return patch;
665
678
  };
666
- export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
679
+ exports.chatModificationToAppPatch = chatModificationToAppPatch;
680
+ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
667
681
  const isInitialSync = !!initialSyncOpts;
668
682
  const accountSettings = initialSyncOpts?.accountSettings;
669
683
  logger?.trace({
@@ -679,7 +693,7 @@ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) =
679
693
  if (action?.muteAction) {
680
694
  ev.emit('chats.update', [{
681
695
  id,
682
- muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
696
+ muteEndTime: action.muteAction?.muted ? (0, _generics.toNumber)(action.muteAction.muteEndTimestamp) : null,
683
697
  conditional: getChatUpdateConditional(id, undefined)
684
698
  }]);
685
699
  } else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
@@ -746,7 +760,7 @@ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) =
746
760
  } else if (action?.pinAction) {
747
761
  ev.emit('chats.update', [{
748
762
  id,
749
- pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
763
+ pinned: action.pinAction?.pinned ? (0, _generics.toNumber)(action.timestamp) : null,
750
764
  conditional: getChatUpdateConditional(id, undefined)
751
765
  }]);
752
766
  } else if (action?.unarchiveChatsSetting) {
@@ -796,12 +810,12 @@ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) =
796
810
  } else if (action?.labelAssociationAction) {
797
811
  ev.emit('labels.association', {
798
812
  type: action.labelAssociationAction.labeled ? 'add' : 'remove',
799
- association: type === LabelAssociationType.Chat ? {
800
- type: LabelAssociationType.Chat,
813
+ association: type === _LabelAssociation.LabelAssociationType.Chat ? {
814
+ type: _LabelAssociation.LabelAssociationType.Chat,
801
815
  chatId: syncAction.index[2],
802
816
  labelId: syncAction.index[1]
803
817
  } : {
804
- type: LabelAssociationType.Message,
818
+ type: _LabelAssociation.LabelAssociationType.Message,
805
819
  chatId: syncAction.index[2],
806
820
  messageId: syncAction.index[3],
807
821
  labelId: syncAction.index[1]
@@ -827,4 +841,4 @@ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) =
827
841
  return lastMsgTimestamp >= chatLastMsgTimestamp;
828
842
  }
829
843
  };
830
- //# sourceMappingURL=chat-utils.js.map
844
+ exports.processSyncAction = processSyncAction;
@@ -1,14 +1,36 @@
1
- import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from 'crypto';
1
+ Object.defineProperty(exports, "__esModule", {
2
+ value: true
3
+ });
4
+ exports.Curve = void 0;
5
+ exports.aesDecrypt = aesDecrypt;
6
+ exports.aesDecryptCTR = aesDecryptCTR;
7
+ exports.aesDecryptGCM = aesDecryptGCM;
8
+ exports.aesDecryptWithIV = aesDecryptWithIV;
9
+ exports.aesEncrypWithIV = aesEncrypWithIV;
10
+ exports.aesEncrypt = aesEncrypt;
11
+ exports.aesEncryptCTR = aesEncryptCTR;
12
+ exports.aesEncryptGCM = aesEncryptGCM;
13
+ exports.derivePairingCodeKey = derivePairingCodeKey;
14
+ exports.generateSignalPubKey = void 0;
15
+ exports.hkdf = hkdf;
16
+ exports.hmacSign = hmacSign;
17
+ exports.md5 = md5;
18
+ exports.sha256 = sha256;
19
+ exports.signedKeyPair = void 0;
20
+ var _crypto = require("crypto");
21
+ var libsignal = _interopRequireWildcard(require("libsignal"));
22
+ var _index = require("../Defaults/index.js");
23
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
2
24
  /* @ts-ignore */
3
- import * as libsignal from 'libsignal';
4
- import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
25
+
5
26
  // insure browser & node compatibility
6
27
  const {
7
28
  subtle
8
29
  } = globalThis.crypto;
9
30
  /** prefix version byte to the pub keys, required for some curve crypto functions */
10
- export const generateSignalPubKey = pubKey => pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]);
11
- export const Curve = {
31
+ const generateSignalPubKey = pubKey => pubKey.length === 33 ? pubKey : Buffer.concat([_index.KEY_BUNDLE_TYPE, pubKey]);
32
+ exports.generateSignalPubKey = generateSignalPubKey;
33
+ const Curve = exports.Curve = {
12
34
  generateKeyPair: () => {
13
35
  const {
14
36
  pubKey,
@@ -34,7 +56,7 @@ export const Curve = {
34
56
  }
35
57
  }
36
58
  };
37
- export const signedKeyPair = (identityKeyPair, keyId) => {
59
+ const signedKeyPair = (identityKeyPair, keyId) => {
38
60
  const preKey = Curve.generateKeyPair();
39
61
  const pubKey = generateSignalPubKey(preKey.public);
40
62
  const signature = Curve.sign(identityKeyPair.private, pubKey);
@@ -44,13 +66,14 @@ export const signedKeyPair = (identityKeyPair, keyId) => {
44
66
  keyId
45
67
  };
46
68
  };
69
+ exports.signedKeyPair = signedKeyPair;
47
70
  const GCM_TAG_LENGTH = 128 >> 3;
48
71
  /**
49
72
  * encrypt AES 256 GCM;
50
73
  * where the tag tag is suffixed to the ciphertext
51
74
  * */
52
- export function aesEncryptGCM(plaintext, key, iv, additionalData) {
53
- const cipher = createCipheriv('aes-256-gcm', key, iv);
75
+ function aesEncryptGCM(plaintext, key, iv, additionalData) {
76
+ const cipher = (0, _crypto.createCipheriv)('aes-256-gcm', key, iv);
54
77
  cipher.setAAD(additionalData);
55
78
  return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
56
79
  }
@@ -58,8 +81,8 @@ export function aesEncryptGCM(plaintext, key, iv, additionalData) {
58
81
  * decrypt AES 256 GCM;
59
82
  * where the auth tag is suffixed to the ciphertext
60
83
  * */
61
- export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
62
- const decipher = createDecipheriv('aes-256-gcm', key, iv);
84
+ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
85
+ const decipher = (0, _crypto.createDecipheriv)('aes-256-gcm', key, iv);
63
86
  // decrypt additional adata
64
87
  const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
65
88
  const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
@@ -68,46 +91,46 @@ export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
68
91
  decipher.setAuthTag(tag);
69
92
  return Buffer.concat([decipher.update(enc), decipher.final()]);
70
93
  }
71
- export function aesEncryptCTR(plaintext, key, iv) {
72
- const cipher = createCipheriv('aes-256-ctr', key, iv);
94
+ function aesEncryptCTR(plaintext, key, iv) {
95
+ const cipher = (0, _crypto.createCipheriv)('aes-256-ctr', key, iv);
73
96
  return Buffer.concat([cipher.update(plaintext), cipher.final()]);
74
97
  }
75
- export function aesDecryptCTR(ciphertext, key, iv) {
76
- const decipher = createDecipheriv('aes-256-ctr', key, iv);
98
+ function aesDecryptCTR(ciphertext, key, iv) {
99
+ const decipher = (0, _crypto.createDecipheriv)('aes-256-ctr', key, iv);
77
100
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
78
101
  }
79
102
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
80
- export function aesDecrypt(buffer, key) {
103
+ function aesDecrypt(buffer, key) {
81
104
  return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
82
105
  }
83
106
  /** decrypt AES 256 CBC */
84
- export function aesDecryptWithIV(buffer, key, IV) {
85
- const aes = createDecipheriv('aes-256-cbc', key, IV);
107
+ function aesDecryptWithIV(buffer, key, IV) {
108
+ const aes = (0, _crypto.createDecipheriv)('aes-256-cbc', key, IV);
86
109
  return Buffer.concat([aes.update(buffer), aes.final()]);
87
110
  }
88
111
  // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
89
- export function aesEncrypt(buffer, key) {
90
- const IV = randomBytes(16);
91
- const aes = createCipheriv('aes-256-cbc', key, IV);
112
+ function aesEncrypt(buffer, key) {
113
+ const IV = (0, _crypto.randomBytes)(16);
114
+ const aes = (0, _crypto.createCipheriv)('aes-256-cbc', key, IV);
92
115
  return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
93
116
  }
94
117
  // encrypt AES 256 CBC with a given IV
95
- export function aesEncrypWithIV(buffer, key, IV) {
96
- const aes = createCipheriv('aes-256-cbc', key, IV);
118
+ function aesEncrypWithIV(buffer, key, IV) {
119
+ const aes = (0, _crypto.createCipheriv)('aes-256-cbc', key, IV);
97
120
  return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
98
121
  }
99
122
  // sign HMAC using SHA 256
100
- export function hmacSign(buffer, key, variant = 'sha256') {
101
- return createHmac(variant, key).update(buffer).digest();
123
+ function hmacSign(buffer, key, variant = 'sha256') {
124
+ return (0, _crypto.createHmac)(variant, key).update(buffer).digest();
102
125
  }
103
- export function sha256(buffer) {
104
- return createHash('sha256').update(buffer).digest();
126
+ function sha256(buffer) {
127
+ return (0, _crypto.createHash)('sha256').update(buffer).digest();
105
128
  }
106
- export function md5(buffer) {
107
- return createHash('md5').update(buffer).digest();
129
+ function md5(buffer) {
130
+ return (0, _crypto.createHash)('md5').update(buffer).digest();
108
131
  }
109
132
  // HKDF key expansion
110
- export async function hkdf(buffer, expandedLength, info) {
133
+ async function hkdf(buffer, expandedLength, info) {
111
134
  // Ensure we have a Uint8Array for the key material
112
135
  const inputKeyMaterial = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
113
136
  // Set default values if not provided
@@ -127,7 +150,7 @@ export async function hkdf(buffer, expandedLength, info) {
127
150
  );
128
151
  return Buffer.from(derivedBits);
129
152
  }
130
- export async function derivePairingCodeKey(pairingCode, salt) {
153
+ async function derivePairingCodeKey(pairingCode, salt) {
131
154
  // Convert inputs to formats Web Crypto API can work with
132
155
  const encoder = new TextEncoder();
133
156
  const pairingCodeBuffer = encoder.encode(pairingCode);
@@ -146,5 +169,4 @@ export async function derivePairingCodeKey(pairingCode, salt) {
146
169
  }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
147
170
  );
148
171
  return Buffer.from(derivedBits);
149
- }
150
- //# sourceMappingURL=crypto.js.map
172
+ }