@badzz88/baileys 8.4.7 → 8.5.0

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