@baileys-md/baileys 11.0.3 → 11.1.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 (122) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1 -1
  3. package/WAProto/index.js +4182 -13516
  4. package/WASignalGroup/GroupProtocol.js +1697 -0
  5. package/WASignalGroup/ciphertext_message.js +16 -0
  6. package/WASignalGroup/group_cipher.js +120 -0
  7. package/WASignalGroup/group_session_builder.js +46 -0
  8. package/WASignalGroup/index.js +5 -0
  9. package/WASignalGroup/keyhelper.js +21 -0
  10. package/WASignalGroup/protobufs.js +3 -0
  11. package/WASignalGroup/queue_job.js +69 -0
  12. package/WASignalGroup/sender_chain_key.js +50 -0
  13. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  14. package/WASignalGroup/sender_key_message.js +92 -0
  15. package/WASignalGroup/sender_key_name.js +70 -0
  16. package/WASignalGroup/sender_key_record.js +56 -0
  17. package/WASignalGroup/sender_key_state.js +129 -0
  18. package/{lib/Signal/Group/sender-message-key.js → WASignalGroup/sender_message_key.js} +16 -4
  19. package/lib/Defaults/baileys-version.json +3 -0
  20. package/lib/Defaults/index.js +71 -52
  21. package/lib/Defaults/{phonenumber-mcc.js → phonenumber-mcc.json} +1 -1
  22. package/lib/Signal/libsignal.js +61 -41
  23. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  24. package/lib/Socket/Client/index.js +19 -3
  25. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  26. package/lib/Socket/Client/web-socket-client.js +62 -0
  27. package/lib/Socket/business.js +42 -37
  28. package/lib/Socket/chats.js +187 -194
  29. package/lib/Socket/groups.js +90 -87
  30. package/lib/Socket/index.js +8 -7
  31. package/lib/Socket/messages-recv.js +335 -360
  32. package/lib/Socket/messages-send.js +279 -156
  33. package/lib/Socket/newsletter.js +213 -144
  34. package/lib/Socket/registration.js +166 -0
  35. package/lib/Socket/socket.js +161 -128
  36. package/lib/Socket/usync.js +26 -19
  37. package/lib/Store/index.js +8 -0
  38. package/lib/Store/make-cache-manager-store.js +83 -0
  39. package/lib/{Utils → Store}/make-in-memory-store.js +27 -19
  40. package/lib/Store/make-mongo-store.js +567 -0
  41. package/lib/{Utils → Store}/make-ordered-dictionary.js +5 -2
  42. package/lib/{Utils → Store}/object-repository.js +4 -1
  43. package/lib/Types/Auth.js +2 -2
  44. package/lib/Types/Call.js +2 -2
  45. package/lib/Types/Chat.js +4 -8
  46. package/lib/Types/Contact.js +2 -2
  47. package/lib/Types/Events.js +2 -2
  48. package/lib/Types/GroupMetadata.js +2 -2
  49. package/lib/Types/Label.js +5 -3
  50. package/lib/Types/LabelAssociation.js +5 -3
  51. package/lib/Types/Message.js +7 -7
  52. package/lib/Types/Newsletter.js +17 -30
  53. package/lib/Types/Product.js +2 -2
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.js +2 -3
  56. package/lib/Types/State.js +2 -2
  57. package/lib/Types/USync.js +2 -2
  58. package/lib/Types/index.js +31 -15
  59. package/lib/Utils/auth-utils.js +47 -31
  60. package/lib/Utils/baileys-event-stream.js +22 -15
  61. package/lib/Utils/business.js +69 -66
  62. package/lib/Utils/chat-utils.js +195 -200
  63. package/lib/Utils/crypto.js +85 -70
  64. package/lib/Utils/decode-wa-message.js +51 -46
  65. package/lib/Utils/event-buffer.js +46 -36
  66. package/lib/Utils/generics.js +188 -116
  67. package/lib/Utils/history.js +46 -37
  68. package/lib/Utils/index.js +33 -19
  69. package/lib/Utils/link-preview.js +55 -14
  70. package/lib/Utils/logger.js +7 -3
  71. package/lib/Utils/lt-hash.js +26 -23
  72. package/lib/Utils/make-mutex.js +10 -7
  73. package/lib/Utils/messages-media.js +368 -239
  74. package/lib/Utils/messages.js +510 -278
  75. package/lib/Utils/noise-handler.js +31 -22
  76. package/lib/Utils/process-message.js +148 -144
  77. package/lib/Utils/signal.js +64 -71
  78. package/lib/Utils/use-multi-file-auth-state.js +32 -14
  79. package/lib/Utils/validate-connection.js +115 -72
  80. package/lib/WABinary/constants.js +20 -1281
  81. package/lib/WABinary/decode.js +52 -15
  82. package/lib/WABinary/encode.js +48 -14
  83. package/lib/WABinary/generic-utils.js +39 -31
  84. package/lib/WABinary/index.js +21 -6
  85. package/lib/WABinary/jid-utils.js +40 -23
  86. package/lib/WABinary/types.js +2 -2
  87. package/lib/WAM/BinaryInfo.js +5 -2
  88. package/lib/WAM/constants.js +2366 -2257
  89. package/lib/WAM/encode.js +21 -17
  90. package/lib/WAM/index.js +19 -4
  91. package/lib/WAUSync/Protocols/USyncContactProtocol.js +11 -8
  92. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  93. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  94. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  95. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  96. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +6 -3
  97. package/lib/WAUSync/Protocols/index.js +20 -5
  98. package/lib/WAUSync/USyncQuery.js +32 -34
  99. package/lib/WAUSync/USyncUser.js +5 -2
  100. package/lib/WAUSync/index.js +19 -4
  101. package/lib/index.js +33 -11
  102. package/package.json +61 -21
  103. package/WAProto/GenerateStatics.sh +0 -3
  104. package/WAProto/WAProto.proto +0 -4633
  105. package/WAProto/fix-imports.js +0 -29
  106. package/lib/Defaults/baileys-version.js +0 -1
  107. package/lib/Signal/Group/ciphertext-message.js +0 -12
  108. package/lib/Signal/Group/group-session-builder.js +0 -30
  109. package/lib/Signal/Group/group_cipher.js +0 -94
  110. package/lib/Signal/Group/index.js +0 -12
  111. package/lib/Signal/Group/keyhelper.js +0 -19
  112. package/lib/Signal/Group/queue-job.js +0 -54
  113. package/lib/Signal/Group/sender-chain-key.js +0 -32
  114. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  115. package/lib/Signal/Group/sender-key-message.js +0 -67
  116. package/lib/Signal/Group/sender-key-name.js +0 -48
  117. package/lib/Signal/Group/sender-key-record.js +0 -50
  118. package/lib/Signal/Group/sender-key-state.js +0 -96
  119. package/lib/Socket/Client/types.js +0 -11
  120. package/lib/Socket/Client/websocket.js +0 -50
  121. package/lib/Socket/communities.js +0 -351
  122. package/lib/Socket/mex.js +0 -42
@@ -1,10 +1,42 @@
1
- import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, subtle } from 'crypto';
2
- /* @ts-ignore */
3
- import * as libsignal from 'libsignal';
4
- import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
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
+ };
28
+ 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;
30
+ const crypto_1 = require("crypto");
31
+ const futoin_hkdf_1 = __importDefault(require("futoin-hkdf"));
32
+ const libsignal = __importStar(require("libsignal"));
33
+ const Defaults_1 = require("../Defaults");
5
34
  /** prefix version byte to the pub keys, required for some curve crypto functions */
6
- export const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]);
7
- export const Curve = {
35
+ const generateSignalPubKey = (pubKey) => (pubKey.length === 33
36
+ ? pubKey
37
+ : Buffer.concat([Defaults_1.KEY_BUNDLE_TYPE, pubKey]));
38
+ exports.generateSignalPubKey = generateSignalPubKey;
39
+ exports.Curve = {
8
40
  generateKeyPair: () => {
9
41
  const { pubKey, privKey } = libsignal.curve.generateKeyPair();
10
42
  return {
@@ -14,13 +46,13 @@ export const Curve = {
14
46
  };
15
47
  },
16
48
  sharedKey: (privateKey, publicKey) => {
17
- const shared = libsignal.curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey);
49
+ const shared = libsignal.curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
18
50
  return Buffer.from(shared);
19
51
  },
20
- sign: (privateKey, buf) => libsignal.curve.calculateSignature(privateKey, buf),
52
+ sign: (privateKey, buf) => (libsignal.curve.calculateSignature(privateKey, buf)),
21
53
  verify: (pubKey, message, signature) => {
22
54
  try {
23
- libsignal.curve.verifySignature(generateSignalPubKey(pubKey), message, signature);
55
+ libsignal.curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
24
56
  return true;
25
57
  }
26
58
  catch (error) {
@@ -28,28 +60,30 @@ export const Curve = {
28
60
  }
29
61
  }
30
62
  };
31
- export const signedKeyPair = (identityKeyPair, keyId) => {
32
- const preKey = Curve.generateKeyPair();
33
- const pubKey = generateSignalPubKey(preKey.public);
34
- const signature = Curve.sign(identityKeyPair.private, pubKey);
63
+ const signedKeyPair = (identityKeyPair, keyId) => {
64
+ const preKey = exports.Curve.generateKeyPair();
65
+ const pubKey = (0, exports.generateSignalPubKey)(preKey.public);
66
+ const signature = exports.Curve.sign(identityKeyPair.private, pubKey);
35
67
  return { keyPair: preKey, signature, keyId };
36
68
  };
69
+ exports.signedKeyPair = signedKeyPair;
37
70
  const GCM_TAG_LENGTH = 128 >> 3;
38
71
  /**
39
72
  * encrypt AES 256 GCM;
40
73
  * where the tag tag is suffixed to the ciphertext
41
74
  * */
42
- export function aesEncryptGCM(plaintext, key, iv, additionalData) {
43
- const cipher = createCipheriv('aes-256-gcm', key, iv);
75
+ function aesEncryptGCM(plaintext, key, iv, additionalData) {
76
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
44
77
  cipher.setAAD(additionalData);
45
78
  return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
46
79
  }
80
+ exports.aesEncryptGCM = aesEncryptGCM;
47
81
  /**
48
82
  * decrypt AES 256 GCM;
49
83
  * where the auth tag is suffixed to the ciphertext
50
84
  * */
51
- export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
52
- const decipher = createDecipheriv('aes-256-gcm', key, iv);
85
+ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
86
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
53
87
  // decrypt additional adata
54
88
  const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
55
89
  const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
@@ -58,79 +92,60 @@ export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
58
92
  decipher.setAuthTag(tag);
59
93
  return Buffer.concat([decipher.update(enc), decipher.final()]);
60
94
  }
61
- export function aesEncryptCTR(plaintext, key, iv) {
62
- const cipher = createCipheriv('aes-256-ctr', key, iv);
95
+ exports.aesDecryptGCM = aesDecryptGCM;
96
+ function aesEncryptCTR(plaintext, key, iv) {
97
+ const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
63
98
  return Buffer.concat([cipher.update(plaintext), cipher.final()]);
64
99
  }
65
- export function aesDecryptCTR(ciphertext, key, iv) {
66
- const decipher = createDecipheriv('aes-256-ctr', key, iv);
100
+ exports.aesEncryptCTR = aesEncryptCTR;
101
+ function aesDecryptCTR(ciphertext, key, iv) {
102
+ const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
67
103
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
68
104
  }
105
+ exports.aesDecryptCTR = aesDecryptCTR;
69
106
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
70
- export function aesDecrypt(buffer, key) {
107
+ function aesDecrypt(buffer, key) {
71
108
  return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
72
109
  }
110
+ exports.aesDecrypt = aesDecrypt;
73
111
  /** decrypt AES 256 CBC */
74
- export function aesDecryptWithIV(buffer, key, IV) {
75
- const aes = createDecipheriv('aes-256-cbc', key, IV);
112
+ function aesDecryptWithIV(buffer, key, IV) {
113
+ const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
76
114
  return Buffer.concat([aes.update(buffer), aes.final()]);
77
115
  }
116
+ exports.aesDecryptWithIV = aesDecryptWithIV;
78
117
  // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
79
- export function aesEncrypt(buffer, key) {
80
- const IV = randomBytes(16);
81
- const aes = createCipheriv('aes-256-cbc', key, IV);
118
+ function aesEncrypt(buffer, key) {
119
+ const IV = (0, crypto_1.randomBytes)(16);
120
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
82
121
  return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
83
122
  }
123
+ exports.aesEncrypt = aesEncrypt;
84
124
  // encrypt AES 256 CBC with a given IV
85
- export function aesEncrypWithIV(buffer, key, IV) {
86
- const aes = createCipheriv('aes-256-cbc', key, IV);
125
+ function aesEncrypWithIV(buffer, key, IV) {
126
+ const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
87
127
  return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
88
128
  }
129
+ exports.aesEncrypWithIV = aesEncrypWithIV;
89
130
  // sign HMAC using SHA 256
90
- export function hmacSign(buffer, key, variant = 'sha256') {
91
- return createHmac(variant, key).update(buffer).digest();
131
+ function hmacSign(buffer, key, variant = 'sha256') {
132
+ return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
92
133
  }
93
- export function sha256(buffer) {
94
- return createHash('sha256').update(buffer).digest();
134
+ exports.hmacSign = hmacSign;
135
+ function sha256(buffer) {
136
+ return (0, crypto_1.createHash)('sha256').update(buffer).digest();
95
137
  }
96
- export function md5(buffer) {
97
- return createHash('md5').update(buffer).digest();
138
+ exports.sha256 = sha256;
139
+ function md5(buffer) {
140
+ return (0, crypto_1.createHash)('md5').update(buffer).digest();
98
141
  }
142
+ exports.md5 = md5;
99
143
  // HKDF key expansion
100
- export async function hkdf(buffer, expandedLength, info) {
101
- // Ensure we have a Uint8Array for the key material
102
- const inputKeyMaterial = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
103
- // Set default values if not provided
104
- const salt = info.salt ? new Uint8Array(info.salt) : new Uint8Array(0);
105
- const infoBytes = info.info ? new TextEncoder().encode(info.info) : new Uint8Array(0);
106
- // Import the input key material
107
- const importedKey = await subtle.importKey('raw', inputKeyMaterial, { name: 'HKDF' }, false, ['deriveBits']);
108
- // Derive bits using HKDF
109
- const derivedBits = await subtle.deriveBits({
110
- name: 'HKDF',
111
- hash: 'SHA-256',
112
- salt: salt,
113
- info: infoBytes
114
- }, importedKey, expandedLength * 8 // Convert bytes to bits
115
- );
116
- 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);
117
146
  }
118
- export async function derivePairingCodeKey(pairingCode, salt) {
119
- // Convert inputs to formats Web Crypto API can work with
120
- const encoder = new TextEncoder();
121
- const pairingCodeBuffer = encoder.encode(pairingCode);
122
- const saltBuffer = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
123
- // Import the pairing code as key material
124
- const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits']);
125
- // Derive bits using PBKDF2 with the same parameters
126
- // 2 << 16 = 131,072 iterations
127
- const derivedBits = await subtle.deriveBits({
128
- name: 'PBKDF2',
129
- salt: saltBuffer,
130
- iterations: 2 << 16,
131
- hash: 'SHA-256'
132
- }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
133
- );
134
- 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');
135
150
  }
136
- //# sourceMappingURL=crypto.js.map
151
+ exports.derivePairingCodeKey = derivePairingCodeKey;
@@ -1,10 +1,14 @@
1
- import { Boom } from '@hapi/boom';
2
- import { proto } from '../../WAProto/index.js';
3
- import { areJidsSameUser, isJidBroadcast, isJidGroup, isJidMetaIa, isJidNewsletter, isJidStatusBroadcast, isJidUser, isLidUser } from '../WABinary/index.js';
4
- import { unpadRandomMax16 } from './generics.js';
5
- export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
6
- export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
7
- export const NACK_REASONS = {
1
+ "use strict";
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;
5
+ const boom_1 = require("@hapi/boom");
6
+ const WAProto_1 = require("../../WAProto");
7
+ const WABinary_1 = require("../WABinary");
8
+ 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 = {
8
12
  ParsingError: 487,
9
13
  UnrecognizedStanza: 488,
10
14
  UnrecognizedStanzaClass: 489,
@@ -23,7 +27,8 @@ export const NACK_REASONS = {
23
27
  * Decode the received node as a message.
24
28
  * @note this will only parse the message, not decrypt it
25
29
  */
26
- export function decodeMessageNode(stanza, meId, meLid) {
30
+ function decodeMessageNode(stanza, meId, meLid) {
31
+ var _a, _b, _c, _d;
27
32
  let msgType;
28
33
  let chatId;
29
34
  let author;
@@ -31,12 +36,12 @@ export function decodeMessageNode(stanza, meId, meLid) {
31
36
  const from = stanza.attrs.from;
32
37
  const participant = stanza.attrs.participant;
33
38
  const recipient = stanza.attrs.recipient;
34
- const isMe = (jid) => areJidsSameUser(jid, meId);
35
- const isMeLid = (jid) => areJidsSameUser(jid, meLid);
36
- if (isJidUser(from) || isLidUser(from)) {
37
- if (recipient && !isJidMetaIa(recipient)) {
39
+ const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
40
+ const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
41
+ if ((0, WABinary_1.isJidUser)(from) || (0, WABinary_1.isLidUser)(from)) {
42
+ if (recipient && !(0, WABinary_1.isJidMetaIa)(recipient)) {
38
43
  if (!isMe(from) && !isMeLid(from)) {
39
- throw new Boom('receipient present, but msg not from me', { data: stanza });
44
+ throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
40
45
  }
41
46
  chatId = recipient;
42
47
  }
@@ -46,20 +51,25 @@ export function decodeMessageNode(stanza, meId, meLid) {
46
51
  msgType = 'chat';
47
52
  author = from;
48
53
  }
49
- else if (isJidGroup(from)) {
54
+ else if ((0, WABinary_1.isJidGroup)(from)) {
50
55
  if (!participant) {
51
- throw new Boom('No participant in group message');
56
+ throw new boom_1.Boom('No participant in group message');
52
57
  }
53
58
  msgType = 'group';
54
59
  author = participant;
55
60
  chatId = from;
56
61
  }
57
- else if (isJidBroadcast(from)) {
62
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
63
+ msgType = 'newsletter';
64
+ author = from;
65
+ chatId = from;
66
+ }
67
+ else if ((0, WABinary_1.isJidBroadcast)(from)) {
58
68
  if (!participant) {
59
- throw new Boom('No participant in group message');
69
+ throw new boom_1.Boom('No participant in group message');
60
70
  }
61
71
  const isParticipantMe = isMe(participant);
62
- if (isJidStatusBroadcast(from)) {
72
+ if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
63
73
  msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
64
74
  }
65
75
  else {
@@ -68,35 +78,30 @@ export function decodeMessageNode(stanza, meId, meLid) {
68
78
  chatId = from;
69
79
  author = participant;
70
80
  }
71
- else if (isJidNewsletter(from)) {
72
- msgType = 'newsletter';
73
- chatId = from;
74
- author = from;
75
- }
76
81
  else {
77
- throw new Boom('Unknown message type', { data: stanza });
82
+ throw new boom_1.Boom('Unknown message type', { data: stanza });
78
83
  }
79
- const fromMe = (isLidUser(from) ? isMeLid : isMe)((stanza.attrs.participant || stanza.attrs.from));
80
- const pushname = stanza?.attrs?.notify;
84
+ const fromMe = (0, WABinary_1.isJidNewsletter)(from) ? !!((_a = stanza.attrs) === null || _a === void 0 ? void 0 : _a.is_sender) || false : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
85
+ const pushname = (_b = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _b === void 0 ? void 0 : _b.notify;
81
86
  const key = {
82
87
  remoteJid: chatId,
83
88
  fromMe,
84
89
  id: msgId,
85
- senderLid: stanza?.attrs?.sender_lid,
86
- senderPn: stanza?.attrs?.sender_pn,
87
90
  participant,
88
91
  participantPn: stanza?.attrs?.participant_pn,
89
- participantLid: stanza?.attrs?.participant_lid,
90
- ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
92
+ server_id: (_c = stanza.attrs) === null || _c === void 0 ? void 0 : _c.server_id
91
93
  };
92
94
  const fullMessage = {
93
95
  key,
94
96
  messageTimestamp: +stanza.attrs.t,
95
97
  pushName: pushname,
96
- broadcast: isJidBroadcast(from)
98
+ broadcast: (0, WABinary_1.isJidBroadcast)(from)
97
99
  };
100
+ if (msgType === 'newsletter') {
101
+ fullMessage.newsletterServerId = +((_d = stanza.attrs) === null || _d === void 0 ? void 0 : _d.server_id);
102
+ }
98
103
  if (key.fromMe) {
99
- fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
104
+ fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
100
105
  }
101
106
  return {
102
107
  fullMessage,
@@ -104,24 +109,22 @@ export function decodeMessageNode(stanza, meId, meLid) {
104
109
  sender: msgType === 'chat' ? author : chatId
105
110
  };
106
111
  }
107
- export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
112
+ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
108
113
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
109
114
  return {
110
115
  fullMessage,
111
116
  category: stanza.attrs.category,
112
117
  author,
113
118
  async decrypt() {
119
+ var _a;
114
120
  let decryptables = 0;
115
121
  if (Array.isArray(stanza.content)) {
116
122
  for (const { tag, attrs, content } of stanza.content) {
117
123
  if (tag === 'verified_name' && content instanceof Uint8Array) {
118
- const cert = proto.VerifiedNameCertificate.decode(content);
119
- const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
124
+ const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
125
+ const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
120
126
  fullMessage.verifiedBizName = details.verifiedName;
121
127
  }
122
- if (tag === 'unavailable' && attrs.type === 'view_once') {
123
- fullMessage.key.isViewOnce = true;
124
- }
125
128
  if (tag !== 'enc' && tag !== 'plaintext') {
126
129
  continue;
127
130
  }
@@ -142,7 +145,7 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
142
145
  break;
143
146
  case 'pkmsg':
144
147
  case 'msg':
145
- const user = isJidUser(sender) ? sender : author;
148
+ const user = (0, WABinary_1.isJidUser)(sender) ? sender : author;
146
149
  msgBuffer = await repository.decryptMessage({
147
150
  jid: user,
148
151
  type: e2eType,
@@ -152,13 +155,15 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
152
155
  case 'plaintext':
153
156
  msgBuffer = content;
154
157
  break;
158
+ case undefined:
159
+ msgBuffer = content;
160
+ break;
155
161
  default:
156
162
  throw new Error(`Unknown e2e type: ${e2eType}`);
157
163
  }
158
- let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer);
159
- msg = msg.deviceSentMessage?.message || msg;
164
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
165
+ msg = ((_a = msg === null || msg === void 0 ? void 0 : msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
160
166
  if (msg.senderKeyDistributionMessage) {
161
- //eslint-disable-next-line max-depth
162
167
  try {
163
168
  await repository.processSenderKeyDistributionMessage({
164
169
  authorJid: author,
@@ -178,17 +183,17 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
178
183
  }
179
184
  catch (err) {
180
185
  logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
181
- fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
186
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
182
187
  fullMessage.messageStubParameters = [err.message];
183
188
  }
184
189
  }
185
190
  }
186
191
  // if nothing was found to decrypt
187
192
  if (!decryptables) {
188
- fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
189
- fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
193
+ fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
194
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
190
195
  }
191
196
  }
192
197
  };
193
198
  };
194
- //# sourceMappingURL=decode-wa-message.js.map
199
+ exports.decryptMessageNode = decryptMessageNode;
@@ -1,9 +1,14 @@
1
- import EventEmitter from 'events';
2
- import { proto } from '../../WAProto/index.js';
3
- import { WAMessageStatus } from '../Types/index.js';
4
- import { trimUndefined } from './generics.js';
5
- import { updateMessageWithReaction, updateMessageWithReceipt } from './messages.js';
6
- import { isRealMessage, shouldIncrementChatUnread } from './process-message.js';
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeEventBuffer = void 0;
7
+ const events_1 = __importDefault(require("events"));
8
+ const Types_1 = require("../Types");
9
+ const generics_1 = require("./generics");
10
+ const messages_1 = require("./messages");
11
+ const process_message_1 = require("./process-message");
7
12
  const BUFFERABLE_EVENT = [
8
13
  'messaging-history.set',
9
14
  'chats.upsert',
@@ -16,7 +21,7 @@ const BUFFERABLE_EVENT = [
16
21
  'messages.delete',
17
22
  'messages.reaction',
18
23
  'message-receipt.update',
19
- 'groups.update'
24
+ 'groups.update',
20
25
  ];
21
26
  const BUFFERABLE_EVENT_SET = new Set(BUFFERABLE_EVENT);
22
27
  /**
@@ -24,8 +29,8 @@ const BUFFERABLE_EVENT_SET = new Set(BUFFERABLE_EVENT);
24
29
  * making the data processing more efficient.
25
30
  * @param ev the baileys event emitter
26
31
  */
27
- export const makeEventBuffer = (logger) => {
28
- const ev = new EventEmitter();
32
+ const makeEventBuffer = (logger) => {
33
+ const ev = new events_1.default();
29
34
  const historyCache = new Set();
30
35
  let data = makeBufferData();
31
36
  let buffersInProgress = 0;
@@ -107,9 +112,10 @@ export const makeEventBuffer = (logger) => {
107
112
  },
108
113
  on: (...args) => ev.on(...args),
109
114
  off: (...args) => ev.off(...args),
110
- removeAllListeners: (...args) => ev.removeAllListeners(...args)
115
+ removeAllListeners: (...args) => ev.removeAllListeners(...args),
111
116
  };
112
117
  };
118
+ exports.makeEventBuffer = makeEventBuffer;
113
119
  const makeBufferData = () => {
114
120
  return {
115
121
  historySets: {
@@ -132,9 +138,8 @@ const makeBufferData = () => {
132
138
  groupUpdates: {}
133
139
  };
134
140
  };
135
- function append(data, historyCache, event,
136
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
137
- eventData, logger) {
141
+ function append(data, historyCache, event, eventData, logger) {
142
+ var _a, _b, _c;
138
143
  switch (event) {
139
144
  case 'messaging-history.set':
140
145
  for (const chat of eventData.chats) {
@@ -151,7 +156,7 @@ eventData, logger) {
151
156
  for (const contact of eventData.contacts) {
152
157
  const existingContact = data.historySets.contacts[contact.id];
153
158
  if (existingContact) {
154
- Object.assign(existingContact, trimUndefined(contact));
159
+ Object.assign(existingContact, (0, generics_1.trimUndefined)(contact));
155
160
  }
156
161
  else {
157
162
  const historyContactId = `c:${contact.id}`;
@@ -180,7 +185,7 @@ eventData, logger) {
180
185
  for (const chat of eventData) {
181
186
  let upsert = data.chatUpserts[chat.id];
182
187
  if (!upsert) {
183
- upsert = data.historySets.chats[chat.id];
188
+ upsert = data.historySets[chat.id];
184
189
  if (upsert) {
185
190
  logger.debug({ chatId: chat.id }, 'absorbed chat upsert in chat set');
186
191
  }
@@ -254,14 +259,14 @@ eventData, logger) {
254
259
  }
255
260
  }
256
261
  if (upsert) {
257
- upsert = Object.assign(upsert, trimUndefined(contact));
262
+ upsert = Object.assign(upsert, (0, generics_1.trimUndefined)(contact));
258
263
  }
259
264
  else {
260
265
  upsert = contact;
261
266
  data.contactUpserts[contact.id] = upsert;
262
267
  }
263
268
  if (data.contactUpdates[contact.id]) {
264
- upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact));
269
+ upsert = Object.assign(data.contactUpdates[contact.id], (0, generics_1.trimUndefined)(contact));
265
270
  delete data.contactUpdates[contact.id];
266
271
  }
267
272
  }
@@ -286,7 +291,7 @@ eventData, logger) {
286
291
  const { messages, type } = eventData;
287
292
  for (const message of messages) {
288
293
  const key = stringifyMessageKey(message.key);
289
- let existing = data.messageUpserts[key]?.message;
294
+ let existing = (_a = data.messageUpserts[key]) === null || _a === void 0 ? void 0 : _a.message;
290
295
  if (!existing) {
291
296
  existing = data.historySets.messages[key];
292
297
  if (existing) {
@@ -307,7 +312,9 @@ eventData, logger) {
307
312
  else {
308
313
  data.messageUpserts[key] = {
309
314
  message,
310
- type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
315
+ type: type === 'notify' || ((_b = data.messageUpserts[key]) === null || _b === void 0 ? void 0 : _b.type) === 'notify'
316
+ ? 'notify'
317
+ : type
311
318
  };
312
319
  }
313
320
  }
@@ -316,13 +323,13 @@ eventData, logger) {
316
323
  const msgUpdates = eventData;
317
324
  for (const { key, update } of msgUpdates) {
318
325
  const keyStr = stringifyMessageKey(key);
319
- const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
326
+ const existing = data.historySets.messages[keyStr] || ((_c = data.messageUpserts[keyStr]) === null || _c === void 0 ? void 0 : _c.message);
320
327
  if (existing) {
321
328
  Object.assign(existing, update);
322
329
  // if the message was received & read by us
323
330
  // the chat counter must have been incremented
324
331
  // so we need to decrement it
325
- if (update.status === WAMessageStatus.READ && !key.fromMe) {
332
+ if (update.status === Types_1.WAMessageStatus.READ && !key.fromMe) {
326
333
  decrementChatReadCounterIfMsgDidUnread(existing);
327
334
  }
328
335
  }
@@ -360,11 +367,12 @@ eventData, logger) {
360
367
  const keyStr = stringifyMessageKey(key);
361
368
  const existing = data.messageUpserts[keyStr];
362
369
  if (existing) {
363
- updateMessageWithReaction(existing.message, reaction);
370
+ (0, messages_1.updateMessageWithReaction)(existing.message, reaction);
364
371
  }
365
372
  else {
366
- data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] };
367
- updateMessageWithReaction(data.messageReactions[keyStr], reaction);
373
+ data.messageReactions[keyStr] = data.messageReactions[keyStr]
374
+ || { key, reactions: [] };
375
+ (0, messages_1.updateMessageWithReaction)(data.messageReactions[keyStr], reaction);
368
376
  }
369
377
  }
370
378
  break;
@@ -374,11 +382,12 @@ eventData, logger) {
374
382
  const keyStr = stringifyMessageKey(key);
375
383
  const existing = data.messageUpserts[keyStr];
376
384
  if (existing) {
377
- updateMessageWithReceipt(existing.message, receipt);
385
+ (0, messages_1.updateMessageWithReceipt)(existing.message, receipt);
378
386
  }
379
387
  else {
380
- data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] };
381
- updateMessageWithReceipt(data.messageReceipts[keyStr], receipt);
388
+ data.messageReceipts[keyStr] = data.messageReceipts[keyStr]
389
+ || { key, userReceipt: [] };
390
+ (0, messages_1.updateMessageWithReceipt)(data.messageReceipts[keyStr], receipt);
382
391
  }
383
392
  }
384
393
  break;
@@ -417,10 +426,10 @@ eventData, logger) {
417
426
  // if the message has already been marked read by us
418
427
  const chatId = message.key.remoteJid;
419
428
  const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId];
420
- if (isRealMessage(message, '') &&
421
- shouldIncrementChatUnread(message) &&
422
- typeof chat?.unreadCount === 'number' &&
423
- chat.unreadCount > 0) {
429
+ if ((0, process_message_1.isRealMessage)(message, '')
430
+ && (0, process_message_1.shouldIncrementChatUnread)(message)
431
+ && typeof (chat === null || chat === void 0 ? void 0 : chat.unreadCount) === 'number'
432
+ && chat.unreadCount > 0) {
424
433
  logger.debug({ chatId: chat.id }, 'decrementing chat counter');
425
434
  chat.unreadCount -= 1;
426
435
  if (chat.unreadCount === 0) {
@@ -493,10 +502,12 @@ function consolidateEvents(data) {
493
502
  return map;
494
503
  }
495
504
  function concatChats(a, b) {
496
- if (b.unreadCount === null && // neutralize unread counter
497
- a.unreadCount < 0) {
498
- a.unreadCount = undefined;
499
- b.unreadCount = undefined;
505
+ if (b.unreadCount === null) {
506
+ // neutralize unread counter
507
+ if (a.unreadCount < 0) {
508
+ a.unreadCount = undefined;
509
+ b.unreadCount = undefined;
510
+ }
500
511
  }
501
512
  if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
502
513
  b = { ...b };
@@ -507,4 +518,3 @@ function concatChats(a, b) {
507
518
  return Object.assign(a, b);
508
519
  }
509
520
  const stringifyMessageKey = (key) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`;
510
- //# sourceMappingURL=event-buffer.js.map