@rexxhayanasi/elaina-baileys 1.1.7 → 1.1.9

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.
@@ -1,20 +1,22 @@
1
1
  "use strict";
2
+ /**
3
+ * Signal Group Key Helper
4
+ * Helper functions to generate sender keys and signing keys safely.
5
+ */
2
6
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
7
  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);
8
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9
9
  }) : (function(o, m, k, k2) {
10
10
  if (k2 === undefined) k2 = k;
11
11
  o[k2] = m[k];
12
12
  }));
13
+
13
14
  var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
15
  Object.defineProperty(o, "default", { enumerable: true, value: v });
15
16
  }) : function(o, v) {
16
17
  o["default"] = v;
17
18
  });
19
+
18
20
  var __importStar = (this && this.__importStar) || (function () {
19
21
  var ownKeys = function(o) {
20
22
  ownKeys = Object.getOwnPropertyNames || function (o) {
@@ -32,45 +34,55 @@ var __importStar = (this && this.__importStar) || (function () {
32
34
  return result;
33
35
  };
34
36
  })();
37
+
35
38
  Object.defineProperty(exports, "__esModule", { value: true });
36
39
  exports.generateSenderKey = generateSenderKey;
37
40
  exports.generateSenderKeyId = generateSenderKeyId;
38
41
  exports.generateSenderSigningKey = generateSenderSigningKey;
42
+
39
43
  const nodeCrypto = __importStar(require("crypto"));
40
- const curve_1 = require("libsignal/src/curve");
44
+ const curve_1 = require("libsignal/src/curve");
41
45
 
46
+ /**
47
+ * Generates a random 32-byte Sender Key.
48
+ * @returns {Buffer} The generated key.
49
+ */
42
50
  function generateSenderKey() {
43
51
  const key = nodeCrypto.randomBytes(32);
44
- if (!Buffer.isBuffer(key) || key.length !== 32) {
45
- throw new Error("Failed to generate valid sender key");
52
+ if (key.length !== 32) {
53
+ throw new Error("Failed to generate a valid 32-byte Sender Key");
46
54
  }
47
55
  return key;
48
56
  }
49
57
 
58
+ /**
59
+ * Generates a random Sender Key ID.
60
+ * @returns {number} The generated Key ID.
61
+ */
50
62
  function generateSenderKeyId() {
51
63
  const id = nodeCrypto.randomInt(2147483647);
52
- if (typeof id !== 'number') {
53
- throw new Error("Failed to generate sender key ID");
64
+ if (!id || typeof id !== 'number') {
65
+ throw new Error("Failed to generate Sender Key ID");
54
66
  }
55
67
  return id;
56
68
  }
57
69
 
70
+ /**
71
+ * Generates a Sender Signing Key Pair.
72
+ * Uses libsignal's curve implementation.
73
+ * @param {Object} [key] Optional existing key pair.
74
+ * @returns {Object} The key pair (public/private).
75
+ */
58
76
  function generateSenderSigningKey(key) {
59
77
  if (!key) {
60
78
  key = (0, curve_1.generateKeyPair)();
61
79
  }
80
+
62
81
  if (!key || !key.pubKey || !key.privKey) {
63
- throw new Error("Invalid key pair provided");
82
+ throw new Error("Invalid KeyPair generated from Curve");
64
83
  }
65
- const publicBuf = Buffer.from(key.pubKey);
66
- const privateBuf = Buffer.from(key.privKey);
67
-
68
- if (publicBuf.length !== 32 || privateBuf.length !== 32) {
69
- throw new Error("Invalid signing key length");
70
- }
71
-
72
84
  return {
73
- public: publicBuf,
74
- private: privateBuf
85
+ public: key.pubKey,
86
+ private: key.privKey
75
87
  };
76
88
  }
@@ -83,9 +83,8 @@ const getImageProcessingLibrary = async () => {
83
83
  throw new boom_1.Boom('No image processing library available');
84
84
  };
85
85
  const hkdfInfoKey = (type) => {
86
- if (type === 'ptv') return 'WhatsApp Video Keys';
87
86
  if (type === 'sticker-pack') return 'WhatsApp Image Keys';
88
-
87
+ if (type === 'ptv') return 'WhatsApp Video Keys';
89
88
  const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type];
90
89
  return `WhatsApp ${hkdfInfo} Keys`;
91
90
  };
@@ -727,7 +726,7 @@ function extensionForMediaMessage(message) {
727
726
  }
728
727
  return extension;
729
728
  }
730
- const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
729
+ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
731
730
  return async (stream, { mediaType, fileEncSha256B64, newsletter, timeoutMs }) => {
732
731
  var _a, _b;
733
732
  let uploadInfo = await refreshMediaConn(false);
@@ -741,6 +740,7 @@ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options },
741
740
  }
742
741
  const reqBody = Buffer.isBuffer(stream) ? stream : Buffer.concat(chunks);
743
742
  fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
743
+
744
744
  let media = Defaults_1.MEDIA_PATH_MAP[mediaType];
745
745
  if (mediaType === 'sticker-pack') {
746
746
  media = '/mms/image';
@@ -748,6 +748,7 @@ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options },
748
748
  if (newsletter) {
749
749
  media = media === null || media === void 0 ? void 0 : media.replace('/mms/', '/newsletter/newsletter-');
750
750
  }
751
+
751
752
  for (const { hostname, maxContentLengthBytes } of hosts) {
752
753
  logger.debug(`uploading to "${hostname}"`);
753
754
  const auth = encodeURIComponent(uploadInfo.auth);
@@ -798,7 +799,7 @@ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options },
798
799
  return urls;
799
800
  };
800
801
  };
801
- exports.getWAUploadToServer = getWAUploadToServer;
802
+ exports.getWAUploadToServer = getWAUploadToServer;
802
803
  const getMediaRetryKey = (mediaKey) => {
803
804
  return (0, crypto_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
804
805
  };
@@ -101,20 +101,20 @@ const prepareWAMessageMedia = async (message, options) => {
101
101
  media: message[mediaType]
102
102
  };
103
103
  delete uploadData[mediaType];
104
- // check if cacheable + generate cache key
104
+
105
105
  const cacheableKey = typeof uploadData.media === 'object' &&
106
106
  ('url' in uploadData.media) &&
107
107
  !!uploadData.media.url &&
108
108
  !!options.mediaCache && (
109
- // generate the key
110
- mediaType + ':' + uploadData.media.url.toString());
109
+ mediaType + ':' + uploadData.media.url.toString());
110
+
111
111
  if (mediaType === 'document' && !uploadData.fileName) {
112
112
  uploadData.fileName = 'file';
113
113
  }
114
114
  if (!uploadData.mimetype) {
115
115
  uploadData.mimetype = MIMETYPE_MAP[mediaType];
116
116
  }
117
- // check for cache hit
117
+
118
118
  if (cacheableKey) {
119
119
  const mediaBuff = options.mediaCache.get(cacheableKey);
120
120
  if (mediaBuff) {
@@ -125,19 +125,78 @@ const prepareWAMessageMedia = async (message, options) => {
125
125
  return obj;
126
126
  }
127
127
  }
128
+
129
+ const isNewsletter = options.newsletter || (options.jid && (0, WABinary_1.isJidNewsletter)(options.jid));
130
+
131
+ if (isNewsletter) {
132
+ logger === null || logger === void 0 ? void 0 : logger.debug({ key: cacheableKey }, 'Preparing raw media for newsletter');
133
+
134
+ const { bodyPath, fileSha256, fileLength, didSaveToTmpPath } = await (0, messages_media_1.prepareStream)(
135
+ uploadData.media,
136
+ options.mediaTypeOverride || mediaType,
137
+ { logger, opts: options.options }
138
+ );
139
+
140
+ const fileEncSha256B64 = fileSha256.toString('base64');
141
+
142
+ const { mediaUrl, directPath } = await options.upload(bodyPath, {
143
+ fileEncSha256B64,
144
+ mediaType,
145
+ timeoutMs: options.mediaUploadTimeoutMs,
146
+ newsletter: true
147
+ });
148
+
149
+ if (didSaveToTmpPath && bodyPath) {
150
+ try {
151
+ await fs_1.promises.unlink(bodyPath);
152
+ } catch (error) {
153
+ logger === null || logger === void 0 ? void 0 : logger.warn('failed to remove tmp file');
154
+ }
155
+ }
156
+
157
+ const obj = Types_1.WAProto.Message.fromObject({
158
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
159
+ url: mediaUrl,
160
+ directPath,
161
+ fileSha256,
162
+ fileLength,
163
+ ...uploadData,
164
+ media: undefined
165
+ })
166
+ });
167
+
168
+ if (uploadData.ptv) {
169
+ obj.ptvMessage = obj.videoMessage;
170
+ delete obj.videoMessage;
171
+ }
172
+
173
+ if (obj.stickerMessage) {
174
+ obj.stickerMessage.stickerSentTs = Date.now();
175
+ }
176
+
177
+ if (cacheableKey) {
178
+ logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'set cache');
179
+ options.mediaCache.set(cacheableKey, Types_1.WAProto.Message.encode(obj).finish());
180
+ }
181
+
182
+ return obj;
183
+ }
184
+
128
185
  const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
129
186
  const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') &&
130
187
  (typeof uploadData['jpegThumbnail'] === 'undefined');
131
188
  const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
132
189
  const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
133
190
  const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
134
- const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, didSaveToTmpPath, } = await (options.newsletter ? messages_media_1.prepareStream : messages_media_1.encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
191
+
192
+ const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, didSaveToTmpPath, } = await (0, messages_media_1.encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
135
193
  logger,
136
194
  saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
137
195
  opts: options.options
138
196
  });
139
- // url safe Base64 encode the SHA256 hash of the body
140
- const fileEncSha256B64 = (options.newsletter ? fileSha256 : fileEncSha256 !== null && fileEncSha256 !== void 0 ? fileEncSha256 : fileSha256).toString('base64');
197
+
198
+ const fileEncSha256B64 = (fileEncSha256 !== null && fileEncSha256 !== void 0 ? fileEncSha256 : fileSha256).toString('base64');
199
+
141
200
  const [{ mediaUrl, directPath, handle }] = await Promise.all([
142
201
  (async () => {
143
202
  const result = await options.upload(encWriteStream, { fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs });
@@ -152,21 +211,16 @@ const prepareWAMessageMedia = async (message, options) => {
152
211
  if (!uploadData.width && originalImageDimensions) {
153
212
  uploadData.width = originalImageDimensions.width;
154
213
  uploadData.height = originalImageDimensions.height;
155
- logger === null || logger === void 0 ? void 0 : logger.debug('set dimensions');
156
214
  }
157
- logger === null || logger === void 0 ? void 0 : logger.debug('generated thumbnail');
158
215
  }
159
216
  if (requiresDurationComputation) {
160
217
  uploadData.seconds = await (0, messages_media_1.getAudioDuration)(bodyPath);
161
- logger === null || logger === void 0 ? void 0 : logger.debug('computed audio duration');
162
218
  }
163
219
  if (requiresWaveformProcessing) {
164
220
  uploadData.waveform = await (0, messages_media_1.getAudioWaveform)(bodyPath, logger);
165
- logger === null || logger === void 0 ? void 0 : logger.debug('processed waveform');
166
221
  }
167
222
  if (requiresAudioBackground) {
168
223
  uploadData.backgroundArgb = await assertColor(options.backgroundColor);
169
- logger === null || logger === void 0 ? void 0 : logger.debug('computed backgroundColor audio status');
170
224
  }
171
225
  }
172
226
  catch (error) {
@@ -174,11 +228,10 @@ const prepareWAMessageMedia = async (message, options) => {
174
228
  }
175
229
  })(),
176
230
  ])
177
- .finally(async () => {
231
+ .finally(async () => {
178
232
  if (!Buffer.isBuffer(encWriteStream)) {
179
233
  encWriteStream.destroy();
180
234
  }
181
- // remove tmp files
182
235
  if (didSaveToTmpPath && bodyPath) {
183
236
  try {
184
237
  await fs_1.promises.access(bodyPath);
@@ -190,6 +243,7 @@ const prepareWAMessageMedia = async (message, options) => {
190
243
  }
191
244
  }
192
245
  });
246
+
193
247
  const obj = Types_1.WAProto.Message.fromObject({
194
248
  [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
195
249
  url: handle ? undefined : mediaUrl,
@@ -203,17 +257,19 @@ const prepareWAMessageMedia = async (message, options) => {
203
257
  media: undefined
204
258
  })
205
259
  });
260
+
206
261
  if (uploadData.ptv) {
207
262
  obj.ptvMessage = obj.videoMessage;
208
263
  delete obj.videoMessage;
209
264
  }
265
+
210
266
  if (cacheableKey) {
211
- logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'set cache');
212
267
  options.mediaCache.set(cacheableKey, Types_1.WAProto.Message.encode(obj).finish());
213
268
  }
214
269
  return obj;
215
270
  };
216
271
  exports.prepareWAMessageMedia = prepareWAMessageMedia;
272
+
217
273
  const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
218
274
  ephemeralExpiration = ephemeralExpiration || 0;
219
275
  const content = {
@@ -398,11 +454,11 @@ const generateWAMessageContent = async (message, options) => {
398
454
  }
399
455
  }
400
456
  else if ('ptv' in message && message.ptv) {
401
- const { videoMessage } = await (0, exports.prepareWAMessageMedia)({
457
+ const { ptvMessage } = await (0, exports.prepareWAMessageMedia)({
402
458
  video: message.ptv,
403
- ptv: true
459
+ ptv: true
404
460
  }, options);
405
- m.ptvMessage = videoMessage;
461
+ m.ptvMessage = ptvMessage;
406
462
  }
407
463
  else if ('product' in message) {
408
464
  const { imageMessage } = await (0, exports.prepareWAMessageMedia)({ image: message.product.productImage }, options);
@@ -1225,4 +1281,4 @@ const prepareStickerPackMessage = async (stickerPack, options) => {
1225
1281
 
1226
1282
  return { stickerPackMessage };
1227
1283
  };
1228
- exports.prepareStickerPackMessage = prepareStickerPackMessage;
1284
+ exports.prepareStickerPackMessage = prepareStickerPackMessage;
package/lib/index.js CHANGED
@@ -55,6 +55,5 @@ __exportStar(require("./WABinary"), exports);
55
55
  __exportStar(require("./WAM"), exports);
56
56
  __exportStar(require("./WAUSync"), exports);
57
57
  __exportStar(require("./Api"), exports);
58
- __exportStar(require("./Auth"), exports);
59
58
 
60
59
  exports.default = Socket_1.default;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexxhayanasi/elaina-baileys",
3
- "version": "1.1.7",
3
+ "version": "1.1.9",
4
4
  "description": "Custom Baileys WhatsApp API",
5
5
  "keywords": [
6
6
  "baileys",
@@ -89,8 +89,7 @@
89
89
  "jimp": "^0.22.10",
90
90
  "link-preview-js": "^3.0.0",
91
91
  "qrcode-terminal": "^0.12.0",
92
- "sharp": "^0.34.1",
93
- "better-sqlite3": "^12.5.0"
92
+ "sharp": "^0.34.1"
94
93
  },
95
94
  "peerDependenciesMeta": {
96
95
  "jimp": {
package/lib/Auth/index.js DELETED
@@ -1,8 +0,0 @@
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.useSQLiteAuth = void 0;
7
- const sqlite_1 = __importDefault(require("./sqlite"));
8
- exports.useSQLiteAuth = sqlite_1.default;
@@ -1,57 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.useSQLiteAuth = void 0;
5
-
6
- const BetterSqlite = require("better-sqlite3");
7
- const { BufferJSON } = require("../index");
8
- const { initAuthCreds } = require("../Utils");
9
-
10
- const db = new BetterSqlite("./session.db");
11
-
12
- db.exec(`
13
- CREATE TABLE IF NOT EXISTS auth (
14
- id TEXT PRIMARY KEY,
15
- data TEXT
16
- )
17
- `);
18
-
19
- const useSQLiteAuth = () => {
20
- const readData = (id) => {
21
- const row = db.prepare("SELECT data FROM auth WHERE id=?").get(id);
22
- return row ? JSON.parse(row.data, BufferJSON.reviver) : null;
23
- };
24
-
25
- const writeData = (id, data) => {
26
- db.prepare("INSERT OR REPLACE INTO auth VALUES (?, ?)")
27
- .run(id, JSON.stringify(data, BufferJSON.replacer));
28
- };
29
-
30
- const state = {
31
- creds: readData("creds") || initAuthCreds(),
32
- keys: {
33
- get(type, ids) {
34
- const data = {};
35
- for (const id of ids) {
36
- const value = readData(`${type}-${id}`);
37
- if (value) data[id] = value;
38
- }
39
- return data;
40
- },
41
- set(data) {
42
- for (const type in data) {
43
- for (const id in data[type]) {
44
- writeData(`${type}-${id}`, data[type][id]);
45
- }
46
- }
47
- }
48
- }
49
- };
50
-
51
- const saveCreds = () => writeData("creds", state.creds);
52
-
53
- return { state, saveCreds };
54
- };
55
-
56
- exports.useSQLiteAuth = useSQLiteAuth;
57
- exports.default = useSQLiteAuth;