@ikyyjee/ikyysinggle 1.7.7

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 (142) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +8083 -0
  3. package/WAProto/fix-imports.js +85 -0
  4. package/WAProto/index.d.ts +29095 -0
  5. package/WAProto/index.js +172336 -0
  6. package/engine-requirements.js +10 -0
  7. package/lib/Defaults/index.js +194 -0
  8. package/lib/Signal/Group/ciphertext-message.js +12 -0
  9. package/lib/Signal/Group/group-session-builder.js +30 -0
  10. package/lib/Signal/Group/group_cipher.js +82 -0
  11. package/lib/Signal/Group/index.js +12 -0
  12. package/lib/Signal/Group/keyhelper.js +18 -0
  13. package/lib/Signal/Group/sender-chain-key.js +26 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  15. package/lib/Signal/Group/sender-key-message.js +66 -0
  16. package/lib/Signal/Group/sender-key-name.js +48 -0
  17. package/lib/Signal/Group/sender-key-record.js +41 -0
  18. package/lib/Signal/Group/sender-key-state.js +84 -0
  19. package/lib/Signal/Group/sender-message-key.js +26 -0
  20. package/lib/Signal/libsignal.js +431 -0
  21. package/lib/Signal/lid-mapping.js +277 -0
  22. package/lib/Socket/Client/index.js +3 -0
  23. package/lib/Socket/Client/types.js +11 -0
  24. package/lib/Socket/Client/websocket.js +102 -0
  25. package/lib/Socket/aigroups.js +221 -0
  26. package/lib/Socket/business.js +379 -0
  27. package/lib/Socket/chats.js +1193 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +524 -0
  30. package/lib/Socket/groups.js +408 -0
  31. package/lib/Socket/index.js +49 -0
  32. package/lib/Socket/interop.js +341 -0
  33. package/lib/Socket/luxu.js +510 -0
  34. package/lib/Socket/managed-account.js +99 -0
  35. package/lib/Socket/messages-recv.js +2009 -0
  36. package/lib/Socket/messages-send.js +1608 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +399 -0
  39. package/lib/Socket/privacy.js +128 -0
  40. package/lib/Socket/registration.js +238 -0
  41. package/lib/Socket/socket.js +1000 -0
  42. package/lib/Socket/text-router.js +67 -0
  43. package/lib/Socket/username.js +234 -0
  44. package/lib/Store/index.js +10 -0
  45. package/lib/Store/keyed-db.js +108 -0
  46. package/lib/Store/make-cache-manager-store.js +85 -0
  47. package/lib/Store/make-in-memory-store.js +198 -0
  48. package/lib/Store/make-ordered-dictionary.js +75 -0
  49. package/lib/Store/object-repository.js +32 -0
  50. package/lib/Types/Auth.js +2 -0
  51. package/lib/Types/Bussines.js +2 -0
  52. package/lib/Types/Call.js +2 -0
  53. package/lib/Types/Chat.js +8 -0
  54. package/lib/Types/Contact.js +2 -0
  55. package/lib/Types/Events.js +2 -0
  56. package/lib/Types/GroupMetadata.js +2 -0
  57. package/lib/Types/Label.js +25 -0
  58. package/lib/Types/LabelAssociation.js +7 -0
  59. package/lib/Types/Message.js +11 -0
  60. package/lib/Types/Mex.js +114 -0
  61. package/lib/Types/Product.js +2 -0
  62. package/lib/Types/Signal.js +2 -0
  63. package/lib/Types/Socket.js +3 -0
  64. package/lib/Types/State.js +56 -0
  65. package/lib/Types/USync.js +2 -0
  66. package/lib/Types/index.js +26 -0
  67. package/lib/Utils/adaptive-healing.js +53 -0
  68. package/lib/Utils/auth-utils.js +302 -0
  69. package/lib/Utils/browser-utils.js +50 -0
  70. package/lib/Utils/business.js +231 -0
  71. package/lib/Utils/chat-utils.js +872 -0
  72. package/lib/Utils/command-loader.js +108 -0
  73. package/lib/Utils/companion-reg-client-utils.js +35 -0
  74. package/lib/Utils/consumer-application.js +106 -0
  75. package/lib/Utils/crypto.js +137 -0
  76. package/lib/Utils/curve25519-js.js +262 -0
  77. package/lib/Utils/decode-wa-message.js +498 -0
  78. package/lib/Utils/event-buffer.js +622 -0
  79. package/lib/Utils/generics.js +403 -0
  80. package/lib/Utils/group-history.js +47 -0
  81. package/lib/Utils/history.js +134 -0
  82. package/lib/Utils/identity-change-handler.js +50 -0
  83. package/lib/Utils/index.js +38 -0
  84. package/lib/Utils/jid-display-normalization.js +198 -0
  85. package/lib/Utils/link-preview.js +85 -0
  86. package/lib/Utils/logger.js +3 -0
  87. package/lib/Utils/lt-hash.js +8 -0
  88. package/lib/Utils/make-mutex.js +33 -0
  89. package/lib/Utils/message-composer.js +273 -0
  90. package/lib/Utils/message-retry-manager.js +267 -0
  91. package/lib/Utils/messages-media.js +791 -0
  92. package/lib/Utils/messages.js +1260 -0
  93. package/lib/Utils/meta-ai-msmsg.js +271 -0
  94. package/lib/Utils/native-bridge.js +77 -0
  95. package/lib/Utils/noise-handler.js +201 -0
  96. package/lib/Utils/offline-node-processor.js +40 -0
  97. package/lib/Utils/optimizer.js +90 -0
  98. package/lib/Utils/pre-key-manager.js +106 -0
  99. package/lib/Utils/process-message.js +630 -0
  100. package/lib/Utils/reporting-utils.js +258 -0
  101. package/lib/Utils/session-pool.js +73 -0
  102. package/lib/Utils/signal.js +207 -0
  103. package/lib/Utils/stanza-ack.js +38 -0
  104. package/lib/Utils/sticker.js +139 -0
  105. package/lib/Utils/sync-action-utils.js +49 -0
  106. package/lib/Utils/tc-token-utils.js +163 -0
  107. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  108. package/lib/Utils/use-sqlite-auth-state.js +168 -0
  109. package/lib/Utils/validate-connection.js +203 -0
  110. package/lib/Utils/view-once-cache.js +79 -0
  111. package/lib/Utils/voip-rekey.js +25 -0
  112. package/lib/Utils/warmup.js +117 -0
  113. package/lib/WABinary/constants.js +1301 -0
  114. package/lib/WABinary/decode.js +262 -0
  115. package/lib/WABinary/encode.js +220 -0
  116. package/lib/WABinary/generic-utils.js +204 -0
  117. package/lib/WABinary/index.js +6 -0
  118. package/lib/WABinary/jid-utils.js +98 -0
  119. package/lib/WABinary/types.js +2 -0
  120. package/lib/WAM/BinaryInfo.js +10 -0
  121. package/lib/WAM/constants.js +22853 -0
  122. package/lib/WAM/encode.js +150 -0
  123. package/lib/WAM/index.js +4 -0
  124. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +41 -0
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  126. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  128. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +52 -0
  129. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +31 -0
  130. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +26 -0
  131. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  132. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +35 -0
  133. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  134. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  135. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  136. package/lib/WAUSync/Protocols/index.js +13 -0
  137. package/lib/WAUSync/USyncQuery.js +127 -0
  138. package/lib/WAUSync/USyncUser.js +31 -0
  139. package/lib/WAUSync/index.js +4 -0
  140. package/lib/antiban.js +4083 -0
  141. package/lib/index.js +24 -0
  142. package/package.json +147 -0
@@ -0,0 +1,791 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { execFile } 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 = 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. Uses execFile with an argv array (never a
86
+ * shell string) so a caller-supplied `time`/`size` can't be interpreted as an
87
+ * extra shell command, even though today's only call site passes fixed values.
88
+ */
89
+ const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
90
+ const args = ['-ss', String(time), '-i', path, '-y', '-vf', `scale=${size.width}:-1`, '-vframes', '1', '-f', 'image2', destPath];
91
+ execFile('ffmpeg', args, err => {
92
+ if (err) {
93
+ reject(err);
94
+ }
95
+ else {
96
+ resolve();
97
+ }
98
+ });
99
+ });
100
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
101
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
102
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
103
+ if (bufferOrFilePath instanceof Readable) {
104
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
105
+ }
106
+ const lib = await getImageProcessingLibrary();
107
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
108
+ const img = lib.sharp.default(bufferOrFilePath);
109
+ const dimensions = await img.metadata();
110
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
111
+ return {
112
+ buffer,
113
+ original: {
114
+ width: dimensions.width,
115
+ height: dimensions.height
116
+ }
117
+ };
118
+ }
119
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
120
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
121
+ const dimensions = {
122
+ width: jimp.width,
123
+ height: jimp.height
124
+ };
125
+ const buffer = await jimp
126
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
127
+ .getBuffer('image/jpeg', { quality: 50 });
128
+ return {
129
+ buffer,
130
+ original: dimensions
131
+ };
132
+ }
133
+ else {
134
+ throw new Boom('No image processing library available');
135
+ }
136
+ };
137
+ export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
138
+ export const generateProfilePicture = async (mediaUpload, dimensions) => {
139
+ let buffer;
140
+ const { width: w = 640, height: h = 640 } = dimensions || {};
141
+ if (Buffer.isBuffer(mediaUpload)) {
142
+ buffer = mediaUpload;
143
+ }
144
+ else {
145
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
146
+ const { stream } = await getStream(mediaUpload);
147
+ // Convert the resulting stream to a buffer
148
+ buffer = await toBuffer(stream);
149
+ }
150
+ const lib = await getImageProcessingLibrary();
151
+ let img;
152
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
153
+ img = lib.sharp
154
+ .default(buffer)
155
+ .resize(w, h)
156
+ .jpeg({
157
+ quality: 50
158
+ })
159
+ .toBuffer();
160
+ }
161
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
162
+ const jimp = await lib.jimp.Jimp.read(buffer);
163
+ const min = Math.min(jimp.width, jimp.height);
164
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
165
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 });
166
+ }
167
+ else {
168
+ throw new Boom('No image processing library available');
169
+ }
170
+ return {
171
+ img: await img
172
+ };
173
+ };
174
+ /** gets the SHA256 of the given media message */
175
+ export const mediaMessageSHA256B64 = (message) => {
176
+ const media = Object.values(message)[0];
177
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
178
+ };
179
+ export async function getAudioDuration(buffer) {
180
+ const musicMetadata = await import('music-metadata');
181
+ let metadata;
182
+ const options = {
183
+ duration: true
184
+ };
185
+ if (Buffer.isBuffer(buffer)) {
186
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
187
+ }
188
+ else if (typeof buffer === 'string') {
189
+ metadata = await musicMetadata.parseFile(buffer, options);
190
+ }
191
+ else {
192
+ metadata = await musicMetadata.parseStream(buffer, undefined, options);
193
+ }
194
+ return metadata.format.duration;
195
+ }
196
+ /**
197
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
198
+ */
199
+ export async function getAudioWaveform(buffer, logger) {
200
+ try {
201
+ // @ts-ignore
202
+ const { default: decoder } = await import('audio-decode');
203
+ let audioData;
204
+ if (Buffer.isBuffer(buffer)) {
205
+ audioData = buffer;
206
+ }
207
+ else if (typeof buffer === 'string') {
208
+ const rStream = createReadStream(buffer);
209
+ audioData = await toBuffer(rStream);
210
+ }
211
+ else {
212
+ audioData = await toBuffer(buffer);
213
+ }
214
+ const audioBuffer = await decoder(audioData);
215
+ const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
216
+ const samples = 64; // Number of samples we want to have in our final data set
217
+ const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
218
+ const filteredData = [];
219
+ for (let i = 0; i < samples; i++) {
220
+ const blockStart = blockSize * i; // the location of the first sample in the block
221
+ let sum = 0;
222
+ for (let j = 0; j < blockSize; j++) {
223
+ sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
224
+ }
225
+ filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
226
+ }
227
+ // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
228
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
229
+ const normalizedData = filteredData.map(n => n * multiplier);
230
+ // Generate waveform like WhatsApp
231
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
232
+ return waveform;
233
+ }
234
+ catch (e) {
235
+ logger?.debug('Failed to generate waveform: ' + e);
236
+ }
237
+ }
238
+ export const toReadable = (buffer) => {
239
+ const readable = new Readable({ read: () => { } });
240
+ readable.push(buffer);
241
+ readable.push(null);
242
+ return readable;
243
+ };
244
+ export const toBuffer = async (stream) => {
245
+ const chunks = [];
246
+ for await (const chunk of stream) {
247
+ chunks.push(chunk);
248
+ }
249
+ stream.destroy();
250
+ return Buffer.concat(chunks);
251
+ };
252
+ export const getStream = async (item, opts) => {
253
+ if (Buffer.isBuffer(item)) {
254
+ return { stream: toReadable(item), type: 'buffer' };
255
+ }
256
+ if ('stream' in item) {
257
+ return { stream: item.stream, type: 'readable' };
258
+ }
259
+ const urlStr = item.url.toString();
260
+ if (urlStr.startsWith('data:')) {
261
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
262
+ return { stream: toReadable(buffer), type: 'buffer' };
263
+ }
264
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
265
+ return { stream: await getHttpStream(item.url, opts), type: 'remote' };
266
+ }
267
+ return { stream: createReadStream(item.url), type: 'file' };
268
+ };
269
+ /** generates a thumbnail for a given media, if required */
270
+ export async function generateThumbnail(file, mediaType, options) {
271
+ let thumbnail;
272
+ let originalImageDimensions;
273
+ if (mediaType === 'image') {
274
+ const { buffer, original } = await extractImageThumb(file);
275
+ thumbnail = buffer.toString('base64');
276
+ if (original.width && original.height) {
277
+ originalImageDimensions = {
278
+ width: original.width,
279
+ height: original.height
280
+ };
281
+ }
282
+ }
283
+ else if (mediaType === 'video') {
284
+ const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg');
285
+ try {
286
+ await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
287
+ const buff = await fs.readFile(imgFilename);
288
+ thumbnail = buff.toString('base64');
289
+ await fs.unlink(imgFilename);
290
+ }
291
+ catch (err) {
292
+ options.logger?.debug('could not generate video thumb: ' + err);
293
+ }
294
+ }
295
+ return {
296
+ thumbnail,
297
+ originalImageDimensions
298
+ };
299
+ }
300
+ export const getHttpStream = async (url, options = {}) => {
301
+ const response = await fetch(url.toString(), {
302
+ dispatcher: options.dispatcher,
303
+ method: 'GET',
304
+ headers: options.headers
305
+ });
306
+ if (!response.ok) {
307
+ throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
308
+ }
309
+ // @ts-ignore Node18+ Readable.fromWeb exists
310
+ return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
311
+ };
312
+ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
313
+ const { stream, type } = await getStream(media, opts);
314
+ logger?.debug('fetched media stream');
315
+ const mediaKey = Crypto.randomBytes(32);
316
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
317
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
318
+ const encFileWriteStream = createWriteStream(encFilePath);
319
+ let originalFileStream;
320
+ let originalFilePath;
321
+ if (saveOriginalFileIfRequired) {
322
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
323
+ originalFileStream = createWriteStream(originalFilePath);
324
+ }
325
+ let fileLength = 0;
326
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
327
+ const hmac = Crypto.createHmac('sha256', macKey).update(iv);
328
+ const sha256Plain = Crypto.createHash('sha256');
329
+ const sha256Enc = Crypto.createHash('sha256');
330
+ const onChunk = async (buff) => {
331
+ sha256Enc.update(buff);
332
+ hmac.update(buff);
333
+ // Handle backpressure: if write returns false, wait for drain
334
+ if (!encFileWriteStream.write(buff)) {
335
+ await once(encFileWriteStream, 'drain');
336
+ }
337
+ };
338
+ try {
339
+ for await (const data of stream) {
340
+ fileLength += data.length;
341
+ if (type === 'remote' &&
342
+ opts?.maxContentLength &&
343
+ fileLength + data.length > opts.maxContentLength) {
344
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
345
+ data: { media, type }
346
+ });
347
+ }
348
+ if (originalFileStream) {
349
+ if (!originalFileStream.write(data)) {
350
+ await once(originalFileStream, 'drain');
351
+ }
352
+ }
353
+ sha256Plain.update(data);
354
+ await onChunk(aes.update(data));
355
+ }
356
+ await onChunk(aes.final());
357
+ const mac = hmac.digest().slice(0, 10);
358
+ sha256Enc.update(mac);
359
+ const fileSha256 = sha256Plain.digest();
360
+ const fileEncSha256 = sha256Enc.digest();
361
+ encFileWriteStream.write(mac);
362
+ const encFinishPromise = once(encFileWriteStream, 'finish');
363
+ const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();
364
+ encFileWriteStream.end();
365
+ originalFileStream?.end?.();
366
+ stream.destroy();
367
+ // Wait for write streams to fully flush to disk
368
+ // This helps reduce memory pressure by allowing OS to release buffers
369
+ await encFinishPromise;
370
+ await originalFinishPromise;
371
+ logger?.debug('encrypted data successfully');
372
+ return {
373
+ mediaKey,
374
+ originalFilePath,
375
+ encFilePath,
376
+ mac,
377
+ fileEncSha256,
378
+ fileSha256,
379
+ fileLength
380
+ };
381
+ }
382
+ catch (error) {
383
+ // destroy all streams with error
384
+ encFileWriteStream.destroy();
385
+ originalFileStream?.destroy?.();
386
+ aes.destroy();
387
+ hmac.destroy();
388
+ sha256Plain.destroy();
389
+ sha256Enc.destroy();
390
+ stream.destroy();
391
+ try {
392
+ await fs.unlink(encFilePath);
393
+ if (originalFilePath) {
394
+ await fs.unlink(originalFilePath);
395
+ }
396
+ }
397
+ catch (err) {
398
+ logger?.error({ err }, 'failed deleting tmp files');
399
+ }
400
+ throw error;
401
+ }
402
+ };
403
+ export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
404
+ const AES_CHUNK_SIZE = 16;
405
+ const toSmallestChunkSize = (num) => {
406
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
407
+ };
408
+ export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
409
+ const extractHost = (url) => {
410
+ if (!url)
411
+ return undefined;
412
+ try {
413
+ return new URL(url).host;
414
+ }
415
+ catch {
416
+ return undefined;
417
+ }
418
+ };
419
+ export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
420
+ // Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
421
+ // Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
422
+ const fallbackHost = opts.host ?? extractHost(url);
423
+ const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url;
424
+ if (!downloadUrl) {
425
+ throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
426
+ }
427
+ const keys = await getMediaKeys(mediaKey, type);
428
+ return downloadEncryptedContent(downloadUrl, keys, opts);
429
+ };
430
+ /**
431
+ * Decrypts and downloads an AES256-CBC encrypted file given the keys.
432
+ * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
433
+ * */
434
+ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
435
+ let bytesFetched = 0;
436
+ let startChunk = 0;
437
+ let firstBlockIsIV = false;
438
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
439
+ if (startByte) {
440
+ const chunk = toSmallestChunkSize(startByte || 0);
441
+ if (chunk) {
442
+ startChunk = chunk - AES_CHUNK_SIZE;
443
+ bytesFetched = chunk;
444
+ firstBlockIsIV = true;
445
+ }
446
+ }
447
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
448
+ const headersInit = options?.headers ? options.headers : undefined;
449
+ const headers = {
450
+ ...(headersInit
451
+ ? Array.isArray(headersInit)
452
+ ? Object.fromEntries(headersInit)
453
+ : headersInit
454
+ : {}),
455
+ Origin: DEFAULT_ORIGIN
456
+ };
457
+ if (startChunk || endChunk) {
458
+ headers.Range = `bytes=${startChunk}-`;
459
+ if (endChunk) {
460
+ headers.Range += endChunk;
461
+ }
462
+ }
463
+ // download the message
464
+ const fetched = await getHttpStream(downloadUrl, {
465
+ ...(options || {}),
466
+ headers
467
+ });
468
+ let remainingBytes = Buffer.from([]);
469
+ let aes;
470
+ const pushBytes = (bytes, push) => {
471
+ if (startByte || endByte) {
472
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
473
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
474
+ push(bytes.slice(start, end));
475
+ bytesFetched += bytes.length;
476
+ }
477
+ else {
478
+ push(bytes);
479
+ }
480
+ };
481
+ const output = new Transform({
482
+ transform(chunk, _, callback) {
483
+ let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk;
484
+ const decryptLength = toSmallestChunkSize(data.length);
485
+ remainingBytes = data.slice(decryptLength);
486
+ data = data.slice(0, decryptLength);
487
+ if (!aes) {
488
+ let ivValue = iv;
489
+ if (firstBlockIsIV) {
490
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
491
+ data = data.slice(AES_CHUNK_SIZE);
492
+ }
493
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
494
+ // if an end byte that is not EOF is specified
495
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
496
+ if (endByte) {
497
+ aes.setAutoPadding(false);
498
+ }
499
+ }
500
+ try {
501
+ pushBytes(aes.update(data), b => this.push(b));
502
+ callback();
503
+ }
504
+ catch (error) {
505
+ callback(error);
506
+ }
507
+ },
508
+ final(callback) {
509
+ try {
510
+ pushBytes(aes.final(), b => this.push(b));
511
+ callback();
512
+ }
513
+ catch (error) {
514
+ callback(error);
515
+ }
516
+ }
517
+ });
518
+ return fetched.pipe(output, { end: true });
519
+ };
520
+ export function extensionForMediaMessage(message) {
521
+ const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
522
+ const type = Object.keys(message)[0];
523
+ let extension;
524
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
525
+ extension = '.jpeg';
526
+ }
527
+ else {
528
+ const messageContent = message[type];
529
+ extension = getExtension(messageContent.mimetype);
530
+ }
531
+ return extension;
532
+ }
533
+ const isNodeRuntime = () => {
534
+ return (typeof process !== 'undefined' &&
535
+ process.versions?.node !== null &&
536
+ typeof process.versions.bun === 'undefined' &&
537
+ typeof globalThis.Deno === 'undefined');
538
+ };
539
+ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
540
+ if (redirectCount > 5) {
541
+ throw new Error('Too many redirects');
542
+ }
543
+ const parsedUrl = new URL(url);
544
+ const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http');
545
+ // Get file size for Content-Length header (required for Node.js streaming)
546
+ const fileStats = await fs.stat(filePath);
547
+ const fileSize = fileStats.size;
548
+ return new Promise((resolve, reject) => {
549
+ const req = httpModule.request({
550
+ hostname: parsedUrl.hostname,
551
+ port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
552
+ path: parsedUrl.pathname + parsedUrl.search,
553
+ method: 'POST',
554
+ headers: {
555
+ ...headers,
556
+ 'Content-Length': fileSize
557
+ },
558
+ agent,
559
+ timeout: timeoutMs
560
+ }, res => {
561
+ // Handle redirects (3xx)
562
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
563
+ res.resume(); // Consume response to free resources
564
+ const newUrl = new URL(res.headers.location, url).toString();
565
+ resolve(uploadWithNodeHttp({
566
+ url: newUrl,
567
+ filePath,
568
+ headers,
569
+ timeoutMs,
570
+ agent
571
+ }, redirectCount + 1));
572
+ return;
573
+ }
574
+ let body = '';
575
+ res.on('data', chunk => (body += chunk));
576
+ res.on('end', () => {
577
+ try {
578
+ resolve(JSON.parse(body));
579
+ }
580
+ catch {
581
+ resolve(undefined);
582
+ }
583
+ });
584
+ });
585
+ req.on('error', reject);
586
+ req.on('timeout', () => {
587
+ req.destroy();
588
+ reject(new Error('Upload timeout'));
589
+ });
590
+ const stream = createReadStream(filePath);
591
+ stream.pipe(req);
592
+ stream.on('error', err => {
593
+ req.destroy();
594
+ reject(err);
595
+ });
596
+ });
597
+ };
598
+ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
599
+ // Convert Node.js Readable to Web ReadableStream
600
+ const nodeStream = createReadStream(filePath);
601
+ const webStream = Readable.toWeb(nodeStream);
602
+ // Native fetch only accepts Undici-style dispatchers, not generic https Agents.
603
+ const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
604
+ const response = await fetch(url, {
605
+ ...(dispatcher ? { dispatcher } : {}),
606
+ method: 'POST',
607
+ body: webStream,
608
+ headers,
609
+ duplex: 'half',
610
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
611
+ });
612
+ try {
613
+ return (await response.json());
614
+ }
615
+ catch {
616
+ return undefined;
617
+ }
618
+ };
619
+ /**
620
+ * Uploads media to WhatsApp servers.
621
+ *
622
+ * ## Why we have two upload implementations:
623
+ *
624
+ * Node.js's native `fetch` (powered by undici) has a known bug where it buffers
625
+ * the entire request body in memory before sending, even when using streams.
626
+ * This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
627
+ * See: https://github.com/nodejs/undici/issues/4058
628
+ *
629
+ * Other runtimes (Bun, Deno, browsers) correctly stream the request body without
630
+ * buffering, so we can use the web-standard Fetch API there.
631
+ *
632
+ * ## Future considerations:
633
+ * Once the undici bug is fixed, we can simplify this to use only the Fetch API
634
+ * across all runtimes. Monitor the GitHub issue for updates.
635
+ */
636
+ const uploadMedia = async (params, logger) => {
637
+ if (isNodeRuntime()) {
638
+ logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
639
+ return uploadWithNodeHttp(params);
640
+ }
641
+ else {
642
+ logger?.debug('Using web-standard Fetch API for upload');
643
+ return uploadWithFetch(params);
644
+ }
645
+ };
646
+ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
647
+ return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
648
+ // send a query JSON to obtain the url & auth token to upload our media
649
+ let uploadInfo = await refreshMediaConn(false);
650
+ let urls;
651
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
652
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
653
+ // Prepare common headers
654
+ const customHeaders = (() => {
655
+ const hdrs = options?.headers;
656
+ if (!hdrs)
657
+ return {};
658
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
659
+ })();
660
+ const headers = {
661
+ ...customHeaders,
662
+ 'Content-Type': 'application/octet-stream',
663
+ Origin: DEFAULT_ORIGIN
664
+ };
665
+ for (const { hostname } of hosts) {
666
+ logger.debug(`uploading to "${hostname}"`);
667
+ const auth = encodeURIComponent(uploadInfo.auth);
668
+ const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
669
+ let result;
670
+ try {
671
+ result = await uploadMedia({
672
+ url,
673
+ filePath,
674
+ headers,
675
+ timeoutMs,
676
+ agent: fetchAgent
677
+ }, logger);
678
+ if (result?.url || result?.direct_path) {
679
+ urls = {
680
+ mediaUrl: result.url,
681
+ directPath: result.direct_path,
682
+ meta_hmac: result.meta_hmac,
683
+ fbid: result.fbid,
684
+ ts: result.ts
685
+ };
686
+ break;
687
+ }
688
+ else {
689
+ uploadInfo = await refreshMediaConn(true);
690
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
691
+ }
692
+ }
693
+ catch (error) {
694
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
695
+ logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
696
+ }
697
+ }
698
+ if (!urls) {
699
+ throw new Boom('Media upload failed on all hosts', { statusCode: 500 });
700
+ }
701
+ return urls;
702
+ };
703
+ };
704
+ const getMediaRetryKey = (mediaKey) => {
705
+ return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
706
+ };
707
+ /**
708
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
709
+ */
710
+ export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
711
+ const recp = { stanzaId: key.id };
712
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
713
+ const iv = Crypto.randomBytes(12);
714
+ const retryKey = getMediaRetryKey(mediaKey);
715
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
716
+ const req = {
717
+ tag: 'receipt',
718
+ attrs: {
719
+ id: key.id,
720
+ to: jidNormalizedUser(meId),
721
+ type: 'server-error'
722
+ },
723
+ content: [
724
+ // this encrypt node is actually pretty useless
725
+ // the media is returned even without this node
726
+ // keeping it here to maintain parity with WA Web
727
+ {
728
+ tag: 'encrypt',
729
+ attrs: {},
730
+ content: [
731
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
732
+ { tag: 'enc_iv', attrs: {}, content: iv }
733
+ ]
734
+ },
735
+ {
736
+ tag: 'rmr',
737
+ attrs: {
738
+ jid: key.remoteJid,
739
+ from_me: (!!key.fromMe).toString(),
740
+ // @ts-ignore
741
+ participant: key.participant || undefined
742
+ }
743
+ }
744
+ ]
745
+ };
746
+ return req;
747
+ };
748
+ export const decodeMediaRetryNode = (node) => {
749
+ const rmrNode = getBinaryNodeChild(node, 'rmr');
750
+ const event = {
751
+ key: {
752
+ id: node.attrs.id,
753
+ remoteJid: rmrNode.attrs.jid,
754
+ fromMe: rmrNode.attrs.from_me === 'true',
755
+ participant: rmrNode.attrs.participant
756
+ }
757
+ };
758
+ const errorNode = getBinaryNodeChild(node, 'error');
759
+ if (errorNode) {
760
+ const errorCode = +errorNode.attrs.code;
761
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
762
+ data: errorNode.attrs,
763
+ statusCode: getStatusCodeForMediaRetry(errorCode)
764
+ });
765
+ }
766
+ else {
767
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
768
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
769
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
770
+ if (ciphertext && iv) {
771
+ event.media = { ciphertext, iv };
772
+ }
773
+ else {
774
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
775
+ }
776
+ }
777
+ return event;
778
+ };
779
+ export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
780
+ const retryKey = getMediaRetryKey(mediaKey);
781
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
782
+ return proto.MediaRetryNotification.decode(plaintext);
783
+ };
784
+ export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
785
+ const MEDIA_RETRY_STATUS_MAP = {
786
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
787
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
788
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
789
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
790
+ };
791
+ //# sourceMappingURL=messages-media.js.map