@d0v3riz/baileys 6.3.0

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 (147) hide show
  1. package/README.md +956 -0
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +2845 -0
  4. package/WAProto/index.d.ts +32006 -0
  5. package/WAProto/index.js +87184 -0
  6. package/WASignalGroup/GroupProtocol.js +1697 -0
  7. package/WASignalGroup/ciphertext_message.js +16 -0
  8. package/WASignalGroup/group_cipher.js +106 -0
  9. package/WASignalGroup/group_session_builder.js +46 -0
  10. package/WASignalGroup/index.js +5 -0
  11. package/WASignalGroup/keyhelper.js +21 -0
  12. package/WASignalGroup/protobufs.js +3 -0
  13. package/WASignalGroup/readme.md +6 -0
  14. package/WASignalGroup/sender_chain_key.js +50 -0
  15. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  16. package/WASignalGroup/sender_key_message.js +92 -0
  17. package/WASignalGroup/sender_key_name.js +70 -0
  18. package/WASignalGroup/sender_key_record.js +54 -0
  19. package/WASignalGroup/sender_key_state.js +129 -0
  20. package/WASignalGroup/sender_message_key.js +39 -0
  21. package/lib/Defaults/baileys-version.json +3 -0
  22. package/lib/Defaults/index.d.ts +284 -0
  23. package/lib/Defaults/index.js +115 -0
  24. package/lib/Defaults/phonenumber-mcc.json +223 -0
  25. package/lib/Signal/libsignal.d.ts +3 -0
  26. package/lib/Signal/libsignal.js +151 -0
  27. package/lib/Socket/Client/abstract-socket-client.d.ts +16 -0
  28. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  29. package/lib/Socket/Client/index.d.ts +3 -0
  30. package/lib/Socket/Client/index.js +19 -0
  31. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  32. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  33. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  34. package/lib/Socket/Client/web-socket-client.js +62 -0
  35. package/lib/Socket/business.d.ts +124 -0
  36. package/lib/Socket/business.js +259 -0
  37. package/lib/Socket/chats.d.ts +74 -0
  38. package/lib/Socket/chats.js +838 -0
  39. package/lib/Socket/groups.d.ts +105 -0
  40. package/lib/Socket/groups.js +291 -0
  41. package/lib/Socket/index.d.ts +126 -0
  42. package/lib/Socket/index.js +10 -0
  43. package/lib/Socket/messages-recv.d.ts +112 -0
  44. package/lib/Socket/messages-recv.js +641 -0
  45. package/lib/Socket/messages-send.d.ts +110 -0
  46. package/lib/Socket/messages-send.js +648 -0
  47. package/lib/Socket/registration.d.ts +211 -0
  48. package/lib/Socket/registration.js +166 -0
  49. package/lib/Socket/socket.d.ts +42 -0
  50. package/lib/Socket/socket.js +527 -0
  51. package/lib/Store/index.d.ts +3 -0
  52. package/lib/Store/index.js +10 -0
  53. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  54. package/lib/Store/make-cache-manager-store.js +83 -0
  55. package/lib/Store/make-in-memory-store.d.ts +117 -0
  56. package/lib/Store/make-in-memory-store.js +435 -0
  57. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  58. package/lib/Store/make-ordered-dictionary.js +81 -0
  59. package/lib/Store/object-repository.d.ts +10 -0
  60. package/lib/Store/object-repository.js +27 -0
  61. package/lib/Types/Auth.d.ts +106 -0
  62. package/lib/Types/Auth.js +2 -0
  63. package/lib/Types/Call.d.ts +12 -0
  64. package/lib/Types/Call.js +2 -0
  65. package/lib/Types/Chat.d.ts +102 -0
  66. package/lib/Types/Chat.js +4 -0
  67. package/lib/Types/Contact.d.ts +18 -0
  68. package/lib/Types/Contact.js +2 -0
  69. package/lib/Types/Events.d.ts +152 -0
  70. package/lib/Types/Events.js +2 -0
  71. package/lib/Types/GroupMetadata.d.ts +42 -0
  72. package/lib/Types/GroupMetadata.js +2 -0
  73. package/lib/Types/Label.d.ts +35 -0
  74. package/lib/Types/Label.js +27 -0
  75. package/lib/Types/LabelAssociation.d.ts +29 -0
  76. package/lib/Types/LabelAssociation.js +9 -0
  77. package/lib/Types/Message.d.ts +245 -0
  78. package/lib/Types/Message.js +9 -0
  79. package/lib/Types/Product.d.ts +78 -0
  80. package/lib/Types/Product.js +2 -0
  81. package/lib/Types/Signal.d.ts +57 -0
  82. package/lib/Types/Signal.js +2 -0
  83. package/lib/Types/Socket.d.ts +106 -0
  84. package/lib/Types/Socket.js +2 -0
  85. package/lib/Types/State.d.ts +27 -0
  86. package/lib/Types/State.js +2 -0
  87. package/lib/Types/index.d.ts +54 -0
  88. package/lib/Types/index.js +39 -0
  89. package/lib/Utils/auth-utils.d.ts +18 -0
  90. package/lib/Utils/auth-utils.js +202 -0
  91. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  92. package/lib/Utils/baileys-event-stream.js +63 -0
  93. package/lib/Utils/business.d.ts +22 -0
  94. package/lib/Utils/business.js +234 -0
  95. package/lib/Utils/chat-utils.d.ts +71 -0
  96. package/lib/Utils/chat-utils.js +710 -0
  97. package/lib/Utils/crypto.d.ts +38 -0
  98. package/lib/Utils/crypto.js +137 -0
  99. package/lib/Utils/decode-wa-message.d.ts +19 -0
  100. package/lib/Utils/decode-wa-message.js +160 -0
  101. package/lib/Utils/event-buffer.d.ts +35 -0
  102. package/lib/Utils/event-buffer.js +514 -0
  103. package/lib/Utils/generics.d.ts +92 -0
  104. package/lib/Utils/generics.js +368 -0
  105. package/lib/Utils/history.d.ts +15 -0
  106. package/lib/Utils/history.js +91 -0
  107. package/lib/Utils/index.d.ts +17 -0
  108. package/lib/Utils/index.js +33 -0
  109. package/lib/Utils/link-preview.d.ts +21 -0
  110. package/lib/Utils/link-preview.js +116 -0
  111. package/lib/Utils/logger.d.ts +4 -0
  112. package/lib/Utils/logger.js +7 -0
  113. package/lib/Utils/lt-hash.d.ts +12 -0
  114. package/lib/Utils/lt-hash.js +51 -0
  115. package/lib/Utils/make-mutex.d.ts +7 -0
  116. package/lib/Utils/make-mutex.js +43 -0
  117. package/lib/Utils/messages-media.d.ts +101 -0
  118. package/lib/Utils/messages-media.js +632 -0
  119. package/lib/Utils/messages.d.ts +75 -0
  120. package/lib/Utils/messages.js +738 -0
  121. package/lib/Utils/noise-handler.d.ts +20 -0
  122. package/lib/Utils/noise-handler.js +142 -0
  123. package/lib/Utils/process-message.d.ts +41 -0
  124. package/lib/Utils/process-message.js +297 -0
  125. package/lib/Utils/signal.d.ts +32 -0
  126. package/lib/Utils/signal.js +151 -0
  127. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  128. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  129. package/lib/Utils/validate-connection.d.ts +11 -0
  130. package/lib/Utils/validate-connection.js +188 -0
  131. package/lib/WABinary/constants.d.ts +27 -0
  132. package/lib/WABinary/constants.js +40 -0
  133. package/lib/WABinary/decode.d.ts +7 -0
  134. package/lib/WABinary/decode.js +252 -0
  135. package/lib/WABinary/encode.d.ts +3 -0
  136. package/lib/WABinary/encode.js +228 -0
  137. package/lib/WABinary/generic-utils.d.ts +15 -0
  138. package/lib/WABinary/generic-utils.js +110 -0
  139. package/lib/WABinary/index.d.ts +5 -0
  140. package/lib/WABinary/index.js +21 -0
  141. package/lib/WABinary/jid-utils.d.ts +27 -0
  142. package/lib/WABinary/jid-utils.js +56 -0
  143. package/lib/WABinary/types.d.ts +18 -0
  144. package/lib/WABinary/types.js +2 -0
  145. package/lib/index.d.ts +9 -0
  146. package/lib/index.js +27 -0
  147. package/package.json +100 -0
@@ -0,0 +1,632 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.extensionForMediaMessage = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.getHttpStream = exports.generateThumbnail = exports.getStream = exports.toBuffer = exports.toReadable = exports.getAudioDuration = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.getMediaKeys = exports.hkdfInfoKey = void 0;
27
+ const boom_1 = require("@hapi/boom");
28
+ const child_process_1 = require("child_process");
29
+ const Crypto = __importStar(require("crypto"));
30
+ const events_1 = require("events");
31
+ const fs_1 = require("fs");
32
+ const os_1 = require("os");
33
+ const path_1 = require("path");
34
+ const stream_1 = require("stream");
35
+ const WAProto_1 = require("../../WAProto");
36
+ const Defaults_1 = require("../Defaults");
37
+ const WABinary_1 = require("../WABinary");
38
+ const crypto_1 = require("./crypto");
39
+ const generics_1 = require("./generics");
40
+ const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
41
+ const getImageProcessingLibrary = async () => {
42
+ const [_jimp, sharp] = await Promise.all([
43
+ (async () => {
44
+ const jimp = await (Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { }));
45
+ return jimp;
46
+ })(),
47
+ (async () => {
48
+ const sharp = await (Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { }));
49
+ return sharp;
50
+ })()
51
+ ]);
52
+ if (sharp) {
53
+ return { sharp };
54
+ }
55
+ const jimp = (_jimp === null || _jimp === void 0 ? void 0 : _jimp.default) || _jimp;
56
+ if (jimp) {
57
+ return { jimp };
58
+ }
59
+ throw new boom_1.Boom('No image processing library available');
60
+ };
61
+ const hkdfInfoKey = (type) => {
62
+ const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type];
63
+ return `WhatsApp ${hkdfInfo} Keys`;
64
+ };
65
+ exports.hkdfInfoKey = hkdfInfoKey;
66
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
67
+ function getMediaKeys(buffer, mediaType) {
68
+ if (!buffer) {
69
+ throw new boom_1.Boom('Cannot derive from empty media key');
70
+ }
71
+ if (typeof buffer === 'string') {
72
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
73
+ }
74
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
75
+ const expandedMediaKey = (0, crypto_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
76
+ return {
77
+ iv: expandedMediaKey.slice(0, 16),
78
+ cipherKey: expandedMediaKey.slice(16, 48),
79
+ macKey: expandedMediaKey.slice(48, 80),
80
+ };
81
+ }
82
+ exports.getMediaKeys = getMediaKeys;
83
+ /** Extracts video thumb using FFMPEG */
84
+ const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
85
+ const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
86
+ (0, child_process_1.exec)(cmd, (err) => {
87
+ if (err) {
88
+ reject(err);
89
+ }
90
+ else {
91
+ resolve();
92
+ }
93
+ });
94
+ });
95
+ const extractImageThumb = async (bufferOrFilePath, width = 32) => {
96
+ var _a, _b;
97
+ if (bufferOrFilePath instanceof stream_1.Readable) {
98
+ bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
99
+ }
100
+ const lib = await getImageProcessingLibrary();
101
+ if ('sharp' in lib && typeof ((_a = lib.sharp) === null || _a === void 0 ? void 0 : _a.default) === 'function') {
102
+ const img = lib.sharp.default(bufferOrFilePath);
103
+ const dimensions = await img.metadata();
104
+ const buffer = await img
105
+ .resize(width)
106
+ .jpeg({ quality: 50 })
107
+ .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 ((_b = lib.jimp) === null || _b === void 0 ? void 0 : _b.read) === 'function') {
117
+ const { read, MIME_JPEG, RESIZE_BILINEAR, AUTO } = lib.jimp;
118
+ const jimp = await read(bufferOrFilePath);
119
+ const dimensions = {
120
+ width: jimp.getWidth(),
121
+ height: jimp.getHeight()
122
+ };
123
+ const buffer = await jimp
124
+ .quality(50)
125
+ .resize(width, AUTO, RESIZE_BILINEAR)
126
+ .getBufferAsync(MIME_JPEG);
127
+ return {
128
+ buffer,
129
+ original: dimensions
130
+ };
131
+ }
132
+ else {
133
+ throw new boom_1.Boom('No image processing library available');
134
+ }
135
+ };
136
+ exports.extractImageThumb = extractImageThumb;
137
+ const encodeBase64EncodedStringForUpload = (b64) => (encodeURIComponent(b64
138
+ .replace(/\+/g, '-')
139
+ .replace(/\//g, '_')
140
+ .replace(/\=+$/, '')));
141
+ exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
142
+ const generateProfilePicture = async (mediaUpload) => {
143
+ var _a, _b;
144
+ let bufferOrFilePath;
145
+ if (Buffer.isBuffer(mediaUpload)) {
146
+ bufferOrFilePath = mediaUpload;
147
+ }
148
+ else if ('url' in mediaUpload) {
149
+ bufferOrFilePath = mediaUpload.url.toString();
150
+ }
151
+ else {
152
+ bufferOrFilePath = await (0, exports.toBuffer)(mediaUpload.stream);
153
+ }
154
+ const lib = await getImageProcessingLibrary();
155
+ let img;
156
+ if ('sharp' in lib && typeof ((_a = lib.sharp) === null || _a === void 0 ? void 0 : _a.default) === 'function') {
157
+ img = lib.sharp.default(bufferOrFilePath)
158
+ .resize(640, 640)
159
+ .jpeg({
160
+ quality: 50,
161
+ })
162
+ .toBuffer();
163
+ }
164
+ else if ('jimp' in lib && typeof ((_b = lib.jimp) === null || _b === void 0 ? void 0 : _b.read) === 'function') {
165
+ const { read, MIME_JPEG, RESIZE_BILINEAR } = lib.jimp;
166
+ const jimp = await read(bufferOrFilePath);
167
+ const min = Math.min(jimp.getWidth(), jimp.getHeight());
168
+ const cropped = jimp.crop(0, 0, min, min);
169
+ img = cropped
170
+ .quality(50)
171
+ .resize(640, 640, RESIZE_BILINEAR)
172
+ .getBufferAsync(MIME_JPEG);
173
+ }
174
+ else {
175
+ throw new boom_1.Boom('No image processing library available');
176
+ }
177
+ return {
178
+ img: await img,
179
+ };
180
+ };
181
+ exports.generateProfilePicture = generateProfilePicture;
182
+ /** gets the SHA256 of the given media message */
183
+ const mediaMessageSHA256B64 = (message) => {
184
+ const media = Object.values(message)[0];
185
+ return (media === null || media === void 0 ? void 0 : media.fileSha256) && Buffer.from(media.fileSha256).toString('base64');
186
+ };
187
+ exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
188
+ async function getAudioDuration(buffer) {
189
+ const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
190
+ let metadata;
191
+ if (Buffer.isBuffer(buffer)) {
192
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true });
193
+ }
194
+ else if (typeof buffer === 'string') {
195
+ const rStream = (0, fs_1.createReadStream)(buffer);
196
+ try {
197
+ metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true });
198
+ }
199
+ finally {
200
+ rStream.destroy();
201
+ }
202
+ }
203
+ else {
204
+ metadata = await musicMetadata.parseStream(buffer, undefined, { duration: true });
205
+ }
206
+ return metadata.format.duration;
207
+ }
208
+ exports.getAudioDuration = getAudioDuration;
209
+ const toReadable = (buffer) => {
210
+ const readable = new stream_1.Readable({ read: () => { } });
211
+ readable.push(buffer);
212
+ readable.push(null);
213
+ return readable;
214
+ };
215
+ exports.toReadable = toReadable;
216
+ const toBuffer = async (stream) => {
217
+ const chunks = [];
218
+ for await (const chunk of stream) {
219
+ chunks.push(chunk);
220
+ }
221
+ stream.destroy();
222
+ return Buffer.concat(chunks);
223
+ };
224
+ exports.toBuffer = toBuffer;
225
+ const getStream = async (item, opts) => {
226
+ if (Buffer.isBuffer(item)) {
227
+ return { stream: (0, exports.toReadable)(item), type: 'buffer' };
228
+ }
229
+ if ('stream' in item) {
230
+ return { stream: item.stream, type: 'readable' };
231
+ }
232
+ if (item.url.toString().startsWith('http://') || item.url.toString().startsWith('https://')) {
233
+ return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
234
+ }
235
+ return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
236
+ };
237
+ exports.getStream = getStream;
238
+ /** generates a thumbnail for a given media, if required */
239
+ async function generateThumbnail(file, mediaType, options) {
240
+ var _a;
241
+ let thumbnail;
242
+ let originalImageDimensions;
243
+ if (mediaType === 'image') {
244
+ const { buffer, original } = await (0, exports.extractImageThumb)(file);
245
+ thumbnail = buffer.toString('base64');
246
+ if (original.width && original.height) {
247
+ originalImageDimensions = {
248
+ width: original.width,
249
+ height: original.height,
250
+ };
251
+ }
252
+ }
253
+ else if (mediaType === 'video') {
254
+ const imgFilename = (0, path_1.join)(getTmpFilesDirectory(), (0, generics_1.generateMessageID)() + '.jpg');
255
+ try {
256
+ await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
257
+ const buff = await fs_1.promises.readFile(imgFilename);
258
+ thumbnail = buff.toString('base64');
259
+ await fs_1.promises.unlink(imgFilename);
260
+ }
261
+ catch (err) {
262
+ (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug('could not generate video thumb: ' + err);
263
+ }
264
+ }
265
+ return {
266
+ thumbnail,
267
+ originalImageDimensions
268
+ };
269
+ }
270
+ exports.generateThumbnail = generateThumbnail;
271
+ const getHttpStream = async (url, options = {}) => {
272
+ const { default: axios } = await Promise.resolve().then(() => __importStar(require('axios')));
273
+ const fetched = await axios.get(url.toString(), { ...options, responseType: 'stream' });
274
+ return fetched.data;
275
+ };
276
+ exports.getHttpStream = getHttpStream;
277
+ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
278
+ const { stream, type } = await (0, exports.getStream)(media, opts);
279
+ logger === null || logger === void 0 ? void 0 : logger.debug('fetched media stream');
280
+ const mediaKey = Crypto.randomBytes(32);
281
+ const { cipherKey, iv, macKey } = getMediaKeys(mediaKey, mediaType);
282
+ const encWriteStream = new stream_1.Readable({ read: () => { } });
283
+ let bodyPath;
284
+ let writeStream;
285
+ let didSaveToTmpPath = false;
286
+ if (type === 'file') {
287
+ bodyPath = media.url;
288
+ }
289
+ else if (saveOriginalFileIfRequired) {
290
+ bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageID)());
291
+ writeStream = (0, fs_1.createWriteStream)(bodyPath);
292
+ didSaveToTmpPath = true;
293
+ }
294
+ let fileLength = 0;
295
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
296
+ let hmac = Crypto.createHmac('sha256', macKey).update(iv);
297
+ let sha256Plain = Crypto.createHash('sha256');
298
+ let sha256Enc = Crypto.createHash('sha256');
299
+ try {
300
+ for await (const data of stream) {
301
+ fileLength += data.length;
302
+ if (type === 'remote'
303
+ && (opts === null || opts === void 0 ? void 0 : opts.maxContentLength)
304
+ && fileLength + data.length > opts.maxContentLength) {
305
+ throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
306
+ data: { media, type }
307
+ });
308
+ }
309
+ sha256Plain = sha256Plain.update(data);
310
+ if (writeStream) {
311
+ if (!writeStream.write(data)) {
312
+ await (0, events_1.once)(writeStream, 'drain');
313
+ }
314
+ }
315
+ onChunk(aes.update(data));
316
+ }
317
+ onChunk(aes.final());
318
+ const mac = hmac.digest().slice(0, 10);
319
+ sha256Enc = sha256Enc.update(mac);
320
+ const fileSha256 = sha256Plain.digest();
321
+ const fileEncSha256 = sha256Enc.digest();
322
+ encWriteStream.push(mac);
323
+ encWriteStream.push(null);
324
+ writeStream === null || writeStream === void 0 ? void 0 : writeStream.end();
325
+ stream.destroy();
326
+ logger === null || logger === void 0 ? void 0 : logger.debug('encrypted data successfully');
327
+ return {
328
+ mediaKey,
329
+ encWriteStream,
330
+ bodyPath,
331
+ mac,
332
+ fileEncSha256,
333
+ fileSha256,
334
+ fileLength,
335
+ didSaveToTmpPath
336
+ };
337
+ }
338
+ catch (error) {
339
+ // destroy all streams with error
340
+ encWriteStream.destroy();
341
+ writeStream === null || writeStream === void 0 ? void 0 : writeStream.destroy();
342
+ aes.destroy();
343
+ hmac.destroy();
344
+ sha256Plain.destroy();
345
+ sha256Enc.destroy();
346
+ stream.destroy();
347
+ if (didSaveToTmpPath) {
348
+ try {
349
+ await fs_1.promises.unlink(bodyPath);
350
+ }
351
+ catch (err) {
352
+ logger === null || logger === void 0 ? void 0 : logger.error({ err }, 'failed to save to tmp path');
353
+ }
354
+ }
355
+ throw error;
356
+ }
357
+ function onChunk(buff) {
358
+ sha256Enc = sha256Enc.update(buff);
359
+ hmac = hmac.update(buff);
360
+ encWriteStream.push(buff);
361
+ }
362
+ };
363
+ exports.encryptedStream = encryptedStream;
364
+ const DEF_HOST = 'mmg.whatsapp.net';
365
+ const AES_CHUNK_SIZE = 16;
366
+ const toSmallestChunkSize = (num) => {
367
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
368
+ };
369
+ const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
370
+ exports.getUrlFromDirectPath = getUrlFromDirectPath;
371
+ const downloadContentFromMessage = ({ mediaKey, directPath, url }, type, opts = {}) => {
372
+ const downloadUrl = url || (0, exports.getUrlFromDirectPath)(directPath);
373
+ const keys = getMediaKeys(mediaKey, type);
374
+ return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
375
+ };
376
+ exports.downloadContentFromMessage = downloadContentFromMessage;
377
+ /**
378
+ * Decrypts and downloads an AES256-CBC encrypted file given the keys.
379
+ * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
380
+ * */
381
+ const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
382
+ let bytesFetched = 0;
383
+ let startChunk = 0;
384
+ let firstBlockIsIV = false;
385
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
386
+ if (startByte) {
387
+ const chunk = toSmallestChunkSize(startByte || 0);
388
+ if (chunk) {
389
+ startChunk = chunk - AES_CHUNK_SIZE;
390
+ bytesFetched = chunk;
391
+ firstBlockIsIV = true;
392
+ }
393
+ }
394
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
395
+ const headers = {
396
+ ...(options === null || options === void 0 ? void 0 : options.headers) || {},
397
+ Origin: Defaults_1.DEFAULT_ORIGIN,
398
+ };
399
+ if (startChunk || endChunk) {
400
+ headers.Range = `bytes=${startChunk}-`;
401
+ if (endChunk) {
402
+ headers.Range += endChunk;
403
+ }
404
+ }
405
+ // download the message
406
+ const fetched = await (0, exports.getHttpStream)(downloadUrl, {
407
+ ...options || {},
408
+ headers,
409
+ maxBodyLength: Infinity,
410
+ maxContentLength: Infinity,
411
+ });
412
+ let remainingBytes = Buffer.from([]);
413
+ let aes;
414
+ const pushBytes = (bytes, push) => {
415
+ if (startByte || endByte) {
416
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
417
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
418
+ push(bytes.slice(start, end));
419
+ bytesFetched += bytes.length;
420
+ }
421
+ else {
422
+ push(bytes);
423
+ }
424
+ };
425
+ const output = new stream_1.Transform({
426
+ transform(chunk, _, callback) {
427
+ let data = Buffer.concat([remainingBytes, chunk]);
428
+ const decryptLength = toSmallestChunkSize(data.length);
429
+ remainingBytes = data.slice(decryptLength);
430
+ data = data.slice(0, decryptLength);
431
+ if (!aes) {
432
+ let ivValue = iv;
433
+ if (firstBlockIsIV) {
434
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
435
+ data = data.slice(AES_CHUNK_SIZE);
436
+ }
437
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
438
+ // if an end byte that is not EOF is specified
439
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
440
+ if (endByte) {
441
+ aes.setAutoPadding(false);
442
+ }
443
+ }
444
+ try {
445
+ pushBytes(aes.update(data), b => this.push(b));
446
+ callback();
447
+ }
448
+ catch (error) {
449
+ callback(error);
450
+ }
451
+ },
452
+ final(callback) {
453
+ try {
454
+ pushBytes(aes.final(), b => this.push(b));
455
+ callback();
456
+ }
457
+ catch (error) {
458
+ callback(error);
459
+ }
460
+ },
461
+ });
462
+ return fetched.pipe(output, { end: true });
463
+ };
464
+ exports.downloadEncryptedContent = downloadEncryptedContent;
465
+ function extensionForMediaMessage(message) {
466
+ const getExtension = (mimetype) => mimetype.split(';')[0].split('/')[1];
467
+ const type = Object.keys(message)[0];
468
+ let extension;
469
+ if (type === 'locationMessage' ||
470
+ type === 'liveLocationMessage' ||
471
+ type === 'productMessage') {
472
+ extension = '.jpeg';
473
+ }
474
+ else {
475
+ const messageContent = message[type];
476
+ extension = getExtension(messageContent.mimetype);
477
+ }
478
+ return extension;
479
+ }
480
+ exports.extensionForMediaMessage = extensionForMediaMessage;
481
+ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
482
+ return async (stream, { mediaType, fileEncSha256B64, timeoutMs }) => {
483
+ var _a, _b;
484
+ const { default: axios } = await Promise.resolve().then(() => __importStar(require('axios')));
485
+ // send a query JSON to obtain the url & auth token to upload our media
486
+ let uploadInfo = await refreshMediaConn(false);
487
+ let urls;
488
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
489
+ const chunks = [];
490
+ for await (const chunk of stream) {
491
+ chunks.push(chunk);
492
+ }
493
+ const reqBody = Buffer.concat(chunks);
494
+ fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
495
+ for (const { hostname, maxContentLengthBytes } of hosts) {
496
+ logger.debug(`uploading to "${hostname}"`);
497
+ const auth = encodeURIComponent(uploadInfo.auth); // the auth token
498
+ const url = `https://${hostname}${Defaults_1.MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
499
+ let result;
500
+ try {
501
+ if (maxContentLengthBytes && reqBody.length > maxContentLengthBytes) {
502
+ throw new boom_1.Boom(`Body too large for "${hostname}"`, { statusCode: 413 });
503
+ }
504
+ const body = await axios.post(url, reqBody, {
505
+ ...options,
506
+ headers: {
507
+ ...options.headers || {},
508
+ 'Content-Type': 'application/octet-stream',
509
+ 'Origin': Defaults_1.DEFAULT_ORIGIN
510
+ },
511
+ httpsAgent: fetchAgent,
512
+ timeout: timeoutMs,
513
+ responseType: 'json',
514
+ maxBodyLength: Infinity,
515
+ maxContentLength: Infinity,
516
+ });
517
+ result = body.data;
518
+ if ((result === null || result === void 0 ? void 0 : result.url) || (result === null || result === void 0 ? void 0 : result.directPath)) {
519
+ urls = {
520
+ mediaUrl: result.url,
521
+ directPath: result.direct_path
522
+ };
523
+ break;
524
+ }
525
+ else {
526
+ uploadInfo = await refreshMediaConn(true);
527
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
528
+ }
529
+ }
530
+ catch (error) {
531
+ if (axios.isAxiosError(error)) {
532
+ result = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data;
533
+ }
534
+ const isLast = hostname === ((_b = hosts[uploadInfo.hosts.length - 1]) === null || _b === void 0 ? void 0 : _b.hostname);
535
+ logger.warn({ trace: error.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
536
+ }
537
+ }
538
+ if (!urls) {
539
+ throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
540
+ }
541
+ return urls;
542
+ };
543
+ };
544
+ exports.getWAUploadToServer = getWAUploadToServer;
545
+ const getMediaRetryKey = (mediaKey) => {
546
+ return (0, crypto_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
547
+ };
548
+ /**
549
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
550
+ */
551
+ const encryptMediaRetryRequest = (key, mediaKey, meId) => {
552
+ const recp = { stanzaId: key.id };
553
+ const recpBuffer = WAProto_1.proto.ServerErrorReceipt.encode(recp).finish();
554
+ const iv = Crypto.randomBytes(12);
555
+ const retryKey = getMediaRetryKey(mediaKey);
556
+ const ciphertext = (0, crypto_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
557
+ const req = {
558
+ tag: 'receipt',
559
+ attrs: {
560
+ id: key.id,
561
+ to: (0, WABinary_1.jidNormalizedUser)(meId),
562
+ type: 'server-error'
563
+ },
564
+ content: [
565
+ // this encrypt node is actually pretty useless
566
+ // the media is returned even without this node
567
+ // keeping it here to maintain parity with WA Web
568
+ {
569
+ tag: 'encrypt',
570
+ attrs: {},
571
+ content: [
572
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
573
+ { tag: 'enc_iv', attrs: {}, content: iv }
574
+ ]
575
+ },
576
+ {
577
+ tag: 'rmr',
578
+ attrs: {
579
+ jid: key.remoteJid,
580
+ 'from_me': (!!key.fromMe).toString(),
581
+ // @ts-ignore
582
+ participant: key.participant || undefined
583
+ }
584
+ }
585
+ ]
586
+ };
587
+ return req;
588
+ };
589
+ exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
590
+ const decodeMediaRetryNode = (node) => {
591
+ const rmrNode = (0, WABinary_1.getBinaryNodeChild)(node, 'rmr');
592
+ const event = {
593
+ key: {
594
+ id: node.attrs.id,
595
+ remoteJid: rmrNode.attrs.jid,
596
+ fromMe: rmrNode.attrs.from_me === 'true',
597
+ participant: rmrNode.attrs.participant
598
+ }
599
+ };
600
+ const errorNode = (0, WABinary_1.getBinaryNodeChild)(node, 'error');
601
+ if (errorNode) {
602
+ const errorCode = +errorNode.attrs.code;
603
+ event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode) });
604
+ }
605
+ else {
606
+ const encryptedInfoNode = (0, WABinary_1.getBinaryNodeChild)(node, 'encrypt');
607
+ const ciphertext = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
608
+ const iv = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
609
+ if (ciphertext && iv) {
610
+ event.media = { ciphertext, iv };
611
+ }
612
+ else {
613
+ event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
614
+ }
615
+ }
616
+ return event;
617
+ };
618
+ exports.decodeMediaRetryNode = decodeMediaRetryNode;
619
+ const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
620
+ const retryKey = getMediaRetryKey(mediaKey);
621
+ const plaintext = (0, crypto_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
622
+ return WAProto_1.proto.MediaRetryNotification.decode(plaintext);
623
+ };
624
+ exports.decryptMediaRetryData = decryptMediaRetryData;
625
+ const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
626
+ exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
627
+ const MEDIA_RETRY_STATUS_MAP = {
628
+ [WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
629
+ [WAProto_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
630
+ [WAProto_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
631
+ [WAProto_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
632
+ };