@eduh_dev021/baileys 0.0.0-stage → 1.1.0

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