alipclutch-baileys 8.5.3 → 8.5.5

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 (112) hide show
  1. package/engine-requirements.js +10 -0
  2. package/lib/Defaults/baileys-version.json +2 -2
  3. package/lib/Defaults/index.d.ts +7 -16
  4. package/lib/Defaults/index.js +119 -90
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  7. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  8. package/lib/Socket/Client/index.d.ts +3 -2
  9. package/lib/Socket/Client/index.js +3 -2
  10. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  11. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  12. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  13. package/lib/Socket/Client/web-socket-client.js +62 -0
  14. package/lib/Socket/business.d.ts +58 -59
  15. package/lib/Socket/chats.d.ts +230 -45
  16. package/lib/Socket/chats.js +238 -139
  17. package/lib/Socket/groups.d.ts +32 -41
  18. package/lib/Socket/groups.js +23 -38
  19. package/lib/Socket/index.d.ts +64 -63
  20. package/lib/Socket/index.js +3 -2
  21. package/lib/Socket/messages-recv.js +65 -9
  22. package/lib/Socket/messages-send.d.ts +47 -49
  23. package/lib/Socket/messages-send.js +395 -543
  24. package/lib/Socket/newsletter.d.ts +37 -39
  25. package/lib/Socket/newsletter.js +123 -88
  26. package/lib/Socket/registration.d.ts +267 -0
  27. package/lib/Socket/registration.js +166 -0
  28. package/lib/Socket/setup.d.ts +253 -0
  29. package/lib/Socket/setup.js +4 -5
  30. package/lib/Socket/socket.d.ts +43 -270
  31. package/lib/Socket/socket.js +19 -8
  32. package/lib/Socket/usync.d.ts +3 -3
  33. package/lib/Store/index.d.ts +2 -1
  34. package/lib/Store/index.js +3 -1
  35. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  36. package/lib/Store/make-cache-manager-store.js +83 -0
  37. package/lib/Store/make-in-memory-store.d.ts +24 -24
  38. package/lib/Store/make-in-memory-store.js +14 -26
  39. package/lib/Store/make-ordered-dictionary.d.ts +1 -1
  40. package/lib/Store/make-ordered-dictionary.js +2 -2
  41. package/lib/Types/Auth.d.ts +7 -0
  42. package/lib/Types/Call.d.ts +1 -1
  43. package/lib/Types/Chat.d.ts +7 -14
  44. package/lib/Types/Contact.d.ts +1 -5
  45. package/lib/Types/Events.d.ts +2 -44
  46. package/lib/Types/GroupMetadata.d.ts +2 -11
  47. package/lib/Types/Label.js +1 -1
  48. package/lib/Types/LabelAssociation.js +1 -1
  49. package/lib/Types/Message.d.ts +21 -148
  50. package/lib/Types/Message.js +2 -0
  51. package/lib/Types/Newsletter.d.ts +97 -73
  52. package/lib/Types/Newsletter.js +38 -18
  53. package/lib/Types/Socket.d.ts +9 -17
  54. package/lib/Types/index.d.ts +1 -8
  55. package/lib/Types/index.js +2 -2
  56. package/lib/Utils/auth-utils.d.ts +3 -3
  57. package/lib/Utils/auth-utils.js +13 -6
  58. package/lib/Utils/business.js +2 -2
  59. package/lib/Utils/chat-utils.d.ts +16 -15
  60. package/lib/Utils/chat-utils.js +35 -36
  61. package/lib/Utils/crypto.d.ts +16 -15
  62. package/lib/Utils/crypto.js +29 -71
  63. package/lib/Utils/decode-wa-message.d.ts +6 -22
  64. package/lib/Utils/decode-wa-message.js +56 -65
  65. package/lib/Utils/event-buffer.d.ts +2 -2
  66. package/lib/Utils/event-buffer.js +7 -11
  67. package/lib/Utils/generics.d.ts +20 -17
  68. package/lib/Utils/generics.js +75 -95
  69. package/lib/Utils/history.d.ts +0 -4
  70. package/lib/Utils/history.js +6 -4
  71. package/lib/Utils/link-preview.d.ts +2 -2
  72. package/lib/Utils/link-preview.js +1 -34
  73. package/lib/Utils/logger.d.ts +3 -10
  74. package/lib/Utils/lt-hash.d.ts +2 -2
  75. package/lib/Utils/lt-hash.js +6 -6
  76. package/lib/Utils/make-mutex.d.ts +2 -2
  77. package/lib/Utils/messages-media.d.ts +24 -28
  78. package/lib/Utils/messages-media.js +111 -272
  79. package/lib/Utils/messages.d.ts +10 -13
  80. package/lib/Utils/messages.js +51 -336
  81. package/lib/Utils/noise-handler.d.ts +12 -10
  82. package/lib/Utils/noise-handler.js +23 -18
  83. package/lib/Utils/process-message.d.ts +4 -5
  84. package/lib/Utils/process-message.js +25 -108
  85. package/lib/Utils/signal.d.ts +1 -2
  86. package/lib/Utils/signal.js +26 -26
  87. package/lib/Utils/use-multi-file-auth-state.d.ts +1 -0
  88. package/lib/Utils/use-multi-file-auth-state.js +0 -6
  89. package/lib/Utils/validate-connection.d.ts +4 -3
  90. package/lib/Utils/validate-connection.js +1 -1
  91. package/lib/WABinary/constants.d.ts +27 -24
  92. package/lib/WABinary/constants.js +13 -1276
  93. package/lib/WABinary/decode.d.ts +4 -3
  94. package/lib/WABinary/decode.js +13 -26
  95. package/lib/WABinary/encode.d.ts +2 -1
  96. package/lib/WABinary/encode.js +152 -137
  97. package/lib/WABinary/generic-utils.d.ts +4 -1
  98. package/lib/WABinary/generic-utils.js +125 -37
  99. package/lib/WABinary/jid-utils.d.ts +5 -11
  100. package/lib/WABinary/jid-utils.js +5 -28
  101. package/lib/WAM/BinaryInfo.d.ts +11 -2
  102. package/lib/WAM/encode.d.ts +2 -1
  103. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  104. package/lib/index.d.ts +1 -0
  105. package/lib/index.js +15 -27
  106. package/package.json +31 -18
  107. package/WAProto/GenerateStatics.sh +0 -4
  108. package/WAProto/WAProto.proto +0 -4775
  109. package/WAProto/index.d.ts +0 -55057
  110. package/WAProto/index.ts.ts +0 -53473
  111. package/lib/Socket/setup.ts +0 -623
  112. package/lib/WABinary/jid-utils.js.bak +0 -83
@@ -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 WABinary_1 = require("../WABinary");
7
6
  const LabelAssociation_1 = require("../Types/LabelAssociation");
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 = async (keydata) => {
13
- const expanded = await (0, crypto_1.hkdf)(keydata, 160, { info: 'WhatsApp Mutation Keys' });
12
+ const mutationKeys = (keydata) => {
13
+ const expanded = (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: async () => {
72
+ finish: () => {
73
73
  const hashArrayBuffer = new Uint8Array(hash).buffer;
74
- const result = await lt_hash_1.LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
74
+ const result = 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 = await mutationKeys(key.keyData);
117
+ const keyValue = 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, await generator.finish());
124
+ Object.assign(state, 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 await ltGenerator.finish();
187
+ return 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 = await mutationKeys(mainKeyObj.keyData);
205
+ const mainKey = 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 = await mutationKeys(keyEnc.keyData);
289
+ const result = 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 = await mutationKeys(keyEnc.keyData);
335
+ const result = 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,31 +418,25 @@ 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
- }
436
421
  else if ('clear' in mod) {
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
- };
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
+ }
446
440
  }
447
441
  else if ('pin' in mod) {
448
442
  patch = {
@@ -639,7 +633,12 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
639
633
  });
640
634
  }
641
635
  else if (action === null || action === void 0 ? void 0 : action.contactAction) {
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 }]);
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
+ }]);
643
642
  }
644
643
  else if (action === null || action === void 0 ? void 0 : action.pushNameSetting) {
645
644
  const name = (_b = action === null || action === void 0 ? void 0 : action.pushNameSetting) === null || _b === void 0 ? void 0 : _b.name;
@@ -1,9 +1,10 @@
1
+ /// <reference types="node" />
1
2
  import { KeyPair } from '../Types';
2
3
  /** prefix version byte to the pub keys, required for some curve crypto functions */
3
- export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike>;
4
+ export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array | Buffer;
4
5
  export declare const Curve: {
5
6
  generateKeyPair: () => KeyPair;
6
- sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer<any>;
7
+ sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer;
7
8
  sign: (privateKey: Uint8Array, buf: Uint8Array) => any;
8
9
  verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean;
9
10
  };
@@ -16,25 +17,25 @@ export declare const signedKeyPair: (identityKeyPair: KeyPair, keyId: number) =>
16
17
  * encrypt AES 256 GCM;
17
18
  * where the tag tag is suffixed to the ciphertext
18
19
  * */
19
- export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
20
+ export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer;
20
21
  /**
21
22
  * decrypt AES 256 GCM;
22
23
  * where the auth tag is suffixed to the ciphertext
23
24
  * */
24
- export declare function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
25
- export declare function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
26
- export declare function aesDecryptCTR(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
25
+ export declare function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer;
26
+ export declare function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer;
27
+ export declare function aesDecryptCTR(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer;
27
28
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
28
- export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer<ArrayBuffer>;
29
+ export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer;
29
30
  /** decrypt AES 256 CBC */
30
- export declare function aesDecryptWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
31
- export declare function aesEncrypt(buffer: Buffer | Uint8Array, key: Buffer): Buffer<ArrayBuffer>;
32
- export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
33
- export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): Buffer<ArrayBufferLike>;
34
- export declare function sha256(buffer: Buffer): Buffer<ArrayBufferLike>;
35
- export declare function md5(buffer: Buffer): Buffer<ArrayBufferLike>;
31
+ export declare function aesDecryptWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer;
32
+ export declare function aesEncrypt(buffer: Buffer | Uint8Array, key: Buffer): Buffer;
33
+ export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer;
34
+ export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): Buffer;
35
+ export declare function sha256(buffer: Buffer): Buffer;
36
+ export declare function md5(buffer: Buffer): Buffer;
36
37
  export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number, info: {
37
38
  salt?: Buffer;
38
39
  info?: string;
39
- }): Promise<Buffer>;
40
- export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;
40
+ }): Buffer;
41
+ export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Buffer;
@@ -15,43 +15,22 @@ 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 () {
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
- })();
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
+ };
35
28
  Object.defineProperty(exports, "__esModule", { value: true });
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;
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;
50
30
  const crypto_1 = require("crypto");
31
+ const futoin_hkdf_1 = __importDefault(require("futoin-hkdf"));
51
32
  const libsignal = __importStar(require("libsignal"));
52
33
  const Defaults_1 = require("../Defaults");
53
- // insure browser & node compatibility
54
- const { subtle } = globalThis.crypto;
55
34
  /** prefix version byte to the pub keys, required for some curve crypto functions */
56
35
  const generateSignalPubKey = (pubKey) => (pubKey.length === 33
57
36
  ? pubKey
@@ -98,6 +77,7 @@ function aesEncryptGCM(plaintext, key, iv, additionalData) {
98
77
  cipher.setAAD(additionalData);
99
78
  return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
100
79
  }
80
+ exports.aesEncryptGCM = aesEncryptGCM;
101
81
  /**
102
82
  * decrypt AES 256 GCM;
103
83
  * where the auth tag is suffixed to the ciphertext
@@ -112,82 +92,60 @@ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
112
92
  decipher.setAuthTag(tag);
113
93
  return Buffer.concat([decipher.update(enc), decipher.final()]);
114
94
  }
95
+ exports.aesDecryptGCM = aesDecryptGCM;
115
96
  function aesEncryptCTR(plaintext, key, iv) {
116
97
  const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
117
98
  return Buffer.concat([cipher.update(plaintext), cipher.final()]);
118
99
  }
100
+ exports.aesEncryptCTR = aesEncryptCTR;
119
101
  function aesDecryptCTR(ciphertext, key, iv) {
120
102
  const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
121
103
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
122
104
  }
105
+ exports.aesDecryptCTR = aesDecryptCTR;
123
106
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
124
107
  function aesDecrypt(buffer, key) {
125
108
  return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
126
109
  }
110
+ exports.aesDecrypt = aesDecrypt;
127
111
  /** decrypt AES 256 CBC */
128
112
  function aesDecryptWithIV(buffer, key, IV) {
129
113
  const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
130
114
  return Buffer.concat([aes.update(buffer), aes.final()]);
131
115
  }
116
+ exports.aesDecryptWithIV = aesDecryptWithIV;
132
117
  // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
133
118
  function aesEncrypt(buffer, key) {
134
119
  const IV = (0, crypto_1.randomBytes)(16);
135
120
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
136
121
  return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
137
122
  }
123
+ exports.aesEncrypt = aesEncrypt;
138
124
  // encrypt AES 256 CBC with a given IV
139
125
  function aesEncrypWithIV(buffer, key, IV) {
140
126
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
141
127
  return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
142
128
  }
129
+ exports.aesEncrypWithIV = aesEncrypWithIV;
143
130
  // sign HMAC using SHA 256
144
131
  function hmacSign(buffer, key, variant = 'sha256') {
145
132
  return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
146
133
  }
134
+ exports.hmacSign = hmacSign;
147
135
  function sha256(buffer) {
148
136
  return (0, crypto_1.createHash)('sha256').update(buffer).digest();
149
137
  }
138
+ exports.sha256 = sha256;
150
139
  function md5(buffer) {
151
140
  return (0, crypto_1.createHash)('md5').update(buffer).digest();
152
141
  }
142
+ exports.md5 = md5;
153
143
  // HKDF key expansion
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);
144
+ function hkdf(buffer, expandedLength, info) {
145
+ return (0, futoin_hkdf_1.default)(!Buffer.isBuffer(buffer) ? Buffer.from(buffer) : buffer, expandedLength, info);
175
146
  }
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);
147
+ exports.hkdf = hkdf;
148
+ function derivePairingCodeKey(pairingCode, salt) {
149
+ return (0, crypto_1.pbkdf2Sync)(pairingCode, salt, 2 << 16, 32, 'sha256');
193
150
  }
151
+ exports.derivePairingCodeKey = derivePairingCodeKey;
@@ -1,34 +1,18 @@
1
- import { ILogger } from './logger';
2
- import { SignalRepository, WAMessage } from '../Types';
1
+ import { Logger } from 'pino';
2
+ import { proto } from '../../WAProto';
3
+ import { SignalRepository } from '../Types';
3
4
  import { BinaryNode } from '../WABinary';
4
- export declare const NO_MESSAGE_FOUND_ERROR_TEXT = "Message absent from node";
5
- export declare const MISSING_KEYS_ERROR_TEXT = "Key used already or never filled";
6
- export declare const NACK_REASONS: {
7
- ParsingError: number;
8
- UnrecognizedStanza: number;
9
- UnrecognizedStanzaClass: number;
10
- UnrecognizedStanzaType: number;
11
- InvalidProtobuf: number;
12
- InvalidHostedCompanionStanza: number;
13
- MissingMessageSecret: number;
14
- SignalErrorOldCounter: number;
15
- MessageDeletedOnPeer: number;
16
- UnhandledError: number;
17
- UnsupportedAdminRevoke: number;
18
- UnsupportedLIDGroup: number;
19
- DBOperationFailed: number;
20
- };
21
5
  /**
22
6
  * Decode the received node as a message.
23
7
  * @note this will only parse the message, not decrypt it
24
8
  */
25
9
  export declare function decodeMessageNode(stanza: BinaryNode, meId: string, meLid: string): {
26
- fullMessage: WAMessage;
10
+ fullMessage: proto.IWebMessageInfo;
27
11
  author: string;
28
12
  sender: string;
29
13
  };
30
- export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepository, logger: ILogger) => {
31
- fullMessage: WAMessage;
14
+ export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepository, logger: Logger) => {
15
+ fullMessage: proto.IWebMessageInfo;
32
16
  category: string;
33
17
  author: string;
34
18
  decrypt(): Promise<void>;
@@ -1,49 +1,42 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decryptMessageNode = exports.NACK_REASONS = exports.MISSING_KEYS_ERROR_TEXT = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
4
- exports.decodeMessageNode = decodeMessageNode;
3
+ exports.decryptMessageNode = exports.decodeMessageNode = void 0;
5
4
  const boom_1 = require("@hapi/boom");
6
5
  const WAProto_1 = require("../../WAProto");
7
6
  const WABinary_1 = require("../WABinary");
8
7
  const generics_1 = require("./generics");
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
- };
8
+ const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
26
9
  /**
27
10
  * Decode the received node as a message.
28
11
  * @note this will only parse the message, not decrypt it
29
12
  */
30
13
  function decodeMessageNode(stanza, meId, meLid) {
31
- var _a, _b, _c, _d, _e, _f, _g;
14
+ var _a, _b;
32
15
  let msgType;
33
16
  let chatId;
34
17
  let author;
35
18
  const msgId = stanza.attrs.id;
36
19
  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;
39
20
  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;
41
21
  const recipient = stanza.attrs.recipient;
42
22
  const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
43
23
  const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
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)) {
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)) {
47
40
  throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
48
41
  }
49
42
  chatId = recipient;
@@ -62,11 +55,6 @@ function decodeMessageNode(stanza, meId, meLid) {
62
55
  author = participant;
63
56
  chatId = from;
64
57
  }
65
- else if ((0, WABinary_1.isJidNewsletter)(from)) {
66
- msgType = 'newsletter';
67
- author = from;
68
- chatId = from;
69
- }
70
58
  else if ((0, WABinary_1.isJidBroadcast)(from)) {
71
59
  if (!participant) {
72
60
  throw new boom_1.Boom('No participant in group message');
@@ -81,20 +69,21 @@ function decodeMessageNode(stanza, meId, meLid) {
81
69
  chatId = from;
82
70
  author = participant;
83
71
  }
72
+ else if ((0, WABinary_1.isJidNewsLetter)(from)) {
73
+ msgType = 'newsletter';
74
+ author = from;
75
+ chatId = from;
76
+ }
84
77
  else {
85
78
  throw new boom_1.Boom('Unknown message type', { data: stanza });
86
79
  }
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;
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;
89
82
  const key = {
90
83
  remoteJid: chatId,
91
84
  fromMe,
92
85
  id: msgId,
93
- senderPn,
94
- senderLid,
95
- participant,
96
- participantLid,
97
- 'server_id': (_f = stanza.attrs) === null || _f === void 0 ? void 0 : _f.server_id
86
+ participant
98
87
  };
99
88
  const fullMessage = {
100
89
  key,
@@ -103,7 +92,7 @@ function decodeMessageNode(stanza, meId, meLid) {
103
92
  broadcast: (0, WABinary_1.isJidBroadcast)(from)
104
93
  };
105
94
  if (msgType === 'newsletter') {
106
- fullMessage.newsletterServerId = +((_g = stanza.attrs) === null || _g === void 0 ? void 0 : _g.server_id);
95
+ fullMessage.newsletterServerId = +((_b = stanza.attrs) === null || _b === void 0 ? void 0 : _b.server_id);
107
96
  }
108
97
  if (key.fromMe) {
109
98
  fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
@@ -114,6 +103,7 @@ function decodeMessageNode(stanza, meId, meLid) {
114
103
  sender: msgType === 'chat' ? author : chatId
115
104
  };
116
105
  }
106
+ exports.decodeMessageNode = decodeMessageNode;
117
107
  const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
118
108
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
119
109
  return {
@@ -123,17 +113,34 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
123
113
  async decrypt() {
124
114
  var _a;
125
115
  let decryptables = 0;
126
- if (Array.isArray(stanza.content)) {
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)) {
127
137
  for (const { tag, attrs, content } of stanza.content) {
128
138
  if (tag === 'verified_name' && content instanceof Uint8Array) {
129
139
  const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
130
140
  const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
131
141
  fullMessage.verifiedBizName = details.verifiedName;
132
142
  }
133
- if (tag === 'unavailable' && attrs.type === 'view_once') {
134
- fullMessage.key.isViewOnce = true;
135
- }
136
- if (tag !== 'enc' && tag !== 'plaintext') {
143
+ if (tag !== 'enc') {
137
144
  continue;
138
145
  }
139
146
  if (!(content instanceof Uint8Array)) {
@@ -142,7 +149,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
142
149
  decryptables += 1;
143
150
  let msgBuffer;
144
151
  try {
145
- const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
152
+ const e2eType = attrs.type;
146
153
  switch (e2eType) {
147
154
  case 'skmsg':
148
155
  msgBuffer = await repository.decryptGroupMessage({
@@ -160,28 +167,12 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
160
167
  ciphertext: content
161
168
  });
162
169
  break;
163
- case 'plaintext':
164
- msgBuffer = content;
165
- break;
166
- case undefined:
167
- msgBuffer = content;
168
- break;
169
170
  default:
170
171
  throw new Error(`Unknown e2e type: ${e2eType}`);
171
172
  }
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
- }
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);
185
176
  if (fullMessage.message) {
186
177
  Object.assign(fullMessage.message, msg);
187
178
  }
@@ -199,7 +190,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
199
190
  // if nothing was found to decrypt
200
191
  if (!decryptables) {
201
192
  fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
202
- fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
193
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT, JSON.stringify(stanza, generics_1.BufferJSON.replacer)];
203
194
  }
204
195
  }
205
196
  };
@@ -1,5 +1,5 @@
1
+ import { Logger } from 'pino';
1
2
  import { BaileysEventEmitter, BaileysEventMap } from '../Types';
2
- import { ILogger } from './logger';
3
3
  /**
4
4
  * A map that contains a list of all events that have been triggered
5
5
  *
@@ -31,5 +31,5 @@ type BaileysBufferableEventEmitter = BaileysEventEmitter & {
31
31
  * making the data processing more efficient.
32
32
  * @param ev the baileys event emitter
33
33
  */
34
- export declare const makeEventBuffer: (logger: ILogger) => BaileysBufferableEventEmitter;
34
+ export declare const makeEventBuffer: (logger: Logger) => BaileysBufferableEventEmitter;
35
35
  export {};