@ubedsockets/baileys 1.6.9 → 1.7.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 (399) hide show
  1. package/WAProto/GenerateStatics.sh +26 -3
  2. package/WAProto/WAProto.proto +432 -180
  3. package/WAProto/add-missing-proto-deps.js +134 -0
  4. package/WAProto/imports-elaina.js +48 -0
  5. package/WAProto/index.js +78044 -140686
  6. package/WAProto/merge-elaina-ai-proto.js +187 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/elaina-version.json +3 -0
  9. package/lib/Defaults/index.js +57 -55
  10. package/lib/Signal/Group/group_cipher.js +1 -1
  11. package/lib/Signal/Group/keyhelper.js +1 -1
  12. package/lib/Signal/Group/sender-chain-key.js +1 -1
  13. package/lib/Signal/Group/sender-key-message.js +1 -1
  14. package/lib/Signal/Group/sender-message-key.js +1 -1
  15. package/lib/Signal/libsignal.js +1 -1
  16. package/lib/Signal/libsignalnode/LICENSE +621 -0
  17. package/lib/Signal/libsignalnode/README.md +11 -0
  18. package/lib/Signal/libsignalnode/generate-proto.sh +1 -0
  19. package/lib/Signal/libsignalnode/index.js +10 -0
  20. package/lib/Signal/libsignalnode/protos/WhisperTextProtocol.proto +28 -0
  21. package/lib/Signal/libsignalnode/src/.eslintrc.json +31 -0
  22. package/lib/Signal/libsignalnode/src/WhisperTextProtocol.js +948 -0
  23. package/lib/Signal/libsignalnode/src/base_key_type.js +6 -0
  24. package/lib/Signal/libsignalnode/src/chain_type.js +6 -0
  25. package/lib/Signal/libsignalnode/src/crypto.js +98 -0
  26. package/lib/Signal/libsignalnode/src/curve.js +142 -0
  27. package/lib/Signal/libsignalnode/src/errors.js +33 -0
  28. package/lib/Signal/libsignalnode/src/keyhelper.js +45 -0
  29. package/lib/Signal/libsignalnode/src/numeric_fingerprint.js +70 -0
  30. package/lib/Signal/libsignalnode/src/protobufs.js +10 -0
  31. package/lib/Signal/libsignalnode/src/protocol_address.js +40 -0
  32. package/lib/Signal/libsignalnode/src/queue_job.js +70 -0
  33. package/lib/Signal/libsignalnode/src/session_builder.js +164 -0
  34. package/lib/Signal/libsignalnode/src/session_cipher.js +332 -0
  35. package/lib/Signal/libsignalnode/src/session_record.js +325 -0
  36. package/lib/Socket/Client/websocket.js +2 -41
  37. package/lib/Socket/Rhandler.js +533 -0
  38. package/lib/Socket/chats.js +249 -123
  39. package/lib/Socket/index.js +1 -1
  40. package/lib/Socket/messages-recv.js +57 -5
  41. package/lib/Socket/messages-send.js +47 -280
  42. package/lib/Socket/newsletter.js +100 -132
  43. package/lib/Socket/socket.js +79 -87
  44. package/lib/Socket/usync.js +0 -2
  45. package/lib/Store/make-in-memory-store.js +1 -1
  46. package/lib/Utils/browser-utils.js +30 -23
  47. package/lib/Utils/crypto.js +22 -18
  48. package/lib/Utils/decode-wa-message.js +12 -2
  49. package/lib/Utils/{baileys-event-stream.js → elaina-event-stream.js} +1 -1
  50. package/lib/Utils/event-buffer.js +2 -2
  51. package/lib/Utils/generics.js +36 -10
  52. package/lib/Utils/index.js +3 -1
  53. package/lib/Utils/message-retry-manager.js +48 -185
  54. package/lib/Utils/messages-media.js +127 -236
  55. package/lib/Utils/messages.js +746 -232
  56. package/lib/Utils/noise-handler.js +1 -2
  57. package/lib/Utils/process-message.js +108 -25
  58. package/lib/Utils/signal.js +1 -10
  59. package/lib/Utils/use-multi-file-auth-state.js +1 -1
  60. package/lib/Utils/validate-connection.js +3 -7
  61. package/lib/Voip/audio-feeder.js +166 -0
  62. package/lib/Voip/index.js +639 -0
  63. package/lib/Voip/relay-transport.js +829 -0
  64. package/lib/Voip/signaling.js +1102 -0
  65. package/lib/Voip/types.js +23 -0
  66. package/lib/Voip/wasm-engine.js +1255 -0
  67. package/lib/Voip/worker-bootstrap.js +1078 -0
  68. package/lib/WABinary/jid-utils.js +17 -1
  69. package/lib/assets/wasm/loader.js +5 -0
  70. package/lib/assets/wasm/whatsapp.wasm +0 -0
  71. package/lib/assets/wasm/worker-modules.js +273 -0
  72. package/lib/index.js +21 -18
  73. package/package.json +32 -18
  74. package/WAProto/AICommon.js +0 -27981
  75. package/WAProto/AICommon.proto +0 -713
  76. package/WAProto/Ephemeral.js +0 -295
  77. package/WAProto/Ephemeral.proto +0 -7
  78. package/WAProto/fix-imports.js +0 -85
  79. package/WAProto/index.d.ts +0 -14017
  80. package/WAProto/vyzen.js +0 -7
  81. package/lib/Defaults/baileys-version.json +0 -3
  82. package/lib/Defaults/index.d.ts +0 -75
  83. package/lib/Defaults/index.d.ts.map +0 -1
  84. package/lib/Defaults/index.js.map +0 -1
  85. package/lib/Signal/Group/ciphertext-message.d.ts +0 -10
  86. package/lib/Signal/Group/ciphertext-message.d.ts.map +0 -1
  87. package/lib/Signal/Group/ciphertext-message.js.map +0 -1
  88. package/lib/Signal/Group/group-session-builder.d.ts +0 -15
  89. package/lib/Signal/Group/group-session-builder.d.ts.map +0 -1
  90. package/lib/Signal/Group/group-session-builder.js.map +0 -1
  91. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  92. package/lib/Signal/Group/group_cipher.d.ts.map +0 -1
  93. package/lib/Signal/Group/group_cipher.js.map +0 -1
  94. package/lib/Signal/Group/index.d.ts +0 -12
  95. package/lib/Signal/Group/index.d.ts.map +0 -1
  96. package/lib/Signal/Group/index.js.map +0 -1
  97. package/lib/Signal/Group/keyhelper.d.ts +0 -11
  98. package/lib/Signal/Group/keyhelper.d.ts.map +0 -1
  99. package/lib/Signal/Group/keyhelper.js.map +0 -1
  100. package/lib/Signal/Group/sender-chain-key.d.ts +0 -14
  101. package/lib/Signal/Group/sender-chain-key.d.ts.map +0 -1
  102. package/lib/Signal/Group/sender-chain-key.js.map +0 -1
  103. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -17
  104. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +0 -1
  105. package/lib/Signal/Group/sender-key-distribution-message.js.map +0 -1
  106. package/lib/Signal/Group/sender-key-message.d.ts +0 -19
  107. package/lib/Signal/Group/sender-key-message.d.ts.map +0 -1
  108. package/lib/Signal/Group/sender-key-message.js.map +0 -1
  109. package/lib/Signal/Group/sender-key-name.d.ts +0 -18
  110. package/lib/Signal/Group/sender-key-name.d.ts.map +0 -1
  111. package/lib/Signal/Group/sender-key-name.js.map +0 -1
  112. package/lib/Signal/Group/sender-key-record.d.ts +0 -31
  113. package/lib/Signal/Group/sender-key-record.d.ts.map +0 -1
  114. package/lib/Signal/Group/sender-key-record.js.map +0 -1
  115. package/lib/Signal/Group/sender-key-state.d.ts +0 -39
  116. package/lib/Signal/Group/sender-key-state.d.ts.map +0 -1
  117. package/lib/Signal/Group/sender-key-state.js.map +0 -1
  118. package/lib/Signal/Group/sender-message-key.d.ts +0 -12
  119. package/lib/Signal/Group/sender-message-key.d.ts.map +0 -1
  120. package/lib/Signal/Group/sender-message-key.js.map +0 -1
  121. package/lib/Signal/libsignal.d.ts +0 -5
  122. package/lib/Signal/libsignal.d.ts.map +0 -1
  123. package/lib/Signal/libsignal.js.map +0 -1
  124. package/lib/Signal/lid-mapping.d.ts +0 -23
  125. package/lib/Signal/lid-mapping.d.ts.map +0 -1
  126. package/lib/Signal/lid-mapping.js +0 -277
  127. package/lib/Signal/lid-mapping.js.map +0 -1
  128. package/lib/Socket/Client/index.d.ts +0 -3
  129. package/lib/Socket/Client/index.d.ts.map +0 -1
  130. package/lib/Socket/Client/index.js.map +0 -1
  131. package/lib/Socket/Client/types.d.ts +0 -16
  132. package/lib/Socket/Client/types.d.ts.map +0 -1
  133. package/lib/Socket/Client/types.js.map +0 -1
  134. package/lib/Socket/Client/websocket.d.ts +0 -13
  135. package/lib/Socket/Client/websocket.d.ts.map +0 -1
  136. package/lib/Socket/Client/websocket.js.map +0 -1
  137. package/lib/Socket/business.d.ts +0 -217
  138. package/lib/Socket/business.d.ts.map +0 -1
  139. package/lib/Socket/business.js.map +0 -1
  140. package/lib/Socket/chats.d.ts +0 -124
  141. package/lib/Socket/chats.d.ts.map +0 -1
  142. package/lib/Socket/chats.js.map +0 -1
  143. package/lib/Socket/communities.d.ts +0 -273
  144. package/lib/Socket/communities.d.ts.map +0 -1
  145. package/lib/Socket/communities.js +0 -431
  146. package/lib/Socket/communities.js.map +0 -1
  147. package/lib/Socket/groups.d.ts +0 -161
  148. package/lib/Socket/groups.d.ts.map +0 -1
  149. package/lib/Socket/groups.js.map +0 -1
  150. package/lib/Socket/index.d.ts +0 -260
  151. package/lib/Socket/index.d.ts.map +0 -1
  152. package/lib/Socket/index.js.map +0 -1
  153. package/lib/Socket/messages-recv.d.ts +0 -203
  154. package/lib/Socket/messages-recv.d.ts.map +0 -1
  155. package/lib/Socket/messages-recv.js.map +0 -1
  156. package/lib/Socket/messages-send.d.ts +0 -199
  157. package/lib/Socket/messages-send.d.ts.map +0 -1
  158. package/lib/Socket/messages-send.js.map +0 -1
  159. package/lib/Socket/mex.d.ts +0 -3
  160. package/lib/Socket/mex.d.ts.map +0 -1
  161. package/lib/Socket/mex.js +0 -42
  162. package/lib/Socket/mex.js.map +0 -1
  163. package/lib/Socket/newsletter.d.ts +0 -170
  164. package/lib/Socket/newsletter.d.ts.map +0 -1
  165. package/lib/Socket/newsletter.js.map +0 -1
  166. package/lib/Socket/setup.js +0 -433
  167. package/lib/Socket/socket.d.ts +0 -59
  168. package/lib/Socket/socket.d.ts.map +0 -1
  169. package/lib/Socket/socket.js.map +0 -1
  170. package/lib/Types/Auth.d.ts +0 -117
  171. package/lib/Types/Auth.d.ts.map +0 -1
  172. package/lib/Types/Auth.js.map +0 -1
  173. package/lib/Types/Bussines.d.ts +0 -25
  174. package/lib/Types/Bussines.d.ts.map +0 -1
  175. package/lib/Types/Bussines.js +0 -2
  176. package/lib/Types/Bussines.js.map +0 -1
  177. package/lib/Types/Call.d.ts +0 -15
  178. package/lib/Types/Call.d.ts.map +0 -1
  179. package/lib/Types/Call.js.map +0 -1
  180. package/lib/Types/Chat.d.ts +0 -124
  181. package/lib/Types/Chat.d.ts.map +0 -1
  182. package/lib/Types/Chat.js.map +0 -1
  183. package/lib/Types/Contact.d.ts +0 -26
  184. package/lib/Types/Contact.d.ts.map +0 -1
  185. package/lib/Types/Contact.js.map +0 -1
  186. package/lib/Types/Events.d.ts +0 -256
  187. package/lib/Types/Events.d.ts.map +0 -1
  188. package/lib/Types/Events.js.map +0 -1
  189. package/lib/Types/GroupMetadata.d.ts +0 -71
  190. package/lib/Types/GroupMetadata.d.ts.map +0 -1
  191. package/lib/Types/GroupMetadata.js.map +0 -1
  192. package/lib/Types/Label.d.ts +0 -47
  193. package/lib/Types/Label.d.ts.map +0 -1
  194. package/lib/Types/Label.js.map +0 -1
  195. package/lib/Types/LabelAssociation.d.ts +0 -30
  196. package/lib/Types/LabelAssociation.d.ts.map +0 -1
  197. package/lib/Types/LabelAssociation.js.map +0 -1
  198. package/lib/Types/Message.d.ts +0 -320
  199. package/lib/Types/Message.d.ts.map +0 -1
  200. package/lib/Types/Message.js.map +0 -1
  201. package/lib/Types/Mex.d.ts +0 -141
  202. package/lib/Types/Mex.d.ts.map +0 -1
  203. package/lib/Types/Mex.js +0 -37
  204. package/lib/Types/Mex.js.map +0 -1
  205. package/lib/Types/Product.d.ts +0 -79
  206. package/lib/Types/Product.d.ts.map +0 -1
  207. package/lib/Types/Product.js.map +0 -1
  208. package/lib/Types/RichType.d.ts +0 -3
  209. package/lib/Types/RichType.d.ts.map +0 -1
  210. package/lib/Types/RichType.js +0 -31
  211. package/lib/Types/Signal.d.ts +0 -87
  212. package/lib/Types/Signal.d.ts.map +0 -1
  213. package/lib/Types/Signal.js.map +0 -1
  214. package/lib/Types/Socket.d.ts +0 -136
  215. package/lib/Types/Socket.d.ts.map +0 -1
  216. package/lib/Types/Socket.js.map +0 -1
  217. package/lib/Types/State.d.ts +0 -97
  218. package/lib/Types/State.d.ts.map +0 -1
  219. package/lib/Types/State.js.map +0 -1
  220. package/lib/Types/USync.d.ts +0 -26
  221. package/lib/Types/USync.d.ts.map +0 -1
  222. package/lib/Types/USync.js.map +0 -1
  223. package/lib/Types/index.d.ts +0 -65
  224. package/lib/Types/index.d.ts.map +0 -1
  225. package/lib/Types/index.js.map +0 -1
  226. package/lib/Utils/Tiktok.js +0 -80
  227. package/lib/Utils/auth-utils.d.ts +0 -24
  228. package/lib/Utils/auth-utils.d.ts.map +0 -1
  229. package/lib/Utils/auth-utils.js.map +0 -1
  230. package/lib/Utils/browser-utils.d.ts +0 -4
  231. package/lib/Utils/browser-utils.d.ts.map +0 -1
  232. package/lib/Utils/browser-utils.js.map +0 -1
  233. package/lib/Utils/business.d.ts +0 -23
  234. package/lib/Utils/business.d.ts.map +0 -1
  235. package/lib/Utils/business.js.map +0 -1
  236. package/lib/Utils/chaanel/vyzen.js +0 -0
  237. package/lib/Utils/chat-utils.d.ts +0 -100
  238. package/lib/Utils/chat-utils.d.ts.map +0 -1
  239. package/lib/Utils/chat-utils.js.map +0 -1
  240. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  241. package/lib/Utils/companion-reg-client-utils.d.ts.map +0 -1
  242. package/lib/Utils/companion-reg-client-utils.js +0 -35
  243. package/lib/Utils/companion-reg-client-utils.js.map +0 -1
  244. package/lib/Utils/crypto.d.ts +0 -37
  245. package/lib/Utils/crypto.d.ts.map +0 -1
  246. package/lib/Utils/crypto.js.map +0 -1
  247. package/lib/Utils/decode-wa-message.d.ts +0 -66
  248. package/lib/Utils/decode-wa-message.d.ts.map +0 -1
  249. package/lib/Utils/decode-wa-message.js.map +0 -1
  250. package/lib/Utils/event-buffer.d.ts +0 -36
  251. package/lib/Utils/event-buffer.d.ts.map +0 -1
  252. package/lib/Utils/event-buffer.js.map +0 -1
  253. package/lib/Utils/facebook.js +0 -48
  254. package/lib/Utils/generics.d.ts +0 -91
  255. package/lib/Utils/generics.d.ts.map +0 -1
  256. package/lib/Utils/generics.js.map +0 -1
  257. package/lib/Utils/history.d.ts +0 -24
  258. package/lib/Utils/history.d.ts.map +0 -1
  259. package/lib/Utils/history.js.map +0 -1
  260. package/lib/Utils/identity-change-handler.d.ts +0 -44
  261. package/lib/Utils/identity-change-handler.d.ts.map +0 -1
  262. package/lib/Utils/identity-change-handler.js +0 -50
  263. package/lib/Utils/identity-change-handler.js.map +0 -1
  264. package/lib/Utils/index.d.ts +0 -22
  265. package/lib/Utils/index.d.ts.map +0 -1
  266. package/lib/Utils/index.js.map +0 -1
  267. package/lib/Utils/instagram.js +0 -50
  268. package/lib/Utils/link-preview.d.ts +0 -21
  269. package/lib/Utils/link-preview.d.ts.map +0 -1
  270. package/lib/Utils/link-preview.js.map +0 -1
  271. package/lib/Utils/logger.d.ts +0 -12
  272. package/lib/Utils/logger.d.ts.map +0 -1
  273. package/lib/Utils/logger.js.map +0 -1
  274. package/lib/Utils/lt-hash.d.ts +0 -8
  275. package/lib/Utils/lt-hash.d.ts.map +0 -1
  276. package/lib/Utils/lt-hash.js.map +0 -1
  277. package/lib/Utils/make-mutex.d.ts +0 -9
  278. package/lib/Utils/make-mutex.d.ts.map +0 -1
  279. package/lib/Utils/make-mutex.js.map +0 -1
  280. package/lib/Utils/message-retry-manager.d.ts +0 -115
  281. package/lib/Utils/message-retry-manager.d.ts.map +0 -1
  282. package/lib/Utils/message-retry-manager.js.map +0 -1
  283. package/lib/Utils/messages-media.d.ts +0 -133
  284. package/lib/Utils/messages-media.d.ts.map +0 -1
  285. package/lib/Utils/messages-media.js.map +0 -1
  286. package/lib/Utils/messages.d.ts +0 -91
  287. package/lib/Utils/messages.d.ts.map +0 -1
  288. package/lib/Utils/messages.js.map +0 -1
  289. package/lib/Utils/noise-handler.d.ts +0 -20
  290. package/lib/Utils/noise-handler.d.ts.map +0 -1
  291. package/lib/Utils/noise-handler.js.map +0 -1
  292. package/lib/Utils/offline-node-processor.d.ts +0 -17
  293. package/lib/Utils/offline-node-processor.d.ts.map +0 -1
  294. package/lib/Utils/offline-node-processor.js +0 -40
  295. package/lib/Utils/offline-node-processor.js.map +0 -1
  296. package/lib/Utils/pre-key-manager.d.ts +0 -28
  297. package/lib/Utils/pre-key-manager.d.ts.map +0 -1
  298. package/lib/Utils/pre-key-manager.js +0 -106
  299. package/lib/Utils/pre-key-manager.js.map +0 -1
  300. package/lib/Utils/process-message.d.ts +0 -60
  301. package/lib/Utils/process-message.d.ts.map +0 -1
  302. package/lib/Utils/process-message.js.map +0 -1
  303. package/lib/Utils/reporting-utils.d.ts +0 -11
  304. package/lib/Utils/reporting-utils.d.ts.map +0 -1
  305. package/lib/Utils/reporting-utils.js +0 -258
  306. package/lib/Utils/reporting-utils.js.map +0 -1
  307. package/lib/Utils/rich-message-utils.js +0 -387
  308. package/lib/Utils/signal.d.ts +0 -47
  309. package/lib/Utils/signal.d.ts.map +0 -1
  310. package/lib/Utils/signal.js.map +0 -1
  311. package/lib/Utils/stanza-ack.d.ts +0 -11
  312. package/lib/Utils/stanza-ack.d.ts.map +0 -1
  313. package/lib/Utils/stanza-ack.js +0 -38
  314. package/lib/Utils/stanza-ack.js.map +0 -1
  315. package/lib/Utils/sync-action-utils.d.ts +0 -19
  316. package/lib/Utils/sync-action-utils.d.ts.map +0 -1
  317. package/lib/Utils/sync-action-utils.js +0 -49
  318. package/lib/Utils/sync-action-utils.js.map +0 -1
  319. package/lib/Utils/tc-token-utils.d.ts +0 -37
  320. package/lib/Utils/tc-token-utils.d.ts.map +0 -1
  321. package/lib/Utils/tc-token-utils.js +0 -163
  322. package/lib/Utils/tc-token-utils.js.map +0 -1
  323. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  324. package/lib/Utils/use-multi-file-auth-state.d.ts.map +0 -1
  325. package/lib/Utils/use-multi-file-auth-state.js.map +0 -1
  326. package/lib/Utils/validate-connection.d.ts +0 -11
  327. package/lib/Utils/validate-connection.d.ts.map +0 -1
  328. package/lib/Utils/validate-connection.js.map +0 -1
  329. package/lib/Utils/youtube.js +0 -44
  330. package/lib/WABinary/constants.d.ts +0 -28
  331. package/lib/WABinary/constants.d.ts.map +0 -1
  332. package/lib/WABinary/constants.js.map +0 -1
  333. package/lib/WABinary/decode.d.ts +0 -7
  334. package/lib/WABinary/decode.d.ts.map +0 -1
  335. package/lib/WABinary/decode.js.map +0 -1
  336. package/lib/WABinary/encode.d.ts +0 -3
  337. package/lib/WABinary/encode.d.ts.map +0 -1
  338. package/lib/WABinary/encode.js.map +0 -1
  339. package/lib/WABinary/generic-utils.d.ts +0 -15
  340. package/lib/WABinary/generic-utils.d.ts.map +0 -1
  341. package/lib/WABinary/generic-utils.js.map +0 -1
  342. package/lib/WABinary/index.d.ts +0 -6
  343. package/lib/WABinary/index.d.ts.map +0 -1
  344. package/lib/WABinary/index.js.map +0 -1
  345. package/lib/WABinary/jid-utils.d.ts +0 -48
  346. package/lib/WABinary/jid-utils.d.ts.map +0 -1
  347. package/lib/WABinary/jid-utils.js.map +0 -1
  348. package/lib/WABinary/types.d.ts +0 -19
  349. package/lib/WABinary/types.d.ts.map +0 -1
  350. package/lib/WABinary/types.js.map +0 -1
  351. package/lib/WAM/BinaryInfo.d.ts +0 -9
  352. package/lib/WAM/BinaryInfo.d.ts.map +0 -1
  353. package/lib/WAM/BinaryInfo.js.map +0 -1
  354. package/lib/WAM/constants.d.ts +0 -40
  355. package/lib/WAM/constants.d.ts.map +0 -1
  356. package/lib/WAM/constants.js.map +0 -1
  357. package/lib/WAM/encode.d.ts +0 -3
  358. package/lib/WAM/encode.d.ts.map +0 -1
  359. package/lib/WAM/encode.js.map +0 -1
  360. package/lib/WAM/index.d.ts +0 -4
  361. package/lib/WAM/index.d.ts.map +0 -1
  362. package/lib/WAM/index.js.map +0 -1
  363. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -10
  364. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +0 -1
  365. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +0 -1
  366. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -23
  367. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +0 -1
  368. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +0 -1
  369. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -13
  370. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +0 -1
  371. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +0 -1
  372. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -13
  373. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +0 -1
  374. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +0 -1
  375. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  376. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +0 -1
  377. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  378. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +0 -1
  379. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -26
  380. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +0 -1
  381. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +0 -1
  382. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -10
  383. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +0 -1
  384. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +0 -1
  385. package/lib/WAUSync/Protocols/index.d.ts +0 -6
  386. package/lib/WAUSync/Protocols/index.d.ts.map +0 -1
  387. package/lib/WAUSync/Protocols/index.js.map +0 -1
  388. package/lib/WAUSync/USyncQuery.d.ts +0 -30
  389. package/lib/WAUSync/USyncQuery.d.ts.map +0 -1
  390. package/lib/WAUSync/USyncQuery.js.map +0 -1
  391. package/lib/WAUSync/USyncUser.d.ts +0 -17
  392. package/lib/WAUSync/USyncUser.d.ts.map +0 -1
  393. package/lib/WAUSync/USyncUser.js.map +0 -1
  394. package/lib/WAUSync/index.d.ts +0 -4
  395. package/lib/WAUSync/index.d.ts.map +0 -1
  396. package/lib/WAUSync/index.js.map +0 -1
  397. package/lib/index.d.ts +0 -12
  398. package/lib/index.d.ts.map +0 -1
  399. package/lib/index.js.map +0 -1
@@ -0,0 +1,1102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SignalingBridge = void 0;
4
+
5
+ const S_WHATSAPP_NET = "@s.whatsapp.net";
6
+ const TC_TOKEN_REQUEST_TIMEOUT_MS = 15000;
7
+ const SESSION_CACHE_TTL_MS = 5 * 60000;
8
+ const ACK_TIMEOUT_MS = 15000;
9
+
10
+ let _baileysModule = null;
11
+
12
+ const loadBaileys = async () => {
13
+ if (_baileysModule) return _baileysModule;
14
+ try {
15
+ _baileysModule = await import("../index.js");
16
+ return _baileysModule;
17
+ } catch {
18
+ throw new Error("Could not import internal Elaina Baileys module.");
19
+ }
20
+ };
21
+
22
+ const getNodeChildren = node => Array.isArray(node.content) ? node.content : [];
23
+
24
+ const setNodeChildren = (node, children) => {
25
+ node.content = children.length ? children : undefined;
26
+ };
27
+
28
+ const replaceNodeChild = (node, tag, nextChild) => {
29
+ const children = getNodeChildren(node);
30
+ const index = children.findIndex(child => child.tag === tag);
31
+ if (index >= 0) children[index] = nextChild;
32
+ else children.push(nextChild);
33
+ setNodeChildren(node, children);
34
+ };
35
+
36
+ const removeNodeChildrenByTag = (node, tag) => {
37
+ setNodeChildren(node, getNodeChildren(node).filter(child => child.tag !== tag));
38
+ };
39
+
40
+ const parseCountAttr = (value, fallback = 0) => {
41
+ const parsed = Number(value);
42
+ return Number.isFinite(parsed) ? parsed : fallback;
43
+ };
44
+
45
+ class SignalingBridge {
46
+ constructor(config) {
47
+ this._sock = config.sock;
48
+ this._baileys = null;
49
+ this._voip = null;
50
+ this._observedTcTokens = new Map();
51
+ this._pendingTcTokenWaiters = new Map();
52
+ this._ensuredSignalSessions = new Map();
53
+ this._remoteDevicePeerByCallId = new Map();
54
+ this._remoteObfuscatedPeerByCallId = new Map();
55
+ this._remoteXmppRoutePeerByCallId = new Map();
56
+ this._incomingCallPeerById = new Map();
57
+ this._outgoingSignalingQueue = Promise.resolve(undefined);
58
+ this._incomingSignalingQueue = Promise.resolve(undefined);
59
+
60
+ this.attachEngine = voip => {
61
+ this._voip = voip;
62
+ };
63
+
64
+ this.init = async () => {
65
+ this._baileys = await loadBaileys();
66
+
67
+ if (this._sock.authState?.keys?.set) {
68
+ const originalKeysSet = this._sock.authState.keys.set.bind(this._sock.authState.keys);
69
+
70
+ this._sock.authState.keys.set = async data => {
71
+ const result = await originalKeysSet(data);
72
+
73
+ for (const [jid, entry] of Object.entries(data?.tctoken ?? {})) {
74
+ if (entry?.token instanceof Uint8Array && entry.token.length > 0) {
75
+ this._rememberTcToken(jid, entry.token, entry.timestamp);
76
+ }
77
+ }
78
+
79
+ return result;
80
+ };
81
+ }
82
+
83
+ if (this._sock.ev?.on) {
84
+ this._sock.ev.on("chats.update", updates => {
85
+ for (const update of updates || []) {
86
+ if (update?.id && update?.tcToken instanceof Uint8Array && update.tcToken.length > 0) {
87
+ console.log("[RTC TC TOKEN FROM CHATS.UPDATE]", {
88
+ jid: update.id,
89
+ length: update.tcToken.length
90
+ });
91
+
92
+ this._rememberTcToken(update.id, update.tcToken, String(Math.floor(Date.now() / 1000)));
93
+ }
94
+ }
95
+ });
96
+ }
97
+
98
+ if (this._sock.ws?.on) {
99
+ const handlePrivacyNotification = node => {
100
+ try {
101
+ if (node?.attrs?.type !== "privacy_token") return;
102
+ this._processPrivacyTokenNotification(node);
103
+ } catch (err) {
104
+ console.error("[RTC RAW PRIVACY TOKEN ERROR]", err?.message || err);
105
+ }
106
+ };
107
+
108
+ this._sock.ws.on("CB:notification,type:privacy_token", handlePrivacyNotification);
109
+ this._sock.ws.on("CB:notification", handlePrivacyNotification);
110
+ }
111
+ };
112
+
113
+ this.sendSignaling = (peerJid, callId, xmlPayload) => {
114
+ this._outgoingSignalingQueue = this._outgoingSignalingQueue
115
+ .then(() => this._doSendSignaling(peerJid, callId, xmlPayload))
116
+ .catch(err => {
117
+ console.error("[RTC SIGNALING ERROR]", err?.stack || err?.message || err);
118
+ });
119
+ };
120
+
121
+ this.processIncomingCall = (node, voip, activeCallId) => {
122
+ this._incomingSignalingQueue = this._incomingSignalingQueue
123
+ .then(() => {
124
+ if (!voip || (typeof voip.isInitialized === "function" && !voip.isInitialized())) return;
125
+ return this._doProcessIncomingCall(node, voip, activeCallId);
126
+ })
127
+ .catch(err => {
128
+ console.error("[RTC INCOMING CALL ERROR]", err?.stack || err?.message || err);
129
+ });
130
+ };
131
+
132
+ this.processIncomingReceipt = (node, voip, activeCallId) => {
133
+ this._incomingSignalingQueue = this._incomingSignalingQueue
134
+ .then(() => {
135
+ if (!voip || (typeof voip.isInitialized === "function" && !voip.isInitialized())) return;
136
+ return this._doProcessIncomingReceipt(node, voip, activeCallId);
137
+ })
138
+ .catch(err => {
139
+ console.error("[RTC INCOMING RECEIPT ERROR]", err?.stack || err?.message || err);
140
+ });
141
+ };
142
+
143
+ this.requestTcToken = async jid => {
144
+ const userJid = this._toBareJid(jid);
145
+ const cached = await this._getTcToken(userJid);
146
+
147
+ if (cached?.length) return cached;
148
+
149
+ const waiter = this._waitForTcToken(userJid, TC_TOKEN_REQUEST_TIMEOUT_MS);
150
+
151
+ const logResponse = (label, response) => {
152
+ console.log(`[RTC TC TOKEN RESPONSE:${label}]`, JSON.stringify(response, (key, value) => {
153
+ if (value instanceof Uint8Array || Buffer.isBuffer(value)) {
154
+ return `<buffer:${value.length}>`;
155
+ }
156
+
157
+ return value;
158
+ }, 2));
159
+ };
160
+
161
+ const tryReadResponse = async (label, response) => {
162
+ logResponse(label, response);
163
+
164
+ const tokenNodes = this._findTcTokenNodes(response);
165
+
166
+ for (const tokenNode of tokenNodes) {
167
+ const content = tokenNode?.content;
168
+
169
+ if (content instanceof Uint8Array && content.length > 0) {
170
+ const token = Buffer.from(content);
171
+ const timestamp = String(tokenNode.attrs?.t ?? Math.floor(Date.now() / 1000));
172
+
173
+ await this._storeTcToken(userJid, token, timestamp);
174
+
175
+ return token;
176
+ }
177
+ }
178
+
179
+ return null;
180
+ };
181
+
182
+ const attempts = [];
183
+
184
+ if (typeof this._sock.getPrivacyTokens === "function") {
185
+ attempts.push({
186
+ label: "getPrivacyTokens",
187
+ run: () => this._sock.getPrivacyTokens([userJid])
188
+ });
189
+ }
190
+
191
+ attempts.push({
192
+ label: "privacy-set-with-t",
193
+ run: () => this._sock.query({
194
+ tag: "iq",
195
+ attrs: {
196
+ to: S_WHATSAPP_NET,
197
+ type: "set",
198
+ xmlns: "privacy",
199
+ id: this._sock.generateMessageTag()
200
+ },
201
+ content: [
202
+ {
203
+ tag: "tokens",
204
+ attrs: {},
205
+ content: [
206
+ {
207
+ tag: "token",
208
+ attrs: {
209
+ jid: userJid,
210
+ t: String(Math.floor(Date.now() / 1000)),
211
+ type: "trusted_contact"
212
+ }
213
+ }
214
+ ]
215
+ }
216
+ ]
217
+ })
218
+ });
219
+
220
+ attempts.push({
221
+ label: "privacy-set-no-t",
222
+ run: () => this._sock.query({
223
+ tag: "iq",
224
+ attrs: {
225
+ to: S_WHATSAPP_NET,
226
+ type: "set",
227
+ xmlns: "privacy",
228
+ id: this._sock.generateMessageTag()
229
+ },
230
+ content: [
231
+ {
232
+ tag: "tokens",
233
+ attrs: {},
234
+ content: [
235
+ {
236
+ tag: "token",
237
+ attrs: {
238
+ jid: userJid,
239
+ type: "trusted_contact"
240
+ }
241
+ }
242
+ ]
243
+ }
244
+ ]
245
+ })
246
+ });
247
+
248
+ for (const attempt of attempts) {
249
+ try {
250
+ const response = await attempt.run();
251
+ const token = await tryReadResponse(attempt.label, response);
252
+
253
+ if (token?.length) return token;
254
+ } catch (err) {
255
+ console.error(`[RTC TC TOKEN REQUEST ERROR:${attempt.label}]`, err?.stack || err?.message || err);
256
+ }
257
+
258
+ const stored = await this._getTcToken(userJid);
259
+ if (stored?.length) return stored;
260
+
261
+ const waited = await Promise.race([
262
+ waiter,
263
+ new Promise(resolve => setTimeout(() => resolve(undefined), 2500))
264
+ ]);
265
+
266
+ if (waited?.length) return waited;
267
+ }
268
+
269
+ const waited = await waiter;
270
+ if (waited?.length) return waited;
271
+
272
+ return this._getTcToken(userJid);
273
+ };
274
+
275
+ this.ensureTcToken = async (...jids) => {
276
+ const uniqueJids = [
277
+ ...new Set(jids.map(jid => this._toBareJid(String(jid ?? "").trim())).filter(Boolean))
278
+ ];
279
+
280
+ for (const jid of uniqueJids) {
281
+ const cached = await this._getTcToken(jid);
282
+ if (cached?.length) return cached;
283
+ }
284
+
285
+ for (const jid of uniqueJids) {
286
+ const fetched = await this.requestTcToken(jid);
287
+ if (fetched?.length) return fetched;
288
+ }
289
+
290
+ return undefined;
291
+ };
292
+
293
+ this.discoverPeerDevices = async peerJid => {
294
+ const bareJid = this._toBareJid(peerJid);
295
+ const { jidDecode } = this._baileys;
296
+ const decoded = jidDecode(bareJid);
297
+
298
+ if (!decoded?.user) return [bareJid];
299
+
300
+ const server = bareJid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
301
+ const attempts = [
302
+ [bareJid, false, false],
303
+ [bareJid, true, false],
304
+ [bareJid, false, true],
305
+ [bareJid, true, true]
306
+ ];
307
+
308
+ for (const [jid, useCache, ignoreZeroDevices] of attempts) {
309
+ try {
310
+ const devices = await this._sock.getUSyncDevices?.([jid], useCache, ignoreZeroDevices);
311
+ const jids = [];
312
+
313
+ for (const device of devices || []) {
314
+ if (!device) continue;
315
+ if (typeof device === "string") {
316
+ jids.push(device);
317
+ continue;
318
+ }
319
+ if (device.jid) {
320
+ jids.push(device.jid);
321
+ continue;
322
+ }
323
+ const user = device.user || decoded.user;
324
+ const dev = device.device;
325
+ if (user && dev !== undefined && dev !== null) {
326
+ jids.push(`${user}:${dev}@${server}`);
327
+ }
328
+ }
329
+
330
+ const list = this._normalizeStartCallPeerList(jids);
331
+ if (list.length) {
332
+ console.log("[RTC DEVICES]", { peerJid: bareJid, list });
333
+ return list;
334
+ }
335
+ } catch (err) {
336
+ console.error("[RTC DEVICES ERROR]", err?.message || err);
337
+ }
338
+ }
339
+
340
+ const fallback = [`${decoded.user}:0@${server}`];
341
+ console.log("[RTC DEVICES FALLBACK]", { peerJid: bareJid, fallback });
342
+ return fallback;
343
+ };
344
+
345
+ this.ensureSessionsForPeers = async jids => {
346
+ const targets = this._expandSignalSessionTargets(jids);
347
+ if (targets.length) await this._ensureSignalSessions(targets, true);
348
+ };
349
+
350
+ this.resolveLid = async jid => {
351
+ const bare = this._toBareJid(String(jid || "").trim());
352
+ if (!bare) return undefined;
353
+ if (bare.endsWith("@lid")) return bare;
354
+
355
+ try {
356
+ const mapped = await this._sock.signalRepository?.lidMapping?.getLIDForPN?.(bare);
357
+ if (mapped) return this._toBareJid(mapped);
358
+ } catch {}
359
+
360
+ try {
361
+ const stored = await this._getStoredLidForPn(bare);
362
+ if (stored) return stored;
363
+ } catch {}
364
+
365
+ const resolved = await this._resolveLidViaUSync(bare);
366
+ if (resolved) {
367
+ await this._storeLidPnMapping(resolved, bare);
368
+ return resolved;
369
+ }
370
+
371
+ return undefined;
372
+ };
373
+
374
+ this.issueTcToken = async jid => {
375
+ const userJid = this._toBareJid(jid);
376
+ const issuedAt = Math.floor(Date.now() / 1000);
377
+
378
+ try {
379
+ await this._sock.query({
380
+ tag: "iq",
381
+ attrs: {
382
+ to: S_WHATSAPP_NET,
383
+ type: "set",
384
+ xmlns: "privacy",
385
+ id: this._sock.generateMessageTag()
386
+ },
387
+ content: [
388
+ {
389
+ tag: "tokens",
390
+ attrs: {},
391
+ content: [
392
+ {
393
+ tag: "token",
394
+ attrs: {
395
+ jid: userJid,
396
+ t: String(issuedAt),
397
+ type: "trusted_contact"
398
+ }
399
+ }
400
+ ]
401
+ }
402
+ ]
403
+ });
404
+ return true;
405
+ } catch (err) {
406
+ console.error("[RTC ISSUE TC TOKEN ERROR]", err?.message || err);
407
+ return false;
408
+ }
409
+ };
410
+
411
+ this.getRemoteDeviceJid = callId => this._remoteDevicePeerByCallId.get(callId);
412
+
413
+ this._resolveLidViaUSync = async pnJid => {
414
+ if (typeof this._sock.executeUSyncQuery !== "function") return undefined;
415
+ const { USyncQuery, USyncUser } = this._baileys;
416
+ if (!USyncQuery || !USyncUser) return undefined;
417
+
418
+ const query = new USyncQuery()
419
+ .withContext("message")
420
+ .withLIDProtocol();
421
+ query.withUser(new USyncUser().withId(pnJid));
422
+
423
+ try {
424
+ const result = await this._sock.executeUSyncQuery(query);
425
+ const row = (result?.list || []).find(item => item?.id === pnJid || item?.lid);
426
+ const lid = this._normalizeLid(row?.lid);
427
+ if (lid) {
428
+ console.log("[RTC LID RESOLVED]", { pn: pnJid, lid });
429
+ return lid;
430
+ }
431
+ } catch (err) {
432
+ console.error("[RTC RESOLVE LID USYNC ERROR]", err?.message || err);
433
+ }
434
+
435
+ return undefined;
436
+ };
437
+
438
+ this._normalizeLid = value => {
439
+ const raw = String(value || "").trim();
440
+ if (!raw) return undefined;
441
+ if (raw.endsWith("@lid")) return this._toBareJid(raw);
442
+ if (raw.endsWith("@hosted.lid")) return this._toBareJid(raw);
443
+ if (/^\d+$/.test(raw)) return `${raw}@lid`;
444
+ return raw.includes("@") ? this._toBareJid(raw) : `${raw}@lid`;
445
+ };
446
+
447
+ this._getStoredLidForPn = async pnJid => {
448
+ const decoded = this._baileys.jidDecode(pnJid);
449
+ if (!decoded?.user || !this._sock.authState?.keys?.get) return undefined;
450
+
451
+ const stored = await this._sock.authState.keys.get("lid-mapping", [decoded.user]);
452
+ const lidUser = stored?.[decoded.user];
453
+ if (!lidUser) return undefined;
454
+
455
+ return this._normalizeLid(String(lidUser));
456
+ };
457
+
458
+ this._storeLidPnMapping = async (lidJid, pnJid) => {
459
+ const normalizedLid = this._normalizeLid(lidJid);
460
+ const normalizedPn = this._toBareJid(pnJid);
461
+ if (!normalizedLid || !normalizedPn) return;
462
+
463
+ try {
464
+ await this._sock.signalRepository?.lidMapping?.storeLIDPNMappings?.([
465
+ { lid: normalizedLid, pn: normalizedPn }
466
+ ]);
467
+ } catch {}
468
+
469
+ const pnDecoded = this._baileys.jidDecode(normalizedPn);
470
+ const lidDecoded = this._baileys.jidDecode(normalizedLid);
471
+ if (!pnDecoded?.user || !lidDecoded?.user || !this._sock.authState?.keys?.set) return;
472
+
473
+ try {
474
+ await this._sock.authState.keys.set({
475
+ "lid-mapping": {
476
+ [pnDecoded.user]: lidDecoded.user,
477
+ [`${lidDecoded.user}_reverse`]: pnDecoded.user
478
+ }
479
+ });
480
+ } catch {}
481
+ };
482
+
483
+ this._doSendSignaling = async (peerJid, callId, xmlPayload) => {
484
+ const { decodeBinaryNode, getBinaryNodeChild } = this._baileys;
485
+ const rawPayload = Buffer.from(xmlPayload);
486
+ let voipNode;
487
+
488
+ try {
489
+ voipNode = await decodeBinaryNode(Buffer.concat([Buffer.from([0]), rawPayload]));
490
+ } catch {
491
+ voipNode = await decodeBinaryNode(rawPayload);
492
+ }
493
+
494
+ const signalingTag = String(voipNode.tag);
495
+ const effectivePeerJid = this._resolveOutboundPeerJid(callId, peerJid);
496
+
497
+ if (signalingTag === "offer" && !voipNode.attrs["call-creator"]) {
498
+ const selfCreator =
499
+ this._sock.authState?.creds?.me?.lid ||
500
+ this._sock.authState?.creds?.me?.lidJid ||
501
+ this._sock.authState?.creds?.me?.id ||
502
+ this._sock.user?.lid ||
503
+ this._sock.user?.id ||
504
+ this._sock.user?.jid;
505
+ if (selfCreator) voipNode.attrs["call-creator"] = this._toBareJid(selfCreator);
506
+ }
507
+
508
+ const destination = getBinaryNodeChild(voipNode, "destination");
509
+
510
+ if (destination) {
511
+ const destinations = getNodeChildren(destination);
512
+ const destinationJids = destinations.map(node => String(node.attrs.jid ?? "").trim()).filter(Boolean);
513
+ const sessionTargets = this._expandSignalSessionTargets(destinationJids);
514
+
515
+ if (sessionTargets.length) {
516
+ await this._ensureSignalSessions(sessionTargets, signalingTag === "offer");
517
+ }
518
+
519
+ const rootEnc = getBinaryNodeChild(voipNode, "enc");
520
+ const encCount = parseCountAttr(rootEnc?.attrs.count);
521
+ let includeDeviceIdentity = false;
522
+
523
+ for (const destNode of destinations) {
524
+ const targetJid = String(destNode.attrs.jid ?? "").trim();
525
+ const destEnc = getBinaryNodeChild(destNode, "enc");
526
+
527
+ if (!targetJid || !destEnc || !(destEnc.content instanceof Uint8Array)) continue;
528
+
529
+ try {
530
+ const encrypted = await this._encryptCallKey(targetJid, destEnc.content, encCount);
531
+ includeDeviceIdentity = includeDeviceIdentity || encrypted.shouldIncludeDeviceIdentity;
532
+ setNodeChildren(destNode, [encrypted.encNode]);
533
+ } catch (err) {
534
+ console.error("[RTC ENCRYPT DEST ERROR]", err?.message || err);
535
+ for (const destinationNode of destinations) removeNodeChildrenByTag(destinationNode, "enc");
536
+ break;
537
+ }
538
+ }
539
+
540
+ if (includeDeviceIdentity) this._appendDeviceIdentity(voipNode);
541
+
542
+ await this._sendCallStanza(this._toBareJid(peerJid), voipNode, signalingTag, effectivePeerJid, peerJid);
543
+ return;
544
+ }
545
+
546
+ if (signalingTag === "offer" || signalingTag === "enc_rekey") {
547
+ const enc = getBinaryNodeChild(voipNode, "enc");
548
+ if (enc && enc.content instanceof Uint8Array) {
549
+ const targetJid = this._toCallDeviceJid(effectivePeerJid);
550
+ const encrypted = await this._encryptCallKey(targetJid, enc.content, parseCountAttr(enc.attrs.count));
551
+ replaceNodeChild(voipNode, "enc", encrypted.encNode);
552
+ if (encrypted.shouldIncludeDeviceIdentity) this._appendDeviceIdentity(voipNode);
553
+ await this._sendCallStanza(targetJid, voipNode, signalingTag, effectivePeerJid, peerJid);
554
+ return;
555
+ }
556
+ }
557
+
558
+ const routeTo = signalingTag !== "offer" && signalingTag !== "enc_rekey"
559
+ ? this._toBareJid(effectivePeerJid)
560
+ : this._toCallDeviceJid(effectivePeerJid);
561
+
562
+ await this._sendCallStanza(routeTo, voipNode, signalingTag, effectivePeerJid, peerJid);
563
+ };
564
+
565
+ this._sendCallStanza = async (routeTo, voipNode, signalingTag, effectivePeerJid, callbackPeerJid) => {
566
+ const stanzaId = this._sock.generateMessageTag();
567
+ console.log("[RTC SEND CALL STANZA]", { to: routeTo, id: stanzaId, tag: signalingTag, peer: effectivePeerJid });
568
+
569
+ await this._sock.sendNode({
570
+ tag: "call",
571
+ attrs: { to: routeTo, id: stanzaId },
572
+ content: [voipNode]
573
+ });
574
+
575
+ void (async () => {
576
+ try {
577
+ if (typeof this._sock.waitForMessage !== "function") {
578
+ console.log("[RTC CALL ACK] waitForMessage not available");
579
+ return;
580
+ }
581
+ const ackNode = await this._sock.waitForMessage(stanzaId, ACK_TIMEOUT_MS);
582
+ console.log("[RTC CALL ACK]", ackNode?.attrs || null);
583
+ if (!ackNode || !this._voip) return;
584
+ if (typeof this._voip.isInitialized === "function" && !this._voip.isInitialized()) return;
585
+
586
+ const { encodeBinaryNode } = this._baileys;
587
+ const ackPayload = Buffer.from(encodeBinaryNode(ackNode)).toString("base64");
588
+ const tcToken = await this.ensureTcToken(effectivePeerJid, callbackPeerJid);
589
+
590
+ try {
591
+ this._voip.handleSignalingAck({
592
+ payload: ackPayload,
593
+ ackError: ackNode.attrs?.error ?? "0",
594
+ msgType: ackNode.attrs?.type ?? signalingTag,
595
+ peerJid: effectivePeerJid,
596
+ extraData: tcToken
597
+ });
598
+ } catch (err) {
599
+ console.error("[RTC HANDLE ACK ERROR]", err?.message || err);
600
+ }
601
+ } catch (err) {
602
+ console.error("[RTC WAIT ACK ERROR]", err?.message || err);
603
+ }
604
+ })();
605
+ };
606
+
607
+ this._doProcessIncomingCall = async (node, voip, activeCallId) => {
608
+ const { getAllBinaryNodeChildren, getBinaryNodeChild, encodeBinaryNode } = this._baileys;
609
+ const voipChild = getAllBinaryNodeChildren(node)[0];
610
+ if (!voipChild) return;
611
+
612
+ const incomingCallId = String(voipChild.attrs["call-id"] ?? voipChild.attrs.call_id ?? "");
613
+ const callIdForRouting = incomingCallId || activeCallId;
614
+ if (activeCallId && incomingCallId && incomingCallId !== activeCallId) return;
615
+
616
+ const senderDeviceJid = String(voipChild.attrs.participant ?? "") || String(node.attrs.participant ?? "") || String(node.attrs.from ?? "") || String(voipChild.attrs["call-creator"] ?? "");
617
+ const callbackPeerJid = String(node.attrs.from ?? "") || senderDeviceJid;
618
+ const platform = voipChild.attrs.platform ?? node.attrs.platform ?? "";
619
+ const appVersion = voipChild.attrs.version ?? node.attrs.version ?? "";
620
+ const epochId = voipChild.attrs.e ?? node.attrs.e ?? "0";
621
+ const timestamp = voipChild.attrs.t ?? node.attrs.t ?? "0";
622
+ const offline = !!(voipChild.attrs.offline ?? node.attrs.offline);
623
+ let usableNode = voipChild;
624
+
625
+ if (getBinaryNodeChild(voipChild, "enc")) {
626
+ usableNode = await this._maybeDecryptEnc(voipChild, senderDeviceJid);
627
+ }
628
+
629
+ const b64 = Buffer.from(encodeBinaryNode(usableNode)).toString("base64");
630
+ const storedPeerJid = callIdForRouting ? this._incomingCallPeerById.get(callIdForRouting) : undefined;
631
+ let mappedRemoteDeviceJid = callIdForRouting ? this._remoteDevicePeerByCallId.get(callIdForRouting) : undefined;
632
+
633
+ if (callIdForRouting && (callbackPeerJid || senderDeviceJid)) {
634
+ this._remoteXmppRoutePeerByCallId.set(callIdForRouting, callbackPeerJid || senderDeviceJid);
635
+ const hinted = this._pickConcreteRouteHint(senderDeviceJid, callbackPeerJid);
636
+ if (hinted && hinted !== mappedRemoteDeviceJid) {
637
+ mappedRemoteDeviceJid = hinted;
638
+ this._remoteDevicePeerByCallId.set(callIdForRouting, hinted);
639
+ }
640
+ }
641
+
642
+ const routedPeerJid = usableNode.tag === "offer"
643
+ ? this._preferDeviceRouteJid(senderDeviceJid, callbackPeerJid, storedPeerJid)
644
+ : this._preferOrderedRouteJid(mappedRemoteDeviceJid, storedPeerJid, senderDeviceJid, callbackPeerJid);
645
+
646
+ if (callIdForRouting && routedPeerJid) this._incomingCallPeerById.set(callIdForRouting, routedPeerJid);
647
+ const tcToken = await this.ensureTcToken(routedPeerJid, callbackPeerJid);
648
+
649
+ if (!voip || (typeof voip.isInitialized === "function" && !voip.isInitialized())) return;
650
+
651
+ switch (usableNode.tag) {
652
+ case "offer":
653
+ voip.handleSignalingOffer({ payload: b64, peerPlatform: Number(platform || 0), peerAppVersion: appVersion, epochId, timestamp, isOffline: offline, isOfferNotContact: false, peerJid: routedPeerJid, tcToken });
654
+ break;
655
+ case "ack":
656
+ voip.handleSignalingAck({ payload: b64, ackError: usableNode.attrs.error ?? "0", msgType: usableNode.attrs.type ?? "", peerJid: routedPeerJid, extraData: tcToken });
657
+ break;
658
+ default:
659
+ voip.handleSignalingMessage({ payload: b64, peerPlatform: platform, peerAppVersion: appVersion, epochId, timestamp, isOffline: offline, peerJid: routedPeerJid, tcToken });
660
+ if (callIdForRouting && (usableNode.tag === "terminate" || usableNode.tag === "reject")) {
661
+ this._incomingCallPeerById.delete(callIdForRouting);
662
+ this._remoteDevicePeerByCallId.delete(callIdForRouting);
663
+ this._remoteObfuscatedPeerByCallId.delete(callIdForRouting);
664
+ this._remoteXmppRoutePeerByCallId.delete(callIdForRouting);
665
+ }
666
+ break;
667
+ }
668
+ };
669
+
670
+ this._doProcessIncomingReceipt = async (node, voip, activeCallId) => {
671
+ const { getAllBinaryNodeChildren, encodeBinaryNode } = this._baileys;
672
+ const receiptChild = getAllBinaryNodeChildren(node)[0];
673
+ if (!receiptChild) return;
674
+ const incomingCallId = String(receiptChild.attrs["call-id"] ?? receiptChild.attrs.call_id ?? "");
675
+ const callIdForRouting = incomingCallId || activeCallId;
676
+ if (activeCallId && incomingCallId && incomingCallId !== activeCallId) return;
677
+ const callbackPeerJid = String(node.attrs.from ?? receiptChild.attrs["call-creator"] ?? "");
678
+ const storedPeerJid = callIdForRouting ? this._incomingCallPeerById.get(callIdForRouting) : undefined;
679
+ const routedPeerJid = this._preferOrderedRouteJid(storedPeerJid, callbackPeerJid);
680
+ if (callIdForRouting && routedPeerJid) this._incomingCallPeerById.set(callIdForRouting, routedPeerJid);
681
+ const tcToken = await this.ensureTcToken(routedPeerJid, callbackPeerJid);
682
+ if (!voip || (typeof voip.isInitialized === "function" && !voip.isInitialized())) return;
683
+ voip.handleSignalingReceipt({ payload: Buffer.from(encodeBinaryNode(node)).toString("base64"), peerJid: routedPeerJid, tcToken });
684
+ };
685
+
686
+ this._maybeDecryptEnc = async (voipNode, peerJid) => {
687
+ const { getBinaryNodeChild, unpadRandomMax16, proto } = this._baileys;
688
+ const enc = getBinaryNodeChild(voipNode, "enc");
689
+ if (!enc || !(enc.content instanceof Uint8Array)) return voipNode;
690
+ const type = enc.attrs.type;
691
+ if (type !== "pkmsg" && type !== "msg") return voipNode;
692
+ const candidates = [...new Set([peerJid, this._toCallDeviceJid(peerJid)])].filter(Boolean);
693
+ let lastErr;
694
+ for (const jid of candidates) {
695
+ try {
696
+ const decrypted = await this._sock.signalRepository.decryptMessage({ jid, type, ciphertext: enc.content });
697
+ const parsed = proto.Message.decode(unpadRandomMax16(decrypted));
698
+ const callKey = parsed.call?.callKey;
699
+ if (!callKey || callKey.length === 0) throw new Error("decrypted signaling has no call.callKey");
700
+ enc.content = callKey;
701
+ return voipNode;
702
+ } catch (err) { lastErr = err; }
703
+ }
704
+ throw lastErr;
705
+ };
706
+
707
+ this._encryptCallKey = async (targetJid, rawCallKey, count) => {
708
+ const { encodeWAMessage } = this._baileys;
709
+ const primaryDeviceJid = this._toPrimaryDeviceJid(targetJid);
710
+ const sessionTargets = primaryDeviceJid && primaryDeviceJid !== targetJid ? [primaryDeviceJid, targetJid] : [targetJid];
711
+ await this._ensureSignalSessions(sessionTargets, false);
712
+ const { type, ciphertext } = await this._sock.signalRepository.encryptMessage({
713
+ jid: targetJid,
714
+ data: encodeWAMessage({ call: { callKey: Buffer.from(rawCallKey) } })
715
+ });
716
+ return {
717
+ encNode: { tag: "enc", attrs: { v: "2", type, count: String(count) }, content: Buffer.from(ciphertext) },
718
+ shouldIncludeDeviceIdentity: type === "pkmsg"
719
+ };
720
+ };
721
+
722
+ this._ensureSignalSessions = async (jids, refresh) => {
723
+ const targets = [...new Set(jids.filter(Boolean).map(jid => this._toCallDeviceJid(jid)))];
724
+
725
+ if (!targets.length) {
726
+ return;
727
+ }
728
+
729
+ if (typeof this._sock.assertSessions === "function") {
730
+ try {
731
+ await this._sock.assertSessions(targets, refresh);
732
+ return;
733
+ } catch (err) {
734
+ console.error("[RTC ASSERT SESSIONS ERROR]", err?.message || err);
735
+ }
736
+ }
737
+
738
+ const { parseAndInjectE2ESessions } = this._baileys;
739
+ const missing = [];
740
+
741
+ for (const jid of targets) {
742
+ try {
743
+ const signalId = this._sock.signalRepository.jidToSignalProtocolAddress(jid);
744
+ const cachedAt = this._ensuredSignalSessions.get(signalId);
745
+
746
+ if (!refresh && cachedAt && Date.now() - cachedAt < SESSION_CACHE_TTL_MS) {
747
+ continue;
748
+ }
749
+
750
+ if (!refresh) {
751
+ const validation = await this._sock.signalRepository.validateSession(jid);
752
+
753
+ if (validation.exists) {
754
+ this._ensuredSignalSessions.set(signalId, Date.now());
755
+ continue;
756
+ }
757
+ }
758
+
759
+ missing.push(jid);
760
+ } catch {
761
+ missing.push(jid);
762
+ }
763
+ }
764
+
765
+ if (!missing.length) {
766
+ return;
767
+ }
768
+
769
+ try {
770
+ const sessionNode = await this._sock.query({
771
+ tag: "iq",
772
+ attrs: {
773
+ xmlns: "encrypt",
774
+ type: "get",
775
+ to: S_WHATSAPP_NET,
776
+ id: this._sock.generateMessageTag()
777
+ },
778
+ content: [
779
+ {
780
+ tag: "key",
781
+ attrs: {},
782
+ content: missing.map(jid => ({
783
+ tag: "user",
784
+ attrs: { jid }
785
+ }))
786
+ }
787
+ ]
788
+ });
789
+
790
+ await parseAndInjectE2ESessions(sessionNode, this._sock.signalRepository);
791
+
792
+ for (const jid of missing) {
793
+ try {
794
+ this._ensuredSignalSessions.set(
795
+ this._sock.signalRepository.jidToSignalProtocolAddress(jid),
796
+ Date.now()
797
+ );
798
+ } catch {}
799
+ }
800
+ } catch (err) {
801
+ console.error("[RTC ENSURE SIGNAL SESSION ERROR]", {
802
+ message: err?.message || String(err),
803
+ targets: missing
804
+ });
805
+
806
+ if (
807
+ String(err?.message || err).toLowerCase().includes("connection closed") ||
808
+ String(err?.message || err).toLowerCase().includes("socket")
809
+ ) {
810
+ return;
811
+ }
812
+
813
+ throw err;
814
+ }
815
+ };
816
+
817
+ this._appendDeviceIdentity = voipNode => {
818
+ const { getBinaryNodeChild, encodeSignedDeviceIdentity } = this._baileys;
819
+ if (getBinaryNodeChild(voipNode, "device-identity")) return;
820
+ const account = this._sock.authState.creds.account;
821
+ if (!account) return;
822
+ const children = getNodeChildren(voipNode);
823
+ children.push({ tag: "device-identity", attrs: {}, content: encodeSignedDeviceIdentity(account, true) });
824
+ setNodeChildren(voipNode, children);
825
+ };
826
+
827
+ this._toBareJid = jid => {
828
+ const { jidDecode, jidEncode } = this._baileys;
829
+ const decoded = jidDecode(jid);
830
+ if (!decoded?.user) return jid;
831
+ const server = String(jid).endsWith("@lid") ? "lid" : "s.whatsapp.net";
832
+ return jidEncode(decoded.user, server);
833
+ };
834
+
835
+ this._toCallDeviceJid = jid => {
836
+ const { jidDecode } = this._baileys;
837
+ const decoded = jidDecode(jid);
838
+ if (!decoded?.user) return jid;
839
+ const server = String(jid).endsWith("@lid") ? "lid" : "s.whatsapp.net";
840
+ if (decoded.device === undefined || decoded.device === null) return `${decoded.user}:0@${server}`;
841
+ return `${decoded.user}:${decoded.device}@${server}`;
842
+ };
843
+
844
+ this._toPrimaryDeviceJid = jid => {
845
+ const { jidDecode } = this._baileys;
846
+ const decoded = jidDecode(jid);
847
+ if (!decoded?.user) return undefined;
848
+ const device = decoded.device;
849
+ if (device == null || device === 0) return undefined;
850
+ const server = String(jid).endsWith("@lid") ? "lid" : "s.whatsapp.net";
851
+ return `${decoded.user}:0@${server}`;
852
+ };
853
+
854
+ this._hasConcreteDevice = jid => {
855
+ const decoded = this._baileys.jidDecode(jid);
856
+ return !!decoded?.user && decoded.device != null;
857
+ };
858
+
859
+ this._preferDeviceRouteJid = (...candidates) => {
860
+ for (const candidate of candidates) {
861
+ const jid = String(candidate ?? "").trim();
862
+ if (jid && this._hasConcreteDevice(jid)) return jid;
863
+ }
864
+ for (const candidate of candidates) {
865
+ const jid = String(candidate ?? "").trim();
866
+ if (jid) return this._toCallDeviceJid(jid);
867
+ }
868
+ return "";
869
+ };
870
+
871
+ this._preferOrderedRouteJid = (...candidates) => {
872
+ for (const candidate of candidates) {
873
+ const jid = String(candidate ?? "").trim();
874
+ if (jid) return this._toCallDeviceJid(jid);
875
+ }
876
+ return "";
877
+ };
878
+
879
+ this._pickConcreteRouteHint = (...candidates) => {
880
+ for (const candidate of candidates) {
881
+ const jid = String(candidate ?? "").trim();
882
+ if (jid && this._hasConcreteDevice(jid)) return jid;
883
+ }
884
+ return "";
885
+ };
886
+
887
+ this._resolveOutboundPeerJid = (callId, wasmPeerJid) => {
888
+ const peerJid = String(wasmPeerJid ?? "").trim();
889
+ if (!peerJid || !callId) return peerJid;
890
+ return this._remoteDevicePeerByCallId.get(callId) ?? peerJid;
891
+ };
892
+
893
+ this._expandSignalSessionTargets = jids => [
894
+ ...new Set(jids.flatMap(jid => {
895
+ const primary = this._toPrimaryDeviceJid(jid);
896
+ return primary && primary !== jid ? [primary, jid] : [jid];
897
+ }))
898
+ ];
899
+
900
+ this._normalizeStartCallPeerList = jids => {
901
+ const { jidDecode } = this._baileys;
902
+ const result = new Set();
903
+ for (const jid of jids) {
904
+ const value = String(jid || "").trim();
905
+ if (!value) continue;
906
+ const decoded = jidDecode(value);
907
+ if (!decoded?.user) {
908
+ result.add(value);
909
+ continue;
910
+ }
911
+ const server = value.endsWith("@lid") ? "lid" : "s.whatsapp.net";
912
+ result.add(`${decoded.user}:0@${server}`);
913
+ if (decoded.device !== undefined && decoded.device !== null) result.add(`${decoded.user}:${decoded.device}@${server}`);
914
+ }
915
+ return [...result].slice(0, 5);
916
+ };
917
+
918
+ this._findTcTokenNodes = node => {
919
+ const result = [];
920
+
921
+ const walk = item => {
922
+ if (!item) return;
923
+
924
+ if (Array.isArray(item)) {
925
+ for (const child of item) walk(child);
926
+ return;
927
+ }
928
+
929
+ if (typeof item !== "object") return;
930
+
931
+ if (
932
+ item.tag === "token" &&
933
+ (item.attrs?.type === "trusted_contact" || item.attrs?.type === undefined) &&
934
+ item.content instanceof Uint8Array &&
935
+ item.content.length > 0
936
+ ) {
937
+ result.push(item);
938
+ }
939
+
940
+ if (Array.isArray(item.content)) {
941
+ for (const child of item.content) walk(child);
942
+ }
943
+ };
944
+
945
+ walk(node);
946
+ return result;
947
+ };
948
+
949
+ this._processPrivacyTokenNotification = node => {
950
+ const { getAllBinaryNodeChildren, getBinaryNodeChildren } = this._baileys;
951
+ const child = getAllBinaryNodeChildren(node)[0];
952
+ const tokenNodes = child ? getBinaryNodeChildren(child, "token") : [];
953
+
954
+ for (const tokenNode of tokenNodes) {
955
+ const jid = String(tokenNode.attrs?.jid || node.attrs?.from || "");
956
+ const content = tokenNode.content;
957
+
958
+ if (jid && content instanceof Uint8Array && content.length > 0) {
959
+ console.log("[RTC TC TOKEN FROM RAW NOTIFICATION]", {
960
+ jid,
961
+ length: content.length
962
+ });
963
+
964
+ this._storeTcToken(jid, Buffer.from(content), String(tokenNode.attrs?.t ?? Math.floor(Date.now() / 1000))).catch(() => {});
965
+ }
966
+ }
967
+ };
968
+
969
+ this._getTcTokenCandidateJids = async jid => {
970
+ const result = new Set();
971
+ const bare = this._toBareJid(jid);
972
+
973
+ if (bare) result.add(bare);
974
+
975
+ try {
976
+ const lid = await this._sock.signalRepository?.lidMapping?.getLIDForPN?.(bare);
977
+ if (lid) result.add(this._toBareJid(lid));
978
+ } catch {}
979
+
980
+ try {
981
+ const pn = await this._sock.signalRepository?.lidMapping?.getPNForLID?.(bare);
982
+ if (pn) result.add(this._toBareJid(pn));
983
+ } catch {}
984
+
985
+ return [...result].filter(Boolean);
986
+ };
987
+
988
+ this._storeTcToken = async (jid, token, timestamp = "") => {
989
+ const candidates = await this._getTcTokenCandidateJids(jid);
990
+
991
+ if (!candidates.length) candidates.push(this._toBareJid(jid));
992
+
993
+ const write = {};
994
+
995
+ for (const storageJid of candidates) {
996
+ if (!storageJid) continue;
997
+ write[storageJid] = {
998
+ token: Buffer.from(token),
999
+ timestamp: String(timestamp || Math.floor(Date.now() / 1000))
1000
+ };
1001
+
1002
+ this._rememberTcToken(storageJid, token, timestamp);
1003
+ }
1004
+
1005
+ try {
1006
+ if (Object.keys(write).length) {
1007
+ await this._sock.authState.keys.set({ tctoken: write });
1008
+ }
1009
+ } catch {}
1010
+
1011
+ return Buffer.from(token);
1012
+ };
1013
+
1014
+ this._waitForTcToken = async (jid, timeoutMs = TC_TOKEN_REQUEST_TIMEOUT_MS) => {
1015
+ const candidates = await this._getTcTokenCandidateJids(jid);
1016
+
1017
+ return new Promise(resolve => {
1018
+ const timer = setTimeout(() => {
1019
+ for (const candidate of candidates) {
1020
+ const waiters = this._pendingTcTokenWaiters.get(candidate);
1021
+ if (!waiters) continue;
1022
+ this._pendingTcTokenWaiters.set(candidate, waiters.filter(fn => fn !== done));
1023
+ }
1024
+
1025
+ const anyWaiters = this._pendingTcTokenWaiters.get("*");
1026
+ if (anyWaiters) {
1027
+ this._pendingTcTokenWaiters.set("*", anyWaiters.filter(fn => fn !== done));
1028
+ }
1029
+
1030
+ resolve(undefined);
1031
+ }, timeoutMs);
1032
+
1033
+ const done = token => {
1034
+ clearTimeout(timer);
1035
+ resolve(Buffer.from(token));
1036
+ };
1037
+
1038
+ for (const candidate of candidates) {
1039
+ const waiters = this._pendingTcTokenWaiters.get(candidate) || [];
1040
+ waiters.push(done);
1041
+ this._pendingTcTokenWaiters.set(candidate, waiters);
1042
+ }
1043
+
1044
+ const anyWaiters = this._pendingTcTokenWaiters.get("*") || [];
1045
+ anyWaiters.push(done);
1046
+ this._pendingTcTokenWaiters.set("*", anyWaiters);
1047
+ });
1048
+ };
1049
+
1050
+ this._rememberTcToken = (jid, token, timestamp = "") => {
1051
+ const bareJid = this._toBareJid(jid);
1052
+ if (!token?.length) return;
1053
+
1054
+ this._observedTcTokens.set(bareJid, {
1055
+ token: Buffer.from(token),
1056
+ timestamp
1057
+ });
1058
+
1059
+ const notify = key => {
1060
+ const waiters = this._pendingTcTokenWaiters.get(key);
1061
+ if (waiters?.length) {
1062
+ this._pendingTcTokenWaiters.delete(key);
1063
+ for (const waiter of waiters) waiter(Buffer.from(token));
1064
+ }
1065
+ };
1066
+
1067
+ notify(bareJid);
1068
+ notify("*");
1069
+ };
1070
+
1071
+ this._getTcToken = async jid => {
1072
+ const candidates = await this._getTcTokenCandidateJids(jid);
1073
+
1074
+ for (const candidate of candidates) {
1075
+ const observed = this._observedTcTokens.get(candidate)?.token;
1076
+ if (observed?.length) return Buffer.from(observed);
1077
+ }
1078
+
1079
+ try {
1080
+ const data = await this._sock.authState.keys.get("tctoken", candidates);
1081
+
1082
+ for (const candidate of candidates) {
1083
+ const token = data[candidate]?.token;
1084
+ if (token && token.length > 0) {
1085
+ this._rememberTcToken(candidate, token, data[candidate]?.timestamp);
1086
+ return Buffer.from(token);
1087
+ }
1088
+ }
1089
+ } catch {}
1090
+
1091
+ return undefined;
1092
+ };
1093
+ }
1094
+ }
1095
+
1096
+ exports.SignalingBridge = SignalingBridge;
1097
+ exports.default = SignalingBridge;
1098
+
1099
+ module.exports = SignalingBridge;
1100
+ module.exports.SignalingBridge = SignalingBridge;
1101
+ module.exports.default = SignalingBridge;
1102
+ Object.defineProperty(module.exports, "__esModule", { value: true });