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