alisaaai-baileys 1.0.6

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 (104) hide show
  1. package/WAProto/WAProto.proto +5311 -0
  2. package/WAProto/index.js +94091 -0
  3. package/lib/Defaults/index.js +121 -0
  4. package/lib/KeyDB/BinarySearch.js +18 -0
  5. package/lib/KeyDB/KeyedDB.js +165 -0
  6. package/lib/KeyDB/index.js +2 -0
  7. package/lib/Signal/Group/ciphertext-message.js +11 -0
  8. package/lib/Signal/Group/group-session-builder.js +31 -0
  9. package/lib/Signal/Group/group_cipher.js +82 -0
  10. package/lib/Signal/Group/index.js +11 -0
  11. package/lib/Signal/Group/keyhelper.js +19 -0
  12. package/lib/Signal/Group/sender-chain-key.js +26 -0
  13. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  14. package/lib/Signal/Group/sender-key-message.js +66 -0
  15. package/lib/Signal/Group/sender-key-name.js +50 -0
  16. package/lib/Signal/Group/sender-key-record.js +41 -0
  17. package/lib/Signal/Group/sender-key-state.js +84 -0
  18. package/lib/Signal/Group/sender-message-key.js +26 -0
  19. package/lib/Signal/libsignal.js +322 -0
  20. package/lib/Signal/lid-mapping.js +153 -0
  21. package/lib/Socket/Client/index.js +3 -0
  22. package/lib/Socket/Client/types.js +12 -0
  23. package/lib/Socket/Client/websocket.js +51 -0
  24. package/lib/Socket/Client/websocket.js.bak +52 -0
  25. package/lib/Socket/business.js +376 -0
  26. package/lib/Socket/chats.js +880 -0
  27. package/lib/Socket/communities.js +412 -0
  28. package/lib/Socket/groups.js +311 -0
  29. package/lib/Socket/index.js +15 -0
  30. package/lib/Socket/messages-recv.js +1162 -0
  31. package/lib/Socket/messages-send.js +1160 -0
  32. package/lib/Socket/mex.js +44 -0
  33. package/lib/Socket/newsletter.js +248 -0
  34. package/lib/Socket/setup.js +465 -0
  35. package/lib/Socket/socket.js +778 -0
  36. package/lib/Store/index.js +5 -0
  37. package/lib/Store/make-cache-manager-store.js +74 -0
  38. package/lib/Store/make-in-memory-store.js +289 -0
  39. package/lib/Store/make-ordered-dictionary.js +78 -0
  40. package/lib/Store/object-repository.js +23 -0
  41. package/lib/Types/Auth.js +3 -0
  42. package/lib/Types/Bussines.js +1 -0
  43. package/lib/Types/Call.js +1 -0
  44. package/lib/Types/Chat.js +7 -0
  45. package/lib/Types/Contact.js +1 -0
  46. package/lib/Types/Events.js +1 -0
  47. package/lib/Types/GroupMetadata.js +1 -0
  48. package/lib/Types/Label.js +23 -0
  49. package/lib/Types/LabelAssociation.js +5 -0
  50. package/lib/Types/Message.js +10 -0
  51. package/lib/Types/Newsletter.js +31 -0
  52. package/lib/Types/Product.js +1 -0
  53. package/lib/Types/Signal.js +1 -0
  54. package/lib/Types/Socket.js +2 -0
  55. package/lib/Types/State.js +9 -0
  56. package/lib/Types/USync.js +1 -0
  57. package/lib/Types/index.js +26 -0
  58. package/lib/Utils/auth-utils.js +217 -0
  59. package/lib/Utils/baileys-event-stream.js +42 -0
  60. package/lib/Utils/browser-utils.js +23 -0
  61. package/lib/Utils/business.js +231 -0
  62. package/lib/Utils/chat-utils.js +750 -0
  63. package/lib/Utils/crypto.js +128 -0
  64. package/lib/Utils/decode-wa-message.js +265 -0
  65. package/lib/Utils/event-buffer.js +526 -0
  66. package/lib/Utils/generics.js +353 -0
  67. package/lib/Utils/history.js +85 -0
  68. package/lib/Utils/index.js +19 -0
  69. package/lib/Utils/link-preview.js +79 -0
  70. package/lib/Utils/logger.js +3 -0
  71. package/lib/Utils/lt-hash.js +44 -0
  72. package/lib/Utils/make-mutex.js +34 -0
  73. package/lib/Utils/message-retry-manager.js +111 -0
  74. package/lib/Utils/messages-media.js +740 -0
  75. package/lib/Utils/messages.js +893 -0
  76. package/lib/Utils/noise-handler.js +142 -0
  77. package/lib/Utils/pre-key-manager.js +83 -0
  78. package/lib/Utils/process-message.js +339 -0
  79. package/lib/Utils/signal.js +159 -0
  80. package/lib/Utils/use-multi-file-auth-state.js +109 -0
  81. package/lib/Utils/validate-connection.js +198 -0
  82. package/lib/WABinary/constants.js +1301 -0
  83. package/lib/WABinary/decode.js +238 -0
  84. package/lib/WABinary/encode.js +216 -0
  85. package/lib/WABinary/generic-utils.js +189 -0
  86. package/lib/WABinary/index.js +5 -0
  87. package/lib/WABinary/jid-utils.js +91 -0
  88. package/lib/WABinary/types.js +1 -0
  89. package/lib/WAM/BinaryInfo.js +9 -0
  90. package/lib/WAM/constants.js +22853 -0
  91. package/lib/WAM/encode.js +154 -0
  92. package/lib/WAM/index.js +5 -0
  93. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  94. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  95. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  96. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  97. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  98. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  99. package/lib/WAUSync/Protocols/index.js +6 -0
  100. package/lib/WAUSync/USyncQuery.js +90 -0
  101. package/lib/WAUSync/USyncUser.js +24 -0
  102. package/lib/WAUSync/index.js +5 -0
  103. package/lib/index.js +16 -0
  104. package/package.json +93 -0
@@ -0,0 +1,740 @@
1
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from "../WABinary/index.js";
2
+ import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from "../Defaults/index.js";
3
+ import { createReadStream, createWriteStream, promises as fs, WriteStream } from "fs";
4
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from "./crypto.js";
5
+ import { generateMessageIDV2 } from "./generics.js";
6
+ import { proto } from "../../WAProto/index.js";
7
+ import { Readable, Transform } from "stream";
8
+ import { exec } from "child_process";
9
+ import { Boom } from "@hapi/boom";
10
+ import * as Crypto from "crypto";
11
+ import { once } from "events";
12
+ import { tmpdir } from "os";
13
+ import { join } from "path";
14
+ import { URL } from "url";
15
+ import Jimp from "jimp";
16
+ import { PassThrough } from 'stream';
17
+ import ff from 'fluent-ffmpeg';
18
+ import * as musicMetadata from 'music-metadata';
19
+
20
+ const getTmpFilesDirectory = () => tmpdir();
21
+
22
+ export const hkdfInfoKey = (type) => {
23
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
24
+ return `WhatsApp ${hkdfInfo} Keys`;
25
+ };
26
+
27
+ export const getRawMediaUploadData = async (media, mediaType, logger) => {
28
+ const { stream } = await getStream(media);
29
+ logger?.debug("got stream for raw upload");
30
+ const hasher = Crypto.createHash("sha256");
31
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
32
+ const fileWriteStream = createWriteStream(filePath);
33
+ let fileLength = 0;
34
+ try {
35
+ for await (const data of stream) {
36
+ fileLength += data.length;
37
+ hasher.update(data);
38
+ if (!fileWriteStream.write(data)) {
39
+ await once(fileWriteStream, "drain");
40
+ }
41
+ }
42
+ fileWriteStream.end();
43
+ await once(fileWriteStream, "finish");
44
+ stream.destroy();
45
+ const fileSha256 = hasher.digest();
46
+ logger?.debug("hashed data for raw upload");
47
+ return {
48
+ filePath: filePath,
49
+ fileSha256,
50
+ fileLength
51
+ };
52
+ }
53
+ catch (error) {
54
+ fileWriteStream.destroy();
55
+ stream.destroy();
56
+ try {
57
+ await fs.unlink(filePath);
58
+ }
59
+ catch {
60
+ }
61
+ throw error;
62
+ }
63
+ };
64
+
65
+ export const prepareStream = async (
66
+ media,
67
+ mediaType,
68
+ { logger, saveOriginalFileIfRequired, opts } = {}
69
+ ) => {
70
+ const { stream, type } = await getStream(media, opts);
71
+ logger?.debug("fetched media stream");
72
+
73
+ let bodyPath;
74
+ let didSaveToTmpPath = false;
75
+
76
+ try {
77
+ const buffer = await toBuffer(stream);
78
+
79
+ if (type === "file") {
80
+ bodyPath = media.url;
81
+ } else if (saveOriginalFileIfRequired) {
82
+ bodyPath = path.join(getTmpFilesDirectory(), mediaType + generateMessageIDV2());
83
+ fs.writeFileSync(bodyPath, buffer);
84
+ didSaveToTmpPath = true;
85
+ }
86
+
87
+ const fileLength = buffer.length;
88
+ const fileSha256 = Crypto.createHash("sha256").update(buffer).digest();
89
+
90
+ stream?.destroy();
91
+ logger?.debug("prepare stream data successfully");
92
+
93
+ return {
94
+ mediaKey: undefined,
95
+ encWriteStream: buffer,
96
+ fileLength,
97
+ fileSha256,
98
+ fileEncSha256: undefined,
99
+ bodyPath,
100
+ didSaveToTmpPath,
101
+ };
102
+ } catch (error) {
103
+ stream.destroy();
104
+ if (didSaveToTmpPath) {
105
+ try {
106
+ await fs.promises.unlink(bodyPath);
107
+ } catch (err) {
108
+ logger?.error({ err }, "failed to save to tmp path");
109
+ }
110
+ }
111
+ throw error;
112
+ }
113
+ };
114
+
115
+ export async function getMediaKeys(buffer, mediaType) {
116
+ if (!buffer) {
117
+ throw new Boom("Cannot derive from empty media key");
118
+ }
119
+ if (typeof buffer === "string") {
120
+ buffer = Buffer.from(buffer.replace("data:;base64,", ""), "base64");
121
+ }
122
+ const expandedMediaKey = await hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
123
+ return {
124
+ iv: expandedMediaKey.slice(0, 16),
125
+ cipherKey: expandedMediaKey.slice(16, 48),
126
+ macKey: expandedMediaKey.slice(48, 80)
127
+ };
128
+ }
129
+
130
+ const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
131
+ const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
132
+ exec(cmd, err => {
133
+ if (err) {
134
+ reject(err);
135
+ }
136
+ else {
137
+ resolve();
138
+ }
139
+ });
140
+ });
141
+
142
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
143
+ if (bufferOrFilePath instanceof Readable) {
144
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
145
+ }
146
+ const image = await Jimp.read(bufferOrFilePath);
147
+ const dimensions = { width: image.bitmap.width, height: image.bitmap.height };
148
+ const resized = image.resize(width, Jimp.RESIZE_BILINEAR).quality(50);
149
+ const buffer = await resized.getBufferAsync(Jimp.MIME_JPEG);
150
+ return { buffer, original: dimensions };
151
+ };
152
+
153
+ export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/\=+$/, ""));
154
+ export const generateProfilePicture = async (mediaUpload) => {
155
+ let bufferOrFilePath;
156
+ let img;
157
+
158
+ if (Buffer.isBuffer(mediaUpload)) {
159
+ bufferOrFilePath = mediaUpload;
160
+ } else if ('url' in mediaUpload) {
161
+ bufferOrFilePath = mediaUpload.url.toString();
162
+ } else {
163
+ bufferOrFilePath = await toBuffer(mediaUpload.stream);
164
+ }
165
+
166
+ const jimp = await Jimp.read(bufferOrFilePath);
167
+ const cropped =
168
+ jimp.getWidth() > jimp.getHeight()
169
+ ? jimp.resize(550, Jimp.AUTO)
170
+ : jimp.resize(Jimp.AUTO, 650);
171
+
172
+ img = await cropped.quality(100).getBufferAsync(Jimp.MIME_JPEG);
173
+
174
+ return { img };
175
+ };
176
+
177
+ export const mediaMessageSHA256B64 = (message) => {
178
+ const media = Object.values(message)[0];
179
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString("base64");
180
+ };
181
+
182
+ export async function getAudioDuration(buffer) {
183
+ try {
184
+ return await new Promise((resolve, reject) => {
185
+ const inputStream = new PassThrough();
186
+ inputStream.end(buffer);
187
+
188
+ ff(inputStream)
189
+ .ffprobe((err, data) => {
190
+ if (err) reject(err);
191
+ else resolve(data.format.duration);
192
+ });
193
+ });
194
+ } catch (error) {
195
+ let metadata;
196
+ if (Buffer.isBuffer(buffer)) {
197
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true });
198
+ } else if (typeof buffer === 'string') {
199
+ const rStream = createReadStream(buffer);
200
+ try {
201
+ metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true });
202
+ } finally {
203
+ rStream.destroy();
204
+ }
205
+ } else {
206
+ metadata = await musicMetadata.parseStream(buffer, undefined, { duration: true });
207
+ }
208
+ return metadata.format.duration;
209
+ }
210
+ }
211
+
212
+ export async function getAudioWaveform(buffer, logger) {
213
+ try {
214
+ let audioData;
215
+ if (Buffer.isBuffer(buffer)) {
216
+ audioData = buffer;
217
+ } else if (typeof buffer === 'string') {
218
+ const rStream = createReadStream(buffer);
219
+ audioData = await toBuffer(rStream);
220
+ } else {
221
+ audioData = await toBuffer(buffer);
222
+ }
223
+
224
+ return await new Promise((resolve, reject) => {
225
+ const inputStream = new PassThrough();
226
+ inputStream.end(audioData);
227
+ const chunks = [];
228
+ const bars = 64;
229
+
230
+ ff(inputStream)
231
+ .audioChannels(1)
232
+ .audioFrequency(16000)
233
+ .format('s16le')
234
+ .on('error', reject)
235
+ .on('end', () => {
236
+ const rawData = Buffer.concat(chunks);
237
+ const samples = rawData.length / 2;
238
+ const amplitudes = [];
239
+
240
+ for (let i = 0; i < samples; i++) {
241
+ amplitudes.push(Math.abs(rawData.readInt16LE(i * 2)) / 32768);
242
+ }
243
+
244
+ const blockSize = Math.floor(amplitudes.length / bars);
245
+ const avg = [];
246
+ for (let i = 0; i < bars; i++) {
247
+ const block = amplitudes.slice(i * blockSize, (i + 1) * blockSize);
248
+ avg.push(block.reduce((a, b) => a + b, 0) / block.length);
249
+ }
250
+
251
+ const max = Math.max(...avg);
252
+ const normalized = avg.map(v => Math.floor((v / max) * 100));
253
+ resolve(new Uint8Array(normalized));
254
+ })
255
+ .pipe()
256
+ .on('data', chunk => chunks.push(chunk));
257
+ });
258
+ } catch (e) {
259
+ logger?.debug(e);
260
+ }
261
+ }
262
+
263
+ export async function convertToOpusBuffer(buffer, logger) {
264
+ try {
265
+ return await new Promise((resolve, reject) => {
266
+ const inStream = new PassThrough();
267
+ const outStream = new PassThrough();
268
+ const chunks = [];
269
+ inStream.end(buffer);
270
+
271
+ ff(inStream)
272
+ .noVideo()
273
+ .audioCodec('libopus')
274
+ .format('ogg')
275
+ .audioBitrate('48k')
276
+ .audioChannels(1)
277
+ .audioFrequency(48000)
278
+ .outputOptions([
279
+ '-vn',
280
+ '-b:a 64k',
281
+ '-ac 2',
282
+ '-ar 48000',
283
+ '-map_metadata', '-1',
284
+ '-application', 'voip'
285
+ ])
286
+ .on('error', reject)
287
+ .on('end', () => resolve(Buffer.concat(chunks)))
288
+ .pipe(outStream, { end: true });
289
+
290
+ outStream.on('data', c => chunks.push(c));
291
+ });
292
+ } catch (e) {
293
+ logger?.debug(e);
294
+ throw e;
295
+ }
296
+ }
297
+
298
+ export const toReadable = (buffer) => {
299
+ const readable = new Readable({ read: () => { } });
300
+ readable.push(buffer);
301
+ readable.push(null);
302
+ return readable;
303
+ };
304
+
305
+ export const toBuffer = async (stream) => {
306
+ const chunks = [];
307
+ for await (const chunk of stream) {
308
+ chunks.push(chunk);
309
+ }
310
+ stream.destroy();
311
+ return Buffer.concat(chunks);
312
+ };
313
+
314
+ export const getStream = async (item, opts) => {
315
+ if (Buffer.isBuffer(item)) {
316
+ return { stream: toReadable(item), type: "buffer" };
317
+ }
318
+ if ("stream" in item) {
319
+ return { stream: item.stream, type: "readable" };
320
+ }
321
+ const urlStr = item.url.toString();
322
+ if (urlStr.startsWith("data:")) {
323
+ const buffer = Buffer.from(urlStr.split(",")[1], "base64");
324
+ return { stream: toReadable(buffer), type: "buffer" };
325
+ }
326
+ if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) {
327
+ return { stream: await getHttpStream(item.url, opts), type: "remote" };
328
+ }
329
+ return { stream: createReadStream(item.url), type: "file" };
330
+ };
331
+
332
+ export async function generateThumbnail(file, mediaType, options) {
333
+ let thumbnail;
334
+ let originalImageDimensions;
335
+ if (mediaType === "image") {
336
+ const { buffer, original } = await extractImageThumb(file);
337
+ thumbnail = buffer.toString("base64");
338
+ if (original.width && original.height) {
339
+ originalImageDimensions = {
340
+ width: original.width,
341
+ height: original.height
342
+ };
343
+ }
344
+ }
345
+ else if (mediaType === "video") {
346
+ const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + ".jpg");
347
+ try {
348
+ await extractVideoThumb(file, imgFilename, "00:00:00", { width: 32, height: 32 });
349
+ const buff = await fs.readFile(imgFilename);
350
+ thumbnail = buff.toString("base64");
351
+ await fs.unlink(imgFilename);
352
+ }
353
+ catch (err) {
354
+ options.logger?.debug("could not generate video thumb: " + err);
355
+ }
356
+ }
357
+ return {
358
+ thumbnail,
359
+ originalImageDimensions
360
+ };
361
+ }
362
+
363
+ export const getHttpStream = async (url, options = {}) => {
364
+ const response = await fetch(url.toString(), {
365
+ dispatcher: options.dispatcher,
366
+ method: "GET",
367
+ headers: options.headers
368
+ });
369
+ if (!response.ok) {
370
+ throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
371
+ }
372
+ return Readable.fromWeb(response.body);
373
+ };
374
+
375
+ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, isPtt, forceOpus } = {}) => {
376
+ const { stream, type } = await getStream(media, opts);
377
+ logger?.debug("fetched media stream");
378
+
379
+ let finalStream = stream;
380
+
381
+ // Tambahan untuk konversi audio jadi Opus (PTT)
382
+ if (mediaType === 'audio' && (isPtt === true || forceOpus === true)) {
383
+ try {
384
+ const buffer = await toBuffer(stream);
385
+ const opusBuffer = await convertToOpusBuffer(buffer, logger);
386
+ finalStream = toReadable(opusBuffer);
387
+ logger?.debug('converted audio to Opus');
388
+ } catch (error) {
389
+ logger?.error('failed to convert audio to Opus, fallback to original stream');
390
+ const { stream: newStream } = await getStream(media, opts);
391
+ finalStream = newStream;
392
+ }
393
+ }
394
+
395
+ const mediaKey = Crypto.randomBytes(32);
396
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
397
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + "-enc");
398
+ const encFileWriteStream = createWriteStream(encFilePath);
399
+ let originalFileStream;
400
+ let originalFilePath;
401
+
402
+ if (saveOriginalFileIfRequired) {
403
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + "-original");
404
+ originalFileStream = createWriteStream(originalFilePath);
405
+ }
406
+
407
+ let fileLength = 0;
408
+ const aes = Crypto.createCipheriv("aes-256-cbc", cipherKey, iv);
409
+ const hmac = Crypto.createHmac("sha256", macKey).update(iv);
410
+ const sha256Plain = Crypto.createHash("sha256");
411
+ const sha256Enc = Crypto.createHash("sha256");
412
+
413
+ const onChunk = (buff) => {
414
+ sha256Enc.update(buff);
415
+ hmac.update(buff);
416
+ encFileWriteStream.write(buff);
417
+ };
418
+
419
+ try {
420
+ for await (const data of finalStream) {
421
+ fileLength += data.length;
422
+ if (type === "remote" && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
423
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
424
+ data: { media, type }
425
+ });
426
+ }
427
+ if (originalFileStream) {
428
+ if (!originalFileStream.write(data)) {
429
+ await once(originalFileStream, "drain");
430
+ }
431
+ }
432
+ sha256Plain.update(data);
433
+ onChunk(aes.update(data));
434
+ }
435
+
436
+ onChunk(aes.final());
437
+ const mac = hmac.digest().slice(0, 10);
438
+ sha256Enc.update(mac);
439
+ const fileSha256 = sha256Plain.digest();
440
+ const fileEncSha256 = sha256Enc.digest();
441
+
442
+ encFileWriteStream.write(mac);
443
+ encFileWriteStream.end();
444
+ originalFileStream?.end?.();
445
+ finalStream.destroy();
446
+ logger?.debug("encrypted data successfully");
447
+
448
+ return {
449
+ mediaKey,
450
+ originalFilePath,
451
+ encFilePath,
452
+ mac,
453
+ fileEncSha256,
454
+ fileSha256,
455
+ fileLength
456
+ };
457
+ } catch (error) {
458
+ encFileWriteStream.destroy();
459
+ originalFileStream?.destroy?.();
460
+ aes.destroy();
461
+ hmac.destroy();
462
+ sha256Plain.destroy();
463
+ sha256Enc.destroy();
464
+ finalStream.destroy();
465
+
466
+ try {
467
+ await fs.promises.unlink(encFilePath);
468
+ if (originalFilePath) {
469
+ await fs.promises.unlink(originalFilePath);
470
+ }
471
+ } catch (err) {
472
+ logger?.error({ err }, "failed deleting tmp files");
473
+ }
474
+ throw error;
475
+ }
476
+ };
477
+
478
+ const DEF_HOST = "mmg.whatsapp.net";
479
+ const AES_CHUNK_SIZE = 16;
480
+ const toSmallestChunkSize = (num) => {
481
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
482
+ };
483
+
484
+ export const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
485
+ export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
486
+ const isValidMediaUrl = url?.startsWith("https://mmg.whatsapp.net/");
487
+ const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath);
488
+ if (!downloadUrl) {
489
+ throw new Boom("No valid media URL or directPath present in message", { statusCode: 400 });
490
+ }
491
+ const keys = await getMediaKeys(mediaKey, type);
492
+ return downloadEncryptedContent(downloadUrl, keys, opts);
493
+ };
494
+
495
+ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
496
+ let bytesFetched = 0;
497
+ let startChunk = 0;
498
+ let firstBlockIsIV = false;
499
+ if (startByte) {
500
+ const chunk = toSmallestChunkSize(startByte || 0);
501
+ if (chunk) {
502
+ startChunk = chunk - AES_CHUNK_SIZE;
503
+ bytesFetched = chunk;
504
+ firstBlockIsIV = true;
505
+ }
506
+ }
507
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
508
+ const headersInit = options?.headers ? options.headers : undefined;
509
+ const headers = {
510
+ ...(headersInit
511
+ ? Array.isArray(headersInit)
512
+ ? Object.fromEntries(headersInit)
513
+ : headersInit
514
+ : {}),
515
+ Origin: DEFAULT_ORIGIN
516
+ };
517
+ if (startChunk || endChunk) {
518
+ headers.Range = `bytes=${startChunk}-`;
519
+ if (endChunk) {
520
+ headers.Range += endChunk;
521
+ }
522
+ }
523
+ const fetched = await getHttpStream(downloadUrl, {
524
+ ...(options || {}),
525
+ headers
526
+ });
527
+ let remainingBytes = Buffer.from([]);
528
+ let aes;
529
+ const pushBytes = (bytes, push) => {
530
+ if (startByte || endByte) {
531
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
532
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
533
+ push(bytes.slice(start, end));
534
+ bytesFetched += bytes.length;
535
+ }
536
+ else {
537
+ push(bytes);
538
+ }
539
+ };
540
+ const output = new Transform({
541
+ transform(chunk, _, callback) {
542
+ let data = Buffer.concat([remainingBytes, chunk]);
543
+ const decryptLength = toSmallestChunkSize(data.length);
544
+ remainingBytes = data.slice(decryptLength);
545
+ data = data.slice(0, decryptLength);
546
+ if (!aes) {
547
+ let ivValue = iv;
548
+ if (firstBlockIsIV) {
549
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
550
+ data = data.slice(AES_CHUNK_SIZE);
551
+ }
552
+ aes = Crypto.createDecipheriv("aes-256-cbc", cipherKey, ivValue);
553
+ if (endByte) {
554
+ aes.setAutoPadding(false);
555
+ }
556
+ }
557
+ try {
558
+ pushBytes(aes.update(data), b => this.push(b));
559
+ callback();
560
+ }
561
+ catch (error) {
562
+ callback(error);
563
+ }
564
+ },
565
+ final(callback) {
566
+ try {
567
+ pushBytes(aes.final(), b => this.push(b));
568
+ callback();
569
+ }
570
+ catch (error) {
571
+ callback(error);
572
+ }
573
+ }
574
+ });
575
+ return fetched.pipe(output, { end: true });
576
+ };
577
+
578
+ export function extensionForMediaMessage(message) {
579
+ const getExtension = (mimetype) => mimetype.split(";")[0]?.split("/")[1];
580
+ const type = Object.keys(message)[0];
581
+ let extension;
582
+ if (type === "locationMessage" || type === "liveLocationMessage" || type === "productMessage") {
583
+ extension = ".jpeg";
584
+ }
585
+ else {
586
+ const messageContent = message[type];
587
+ extension = getExtension(messageContent.mimetype);
588
+ }
589
+ return extension;
590
+ }
591
+
592
+ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
593
+ return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
594
+ let uploadInfo = await refreshMediaConn(false);
595
+ let urls;
596
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
597
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
598
+ for (const { hostname } of hosts) {
599
+ logger.debug(`uploading to "${hostname}"`);
600
+ const auth = encodeURIComponent(uploadInfo.auth);
601
+ const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
602
+ let result;
603
+ try {
604
+ const stream = createReadStream(filePath);
605
+ const response = await fetch(url, {
606
+ dispatcher: fetchAgent,
607
+ method: "POST",
608
+ body: stream,
609
+ headers: {
610
+ ...(() => {
611
+ const hdrs = options?.headers;
612
+ if (!hdrs)
613
+ return {};
614
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
615
+ })(),
616
+ "Content-Type": "application/octet-stream",
617
+ Origin: DEFAULT_ORIGIN
618
+ },
619
+ duplex: "half",
620
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
621
+ });
622
+ let parsed = undefined;
623
+ try {
624
+ parsed = await response.json();
625
+ }
626
+ catch {
627
+ parsed = undefined;
628
+ }
629
+ result = parsed;
630
+ if (result?.url || result?.directPath) {
631
+ urls = {
632
+ mediaUrl: result.url,
633
+ directPath: result.direct_path,
634
+ meta_hmac: result.meta_hmac,
635
+ fbid: result.fbid,
636
+ ts: result.ts
637
+ };
638
+ break;
639
+ }
640
+ else {
641
+ uploadInfo = await refreshMediaConn(true);
642
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
643
+ }
644
+ }
645
+ catch (error) {
646
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
647
+ logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? "" : ", retrying..."}`);
648
+ }
649
+ }
650
+ if (!urls) {
651
+ throw new Boom("Media upload failed on all hosts", { statusCode: 500 });
652
+ }
653
+ return urls;
654
+ };
655
+ };
656
+
657
+ const getMediaRetryKey = (mediaKey) => {
658
+ return hkdf(mediaKey, 32, { info: "WhatsApp Media Retry Notification" });
659
+ };
660
+
661
+ export const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
662
+ const recp = { stanzaId: key.id };
663
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
664
+ const iv = Crypto.randomBytes(12);
665
+ const retryKey = await getMediaRetryKey(mediaKey);
666
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
667
+ const req = {
668
+ tag: "receipt",
669
+ attrs: {
670
+ id: key.id,
671
+ to: jidNormalizedUser(meId),
672
+ type: "server-error"
673
+ },
674
+ content: [
675
+ {
676
+ tag: "encrypt",
677
+ attrs: {},
678
+ content: [
679
+ { tag: "enc_p", attrs: {}, content: ciphertext },
680
+ { tag: "enc_iv", attrs: {}, content: iv }
681
+ ]
682
+ },
683
+ {
684
+ tag: "rmr",
685
+ attrs: {
686
+ jid: key.remoteJid,
687
+ from_me: (!!key.fromMe).toString(),
688
+ participant: key.participant || undefined
689
+ }
690
+ }
691
+ ]
692
+ };
693
+ return req;
694
+ };
695
+
696
+ export const decodeMediaRetryNode = (node) => {
697
+ const rmrNode = getBinaryNodeChild(node, "rmr");
698
+ const event = {
699
+ key: {
700
+ id: node.attrs.id,
701
+ remoteJid: rmrNode.attrs.jid,
702
+ fromMe: rmrNode.attrs.from_me === "true",
703
+ participant: rmrNode.attrs.participant
704
+ }
705
+ };
706
+ const errorNode = getBinaryNodeChild(node, "error");
707
+ if (errorNode) {
708
+ const errorCode = +errorNode.attrs.code;
709
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
710
+ data: errorNode.attrs,
711
+ statusCode: getStatusCodeForMediaRetry(errorCode)
712
+ });
713
+ }
714
+ else {
715
+ const encryptedInfoNode = getBinaryNodeChild(node, "encrypt");
716
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, "enc_p");
717
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, "enc_iv");
718
+ if (ciphertext && iv) {
719
+ event.media = { ciphertext, iv };
720
+ }
721
+ else {
722
+ event.error = new Boom("Failed to re-upload media (missing ciphertext)", { statusCode: 404 });
723
+ }
724
+ }
725
+ return event;
726
+ };
727
+
728
+ export const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
729
+ const retryKey = await getMediaRetryKey(mediaKey);
730
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
731
+ return proto.MediaRetryNotification.decode(plaintext);
732
+ };
733
+
734
+ export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
735
+ const MEDIA_RETRY_STATUS_MAP = {
736
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
737
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
738
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
739
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
740
+ };