@vanzxysenpai/baileys 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (431) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +25 -0
  3. package/NOTICE.md +158 -0
  4. package/README.md +5294 -2
  5. package/VanzxyBanner.js +134 -0
  6. package/WAProto/index.d.ts +13317 -0
  7. package/WAProto/index.js +147553 -0
  8. package/lib/Builders/A2UI.d.ts +131 -0
  9. package/lib/Builders/A2UI.js +343 -0
  10. package/lib/Builders/AIRich.d.ts +1021 -0
  11. package/lib/Builders/AIRich.js +2889 -0
  12. package/lib/Builders/Album.d.ts +51 -0
  13. package/lib/Builders/Album.js +99 -0
  14. package/lib/Builders/Button.d.ts +137449 -0
  15. package/lib/Builders/Button.js +1054 -0
  16. package/lib/Builders/ButtonV2.d.ts +43 -0
  17. package/lib/Builders/ButtonV2.js +175 -0
  18. package/lib/Builders/ButtonV3.d.ts +35 -0
  19. package/lib/Builders/ButtonV3.js +189 -0
  20. package/lib/Builders/Carousel.d.ts +68 -0
  21. package/lib/Builders/Carousel.js +161 -0
  22. package/lib/Builders/Event.d.ts +61 -0
  23. package/lib/Builders/Event.js +118 -0
  24. package/lib/Builders/Expiring.d.ts +17 -0
  25. package/lib/Builders/Expiring.js +27 -0
  26. package/lib/Builders/Poll.d.ts +63 -0
  27. package/lib/Builders/Poll.js +139 -0
  28. package/lib/Builders/VanzxyBaileys.d.ts +42 -0
  29. package/lib/Builders/VanzxyBaileys.js +110 -0
  30. package/lib/Builders/errors.d.ts +25 -0
  31. package/lib/Builders/errors.js +29 -0
  32. package/lib/Builders/index.d.ts +14 -0
  33. package/lib/Builders/index.js +23 -0
  34. package/lib/Builders/shared.d.ts +395 -0
  35. package/lib/Builders/shared.js +738 -0
  36. package/lib/Defaults/bot-jid.d.ts +1 -0
  37. package/lib/Defaults/bot-jid.js +1 -0
  38. package/lib/Defaults/index.d.ts +161 -0
  39. package/lib/Defaults/index.js +165 -0
  40. package/lib/Defaults/version.d.ts +1 -0
  41. package/lib/Defaults/version.js +1 -0
  42. package/lib/Framework/Bot.d.ts +865 -0
  43. package/lib/Framework/Bot.js +230 -0
  44. package/lib/Framework/Context.d.ts +17 -0
  45. package/lib/Framework/Context.js +90 -0
  46. package/lib/Framework/MediaManager.d.ts +15 -0
  47. package/lib/Framework/MediaManager.js +154 -0
  48. package/lib/Framework/SessionManager.d.ts +10 -0
  49. package/lib/Framework/SessionManager.js +34 -0
  50. package/lib/Framework/StatsManager.d.ts +20 -0
  51. package/lib/Framework/StatsManager.js +117 -0
  52. package/lib/Framework/Store/SQLiteStore.d.ts +13 -0
  53. package/lib/Framework/Store/SQLiteStore.js +68 -0
  54. package/lib/Framework/index.d.ts +6 -0
  55. package/lib/Framework/index.js +11 -0
  56. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  57. package/lib/Signal/Group/ciphertext-message.js +11 -0
  58. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  59. package/lib/Signal/Group/group-session-builder.js +29 -0
  60. package/lib/Signal/Group/group_cipher.d.ts +10 -0
  61. package/lib/Signal/Group/group_cipher.js +81 -0
  62. package/lib/Signal/Group/index.d.ts +11 -0
  63. package/lib/Signal/Group/index.js +11 -0
  64. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  65. package/lib/Signal/Group/keyhelper.js +17 -0
  66. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  67. package/lib/Signal/Group/sender-chain-key.js +25 -0
  68. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  69. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  70. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  71. package/lib/Signal/Group/sender-key-message.js +65 -0
  72. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  73. package/lib/Signal/Group/sender-key-name.js +47 -0
  74. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  75. package/lib/Signal/Group/sender-key-record.js +40 -0
  76. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  77. package/lib/Signal/Group/sender-key-state.js +83 -0
  78. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  79. package/lib/Signal/Group/sender-message-key.js +25 -0
  80. package/lib/Signal/libsignal.d.ts +58 -0
  81. package/lib/Signal/libsignal.js +436 -0
  82. package/lib/Signal/lid-mapping.d.ts +20 -0
  83. package/lib/Signal/lid-mapping.js +276 -0
  84. package/lib/Socket/Client/index.d.ts +2 -0
  85. package/lib/Socket/Client/index.js +2 -0
  86. package/lib/Socket/Client/types.d.ts +5 -0
  87. package/lib/Socket/Client/types.js +10 -0
  88. package/lib/Socket/Client/websocket.d.ts +12 -0
  89. package/lib/Socket/Client/websocket.js +53 -0
  90. package/lib/Socket/business.d.ts +674 -0
  91. package/lib/Socket/business.js +379 -0
  92. package/lib/Socket/chats.d.ts +137 -0
  93. package/lib/Socket/chats.js +1299 -0
  94. package/lib/Socket/communities.d.ts +805 -0
  95. package/lib/Socket/communities.js +454 -0
  96. package/lib/Socket/dugong.d.ts +118 -0
  97. package/lib/Socket/dugong.js +810 -0
  98. package/lib/Socket/groups.d.ts +287 -0
  99. package/lib/Socket/groups.js +386 -0
  100. package/lib/Socket/index.d.ts +826 -0
  101. package/lib/Socket/index.js +35 -0
  102. package/lib/Socket/messages-recv.d.ts +613 -0
  103. package/lib/Socket/messages-recv.js +1851 -0
  104. package/lib/Socket/messages-send.d.ts +608 -0
  105. package/lib/Socket/messages-send.js +1574 -0
  106. package/lib/Socket/mex-fallback.d.ts +51 -0
  107. package/lib/Socket/mex-fallback.js +97 -0
  108. package/lib/Socket/mex.d.ts +1 -0
  109. package/lib/Socket/mex.js +41 -0
  110. package/lib/Socket/newsletter-ext.d.ts +47 -0
  111. package/lib/Socket/newsletter-ext.js +262 -0
  112. package/lib/Socket/newsletter.d.ts +285 -0
  113. package/lib/Socket/newsletter.js +223 -0
  114. package/lib/Socket/socket.d.ts +60 -0
  115. package/lib/Socket/socket.js +1001 -0
  116. package/lib/Socket/username.d.ts +842 -0
  117. package/lib/Socket/username.js +156 -0
  118. package/lib/Store/index.d.ts +3 -0
  119. package/lib/Store/index.js +3 -0
  120. package/lib/Store/make-in-memory-store.d.ts +62 -0
  121. package/lib/Store/make-in-memory-store.js +425 -0
  122. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  123. package/lib/Store/make-ordered-dictionary.js +78 -0
  124. package/lib/Store/object-repository.d.ts +10 -0
  125. package/lib/Store/object-repository.js +23 -0
  126. package/lib/Types/Auth.d.ts +1 -0
  127. package/lib/Types/Auth.js +1 -0
  128. package/lib/Types/Bussines.d.ts +1 -0
  129. package/lib/Types/Bussines.js +1 -0
  130. package/lib/Types/Call.d.ts +1 -0
  131. package/lib/Types/Call.js +1 -0
  132. package/lib/Types/Chat.d.ts +1 -0
  133. package/lib/Types/Chat.js +7 -0
  134. package/lib/Types/Contact.d.ts +1 -0
  135. package/lib/Types/Contact.js +1 -0
  136. package/lib/Types/Events.d.ts +1 -0
  137. package/lib/Types/Events.js +1 -0
  138. package/lib/Types/GroupMetadata.d.ts +1 -0
  139. package/lib/Types/GroupMetadata.js +1 -0
  140. package/lib/Types/Label.d.ts +2 -0
  141. package/lib/Types/Label.js +24 -0
  142. package/lib/Types/LabelAssociation.d.ts +2 -0
  143. package/lib/Types/LabelAssociation.js +6 -0
  144. package/lib/Types/Message.d.ts +11 -0
  145. package/lib/Types/Message.js +17 -0
  146. package/lib/Types/Mex.d.ts +2 -0
  147. package/lib/Types/Mex.js +38 -0
  148. package/lib/Types/Product.d.ts +1 -0
  149. package/lib/Types/Product.js +1 -0
  150. package/lib/Types/RichType.d.ts +2 -0
  151. package/lib/Types/RichType.js +22 -0
  152. package/lib/Types/Signal.d.ts +1 -0
  153. package/lib/Types/Signal.js +1 -0
  154. package/lib/Types/Socket.d.ts +1 -0
  155. package/lib/Types/Socket.js +1 -0
  156. package/lib/Types/State.d.ts +5 -0
  157. package/lib/Types/State.js +55 -0
  158. package/lib/Types/USync.d.ts +1 -0
  159. package/lib/Types/USync.js +1 -0
  160. package/lib/Types/index.d.ts +15 -0
  161. package/lib/Types/index.js +27 -0
  162. package/lib/Utils/PersistentStore.d.ts +83 -0
  163. package/lib/Utils/PersistentStore.js +592 -0
  164. package/lib/Utils/anchor-guard.d.ts +31 -0
  165. package/lib/Utils/anchor-guard.js +329 -0
  166. package/lib/Utils/android-stanza-id.d.ts +4 -0
  167. package/lib/Utils/android-stanza-id.js +21 -0
  168. package/lib/Utils/anti-delete.d.ts +62 -0
  169. package/lib/Utils/anti-delete.js +212 -0
  170. package/lib/Utils/auth-secure.d.ts +180 -0
  171. package/lib/Utils/auth-secure.js +791 -0
  172. package/lib/Utils/auth-utils.d.ts +59 -0
  173. package/lib/Utils/auth-utils.js +326 -0
  174. package/lib/Utils/auto-reconnect.d.ts +8 -0
  175. package/lib/Utils/auto-reconnect.js +204 -0
  176. package/lib/Utils/auto-reply.d.ts +35 -0
  177. package/lib/Utils/auto-reply.js +152 -0
  178. package/lib/Utils/bad-mac-handler.d.ts +59 -0
  179. package/lib/Utils/bad-mac-handler.js +119 -0
  180. package/lib/Utils/baileys-event-stream.d.ts +5 -0
  181. package/lib/Utils/baileys-event-stream.js +62 -0
  182. package/lib/Utils/browser-utils.d.ts +9 -0
  183. package/lib/Utils/browser-utils.js +29 -0
  184. package/lib/Utils/business.d.ts +49 -0
  185. package/lib/Utils/business.js +236 -0
  186. package/lib/Utils/button-helper-utils.d.ts +59 -0
  187. package/lib/Utils/button-helper-utils.js +266 -0
  188. package/lib/Utils/button-sender.d.ts +164 -0
  189. package/lib/Utils/button-sender.js +845 -0
  190. package/lib/Utils/chat-control.d.ts +98 -0
  191. package/lib/Utils/chat-control.js +231 -0
  192. package/lib/Utils/chat-history-helpers.d.ts +4 -0
  193. package/lib/Utils/chat-history-helpers.js +70 -0
  194. package/lib/Utils/chat-utils.d.ts +408 -0
  195. package/lib/Utils/chat-utils.js +879 -0
  196. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  197. package/lib/Utils/companion-reg-client-utils.js +39 -0
  198. package/lib/Utils/connection-watchdog.d.ts +10 -0
  199. package/lib/Utils/connection-watchdog.js +74 -0
  200. package/lib/Utils/crypto.d.ts +41 -0
  201. package/lib/Utils/crypto.js +145 -0
  202. package/lib/Utils/decode-wa-message.d.ts +83 -0
  203. package/lib/Utils/decode-wa-message.js +315 -0
  204. package/lib/Utils/disconnect-reason.d.ts +13 -0
  205. package/lib/Utils/disconnect-reason.js +36 -0
  206. package/lib/Utils/event-buffer.d.ts +12 -0
  207. package/lib/Utils/event-buffer.js +640 -0
  208. package/lib/Utils/fetch-timeout.d.ts +4 -0
  209. package/lib/Utils/fetch-timeout.js +14 -0
  210. package/lib/Utils/ffmpeg-path.d.ts +5 -0
  211. package/lib/Utils/ffmpeg-path.js +130 -0
  212. package/lib/Utils/generics.d.ts +79 -0
  213. package/lib/Utils/generics.js +426 -0
  214. package/lib/Utils/group-metadata-cache.d.ts +3 -0
  215. package/lib/Utils/group-metadata-cache.js +25 -0
  216. package/lib/Utils/group-status-detection.d.ts +5 -0
  217. package/lib/Utils/group-status-detection.js +114 -0
  218. package/lib/Utils/history.d.ts +91 -0
  219. package/lib/Utils/history.js +144 -0
  220. package/lib/Utils/html-app.d.ts +14 -0
  221. package/lib/Utils/html-app.js +97 -0
  222. package/lib/Utils/html-multiplayer.d.ts +8 -0
  223. package/lib/Utils/html-multiplayer.js +90 -0
  224. package/lib/Utils/humanizer.d.ts +8 -0
  225. package/lib/Utils/humanizer.js +74 -0
  226. package/lib/Utils/identity-change-handler.d.ts +13 -0
  227. package/lib/Utils/identity-change-handler.js +49 -0
  228. package/lib/Utils/index.d.ts +88 -0
  229. package/lib/Utils/index.js +93 -0
  230. package/lib/Utils/jid-tools.d.ts +3 -0
  231. package/lib/Utils/jid-tools.js +78 -0
  232. package/lib/Utils/link-preview-metadata.d.ts +47 -0
  233. package/lib/Utils/link-preview-metadata.js +90 -0
  234. package/lib/Utils/link-preview.d.ts +12 -0
  235. package/lib/Utils/link-preview.js +84 -0
  236. package/lib/Utils/lock-manager.d.ts +5 -0
  237. package/lib/Utils/lock-manager.js +50 -0
  238. package/lib/Utils/logger.d.ts +2 -0
  239. package/lib/Utils/logger.js +2 -0
  240. package/lib/Utils/lt-hash.d.ts +12 -0
  241. package/lib/Utils/lt-hash.js +26 -0
  242. package/lib/Utils/make-mutex.d.ts +6 -0
  243. package/lib/Utils/make-mutex.js +32 -0
  244. package/lib/Utils/media-messages.d.ts +35 -0
  245. package/lib/Utils/media-messages.js +70 -0
  246. package/lib/Utils/media-processor.d.ts +6 -0
  247. package/lib/Utils/media-processor.js +174 -0
  248. package/lib/Utils/media-set.d.ts +6 -0
  249. package/lib/Utils/media-set.js +169 -0
  250. package/lib/Utils/message-kind.d.ts +26 -0
  251. package/lib/Utils/message-kind.js +138 -0
  252. package/lib/Utils/message-retry-manager.d.ts +79 -0
  253. package/lib/Utils/message-retry-manager.js +264 -0
  254. package/lib/Utils/message-search.d.ts +40 -0
  255. package/lib/Utils/message-search.js +181 -0
  256. package/lib/Utils/messages-media.d.ts +136 -0
  257. package/lib/Utils/messages-media.js +867 -0
  258. package/lib/Utils/messages.d.ts +66 -0
  259. package/lib/Utils/messages.js +2271 -0
  260. package/lib/Utils/meta-ai-msmsg.d.ts +3 -0
  261. package/lib/Utils/meta-ai-msmsg.js +132 -0
  262. package/lib/Utils/meta-ai.d.ts +4 -0
  263. package/lib/Utils/meta-ai.js +75 -0
  264. package/lib/Utils/migrate-auth-state.d.ts +23 -0
  265. package/lib/Utils/migrate-auth-state.js +126 -0
  266. package/lib/Utils/mini-app.d.ts +20 -0
  267. package/lib/Utils/mini-app.js +215 -0
  268. package/lib/Utils/mock-socket.d.ts +67 -0
  269. package/lib/Utils/mock-socket.js +254 -0
  270. package/lib/Utils/modern-messages.d.ts +64 -0
  271. package/lib/Utils/modern-messages.js +497 -0
  272. package/lib/Utils/native-flow.d.ts +19 -0
  273. package/lib/Utils/native-flow.js +112 -0
  274. package/lib/Utils/newsletter-status.d.ts +157 -0
  275. package/lib/Utils/newsletter-status.js +652 -0
  276. package/lib/Utils/noise-handler.d.ts +20 -0
  277. package/lib/Utils/noise-handler.js +200 -0
  278. package/lib/Utils/offline-node-processor.d.ts +9 -0
  279. package/lib/Utils/offline-node-processor.js +39 -0
  280. package/lib/Utils/pairing-utils.d.ts +5 -0
  281. package/lib/Utils/pairing-utils.js +29 -0
  282. package/lib/Utils/passkey.d.ts +4 -0
  283. package/lib/Utils/passkey.js +11 -0
  284. package/lib/Utils/past-participants.d.ts +2 -0
  285. package/lib/Utils/past-participants.js +40 -0
  286. package/lib/Utils/payment-detection.d.ts +40 -0
  287. package/lib/Utils/payment-detection.js +213 -0
  288. package/lib/Utils/payment-guard.d.ts +28 -0
  289. package/lib/Utils/payment-guard.js +143 -0
  290. package/lib/Utils/payment-messages.d.ts +42 -0
  291. package/lib/Utils/payment-messages.js +161 -0
  292. package/lib/Utils/payment-utils.d.ts +75 -0
  293. package/lib/Utils/payment-utils.js +145 -0
  294. package/lib/Utils/phone-utils.d.ts +3 -0
  295. package/lib/Utils/phone-utils.js +29 -0
  296. package/lib/Utils/pre-key-manager.d.ts +25 -0
  297. package/lib/Utils/pre-key-manager.js +105 -0
  298. package/lib/Utils/process-message.d.ts +103 -0
  299. package/lib/Utils/process-message.js +868 -0
  300. package/lib/Utils/qr-terminal.d.ts +1 -0
  301. package/lib/Utils/qr-terminal.js +16 -0
  302. package/lib/Utils/reconnect-backoff.d.ts +25 -0
  303. package/lib/Utils/reconnect-backoff.js +47 -0
  304. package/lib/Utils/reporting-utils.d.ts +12 -0
  305. package/lib/Utils/reporting-utils.js +257 -0
  306. package/lib/Utils/rich-message-utils.d.ts +54 -0
  307. package/lib/Utils/rich-message-utils.js +435 -0
  308. package/lib/Utils/rich-messages.d.ts +298 -0
  309. package/lib/Utils/rich-messages.js +1145 -0
  310. package/lib/Utils/scheduled-message.d.ts +81 -0
  311. package/lib/Utils/scheduled-message.js +101 -0
  312. package/lib/Utils/scheduling.d.ts +59 -0
  313. package/lib/Utils/scheduling.js +139 -0
  314. package/lib/Utils/signal.d.ts +82 -0
  315. package/lib/Utils/signal.js +200 -0
  316. package/lib/Utils/stanza-ack.d.ts +16 -0
  317. package/lib/Utils/stanza-ack.js +37 -0
  318. package/lib/Utils/status-stickers.d.ts +79 -0
  319. package/lib/Utils/status-stickers.js +261 -0
  320. package/lib/Utils/status.d.ts +107 -0
  321. package/lib/Utils/status.js +131 -0
  322. package/lib/Utils/sticker-pack-maker.d.ts +20 -0
  323. package/lib/Utils/sticker-pack-maker.js +112 -0
  324. package/lib/Utils/stickerpack.d.ts +18 -0
  325. package/lib/Utils/stickerpack.js +316 -0
  326. package/lib/Utils/sync-action-utils.d.ts +2 -0
  327. package/lib/Utils/sync-action-utils.js +48 -0
  328. package/lib/Utils/tag.d.ts +8 -0
  329. package/lib/Utils/tag.js +45 -0
  330. package/lib/Utils/tc-token-utils.d.ts +29 -0
  331. package/lib/Utils/tc-token-utils.js +162 -0
  332. package/lib/Utils/templates.d.ts +86 -0
  333. package/lib/Utils/templates.js +148 -0
  334. package/lib/Utils/text-format.d.ts +13 -0
  335. package/lib/Utils/text-format.js +81 -0
  336. package/lib/Utils/text-tools.d.ts +3 -0
  337. package/lib/Utils/text-tools.js +38 -0
  338. package/lib/Utils/ttl-cache.d.ts +29 -0
  339. package/lib/Utils/ttl-cache.js +123 -0
  340. package/lib/Utils/use-cache-manager-auth-state.d.ts +22 -0
  341. package/lib/Utils/use-cache-manager-auth-state.js +86 -0
  342. package/lib/Utils/use-multi-file-auth-state.d.ts +20 -0
  343. package/lib/Utils/use-multi-file-auth-state.js +201 -0
  344. package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
  345. package/lib/Utils/use-single-file-auth-state.js +111 -0
  346. package/lib/Utils/use-sqlite-auth-state.d.ts +13 -0
  347. package/lib/Utils/use-sqlite-auth-state.js +171 -0
  348. package/lib/Utils/username.d.ts +22 -0
  349. package/lib/Utils/username.js +59 -0
  350. package/lib/Utils/validate-connection.d.ts +43 -0
  351. package/lib/Utils/validate-connection.js +197 -0
  352. package/lib/Utils/vcard.d.ts +40 -0
  353. package/lib/Utils/vcard.js +92 -0
  354. package/lib/Utils/voice-note.d.ts +13 -0
  355. package/lib/Utils/voice-note.js +47 -0
  356. package/lib/VoIP/audio-feeder.d.ts +15 -0
  357. package/lib/VoIP/audio-feeder.js +132 -0
  358. package/lib/VoIP/index.d.ts +22 -0
  359. package/lib/VoIP/index.js +277 -0
  360. package/lib/VoIP/relay-transport.d.ts +16 -0
  361. package/lib/VoIP/relay-transport.js +559 -0
  362. package/lib/VoIP/signaling.d.ts +16 -0
  363. package/lib/VoIP/signaling.js +624 -0
  364. package/lib/VoIP/types.d.ts +11 -0
  365. package/lib/VoIP/types.js +17 -0
  366. package/lib/VoIP/wasm-engine.d.ts +28 -0
  367. package/lib/VoIP/wasm-engine.js +1214 -0
  368. package/lib/VoIP/worker-bootstrap.d.ts +1 -0
  369. package/lib/VoIP/worker-bootstrap.js +1042 -0
  370. package/lib/WABinary/constants.d.ts +61 -0
  371. package/lib/WABinary/constants.js +1466 -0
  372. package/lib/WABinary/decode.d.ts +9 -0
  373. package/lib/WABinary/decode.js +261 -0
  374. package/lib/WABinary/encode.d.ts +2 -0
  375. package/lib/WABinary/encode.js +219 -0
  376. package/lib/WABinary/generic-utils.d.ts +45 -0
  377. package/lib/WABinary/generic-utils.js +285 -0
  378. package/lib/WABinary/index.d.ts +5 -0
  379. package/lib/WABinary/index.js +5 -0
  380. package/lib/WABinary/jid-utils.d.ts +32 -0
  381. package/lib/WABinary/jid-utils.js +102 -0
  382. package/lib/WABinary/types.d.ts +1 -0
  383. package/lib/WABinary/types.js +1 -0
  384. package/lib/WAM/BinaryInfo.d.ts +7 -0
  385. package/lib/WAM/BinaryInfo.js +9 -0
  386. package/lib/WAM/constants.d.ts +34926 -0
  387. package/lib/WAM/constants.js +22852 -0
  388. package/lib/WAM/encode.d.ts +1 -0
  389. package/lib/WAM/encode.js +149 -0
  390. package/lib/WAM/index.d.ts +3 -0
  391. package/lib/WAM/index.js +3 -0
  392. package/lib/WAUSync/Protocols/USyncBusinessProtocol.d.ts +43 -0
  393. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +32 -0
  394. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  395. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  396. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +29 -0
  397. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +60 -0
  398. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  399. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  400. package/lib/WAUSync/Protocols/USyncFeatureProtocol.d.ts +13 -0
  401. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +28 -0
  402. package/lib/WAUSync/Protocols/USyncPictureProtocol.d.ts +22 -0
  403. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  404. package/lib/WAUSync/Protocols/USyncSidelistProtocol.d.ts +20 -0
  405. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +23 -0
  406. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  407. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  408. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.d.ts +14 -0
  409. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +24 -0
  410. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  411. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  412. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  413. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  414. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  415. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  416. package/lib/WAUSync/Protocols/index.d.ts +12 -0
  417. package/lib/WAUSync/Protocols/index.js +12 -0
  418. package/lib/WAUSync/USyncQuery.d.ts +25 -0
  419. package/lib/WAUSync/USyncQuery.js +140 -0
  420. package/lib/WAUSync/USyncUser.d.ts +24 -0
  421. package/lib/WAUSync/USyncUser.js +47 -0
  422. package/lib/WAUSync/index.d.ts +3 -0
  423. package/lib/WAUSync/index.js +3 -0
  424. package/lib/assets/wasm/loader.js +5 -0
  425. package/lib/assets/wasm/whatsapp.wasm +0 -0
  426. package/lib/assets/wasm/worker-modules.js +273 -0
  427. package/lib/exports-extra.d.ts +45 -0
  428. package/lib/exports-extra.js +47 -0
  429. package/lib/index.d.ts +16 -0
  430. package/lib/index.js +24 -0
  431. package/package.json +161 -4
@@ -0,0 +1,867 @@
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 { resolveFfmpegPath } from './ffmpeg-path.js';
12
+ import { DEFAULT_MAX_REMOTE_MEDIA_BYTES, DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP, NEWSLETTER_MEDIA_PATH_MAP } from '../Defaults/index.js';
13
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js';
14
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
15
+ import { generateMessageIDV2 } from './generics.js';
16
+ const getTmpFilesDirectory = () => tmpdir();
17
+ let imageProcessingLibrary;
18
+ let _imageLibInitPromise = null;
19
+ export const getImageProcessingLibrary = async () => {
20
+ if (imageProcessingLibrary) {
21
+ return imageProcessingLibrary;
22
+ }
23
+ if (!_imageLibInitPromise) {
24
+ _imageLibInitPromise = (async () => {
25
+ //@ts-ignore
26
+ const [sharp, image, jimp] = await Promise.all([
27
+ import('sharp').catch(() => { }),
28
+ import('@napi-rs/image').catch(() => { }),
29
+ import('jimp').catch(() => { })
30
+ ]);
31
+ if (sharp) {
32
+ imageProcessingLibrary = { sharp };
33
+ }
34
+ else if (image) {
35
+ imageProcessingLibrary = { image };
36
+ }
37
+ else if (jimp) {
38
+ imageProcessingLibrary = { jimp };
39
+ }
40
+ else {
41
+ throw new Boom('No image processing library available');
42
+ }
43
+ return imageProcessingLibrary;
44
+ })();
45
+ }
46
+ return _imageLibInitPromise;
47
+ };
48
+ export const hkdfInfoKey = (type) => {
49
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
50
+ return `WhatsApp ${hkdfInfo} Keys`;
51
+ };
52
+ export const getRawMediaUploadData = async (media, mediaType, logger) => {
53
+ const { stream } = await getStream(media);
54
+ logger?.debug('got stream for raw upload');
55
+ const hasher = Crypto.createHash('sha256');
56
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
57
+ const fileWriteStream = createWriteStream(filePath);
58
+ let fileLength = 0;
59
+ try {
60
+ for await (const data of stream) {
61
+ fileLength += data.length;
62
+ hasher.update(data);
63
+ if (!fileWriteStream.write(data)) {
64
+ await once(fileWriteStream, 'drain');
65
+ }
66
+ }
67
+ fileWriteStream.end();
68
+ await once(fileWriteStream, 'finish');
69
+ stream.destroy();
70
+ const fileSha256 = hasher.digest();
71
+ logger?.debug('hashed data for raw upload');
72
+ return {
73
+ filePath: filePath,
74
+ fileSha256,
75
+ fileLength
76
+ };
77
+ }
78
+ catch (error) {
79
+ fileWriteStream.destroy();
80
+ stream.destroy();
81
+ try {
82
+ await fs.unlink(filePath);
83
+ }
84
+ catch {
85
+ //
86
+ }
87
+ throw error;
88
+ }
89
+ };
90
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
91
+ export async function getMediaKeys(buffer, mediaType) {
92
+ if (!buffer) {
93
+ throw new Boom('Cannot derive from empty media key');
94
+ }
95
+ if (typeof buffer === 'string') {
96
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
97
+ }
98
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
99
+ const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
100
+ return {
101
+ iv: expandedMediaKey.slice(0, 16),
102
+ cipherKey: expandedMediaKey.slice(16, 48),
103
+ macKey: expandedMediaKey.slice(48, 80)
104
+ };
105
+ }
106
+ /** Extracts video thumb using FFMPEG */
107
+ export const extractVideoThumb = async (path, time, size) => {
108
+ // Vanz@Port (2.0.3): honour setFfmpegPath()/FFMPEG_PATH/ffmpeg-static; falls back to the bare 'ffmpeg' on PATH like before.
109
+ const ffmpeg = spawn((await resolveFfmpegPath()) || 'ffmpeg', [
110
+ '-loglevel', 'error',
111
+ '-ss', String(time),
112
+ '-i', path,
113
+ '-an', '-sn', '-dn',
114
+ '-map_metadata', '-1',
115
+ '-vf', `scale=${size.width}:-1`,
116
+ '-frames:v', '1',
117
+ '-c:v', 'mjpeg',
118
+ '-f', 'image2pipe',
119
+ 'pipe:1'
120
+ ], {
121
+ stdio: ['ignore', 'pipe', 'pipe']
122
+ });
123
+ let buffer = Buffer.alloc(0);
124
+ const stderrChunks = [];
125
+ ffmpeg.stdout.on('data', (chunk) => {
126
+ buffer = Buffer.concat([buffer, chunk]);
127
+ });
128
+ ffmpeg.stderr.on('data', (chunk) => stderrChunks.push(chunk));
129
+ const [code] = await once(ffmpeg, 'close');
130
+ if (code !== 0) {
131
+ throw new Boom(`FFmpeg failed (code ${code}):\n` +
132
+ Buffer.concat(stderrChunks).toString('utf8'));
133
+ }
134
+ return buffer;
135
+ };
136
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
137
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
138
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
139
+ if (bufferOrFilePath instanceof Readable) {
140
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
141
+ }
142
+ const lib = await getImageProcessingLibrary();
143
+ if ('sharp' in lib && lib.sharp?.default) {
144
+ const img = lib.sharp.default(bufferOrFilePath);
145
+ const dimensions = await img.metadata();
146
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
147
+ return {
148
+ buffer,
149
+ original: {
150
+ width: dimensions.width,
151
+ height: dimensions.height
152
+ }
153
+ };
154
+ }
155
+ else if ('image' in lib && lib.image?.Transformer) {
156
+ if (!Buffer.isBuffer(bufferOrFilePath)) {
157
+ bufferOrFilePath = await fs.readFile(bufferOrFilePath);
158
+ }
159
+ const img = new lib.image.Transformer(bufferOrFilePath);
160
+ const dimensions = await img.metadata();
161
+ const buffer = await img.resize(width, undefined, 0).jpeg(50);
162
+ return {
163
+ buffer,
164
+ original: {
165
+ width: dimensions.width,
166
+ height: dimensions.height
167
+ }
168
+ };
169
+ }
170
+ else if ('jimp' in lib && lib.jimp?.Jimp) {
171
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
172
+ const dimensions = {
173
+ width: jimp.width,
174
+ height: jimp.height
175
+ };
176
+ const buffer = await jimp
177
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
178
+ .getBuffer('image/jpeg', { quality: 50 });
179
+ return {
180
+ buffer,
181
+ original: dimensions
182
+ };
183
+ }
184
+ else {
185
+ throw new Boom('No image processing library available');
186
+ }
187
+ };
188
+ export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
189
+ export const generateProfilePicture = async (mediaUpload, dimensions) => {
190
+ let buffer;
191
+ const { width: w = 720, height: h = 720 } = dimensions || {};
192
+ if (Buffer.isBuffer(mediaUpload)) {
193
+ buffer = mediaUpload;
194
+ }
195
+ else {
196
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
197
+ const { stream } = await getStream(mediaUpload);
198
+ // Convert the resulting stream to a buffer
199
+ buffer = await toBuffer(stream);
200
+ }
201
+ const lib = await getImageProcessingLibrary();
202
+ let img;
203
+ if ('sharp' in lib && lib.sharp?.default) {
204
+ img = lib.sharp
205
+ .default(buffer)
206
+ .resize(w, h)
207
+ .jpeg({
208
+ quality: 80
209
+ })
210
+ .toBuffer();
211
+ }
212
+ else if ('image' in lib && lib.image?.Transformer) {
213
+ img = new lib.image
214
+ .Transformer(buffer)
215
+ .resize(w, h, 0)
216
+ .jpeg(80);
217
+ }
218
+ else if ('jimp' in lib && lib.jimp?.Jimp) {
219
+ const jimp = await lib.jimp.Jimp.read(buffer);
220
+ const min = Math.min(jimp.width, jimp.height);
221
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
222
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 80 });
223
+ }
224
+ else {
225
+ throw new Boom('No image processing library available');
226
+ }
227
+ return {
228
+ img: await img
229
+ };
230
+ };
231
+ /** gets the SHA256 of the given media message */
232
+ export const mediaMessageSHA256B64 = (message) => {
233
+ const media = Object.values(message)[0];
234
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
235
+ };
236
+ export async function getAudioDuration(buffer) {
237
+ const musicMetadata = await import('music-metadata');
238
+ let metadata;
239
+ const options = {
240
+ duration: true
241
+ };
242
+ if (Buffer.isBuffer(buffer)) {
243
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
244
+ }
245
+ else if (typeof buffer === 'string') {
246
+ metadata = await musicMetadata.parseFile(buffer, options);
247
+ }
248
+ else {
249
+ metadata = await musicMetadata.parseStream(buffer, undefined, options);
250
+ }
251
+ return metadata.format.duration;
252
+ }
253
+ /**
254
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
255
+ */
256
+ export async function getAudioWaveform(buffer, logger) {
257
+ try {
258
+ // @ts-ignore
259
+ const { default: decoder } = await import('audio-decode');
260
+ let audioData;
261
+ if (Buffer.isBuffer(buffer)) {
262
+ audioData = buffer;
263
+ }
264
+ else if (typeof buffer === 'string') {
265
+ const rStream = createReadStream(buffer);
266
+ audioData = await toBuffer(rStream);
267
+ }
268
+ else {
269
+ audioData = await toBuffer(buffer);
270
+ }
271
+ const audioBuffer = await decoder(audioData);
272
+ const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
273
+ const samples = 64; // Number of samples we want to have in our final data set
274
+ const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
275
+ const filteredData = [];
276
+ for (let i = 0; i < samples; i++) {
277
+ const blockStart = blockSize * i; // the location of the first sample in the block
278
+ let sum = 0;
279
+ for (let j = 0; j < blockSize; j++) {
280
+ sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
281
+ }
282
+ filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
283
+ }
284
+ // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
285
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
286
+ const normalizedData = filteredData.map(n => n * multiplier);
287
+ // Generate waveform like WhatsApp
288
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
289
+ return waveform;
290
+ }
291
+ catch (e) {
292
+ logger?.debug('Failed to generate waveform: ' + e);
293
+ }
294
+ }
295
+ export const toReadable = (buffer) => {
296
+ const readable = new Readable({ read: () => { } });
297
+ readable.push(buffer);
298
+ readable.push(null);
299
+ return readable;
300
+ };
301
+ export const toBuffer = async (stream) => {
302
+ const chunks = [];
303
+ for await (const chunk of stream) {
304
+ chunks.push(chunk);
305
+ }
306
+ stream.destroy();
307
+ return Buffer.concat(chunks);
308
+ };
309
+ export const getStream = async (item, opts) => {
310
+ if (Buffer.isBuffer(item)) {
311
+ return { stream: toReadable(item), type: 'buffer' };
312
+ }
313
+ if ('stream' in item) {
314
+ return { stream: item.stream, type: 'readable' };
315
+ }
316
+ const urlStr = item.url.toString();
317
+ if (urlStr.startsWith('data:')) {
318
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
319
+ return { stream: toReadable(buffer), type: 'buffer' };
320
+ }
321
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
322
+ return { stream: await getHttpStream(item.url, opts), type: 'remote' };
323
+ }
324
+ return { stream: createReadStream(item.url), type: 'file' };
325
+ };
326
+ /** generates a thumbnail for a given media, if required */
327
+ export async function generateThumbnail(file, mediaType, options) {
328
+ let thumbnail;
329
+ let originalImageDimensions;
330
+ if (mediaType === 'image') {
331
+ const { buffer, original } = await extractImageThumb(file);
332
+ thumbnail = buffer.toString('base64');
333
+ if (original.width && original.height) {
334
+ originalImageDimensions = {
335
+ width: original.width,
336
+ height: original.height
337
+ };
338
+ }
339
+ }
340
+ else if (mediaType === 'video') {
341
+ try {
342
+ const buff = await extractVideoThumb(file, '00:00:00', { width: 32, height: 32 });
343
+ thumbnail = buff.toString('base64');
344
+ }
345
+ catch (err) {
346
+ options.logger?.debug('could not generate video thumb: ' + err);
347
+ }
348
+ }
349
+ return {
350
+ thumbnail,
351
+ originalImageDimensions
352
+ };
353
+ }
354
+ export const getHttpStream = async (url, options = {}) => {
355
+ const response = await fetch(url.toString(), {
356
+ dispatcher: options.dispatcher,
357
+ method: 'GET',
358
+ headers: options.headers,
359
+ signal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : AbortSignal.timeout(60000)
360
+ });
361
+ if (!response.ok) {
362
+ throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
363
+ }
364
+ // @ts-ignore Node18+ Readable.fromWeb exists
365
+ return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
366
+ };
367
+ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
368
+ const { stream, type } = await getStream(media, opts);
369
+ logger?.debug('fetched media stream');
370
+ const maxRemoteBytes = opts?.maxContentLength ?? DEFAULT_MAX_REMOTE_MEDIA_BYTES;
371
+ const mediaKey = Crypto.randomBytes(32);
372
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
373
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
374
+ const encFileWriteStream = createWriteStream(encFilePath);
375
+ let originalFileStream;
376
+ let originalFilePath;
377
+ if (saveOriginalFileIfRequired) {
378
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
379
+ originalFileStream = createWriteStream(originalFilePath);
380
+ }
381
+ let fileLength = 0;
382
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
383
+ const hmac = Crypto.createHmac('sha256', macKey).update(iv);
384
+ const sha256Plain = Crypto.createHash('sha256');
385
+ const sha256Enc = Crypto.createHash('sha256');
386
+ const onChunk = async (buff) => {
387
+ sha256Enc.update(buff);
388
+ hmac.update(buff);
389
+ // Handle backpressure: if write returns false, wait for drain
390
+ if (!encFileWriteStream.write(buff)) {
391
+ await once(encFileWriteStream, 'drain');
392
+ }
393
+ };
394
+ try {
395
+ for await (const data of stream) {
396
+ fileLength += data.length;
397
+ if (type === 'remote' && maxRemoteBytes && fileLength > maxRemoteBytes) {
398
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
399
+ statusCode: 413,
400
+ data: { type, maxContentLength: maxRemoteBytes }
401
+ });
402
+ }
403
+ if (originalFileStream) {
404
+ if (!originalFileStream.write(data)) {
405
+ await once(originalFileStream, 'drain');
406
+ }
407
+ }
408
+ sha256Plain.update(data);
409
+ await onChunk(aes.update(data));
410
+ }
411
+ await onChunk(aes.final());
412
+ const mac = hmac.digest().slice(0, 10);
413
+ sha256Enc.update(mac);
414
+ const fileSha256 = sha256Plain.digest();
415
+ const fileEncSha256 = sha256Enc.digest();
416
+ encFileWriteStream.write(mac);
417
+ const encFinishPromise = once(encFileWriteStream, 'finish');
418
+ const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();
419
+ encFileWriteStream.end();
420
+ originalFileStream?.end?.();
421
+ stream.destroy();
422
+ // Wait for write streams to fully flush to disk
423
+ // This helps reduce memory pressure by allowing OS to release buffers
424
+ await encFinishPromise;
425
+ await originalFinishPromise;
426
+ logger?.debug('encrypted data successfully');
427
+ return {
428
+ mediaKey,
429
+ originalFilePath,
430
+ encFilePath,
431
+ mac,
432
+ fileEncSha256,
433
+ fileSha256,
434
+ fileLength
435
+ };
436
+ }
437
+ catch (error) {
438
+ // destroy all streams with error
439
+ encFileWriteStream.destroy();
440
+ originalFileStream?.destroy?.();
441
+ aes.destroy();
442
+ hmac.destroy();
443
+ sha256Plain.destroy();
444
+ sha256Enc.destroy();
445
+ stream.destroy();
446
+ try {
447
+ await fs.unlink(encFilePath);
448
+ if (originalFilePath) {
449
+ await fs.unlink(originalFilePath);
450
+ }
451
+ }
452
+ catch (err) {
453
+ logger?.error({ err }, 'failed deleting tmp files');
454
+ }
455
+ throw error;
456
+ }
457
+ };
458
+ export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
459
+ const AES_CHUNK_SIZE = 16;
460
+ const toSmallestChunkSize = (num) => {
461
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
462
+ };
463
+ export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
464
+ const extractHost = (url) => {
465
+ if (!url)
466
+ return undefined;
467
+ try {
468
+ return new URL(url).host;
469
+ }
470
+ catch {
471
+ return undefined;
472
+ }
473
+ };
474
+ export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
475
+ // Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
476
+ // Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
477
+ const fallbackHost = opts.host ?? extractHost(url);
478
+ const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url;
479
+ if (!downloadUrl) {
480
+ throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
481
+ }
482
+ const keys = await getMediaKeys(mediaKey, type);
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
+ // Lia@Changes 06-02-26 --- Switch media path map for newsletter uploads
737
+ const mediaPathMap = newsletter ? NEWSLETTER_MEDIA_PATH_MAP : MEDIA_PATH_MAP;
738
+ // Lia@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
+ if (!isLast) {
771
+ await new Promise(r => setTimeout(r, 300 * (hostIdx + 1)));
772
+ }
773
+ }
774
+ }
775
+ if (!urls) {
776
+ throw new Boom('Media upload failed on all hosts', { statusCode: 500 });
777
+ }
778
+ return urls;
779
+ };
780
+ };
781
+ const getMediaRetryKey = (mediaKey) => {
782
+ return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
783
+ };
784
+ /**
785
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
786
+ */
787
+ export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
788
+ const recp = { stanzaId: key.id };
789
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
790
+ const iv = Crypto.randomBytes(12);
791
+ const retryKey = getMediaRetryKey(mediaKey);
792
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
793
+ const req = {
794
+ tag: 'receipt',
795
+ attrs: {
796
+ id: key.id,
797
+ to: jidNormalizedUser(meId),
798
+ type: 'server-error'
799
+ },
800
+ content: [
801
+ // this encrypt node is actually pretty useless
802
+ // the media is returned even without this node
803
+ // keeping it here to maintain parity with WA Web
804
+ {
805
+ tag: 'encrypt',
806
+ attrs: {},
807
+ content: [
808
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
809
+ { tag: 'enc_iv', attrs: {}, content: iv }
810
+ ]
811
+ },
812
+ {
813
+ tag: 'rmr',
814
+ attrs: {
815
+ jid: key.remoteJid,
816
+ from_me: (!!key.fromMe).toString(),
817
+ // @ts-ignore
818
+ participant: key.participant || undefined
819
+ }
820
+ }
821
+ ]
822
+ };
823
+ return req;
824
+ };
825
+ export const decodeMediaRetryNode = (node) => {
826
+ const rmrNode = getBinaryNodeChild(node, 'rmr');
827
+ const event = {
828
+ key: {
829
+ id: node.attrs.id,
830
+ remoteJid: rmrNode.attrs.jid,
831
+ fromMe: rmrNode.attrs.from_me === 'true',
832
+ participant: rmrNode.attrs.participant
833
+ }
834
+ };
835
+ const errorNode = getBinaryNodeChild(node, 'error');
836
+ if (errorNode) {
837
+ const errorCode = +errorNode.attrs.code;
838
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
839
+ data: errorNode.attrs,
840
+ statusCode: getStatusCodeForMediaRetry(errorCode)
841
+ });
842
+ }
843
+ else {
844
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
845
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
846
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
847
+ if (ciphertext && iv) {
848
+ event.media = { ciphertext, iv };
849
+ }
850
+ else {
851
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
852
+ }
853
+ }
854
+ return event;
855
+ };
856
+ export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
857
+ const retryKey = getMediaRetryKey(mediaKey);
858
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
859
+ return proto.MediaRetryNotification.decode(plaintext);
860
+ };
861
+ export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
862
+ const MEDIA_RETRY_STATUS_MAP = {
863
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
864
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
865
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
866
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
867
+ };