@aseppxyzz12/baileys 1.1.8

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 (185) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +2579 -0
  3. package/WAProto/AICommon/AICommon.js +19396 -0
  4. package/WAProto/AICommon/AICommon.proto +820 -0
  5. package/WAProto/Adv/Adv.js +1137 -0
  6. package/WAProto/Adv/Adv.proto +42 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +8975 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +484 -0
  9. package/WAProto/Cert/Cert.js +893 -0
  10. package/WAProto/Cert/Cert.proto +30 -0
  11. package/WAProto/ChatLockSettings/ChatLockSettings.js +673 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.proto +9 -0
  13. package/WAProto/CompanionReg/CompanionReg.js +2457 -0
  14. package/WAProto/CompanionReg/CompanionReg.proto +103 -0
  15. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +846 -0
  16. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +38 -0
  17. package/WAProto/E2E/E2E.js +78728 -0
  18. package/WAProto/E2E/E2E.proto +1970 -0
  19. package/WAProto/Ephemeral/Ephemeral.js +143 -0
  20. package/WAProto/Ephemeral/Ephemeral.proto +7 -0
  21. package/WAProto/HistorySync/HistorySync.js +95931 -0
  22. package/WAProto/HistorySync/HistorySync.proto +229 -0
  23. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +414 -0
  24. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +13 -0
  25. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +980 -0
  26. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +38 -0
  27. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +81185 -0
  28. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +88 -0
  29. package/WAProto/MmsRetry/MmsRetry.js +310 -0
  30. package/WAProto/MmsRetry/MmsRetry.proto +19 -0
  31. package/WAProto/Protocol/Protocol.js +399 -0
  32. package/WAProto/Protocol/Protocol.proto +22 -0
  33. package/WAProto/Reporting/Reporting.js +535 -0
  34. package/WAProto/Reporting/Reporting.proto +22 -0
  35. package/WAProto/ServerSync/ServerSync.js +1830 -0
  36. package/WAProto/ServerSync/ServerSync.proto +70 -0
  37. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +3267 -0
  38. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +95 -0
  39. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1140 -0
  40. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +44 -0
  41. package/WAProto/StatusAttributions/StatusAttributions.js +1604 -0
  42. package/WAProto/StatusAttributions/StatusAttributions.proto +89 -0
  43. package/WAProto/SyncAction/SyncAction.js +17424 -0
  44. package/WAProto/SyncAction/SyncAction.proto +663 -0
  45. package/WAProto/UserPassword/UserPassword.js +544 -0
  46. package/WAProto/UserPassword/UserPassword.proto +28 -0
  47. package/WAProto/VnameCert/VnameCert.js +1466 -0
  48. package/WAProto/VnameCert/VnameCert.proto +65 -0
  49. package/WAProto/Wa6/Wa6.js +4601 -0
  50. package/WAProto/Wa6/Wa6.proto +241 -0
  51. package/WAProto/Web/Web.js +90819 -0
  52. package/WAProto/Web/Web.proto +605 -0
  53. package/WAProto/index.js +30 -0
  54. package/engine-requirements.js +9 -0
  55. package/lib/Defaults/baileys-version.json +3 -0
  56. package/lib/Defaults/connection.js +39 -0
  57. package/lib/Defaults/constants.js +50 -0
  58. package/lib/Defaults/history.js +13 -0
  59. package/lib/Defaults/index.js +36 -0
  60. package/lib/Defaults/media.js +43 -0
  61. package/lib/Defaults/phonenumber-mcc.json +223 -0
  62. package/lib/Defaults/prefix.js +12 -0
  63. package/lib/Function/Download/tiktok.js +19 -0
  64. package/lib/Function/Tools/bypass.js +19 -0
  65. package/lib/Function/index.js +13 -0
  66. package/lib/Signal/Group/ciphertext-message.js +14 -0
  67. package/lib/Signal/Group/group-session-builder.js +46 -0
  68. package/lib/Signal/Group/group_cipher.js +104 -0
  69. package/lib/Signal/Group/index.js +42 -0
  70. package/lib/Signal/Group/keyhelper.js +21 -0
  71. package/lib/Signal/Group/queue-job.js +57 -0
  72. package/lib/Signal/Group/sender-chain-key.js +34 -0
  73. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  74. package/lib/Signal/Group/sender-key-message.js +78 -0
  75. package/lib/Signal/Group/sender-key-name.js +49 -0
  76. package/lib/Signal/Group/sender-key-record.js +45 -0
  77. package/lib/Signal/Group/sender-key-state.js +100 -0
  78. package/lib/Signal/Group/sender-message-key.js +28 -0
  79. package/lib/Signal/libsignal.js +364 -0
  80. package/lib/Signal/lid-mapping.js +164 -0
  81. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  82. package/lib/Socket/Client/index.js +31 -0
  83. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  84. package/lib/Socket/Client/types.js +12 -0
  85. package/lib/Socket/Client/web-socket-client.js +62 -0
  86. package/lib/Socket/Client/websocket.js +67 -0
  87. package/lib/Socket/business.js +291 -0
  88. package/lib/Socket/chats.js +874 -0
  89. package/lib/Socket/community.js +454 -0
  90. package/lib/Socket/dugong.js +658 -0
  91. package/lib/Socket/groups.js +357 -0
  92. package/lib/Socket/index.js +13 -0
  93. package/lib/Socket/messages-recv.js +1509 -0
  94. package/lib/Socket/messages-send.js +1505 -0
  95. package/lib/Socket/mex.js +54 -0
  96. package/lib/Socket/newsletter.js +171 -0
  97. package/lib/Socket/registration.js +167 -0
  98. package/lib/Socket/rich-content.js +279 -0
  99. package/lib/Socket/socket.js +905 -0
  100. package/lib/Socket/username.js +157 -0
  101. package/lib/Socket/usync.js +70 -0
  102. package/lib/Store/index.js +37 -0
  103. package/lib/Store/keyed-db.js +114 -0
  104. package/lib/Store/make-cache-manager-store.js +77 -0
  105. package/lib/Store/make-in-memory-store.js +423 -0
  106. package/lib/Store/make-ordered-dictionary.js +78 -0
  107. package/lib/Store/object-repository.js +26 -0
  108. package/lib/Types/Auth.js +2 -0
  109. package/lib/Types/Bussines.js +2 -0
  110. package/lib/Types/Call.js +2 -0
  111. package/lib/Types/Chat.js +10 -0
  112. package/lib/Types/Contact.js +2 -0
  113. package/lib/Types/Events.js +2 -0
  114. package/lib/Types/GroupMetadata.js +2 -0
  115. package/lib/Types/Label.js +25 -0
  116. package/lib/Types/LabelAssociation.js +4 -0
  117. package/lib/Types/Message.js +11 -0
  118. package/lib/Types/Mex.js +40 -0
  119. package/lib/Types/MexUpdates.js +15 -0
  120. package/lib/Types/Newsletter.js +32 -0
  121. package/lib/Types/Product.js +2 -0
  122. package/lib/Types/Signal.js +2 -0
  123. package/lib/Types/Socket.js +2 -0
  124. package/lib/Types/State.js +9 -0
  125. package/lib/Types/USync.js +2 -0
  126. package/lib/Types/index.js +60 -0
  127. package/lib/Utils/auth-utils.js +256 -0
  128. package/lib/Utils/baileys-event-stream.js +63 -0
  129. package/lib/Utils/bot-toolkit.js +455 -0
  130. package/lib/Utils/browser-utils.js +29 -0
  131. package/lib/Utils/business.js +233 -0
  132. package/lib/Utils/chat-utils.js +904 -0
  133. package/lib/Utils/companion-reg-client-utils.js +41 -0
  134. package/lib/Utils/crypto.js +144 -0
  135. package/lib/Utils/decode-wa-message.js +305 -0
  136. package/lib/Utils/event-buffer.js +555 -0
  137. package/lib/Utils/generics.js +411 -0
  138. package/lib/Utils/history.js +100 -0
  139. package/lib/Utils/identity-change-handler.js +53 -0
  140. package/lib/Utils/index.js +57 -0
  141. package/lib/Utils/link-preview.js +76 -0
  142. package/lib/Utils/logger.js +4 -0
  143. package/lib/Utils/lt-hash.js +45 -0
  144. package/lib/Utils/make-mutex.js +33 -0
  145. package/lib/Utils/message-composer.js +289 -0
  146. package/lib/Utils/message-retry-manager.js +134 -0
  147. package/lib/Utils/messages-media.js +806 -0
  148. package/lib/Utils/messages.js +1908 -0
  149. package/lib/Utils/noise-handler.js +157 -0
  150. package/lib/Utils/offline-node-processor.js +42 -0
  151. package/lib/Utils/pre-key-manager.js +86 -0
  152. package/lib/Utils/process-message.js +814 -0
  153. package/lib/Utils/reporting-utils.js +264 -0
  154. package/lib/Utils/signal.js +183 -0
  155. package/lib/Utils/stanza-ack.js +36 -0
  156. package/lib/Utils/sync-action-utils.js +52 -0
  157. package/lib/Utils/tc-token-utils.js +167 -0
  158. package/lib/Utils/use-multi-file-auth-state.js +104 -0
  159. package/lib/Utils/validate-connection.js +229 -0
  160. package/lib/Utils/vialeys-event-stream.js +41 -0
  161. package/lib/WABinary/constants.js +1308 -0
  162. package/lib/WABinary/decode.js +233 -0
  163. package/lib/WABinary/encode.js +212 -0
  164. package/lib/WABinary/generic-utils.js +124 -0
  165. package/lib/WABinary/index.js +36 -0
  166. package/lib/WABinary/jid-utils.js +101 -0
  167. package/lib/WABinary/types.js +2 -0
  168. package/lib/WAM/BinaryInfo.js +12 -0
  169. package/lib/WAM/constants.js +20491 -0
  170. package/lib/WAM/encode.js +148 -0
  171. package/lib/WAM/index.js +34 -0
  172. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.js +38 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -0
  176. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -0
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +32 -0
  178. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  179. package/lib/WAUSync/Protocols/index.js +38 -0
  180. package/lib/WAUSync/USyncQuery.js +97 -0
  181. package/lib/WAUSync/USyncUser.js +33 -0
  182. package/lib/WAUSync/index.js +34 -0
  183. package/lib/index.js +113 -0
  184. package/lib/messages-send.js +1496 -0
  185. package/package.json +100 -0
@@ -0,0 +1,806 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { Boom: Boom } = require("@hapi/boom");
4
+ const { exec: exec } = require("child_process");
5
+ const { once: once } = require("events");
6
+ const {
7
+ createHash: createHash,
8
+ randomBytes: randomBytes,
9
+ createHmac: createHmac,
10
+ createCipheriv: createCipheriv,
11
+ createDecipheriv: createDecipheriv,
12
+ } = require("crypto");
13
+ const {
14
+ promises: promises,
15
+ createReadStream: createReadStream,
16
+ createWriteStream: createWriteStream,
17
+ } = require("fs");
18
+ const {
19
+ parseBuffer: parseBuffer,
20
+ parseFile: parseFile,
21
+ parseStream: parseStream,
22
+ } = require("music-metadata");
23
+ const { tmpdir: tmpdir } = require("os");
24
+ const { join: join } = require("path");
25
+ const { Readable: Readable, Transform: Transform } = require("stream");
26
+ const { proto: proto } = require("../../WAProto");
27
+ const {
28
+ MEDIA_PATH_MAP: MEDIA_PATH_MAP,
29
+ MEDIA_HKDF_KEY_MAPPING: MEDIA_HKDF_KEY_MAPPING,
30
+ } = require("../Defaults/media");
31
+ const { DEFAULT_ORIGIN: DEFAULT_ORIGIN } = require("../Defaults/constants");
32
+ const {
33
+ getBinaryNodeChild: getBinaryNodeChild,
34
+ getBinaryNodeChildBuffer: getBinaryNodeChildBuffer,
35
+ jidNormalizedUser: jidNormalizedUser,
36
+ } = require("../WABinary");
37
+ const {
38
+ aesDecryptGCM: aesDecryptGCM,
39
+ aesEncryptGCM: aesEncryptGCM,
40
+ hkdf: hkdf,
41
+ } = require("./crypto");
42
+ const { generateMessageID: generateMessageID } = require("./generics");
43
+ const getTmpFilesDirectory = () => tmpdir();
44
+ const getImageProcessingLibrary = () => {
45
+ let sharp, jimp;
46
+ try {
47
+ sharp = require("sharp");
48
+ } catch {}
49
+ if (sharp) {
50
+ return { sharp: sharp };
51
+ }
52
+ try {
53
+ jimp = require("jimp");
54
+ } catch {}
55
+ if (jimp) {
56
+ return { jimp: jimp };
57
+ }
58
+ throw new Boom("No image processing library available");
59
+ };
60
+ const hkdfInfoKey = (type) => {
61
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
62
+ return `WhatsApp ${hkdfInfo} Keys`;
63
+ };
64
+ const getRawMediaUploadData = async (media, mediaType, logger) => {
65
+ const { stream: stream } = await getStream(media);
66
+ logger?.debug("got stream for raw upload");
67
+ const hasher = createHash("sha256");
68
+ const filePath = join(getTmpFilesDirectory(), mediaType + generateMessageID());
69
+ const fileWriteStream = createWriteStream(filePath);
70
+ let fileLength = 0;
71
+ try {
72
+ for await (const data of stream) {
73
+ fileLength += data.length;
74
+ hasher.update(data);
75
+ if (!fileWriteStream.write(data)) {
76
+ await once(fileWriteStream, "drain");
77
+ }
78
+ }
79
+ fileWriteStream.end();
80
+ await once(fileWriteStream, "finish");
81
+ stream.destroy();
82
+ const fileSha256 = hasher.digest();
83
+ logger?.debug("hashed data for raw upload");
84
+ return {
85
+ filePath: filePath,
86
+ fileSha256: fileSha256,
87
+ fileLength: fileLength,
88
+ };
89
+ } catch (error) {
90
+ fileWriteStream.destroy();
91
+ stream.destroy();
92
+ try {
93
+ await promises.unlink(filePath);
94
+ } catch {}
95
+ throw error;
96
+ }
97
+ };
98
+ async function getMediaKeys(buffer, mediaType) {
99
+ if (!buffer) {
100
+ throw new Boom("Cannot derive from empty media key");
101
+ }
102
+ if (typeof buffer === "string") {
103
+ buffer = Buffer.from(buffer.replace("data:base64,", ""), "base64");
104
+ }
105
+ const expandedMediaKey = await hkdf(buffer, 112, {
106
+ info: hkdfInfoKey(mediaType),
107
+ });
108
+ return {
109
+ iv: expandedMediaKey.slice(0, 16),
110
+ cipherKey: expandedMediaKey.slice(16, 48),
111
+ macKey: expandedMediaKey.slice(48, 80),
112
+ };
113
+ }
114
+ const extractVideoThumb = async (path, destPath, time, size) =>
115
+ new Promise((resolve, reject) => {
116
+ const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
117
+ exec(cmd, (err) => {
118
+ if (err) {
119
+ reject(err);
120
+ } else {
121
+ resolve();
122
+ }
123
+ });
124
+ });
125
+ const extractImageThumb = async (bufferOrFilePath, width = 32, quality = 50) => {
126
+ if (bufferOrFilePath instanceof Readable) {
127
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
128
+ }
129
+ const lib = await getImageProcessingLibrary();
130
+ if ("sharp" in lib && typeof lib.sharp === "function") {
131
+ const img = lib.sharp(bufferOrFilePath);
132
+ const dimensions = await img.metadata();
133
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
134
+ return {
135
+ buffer: buffer,
136
+ original: { width: dimensions.width, height: dimensions.height },
137
+ };
138
+ } else if ("jimp" in lib && typeof lib.jimp.read === "function") {
139
+ const {
140
+ read: read,
141
+ MIME_JPEG: MIME_JPEG,
142
+ RESIZE_BEZIER: RESIZE_BEZIER,
143
+ AUTO: AUTO,
144
+ } = lib.jimp;
145
+ const jimp = await read(bufferOrFilePath);
146
+ const dimensions = { width: jimp.getWidth(), height: jimp.getHeight() };
147
+ const buffer = await jimp
148
+ .quality(quality)
149
+ .resize(width, AUTO, RESIZE_BEZIER)
150
+ .getBufferAsync(MIME_JPEG);
151
+ return { buffer: buffer, original: dimensions };
152
+ } else {
153
+ throw new Boom("No image processing library available");
154
+ }
155
+ };
156
+ const encodeBase64EncodedStringForUpload = (b64) =>
157
+ encodeURIComponent(b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/\=+$/, ""));
158
+ const generateProfilePicture = async (mediaUpload, dimensions) => {
159
+ let buffer;
160
+ const { width: w = 640, height: h = 640 } = dimensions || {};
161
+ if (Buffer.isBuffer(mediaUpload)) {
162
+ buffer = mediaUpload;
163
+ } else {
164
+ const { stream: stream } = await getStream(mediaUpload);
165
+ buffer = await toBuffer(stream);
166
+ }
167
+ const lib = await getImageProcessingLibrary();
168
+ let img;
169
+ if ("sharp" in lib && typeof lib.sharp?.default === "function") {
170
+ img = lib.sharp.default(buffer).resize(w, h).jpeg({ quality: 50 }).toBuffer();
171
+ } else if ("jimp" in lib && typeof lib.jimp?.read === "function") {
172
+ const jimp = await lib.jimp.read(buffer);
173
+ const min = Math.min(jimp.width, jimp.height);
174
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
175
+ img = cropped
176
+ .resize({ w: w, h: h, mode: lib.jimp.ResizeStrategy.BILINEAR })
177
+ .getBuffer("image/jpeg", { quality: 50 });
178
+ } else {
179
+ throw new Boom("No image processing library available");
180
+ }
181
+ return { img: await img };
182
+ };
183
+ const mediaMessageSHA256B64 = (message) => {
184
+ const media = Object.values(message)[0];
185
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString("base64");
186
+ };
187
+ async function getAudioDuration(buffer) {
188
+ const options = { duration: true };
189
+ let metadata;
190
+ if (Buffer.isBuffer(buffer)) {
191
+ metadata = await parseBuffer(buffer, undefined, options);
192
+ } else if (typeof buffer === "string") {
193
+ metadata = await parseFile(buffer, options);
194
+ } else {
195
+ metadata = await parseStream(buffer, undefined, options);
196
+ }
197
+ return metadata.format?.duration;
198
+ }
199
+ async function getAudioWaveform(buffer, logger) {
200
+ try {
201
+ const { default: decoder } = await eval("import('audio-decode')");
202
+ let audioData;
203
+ if (Buffer.isBuffer(buffer)) {
204
+ audioData = buffer;
205
+ } else if (typeof buffer === "string") {
206
+ const rStream = createReadStream(buffer);
207
+ audioData = await toBuffer(rStream);
208
+ } else {
209
+ audioData = await toBuffer(buffer);
210
+ }
211
+ const audioBuffer = await decoder(audioData);
212
+ const rawData = audioBuffer.getChannelData(0);
213
+ const samples = 64;
214
+ const blockSize = Math.floor(rawData.length / samples);
215
+ const filteredData = [];
216
+ for (let i = 0; i < samples; i++) {
217
+ const blockStart = blockSize * i;
218
+ let sum = 0;
219
+ for (let j = 0; j < blockSize; j++) {
220
+ sum = sum + Math.abs(rawData[blockStart + j]);
221
+ }
222
+ filteredData.push(sum / blockSize);
223
+ }
224
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
225
+ const normalizedData = filteredData.map((n) => n * multiplier);
226
+ const waveform = new Uint8Array(normalizedData.map((n) => Math.floor(100 * n)));
227
+ return waveform;
228
+ } catch (e) {
229
+ logger?.debug("Failed to generate waveform: " + e);
230
+ }
231
+ }
232
+ const toReadable = (buffer) => {
233
+ const readable = new Readable({ read: () => {} });
234
+ readable.push(buffer);
235
+ readable.push(null);
236
+ return readable;
237
+ };
238
+ const toBuffer = async (stream) => {
239
+ const chunks = [];
240
+ for await (const chunk of stream) {
241
+ chunks.push(chunk);
242
+ }
243
+ stream.destroy();
244
+ return Buffer.concat(chunks);
245
+ };
246
+ const getStream = async (item, opts) => {
247
+ if (Buffer.isBuffer(item)) {
248
+ return { stream: toReadable(item), type: "buffer" };
249
+ }
250
+ if ("stream" in item) {
251
+ return { stream: item.stream, type: "readable" };
252
+ }
253
+ const urlStr = item.url.toString();
254
+ if (urlStr.startsWith("data:")) {
255
+ const buffer = Buffer.from(urlStr.split(",")[1], "base64");
256
+ return { stream: await toReadable(buffer), type: "buffer" };
257
+ }
258
+ if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) {
259
+ return { stream: await getHttpStream(item.url, opts), type: "remote" };
260
+ }
261
+ return { stream: createReadStream(item.url), type: "file" };
262
+ };
263
+ async function generateThumbnail(file, mediaType, options) {
264
+ let thumbnail;
265
+ let originalImageDimensions;
266
+ if (mediaType === "image") {
267
+ const { buffer: buffer, original: original } = await extractImageThumb(file);
268
+ thumbnail = buffer.toString("base64");
269
+ if (original.width && original.height) {
270
+ originalImageDimensions = {
271
+ width: original.width,
272
+ height: original.height,
273
+ };
274
+ }
275
+ } else if (mediaType === "video") {
276
+ const imgFilename = join(getTmpFilesDirectory(), generateMessageID() + ".jpg");
277
+ try {
278
+ await extractVideoThumb(file, imgFilename, "00:00:00", {
279
+ width: 32,
280
+ height: 32,
281
+ });
282
+ const buff = await promises.readFile(imgFilename);
283
+ thumbnail = buff.toString("base64");
284
+ await promises.unlink(imgFilename);
285
+ } catch (err) {
286
+ options.logger?.debug("could not generate video thumb: " + err);
287
+ }
288
+ }
289
+ return {
290
+ thumbnail: thumbnail,
291
+ originalImageDimensions: originalImageDimensions,
292
+ };
293
+ }
294
+ const getHttpStream = async (url, options = {}) => {
295
+ const response = await fetch(url.toString(), {
296
+ dispatcher: options.dispatcher,
297
+ method: "GET",
298
+ headers: options.headers,
299
+ });
300
+ if (!response.ok) {
301
+ throw new Boom(`Failed to fetch stream from ${url}`, {
302
+ statusCode: response.status,
303
+ data: { url: url },
304
+ });
305
+ }
306
+ return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
307
+ };
308
+ const encryptedStream = async (
309
+ media,
310
+ mediaType,
311
+ { logger: logger, saveOriginalFileIfRequired: saveOriginalFileIfRequired, opts: opts } = {}
312
+ ) => {
313
+ const { stream: stream, type: type } = await getStream(media, opts);
314
+ logger?.debug("fetched media stream");
315
+ const mediaKey = randomBytes(32);
316
+ const {
317
+ cipherKey: cipherKey,
318
+ iv: iv,
319
+ macKey: macKey,
320
+ } = await getMediaKeys(mediaKey, mediaType);
321
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageID() + "-enc");
322
+ const encFileWriteStream = createWriteStream(encFilePath);
323
+ let originalFileStream;
324
+ let originalFilePath;
325
+ if (saveOriginalFileIfRequired) {
326
+ originalFilePath = join(
327
+ getTmpFilesDirectory(),
328
+ mediaType + generateMessageID() + "-original"
329
+ );
330
+ originalFileStream = createWriteStream(originalFilePath);
331
+ }
332
+ let fileLength = 0;
333
+ const aes = createCipheriv("aes-256-cbc", cipherKey, iv);
334
+ const hmac = createHmac("sha256", macKey).update(iv);
335
+ const sha256Plain = createHash("sha256");
336
+ const sha256Enc = createHash("sha256");
337
+ const onChunk = async (buff) => {
338
+ sha256Enc.update(buff);
339
+ hmac.update(buff);
340
+ if (!encFileWriteStream.write(buff)) {
341
+ await once(encFileWriteStream, "drain");
342
+ }
343
+ };
344
+ try {
345
+ for await (const data of stream) {
346
+ fileLength += data.length;
347
+ if (
348
+ type === "remote" &&
349
+ opts?.maxContentLength &&
350
+ fileLength + data.length > opts.maxContentLength
351
+ ) {
352
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
353
+ data: { media: media, type: type },
354
+ });
355
+ }
356
+ if (originalFileStream) {
357
+ if (!originalFileStream.write(data)) {
358
+ await once(originalFileStream, "drain");
359
+ }
360
+ }
361
+ sha256Plain.update(data);
362
+ await onChunk(aes.update(data));
363
+ }
364
+ await onChunk(aes.final());
365
+ const mac = hmac.digest().slice(0, 10);
366
+ sha256Enc.update(mac);
367
+ const fileSha256 = sha256Plain.digest();
368
+ const fileEncSha256 = sha256Enc.digest();
369
+ encFileWriteStream.write(mac);
370
+ const encFinishPromise = once(encFileWriteStream, "finish");
371
+ const originalFinishPromise = originalFileStream
372
+ ? once(originalFileStream, "finish")
373
+ : Promise.resolve();
374
+ encFileWriteStream.end();
375
+ originalFileStream?.end?.();
376
+ stream.destroy();
377
+ await encFinishPromise;
378
+ await originalFinishPromise;
379
+ logger?.debug("encrypted data successfully");
380
+ return {
381
+ mediaKey: mediaKey,
382
+ originalFilePath: originalFilePath,
383
+ encFilePath: encFilePath,
384
+ mac: mac,
385
+ fileEncSha256: fileEncSha256,
386
+ fileSha256: fileSha256,
387
+ fileLength: fileLength,
388
+ };
389
+ } catch (error) {
390
+ encFileWriteStream.destroy();
391
+ originalFileStream?.destroy?.();
392
+ aes.destroy();
393
+ hmac.destroy();
394
+ sha256Plain.destroy();
395
+ sha256Enc.destroy();
396
+ stream.destroy();
397
+ try {
398
+ await promises.unlink(encFilePath);
399
+ if (originalFilePath) {
400
+ await promises.unlink(originalFilePath);
401
+ }
402
+ } catch (err) {
403
+ logger?.error({ err: err }, "failed deleting tmp files");
404
+ }
405
+ throw error;
406
+ }
407
+ };
408
+ const DEF_HOST = "mmg.whatsapp.net";
409
+ const AES_CHUNK_SIZE = 16;
410
+ const toSmallestChunkSize = (num) => Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
411
+ const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
412
+ const downloadContentFromMessage = async (
413
+ { mediaKey: mediaKey, directPath: directPath, url: url },
414
+ type,
415
+ opts = {}
416
+ ) => {
417
+ const isValidMediaUrl = url?.startsWith("https://mmg.whatsapp.net/");
418
+ const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath);
419
+ if (!downloadUrl) {
420
+ throw new Boom("No valid media URL or directPath present in message", {
421
+ statusCode: 400,
422
+ });
423
+ }
424
+ const keys = await getMediaKeys(mediaKey, type);
425
+ return downloadEncryptedContent(downloadUrl, keys, opts);
426
+ };
427
+ const downloadEncryptedContent = async (
428
+ downloadUrl,
429
+ { cipherKey: cipherKey, iv: iv },
430
+ { startByte: startByte, endByte: endByte, options: options } = {}
431
+ ) => {
432
+ let bytesFetched = 0;
433
+ let startChunk = 0;
434
+ let firstBlockIsIV = false;
435
+ if (startByte) {
436
+ const chunk = toSmallestChunkSize(startByte || 0);
437
+ if (chunk) {
438
+ startChunk = chunk - AES_CHUNK_SIZE;
439
+ bytesFetched = chunk;
440
+ firstBlockIsIV = true;
441
+ }
442
+ }
443
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
444
+ const headersInit = options?.headers ? options.headers : undefined;
445
+ const headers = {
446
+ ...(headersInit
447
+ ? Array.isArray(headersInit)
448
+ ? Object.fromEntries(headersInit)
449
+ : headersInit
450
+ : {}),
451
+ Origin: DEFAULT_ORIGIN,
452
+ };
453
+ if (startChunk || endChunk) {
454
+ headers.Range = `bytes=${startChunk}-`;
455
+ if (endChunk) {
456
+ headers.Range += endChunk;
457
+ }
458
+ }
459
+ const fetched = await getHttpStream(downloadUrl, {
460
+ ...(options || {}),
461
+ headers: headers,
462
+ });
463
+ let remainingBytes = Buffer.from([]);
464
+ let aes;
465
+ const pushBytes = (bytes, push) => {
466
+ if (startByte || endByte) {
467
+ const start =
468
+ bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
469
+ const end =
470
+ bytesFetched + bytes.length < endByte
471
+ ? undefined
472
+ : Math.max(endByte - bytesFetched, 0);
473
+ push(bytes.slice(start, end));
474
+ bytesFetched += bytes.length;
475
+ } else {
476
+ push(bytes);
477
+ }
478
+ };
479
+ const output = new Transform({
480
+ transform(chunk, _, callback) {
481
+ let data = Buffer.concat([remainingBytes, chunk]);
482
+ const decryptLength = toSmallestChunkSize(data.length);
483
+ remainingBytes = data.slice(decryptLength);
484
+ data = data.slice(0, decryptLength);
485
+ if (!aes) {
486
+ let ivValue = iv;
487
+ if (firstBlockIsIV) {
488
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
489
+ data = data.slice(AES_CHUNK_SIZE);
490
+ }
491
+ aes = createDecipheriv("aes-256-cbc", cipherKey, ivValue);
492
+ if (endByte) {
493
+ aes.setAutoPadding(false);
494
+ }
495
+ }
496
+ try {
497
+ pushBytes(aes.update(data), (b) => this.push(b));
498
+ callback();
499
+ } catch (error) {
500
+ callback(error);
501
+ }
502
+ },
503
+ final(callback) {
504
+ try {
505
+ pushBytes(aes.final(), (b) => this.push(b));
506
+ callback();
507
+ } catch (error) {
508
+ callback(error);
509
+ }
510
+ },
511
+ });
512
+ return fetched.pipe(output, { end: true });
513
+ };
514
+ function extensionForMediaMessage(message) {
515
+ const getExtension = (mimetype) => mimetype.split("")[0].split("/")[1];
516
+ const type = Object.keys(message)[0];
517
+ let extension;
518
+ if (type === "locationMessage" || type === "liveLocationMessage" || type === "productMessage") {
519
+ extension = ".jpeg";
520
+ } else {
521
+ const messageContent = message[type];
522
+ extension = getExtension(messageContent.mimetype);
523
+ }
524
+ return extension;
525
+ }
526
+ const isNodeRuntime = () =>
527
+ typeof process !== "undefined" &&
528
+ process.versions?.node !== null &&
529
+ typeof process.versions.bun === "undefined" &&
530
+ typeof globalThis.Deno === "undefined";
531
+ const uploadWithNodeHttp = async (
532
+ { url: url, filePath: filePath, headers: headers, timeoutMs: timeoutMs, agent: agent },
533
+ redirectCount = 0
534
+ ) => {
535
+ if (redirectCount > 5) {
536
+ throw new Error("Too many redirects");
537
+ }
538
+ const parsedUrl = new URL(url);
539
+ const httpModule = parsedUrl.protocol === "https:" ? require("https") : require("http");
540
+ const fileStats = await promises.stat(filePath);
541
+ const fileSize = fileStats.size;
542
+ return new Promise((resolve, reject) => {
543
+ const req = httpModule.request(
544
+ {
545
+ hostname: parsedUrl.hostname,
546
+ port: parsedUrl.port || (parsedUrl.protocol === "https:" ? 443 : 80),
547
+ path: parsedUrl.pathname + parsedUrl.search,
548
+ method: "POST",
549
+ headers: { ...headers, "Content-Length": fileSize },
550
+ agent: agent,
551
+ timeout: timeoutMs,
552
+ },
553
+ (res) => {
554
+ if (
555
+ res.statusCode &&
556
+ res.statusCode >= 300 &&
557
+ res.statusCode < 400 &&
558
+ res.headers.location
559
+ ) {
560
+ res.resume();
561
+ const newUrl = new URL(res.headers.location, url).toString();
562
+ resolve(
563
+ uploadWithNodeHttp(
564
+ {
565
+ url: newUrl,
566
+ filePath: filePath,
567
+ headers: headers,
568
+ timeoutMs: timeoutMs,
569
+ agent: agent,
570
+ },
571
+ redirectCount + 1
572
+ )
573
+ );
574
+ return;
575
+ }
576
+ let body = "";
577
+ res.on("data", (chunk) => (body += chunk));
578
+ res.on("end", () => {
579
+ try {
580
+ resolve(JSON.parse(body));
581
+ } catch {
582
+ resolve(undefined);
583
+ }
584
+ });
585
+ }
586
+ );
587
+ req.on("error", reject);
588
+ req.on("timeout", () => {
589
+ req.destroy();
590
+ reject(new Error("Upload timeout"));
591
+ });
592
+ const stream = createReadStream(filePath);
593
+ stream.pipe(req);
594
+ stream.on("error", (err) => {
595
+ req.destroy();
596
+ reject(err);
597
+ });
598
+ });
599
+ };
600
+ const uploadWithFetch = async ({
601
+ url: url,
602
+ filePath: filePath,
603
+ headers: headers,
604
+ timeoutMs: timeoutMs,
605
+ agent: agent,
606
+ }) => {
607
+ const nodeStream = createReadStream(filePath);
608
+ const webStream = Readable.toWeb(nodeStream);
609
+ const response = await fetch(url, {
610
+ dispatcher: agent,
611
+ method: "POST",
612
+ body: webStream,
613
+ headers: headers,
614
+ duplex: "half",
615
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined,
616
+ });
617
+ try {
618
+ return await response.json();
619
+ } catch {
620
+ return undefined;
621
+ }
622
+ };
623
+ const uploadMedia = async (params, logger) => {
624
+ if (isNodeRuntime()) {
625
+ logger?.debug("Using Node.js https module for upload (avoids undici buffering bug)");
626
+ return uploadWithNodeHttp(params);
627
+ } else {
628
+ logger?.debug("Using web-standard Fetch API for upload");
629
+ return uploadWithFetch(params);
630
+ }
631
+ };
632
+ const getWAUploadToServer =
633
+ (
634
+ {
635
+ customUploadHosts: customUploadHosts,
636
+ fetchAgent: fetchAgent,
637
+ logger: logger,
638
+ options: options,
639
+ },
640
+ refreshMediaConn
641
+ ) =>
642
+ async (
643
+ filePath,
644
+ { mediaType: mediaType, fileEncSha256B64: fileEncSha256B64, timeoutMs: timeoutMs }
645
+ ) => {
646
+ let uploadInfo = await refreshMediaConn(false);
647
+ let urls;
648
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
649
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
650
+ const customHeaders = (() => {
651
+ const hdrs = options?.headers;
652
+ if (!hdrs) return {};
653
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
654
+ })();
655
+ const headers = {
656
+ ...customHeaders,
657
+ "Content-Type": "application/octet-stream",
658
+ Origin: DEFAULT_ORIGIN,
659
+ };
660
+ for (const { hostname: hostname } of hosts) {
661
+ logger.debug(`uploading to "${hostname}"`);
662
+ const auth = encodeURIComponent(uploadInfo.auth);
663
+ const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
664
+ let result;
665
+ try {
666
+ result = await uploadMedia(
667
+ {
668
+ url: url,
669
+ filePath: filePath,
670
+ headers: headers,
671
+ timeoutMs: timeoutMs,
672
+ agent: fetchAgent,
673
+ },
674
+ logger
675
+ );
676
+ if (result?.url || result?.direct_path) {
677
+ urls = {
678
+ mediaUrl: result.url,
679
+ directPath: result.direct_path,
680
+ meta_hmac: result.meta_hmac,
681
+ fbid: result.fbid,
682
+ ts: result.ts,
683
+ };
684
+ break;
685
+ } else {
686
+ uploadInfo = await refreshMediaConn(true);
687
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
688
+ }
689
+ } catch (error) {
690
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
691
+ logger.warn(
692
+ { trace: error?.stack, uploadResult: result },
693
+ `Error in uploading to ${hostname} ${isLast ? "" : ", retrying..."}`
694
+ );
695
+ }
696
+ }
697
+ if (!urls) {
698
+ throw new Boom("Media upload failed on all hosts", { statusCode: 500 });
699
+ }
700
+ return urls;
701
+ };
702
+ const getMediaRetryKey = (mediaKey) =>
703
+ hkdf(mediaKey, 32, { info: "WhatsApp Media Retry Notification" });
704
+ const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
705
+ const recp = { stanzaId: key.id };
706
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
707
+ const iv = randomBytes(12);
708
+ const retryKey = await getMediaRetryKey(mediaKey);
709
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
710
+ const req = {
711
+ tag: "receipt",
712
+ attrs: { id: key.id, to: jidNormalizedUser(meId), type: "server-error" },
713
+ content: [
714
+ {
715
+ tag: "encrypt",
716
+ attrs: {},
717
+ content: [
718
+ { tag: "enc_p", attrs: {}, content: ciphertext },
719
+ { tag: "enc_iv", attrs: {}, content: iv },
720
+ ],
721
+ },
722
+ {
723
+ tag: "rmr",
724
+ attrs: {
725
+ jid: key.remoteJid,
726
+ from_me: (!!key.fromMe).toString(),
727
+ participant: key.participant || undefined,
728
+ },
729
+ },
730
+ ],
731
+ };
732
+ return req;
733
+ };
734
+ const decodeMediaRetryNode = (node) => {
735
+ const rmrNode = getBinaryNodeChild(node, "rmr");
736
+ const event = {
737
+ key: {
738
+ id: node.attrs.id,
739
+ remoteJid: rmrNode.attrs.jid,
740
+ fromMe: rmrNode.attrs.from_me === "true",
741
+ participant: rmrNode.attrs.participant,
742
+ },
743
+ };
744
+ const errorNode = getBinaryNodeChild(node, "error");
745
+ if (errorNode) {
746
+ const errorCode = +errorNode.attrs.code;
747
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
748
+ data: errorNode.attrs,
749
+ statusCode: getStatusCodeForMediaRetry(errorCode),
750
+ });
751
+ } else {
752
+ const encryptedInfoNode = getBinaryNodeChild(node, "encrypt");
753
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, "enc_p");
754
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, "enc_iv");
755
+ if (ciphertext && iv) {
756
+ event.media = { ciphertext: ciphertext, iv: iv };
757
+ } else {
758
+ event.error = new Boom("Failed to re-upload media (missing ciphertext)", {
759
+ statusCode: 404,
760
+ });
761
+ }
762
+ }
763
+ return event;
764
+ };
765
+ const decryptMediaRetryData = async ({ ciphertext: ciphertext, iv: iv }, mediaKey, msgId) => {
766
+ const retryKey = await getMediaRetryKey(mediaKey);
767
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
768
+ return proto.MediaRetryNotification.decode(plaintext);
769
+ };
770
+ const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
771
+ const MEDIA_RETRY_STATUS_MAP = {
772
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
773
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
774
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
775
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418,
776
+ };
777
+ module.exports = {
778
+ hkdfInfoKey: hkdfInfoKey,
779
+ getMediaKeys: getMediaKeys,
780
+ extractVideoThumb: extractVideoThumb,
781
+ extractImageThumb: extractImageThumb,
782
+ encodeBase64EncodedStringForUpload: encodeBase64EncodedStringForUpload,
783
+ generateProfilePicture: generateProfilePicture,
784
+ mediaMessageSHA256B64: mediaMessageSHA256B64,
785
+ getAudioDuration: getAudioDuration,
786
+ getAudioWaveform: getAudioWaveform,
787
+ toReadable: toReadable,
788
+ toBuffer: toBuffer,
789
+ getStream: getStream,
790
+ generateThumbnail: generateThumbnail,
791
+ getHttpStream: getHttpStream,
792
+ encryptedStream: encryptedStream,
793
+ getUrlFromDirectPath: getUrlFromDirectPath,
794
+ downloadContentFromMessage: downloadContentFromMessage,
795
+ downloadEncryptedContent: downloadEncryptedContent,
796
+ extensionForMediaMessage: extensionForMediaMessage,
797
+ uploadWithNodeHttp: uploadWithNodeHttp,
798
+ getRawMediaUploadData: getRawMediaUploadData,
799
+ getWAUploadToServer: getWAUploadToServer,
800
+ getMediaRetryKey: getMediaRetryKey,
801
+ encryptMediaRetryRequest: encryptMediaRetryRequest,
802
+ decodeMediaRetryNode: decodeMediaRetryNode,
803
+ decryptMediaRetryData: decryptMediaRetryData,
804
+ getStatusCodeForMediaRetry: getStatusCodeForMediaRetry,
805
+ MEDIA_RETRY_STATUS_MAP: MEDIA_RETRY_STATUS_MAP,
806
+ };