lordceaser-baileys 1.0.20 → 1.0.21

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 (123) hide show
  1. package/lib/Defaults/baileys-version.json +1 -1
  2. package/lib/Defaults/index.d.ts +235 -3
  3. package/lib/Defaults/index.js +22 -6
  4. package/lib/Defaults/phonenumber-mcc.json +223 -0
  5. package/lib/Signal/libsignal.js +9 -18
  6. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +2 -0
  7. package/lib/Socket/Client/index.d.ts +3 -2
  8. package/lib/Socket/Client/index.js +3 -2
  9. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  10. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  11. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +1 -1
  12. package/lib/Socket/Client/{websocket.js → web-socket-client.js} +2 -2
  13. package/lib/Socket/business.d.ts +40 -38
  14. package/lib/Socket/chats.d.ts +23 -25
  15. package/lib/Socket/chats.js +78 -79
  16. package/lib/Socket/groups.d.ts +29 -30
  17. package/lib/Socket/groups.js +3 -4
  18. package/lib/Socket/index.d.ts +48 -44
  19. package/lib/Socket/index.js +2 -2
  20. package/lib/Socket/messages-recv.d.ts +37 -37
  21. package/lib/Socket/messages-recv.js +44 -98
  22. package/lib/Socket/messages-send.d.ts +31 -33
  23. package/lib/Socket/messages-send.js +70 -82
  24. package/lib/Socket/registration.d.ts +242 -0
  25. package/lib/Socket/registration.js +166 -0
  26. package/lib/Socket/socket.d.ts +10 -9
  27. package/lib/Socket/socket.js +23 -28
  28. package/lib/Store/index.d.ts +3 -0
  29. package/lib/Store/index.js +10 -0
  30. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  31. package/lib/Store/make-cache-manager-store.js +83 -0
  32. package/lib/Store/make-in-memory-store.d.ts +118 -0
  33. package/lib/Store/make-in-memory-store.js +422 -0
  34. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  35. package/lib/Store/make-ordered-dictionary.js +81 -0
  36. package/lib/Store/object-repository.d.ts +10 -0
  37. package/lib/Store/object-repository.js +27 -0
  38. package/lib/Types/Auth.d.ts +7 -0
  39. package/lib/Types/Chat.d.ts +7 -12
  40. package/lib/Types/Contact.d.ts +1 -1
  41. package/lib/Types/GroupMetadata.d.ts +0 -2
  42. package/lib/Types/Label.js +1 -1
  43. package/lib/Types/LabelAssociation.js +1 -1
  44. package/lib/Types/Message.d.ts +10 -9
  45. package/lib/Types/Message.js +3 -1
  46. package/lib/Types/Socket.d.ts +11 -16
  47. package/lib/Types/index.js +1 -1
  48. package/lib/Utils/auth-utils.d.ts +3 -3
  49. package/lib/Utils/auth-utils.js +13 -7
  50. package/lib/Utils/business.js +5 -13
  51. package/lib/Utils/chat-utils.d.ts +14 -13
  52. package/lib/Utils/chat-utils.js +31 -36
  53. package/lib/Utils/crypto.d.ts +15 -14
  54. package/lib/Utils/crypto.js +30 -70
  55. package/lib/Utils/decode-wa-message.d.ts +2 -18
  56. package/lib/Utils/decode-wa-message.js +19 -23
  57. package/lib/Utils/event-buffer.d.ts +2 -2
  58. package/lib/Utils/event-buffer.js +7 -7
  59. package/lib/Utils/generics.d.ts +14 -15
  60. package/lib/Utils/generics.js +29 -33
  61. package/lib/Utils/history.d.ts +2 -2
  62. package/lib/Utils/history.js +1 -1
  63. package/lib/Utils/link-preview.d.ts +2 -2
  64. package/lib/Utils/link-preview.js +1 -34
  65. package/lib/Utils/logger.d.ts +3 -10
  66. package/lib/Utils/lt-hash.d.ts +2 -2
  67. package/lib/Utils/lt-hash.js +6 -6
  68. package/lib/Utils/make-mutex.d.ts +2 -2
  69. package/lib/Utils/make-mutex.js +0 -1
  70. package/lib/Utils/messages-media.d.ts +24 -20
  71. package/lib/Utils/messages-media.js +76 -79
  72. package/lib/Utils/messages.d.ts +9 -7
  73. package/lib/Utils/messages.js +30 -29
  74. package/lib/Utils/noise-handler.d.ts +11 -9
  75. package/lib/Utils/noise-handler.js +22 -17
  76. package/lib/Utils/process-message.d.ts +5 -4
  77. package/lib/Utils/process-message.js +40 -68
  78. package/lib/Utils/signal.d.ts +1 -2
  79. package/lib/Utils/signal.js +19 -11
  80. package/lib/Utils/use-multi-file-auth-state.js +14 -46
  81. package/lib/Utils/validate-connection.d.ts +3 -2
  82. package/lib/Utils/validate-connection.js +46 -16
  83. package/lib/WABinary/constants.js +5 -5
  84. package/lib/WABinary/decode.d.ts +3 -2
  85. package/lib/WABinary/decode.js +9 -20
  86. package/lib/WABinary/encode.d.ts +2 -1
  87. package/lib/WABinary/encode.js +18 -38
  88. package/lib/WABinary/generic-utils.d.ts +2 -1
  89. package/lib/WABinary/generic-utils.js +3 -3
  90. package/lib/WABinary/jid-utils.d.ts +3 -7
  91. package/lib/WABinary/jid-utils.js +2 -9
  92. package/lib/WAM/BinaryInfo.d.ts +11 -2
  93. package/lib/WAM/constants.d.ts +2 -3
  94. package/lib/WAM/encode.d.ts +2 -1
  95. package/lib/WAM/encode.js +2 -2
  96. package/lib/index.d.ts +1 -1
  97. package/lib/index.js +1 -1
  98. package/package.json +2 -2
  99. package/lib/Socket/usync.d.ts +0 -36
  100. package/lib/Socket/usync.js +0 -70
  101. package/lib/Types/USync.d.ts +0 -25
  102. package/lib/Types/USync.js +0 -2
  103. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  104. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -32
  105. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  106. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  107. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  108. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  109. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  110. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  111. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  112. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  113. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  114. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  115. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  116. package/lib/WAUSync/Protocols/index.js +0 -20
  117. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  118. package/lib/WAUSync/USyncQuery.js +0 -89
  119. package/lib/WAUSync/USyncUser.d.ts +0 -12
  120. package/lib/WAUSync/USyncUser.js +0 -26
  121. package/lib/WAUSync/index.d.ts +0 -3
  122. package/lib/WAUSync/index.js +0 -19
  123. /package/lib/Socket/Client/{types.js → abstract-socket-client.js} +0 -0
@@ -15,43 +15,24 @@ 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"));
33
+ const util_1 = require("util");
52
34
  const Defaults_1 = require("../Defaults");
53
- // insure browser & node compatibility
54
- const { subtle } = globalThis.crypto;
35
+ const pbkdf2Promise = (0, util_1.promisify)(crypto_1.pbkdf2);
55
36
  /** prefix version byte to the pub keys, required for some curve crypto functions */
56
37
  const generateSignalPubKey = (pubKey) => (pubKey.length === 33
57
38
  ? pubKey
@@ -98,6 +79,7 @@ function aesEncryptGCM(plaintext, key, iv, additionalData) {
98
79
  cipher.setAAD(additionalData);
99
80
  return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
100
81
  }
82
+ exports.aesEncryptGCM = aesEncryptGCM;
101
83
  /**
102
84
  * decrypt AES 256 GCM;
103
85
  * where the auth tag is suffixed to the ciphertext
@@ -112,82 +94,60 @@ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
112
94
  decipher.setAuthTag(tag);
113
95
  return Buffer.concat([decipher.update(enc), decipher.final()]);
114
96
  }
97
+ exports.aesDecryptGCM = aesDecryptGCM;
115
98
  function aesEncryptCTR(plaintext, key, iv) {
116
99
  const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
117
100
  return Buffer.concat([cipher.update(plaintext), cipher.final()]);
118
101
  }
102
+ exports.aesEncryptCTR = aesEncryptCTR;
119
103
  function aesDecryptCTR(ciphertext, key, iv) {
120
104
  const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
121
105
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
122
106
  }
107
+ exports.aesDecryptCTR = aesDecryptCTR;
123
108
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
124
109
  function aesDecrypt(buffer, key) {
125
110
  return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
126
111
  }
112
+ exports.aesDecrypt = aesDecrypt;
127
113
  /** decrypt AES 256 CBC */
128
114
  function aesDecryptWithIV(buffer, key, IV) {
129
115
  const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
130
116
  return Buffer.concat([aes.update(buffer), aes.final()]);
131
117
  }
118
+ exports.aesDecryptWithIV = aesDecryptWithIV;
132
119
  // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
133
120
  function aesEncrypt(buffer, key) {
134
121
  const IV = (0, crypto_1.randomBytes)(16);
135
122
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
136
123
  return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
137
124
  }
125
+ exports.aesEncrypt = aesEncrypt;
138
126
  // encrypt AES 256 CBC with a given IV
139
127
  function aesEncrypWithIV(buffer, key, IV) {
140
128
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
141
129
  return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
142
130
  }
131
+ exports.aesEncrypWithIV = aesEncrypWithIV;
143
132
  // sign HMAC using SHA 256
144
133
  function hmacSign(buffer, key, variant = 'sha256') {
145
134
  return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
146
135
  }
136
+ exports.hmacSign = hmacSign;
147
137
  function sha256(buffer) {
148
138
  return (0, crypto_1.createHash)('sha256').update(buffer).digest();
149
139
  }
140
+ exports.sha256 = sha256;
150
141
  function md5(buffer) {
151
142
  return (0, crypto_1.createHash)('md5').update(buffer).digest();
152
143
  }
144
+ exports.md5 = md5;
153
145
  // 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);
146
+ function hkdf(buffer, expandedLength, info) {
147
+ return (0, futoin_hkdf_1.default)(!Buffer.isBuffer(buffer) ? Buffer.from(buffer) : buffer, expandedLength, info);
175
148
  }
149
+ exports.hkdf = hkdf;
176
150
  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);
151
+ return await pbkdf2Promise(pairingCode, salt, 2 << 16, 32, 'sha256');
193
152
  }
153
+ exports.derivePairingCodeKey = derivePairingCodeKey;
@@ -1,24 +1,8 @@
1
+ import { Logger } from 'pino';
1
2
  import { proto } from '../../WAProto';
2
3
  import { SignalRepository } from '../Types';
3
4
  import { BinaryNode } from '../WABinary';
4
- import { ILogger } from './logger';
5
5
  export declare const NO_MESSAGE_FOUND_ERROR_TEXT = "Message absent from node";
6
- export declare const MISSING_KEYS_ERROR_TEXT = "Key used already or never filled";
7
- export declare const NACK_REASONS: {
8
- ParsingError: number;
9
- UnrecognizedStanza: number;
10
- UnrecognizedStanzaClass: number;
11
- UnrecognizedStanzaType: number;
12
- InvalidProtobuf: number;
13
- InvalidHostedCompanionStanza: number;
14
- MissingMessageSecret: number;
15
- SignalErrorOldCounter: number;
16
- MessageDeletedOnPeer: number;
17
- UnhandledError: number;
18
- UnsupportedAdminRevoke: number;
19
- UnsupportedLIDGroup: number;
20
- DBOperationFailed: number;
21
- };
22
6
  /**
23
7
  * Decode the received node as a message.
24
8
  * @note this will only parse the message, not decrypt it
@@ -28,7 +12,7 @@ export declare function decodeMessageNode(stanza: BinaryNode, meId: string, meLi
28
12
  author: string;
29
13
  sender: string;
30
14
  };
31
- export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepository, logger: ILogger) => {
15
+ export declare const decryptMessageNode: (stanza: BinaryNode, meId: string, meLid: string, repository: SignalRepository, logger: Logger) => {
32
16
  fullMessage: proto.IWebMessageInfo;
33
17
  category: string;
34
18
  author: string;
@@ -1,28 +1,11 @@
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 = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
5
4
  const boom_1 = require("@hapi/boom");
6
- const WAProto_1 = require("../WAProto");
5
+ const WAProto_1 = require("../../WAProto");
7
6
  const WABinary_1 = require("../WABinary");
8
7
  const generics_1 = require("./generics");
9
8
  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
- };
26
9
  /**
27
10
  * Decode the received node as a message.
28
11
  * @note this will only parse the message, not decrypt it
@@ -38,9 +21,22 @@ function decodeMessageNode(stanza, meId, meLid) {
38
21
  const recipient = stanza.attrs.recipient;
39
22
  const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
40
23
  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)) {
43
- 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)) {
44
40
  throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
45
41
  }
46
42
  chatId = recipient;
@@ -104,6 +100,7 @@ function decodeMessageNode(stanza, meId, meLid) {
104
100
  sender: msgType === 'chat' ? author : chatId
105
101
  };
106
102
  }
103
+ exports.decodeMessageNode = decodeMessageNode;
107
104
  const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
108
105
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
109
106
  return {
@@ -156,7 +153,6 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
156
153
  let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
157
154
  msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
158
155
  if (msg.senderKeyDistributionMessage) {
159
- //eslint-disable-next-line max-depth
160
156
  try {
161
157
  await repository.processSenderKeyDistributionMessage({
162
158
  authorJid: author,
@@ -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 {};
@@ -138,9 +138,7 @@ const makeBufferData = () => {
138
138
  groupUpdates: {}
139
139
  };
140
140
  };
141
- function append(data, historyCache, event,
142
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
143
- eventData, logger) {
141
+ function append(data, historyCache, event, eventData, logger) {
144
142
  var _a, _b, _c;
145
143
  switch (event) {
146
144
  case 'messaging-history.set':
@@ -504,10 +502,12 @@ function consolidateEvents(data) {
504
502
  return map;
505
503
  }
506
504
  function concatChats(a, b) {
507
- if (b.unreadCount === null && // neutralize unread counter
508
- a.unreadCount < 0) {
509
- a.unreadCount = undefined;
510
- 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
+ }
511
511
  }
512
512
  if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
513
513
  b = { ...b };
@@ -1,6 +1,8 @@
1
+ /// <reference types="node" />
1
2
  import { AxiosRequestConfig } from 'axios';
3
+ import { Logger } from 'pino';
2
4
  import { proto } from '../../WAProto';
3
- import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, ConnectionState, WACallUpdateType, WAVersion } from '../Types';
5
+ import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, WACallUpdateType, WAVersion } from '../Types';
4
6
  import { BinaryNode } from '../WABinary';
5
7
  export declare const Browsers: BrowsersMap;
6
8
  export declare const getPlatformId: (browser: string) => any;
@@ -9,11 +11,11 @@ export declare const BufferJSON: {
9
11
  reviver: (_: any, value: any) => any;
10
12
  };
11
13
  export declare const getKeyAuthor: (key: proto.IMessageKey | undefined | null, meId?: string) => string;
12
- export declare const writeRandomPadMax16: (msg: Uint8Array) => Buffer<ArrayBuffer>;
13
- export declare const unpadRandomMax16: (e: Uint8Array | Buffer) => Uint8Array<ArrayBuffer>;
14
- export declare const encodeWAMessage: (message: proto.IMessage) => Buffer<ArrayBuffer>;
14
+ export declare const writeRandomPadMax16: (msg: Uint8Array) => Buffer;
15
+ export declare const unpadRandomMax16: (e: Uint8Array | Buffer) => Uint8Array;
16
+ export declare const encodeWAMessage: (message: proto.IMessage) => Buffer;
15
17
  export declare const generateRegistrationId: () => number;
16
- export declare const encodeBigEndian: (e: number, t?: number) => Uint8Array<ArrayBuffer>;
18
+ export declare const encodeBigEndian: (e: number, t?: number) => Uint8Array;
17
19
  export declare const toNumber: (t: Long | number | null | undefined) => number;
18
20
  /** unix timestamp of a date in seconds */
19
21
  export declare const unixTimestampSeconds: (date?: Date) => number;
@@ -32,13 +34,14 @@ export declare const delayCancellable: (ms: number) => {
32
34
  export declare function promiseTimeout<T>(ms: number | undefined, promise: (resolve: (v: T) => void, reject: (error: any) => void) => void): Promise<T>;
33
35
  export declare const generateMessageIDV2: (userId?: string) => string;
34
36
  export declare const generateMessageID: () => string;
35
- export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
36
- export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
37
+ export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => boolean | undefined, timeoutMs?: number) => Promise<void>;
38
+ export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number) => Promise<void>;
39
+ export declare const printQRIfNecessaryListener: (ev: BaileysEventEmitter, logger: Logger) => void;
37
40
  /**
38
41
  * utility that fetches latest baileys version from the master branch.
39
42
  * Use to ensure your WA connection is always on the latest version
40
43
  */
41
- export declare const fetchLatestBaileysVersion: (options?: AxiosRequestConfig<{}>) => Promise<{
44
+ export declare const fetchLatestBaileysVersion: (options?: AxiosRequestConfig<any>) => Promise<{
42
45
  version: WAVersion;
43
46
  isLatest: boolean;
44
47
  error?: undefined;
@@ -51,7 +54,7 @@ export declare const fetchLatestBaileysVersion: (options?: AxiosRequestConfig<{}
51
54
  * A utility that fetches the latest web version of whatsapp.
52
55
  * Use to ensure your WA connection is always on the latest version
53
56
  */
54
- export declare const fetchLatestWaWebVersion: (options: AxiosRequestConfig<{}>) => Promise<{
57
+ export declare const fetchLatestWaWebVersion: (options: AxiosRequestConfig<any>) => Promise<{
55
58
  version: WAVersion;
56
59
  isLatest: boolean;
57
60
  error?: undefined;
@@ -81,10 +84,6 @@ export declare const getCodeFromWSError: (error: Error) => number;
81
84
  * Is the given platform WA business
82
85
  * @param platform AuthenticationCreds.platform
83
86
  */
84
- export declare const isWABusinessPlatform: (platform: string) => platform is "smbi" | "smba";
85
- export declare function trimUndefined(obj: {
86
- [_: string]: any;
87
- }): {
88
- [_: string]: any;
89
- };
87
+ export declare const isWABusinessPlatform: (platform: string) => boolean;
88
+ export declare function trimUndefined(obj: any): any;
90
89
  export declare function bytesToCrockford(buffer: Buffer): string;
@@ -3,16 +3,12 @@ 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.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
7
- exports.promiseTimeout = promiseTimeout;
8
- exports.bindWaitForEvent = bindWaitForEvent;
9
- exports.trimUndefined = trimUndefined;
10
- exports.bytesToCrockford = bytesToCrockford;
6
+ exports.bytesToCrockford = exports.trimUndefined = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.generateMessageIDV2 = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
11
7
  const boom_1 = require("@hapi/boom");
12
8
  const axios_1 = __importDefault(require("axios"));
13
9
  const crypto_1 = require("crypto");
14
10
  const os_1 = require("os");
15
- const WAProto_1 = require("../WAProto");
11
+ const WAProto_1 = require("../../WAProto");
16
12
  const baileys_version_json_1 = require("../Defaults/baileys-version.json");
17
13
  const Types_1 = require("../Types");
18
14
  const WABinary_1 = require("../WABinary");
@@ -35,18 +31,16 @@ exports.Browsers = {
35
31
  };
36
32
  const getPlatformId = (browser) => {
37
33
  const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
38
- return platformType ? platformType.toString() : '1'; //chrome
34
+ return platformType ? platformType.toString().charCodeAt(0).toString() : '49'; //chrome
39
35
  };
40
36
  exports.getPlatformId = getPlatformId;
41
37
  exports.BufferJSON = {
42
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
43
38
  replacer: (k, value) => {
44
39
  if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
45
40
  return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
46
41
  }
47
42
  return value;
48
43
  },
49
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
50
44
  reviver: (_, value) => {
51
45
  if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
52
46
  const val = value.data || value.value;
@@ -94,7 +88,7 @@ const encodeBigEndian = (e, t = 4) => {
94
88
  return a;
95
89
  };
96
90
  exports.encodeBigEndian = encodeBigEndian;
97
- const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
91
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
98
92
  exports.toNumber = toNumber;
99
93
  /** unix timestamp of a date in seconds */
100
94
  const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
@@ -160,6 +154,7 @@ async function promiseTimeout(ms, promise) {
160
154
  .finally(cancel);
161
155
  return p;
162
156
  }
157
+ exports.promiseTimeout = promiseTimeout;
163
158
  // inspired from whatsmeow code
164
159
  // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
165
160
  const generateMessageIDV2 = (userId) => {
@@ -193,8 +188,8 @@ function bindWaitForEvent(ev, event) {
193
188
  }
194
189
  };
195
190
  ev.on('connection.update', closeListener);
196
- listener = async (update) => {
197
- if (await check(update)) {
191
+ listener = (update) => {
192
+ if (check(update)) {
198
193
  resolve();
199
194
  }
200
195
  };
@@ -206,8 +201,22 @@ function bindWaitForEvent(ev, event) {
206
201
  }));
207
202
  };
208
203
  }
204
+ exports.bindWaitForEvent = bindWaitForEvent;
209
205
  const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
210
206
  exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
207
+ const printQRIfNecessaryListener = (ev, logger) => {
208
+ ev.on('connection.update', async ({ qr }) => {
209
+ if (qr) {
210
+ const QR = await import('qrcode-terminal')
211
+ .then(m => m.default || m)
212
+ .catch(() => {
213
+ logger.error('QR code terminal not added as dependency');
214
+ });
215
+ QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
216
+ }
217
+ });
218
+ };
219
+ exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
211
220
  /**
212
221
  * utility that fetches latest baileys version from the master branch.
213
222
  * Use to ensure your WA connection is always on the latest version
@@ -239,24 +248,13 @@ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
239
248
  */
240
249
  const fetchLatestWaWebVersion = async (options) => {
241
250
  try {
242
- const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
251
+ const result = await axios_1.default.get('https://web.whatsapp.com/check-update?version=1&platform=web', {
243
252
  ...options,
244
253
  responseType: 'json'
245
254
  });
246
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
247
- const match = data.match(regex);
248
- if (!(match === null || match === void 0 ? void 0 : match[1])) {
249
- return {
250
- version: baileys_version_json_1.version,
251
- isLatest: false,
252
- error: {
253
- message: 'Could not find client revision in the fetched content'
254
- }
255
- };
256
- }
257
- const clientRevision = match[1];
255
+ const version = result.data.currentVersion.split('.');
258
256
  return {
259
- version: [2, 3000, +clientRevision],
257
+ version: [+version[0], +version[1], +version[2]],
260
258
  isLatest: true
261
259
  };
262
260
  }
@@ -276,7 +274,6 @@ const generateMdTagPrefix = () => {
276
274
  };
277
275
  exports.generateMdTagPrefix = generateMdTagPrefix;
278
276
  const STATUS_MAP = {
279
- 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
280
277
  'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
281
278
  'read': WAProto_1.proto.WebMessageInfo.Status.READ,
282
279
  'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
@@ -352,9 +349,7 @@ const getCodeFromWSError = (error) => {
352
349
  statusCode = code;
353
350
  }
354
351
  }
355
- else if (
356
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
357
- ((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
352
+ else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
358
353
  || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
359
354
  statusCode = 408;
360
355
  }
@@ -369,7 +364,6 @@ const isWABusinessPlatform = (platform) => {
369
364
  return platform === 'smbi' || platform === 'smba';
370
365
  };
371
366
  exports.isWABusinessPlatform = isWABusinessPlatform;
372
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
373
367
  function trimUndefined(obj) {
374
368
  for (const key in obj) {
375
369
  if (typeof obj[key] === 'undefined') {
@@ -378,13 +372,14 @@ function trimUndefined(obj) {
378
372
  }
379
373
  return obj;
380
374
  }
375
+ exports.trimUndefined = trimUndefined;
381
376
  const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
382
377
  function bytesToCrockford(buffer) {
383
378
  let value = 0;
384
379
  let bitCount = 0;
385
380
  const crockford = [];
386
- for (const element of buffer) {
387
- value = (value << 8) | (element & 0xff);
381
+ for (let i = 0; i < buffer.length; i++) {
382
+ value = (value << 8) | (buffer[i] & 0xff);
388
383
  bitCount += 8;
389
384
  while (bitCount >= 5) {
390
385
  crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
@@ -396,3 +391,4 @@ function bytesToCrockford(buffer) {
396
391
  }
397
392
  return crockford.join('');
398
393
  }
394
+ exports.bytesToCrockford = bytesToCrockford;
@@ -1,7 +1,7 @@
1
1
  import { AxiosRequestConfig } from 'axios';
2
2
  import { proto } from '../../WAProto';
3
3
  import { Chat, Contact } from '../Types';
4
- export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => Promise<proto.HistorySync>;
4
+ export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<proto.HistorySync>;
5
5
  export declare const processHistoryMessage: (item: proto.IHistorySync) => {
6
6
  chats: Chat[];
7
7
  contacts: Contact[];
@@ -9,7 +9,7 @@ export declare const processHistoryMessage: (item: proto.IHistorySync) => {
9
9
  syncType: proto.HistorySync.HistorySyncType;
10
10
  progress: number | null | undefined;
11
11
  };
12
- export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => Promise<{
12
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<{
13
13
  chats: Chat[];
14
14
  contacts: Contact[];
15
15
  messages: proto.IWebMessageInfo[];
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getHistoryMsg = exports.downloadAndProcessHistorySyncNotification = exports.processHistoryMessage = exports.downloadHistory = void 0;
4
4
  const util_1 = require("util");
5
5
  const zlib_1 = require("zlib");
6
- const WAProto_1 = require("../WAProto");
6
+ const WAProto_1 = require("../../WAProto");
7
7
  const Types_1 = require("../Types");
8
8
  const WABinary_1 = require("../WABinary");
9
9
  const generics_1 = require("./generics");
@@ -1,6 +1,6 @@
1
1
  import { AxiosRequestConfig } from 'axios';
2
+ import { Logger } from 'pino';
2
3
  import { WAMediaUploadFunction, WAUrlInfo } from '../Types';
3
- import { ILogger } from './logger';
4
4
  export type URLGenerationOptions = {
5
5
  thumbnailWidth: number;
6
6
  fetchOpts: {
@@ -10,7 +10,7 @@ export type URLGenerationOptions = {
10
10
  headers?: AxiosRequestConfig<{}>['headers'];
11
11
  };
12
12
  uploadImage?: WAMediaUploadFunction;
13
- logger?: ILogger;
13
+ logger?: Logger;
14
14
  };
15
15
  /**
16
16
  * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
@@ -1,37 +1,4 @@
1
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 () {
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
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
3
  exports.getUrlInfo = void 0;
37
4
  const messages_1 = require("./messages");
@@ -58,7 +25,7 @@ const getUrlInfo = async (text, opts = {
58
25
  // retries
59
26
  const retries = 0;
60
27
  const maxRetry = 5;
61
- const { getLinkPreview } = await Promise.resolve().then(() => __importStar(require('link-preview-js')));
28
+ const { getLinkPreview } = await import('link-preview-js');
62
29
  let previewLink = text;
63
30
  if (!text.startsWith('https://') && !text.startsWith('http://')) {
64
31
  previewLink = 'https://' + previewLink;
@@ -1,11 +1,4 @@
1
- export interface ILogger {
2
- level: string;
3
- child(obj: Record<string, unknown>): ILogger;
4
- trace(obj: unknown, msg?: string): any;
5
- debug(obj: unknown, msg?: string): any;
6
- info(obj: unknown, msg?: string): any;
7
- warn(obj: unknown, msg?: string): any;
8
- error(obj: unknown, msg?: string): any;
9
- }
10
- declare const _default: import("pino").Logger<never, boolean>;
1
+ declare const _default: import("pino").Logger<{
2
+ timestamp: () => string;
3
+ }>;
11
4
  export default _default;