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