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