@nexustechpro/baileys 1.0.1

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