@skycodee/baileys 8.0.0 → 8.0.2

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 (114) hide show
  1. package/package.json +4 -4
  2. package/src/Defaults/baileys-version.json +1 -0
  3. package/src/Defaults/index.ts +149 -0
  4. package/src/Signal/Group/ciphertext-message.ts +9 -0
  5. package/src/Signal/Group/group-session-builder.ts +56 -0
  6. package/src/Signal/Group/group_cipher.ts +117 -0
  7. package/src/Signal/Group/index.ts +11 -0
  8. package/src/Signal/Group/keyhelper.ts +28 -0
  9. package/src/Signal/Group/sender-chain-key.ts +34 -0
  10. package/src/Signal/Group/sender-key-distribution-message.ts +95 -0
  11. package/src/Signal/Group/sender-key-message.ts +96 -0
  12. package/src/Signal/Group/sender-key-name.ts +66 -0
  13. package/src/Signal/Group/sender-key-record.ts +69 -0
  14. package/src/Signal/Group/sender-key-state.ts +134 -0
  15. package/src/Signal/Group/sender-message-key.ts +36 -0
  16. package/src/Signal/libsignal.ts +521 -0
  17. package/src/Signal/lid-mapping.ts +328 -0
  18. package/src/Socket/Client/index.ts +2 -0
  19. package/src/Socket/Client/types.ts +22 -0
  20. package/src/Socket/Client/websocket.ts +63 -0
  21. package/src/Socket/business.ts +424 -0
  22. package/src/Socket/chats.ts +1272 -0
  23. package/src/Socket/communities.ts +477 -0
  24. package/src/Socket/groups.ts +361 -0
  25. package/src/Socket/index.ts +15 -0
  26. package/src/Socket/messages-recv.ts +1668 -0
  27. package/src/Socket/messages-send.ts +1296 -0
  28. package/src/Socket/mex.ts +58 -0
  29. package/src/Socket/newsletter.ts +229 -0
  30. package/src/Socket/socket.ts +1184 -0
  31. package/src/Types/Auth.ts +116 -0
  32. package/src/Types/Bussines.ts +20 -0
  33. package/src/Types/Call.ts +15 -0
  34. package/src/Types/Chat.ts +138 -0
  35. package/src/Types/Contact.ts +24 -0
  36. package/src/Types/Events.ts +159 -0
  37. package/src/Types/GroupMetadata.ts +70 -0
  38. package/src/Types/Label.ts +48 -0
  39. package/src/Types/LabelAssociation.ts +35 -0
  40. package/src/Types/Message.ts +380 -0
  41. package/src/Types/Newsletter.ts +98 -0
  42. package/src/Types/Product.ts +85 -0
  43. package/src/Types/Signal.ts +76 -0
  44. package/src/Types/Socket.ts +150 -0
  45. package/src/Types/State.ts +43 -0
  46. package/src/Types/USync.ts +27 -0
  47. package/src/Types/globals.d.ts +8 -0
  48. package/src/Types/index.ts +67 -0
  49. package/src/Utils/auth-utils.ts +368 -0
  50. package/src/Utils/browser-utils.ts +31 -0
  51. package/src/Utils/business.ts +286 -0
  52. package/src/Utils/chat-utils.ts +974 -0
  53. package/src/Utils/crypto.ts +147 -0
  54. package/src/Utils/decode-wa-message.ts +355 -0
  55. package/src/Utils/event-buffer.ts +692 -0
  56. package/src/Utils/generics.ts +474 -0
  57. package/src/Utils/history.ts +161 -0
  58. package/src/Utils/identity-change-handler.ts +83 -0
  59. package/src/Utils/index.ts +19 -0
  60. package/src/Utils/link-preview.ts +111 -0
  61. package/src/Utils/logger.ts +13 -0
  62. package/src/Utils/lt-hash.ts +8 -0
  63. package/src/Utils/make-mutex.ts +42 -0
  64. package/src/Utils/message-retry-manager.ts +295 -0
  65. package/src/Utils/messages-media.ts +984 -0
  66. package/src/Utils/messages.ts +1097 -0
  67. package/src/Utils/noise-handler.ts +268 -0
  68. package/src/Utils/pre-key-manager.ts +126 -0
  69. package/src/Utils/process-message.ts +670 -0
  70. package/src/Utils/reporting-utils.ts +344 -0
  71. package/src/Utils/signal.ts +214 -0
  72. package/src/Utils/sync-action-utils.ts +74 -0
  73. package/src/Utils/tc-token-utils.ts +34 -0
  74. package/src/Utils/use-multi-file-auth-state.ts +136 -0
  75. package/src/Utils/validate-connection.ts +253 -0
  76. package/src/WABinary/constants.ts +1305 -0
  77. package/src/WABinary/decode.ts +308 -0
  78. package/src/WABinary/encode.ts +258 -0
  79. package/src/WABinary/generic-utils.ts +141 -0
  80. package/src/WABinary/index.ts +5 -0
  81. package/src/WABinary/jid-utils.ts +128 -0
  82. package/src/WABinary/types.ts +17 -0
  83. package/src/WAM/BinaryInfo.ts +12 -0
  84. package/src/WAM/constants.ts +22889 -0
  85. package/src/WAM/encode.ts +169 -0
  86. package/src/WAM/index.ts +3 -0
  87. package/src/WAUSync/Protocols/USyncContactProtocol.ts +32 -0
  88. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +78 -0
  89. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +35 -0
  90. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +44 -0
  91. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +76 -0
  92. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +33 -0
  93. package/src/WAUSync/Protocols/index.ts +4 -0
  94. package/src/WAUSync/USyncQuery.ts +133 -0
  95. package/src/WAUSync/USyncUser.ts +32 -0
  96. package/src/WAUSync/index.ts +3 -0
  97. package/src/__tests__/Signal/Group/sender-key-state-regression.test.ts +22 -0
  98. package/src/__tests__/Signal/lid-mapping.test.ts +47 -0
  99. package/src/__tests__/Socket/identity-change-handling.test.ts +207 -0
  100. package/src/__tests__/TestUtils/session.ts +47 -0
  101. package/src/__tests__/Utils/generics.test.ts +70 -0
  102. package/src/__tests__/Utils/history.test.ts +362 -0
  103. package/src/__tests__/Utils/messages-media.test.ts +405 -0
  104. package/src/__tests__/Utils/noise-handler.test.ts +339 -0
  105. package/src/__tests__/Utils/process-message.test.ts +138 -0
  106. package/src/__tests__/Utils/process-sync-action.test.ts +359 -0
  107. package/src/__tests__/Utils/reporting-utils.test.ts +160 -0
  108. package/src/__tests__/Utils/signal.test.ts +69 -0
  109. package/src/__tests__/Utils/sync-action-utils.test.ts +183 -0
  110. package/src/__tests__/binary/connection-deadlock.test.ts +54 -0
  111. package/src/__tests__/e2e/fetch-wa-web-version.test-e2e.ts +60 -0
  112. package/src/__tests__/e2e/send-receive-message.test-e2e.ts +644 -0
  113. package/src/__tests__/proto-tojson-long.test.ts +31 -0
  114. package/src/index.ts +13 -0
@@ -0,0 +1,984 @@
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 type { Agent } from 'https'
7
+ import type { IAudioMetadata } from 'music-metadata'
8
+ import { tmpdir } from 'os'
9
+ import { join } from 'path'
10
+ import { Readable, Transform } from 'stream'
11
+ import { URL } from 'url'
12
+ import { proto } from '../../WAProto/index.js'
13
+ import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP, type MediaType } from '../Defaults'
14
+ import type {
15
+ BaileysEventMap,
16
+ DownloadableMessage,
17
+ MediaConnInfo,
18
+ MediaDecryptionKeyInfo,
19
+ MessageType,
20
+ SocketConfig,
21
+ WAGenericMediaMessage,
22
+ WAMediaUpload,
23
+ WAMediaUploadFunction,
24
+ WAMessageContent,
25
+ WAMessageKey
26
+ } from '../Types'
27
+ import { type BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary'
28
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto'
29
+ import { generateMessageIDV2 } from './generics'
30
+ import type { ILogger } from './logger'
31
+
32
+ const getTmpFilesDirectory = () => tmpdir()
33
+
34
+ const getImageProcessingLibrary = async () => {
35
+ //@ts-ignore
36
+ const [jimp, sharp] = await Promise.all([import('jimp').catch(() => {}), import('sharp').catch(() => {})])
37
+
38
+ if (sharp) {
39
+ return { sharp }
40
+ }
41
+
42
+ if (jimp) {
43
+ return { jimp }
44
+ }
45
+
46
+ throw new Boom('No image processing library available')
47
+ }
48
+
49
+ export const hkdfInfoKey = (type: MediaType) => {
50
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type]
51
+ return `WhatsApp ${hkdfInfo} Keys`
52
+ }
53
+
54
+ export const getRawMediaUploadData = async (media: WAMediaUpload, mediaType: MediaType, logger?: ILogger) => {
55
+ const { stream } = await getStream(media)
56
+ logger?.debug('got stream for raw upload')
57
+
58
+ const hasher = Crypto.createHash('sha256')
59
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2())
60
+ const fileWriteStream = createWriteStream(filePath)
61
+
62
+ let fileLength = 0
63
+ try {
64
+ for await (const data of stream) {
65
+ fileLength += data.length
66
+ hasher.update(data)
67
+ if (!fileWriteStream.write(data)) {
68
+ await once(fileWriteStream, 'drain')
69
+ }
70
+ }
71
+
72
+ fileWriteStream.end()
73
+ await once(fileWriteStream, 'finish')
74
+ stream.destroy()
75
+ const fileSha256 = hasher.digest()
76
+ logger?.debug('hashed data for raw upload')
77
+ return {
78
+ filePath: filePath,
79
+ fileSha256,
80
+ fileLength
81
+ }
82
+ } catch (error) {
83
+ fileWriteStream.destroy()
84
+ stream.destroy()
85
+ try {
86
+ await fs.unlink(filePath)
87
+ } catch {
88
+ //
89
+ }
90
+
91
+ throw error
92
+ }
93
+ }
94
+
95
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
96
+ export async function getMediaKeys(
97
+ buffer: Uint8Array | string | null | undefined,
98
+ mediaType: MediaType
99
+ ): Promise<MediaDecryptionKeyInfo> {
100
+ if (!buffer) {
101
+ throw new Boom('Cannot derive from empty media key')
102
+ }
103
+
104
+ if (typeof buffer === 'string') {
105
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64')
106
+ }
107
+
108
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
109
+ const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
110
+ return {
111
+ iv: expandedMediaKey.slice(0, 16),
112
+ cipherKey: expandedMediaKey.slice(16, 48),
113
+ macKey: expandedMediaKey.slice(48, 80)
114
+ }
115
+ }
116
+
117
+ /** Extracts video thumb using FFMPEG */
118
+ const extractVideoThumb = async (
119
+ path: string,
120
+ destPath: string,
121
+ time: string,
122
+ size: { width: number; height: number }
123
+ ) =>
124
+ new Promise<void>((resolve, reject) => {
125
+ const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`
126
+ exec(cmd, err => {
127
+ if (err) {
128
+ reject(err)
129
+ } else {
130
+ resolve()
131
+ }
132
+ })
133
+ })
134
+
135
+ export const extractImageThumb = async (bufferOrFilePath: Readable | Buffer | string, width = 32) => {
136
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
137
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
138
+ if (bufferOrFilePath instanceof Readable) {
139
+ bufferOrFilePath = await toBuffer(bufferOrFilePath)
140
+ }
141
+
142
+ const lib = await getImageProcessingLibrary()
143
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
144
+ const img = lib.sharp.default(bufferOrFilePath)
145
+ const dimensions = await img.metadata()
146
+
147
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer()
148
+ return {
149
+ buffer,
150
+ original: {
151
+ width: dimensions.width,
152
+ height: dimensions.height
153
+ }
154
+ }
155
+ } else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
156
+ const jimp = await (lib.jimp.Jimp as any).read(bufferOrFilePath)
157
+ const dimensions = {
158
+ width: jimp.width,
159
+ height: jimp.height
160
+ }
161
+ const buffer = await jimp
162
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
163
+ .getBuffer('image/jpeg', { quality: 50 })
164
+ return {
165
+ buffer,
166
+ original: dimensions
167
+ }
168
+ } else {
169
+ throw new Boom('No image processing library available')
170
+ }
171
+ }
172
+
173
+ export const encodeBase64EncodedStringForUpload = (b64: string) =>
174
+ encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''))
175
+
176
+ export const generateProfilePicture = async (
177
+ mediaUpload: WAMediaUpload,
178
+ dimensions?: { width: number; height: number }
179
+ ) => {
180
+ let buffer: Buffer
181
+
182
+ const { width: w = 640, height: h = 640 } = dimensions || {}
183
+
184
+ if (Buffer.isBuffer(mediaUpload)) {
185
+ buffer = mediaUpload
186
+ } else {
187
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
188
+ const { stream } = await getStream(mediaUpload)
189
+ // Convert the resulting stream to a buffer
190
+ buffer = await toBuffer(stream)
191
+ }
192
+
193
+ const lib = await getImageProcessingLibrary()
194
+ let img: Promise<Buffer>
195
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
196
+ img = lib.sharp
197
+ .default(buffer)
198
+ .resize(w, h)
199
+ .jpeg({
200
+ quality: 50
201
+ })
202
+ .toBuffer()
203
+ } else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
204
+ const jimp = await (lib.jimp.Jimp as any).read(buffer)
205
+ const min = Math.min(jimp.width, jimp.height)
206
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min })
207
+
208
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 })
209
+ } else {
210
+ throw new Boom('No image processing library available')
211
+ }
212
+
213
+ return {
214
+ img: await img
215
+ }
216
+ }
217
+
218
+ /** gets the SHA256 of the given media message */
219
+ export const mediaMessageSHA256B64 = (message: WAMessageContent) => {
220
+ const media = Object.values(message)[0] as WAGenericMediaMessage
221
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64')
222
+ }
223
+
224
+ export async function getAudioDuration(buffer: Buffer | string | Readable) {
225
+ const musicMetadata = await import('music-metadata')
226
+ let metadata: IAudioMetadata
227
+ const options = {
228
+ duration: true
229
+ }
230
+ if (Buffer.isBuffer(buffer)) {
231
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options)
232
+ } else if (typeof buffer === 'string') {
233
+ metadata = await musicMetadata.parseFile(buffer, options)
234
+ } else {
235
+ metadata = await musicMetadata.parseStream(buffer, undefined, options)
236
+ }
237
+
238
+ return metadata.format.duration
239
+ }
240
+
241
+ /**
242
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
243
+ */
244
+ export async function getAudioWaveform(buffer: Buffer | string | Readable, logger?: ILogger) {
245
+ try {
246
+ // @ts-ignore
247
+ const { default: decoder } = await import('audio-decode')
248
+ let audioData: Buffer
249
+ if (Buffer.isBuffer(buffer)) {
250
+ audioData = buffer
251
+ } else if (typeof buffer === 'string') {
252
+ const rStream = createReadStream(buffer)
253
+ audioData = await toBuffer(rStream)
254
+ } else {
255
+ audioData = await toBuffer(buffer)
256
+ }
257
+
258
+ const audioBuffer = await decoder(audioData)
259
+
260
+ const rawData = audioBuffer.getChannelData(0) // We only need to work with one channel of data
261
+ const samples = 64 // Number of samples we want to have in our final data set
262
+ const blockSize = Math.floor(rawData.length / samples) // the number of samples in each subdivision
263
+ const filteredData: number[] = []
264
+ for (let i = 0; i < samples; i++) {
265
+ const blockStart = blockSize * i // the location of the first sample in the block
266
+ let sum = 0
267
+ for (let j = 0; j < blockSize; j++) {
268
+ sum = sum + Math.abs(rawData[blockStart + j]) // find the sum of all the samples in the block
269
+ }
270
+
271
+ filteredData.push(sum / blockSize) // divide the sum by the block size to get the average
272
+ }
273
+
274
+ // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
275
+ const multiplier = Math.pow(Math.max(...filteredData), -1)
276
+ const normalizedData = filteredData.map(n => n * multiplier)
277
+
278
+ // Generate waveform like WhatsApp
279
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)))
280
+
281
+ return waveform
282
+ } catch (e) {
283
+ logger?.debug('Failed to generate waveform: ' + e)
284
+ }
285
+ }
286
+
287
+ export const toReadable = (buffer: Buffer) => {
288
+ const readable = new Readable({ read: () => {} })
289
+ readable.push(buffer)
290
+ readable.push(null)
291
+ return readable
292
+ }
293
+
294
+ export const toBuffer = async (stream: Readable) => {
295
+ const chunks: Buffer[] = []
296
+ for await (const chunk of stream) {
297
+ chunks.push(chunk)
298
+ }
299
+
300
+ stream.destroy()
301
+ return Buffer.concat(chunks)
302
+ }
303
+
304
+ export const getStream = async (item: WAMediaUpload, opts?: RequestInit & { maxContentLength?: number }) => {
305
+ if (Buffer.isBuffer(item)) {
306
+ return { stream: toReadable(item), type: 'buffer' } as const
307
+ }
308
+
309
+ if ('stream' in item) {
310
+ return { stream: item.stream, type: 'readable' } as const
311
+ }
312
+
313
+ const urlStr = item.url.toString()
314
+
315
+ if (urlStr.startsWith('data:')) {
316
+ const buffer = Buffer.from(urlStr.split(',')[1]!, 'base64')
317
+ return { stream: toReadable(buffer), type: 'buffer' } as const
318
+ }
319
+
320
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
321
+ return { stream: await getHttpStream(item.url, opts), type: 'remote' } as const
322
+ }
323
+
324
+ return { stream: createReadStream(item.url), type: 'file' } as const
325
+ }
326
+
327
+ /** generates a thumbnail for a given media, if required */
328
+ export async function generateThumbnail(
329
+ file: string,
330
+ mediaType: 'video' | 'image',
331
+ options: {
332
+ logger?: ILogger
333
+ }
334
+ ) {
335
+ let thumbnail: string | undefined
336
+ let originalImageDimensions: { width: number; height: number } | undefined
337
+ if (mediaType === 'image') {
338
+ const { buffer, original } = await extractImageThumb(file)
339
+ thumbnail = buffer.toString('base64')
340
+ if (original.width && original.height) {
341
+ originalImageDimensions = {
342
+ width: original.width,
343
+ height: original.height
344
+ }
345
+ }
346
+ } else if (mediaType === 'video') {
347
+ const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + '.jpg')
348
+ try {
349
+ await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 })
350
+ const buff = await fs.readFile(imgFilename)
351
+ thumbnail = buff.toString('base64')
352
+
353
+ await fs.unlink(imgFilename)
354
+ } catch (err) {
355
+ options.logger?.debug('could not generate video thumb: ' + err)
356
+ }
357
+ }
358
+
359
+ return {
360
+ thumbnail,
361
+ originalImageDimensions
362
+ }
363
+ }
364
+
365
+ export const getHttpStream = async (url: string | URL, options: RequestInit & { isStream?: true } = {}) => {
366
+ const response = await fetch(url.toString(), {
367
+ dispatcher: options.dispatcher,
368
+ method: 'GET',
369
+ headers: options.headers as HeadersInit
370
+ })
371
+ if (!response.ok) {
372
+ throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } })
373
+ }
374
+
375
+ // @ts-ignore Node18+ Readable.fromWeb exists
376
+ return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body as any)
377
+ }
378
+
379
+ type EncryptedStreamOptions = {
380
+ saveOriginalFileIfRequired?: boolean
381
+ logger?: ILogger
382
+ opts?: RequestInit
383
+ }
384
+
385
+ export const encryptedStream = async (
386
+ media: WAMediaUpload,
387
+ mediaType: MediaType,
388
+ { logger, saveOriginalFileIfRequired, opts }: EncryptedStreamOptions = {}
389
+ ) => {
390
+ const { stream, type } = await getStream(media, opts)
391
+
392
+ logger?.debug('fetched media stream')
393
+
394
+ const mediaKey = Crypto.randomBytes(32)
395
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
396
+
397
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc')
398
+ const encFileWriteStream = createWriteStream(encFilePath)
399
+
400
+ let originalFileStream: WriteStream | undefined
401
+ let originalFilePath: string | undefined
402
+
403
+ if (saveOriginalFileIfRequired) {
404
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original')
405
+ originalFileStream = createWriteStream(originalFilePath)
406
+ }
407
+
408
+ let fileLength = 0
409
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv)
410
+ const hmac = Crypto.createHmac('sha256', macKey!).update(iv)
411
+ const sha256Plain = Crypto.createHash('sha256')
412
+ const sha256Enc = Crypto.createHash('sha256')
413
+
414
+ const onChunk = async (buff: Buffer) => {
415
+ sha256Enc.update(buff)
416
+ hmac.update(buff)
417
+ // Handle backpressure: if write returns false, wait for drain
418
+ if (!encFileWriteStream.write(buff)) {
419
+ await once(encFileWriteStream, 'drain')
420
+ }
421
+ }
422
+
423
+ try {
424
+ for await (const data of stream) {
425
+ fileLength += data.length
426
+
427
+ if (
428
+ type === 'remote' &&
429
+ (opts as any)?.maxContentLength &&
430
+ fileLength + data.length > (opts as any).maxContentLength
431
+ ) {
432
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
433
+ data: { media, type }
434
+ })
435
+ }
436
+
437
+ if (originalFileStream) {
438
+ if (!originalFileStream.write(data)) {
439
+ await once(originalFileStream, 'drain')
440
+ }
441
+ }
442
+
443
+ sha256Plain.update(data)
444
+ await onChunk(aes.update(data))
445
+ }
446
+
447
+ await onChunk(aes.final())
448
+
449
+ const mac = hmac.digest().slice(0, 10)
450
+ sha256Enc.update(mac)
451
+
452
+ const fileSha256 = sha256Plain.digest()
453
+ const fileEncSha256 = sha256Enc.digest()
454
+
455
+ encFileWriteStream.write(mac)
456
+
457
+ const encFinishPromise = once(encFileWriteStream, 'finish')
458
+ const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve()
459
+
460
+ encFileWriteStream.end()
461
+ originalFileStream?.end?.()
462
+ stream.destroy()
463
+
464
+ // Wait for write streams to fully flush to disk
465
+ // This helps reduce memory pressure by allowing OS to release buffers
466
+ await encFinishPromise
467
+ await originalFinishPromise
468
+
469
+ logger?.debug('encrypted data successfully')
470
+
471
+ return {
472
+ mediaKey,
473
+ originalFilePath,
474
+ encFilePath,
475
+ mac,
476
+ fileEncSha256,
477
+ fileSha256,
478
+ fileLength
479
+ }
480
+ } catch (error) {
481
+ // destroy all streams with error
482
+ encFileWriteStream.destroy()
483
+ originalFileStream?.destroy?.()
484
+ aes.destroy()
485
+ hmac.destroy()
486
+ sha256Plain.destroy()
487
+ sha256Enc.destroy()
488
+ stream.destroy()
489
+
490
+ try {
491
+ await fs.unlink(encFilePath)
492
+ if (originalFilePath) {
493
+ await fs.unlink(originalFilePath)
494
+ }
495
+ } catch (err) {
496
+ logger?.error({ err }, 'failed deleting tmp files')
497
+ }
498
+
499
+ throw error
500
+ }
501
+ }
502
+
503
+ const DEF_HOST = 'mmg.whatsapp.net'
504
+ const AES_CHUNK_SIZE = 16
505
+
506
+ const toSmallestChunkSize = (num: number) => {
507
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
508
+ }
509
+
510
+ export type MediaDownloadOptions = {
511
+ startByte?: number
512
+ endByte?: number
513
+ options?: RequestInit
514
+ }
515
+
516
+ export const getUrlFromDirectPath = (directPath: string) => `https://${DEF_HOST}${directPath}`
517
+
518
+ export const downloadContentFromMessage = async (
519
+ { mediaKey, directPath, url }: DownloadableMessage,
520
+ type: MediaType,
521
+ opts: MediaDownloadOptions = {}
522
+ ) => {
523
+ const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/')
524
+ const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath!)
525
+ if (!downloadUrl) {
526
+ throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 })
527
+ }
528
+
529
+ const keys = await getMediaKeys(mediaKey, type)
530
+
531
+ return downloadEncryptedContent(downloadUrl, keys, opts)
532
+ }
533
+
534
+ /**
535
+ * Decrypts and downloads an AES256-CBC encrypted file given the keys.
536
+ * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
537
+ * */
538
+ export const downloadEncryptedContent = async (
539
+ downloadUrl: string,
540
+ { cipherKey, iv }: MediaDecryptionKeyInfo,
541
+ { startByte, endByte, options }: MediaDownloadOptions = {}
542
+ ) => {
543
+ let bytesFetched = 0
544
+ let startChunk = 0
545
+ let firstBlockIsIV = false
546
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
547
+ if (startByte) {
548
+ const chunk = toSmallestChunkSize(startByte || 0)
549
+ if (chunk) {
550
+ startChunk = chunk - AES_CHUNK_SIZE
551
+ bytesFetched = chunk
552
+
553
+ firstBlockIsIV = true
554
+ }
555
+ }
556
+
557
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
558
+
559
+ const headersInit = options?.headers ? options.headers : undefined
560
+ const headers: Record<string, string> = {
561
+ ...(headersInit
562
+ ? Array.isArray(headersInit)
563
+ ? Object.fromEntries(headersInit)
564
+ : (headersInit as Record<string, string>)
565
+ : {}),
566
+ Origin: DEFAULT_ORIGIN
567
+ }
568
+ if (startChunk || endChunk) {
569
+ headers.Range = `bytes=${startChunk}-`
570
+ if (endChunk) {
571
+ headers.Range += endChunk
572
+ }
573
+ }
574
+
575
+ // download the message
576
+ const fetched = await getHttpStream(downloadUrl, {
577
+ ...(options || {}),
578
+ headers
579
+ })
580
+
581
+ let remainingBytes = Buffer.from([])
582
+
583
+ let aes: Crypto.Decipher
584
+
585
+ const pushBytes = (bytes: Buffer, push: (bytes: Buffer) => void) => {
586
+ if (startByte || endByte) {
587
+ const start = bytesFetched >= startByte! ? undefined : Math.max(startByte! - bytesFetched, 0)
588
+ const end = bytesFetched + bytes.length < endByte! ? undefined : Math.max(endByte! - bytesFetched, 0)
589
+
590
+ push(bytes.slice(start, end))
591
+
592
+ bytesFetched += bytes.length
593
+ } else {
594
+ push(bytes)
595
+ }
596
+ }
597
+
598
+ const output = new Transform({
599
+ transform(chunk, _, callback) {
600
+ let data = Buffer.concat([remainingBytes, chunk])
601
+
602
+ const decryptLength = toSmallestChunkSize(data.length)
603
+ remainingBytes = data.slice(decryptLength)
604
+ data = data.slice(0, decryptLength)
605
+
606
+ if (!aes) {
607
+ let ivValue = iv
608
+ if (firstBlockIsIV) {
609
+ ivValue = data.slice(0, AES_CHUNK_SIZE)
610
+ data = data.slice(AES_CHUNK_SIZE)
611
+ }
612
+
613
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
614
+ // if an end byte that is not EOF is specified
615
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
616
+ if (endByte) {
617
+ aes.setAutoPadding(false)
618
+ }
619
+ }
620
+
621
+ try {
622
+ pushBytes(aes.update(data), b => this.push(b))
623
+ callback()
624
+ } catch (error: any) {
625
+ callback(error)
626
+ }
627
+ },
628
+ final(callback) {
629
+ try {
630
+ pushBytes(aes.final(), b => this.push(b))
631
+ callback()
632
+ } catch (error: any) {
633
+ callback(error)
634
+ }
635
+ }
636
+ })
637
+ return fetched.pipe(output, { end: true })
638
+ }
639
+
640
+ export function extensionForMediaMessage(message: WAMessageContent) {
641
+ const getExtension = (mimetype: string) => mimetype.split(';')[0]?.split('/')[1]
642
+ const type = Object.keys(message)[0] as Exclude<MessageType, 'toJSON'>
643
+ let extension: string
644
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
645
+ extension = '.jpeg'
646
+ } else {
647
+ const messageContent = message[type] as WAGenericMediaMessage
648
+ extension = getExtension(messageContent.mimetype!)!
649
+ }
650
+
651
+ return extension
652
+ }
653
+
654
+ const isNodeRuntime = (): boolean => {
655
+ return (
656
+ typeof process !== 'undefined' &&
657
+ process.versions?.node !== null &&
658
+ typeof process.versions.bun === 'undefined' &&
659
+ typeof (globalThis as any).Deno === 'undefined'
660
+ )
661
+ }
662
+
663
+ type MediaUploadResult = {
664
+ url?: string
665
+ direct_path?: string
666
+ meta_hmac?: string
667
+ ts?: number
668
+ fbid?: number
669
+ }
670
+
671
+ export type UploadParams = {
672
+ url: string
673
+ filePath: string
674
+ headers: Record<string, string>
675
+ timeoutMs?: number
676
+ agent?: Agent
677
+ }
678
+
679
+ export const uploadWithNodeHttp = async (
680
+ { url, filePath, headers, timeoutMs, agent }: UploadParams,
681
+ redirectCount = 0
682
+ ): Promise<MediaUploadResult | undefined> => {
683
+ if (redirectCount > 5) {
684
+ throw new Error('Too many redirects')
685
+ }
686
+
687
+ const parsedUrl = new URL(url)
688
+ const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http')
689
+
690
+ // Get file size for Content-Length header (required for Node.js streaming)
691
+ const fileStats = await fs.stat(filePath)
692
+ const fileSize = fileStats.size
693
+
694
+ return new Promise((resolve, reject) => {
695
+ const req = httpModule.request(
696
+ {
697
+ hostname: parsedUrl.hostname,
698
+ port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
699
+ path: parsedUrl.pathname + parsedUrl.search,
700
+ method: 'POST',
701
+ headers: {
702
+ ...headers,
703
+ 'Content-Length': fileSize
704
+ },
705
+ agent,
706
+ timeout: timeoutMs
707
+ },
708
+ res => {
709
+ // Handle redirects (3xx)
710
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
711
+ res.resume() // Consume response to free resources
712
+ const newUrl = new URL(res.headers.location, url).toString()
713
+ resolve(
714
+ uploadWithNodeHttp(
715
+ {
716
+ url: newUrl,
717
+ filePath,
718
+ headers,
719
+ timeoutMs,
720
+ agent
721
+ },
722
+ redirectCount + 1
723
+ )
724
+ )
725
+ return
726
+ }
727
+
728
+ let body = ''
729
+ res.on('data', chunk => (body += chunk))
730
+ res.on('end', () => {
731
+ try {
732
+ resolve(JSON.parse(body))
733
+ } catch {
734
+ resolve(undefined)
735
+ }
736
+ })
737
+ }
738
+ )
739
+
740
+ req.on('error', reject)
741
+ req.on('timeout', () => {
742
+ req.destroy()
743
+ reject(new Error('Upload timeout'))
744
+ })
745
+
746
+ const stream = createReadStream(filePath)
747
+ stream.pipe(req)
748
+ stream.on('error', err => {
749
+ req.destroy()
750
+ reject(err)
751
+ })
752
+ })
753
+ }
754
+
755
+ const uploadWithFetch = async ({
756
+ url,
757
+ filePath,
758
+ headers,
759
+ timeoutMs,
760
+ agent
761
+ }: UploadParams): Promise<MediaUploadResult | undefined> => {
762
+ // Convert Node.js Readable to Web ReadableStream
763
+ const nodeStream = createReadStream(filePath)
764
+ const webStream = Readable.toWeb(nodeStream) as ReadableStream
765
+
766
+ const response = await fetch(url, {
767
+ dispatcher: agent,
768
+ method: 'POST',
769
+ body: webStream,
770
+ headers,
771
+ duplex: 'half',
772
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
773
+ })
774
+
775
+ try {
776
+ return (await response.json()) as MediaUploadResult
777
+ } catch {
778
+ return undefined
779
+ }
780
+ }
781
+
782
+ /**
783
+ * Uploads media to WhatsApp servers.
784
+ *
785
+ * ## Why we have two upload implementations:
786
+ *
787
+ * Node.js's native `fetch` (powered by undici) has a known bug where it buffers
788
+ * the entire request body in memory before sending, even when using streams.
789
+ * This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
790
+ * See: https://github.com/nodejs/undici/issues/4058
791
+ *
792
+ * Other runtimes (Bun, Deno, browsers) correctly stream the request body without
793
+ * buffering, so we can use the web-standard Fetch API there.
794
+ *
795
+ * ## Future considerations:
796
+ * Once the undici bug is fixed, we can simplify this to use only the Fetch API
797
+ * across all runtimes. Monitor the GitHub issue for updates.
798
+ */
799
+ const uploadMedia = async (params: UploadParams, logger?: ILogger): Promise<MediaUploadResult | undefined> => {
800
+ if (isNodeRuntime()) {
801
+ logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)')
802
+ return uploadWithNodeHttp(params)
803
+ } else {
804
+ logger?.debug('Using web-standard Fetch API for upload')
805
+ return uploadWithFetch(params)
806
+ }
807
+ }
808
+
809
+ export const getWAUploadToServer = (
810
+ { customUploadHosts, fetchAgent, logger, options }: SocketConfig,
811
+ refreshMediaConn: (force: boolean) => Promise<MediaConnInfo>
812
+ ): WAMediaUploadFunction => {
813
+ return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
814
+ // send a query JSON to obtain the url & auth token to upload our media
815
+ let uploadInfo = await refreshMediaConn(false)
816
+
817
+ let urls: { mediaUrl: string; directPath: string; meta_hmac?: string; ts?: number; fbid?: number } | undefined
818
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts]
819
+
820
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
821
+
822
+ // Prepare common headers
823
+ const customHeaders = (() => {
824
+ const hdrs = options?.headers
825
+ if (!hdrs) return {}
826
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : (hdrs as Record<string, string>)
827
+ })()
828
+
829
+ const headers = {
830
+ ...customHeaders,
831
+ 'Content-Type': 'application/octet-stream',
832
+ Origin: DEFAULT_ORIGIN
833
+ }
834
+
835
+ for (const { hostname } of hosts) {
836
+ logger.debug(`uploading to "${hostname}"`)
837
+
838
+ const auth = encodeURIComponent(uploadInfo.auth)
839
+ const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
840
+
841
+ let result: MediaUploadResult | undefined
842
+ try {
843
+ result = await uploadMedia(
844
+ {
845
+ url,
846
+ filePath,
847
+ headers,
848
+ timeoutMs,
849
+ agent: fetchAgent
850
+ },
851
+ logger
852
+ )
853
+
854
+ if (result?.url || result?.direct_path) {
855
+ urls = {
856
+ mediaUrl: result.url!,
857
+ directPath: result.direct_path!,
858
+ meta_hmac: result.meta_hmac,
859
+ fbid: result.fbid,
860
+ ts: result.ts
861
+ }
862
+ break
863
+ } else {
864
+ uploadInfo = await refreshMediaConn(true)
865
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
866
+ }
867
+ } catch (error: any) {
868
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname
869
+ logger.warn(
870
+ { trace: error?.stack, uploadResult: result },
871
+ `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`
872
+ )
873
+ }
874
+ }
875
+
876
+ if (!urls) {
877
+ throw new Boom('Media upload failed on all hosts', { statusCode: 500 })
878
+ }
879
+
880
+ return urls
881
+ }
882
+ }
883
+
884
+ const getMediaRetryKey = (mediaKey: Buffer | Uint8Array) => {
885
+ return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
886
+ }
887
+
888
+ /**
889
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
890
+ */
891
+ export const encryptMediaRetryRequest = (key: WAMessageKey, mediaKey: Buffer | Uint8Array, meId: string) => {
892
+ const recp: proto.IServerErrorReceipt = { stanzaId: key.id }
893
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
894
+
895
+ const iv = Crypto.randomBytes(12)
896
+ const retryKey = getMediaRetryKey(mediaKey)
897
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id!))
898
+
899
+ const req: BinaryNode = {
900
+ tag: 'receipt',
901
+ attrs: {
902
+ id: key.id!,
903
+ to: jidNormalizedUser(meId),
904
+ type: 'server-error'
905
+ },
906
+ content: [
907
+ // this encrypt node is actually pretty useless
908
+ // the media is returned even without this node
909
+ // keeping it here to maintain parity with WA Web
910
+ {
911
+ tag: 'encrypt',
912
+ attrs: {},
913
+ content: [
914
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
915
+ { tag: 'enc_iv', attrs: {}, content: iv }
916
+ ]
917
+ },
918
+ {
919
+ tag: 'rmr',
920
+ attrs: {
921
+ jid: key.remoteJid!,
922
+ from_me: (!!key.fromMe).toString(),
923
+ // @ts-ignore
924
+ participant: key.participant || undefined
925
+ }
926
+ }
927
+ ]
928
+ }
929
+
930
+ return req
931
+ }
932
+
933
+ export const decodeMediaRetryNode = (node: BinaryNode) => {
934
+ const rmrNode = getBinaryNodeChild(node, 'rmr')!
935
+
936
+ const event: BaileysEventMap['messages.media-update'][number] = {
937
+ key: {
938
+ id: node.attrs.id,
939
+ remoteJid: rmrNode.attrs.jid,
940
+ fromMe: rmrNode.attrs.from_me === 'true',
941
+ participant: rmrNode.attrs.participant
942
+ }
943
+ }
944
+
945
+ const errorNode = getBinaryNodeChild(node, 'error')
946
+ if (errorNode) {
947
+ const errorCode = +errorNode.attrs.code!
948
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
949
+ data: errorNode.attrs,
950
+ statusCode: getStatusCodeForMediaRetry(errorCode)
951
+ })
952
+ } else {
953
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt')
954
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p')
955
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv')
956
+ if (ciphertext && iv) {
957
+ event.media = { ciphertext, iv }
958
+ } else {
959
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
960
+ }
961
+ }
962
+
963
+ return event
964
+ }
965
+
966
+ export const decryptMediaRetryData = (
967
+ { ciphertext, iv }: { ciphertext: Uint8Array; iv: Uint8Array },
968
+ mediaKey: Uint8Array,
969
+ msgId: string
970
+ ) => {
971
+ const retryKey = getMediaRetryKey(mediaKey)
972
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId))
973
+ return proto.MediaRetryNotification.decode(plaintext)
974
+ }
975
+
976
+ export const getStatusCodeForMediaRetry = (code: number) =>
977
+ MEDIA_RETRY_STATUS_MAP[code as proto.MediaRetryNotification.ResultType]
978
+
979
+ const MEDIA_RETRY_STATUS_MAP = {
980
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
981
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
982
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
983
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
984
+ } as const