@gara31/void-baileys 7.0.0-rc.10

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