@vinzsocket/baileys 2.8.35 → 3.0.10

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