@pontalabs/baileys 1.0.4 → 1.0.6

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 (447) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +267 -839
  3. package/WAProto/GenerateStatics.sh +3 -4
  4. package/WAProto/WAProto.proto +1215 -511
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14017 -55
  7. package/WAProto/index.js +97689 -29
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +72 -74
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +94 -108
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +8 -7
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +9 -16
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +11 -13
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +19 -61
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +14 -16
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +41 -70
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -11
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -61
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +9 -14
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +10 -58
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +13 -13
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +13 -34
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -16
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +28 -36
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +18 -18
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +38 -45
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +14 -15
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +20 -31
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +24 -25
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +18 -35
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +29 -34
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +37 -100
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +11 -10
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +15 -22
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -8
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +279 -121
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +23 -28
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +277 -184
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -2
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -22
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +15 -15
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +8 -15
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +12 -12
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +29 -37
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +208 -178
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +91 -127
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +120 -93
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +727 -652
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +273 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +431 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/dugong.js +261 -0
  94. package/lib/Socket/dugong.js.bak +204 -0
  95. package/lib/Socket/groups.d.ts +143 -111
  96. package/lib/Socket/groups.d.ts.map +1 -0
  97. package/lib/Socket/groups.js +165 -177
  98. package/lib/Socket/groups.js.map +1 -0
  99. package/lib/Socket/index.d.ts +252 -183
  100. package/lib/Socket/index.d.ts.map +1 -0
  101. package/lib/Socket/index.js +38 -18
  102. package/lib/Socket/index.js.bak +44 -0
  103. package/lib/Socket/index.js.map +1 -0
  104. package/lib/Socket/messages-recv.d.ts +196 -167
  105. package/lib/Socket/messages-recv.d.ts.map +1 -0
  106. package/lib/Socket/messages-recv.js +1443 -1563
  107. package/lib/Socket/messages-recv.js.map +1 -0
  108. package/lib/Socket/messages-send.d.ts +192 -158
  109. package/lib/Socket/messages-send.d.ts.map +1 -0
  110. package/lib/Socket/messages-send.js +1102 -1208
  111. package/lib/Socket/messages-send.js.bak +1400 -0
  112. package/lib/Socket/messages-send.js.map +1 -0
  113. package/lib/Socket/mex.d.ts +3 -0
  114. package/lib/Socket/mex.d.ts.map +1 -0
  115. package/lib/Socket/mex.js +42 -0
  116. package/lib/Socket/mex.js.map +1 -0
  117. package/lib/Socket/newsletter.d.ts +163 -138
  118. package/lib/Socket/newsletter.d.ts.map +1 -0
  119. package/lib/Socket/newsletter.js +153 -249
  120. package/lib/Socket/newsletter.js.map +1 -0
  121. package/lib/Socket/socket.d.ts +50 -36
  122. package/lib/Socket/socket.d.ts.map +1 -0
  123. package/lib/Socket/socket.js +749 -820
  124. package/lib/Socket/socket.js.map +1 -0
  125. package/lib/Store/index.d.ts +4 -4
  126. package/lib/Store/index.d.ts.map +1 -0
  127. package/lib/Store/index.js +4 -24
  128. package/lib/Store/index.js.map +1 -0
  129. package/lib/Store/make-in-memory-store.d.ts +44 -104
  130. package/lib/Store/make-in-memory-store.d.ts.map +1 -0
  131. package/lib/Store/make-in-memory-store.js +199 -213
  132. package/lib/Store/make-in-memory-store.js.map +1 -0
  133. package/lib/Store/make-ordered-dictionary.d.ts +13 -12
  134. package/lib/Store/make-ordered-dictionary.d.ts.map +1 -0
  135. package/lib/Store/make-ordered-dictionary.js +38 -45
  136. package/lib/Store/make-ordered-dictionary.js.map +1 -0
  137. package/lib/Store/object-repository.d.ts +11 -10
  138. package/lib/Store/object-repository.d.ts.map +1 -0
  139. package/lib/Store/object-repository.js +9 -16
  140. package/lib/Store/object-repository.js.map +1 -0
  141. package/lib/Types/Auth.d.ts +93 -97
  142. package/lib/Types/Auth.d.ts.map +1 -0
  143. package/lib/Types/Auth.js +2 -3
  144. package/lib/Types/Auth.js.map +1 -0
  145. package/lib/Types/Bussines.d.ts +25 -0
  146. package/lib/Types/Bussines.d.ts.map +1 -0
  147. package/lib/Types/Bussines.js +2 -3
  148. package/lib/Types/Bussines.js.map +1 -0
  149. package/lib/Types/Call.d.ts +14 -13
  150. package/lib/Types/Call.d.ts.map +1 -0
  151. package/lib/Types/Call.js +2 -3
  152. package/lib/Types/Call.js.map +1 -0
  153. package/lib/Types/Chat.d.ts +78 -97
  154. package/lib/Types/Chat.d.ts.map +1 -0
  155. package/lib/Types/Chat.js +8 -9
  156. package/lib/Types/Chat.js.map +1 -0
  157. package/lib/Types/Contact.d.ts +12 -9
  158. package/lib/Types/Contact.d.ts.map +1 -0
  159. package/lib/Types/Contact.js +2 -3
  160. package/lib/Types/Contact.js.map +1 -0
  161. package/lib/Types/Events.d.ts +206 -176
  162. package/lib/Types/Events.d.ts.map +1 -0
  163. package/lib/Types/Events.js +2 -3
  164. package/lib/Types/Events.js.map +1 -0
  165. package/lib/Types/GroupMetadata.d.ts +53 -48
  166. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  167. package/lib/Types/GroupMetadata.js +2 -3
  168. package/lib/Types/GroupMetadata.js.map +1 -0
  169. package/lib/Types/Label.d.ts +13 -14
  170. package/lib/Types/Label.d.ts.map +1 -0
  171. package/lib/Types/Label.js +24 -30
  172. package/lib/Types/Label.js.map +1 -0
  173. package/lib/Types/LabelAssociation.d.ts +15 -20
  174. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  175. package/lib/Types/LabelAssociation.js +6 -12
  176. package/lib/Types/LabelAssociation.js.map +1 -0
  177. package/lib/Types/Message.d.ts +248 -412
  178. package/lib/Types/Message.d.ts.map +1 -0
  179. package/lib/Types/Message.js +17 -19
  180. package/lib/Types/Message.js.map +1 -0
  181. package/lib/Types/Mex.d.ts +141 -0
  182. package/lib/Types/Mex.d.ts.map +1 -0
  183. package/lib/Types/Mex.js +37 -0
  184. package/lib/Types/Mex.js.map +1 -0
  185. package/lib/Types/Product.d.ts +58 -71
  186. package/lib/Types/Product.d.ts.map +1 -0
  187. package/lib/Types/Product.js +2 -3
  188. package/lib/Types/Product.js.map +1 -0
  189. package/lib/Types/RichType.d.ts +3 -0
  190. package/lib/Types/RichType.d.ts.map +1 -0
  191. package/lib/Types/RichType.js +23 -0
  192. package/lib/Types/RichType.js.bak +23 -0
  193. package/lib/Types/RichType.js.map +1 -0
  194. package/lib/Types/Signal.d.ts +71 -82
  195. package/lib/Types/Signal.d.ts.map +1 -0
  196. package/lib/Types/Signal.js +2 -3
  197. package/lib/Types/Signal.js.map +1 -0
  198. package/lib/Types/Socket.d.ts +76 -81
  199. package/lib/Types/Socket.d.ts.map +1 -0
  200. package/lib/Types/Socket.js +3 -3
  201. package/lib/Types/Socket.js.map +1 -0
  202. package/lib/Types/State.d.ts +75 -19
  203. package/lib/Types/State.d.ts.map +1 -0
  204. package/lib/Types/State.js +56 -14
  205. package/lib/Types/State.js.map +1 -0
  206. package/lib/Types/USync.d.ts +8 -8
  207. package/lib/Types/USync.d.ts.map +1 -0
  208. package/lib/Types/USync.js +2 -3
  209. package/lib/Types/USync.js.map +1 -0
  210. package/lib/Types/index.d.ts +47 -62
  211. package/lib/Types/index.d.ts.map +1 -0
  212. package/lib/Types/index.js +26 -50
  213. package/lib/Types/index.js.map +1 -0
  214. package/lib/Utils/auth-utils.d.ts +13 -10
  215. package/lib/Utils/auth-utils.d.ts.map +1 -0
  216. package/lib/Utils/auth-utils.js +213 -454
  217. package/lib/Utils/auth-utils.js.map +1 -0
  218. package/lib/Utils/browser-utils.d.ts +4 -0
  219. package/lib/Utils/browser-utils.d.ts.map +1 -0
  220. package/lib/Utils/browser-utils.js +28 -0
  221. package/lib/Utils/browser-utils.js.map +1 -0
  222. package/lib/Utils/business.d.ts +14 -20
  223. package/lib/Utils/business.d.ts.map +1 -0
  224. package/lib/Utils/business.js +110 -134
  225. package/lib/Utils/business.js.map +1 -0
  226. package/lib/Utils/chat-utils.d.ts +88 -70
  227. package/lib/Utils/chat-utils.d.ts.map +1 -0
  228. package/lib/Utils/chat-utils.js +466 -403
  229. package/lib/Utils/chat-utils.js.map +1 -0
  230. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  231. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  232. package/lib/Utils/companion-reg-client-utils.js +35 -0
  233. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  234. package/lib/Utils/crypto.d.ts +27 -46
  235. package/lib/Utils/crypto.d.ts.map +1 -0
  236. package/lib/Utils/crypto.js +117 -188
  237. package/lib/Utils/crypto.js.map +1 -0
  238. package/lib/Utils/decode-wa-message.d.ts +58 -45
  239. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  240. package/lib/Utils/decode-wa-message.js +213 -303
  241. package/lib/Utils/decode-wa-message.js.map +1 -0
  242. package/lib/Utils/event-buffer.d.ts +14 -17
  243. package/lib/Utils/event-buffer.d.ts.map +1 -0
  244. package/lib/Utils/event-buffer.js +321 -296
  245. package/lib/Utils/event-buffer.js.map +1 -0
  246. package/lib/Utils/generics.d.ts +66 -92
  247. package/lib/Utils/generics.d.ts.map +1 -0
  248. package/lib/Utils/generics.js +270 -436
  249. package/lib/Utils/generics.js.map +1 -0
  250. package/lib/Utils/history.d.ts +24 -23
  251. package/lib/Utils/history.d.ts.map +1 -0
  252. package/lib/Utils/history.js +106 -76
  253. package/lib/Utils/history.js.map +1 -0
  254. package/lib/Utils/identity-change-handler.d.ts +44 -0
  255. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  256. package/lib/Utils/identity-change-handler.js +50 -0
  257. package/lib/Utils/identity-change-handler.js.map +1 -0
  258. package/lib/Utils/index.d.ts +24 -21
  259. package/lib/Utils/index.d.ts.map +1 -0
  260. package/lib/Utils/index.js +24 -41
  261. package/lib/Utils/index.js.map +1 -0
  262. package/lib/Utils/link-preview.d.ts +12 -14
  263. package/lib/Utils/link-preview.d.ts.map +1 -0
  264. package/lib/Utils/link-preview.js +40 -75
  265. package/lib/Utils/link-preview.js.map +1 -0
  266. package/lib/Utils/logger.d.ts +10 -11
  267. package/lib/Utils/logger.d.ts.map +1 -0
  268. package/lib/Utils/logger.js +3 -7
  269. package/lib/Utils/logger.js.map +1 -0
  270. package/lib/Utils/lt-hash.d.ts +8 -14
  271. package/lib/Utils/lt-hash.d.ts.map +1 -0
  272. package/lib/Utils/lt-hash.js +3 -53
  273. package/lib/Utils/lt-hash.js.map +1 -0
  274. package/lib/Utils/make-mutex.d.ts +7 -7
  275. package/lib/Utils/make-mutex.d.ts.map +1 -0
  276. package/lib/Utils/make-mutex.js +28 -44
  277. package/lib/Utils/make-mutex.js.map +1 -0
  278. package/lib/Utils/message-retry-manager.d.ts +115 -88
  279. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  280. package/lib/Utils/message-retry-manager.js +265 -160
  281. package/lib/Utils/message-retry-manager.js.map +1 -0
  282. package/lib/Utils/messages-media.d.ts +105 -107
  283. package/lib/Utils/messages-media.d.ts.map +1 -0
  284. package/lib/Utils/messages-media.js +548 -619
  285. package/lib/Utils/messages-media.js.bak +786 -0
  286. package/lib/Utils/messages-media.js.map +1 -0
  287. package/lib/Utils/messages.d.ts +52 -66
  288. package/lib/Utils/messages.d.ts.map +1 -0
  289. package/lib/Utils/messages.js +1730 -1558
  290. package/lib/Utils/messages.js.backup +1768 -0
  291. package/lib/Utils/messages.js.bak +1809 -0
  292. package/lib/Utils/messages.js.bak2 +893 -0
  293. package/lib/Utils/messages.js.bak3 +1183 -0
  294. package/lib/Utils/messages.js.map +1 -0
  295. package/lib/Utils/noise-handler.d.ts +18 -18
  296. package/lib/Utils/noise-handler.d.ts.map +1 -0
  297. package/lib/Utils/noise-handler.js +176 -130
  298. package/lib/Utils/noise-handler.js.map +1 -0
  299. package/lib/Utils/offline-node-processor.d.ts +17 -0
  300. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  301. package/lib/Utils/offline-node-processor.js +40 -0
  302. package/lib/Utils/offline-node-processor.js.map +1 -0
  303. package/lib/Utils/pre-key-manager.d.ts +28 -0
  304. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  305. package/lib/Utils/pre-key-manager.js +106 -0
  306. package/lib/Utils/pre-key-manager.js.map +1 -0
  307. package/lib/Utils/process-message.d.ts +43 -32
  308. package/lib/Utils/process-message.d.ts.map +1 -0
  309. package/lib/Utils/process-message.js +484 -282
  310. package/lib/Utils/process-message.js.map +1 -0
  311. package/lib/Utils/reporting-utils.d.ts +11 -0
  312. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  313. package/lib/Utils/reporting-utils.js +258 -0
  314. package/lib/Utils/reporting-utils.js.map +1 -0
  315. package/lib/Utils/rich-message-utils.d.ts +49 -0
  316. package/lib/Utils/rich-message-utils.d.ts.map +1 -0
  317. package/lib/Utils/rich-message-utils.js +1220 -724
  318. package/lib/Utils/rich-message-utils.js.backup +706 -0
  319. package/lib/Utils/rich-message-utils.js.bak +246 -0
  320. package/lib/Utils/rich-message-utils.js.map +1 -0
  321. package/lib/Utils/rich-message-utils.js.original +1332 -0
  322. package/lib/Utils/signal.d.ts +37 -32
  323. package/lib/Utils/signal.d.ts.map +1 -0
  324. package/lib/Utils/signal.js +140 -105
  325. package/lib/Utils/signal.js.map +1 -0
  326. package/lib/Utils/stanza-ack.d.ts +11 -0
  327. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  328. package/lib/Utils/stanza-ack.js +38 -0
  329. package/lib/Utils/stanza-ack.js.map +1 -0
  330. package/lib/Utils/sync-action-utils.d.ts +19 -0
  331. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  332. package/lib/Utils/sync-action-utils.js +49 -0
  333. package/lib/Utils/sync-action-utils.js.map +1 -0
  334. package/lib/Utils/tc-token-utils.d.ts +37 -0
  335. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  336. package/lib/Utils/tc-token-utils.js +163 -0
  337. package/lib/Utils/tc-token-utils.js.map +1 -0
  338. package/lib/Utils/use-multi-file-auth-state.d.ts +5 -5
  339. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  340. package/lib/Utils/use-multi-file-auth-state.js +70 -120
  341. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  342. package/lib/Utils/use-single-file-auth-state.d.ts +11 -13
  343. package/lib/Utils/use-single-file-auth-state.d.ts.map +1 -0
  344. package/lib/Utils/use-single-file-auth-state.js +92 -66
  345. package/lib/Utils/use-single-file-auth-state.js.map +1 -0
  346. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  347. package/lib/Utils/use-sqlite-auth-state.d.ts.map +1 -0
  348. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  349. package/lib/Utils/use-sqlite-auth-state.js.map +1 -0
  350. package/lib/Utils/validate-connection.d.ts +11 -13
  351. package/lib/Utils/validate-connection.d.ts.map +1 -0
  352. package/lib/Utils/validate-connection.js +128 -113
  353. package/lib/Utils/validate-connection.js.map +1 -0
  354. package/lib/WABinary/constants.d.ts +25 -27
  355. package/lib/WABinary/constants.d.ts.map +1 -0
  356. package/lib/WABinary/constants.js +1451 -1292
  357. package/lib/WABinary/constants.js.bak +1373 -0
  358. package/lib/WABinary/constants.js.map +1 -0
  359. package/lib/WABinary/decode.d.ts +7 -9
  360. package/lib/WABinary/decode.d.ts.map +1 -0
  361. package/lib/WABinary/decode.js +163 -189
  362. package/lib/WABinary/decode.js.map +1 -0
  363. package/lib/WABinary/encode.d.ts +3 -3
  364. package/lib/WABinary/encode.d.ts.map +1 -0
  365. package/lib/WABinary/encode.js +110 -155
  366. package/lib/WABinary/encode.js.map +1 -0
  367. package/lib/WABinary/generic-utils.d.ts +14 -27
  368. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  369. package/lib/WABinary/generic-utils.js +177 -105
  370. package/lib/WABinary/generic-utils.js.map +1 -0
  371. package/lib/WABinary/index.d.ts +6 -5
  372. package/lib/WABinary/index.d.ts.map +1 -0
  373. package/lib/WABinary/index.js +6 -25
  374. package/lib/WABinary/index.js.map +1 -0
  375. package/lib/WABinary/jid-utils.d.ts +41 -51
  376. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  377. package/lib/WABinary/jid-utils.js +83 -120
  378. package/lib/WABinary/jid-utils.js.map +1 -0
  379. package/lib/WABinary/types.d.ts +10 -13
  380. package/lib/WABinary/types.d.ts.map +1 -0
  381. package/lib/WABinary/types.js +2 -3
  382. package/lib/WABinary/types.js.map +1 -0
  383. package/lib/WAM/BinaryInfo.d.ts +8 -15
  384. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  385. package/lib/WAM/BinaryInfo.js +7 -14
  386. package/lib/WAM/BinaryInfo.js.map +1 -0
  387. package/lib/WAM/constants.d.ts +30 -37
  388. package/lib/WAM/constants.d.ts.map +1 -0
  389. package/lib/WAM/constants.js +19193 -11711
  390. package/lib/WAM/constants.js.map +1 -0
  391. package/lib/WAM/encode.d.ts +3 -3
  392. package/lib/WAM/encode.d.ts.map +1 -0
  393. package/lib/WAM/encode.js +95 -109
  394. package/lib/WAM/encode.js.map +1 -0
  395. package/lib/WAM/index.d.ts +4 -3
  396. package/lib/WAM/index.d.ts.map +1 -0
  397. package/lib/WAM/index.js +4 -23
  398. package/lib/WAM/index.js.map +1 -0
  399. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -9
  400. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  401. package/lib/WAUSync/Protocols/USyncContactProtocol.js +37 -21
  402. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  403. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +19 -22
  404. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  405. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +18 -26
  406. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  407. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +11 -12
  408. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  409. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -20
  410. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  411. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +11 -12
  412. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  413. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +16 -24
  414. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  415. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  416. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  417. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  418. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  419. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  420. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  421. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  422. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  423. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  424. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  425. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  426. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  427. package/lib/WAUSync/Protocols/index.d.ts +6 -6
  428. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  429. package/lib/WAUSync/Protocols/index.js +6 -26
  430. package/lib/WAUSync/Protocols/index.js.map +1 -0
  431. package/lib/WAUSync/USyncQuery.d.ts +27 -28
  432. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  433. package/lib/WAUSync/USyncQuery.js +68 -62
  434. package/lib/WAUSync/USyncQuery.js.map +1 -0
  435. package/lib/WAUSync/USyncUser.d.ts +15 -10
  436. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  437. package/lib/WAUSync/USyncUser.js +20 -19
  438. package/lib/WAUSync/USyncUser.js.map +1 -0
  439. package/lib/WAUSync/index.d.ts +4 -3
  440. package/lib/WAUSync/index.d.ts.map +1 -0
  441. package/lib/WAUSync/index.js +4 -23
  442. package/lib/WAUSync/index.js.map +1 -0
  443. package/lib/index.d.ts +11 -12
  444. package/lib/index.d.ts.map +1 -0
  445. package/lib/index.js +12 -39
  446. package/lib/index.js.map +1 -0
  447. package/package.json +86 -42
@@ -1,527 +1,290 @@
1
- "use strict"
2
-
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod }
5
- }
6
-
7
- Object.defineProperty(exports, "__esModule", { value: true })
8
-
9
- const crypto_1 = require("crypto")
10
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"))
11
- const Defaults_1 = require("../Defaults")
12
- const LRUCache_1 = require("lru-cache")
13
- const crypto_2 = require("./crypto")
14
- const generics_1 = require("./generics")
15
- const mutex_1 = require("async-mutex")
16
-
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { AsyncLocalStorage } from 'async_hooks';
4
+ import { Mutex } from 'async-mutex';
5
+ import { randomBytes } from 'crypto';
6
+ import PQueue from 'p-queue';
7
+ import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js';
8
+ import { Curve, signedKeyPair } from './crypto.js';
9
+ import { delay, generateRegistrationId } from './generics.js';
10
+ import { PreKeyManager } from './pre-key-manager.js';
17
11
  /**
18
12
  * Adds caching capability to a SignalKeyStore
19
13
  * @param store the store to add caching to
20
14
  * @param logger to log trace events
21
15
  * @param _cache cache store to use
22
16
  */
23
- function makeCacheableSignalKeyStore(store, logger, _cache) {
24
- const cache = _cache || new node_cache_1.default({
25
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
26
- useClones: false,
27
- deleteOnExpire: true,
28
- })
29
-
17
+ export function makeCacheableSignalKeyStore(store, logger, _cache) {
18
+ const cache = _cache ||
19
+ new NodeCache({
20
+ stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
21
+ useClones: false,
22
+ deleteOnExpire: true
23
+ });
30
24
  // Mutex for protecting cache operations
31
- const cacheMutex = new mutex_1.Mutex()
32
-
25
+ const cacheMutex = new Mutex();
33
26
  function getUniqueId(type, id) {
34
- return `${type}.${id}`
27
+ return `${type}.${id}`;
35
28
  }
36
29
  return {
37
30
  async get(type, ids) {
38
31
  return cacheMutex.runExclusive(async () => {
39
- const data = {}
40
- const idsToFetch = []
32
+ const data = {};
33
+ const idsToFetch = [];
41
34
  for (const id of ids) {
42
- const item = cache.get(getUniqueId(type, id))
35
+ const item = (await cache.get(getUniqueId(type, id)));
43
36
  if (typeof item !== 'undefined') {
44
- data[id] = item
37
+ data[id] = item;
45
38
  }
46
39
  else {
47
- idsToFetch.push(id)
40
+ idsToFetch.push(id);
48
41
  }
49
42
  }
50
43
  if (idsToFetch.length) {
51
- logger?.trace({ items: idsToFetch.length }, 'loading from store')
52
- const fetched = await store.get(type, idsToFetch)
44
+ logger?.trace({ items: idsToFetch.length }, 'loading from store');
45
+ const fetched = await store.get(type, idsToFetch);
53
46
  for (const id of idsToFetch) {
54
- const item = fetched[id]
47
+ const item = fetched[id];
55
48
  if (item) {
56
- data[id] = item
57
- cache.set(getUniqueId(type, id), item)
49
+ data[id] = item;
50
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
51
+ await cache.set(getUniqueId(type, id), item);
58
52
  }
59
53
  }
60
54
  }
61
- return data
62
- })
55
+ return data;
56
+ });
63
57
  },
64
58
  async set(data) {
65
59
  return cacheMutex.runExclusive(async () => {
66
- let keys = 0
60
+ let keys = 0;
67
61
  for (const type in data) {
68
62
  for (const id in data[type]) {
69
- await cache.set(getUniqueId(type, id), data[type][id])
70
- keys += 1
63
+ await cache.set(getUniqueId(type, id), data[type][id]);
64
+ keys += 1;
71
65
  }
72
66
  }
73
- logger?.trace({ keys }, 'updated cache')
74
- await store.set(data)
75
- })
67
+ logger?.trace({ keys }, 'updated cache');
68
+ await store.set(data);
69
+ });
76
70
  },
77
71
  async clear() {
78
- await cache.flushAll()
79
- await store.clear?.call(store)
80
- }
81
- }
82
- }
83
-
84
- /**
85
- * Handles pre-key operations.
86
- *
87
- * IMPORTANT: locking for this function is provided by the CALLER via the
88
- * session-scoped `getKeyTypeMutex(keyType)` mutex (the same one used by
89
- * get()/set() for that key type). We intentionally do NOT acquire our own
90
- * mutex here anymore.
91
- *
92
- * Previously this used module-level singleton mutexes (`preKeyMutex`,
93
- * `signedPreKeyMutex`) declared OUTSIDE `addTransactionCapability`. Because
94
- * those were created once per process (not once per auth state / socket),
95
- * every session running in the same Node process shared the exact same
96
- * lock. That caused two problems:
97
- * 1. Unrelated sessions serialized on each other's pre-key writes
98
- * (needless contention/latency when running multiple accounts).
99
- * 2. The lock domain didn't match the one used by get()/withMutexes()
100
- * (`getKeyTypeMutex`), so reads/writes and deletion-validation could
101
- * interleave without real mutual exclusion (TOCTOU race on the
102
- * "does this key still exist" check), which is what let pre-key /
103
- * signed-pre-key state get corrupted under concurrent access.
104
- */
105
- async function handlePreKeyOperations(data, keyType, transactionCache, mutations, logger, isInTransaction, state) {
106
- const keyData = data[keyType]
107
- if (!keyData)
108
- return
109
-
110
- // Ensure structures exist
111
- transactionCache[keyType] = transactionCache[keyType] || {}
112
- mutations[keyType] = mutations[keyType] || {}
113
-
114
- // Separate deletions from updates for batch processing
115
- const deletionKeys = []
116
- const updateKeys = []
117
-
118
- for (const keyId in keyData) {
119
- if (keyData[keyId] === null) {
120
- deletionKeys.push(keyId)
121
- }
122
- else {
123
- updateKeys.push(keyId)
124
- }
125
- }
126
-
127
- // Process updates first (no validation needed)
128
- for (const keyId of updateKeys) {
129
- if (transactionCache[keyType]) {
130
- transactionCache[keyType][keyId] = keyData[keyId]
131
- }
132
- if (mutations[keyType]) {
133
- mutations[keyType][keyId] = keyData[keyId]
72
+ await cache.flushAll();
73
+ await store.clear?.();
134
74
  }
135
- }
136
-
137
- // Process deletions with validation
138
- if (deletionKeys.length === 0)
139
- return
140
-
141
- if (isInTransaction) {
142
- // In transaction, only allow deletion if key exists in cache
143
- for (const keyId of deletionKeys) {
144
- if (transactionCache[keyType]) {
145
- transactionCache[keyType][keyId] = null
146
- if (mutations[keyType]) {
147
- // Mark for deletion in mutations
148
- mutations[keyType][keyId] = null
149
- }
150
- }
151
- else {
152
- logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`)
153
- }
154
- }
155
- return
156
- }
157
-
158
- // Outside transaction, batch validate all deletions
159
- if (!state)
160
- return
161
-
162
- const existingKeys = await state.get(keyType, deletionKeys)
163
- for (const keyId of deletionKeys) {
164
- if (existingKeys[keyId]) {
165
- if (transactionCache[keyType])
166
- transactionCache[keyType][keyId] = null
167
- if (mutations[keyType])
168
- mutations[keyType][keyId] = null
169
- }
170
- else {
171
- logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
172
- }
173
- }
75
+ };
174
76
  }
175
-
176
77
  /**
177
- * Handles normal key operations for transactions
178
- */
179
- function handleNormalKeyOperations(data, key, transactionCache, mutations) {
180
- Object.assign(transactionCache[key], data[key])
181
- mutations[key] = mutations[key] || {}
182
- Object.assign(mutations[key], data[key])
183
- }
184
-
185
- /**
186
- * Process pre-key / signed-pre-key deletions with validation.
187
- *
188
- * NOTE: this is only ever called from inside a `withMutexes([..., keyType, ...])`
189
- * block in `set()` below, which already holds the session-scoped
190
- * `getKeyTypeMutex(keyType)` lock for the duration of the call. It must NOT
191
- * acquire its own mutex here - `async-mutex`'s Mutex is not reentrant, so
192
- * doing so would either deadlock (if it tried to re-acquire the same lock)
193
- * or - as in the previous version - silently acquire a *different*, global
194
- * lock that gave no real protection at all.
195
- */
196
- async function processPreKeyDeletions(data, keyType, state, logger) {
197
- const keyData = data[keyType]
198
- if (!keyData)
199
- return
200
-
201
- // Validate deletions
202
- const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null)
203
- if (deletionIds.length === 0)
204
- return
205
-
206
- const existingKeys = await state.get(keyType, deletionIds)
207
- for (const keyId of deletionIds) {
208
- if (!existingKeys[keyId]) {
209
- logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
210
- if (data[keyType])
211
- delete data[keyType][keyId]
212
- }
213
- }
214
- }
215
-
216
- /**
217
- * Executes a function with mutexes acquired for given key types
218
- * Uses async-mutex's runExclusive with efficient batching
219
- */
220
- async function withMutexes(keyTypes, getKeyTypeMutex, fn) {
221
- if (keyTypes.length === 0) {
222
- return fn()
223
- }
224
-
225
- if (keyTypes.length === 1) {
226
- return getKeyTypeMutex(keyTypes[0]).runExclusive(fn)
227
- }
228
-
229
- // For multiple mutexes, sort by key type to prevent deadlocks
230
- // Then acquire all mutexes in order using Promise.all for better efficiency
231
- const sortedKeyTypes = [...keyTypes].sort()
232
- const mutexes = sortedKeyTypes.map(getKeyTypeMutex)
233
-
234
- // Acquire all mutexes in order to prevent deadlocks
235
- const releases = []
236
- try {
237
- for (const mutex of mutexes) {
238
- releases.push(await mutex.acquire())
239
- }
240
- return await fn()
241
- }
242
- finally {
243
- // Release in reverse order
244
- while (releases.length > 0) {
245
- const release = releases.pop()
246
- if (release)
247
- release()
248
- }
249
- }
250
- }
251
-
252
- /**
253
- * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
254
- * this allows batch read & write operations & improves the performance of the lib
78
+ * Adds DB-like transaction capability to the SignalKeyStore
79
+ * Uses AsyncLocalStorage for automatic context management
255
80
  * @param state the key store to apply this capability to
256
81
  * @param logger logger to log events
257
82
  * @returns SignalKeyStore with transaction capability
258
83
  */
259
- const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
260
- // number of queries made to the DB during the transaction
261
- // only there for logging purposes
262
- let dbQueriesInTransaction = 0
263
- let transactionCache = {}
264
- let mutations = {}
265
-
266
- // LRU Cache to hold mutexes for different key types
267
- const mutexCache = new LRUCache_1.LRUCache({
268
- ttl: 60 * 60 * 1000, // 1 hour
269
- ttlAutopurge: true,
270
- updateAgeOnGet: true
271
- })
272
-
273
- let transactionsInProgress = 0
274
-
275
- function getKeyTypeMutex(type) {
276
- return getMutex(`keytype:${type}`)
84
+ export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
85
+ const txStorage = new AsyncLocalStorage();
86
+ // Queues for concurrency control (keyed by signal data type - bounded set)
87
+ const keyQueues = new Map();
88
+ // Transaction mutexes with reference counting for cleanup
89
+ const txMutexes = new Map();
90
+ const txMutexRefCounts = new Map();
91
+ // Pre-key manager for specialized operations
92
+ const preKeyManager = new PreKeyManager(state, logger);
93
+ /**
94
+ * Get or create a queue for a specific key type
95
+ */
96
+ function getQueue(key) {
97
+ if (!keyQueues.has(key)) {
98
+ keyQueues.set(key, new PQueue({ concurrency: 1 }));
99
+ }
100
+ return keyQueues.get(key);
277
101
  }
278
-
279
- function getSenderKeyMutex(senderKeyName) {
280
- return getMutex(`senderkey:${senderKeyName}`)
102
+ /**
103
+ * Get or create a transaction mutex
104
+ */
105
+ function getTxMutex(key) {
106
+ if (!txMutexes.has(key)) {
107
+ txMutexes.set(key, new Mutex());
108
+ txMutexRefCounts.set(key, 0);
109
+ }
110
+ return txMutexes.get(key);
281
111
  }
282
-
283
- function getTransactionMutex(key) {
284
- return getMutex(`transaction:${key}`)
112
+ /**
113
+ * Acquire a reference to a transaction mutex
114
+ */
115
+ function acquireTxMutexRef(key) {
116
+ const count = txMutexRefCounts.get(key) ?? 0;
117
+ txMutexRefCounts.set(key, count + 1);
285
118
  }
286
-
287
- // Get or create a mutex for a specific key name
288
- function getMutex(key) {
289
- let mutex = mutexCache.get(key)
290
- if (!mutex) {
291
- mutex = new mutex_1.Mutex()
292
- mutexCache.set(key, mutex)
293
- logger.info({ key }, 'created new mutex')
119
+ /**
120
+ * Release a reference to a transaction mutex and cleanup if no longer needed
121
+ */
122
+ function releaseTxMutexRef(key) {
123
+ const count = (txMutexRefCounts.get(key) ?? 1) - 1;
124
+ txMutexRefCounts.set(key, count);
125
+ // Cleanup if no more references and mutex is not locked
126
+ if (count <= 0) {
127
+ const mutex = txMutexes.get(key);
128
+ if (mutex && !mutex.isLocked()) {
129
+ txMutexes.delete(key);
130
+ txMutexRefCounts.delete(key);
131
+ }
294
132
  }
295
- return mutex
296
- }
297
-
298
- // Sender key operations with proper mutex sequencing
299
- function queueSenderKeyOperation(senderKeyName, operation) {
300
- return getSenderKeyMutex(senderKeyName).runExclusive(operation)
301
133
  }
302
-
303
- // Check if we are currently in a transaction
134
+ /**
135
+ * Check if currently in a transaction
136
+ */
304
137
  function isInTransaction() {
305
- return transactionsInProgress > 0
138
+ return !!txStorage.getStore();
306
139
  }
307
-
308
- // Helper function to handle transaction commit with retries
309
- async function commitTransaction() {
310
- if (!Object.keys(mutations).length) {
311
- logger.trace('no mutations in transaction')
312
- return
140
+ /**
141
+ * Commit transaction with retries
142
+ */
143
+ async function commitWithRetry(mutations) {
144
+ if (Object.keys(mutations).length === 0) {
145
+ logger.trace('no mutations in transaction');
146
+ return;
313
147
  }
314
148
  logger.trace('committing transaction');
315
- let tries = maxCommitRetries
316
- while (tries > 0) {
317
- tries -= 1;
149
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
318
150
  try {
319
- await state.set(mutations)
320
- logger.trace({ dbQueriesInTransaction }, 'committed transaction')
321
- return
151
+ await state.set(mutations);
152
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction');
153
+ return;
322
154
  }
323
155
  catch (error) {
324
- logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`)
325
- if (tries > 0) {
326
- await generics_1.delay(delayBetweenTriesMs)
156
+ const retriesLeft = maxCommitRetries - attempt - 1;
157
+ logger.warn(`failed to commit mutations, retries left=${retriesLeft}`);
158
+ if (retriesLeft === 0) {
159
+ throw error;
327
160
  }
161
+ await delay(delayBetweenTriesMs);
328
162
  }
329
163
  }
330
164
  }
331
-
332
- // Helper function to clean up transaction state
333
- function cleanupTransactionState() {
334
- transactionsInProgress -= 1
335
- if (transactionsInProgress === 0) {
336
- transactionCache = {}
337
- mutations = {}
338
- dbQueriesInTransaction = 0
339
- }
340
- }
341
-
342
- // Helper function to execute work within transaction
343
- async function executeTransactionWork(work) {
344
- const result = await work()
345
- // commit if this is the outermost transaction
346
- if (transactionsInProgress === 1) {
347
- await commitTransaction()
348
- }
349
- return result
350
- }
351
-
352
165
  return {
353
166
  get: async (type, ids) => {
354
- if (isInTransaction()) {
355
- const dict = transactionCache[type]
356
- const idsRequiringFetch = dict ? ids.filter(item => typeof dict[item] === 'undefined') : ids
357
-
358
- // only fetch if there are any items to fetch
359
- if (idsRequiringFetch.length) {
360
- dbQueriesInTransaction += 1
361
-
362
- // Use per-sender-key queue for sender-key operations when possible
363
- if (type === 'sender-key') {
364
- logger.info({ idsRequiringFetch }, 'processing sender keys in transaction')
365
- // For sender keys, process each one with queued operations to maintain serialization
366
- for (const senderKeyName of idsRequiringFetch) {
367
- await queueSenderKeyOperation(senderKeyName, async () => {
368
- logger.info({ senderKeyName }, 'fetching sender key in transaction')
369
- const result = await state.get(type, [senderKeyName])
370
- // Update transaction cache
371
- transactionCache[type] || (transactionCache[type] = {})
372
- Object.assign(transactionCache[type], result)
373
- logger.info({ senderKeyName, hasResult: !!result[senderKeyName] }, 'sender key fetch complete')
374
- })
375
- }
376
- }
377
- else {
378
- // Use runExclusive for cleaner mutex handling
379
- await getKeyTypeMutex(type).runExclusive(async () => {
380
- const result = await state.get(type, idsRequiringFetch)
381
- // Update transaction cache
382
- transactionCache[type] || (transactionCache[type] = {})
383
- Object.assign(transactionCache[type], result)
384
- })
385
- }
386
- }
387
- return ids.reduce((dict, id) => {
388
- const value = transactionCache[type]?.[id]
389
- if (value) {
390
- dict[id] = value
391
- }
392
- return dict
393
- }, {})
167
+ const ctx = txStorage.getStore();
168
+ if (!ctx) {
169
+ // No transaction - direct read without exclusive lock for concurrency
170
+ return state.get(type, ids);
394
171
  }
395
- else {
396
- // Not in transaction, fetch directly with queue protection
397
- if (type === 'sender-key') {
398
- // For sender keys, use individual queues to maintain per-key serialization
399
- const results = {}
400
- for (const senderKeyName of ids) {
401
- const result = await queueSenderKeyOperation(senderKeyName, async () => await state.get(type, [senderKeyName]))
402
- Object.assign(results, result)
403
- }
404
- return results
405
- }
406
- else {
407
- return await getKeyTypeMutex(type).runExclusive(() => state.get(type, ids))
172
+ // In transaction - check cache first
173
+ const cached = ctx.cache[type] || {};
174
+ const missing = ids.filter(id => !(id in cached));
175
+ if (missing.length > 0) {
176
+ ctx.dbQueries++;
177
+ logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction');
178
+ const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing));
179
+ // Update cache
180
+ ctx.cache[type] = ctx.cache[type] || {};
181
+ Object.assign(ctx.cache[type], fetched);
182
+ }
183
+ // Return requested ids from cache
184
+ const result = {};
185
+ for (const id of ids) {
186
+ const value = ctx.cache[type]?.[id];
187
+ if (value !== undefined && value !== null) {
188
+ result[id] = value;
408
189
  }
409
190
  }
191
+ return result;
410
192
  },
411
193
  set: async (data) => {
412
- if (isInTransaction()) {
413
- logger.trace({ types: Object.keys(data) }, 'caching in transaction')
414
- for (const key_ in data) {
415
- const key = key_
416
- transactionCache[key] = transactionCache[key] || {}
417
- // Special handling for pre-keys and signed-pre-keys.
418
- // Locked via the session-scoped getKeyTypeMutex(key) so this can't
419
- // interleave with a concurrent non-transactional get()/set() for the
420
- // same key type on this SAME auth state - no cross-session locking,
421
- // no lock-domain mismatch.
422
- if (key === 'pre-key' || key === 'signed-pre-key') {
423
- await getKeyTypeMutex(key).runExclusive(() => handlePreKeyOperations(data, key, transactionCache, mutations, logger, true))
424
- }
425
- else {
426
- // Normal handling for other key types
427
- handleNormalKeyOperations(data, key, transactionCache, mutations)
194
+ const ctx = txStorage.getStore();
195
+ if (!ctx) {
196
+ // No transaction - direct write with queue protection
197
+ const types = Object.keys(data);
198
+ // Process pre-keys with validation
199
+ for (const type_ of types) {
200
+ const type = type_;
201
+ if (type === 'pre-key') {
202
+ await preKeyManager.validateDeletions(data, type);
428
203
  }
429
204
  }
205
+ // Write all data in parallel
206
+ await Promise.all(types.map(type => getQueue(type).add(async () => {
207
+ const typeData = { [type]: data[type] };
208
+ await state.set(typeData);
209
+ })));
210
+ return;
430
211
  }
431
- else {
432
- // Not in transaction, apply directly with mutex protection
433
- const hasSenderKeys = 'sender-key' in data
434
- const senderKeyNames = hasSenderKeys ? Object.keys(data['sender-key'] || {}) : []
435
- if (hasSenderKeys) {
436
- logger.info({ senderKeyNames }, 'processing sender key set operations')
437
- // Handle sender key operations with per-key queues
438
- for (const senderKeyName of senderKeyNames) {
439
- await queueSenderKeyOperation(senderKeyName, async () => {
440
- // Create data subset for this specific sender key
441
- const senderKeyData = {
442
- 'sender-key': {
443
- [senderKeyName]: data['sender-key'][senderKeyName]
444
- }
445
- };
446
- logger.trace({ senderKeyName }, 'storing sender key')
447
- // Apply changes to the store
448
- await state.set(senderKeyData)
449
- logger.trace({ senderKeyName }, 'sender key stored')
450
- })
451
- }
452
- // Handle any non-sender-key data with regular mutexes
453
- const nonSenderKeyData = { ...data }
454
- delete nonSenderKeyData['sender-key']
455
- if (Object.keys(nonSenderKeyData).length > 0) {
456
- await withMutexes(Object.keys(nonSenderKeyData), getKeyTypeMutex, async () => {
457
- // Process pre-keys and signed-pre-keys separately with specialized mutexes
458
- for (const key_ in nonSenderKeyData) {
459
- const keyType = key_
460
- if (keyType === 'pre-key' || keyType === 'signed-pre-key') {
461
- await processPreKeyDeletions(nonSenderKeyData, keyType, state, logger)
462
- }
463
- }
464
- // Apply changes to the store
465
- await state.set(nonSenderKeyData)
466
- })
467
- }
212
+ // In transaction - update cache and mutations
213
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction');
214
+ for (const key_ in data) {
215
+ const key = key_;
216
+ // Ensure structures exist
217
+ ctx.cache[key] = ctx.cache[key] || {};
218
+ ctx.mutations[key] = ctx.mutations[key] || {};
219
+ // Special handling for pre-keys
220
+ if (key === 'pre-key') {
221
+ await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true);
468
222
  }
469
223
  else {
470
- // No sender keys - use original logic
471
- await withMutexes(Object.keys(data), getKeyTypeMutex, async () => {
472
- // Process pre-keys and signed-pre-keys separately with specialized mutexes
473
- for (const key_ in data) {
474
- const keyType = key_
475
- if (keyType === 'pre-key' || keyType === 'signed-pre-key') {
476
- await processPreKeyDeletions(data, keyType, state, logger)
477
- }
478
- }
479
- // Apply changes to the store
480
- await state.set(data)
481
- })
224
+ // Normal key types
225
+ Object.assign(ctx.cache[key], data[key]);
226
+ Object.assign(ctx.mutations[key], data[key]);
482
227
  }
483
228
  }
484
229
  },
485
230
  isInTransaction,
486
- async transaction(work, key) {
487
- const releaseTxMutex = await getTransactionMutex(key).acquire()
231
+ transaction: async (work, key) => {
232
+ const existing = txStorage.getStore();
233
+ // Nested transaction - reuse existing context
234
+ if (existing) {
235
+ logger.trace('reusing existing transaction context');
236
+ return work();
237
+ }
238
+ // New transaction - acquire mutex and create context
239
+ const mutex = getTxMutex(key);
240
+ acquireTxMutexRef(key);
488
241
  try {
489
- transactionsInProgress += 1;
490
- if (transactionsInProgress === 1) {
491
- logger.trace('entering transaction')
492
- }
493
- try {
494
- return await executeTransactionWork(work)
495
- }
496
- finally {
497
- cleanupTransactionState();
498
- // Release AFTER commit & cleanup to prevent race conditions
499
- // where another transaction starts before this one finishes writing
500
- releaseTxMutex()
501
- }
242
+ return await mutex.runExclusive(async () => {
243
+ const ctx = {
244
+ cache: {},
245
+ mutations: {},
246
+ dbQueries: 0
247
+ };
248
+ logger.trace('entering transaction');
249
+ try {
250
+ const result = await txStorage.run(ctx, work);
251
+ // Commit mutations
252
+ await commitWithRetry(ctx.mutations);
253
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed');
254
+ return result;
255
+ }
256
+ catch (error) {
257
+ logger.error({ error }, 'transaction failed, rolling back');
258
+ throw error;
259
+ }
260
+ });
502
261
  }
503
- catch (error) {
504
- // Only release here if we haven't already released in the finally block
505
- // (i.e., error thrown before transactionsInProgress was incremented)
506
- if (transactionsInProgress > 0) {
507
- cleanupTransactionState()
508
- }
509
- releaseTxMutex()
510
- throw error
262
+ finally {
263
+ releaseTxMutexRef(key);
511
264
  }
512
265
  }
266
+ };
267
+ };
268
+ /**
269
+ * Returns the authenticated user's JID, or throws a Boom-401 if creds are not yet authenticated.
270
+ * Use this anywhere we'd otherwise reach for `creds.me!.id` to fail fast with a descriptive error.
271
+ */
272
+ export const assertMeId = (creds) => {
273
+ const id = creds.me?.id;
274
+ if (!id) {
275
+ throw new Boom('Cannot proceed: socket is not authenticated yet (creds.me.id is missing)', { statusCode: 401 });
513
276
  }
514
- }
515
-
516
- const initAuthCreds = () => {
517
- const identityKey = crypto_2.Curve.generateKeyPair()
277
+ return id;
278
+ };
279
+ export const initAuthCreds = () => {
280
+ const identityKey = Curve.generateKeyPair();
518
281
  return {
519
- noiseKey: crypto_2.Curve.generateKeyPair(),
520
- pairingEphemeralKeyPair: crypto_2.Curve.generateKeyPair(),
282
+ noiseKey: Curve.generateKeyPair(),
283
+ pairingEphemeralKeyPair: Curve.generateKeyPair(),
521
284
  signedIdentityKey: identityKey,
522
- signedPreKey: crypto_2.signedKeyPair(identityKey, 1),
523
- registrationId: generics_1.generateRegistrationId(),
524
- advSecretKey: crypto_1.randomBytes(32).toString('base64'),
285
+ signedPreKey: signedKeyPair(identityKey, 1),
286
+ registrationId: generateRegistrationId(),
287
+ advSecretKey: randomBytes(32).toString('base64'),
525
288
  processedHistoryMessages: [],
526
289
  nextPreKeyId: 1,
527
290
  firstUnuploadedPreKeyId: 1,
@@ -532,12 +295,8 @@ const initAuthCreds = () => {
532
295
  registered: false,
533
296
  pairingCode: undefined,
534
297
  lastPropHash: undefined,
535
- routingInfo: undefined
536
- }
537
- }
538
-
539
- module.exports = {
540
- makeCacheableSignalKeyStore,
541
- addTransactionCapability,
542
- initAuthCreds
543
- }
298
+ routingInfo: undefined,
299
+ additionalData: undefined
300
+ };
301
+ };
302
+ //# sourceMappingURL=auth-utils.js.map