cuki-bailx 1.2.5 → 2.0.7

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 (154) hide show
  1. package/WAProto/AICommon.js +27981 -0
  2. package/WAProto/AICommon.proto +713 -0
  3. package/WAProto/Ephemeral.js +295 -0
  4. package/WAProto/Ephemeral.proto +7 -0
  5. package/WAProto/GenerateStatics.sh +4 -0
  6. package/WAProto/WAProto.proto +4775 -0
  7. package/WAProto/cuki.js +7 -0
  8. package/WAProto/index.js +56886 -17506
  9. package/lib/Defaults/baileys-version.json +2 -2
  10. package/lib/Defaults/index.js +117 -102
  11. package/lib/Socket/Client/index.js +2 -3
  12. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +54 -5
  13. package/lib/Socket/chats.js +97 -90
  14. package/lib/Socket/groups.js +20 -5
  15. package/lib/Socket/index.js +2 -2
  16. package/lib/Socket/messages-recv.js +9 -65
  17. package/lib/Socket/messages-send.js +612 -286
  18. package/lib/Socket/newsletter.js +68 -41
  19. package/lib/Socket/{dugong.js → setup.js} +5 -13
  20. package/lib/Socket/socket.js +58 -32
  21. package/lib/Store/index.js +1 -3
  22. package/lib/Store/make-in-memory-store.js +26 -14
  23. package/lib/Store/make-ordered-dictionary.js +2 -2
  24. package/lib/Types/Label.js +1 -1
  25. package/lib/Types/LabelAssociation.js +1 -1
  26. package/lib/Types/Message.js +0 -2
  27. package/lib/Types/Newsletter.js +3 -17
  28. package/lib/Types/index.js +2 -2
  29. package/lib/Utils/auth-utils.js +6 -13
  30. package/lib/Utils/business.js +2 -2
  31. package/lib/Utils/chat-utils.js +36 -35
  32. package/lib/Utils/crypto.js +71 -29
  33. package/lib/Utils/decode-wa-message.js +65 -56
  34. package/lib/Utils/event-buffer.js +11 -7
  35. package/lib/Utils/generics.js +73 -23
  36. package/lib/Utils/history.js +4 -6
  37. package/lib/Utils/link-preview.js +34 -1
  38. package/lib/Utils/lt-hash.js +6 -6
  39. package/lib/Utils/messages-media.js +479 -161
  40. package/lib/Utils/messages.js +391 -77
  41. package/lib/Utils/noise-handler.js +19 -23
  42. package/lib/Utils/signal.js +47 -36
  43. package/lib/Utils/use-multi-file-auth-state.js +51 -6
  44. package/lib/Utils/validate-connection.js +94 -66
  45. package/lib/WABinary/constants.js +1276 -13
  46. package/lib/WABinary/decode.js +26 -13
  47. package/lib/WABinary/encode.js +39 -17
  48. package/lib/WABinary/generic-utils.js +2 -85
  49. package/lib/WABinary/jid-utils.js +12 -5
  50. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  51. package/lib/index.js +18 -5
  52. package/package.json +100 -105
  53. package/engine-requirements.js +0 -10
  54. package/lib/Defaults/index.d.ts +0 -53
  55. package/lib/Defaults/phonenumber-mcc.json +0 -223
  56. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  57. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  58. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  59. package/lib/Signal/Group/index.d.ts +0 -11
  60. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  61. package/lib/Signal/Group/queue-job.d.ts +0 -1
  62. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  63. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  64. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  65. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  66. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  67. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  68. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  69. package/lib/Signal/libsignal.d.ts +0 -3
  70. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  71. package/lib/Socket/Client/index.d.ts +0 -3
  72. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  73. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  74. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  75. package/lib/Socket/business.d.ts +0 -171
  76. package/lib/Socket/chats.d.ts +0 -80
  77. package/lib/Socket/dugong.d.ts +0 -219
  78. package/lib/Socket/groups.d.ts +0 -115
  79. package/lib/Socket/index.d.ts +0 -173
  80. package/lib/Socket/messages-recv.d.ts +0 -161
  81. package/lib/Socket/messages-send.d.ts +0 -149
  82. package/lib/Socket/newsletter.d.ts +0 -134
  83. package/lib/Socket/registration.d.ts +0 -267
  84. package/lib/Socket/registration.js +0 -166
  85. package/lib/Socket/socket.d.ts +0 -43
  86. package/lib/Socket/socket.js.bak +0 -630
  87. package/lib/Socket/usync.d.ts +0 -36
  88. package/lib/Store/index.d.ts +0 -3
  89. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  90. package/lib/Store/make-cache-manager-store.js +0 -83
  91. package/lib/Store/make-in-memory-store.d.ts +0 -118
  92. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  93. package/lib/Store/object-repository.d.ts +0 -10
  94. package/lib/Types/Auth.d.ts +0 -110
  95. package/lib/Types/Call.d.ts +0 -13
  96. package/lib/Types/Chat.d.ts +0 -102
  97. package/lib/Types/Contact.d.ts +0 -19
  98. package/lib/Types/Events.d.ts +0 -157
  99. package/lib/Types/GroupMetadata.d.ts +0 -55
  100. package/lib/Types/Label.d.ts +0 -35
  101. package/lib/Types/LabelAssociation.d.ts +0 -29
  102. package/lib/Types/Message.d.ts +0 -273
  103. package/lib/Types/Newsletter.d.ts +0 -92
  104. package/lib/Types/Product.d.ts +0 -78
  105. package/lib/Types/Signal.d.ts +0 -57
  106. package/lib/Types/Socket.d.ts +0 -111
  107. package/lib/Types/State.d.ts +0 -27
  108. package/lib/Types/USync.d.ts +0 -25
  109. package/lib/Types/index.d.ts +0 -57
  110. package/lib/Utils/auth-utils.d.ts +0 -18
  111. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  112. package/lib/Utils/business.d.ts +0 -22
  113. package/lib/Utils/chat-utils.d.ts +0 -71
  114. package/lib/Utils/crypto.d.ts +0 -41
  115. package/lib/Utils/decode-wa-message.d.ts +0 -19
  116. package/lib/Utils/event-buffer.d.ts +0 -35
  117. package/lib/Utils/generics.d.ts +0 -92
  118. package/lib/Utils/history.d.ts +0 -15
  119. package/lib/Utils/index.d.ts +0 -17
  120. package/lib/Utils/link-preview.d.ts +0 -21
  121. package/lib/Utils/logger.d.ts +0 -4
  122. package/lib/Utils/lt-hash.d.ts +0 -12
  123. package/lib/Utils/make-mutex.d.ts +0 -7
  124. package/lib/Utils/messages-media.d.ts +0 -116
  125. package/lib/Utils/messages.d.ts +0 -77
  126. package/lib/Utils/noise-handler.d.ts +0 -21
  127. package/lib/Utils/process-message.d.ts +0 -41
  128. package/lib/Utils/signal.d.ts +0 -32
  129. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  130. package/lib/Utils/validate-connection.d.ts +0 -11
  131. package/lib/WABinary/constants.d.ts +0 -27
  132. package/lib/WABinary/decode.d.ts +0 -7
  133. package/lib/WABinary/encode.d.ts +0 -3
  134. package/lib/WABinary/generic-utils.d.ts +0 -16
  135. package/lib/WABinary/index.d.ts +0 -5
  136. package/lib/WABinary/jid-utils.d.ts +0 -31
  137. package/lib/WABinary/types.d.ts +0 -18
  138. package/lib/WAM/BinaryInfo.d.ts +0 -17
  139. package/lib/WAM/constants.d.ts +0 -38
  140. package/lib/WAM/encode.d.ts +0 -3
  141. package/lib/WAM/index.d.ts +0 -3
  142. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  143. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  144. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  145. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  146. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  147. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  148. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  149. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  150. package/lib/WAUSync/USyncUser.d.ts +0 -12
  151. package/lib/WAUSync/index.d.ts +0 -3
  152. package/lib/index.d.ts +0 -12
  153. package/lib/index.js.bak +0 -48
  154. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -17,11 +17,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.DisconnectReason = void 0;
18
18
  __exportStar(require("./Auth"), exports);
19
19
  __exportStar(require("./GroupMetadata"), exports);
20
+ __exportStar(require("./Newsletter"), exports);
20
21
  __exportStar(require("./Chat"), exports);
21
22
  __exportStar(require("./Contact"), exports);
22
23
  __exportStar(require("./State"), exports);
23
24
  __exportStar(require("./Message"), exports);
24
- __exportStar(require("./Newsletter"), exports);
25
25
  __exportStar(require("./Socket"), exports);
26
26
  __exportStar(require("./Events"), exports);
27
27
  __exportStar(require("./Product"), exports);
@@ -39,4 +39,4 @@ var DisconnectReason;
39
39
  DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
40
40
  DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
41
41
  DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
42
- })(DisconnectReason = exports.DisconnectReason || (exports.DisconnectReason = {}));
42
+ })(DisconnectReason || (exports.DisconnectReason = DisconnectReason = {}));
@@ -3,10 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.initAuthCreds = exports.addTransactionCapability = exports.makeCacheableSignalKeyStore = void 0;
6
+ exports.initAuthCreds = exports.addTransactionCapability = void 0;
7
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
7
8
  const crypto_1 = require("crypto");
8
- const node_cache_1 = __importDefault(require("node-cache"));
9
- const uuid_1 = require("uuid");
9
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
10
10
  const Defaults_1 = require("../Defaults");
11
11
  const crypto_2 = require("./crypto");
12
12
  const generics_1 = require("./generics");
@@ -18,7 +18,7 @@ const generics_1 = require("./generics");
18
18
  */
19
19
  function makeCacheableSignalKeyStore(store, logger, _cache) {
20
20
  const cache = _cache || new node_cache_1.default({
21
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
21
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
22
22
  useClones: false,
23
23
  deleteOnExpire: true,
24
24
  });
@@ -39,7 +39,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
39
39
  }
40
40
  }
41
41
  if (idsToFetch.length) {
42
- logger.trace({ items: idsToFetch.length }, 'loading from store');
42
+ logger === null || logger === void 0 ? void 0 : logger.trace({ items: idsToFetch.length }, 'loading from store');
43
43
  const fetched = await store.get(type, idsToFetch);
44
44
  for (const id of idsToFetch) {
45
45
  const item = fetched[id];
@@ -59,7 +59,7 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
59
59
  keys += 1;
60
60
  }
61
61
  }
62
- logger.trace({ keys }, 'updated cache');
62
+ logger === null || logger === void 0 ? void 0 : logger.trace({ keys }, 'updated cache');
63
63
  await store.set(data);
64
64
  },
65
65
  async clear() {
@@ -69,7 +69,6 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
69
69
  }
70
70
  };
71
71
  }
72
- exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
73
72
  /**
74
73
  * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
75
74
  * this allows batch read & write operations & improves the performance of the lib
@@ -191,13 +190,7 @@ const initAuthCreds = () => {
191
190
  accountSettings: {
192
191
  unarchiveChats: false
193
192
  },
194
- // mobile creds
195
- deviceId: Buffer.from((0, uuid_1.v4)().replace(/-/g, ''), 'hex').toString('base64url'),
196
- phoneId: (0, uuid_1.v4)(),
197
- identityId: (0, crypto_1.randomBytes)(20),
198
193
  registered: false,
199
- backupToken: (0, crypto_1.randomBytes)(20),
200
- registration: {},
201
194
  pairingCode: undefined,
202
195
  lastPropHash: undefined,
203
196
  routingInfo: undefined,
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.uploadingNecessaryImages = exports.uploadingNecessaryImagesOfProduct = exports.parseProductNode = exports.toProductNode = exports.parseOrderDetailsNode = exports.parseCollectionsNode = exports.parseCatalogNode = void 0;
3
+ exports.uploadingNecessaryImages = exports.parseProductNode = exports.toProductNode = exports.parseOrderDetailsNode = exports.parseCollectionsNode = exports.parseCatalogNode = void 0;
4
+ exports.uploadingNecessaryImagesOfProduct = uploadingNecessaryImagesOfProduct;
4
5
  const boom_1 = require("@hapi/boom");
5
6
  const crypto_1 = require("crypto");
6
7
  const WABinary_1 = require("../WABinary");
@@ -188,7 +189,6 @@ async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, time
188
189
  };
189
190
  return product;
190
191
  }
191
- exports.uploadingNecessaryImagesOfProduct = uploadingNecessaryImagesOfProduct;
192
192
  /**
193
193
  * Uploads images not already uploaded to WA's servers
194
194
  */
@@ -3,14 +3,14 @@ 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
5
  const WAProto_1 = require("../../WAProto");
6
- const LabelAssociation_1 = require("../Types/LabelAssociation");
7
6
  const WABinary_1 = require("../WABinary");
7
+ const LabelAssociation_1 = require("../Types/LabelAssociation");
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),
@@ -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,
@@ -114,14 +114,14 @@ const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation
114
114
  version: apiVersion
115
115
  });
116
116
  const encoded = WAProto_1.proto.SyncActionData.encode(dataProto).finish();
117
- const keyValue = mutationKeys(key.keyData);
117
+ const keyValue = await mutationKeys(key.keyData);
118
118
  const encValue = (0, crypto_1.aesEncrypt)(encoded, keyValue.valueEncryptionKey);
119
119
  const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
120
120
  const indexMac = (0, crypto_1.hmacSign)(indexBuffer, keyValue.indexKey);
121
121
  // update LT hash
122
122
  const generator = makeLtHashGenerator(state);
123
123
  generator.mix({ indexMac, valueMac, operation });
124
- Object.assign(state, generator.finish());
124
+ Object.assign(state, await generator.finish());
125
125
  state.version += 1;
126
126
  const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
127
127
  const patch = {
@@ -184,7 +184,7 @@ const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncK
184
184
  operation: operation
185
185
  });
186
186
  }
187
- return ltGenerator.finish();
187
+ return await ltGenerator.finish();
188
188
  async function getKey(keyId) {
189
189
  const base64Key = Buffer.from(keyId).toString('base64');
190
190
  const keyEnc = await getAppStateSyncKey(base64Key);
@@ -202,7 +202,7 @@ const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onM
202
202
  if (!mainKeyObj) {
203
203
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
204
204
  }
205
- const mainKey = mutationKeys(mainKeyObj.keyData);
205
+ const mainKey = await mutationKeys(mainKeyObj.keyData);
206
206
  const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
207
207
  const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, (0, generics_1.toNumber)(msg.version.version), name, mainKey.patchMacKey);
208
208
  if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
@@ -286,7 +286,7 @@ const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVe
286
286
  if (!keyEnc) {
287
287
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
288
288
  }
289
- const result = mutationKeys(keyEnc.keyData);
289
+ const result = await mutationKeys(keyEnc.keyData);
290
290
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
291
291
  if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
292
292
  throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
@@ -332,7 +332,7 @@ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options,
332
332
  if (!keyEnc) {
333
333
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
334
334
  }
335
- const result = mutationKeys(keyEnc.keyData);
335
+ const result = await mutationKeys(keyEnc.keyData);
336
336
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
337
337
  if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
338
338
  throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
@@ -418,25 +418,31 @@ const chatModificationToAppPatch = (mod, jid) => {
418
418
  operation: OP.SET
419
419
  };
420
420
  }
421
+ else if ('deleteForMe' in mod) {
422
+ const { timestamp, key, deleteMedia } = mod.deleteForMe;
423
+ patch = {
424
+ syncAction: {
425
+ deleteMessageForMeAction: {
426
+ deleteMedia,
427
+ messageTimestamp: timestamp
428
+ }
429
+ },
430
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
431
+ type: 'regular_high',
432
+ apiVersion: 3,
433
+ operation: OP.SET
434
+ };
435
+ }
421
436
  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
- }
437
+ patch = {
438
+ syncAction: {
439
+ clearChatAction: {} // add message range later
440
+ },
441
+ index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
442
+ type: 'regular_high',
443
+ apiVersion: 6,
444
+ operation: OP.SET
445
+ };
440
446
  }
441
447
  else if ('pin' in mod) {
442
448
  patch = {
@@ -633,12 +639,7 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
633
639
  });
634
640
  }
635
641
  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
+ ev.emit('contacts.upsert', [{ id, name: action.contactAction.fullName, lid: action.contactAction.lidJid || undefined, jid: (0, WABinary_1.isJidUser)(id) ? id : action.contactAction.pnJid }]);
642
643
  }
643
644
  else if (action === null || action === void 0 ? void 0 : action.pushNameSetting) {
644
645
  const name = (_b = action === null || action === void 0 ? void 0 : action.pushNameSetting) === null || _b === void 0 ? void 0 : _b.name;
@@ -15,22 +15,43 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
28
35
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.derivePairingCodeKey = exports.hkdf = exports.md5 = exports.sha256 = exports.hmacSign = exports.aesEncrypWithIV = exports.aesEncrypt = exports.aesDecryptWithIV = exports.aesDecrypt = exports.aesDecryptCTR = exports.aesEncryptCTR = exports.aesDecryptGCM = exports.aesEncryptGCM = exports.signedKeyPair = exports.Curve = exports.generateSignalPubKey = void 0;
36
+ exports.signedKeyPair = exports.Curve = exports.generateSignalPubKey = void 0;
37
+ exports.aesEncryptGCM = aesEncryptGCM;
38
+ exports.aesDecryptGCM = aesDecryptGCM;
39
+ exports.aesEncryptCTR = aesEncryptCTR;
40
+ exports.aesDecryptCTR = aesDecryptCTR;
41
+ exports.aesDecrypt = aesDecrypt;
42
+ exports.aesDecryptWithIV = aesDecryptWithIV;
43
+ exports.aesEncrypt = aesEncrypt;
44
+ exports.aesEncrypWithIV = aesEncrypWithIV;
45
+ exports.hmacSign = hmacSign;
46
+ exports.sha256 = sha256;
47
+ exports.md5 = md5;
48
+ exports.hkdf = hkdf;
49
+ exports.derivePairingCodeKey = derivePairingCodeKey;
30
50
  const crypto_1 = require("crypto");
31
- const futoin_hkdf_1 = __importDefault(require("futoin-hkdf"));
32
51
  const libsignal = __importStar(require("libsignal"));
33
52
  const Defaults_1 = require("../Defaults");
53
+ // insure browser & node compatibility
54
+ const { subtle } = globalThis.crypto;
34
55
  /** prefix version byte to the pub keys, required for some curve crypto functions */
35
56
  const generateSignalPubKey = (pubKey) => (pubKey.length === 33
36
57
  ? pubKey
@@ -77,7 +98,6 @@ function aesEncryptGCM(plaintext, key, iv, additionalData) {
77
98
  cipher.setAAD(additionalData);
78
99
  return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
79
100
  }
80
- exports.aesEncryptGCM = aesEncryptGCM;
81
101
  /**
82
102
  * decrypt AES 256 GCM;
83
103
  * where the auth tag is suffixed to the ciphertext
@@ -92,60 +112,82 @@ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
92
112
  decipher.setAuthTag(tag);
93
113
  return Buffer.concat([decipher.update(enc), decipher.final()]);
94
114
  }
95
- exports.aesDecryptGCM = aesDecryptGCM;
96
115
  function aesEncryptCTR(plaintext, key, iv) {
97
116
  const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
98
117
  return Buffer.concat([cipher.update(plaintext), cipher.final()]);
99
118
  }
100
- exports.aesEncryptCTR = aesEncryptCTR;
101
119
  function aesDecryptCTR(ciphertext, key, iv) {
102
120
  const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
103
121
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
104
122
  }
105
- exports.aesDecryptCTR = aesDecryptCTR;
106
123
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
107
124
  function aesDecrypt(buffer, key) {
108
125
  return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
109
126
  }
110
- exports.aesDecrypt = aesDecrypt;
111
127
  /** decrypt AES 256 CBC */
112
128
  function aesDecryptWithIV(buffer, key, IV) {
113
129
  const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
114
130
  return Buffer.concat([aes.update(buffer), aes.final()]);
115
131
  }
116
- exports.aesDecryptWithIV = aesDecryptWithIV;
117
132
  // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
118
133
  function aesEncrypt(buffer, key) {
119
134
  const IV = (0, crypto_1.randomBytes)(16);
120
135
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
121
136
  return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
122
137
  }
123
- exports.aesEncrypt = aesEncrypt;
124
138
  // encrypt AES 256 CBC with a given IV
125
139
  function aesEncrypWithIV(buffer, key, IV) {
126
140
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
127
141
  return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
128
142
  }
129
- exports.aesEncrypWithIV = aesEncrypWithIV;
130
143
  // sign HMAC using SHA 256
131
144
  function hmacSign(buffer, key, variant = 'sha256') {
132
145
  return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
133
146
  }
134
- exports.hmacSign = hmacSign;
135
147
  function sha256(buffer) {
136
148
  return (0, crypto_1.createHash)('sha256').update(buffer).digest();
137
149
  }
138
- exports.sha256 = sha256;
139
150
  function md5(buffer) {
140
151
  return (0, crypto_1.createHash)('md5').update(buffer).digest();
141
152
  }
142
- exports.md5 = md5;
143
153
  // HKDF key expansion
144
- function hkdf(buffer, expandedLength, info) {
145
- return (0, futoin_hkdf_1.default)(!Buffer.isBuffer(buffer) ? Buffer.from(buffer) : buffer, expandedLength, info);
154
+ async function hkdf(buffer, expandedLength, info) {
155
+ // Ensure we have a Uint8Array for the key material
156
+ const inputKeyMaterial = buffer instanceof Uint8Array
157
+ ? buffer
158
+ : new Uint8Array(buffer);
159
+ // Set default values if not provided
160
+ const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
161
+ const infoBytes = info.info
162
+ ? new TextEncoder().encode(info.info)
163
+ : new Uint8Array(0);
164
+ // Import the input key material
165
+ const importedKey = await subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits']);
166
+ // Derive bits using HKDF
167
+ const derivedBits = await subtle.deriveBits({
168
+ name: 'HKDF',
169
+ hash: 'SHA-256',
170
+ salt: salt,
171
+ info: infoBytes
172
+ }, importedKey, expandedLength * 8 // Convert bytes to bits
173
+ );
174
+ return Buffer.from(derivedBits);
146
175
  }
147
- exports.hkdf = hkdf;
148
- function derivePairingCodeKey(pairingCode, salt) {
149
- return (0, crypto_1.pbkdf2Sync)(pairingCode, salt, 2 << 16, 32, 'sha256');
176
+ async function derivePairingCodeKey(pairingCode, salt) {
177
+ // Convert inputs to formats Web Crypto API can work with
178
+ const encoder = new TextEncoder();
179
+ const pairingCodeBuffer = encoder.encode(pairingCode);
180
+ const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
181
+ // Import the pairing code as key material
182
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits']);
183
+ // Derive bits using PBKDF2 with the same parameters
184
+ // 2 << 16 = 131,072 iterations
185
+ const derivedBits = await subtle.deriveBits({
186
+ name: 'PBKDF2',
187
+ salt: saltBuffer,
188
+ iterations: 2 << 16,
189
+ hash: 'SHA-256'
190
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
191
+ );
192
+ return Buffer.from(derivedBits);
150
193
  }
151
- exports.derivePairingCodeKey = derivePairingCodeKey;
@@ -1,42 +1,49 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decryptMessageNode = exports.decodeMessageNode = void 0;
3
+ exports.decryptMessageNode = exports.NACK_REASONS = exports.MISSING_KEYS_ERROR_TEXT = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
4
+ exports.decodeMessageNode = decodeMessageNode;
4
5
  const boom_1 = require("@hapi/boom");
5
6
  const WAProto_1 = require("../../WAProto");
6
7
  const WABinary_1 = require("../WABinary");
7
8
  const generics_1 = require("./generics");
8
- const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
9
+ exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
10
+ exports.MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
11
+ exports.NACK_REASONS = {
12
+ ParsingError: 487,
13
+ UnrecognizedStanza: 488,
14
+ UnrecognizedStanzaClass: 489,
15
+ UnrecognizedStanzaType: 490,
16
+ InvalidProtobuf: 491,
17
+ InvalidHostedCompanionStanza: 493,
18
+ MissingMessageSecret: 495,
19
+ SignalErrorOldCounter: 496,
20
+ MessageDeletedOnPeer: 499,
21
+ UnhandledError: 500,
22
+ UnsupportedAdminRevoke: 550,
23
+ UnsupportedLIDGroup: 551,
24
+ DBOperationFailed: 552
25
+ };
9
26
  /**
10
27
  * Decode the received node as a message.
11
28
  * @note this will only parse the message, not decrypt it
12
29
  */
13
30
  function decodeMessageNode(stanza, meId, meLid) {
14
- var _a, _b;
31
+ var _a, _b, _c, _d, _e, _f, _g;
15
32
  let msgType;
16
33
  let chatId;
17
34
  let author;
18
35
  const msgId = stanza.attrs.id;
19
36
  const from = stanza.attrs.from;
37
+ const senderPn = (_a = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _a === void 0 ? void 0 : _a.sender_pn;
38
+ const senderLid = (_b = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _b === void 0 ? void 0 : _b.sender_lid;
20
39
  const participant = stanza.attrs.participant;
40
+ const participantLid = (_c = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _c === void 0 ? void 0 : _c.participant_lid;
21
41
  const recipient = stanza.attrs.recipient;
22
42
  const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
23
43
  const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
24
- if ((0, WABinary_1.isJidUser)(from)) {
25
- if (recipient) {
26
- if (!isMe(from)) {
27
- throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
28
- }
29
- chatId = recipient;
30
- }
31
- else {
32
- chatId = from;
33
- }
34
- msgType = 'chat';
35
- author = from;
36
- }
37
- else if ((0, WABinary_1.isLidUser)(from)) {
38
- if (recipient) {
39
- if (!isMeLid(from)) {
44
+ if ((0, WABinary_1.isJidUser)(from) || (0, WABinary_1.isLidUser)(from)) {
45
+ if (recipient && !(0, WABinary_1.isJidMetaAi)(recipient)) {
46
+ if (!isMe(from) && !isMeLid(from)) {
40
47
  throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
41
48
  }
42
49
  chatId = recipient;
@@ -55,6 +62,11 @@ function decodeMessageNode(stanza, meId, meLid) {
55
62
  author = participant;
56
63
  chatId = from;
57
64
  }
65
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
66
+ msgType = 'newsletter';
67
+ author = from;
68
+ chatId = from;
69
+ }
58
70
  else if ((0, WABinary_1.isJidBroadcast)(from)) {
59
71
  if (!participant) {
60
72
  throw new boom_1.Boom('No participant in group message');
@@ -69,21 +81,20 @@ function decodeMessageNode(stanza, meId, meLid) {
69
81
  chatId = from;
70
82
  author = participant;
71
83
  }
72
- else if ((0, WABinary_1.isJidNewsLetter)(from)) {
73
- msgType = 'newsletter';
74
- author = from;
75
- chatId = from;
76
- }
77
84
  else {
78
85
  throw new boom_1.Boom('Unknown message type', { data: stanza });
79
86
  }
80
- const fromMe = (0, WABinary_1.isJidNewsLetter)(from) ? !!((_a = stanza.attrs) === null || _a === void 0 ? void 0 : _a.is_sender) : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
81
- const pushname = stanza.attrs.notify;
87
+ const fromMe = (0, WABinary_1.isJidNewsletter)(from) ? !!((_d = stanza.attrs) === null || _d === void 0 ? void 0 : _d.is_sender) || false : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
88
+ const pushname = (_e = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _e === void 0 ? void 0 : _e.notify;
82
89
  const key = {
83
90
  remoteJid: chatId,
84
91
  fromMe,
85
92
  id: msgId,
86
- participant
93
+ senderPn,
94
+ senderLid,
95
+ participant,
96
+ participantLid,
97
+ 'server_id': (_f = stanza.attrs) === null || _f === void 0 ? void 0 : _f.server_id
87
98
  };
88
99
  const fullMessage = {
89
100
  key,
@@ -92,7 +103,7 @@ function decodeMessageNode(stanza, meId, meLid) {
92
103
  broadcast: (0, WABinary_1.isJidBroadcast)(from)
93
104
  };
94
105
  if (msgType === 'newsletter') {
95
- fullMessage.newsletterServerId = +((_b = stanza.attrs) === null || _b === void 0 ? void 0 : _b.server_id);
106
+ fullMessage.newsletterServerId = +((_g = stanza.attrs) === null || _g === void 0 ? void 0 : _g.server_id);
96
107
  }
97
108
  if (key.fromMe) {
98
109
  fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
@@ -103,7 +114,6 @@ function decodeMessageNode(stanza, meId, meLid) {
103
114
  sender: msgType === 'chat' ? author : chatId
104
115
  };
105
116
  }
106
- exports.decodeMessageNode = decodeMessageNode;
107
117
  const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
108
118
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
109
119
  return {
@@ -113,34 +123,17 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
113
123
  async decrypt() {
114
124
  var _a;
115
125
  let decryptables = 0;
116
- async function processSenderKeyDistribution(msg) {
117
- if (msg.senderKeyDistributionMessage) {
118
- try {
119
- await repository.processSenderKeyDistributionMessage({
120
- authorJid: author,
121
- item: msg.senderKeyDistributionMessage
122
- });
123
- }
124
- catch (err) {
125
- logger.error({ key: fullMessage.key, err }, 'failed to process senderKeyDistribution');
126
- }
127
- }
128
- }
129
- if ((0, WABinary_1.isJidNewsLetter)(fullMessage.key.remoteJid)) {
130
- const node = (0, WABinary_1.getBinaryNodeChild)(stanza, 'plaintext');
131
- const msg = WAProto_1.proto.Message.decode(node === null || node === void 0 ? void 0 : node.content);
132
- await processSenderKeyDistribution(msg);
133
- fullMessage.message = msg;
134
- decryptables += 1;
135
- }
136
- else if (Array.isArray(stanza.content)) {
126
+ if (Array.isArray(stanza.content)) {
137
127
  for (const { tag, attrs, content } of stanza.content) {
138
128
  if (tag === 'verified_name' && content instanceof Uint8Array) {
139
129
  const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
140
130
  const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
141
131
  fullMessage.verifiedBizName = details.verifiedName;
142
132
  }
143
- if (tag !== 'enc') {
133
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
134
+ fullMessage.key.isViewOnce = true;
135
+ }
136
+ if (tag !== 'enc' && tag !== 'plaintext') {
144
137
  continue;
145
138
  }
146
139
  if (!(content instanceof Uint8Array)) {
@@ -149,7 +142,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
149
142
  decryptables += 1;
150
143
  let msgBuffer;
151
144
  try {
152
- const e2eType = attrs.type;
145
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
153
146
  switch (e2eType) {
154
147
  case 'skmsg':
155
148
  msgBuffer = await repository.decryptGroupMessage({
@@ -167,12 +160,28 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
167
160
  ciphertext: content
168
161
  });
169
162
  break;
163
+ case 'plaintext':
164
+ msgBuffer = content;
165
+ break;
166
+ case undefined:
167
+ msgBuffer = content;
168
+ break;
170
169
  default:
171
170
  throw new Error(`Unknown e2e type: ${e2eType}`);
172
171
  }
173
- let msg = WAProto_1.proto.Message.decode((0, generics_1.unpadRandomMax16)(msgBuffer));
174
- msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
175
- await processSenderKeyDistribution(msg);
172
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
173
+ msg = ((_a = msg === null || msg === void 0 ? void 0 : msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
174
+ if (msg.senderKeyDistributionMessage) {
175
+ try {
176
+ await repository.processSenderKeyDistributionMessage({
177
+ authorJid: author,
178
+ item: msg.senderKeyDistributionMessage
179
+ });
180
+ }
181
+ catch (err) {
182
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
183
+ }
184
+ }
176
185
  if (fullMessage.message) {
177
186
  Object.assign(fullMessage.message, msg);
178
187
  }
@@ -190,7 +199,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
190
199
  // if nothing was found to decrypt
191
200
  if (!decryptables) {
192
201
  fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
193
- fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT, JSON.stringify(stanza, generics_1.BufferJSON.replacer)];
202
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
194
203
  }
195
204
  }
196
205
  };
@@ -176,6 +176,9 @@ function append(data, historyCache, event, eventData, logger) {
176
176
  }
177
177
  }
178
178
  data.historySets.empty = false;
179
+ data.historySets.syncType = eventData.syncType;
180
+ data.historySets.progress = eventData.progress;
181
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
179
182
  data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
180
183
  break;
181
184
  case 'chats.upsert':
@@ -442,7 +445,10 @@ function consolidateEvents(data) {
442
445
  chats: Object.values(data.historySets.chats),
443
446
  messages: Object.values(data.historySets.messages),
444
447
  contacts: Object.values(data.historySets.contacts),
445
- isLatest: data.historySets.isLatest
448
+ syncType: data.historySets.syncType,
449
+ progress: data.historySets.progress,
450
+ isLatest: data.historySets.isLatest,
451
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
446
452
  };
447
453
  }
448
454
  const chatUpsertList = Object.values(data.chatUpserts);
@@ -496,12 +502,10 @@ function consolidateEvents(data) {
496
502
  return map;
497
503
  }
498
504
  function concatChats(a, b) {
499
- if (b.unreadCount === null) {
500
- // neutralize unread counter
501
- if (a.unreadCount < 0) {
502
- a.unreadCount = undefined;
503
- b.unreadCount = undefined;
504
- }
505
+ if (b.unreadCount === null && // neutralize unread counter
506
+ a.unreadCount < 0) {
507
+ a.unreadCount = undefined;
508
+ b.unreadCount = undefined;
505
509
  }
506
510
  if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
507
511
  b = { ...b };