@hiroosy/baileys-lite 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,841 @@
1
+ /**
2
+ * Media handling utilities. Combines what used to be messages-media.js and link-preview.js.
3
+ *
4
+ * Optional packages (`sharp`, `@napi-rs/image`, `jimp`) are NOT declared in package.json. They are dynamically
5
+ * imported and used only if the application installs them itself; each call site degrades gracefully when one is
6
+ * missing (see below). Audio durations, WAV/FLAC waveforms and link previews no longer need `music-metadata`,
7
+ * `audio-decode` or `link-preview-js` — they're handled by the built-in modules in ../foundation.
8
+ */
9
+ import { spawn } from 'node:child_process'
10
+ import { audioDuration } from '../foundation/audio-duration.js'
11
+ import { decodeChannel0, waveformFromSamples } from '../foundation/audio-samples.js'
12
+ import { getLinkPreview } from '../foundation/link-preview.js'
13
+ import * as Crypto from 'node:crypto'
14
+ import { once } from 'node:events'
15
+ import { createReadStream, createWriteStream, promises as fs } from 'node:fs'
16
+ import { tmpdir } from 'node:os'
17
+ import { join } from 'node:path'
18
+ import { Readable, Transform } from 'node:stream'
19
+ import { proto } from '../../WAProto/index.js'
20
+ import { Boom } from '../foundation/boom.js'
21
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../binary/wa-binary.js'
22
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './wa-protocol-core.js'
23
+ import { generateMessageIDV2 } from './wa-protocol-core.js'
24
+
25
+ const DEFAULT_ORIGIN = 'https://web.whatsapp.com'
26
+
27
+ export const MEDIA_HKDF_KEY_MAPPING = {
28
+ audio: 'Audio',
29
+ document: 'Document',
30
+ gif: 'Video',
31
+ image: 'Image',
32
+ ppic: '',
33
+ product: 'Image',
34
+ ptt: 'Audio',
35
+ 'sticker-pack': 'Sticker Pack',
36
+ 'thumbnail-sticker-pack': 'Sticker Pack Thumbnail',
37
+ sticker: 'Image',
38
+ video: 'Video',
39
+ 'thumbnail-document': 'Document Thumbnail',
40
+ 'thumbnail-image': 'Image Thumbnail',
41
+ 'thumbnail-video': 'Video Thumbnail',
42
+ 'thumbnail-link': 'Link Thumbnail',
43
+ 'md-msg-hist': 'History',
44
+ 'md-app-state': 'App State',
45
+ 'product-catalog-image': 'Product Catalog Image',
46
+ 'payment-bg-image': 'Payment Background',
47
+ ptv: 'Video',
48
+ 'biz-cover-photo': 'Image',
49
+ location: 'Location',
50
+ contact: 'Contact',
51
+ 'voip-token': 'Voip Token'
52
+ }
53
+
54
+ export const MEDIA_PATH_MAP = {
55
+ image: '/mms/image',
56
+ video: '/mms/video',
57
+ document: '/mms/document',
58
+ audio: '/mms/audio',
59
+ sticker: '/mms/image',
60
+ 'sticker-pack': '/mms/sticker-pack',
61
+ 'thumbnail-sticker-pack': '/mms/thumbnail-sticker-pack',
62
+ 'thumbnail-link': '/mms/image',
63
+ 'thumbnail-image': '/mms/image',
64
+ 'thumbnail-video': '/mms/video',
65
+ 'thumbnail-document': '/mms/document',
66
+ 'product-catalog-image': '/product/image',
67
+ 'md-app-state': '',
68
+ 'md-msg-hist': '/mms/md-app-state',
69
+ 'biz-cover-photo': '/pps/biz-cover-photo'
70
+ }
71
+
72
+ export const MEDIA_KEYS = Object.keys(MEDIA_PATH_MAP)
73
+
74
+ const NEWSLETTER_MEDIA_PATH_MAP = {
75
+ image: '/newsletter/newsletter-image',
76
+ video: '/newsletter/newsletter-video',
77
+ document: '/newsletter/newsletter-document',
78
+ audio: '/newsletter/newsletter-audio',
79
+ sticker: '/newsletter/newsletter-image',
80
+ 'thumbnail-link': '/newsletter/newsletter-thumbnail-link'
81
+ }
82
+
83
+ const getTmpFilesDirectory = () => tmpdir()
84
+
85
+ /* ------------------------------------------------------------------ */
86
+ /* Image processing (sharp / @napi-rs/image / jimp — first available) */
87
+ /* ------------------------------------------------------------------ */
88
+
89
+ let imageProcessingLibrary
90
+ export const getImageProcessingLibrary = async () => {
91
+ if (imageProcessingLibrary) return imageProcessingLibrary
92
+ const [sharp, image, jimp] = await Promise.all([
93
+ import('sharp').catch(() => {}),
94
+ import('@napi-rs/image').catch(() => {}),
95
+ import('jimp').catch(() => {})
96
+ ])
97
+ if (sharp) imageProcessingLibrary = { sharp }
98
+ else if (image) imageProcessingLibrary = { image }
99
+ else if (jimp) imageProcessingLibrary = { jimp }
100
+ else throw new Boom('No image processing library available')
101
+ return imageProcessingLibrary
102
+ }
103
+
104
+ export const hkdfInfoKey = type => `WhatsApp ${MEDIA_HKDF_KEY_MAPPING[type]} Keys`
105
+
106
+ export const getRawMediaUploadData = async (media, mediaType, logger) => {
107
+ const { stream } = await getStream(media)
108
+ logger?.debug('got stream for raw upload')
109
+ const hasher = Crypto.createHash('sha256')
110
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2())
111
+ const fileWriteStream = createWriteStream(filePath)
112
+ let fileLength = 0
113
+ try {
114
+ for await (const data of stream) {
115
+ fileLength += data.length
116
+ hasher.update(data)
117
+ if (!fileWriteStream.write(data)) await once(fileWriteStream, 'drain')
118
+ }
119
+ fileWriteStream.end()
120
+ await once(fileWriteStream, 'finish')
121
+ stream.destroy()
122
+ const fileSha256 = hasher.digest()
123
+ logger?.debug('hashed data for raw upload')
124
+ return { filePath, fileSha256, fileLength }
125
+ } catch (error) {
126
+ fileWriteStream.destroy()
127
+ stream.destroy()
128
+ try {
129
+ await fs.unlink(filePath)
130
+ } catch {
131
+ // ignore
132
+ }
133
+ throw error
134
+ }
135
+ }
136
+
137
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
138
+ export async function getMediaKeys(buffer, mediaType) {
139
+ if (!buffer) throw new Boom('Cannot derive from empty media key')
140
+ if (typeof buffer === 'string') buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64')
141
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
142
+ const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
143
+ return {
144
+ iv: expandedMediaKey.slice(0, 16),
145
+ cipherKey: expandedMediaKey.slice(16, 48),
146
+ macKey: expandedMediaKey.slice(48, 80)
147
+ }
148
+ }
149
+
150
+ /** Extracts video thumb using FFMPEG */
151
+ export const extractVideoThumb = async (path, time, size) => {
152
+ const ffmpeg = spawn(
153
+ 'ffmpeg',
154
+ [
155
+ '-loglevel',
156
+ 'error',
157
+ '-ss',
158
+ String(time),
159
+ '-i',
160
+ path,
161
+ '-an',
162
+ '-sn',
163
+ '-dn',
164
+ '-map_metadata',
165
+ '-1',
166
+ '-vf',
167
+ `scale=${size.width}:-1`,
168
+ '-frames:v',
169
+ '1',
170
+ '-c:v',
171
+ 'mjpeg',
172
+ '-f',
173
+ 'image2pipe',
174
+ 'pipe:1'
175
+ ],
176
+ { stdio: ['ignore', 'pipe', 'pipe'] }
177
+ )
178
+ let buffer = Buffer.alloc(0)
179
+ const stderrChunks = []
180
+ ffmpeg.stdout.on('data', chunk => {
181
+ buffer = Buffer.concat([buffer, chunk])
182
+ })
183
+ ffmpeg.stderr.on('data', chunk => stderrChunks.push(chunk))
184
+ const [code] = await once(ffmpeg, 'close')
185
+ if (code !== 0) throw new Boom(`FFmpeg failed (code ${code}):\n` + Buffer.concat(stderrChunks).toString('utf8'))
186
+ return buffer
187
+ }
188
+
189
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
190
+ if (bufferOrFilePath instanceof Readable) bufferOrFilePath = await toBuffer(bufferOrFilePath)
191
+ const lib = await getImageProcessingLibrary()
192
+ if ('sharp' in lib && lib.sharp?.default) {
193
+ const img = lib.sharp.default(bufferOrFilePath)
194
+ const dimensions = await img.metadata()
195
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer()
196
+ return { buffer, original: { width: dimensions.width, height: dimensions.height } }
197
+ } else if ('image' in lib && lib.image?.Transformer) {
198
+ if (!Buffer.isBuffer(bufferOrFilePath)) bufferOrFilePath = await fs.readFile(bufferOrFilePath)
199
+ const img = new lib.image.Transformer(bufferOrFilePath)
200
+ const dimensions = await img.metadata()
201
+ const buffer = await img.resize(width, undefined, 0).jpeg(50)
202
+ return { buffer, original: { width: dimensions.width, height: dimensions.height } }
203
+ } else if ('jimp' in lib && lib.jimp?.Jimp) {
204
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath)
205
+ const dimensions = { width: jimp.width, height: jimp.height }
206
+ const buffer = await jimp.resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 })
207
+ return { buffer, original: dimensions }
208
+ } else {
209
+ throw new Boom('No image processing library available')
210
+ }
211
+ }
212
+
213
+ export const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''))
214
+
215
+ export const generateProfilePicture = async (mediaUpload, dimensions) => {
216
+ let buffer
217
+ const { width: w = 720, height: h = 720 } = dimensions || {}
218
+ if (Buffer.isBuffer(mediaUpload)) {
219
+ buffer = mediaUpload
220
+ } else {
221
+ const { stream } = await getStream(mediaUpload)
222
+ buffer = await toBuffer(stream)
223
+ }
224
+ const lib = await getImageProcessingLibrary()
225
+ let img
226
+ if ('sharp' in lib && lib.sharp?.default) {
227
+ img = lib.sharp.default(buffer).resize(w, h).jpeg({ quality: 80 }).toBuffer()
228
+ } else if ('image' in lib && lib.image?.Transformer) {
229
+ img = new lib.image.Transformer(buffer).resize(w, h, 0).jpeg(80)
230
+ } else if ('jimp' in lib && lib.jimp?.Jimp) {
231
+ const jimp = await lib.jimp.Jimp.read(buffer)
232
+ const min = Math.min(jimp.width, jimp.height)
233
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min })
234
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 80 })
235
+ } else {
236
+ throw new Boom('No image processing library available')
237
+ }
238
+ return { img: await img }
239
+ }
240
+
241
+ /** gets the SHA256 of the given media message */
242
+ export const mediaMessageSHA256B64 = message => {
243
+ const media = Object.values(message)[0]
244
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64')
245
+ }
246
+
247
+ /**
248
+ * Duration of an audio file in seconds. Accepts a Buffer, a file path, or a Readable stream.
249
+ *
250
+ * Built-in parser: Ogg Opus/Vorbis, WAV, FLAC, MP4/M4A, MP3, ADTS-AAC, AIFF/AIFF-C, Matroska/WebM, AMR-NB/WB —
251
+ * see src/foundation/audio-duration.js. Anything else (WMA, APE, WavPack, Musepack, DSD, ...) resolves
252
+ * `undefined` rather than guessing.
253
+ */
254
+ export async function getAudioDuration(buffer) {
255
+ if (!Buffer.isBuffer(buffer) && typeof buffer !== 'string') buffer = await toBuffer(buffer)
256
+ const native = await audioDuration(buffer)
257
+ if (typeof native === 'number' && Number.isFinite(native)) return native
258
+ return ffprobeDuration(buffer) // containers the built-in parser doesn't cover (WMA, APE, ...)
259
+ }
260
+
261
+ async function ffprobeDuration(input) {
262
+ const usesStdin = Buffer.isBuffer(input)
263
+ const args = ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', usesStdin ? 'pipe:0' : input]
264
+ try {
265
+ const ffprobe = spawn('ffprobe', args, { stdio: [usesStdin ? 'pipe' : 'ignore', 'pipe', 'ignore'] })
266
+ const outChunks = []
267
+ ffprobe.stdout.on('data', chunk => outChunks.push(chunk))
268
+ if (usesStdin) ffprobe.stdin.end(input)
269
+ const [code] = await once(ffprobe, 'close')
270
+ if (code !== 0) return undefined
271
+ const seconds = parseFloat(Buffer.concat(outChunks).toString('utf8').trim())
272
+ return Number.isFinite(seconds) ? seconds : undefined
273
+ } catch {
274
+ return undefined // ffprobe not installed
275
+ }
276
+ }
277
+
278
+ /**
279
+ * First channel of an audio file as float samples via the system `ffmpeg` binary (a program, not an npm package;
280
+ * media.js already shells out to it for video thumbnails). Used only for containers the built-in decoder cannot
281
+ * read (Ogg Opus/Vorbis, MP3, AAC/M4A, AMR, ...). Resolves `undefined` when ffmpeg is missing or fails.
282
+ */
283
+ const decodeChannel0WithFfmpeg = audioData =>
284
+ new Promise(resolve => {
285
+ let child
286
+ try {
287
+ child = spawn('ffmpeg', ['-v', 'error', '-i', 'pipe:0', '-af', 'pan=mono|c0=c0', '-ar', '16000', '-f', 'f32le', 'pipe:1'], { stdio: ['pipe', 'pipe', 'ignore'] })
288
+ } catch {
289
+ return resolve(undefined)
290
+ }
291
+ const out = []
292
+ const timer = setTimeout(() => {
293
+ child.kill('SIGKILL')
294
+ resolve(undefined)
295
+ }, 60000)
296
+ child.on('error', () => resolve(undefined)) // ENOENT: ffmpeg not installed
297
+ child.stdin.on('error', () => {}) // ffmpeg may close its input early (EPIPE)
298
+ child.stdout.on('data', c => out.push(c))
299
+ child.on('close', code => {
300
+ clearTimeout(timer)
301
+ const raw = Buffer.concat(out)
302
+ if (code !== 0 || raw.length < 4) return resolve(undefined)
303
+ const copy = new Float32Array(Math.floor(raw.length / 4))
304
+ for (let i = 0; i < copy.length; i++) copy[i] = raw.readFloatLE(i * 4)
305
+ resolve(copy)
306
+ })
307
+ child.stdin.end(audioData)
308
+ })
309
+
310
+ /**
311
+ * 64-value voice-note waveform (0..100). WAV and FLAC are decoded by the built-in decoder; other formats need the
312
+ * system `ffmpeg` binary. Without either, resolves `undefined` (the voice note is still sent, just without a waveform).
313
+ * referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
314
+ */
315
+ export async function getAudioWaveform(buffer, logger) {
316
+ try {
317
+ let audioData
318
+ if (Buffer.isBuffer(buffer)) audioData = buffer
319
+ else if (typeof buffer === 'string') audioData = await toBuffer(createReadStream(buffer))
320
+ else audioData = await toBuffer(buffer)
321
+ const rawData = decodeChannel0(audioData) ?? (await decodeChannel0WithFfmpeg(audioData))
322
+ if (!rawData || !rawData.length) {
323
+ logger?.debug('Failed to generate waveform: no decoder for this audio (built-in handles WAV/FLAC; other formats need ffmpeg)')
324
+ return undefined
325
+ }
326
+ return waveformFromSamples(rawData)
327
+ } catch (e) {
328
+ logger?.debug('Failed to generate waveform: ' + e)
329
+ }
330
+ }
331
+
332
+ export const toReadable = buffer => {
333
+ const readable = new Readable({ read: () => {} })
334
+ readable.push(buffer)
335
+ readable.push(null)
336
+ return readable
337
+ }
338
+
339
+ export const toBuffer = async stream => {
340
+ const chunks = []
341
+ for await (const chunk of stream) chunks.push(chunk)
342
+ stream.destroy()
343
+ return Buffer.concat(chunks)
344
+ }
345
+
346
+ export const getStream = async (item, opts) => {
347
+ if (Buffer.isBuffer(item)) return { stream: toReadable(item), type: 'buffer' }
348
+ if ('stream' in item) return { stream: item.stream, type: 'readable' }
349
+ const urlStr = item.url.toString()
350
+ if (urlStr.startsWith('data:')) {
351
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64')
352
+ return { stream: toReadable(buffer), type: 'buffer' }
353
+ }
354
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) return { stream: await getHttpStream(item.url, opts), type: 'remote' }
355
+ return { stream: createReadStream(item.url), type: 'file' }
356
+ }
357
+
358
+ /** generates a thumbnail for a given media, if required */
359
+ export async function generateThumbnail(file, mediaType, options) {
360
+ let thumbnail
361
+ let originalImageDimensions
362
+ if (mediaType === 'image') {
363
+ const { buffer, original } = await extractImageThumb(file)
364
+ thumbnail = buffer.toString('base64')
365
+ if (original.width && original.height) originalImageDimensions = { width: original.width, height: original.height }
366
+ } else if (mediaType === 'video') {
367
+ try {
368
+ const buff = await extractVideoThumb(file, '00:00:00', { width: 32, height: 32 })
369
+ thumbnail = buff.toString('base64')
370
+ } catch (err) {
371
+ options.logger?.debug('could not generate video thumb: ' + err)
372
+ }
373
+ }
374
+ return { thumbnail, originalImageDimensions }
375
+ }
376
+
377
+ export const getHttpStream = async (url, options = {}) => {
378
+ const response = await fetch(url.toString(), { dispatcher: options.dispatcher, method: 'GET', headers: options.headers })
379
+ if (!response.ok) throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } })
380
+ return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body)
381
+ }
382
+
383
+ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
384
+ const { stream, type } = await getStream(media, opts)
385
+ logger?.debug('fetched media stream')
386
+ const mediaKey = Crypto.randomBytes(32)
387
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType)
388
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc')
389
+ const encFileWriteStream = createWriteStream(encFilePath)
390
+ let originalFileStream
391
+ let originalFilePath
392
+ if (saveOriginalFileIfRequired) {
393
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original')
394
+ originalFileStream = createWriteStream(originalFilePath)
395
+ }
396
+ let fileLength = 0
397
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv)
398
+ const hmac = Crypto.createHmac('sha256', macKey).update(iv)
399
+ const sha256Plain = Crypto.createHash('sha256')
400
+ const sha256Enc = Crypto.createHash('sha256')
401
+ const onChunk = async buff => {
402
+ sha256Enc.update(buff)
403
+ hmac.update(buff)
404
+ if (!encFileWriteStream.write(buff)) await once(encFileWriteStream, 'drain')
405
+ }
406
+ try {
407
+ for await (const data of stream) {
408
+ fileLength += data.length
409
+ if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
410
+ throw new Boom(`content length exceeded when encrypting "${type}"`, { data: { media, type } })
411
+ }
412
+ if (originalFileStream) {
413
+ if (!originalFileStream.write(data)) await once(originalFileStream, 'drain')
414
+ }
415
+ sha256Plain.update(data)
416
+ await onChunk(aes.update(data))
417
+ }
418
+ await onChunk(aes.final())
419
+ const mac = hmac.digest().slice(0, 10)
420
+ sha256Enc.update(mac)
421
+ const fileSha256 = sha256Plain.digest()
422
+ const fileEncSha256 = sha256Enc.digest()
423
+ encFileWriteStream.write(mac)
424
+ const encFinishPromise = once(encFileWriteStream, 'finish')
425
+ const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve()
426
+ encFileWriteStream.end()
427
+ originalFileStream?.end?.()
428
+ stream.destroy()
429
+ // Wait for write streams to fully flush to disk (reduces memory pressure).
430
+ await encFinishPromise
431
+ await originalFinishPromise
432
+ logger?.debug('encrypted data successfully')
433
+ return { mediaKey, originalFilePath, encFilePath, mac, fileEncSha256, fileSha256, fileLength }
434
+ } catch (error) {
435
+ encFileWriteStream.destroy()
436
+ originalFileStream?.destroy?.()
437
+ aes.destroy()
438
+ hmac.destroy()
439
+ sha256Plain.destroy()
440
+ sha256Enc.destroy()
441
+ stream.destroy()
442
+ try {
443
+ await fs.unlink(encFilePath)
444
+ if (originalFilePath) await fs.unlink(originalFilePath)
445
+ } catch (err) {
446
+ logger?.error({ err }, 'failed deleting tmp files')
447
+ }
448
+ throw error
449
+ }
450
+ }
451
+
452
+ export const DEF_MEDIA_HOST = 'mmg.whatsapp.net'
453
+ const AES_CHUNK_SIZE = 16
454
+ const toSmallestChunkSize = num => Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE
455
+
456
+ export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`
457
+
458
+ const extractHost = url => {
459
+ if (!url) return undefined
460
+ try {
461
+ return new URL(url).host
462
+ } catch {
463
+ return undefined
464
+ }
465
+ }
466
+
467
+ export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
468
+ // Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
469
+ const fallbackHost = opts.host ?? extractHost(url)
470
+ const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url
471
+ if (!downloadUrl) throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 })
472
+ const keys = await getMediaKeys(mediaKey, type)
473
+ return downloadEncryptedContent(downloadUrl, keys, opts)
474
+ }
475
+
476
+ /** Decrypts and downloads an AES256-CBC encrypted file; the plaintext's SHA256 is appended to the ciphertext. */
477
+ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
478
+ let bytesFetched = 0
479
+ let startChunk = 0
480
+ let firstBlockIsIV = false
481
+ if (startByte) {
482
+ const chunk = toSmallestChunkSize(startByte || 0)
483
+ if (chunk) {
484
+ startChunk = chunk - AES_CHUNK_SIZE
485
+ bytesFetched = chunk
486
+ firstBlockIsIV = true
487
+ }
488
+ }
489
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined
490
+ const headersInit = options?.headers ? options.headers : undefined
491
+ const headers = {
492
+ ...(headersInit ? (Array.isArray(headersInit) ? Object.fromEntries(headersInit) : headersInit) : {}),
493
+ Origin: DEFAULT_ORIGIN
494
+ }
495
+ if (startChunk || endChunk) {
496
+ headers.Range = `bytes=${startChunk}-`
497
+ if (endChunk) headers.Range += endChunk
498
+ }
499
+ const fetched = await getHttpStream(downloadUrl, { ...(options || {}), headers })
500
+ let remainingBytes = Buffer.from([])
501
+ let aes
502
+
503
+ const pushBytes = (bytes, push) => {
504
+ if (startByte || endByte) {
505
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0)
506
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0)
507
+ push(bytes.slice(start, end))
508
+ bytesFetched += bytes.length
509
+ } else {
510
+ push(bytes)
511
+ }
512
+ }
513
+
514
+ const output = new Transform({
515
+ transform(chunk, _, callback) {
516
+ let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk
517
+ const decryptLength = toSmallestChunkSize(data.length)
518
+ remainingBytes = data.slice(decryptLength)
519
+ data = data.slice(0, decryptLength)
520
+ if (!aes) {
521
+ let ivValue = iv
522
+ if (firstBlockIsIV) {
523
+ ivValue = data.slice(0, AES_CHUNK_SIZE)
524
+ data = data.slice(AES_CHUNK_SIZE)
525
+ }
526
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
527
+ if (endByte) aes.setAutoPadding(false) // avoid PKCS7 errors when trimming to a byte range
528
+ }
529
+ try {
530
+ pushBytes(aes.update(data), b => this.push(b))
531
+ callback()
532
+ } catch (error) {
533
+ callback(error)
534
+ }
535
+ },
536
+ final(callback) {
537
+ try {
538
+ pushBytes(aes.final(), b => this.push(b))
539
+ callback()
540
+ } catch (error) {
541
+ callback(error)
542
+ }
543
+ }
544
+ })
545
+ // pipe() does not forward 'error' events from source to destination -- without this,
546
+ // a dropped connection or malformed response on `fetched` crashes the process
547
+ // (unhandled 'error' on the source) instead of surfacing as an error on the
548
+ // returned stream that callers can catch.
549
+ fetched.on('error', err => output.destroy(err))
550
+ return fetched.pipe(output, { end: true })
551
+ }
552
+
553
+ export function extensionForMediaMessage(message) {
554
+ const getExtension = mimetype => mimetype.split(';')[0]?.split('/')[1]
555
+ const type = Object.keys(message)[0]
556
+ let extension
557
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
558
+ extension = '.jpeg'
559
+ } else {
560
+ extension = getExtension(message[type].mimetype)
561
+ }
562
+ return extension
563
+ }
564
+
565
+ const isNodeRuntime = () =>
566
+ typeof process !== 'undefined' && process.versions?.node !== null && typeof process.versions.bun === 'undefined' && typeof globalThis.Deno === 'undefined'
567
+
568
+ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
569
+ if (redirectCount > 5) throw new Error('Too many redirects')
570
+ const parsedUrl = new URL(url)
571
+ const httpModule = parsedUrl.protocol === 'https:' ? await import('node:https') : await import('node:http')
572
+ const fileStats = await fs.stat(filePath) // Content-Length is required for Node.js streaming
573
+ const fileSize = fileStats.size
574
+ return new Promise((resolve, reject) => {
575
+ const req = httpModule.request(
576
+ {
577
+ hostname: parsedUrl.hostname,
578
+ port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
579
+ path: parsedUrl.pathname + parsedUrl.search,
580
+ method: 'POST',
581
+ headers: { ...headers, 'Content-Length': fileSize },
582
+ agent,
583
+ timeout: timeoutMs
584
+ },
585
+ res => {
586
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
587
+ res.resume() // consume response to free resources
588
+ const newUrl = new URL(res.headers.location, url).toString()
589
+ resolve(uploadWithNodeHttp({ url: newUrl, filePath, headers, timeoutMs, agent }, redirectCount + 1))
590
+ return
591
+ }
592
+ let body = ''
593
+ res.on('data', chunk => (body += chunk))
594
+ res.on('end', () => {
595
+ try {
596
+ resolve(JSON.parse(body))
597
+ } catch {
598
+ resolve(undefined)
599
+ }
600
+ })
601
+ }
602
+ )
603
+ req.on('error', reject)
604
+ req.on('timeout', () => {
605
+ req.destroy()
606
+ reject(new Error('Upload timeout'))
607
+ })
608
+ const stream = createReadStream(filePath)
609
+ stream.pipe(req)
610
+ stream.on('error', err => {
611
+ req.destroy()
612
+ reject(err)
613
+ })
614
+ })
615
+ }
616
+
617
+ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
618
+ const nodeStream = createReadStream(filePath)
619
+ const webStream = Readable.toWeb(nodeStream)
620
+ // Native fetch only accepts Undici-style dispatchers, not generic https Agents.
621
+ const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined
622
+ const response = await fetch(url, {
623
+ ...(dispatcher ? { dispatcher } : {}),
624
+ method: 'POST',
625
+ body: webStream,
626
+ headers,
627
+ duplex: 'half',
628
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
629
+ })
630
+ try {
631
+ return await response.json()
632
+ } catch {
633
+ return undefined
634
+ }
635
+ }
636
+
637
+ /**
638
+ * Uploads media to WhatsApp servers.
639
+ *
640
+ * Two implementations: Node's native `fetch` (undici) buffers the whole request body in
641
+ * memory even when streaming, causing high memory use on large files
642
+ * (see https://github.com/nodejs/undici/issues/4058) — so on Node we use `node:http(s)`
643
+ * directly. Other runtimes (Bun, Deno, browsers) stream correctly, so they use fetch.
644
+ */
645
+ const uploadMedia = async (params, logger) => {
646
+ if (isNodeRuntime()) {
647
+ logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)')
648
+ return uploadWithNodeHttp(params)
649
+ } else {
650
+ logger?.debug('Using web-standard Fetch API for upload')
651
+ return uploadWithFetch(params)
652
+ }
653
+ }
654
+
655
+ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
656
+ return async (filePath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
657
+ let uploadInfo = await refreshMediaConn(false)
658
+ let urls
659
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts]
660
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
661
+ const customHeaders = (() => {
662
+ const hdrs = options?.headers
663
+ if (!hdrs) return {}
664
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs
665
+ })()
666
+ const headers = { ...customHeaders, 'Content-Type': 'application/octet-stream', Origin: DEFAULT_ORIGIN }
667
+
668
+ for (const { hostname } of hosts) {
669
+ logger.debug(`uploading to "${hostname}"`)
670
+ const auth = encodeURIComponent(uploadInfo.auth)
671
+ const mediaPathMap = newsletter ? NEWSLETTER_MEDIA_PATH_MAP : MEDIA_PATH_MAP
672
+ const serverThumb = newsletter ? '&server_thumb_gen=1' : ''
673
+ const url = `https://${hostname}${mediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}${serverThumb}`
674
+ let result
675
+ try {
676
+ result = await uploadMedia({ url, filePath, headers, timeoutMs, agent: fetchAgent }, logger)
677
+ if (result?.url || result?.direct_path) {
678
+ urls = {
679
+ mediaUrl: result.url,
680
+ directPath: result.direct_path,
681
+ meta_hmac: result.meta_hmac,
682
+ fbid: result.fbid,
683
+ ts: result.ts,
684
+ thumbnailDirectPath: result.thumbnail_info?.thumbnail_direct_path,
685
+ thumbnailSha256: result.thumbnail_info?.thumbnail_sha256
686
+ }
687
+ break
688
+ } else {
689
+ uploadInfo = await refreshMediaConn(true)
690
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`)
691
+ }
692
+ } catch (error) {
693
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname
694
+ logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`)
695
+ }
696
+ }
697
+ if (!urls) throw new Boom('Media upload failed on all hosts', { statusCode: 500 })
698
+ return urls
699
+ }
700
+ }
701
+
702
+ const getMediaRetryKey = mediaKey => hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
703
+
704
+ /** Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL */
705
+ export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
706
+ const recp = { stanzaId: key.id }
707
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
708
+ const iv = Crypto.randomBytes(12)
709
+ const retryKey = getMediaRetryKey(mediaKey)
710
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id))
711
+ return {
712
+ tag: 'receipt',
713
+ attrs: { id: key.id, to: jidNormalizedUser(meId), type: 'server-error' },
714
+ content: [
715
+ // this encrypt node is actually pretty useless — media returns even without it —
716
+ // kept here to maintain parity with WA Web
717
+ {
718
+ tag: 'encrypt',
719
+ attrs: {},
720
+ content: [
721
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
722
+ { tag: 'enc_iv', attrs: {}, content: iv }
723
+ ]
724
+ },
725
+ { tag: 'rmr', attrs: { jid: key.remoteJid, from_me: (!!key.fromMe).toString(), participant: key.participant || undefined } }
726
+ ]
727
+ }
728
+ }
729
+
730
+ export const decodeMediaRetryNode = node => {
731
+ const rmrNode = getBinaryNodeChild(node, 'rmr')
732
+ const event = {
733
+ key: {
734
+ id: node.attrs.id,
735
+ remoteJid: rmrNode.attrs.jid,
736
+ fromMe: rmrNode.attrs.from_me === 'true',
737
+ participant: rmrNode.attrs.participant
738
+ }
739
+ }
740
+ const errorNode = getBinaryNodeChild(node, 'error')
741
+ if (errorNode) {
742
+ const errorCode = +errorNode.attrs.code
743
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: getStatusCodeForMediaRetry(errorCode) })
744
+ } else {
745
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt')
746
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p')
747
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv')
748
+ if (ciphertext && iv) event.media = { ciphertext, iv }
749
+ else event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 })
750
+ }
751
+ return event
752
+ }
753
+
754
+ export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
755
+ const retryKey = getMediaRetryKey(mediaKey)
756
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId))
757
+ return proto.MediaRetryNotification.decode(plaintext)
758
+ }
759
+
760
+ const MEDIA_RETRY_STATUS_MAP = {
761
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
762
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
763
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
764
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
765
+ }
766
+ export const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code]
767
+
768
+ /* ------------------------------------------------------------------ */
769
+ /* Link preview */
770
+ /* ------------------------------------------------------------------ */
771
+
772
+ const THUMBNAIL_WIDTH_PX = 192
773
+
774
+ /** Fetches an image and generates a thumbnail for it */
775
+ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
776
+ const stream = await getHttpStream(url, fetchOpts)
777
+ return extractImageThumb(stream, thumbnailWidth)
778
+ }
779
+
780
+ /**
781
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it.
782
+ * Returns undefined if the fetch failed or no URL was found.
783
+ */
784
+ export const getUrlInfo = async (text, opts = { thumbnailWidth: THUMBNAIL_WIDTH_PX, fetchOpts: { timeout: 3000 } }) => {
785
+ try {
786
+ let retries = 0
787
+ const maxRetry = 5
788
+ let previewLink = text
789
+ if (!text.startsWith('https://') && !text.startsWith('http://')) previewLink = 'https://' + previewLink
790
+
791
+ const info = await getLinkPreview(previewLink, {
792
+ ...opts.fetchOpts,
793
+ followRedirects: 'follow',
794
+ handleRedirects: (baseURL, forwardedURL) => {
795
+ const urlObj = new URL(baseURL)
796
+ const forwardedURLObj = new URL(forwardedURL)
797
+ if (retries >= maxRetry) return false
798
+ if (
799
+ forwardedURLObj.hostname === urlObj.hostname ||
800
+ forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
801
+ 'www.' + forwardedURLObj.hostname === urlObj.hostname
802
+ ) {
803
+ retries += 1
804
+ return true
805
+ }
806
+ return false
807
+ },
808
+ headers: opts.fetchOpts?.headers
809
+ })
810
+
811
+ if (info && 'title' in info && info.title) {
812
+ const [image] = info.images
813
+ const urlInfo = {
814
+ 'canonical-url': info.url,
815
+ 'matched-text': text,
816
+ title: info.title,
817
+ description: info.description,
818
+ originalThumbnailUrl: image
819
+ }
820
+ if (opts.uploadImage) {
821
+ // imported lazily to avoid a hard circular dependency with the message-composition module
822
+ const { prepareWAMessageMedia } = await import('./message-compose.js')
823
+ const { imageMessage } = await prepareWAMessageMedia(
824
+ { image: { url: image } },
825
+ { upload: opts.uploadImage, mediaTypeOverride: 'thumbnail-link', options: opts.fetchOpts }
826
+ )
827
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined
828
+ urlInfo.highQualityThumbnail = imageMessage || undefined
829
+ } else {
830
+ try {
831
+ urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined
832
+ } catch (error) {
833
+ opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail')
834
+ }
835
+ }
836
+ return urlInfo
837
+ }
838
+ } catch (error) {
839
+ if (!error.message.includes('receive a valid')) throw error
840
+ }
841
+ }