@bsv/wallet-toolbox 1.3.21 → 1.3.22

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 (502) hide show
  1. package/mobile/out/src/CWIStyleWalletManager.d.ts +437 -0
  2. package/mobile/out/src/CWIStyleWalletManager.d.ts.map +1 -0
  3. package/mobile/out/src/CWIStyleWalletManager.js +1255 -0
  4. package/mobile/out/src/CWIStyleWalletManager.js.map +1 -0
  5. package/mobile/out/src/SetupClient.d.ts +126 -0
  6. package/mobile/out/src/SetupClient.d.ts.map +1 -0
  7. package/mobile/out/src/SetupClient.js +220 -0
  8. package/mobile/out/src/SetupClient.js.map +1 -0
  9. package/mobile/out/src/SetupWallet.d.ts +100 -0
  10. package/mobile/out/src/SetupWallet.d.ts.map +1 -0
  11. package/mobile/out/src/SetupWallet.js +3 -0
  12. package/mobile/out/src/SetupWallet.js.map +1 -0
  13. package/mobile/out/src/SimpleWalletManager.d.ts +169 -0
  14. package/mobile/out/src/SimpleWalletManager.d.ts.map +1 -0
  15. package/mobile/out/src/SimpleWalletManager.js +315 -0
  16. package/mobile/out/src/SimpleWalletManager.js.map +1 -0
  17. package/mobile/out/src/Wallet.d.ts +177 -0
  18. package/mobile/out/src/Wallet.d.ts.map +1 -0
  19. package/mobile/out/src/Wallet.js +742 -0
  20. package/mobile/out/src/Wallet.js.map +1 -0
  21. package/mobile/out/src/WalletAuthenticationManager.d.ts +33 -0
  22. package/mobile/out/src/WalletAuthenticationManager.d.ts.map +1 -0
  23. package/mobile/out/src/WalletAuthenticationManager.js +113 -0
  24. package/mobile/out/src/WalletAuthenticationManager.js.map +1 -0
  25. package/mobile/out/src/WalletPermissionsManager.d.ts +598 -0
  26. package/mobile/out/src/WalletPermissionsManager.d.ts.map +1 -0
  27. package/mobile/out/src/WalletPermissionsManager.js +1868 -0
  28. package/mobile/out/src/WalletPermissionsManager.js.map +1 -0
  29. package/mobile/out/src/WalletSettingsManager.d.ts +52 -0
  30. package/mobile/out/src/WalletSettingsManager.d.ts.map +1 -0
  31. package/mobile/out/src/WalletSettingsManager.js +82 -0
  32. package/mobile/out/src/WalletSettingsManager.js.map +1 -0
  33. package/mobile/out/src/index.client.d.ts +19 -0
  34. package/mobile/out/src/index.client.d.ts.map +1 -0
  35. package/mobile/out/src/index.client.js +58 -0
  36. package/mobile/out/src/index.client.js.map +1 -0
  37. package/mobile/out/src/index.mobile.d.ts +19 -0
  38. package/mobile/out/src/index.mobile.d.ts.map +1 -0
  39. package/mobile/out/src/index.mobile.js +58 -0
  40. package/mobile/out/src/index.mobile.js.map +1 -0
  41. package/mobile/out/src/monitor/Monitor.d.ts +91 -0
  42. package/mobile/out/src/monitor/Monitor.d.ts.map +1 -0
  43. package/mobile/out/src/monitor/Monitor.js +298 -0
  44. package/mobile/out/src/monitor/Monitor.js.map +1 -0
  45. package/mobile/out/src/monitor/tasks/TaskCheckForProofs.d.ts +53 -0
  46. package/mobile/out/src/monitor/tasks/TaskCheckForProofs.d.ts.map +1 -0
  47. package/mobile/out/src/monitor/tasks/TaskCheckForProofs.js +194 -0
  48. package/mobile/out/src/monitor/tasks/TaskCheckForProofs.js.map +1 -0
  49. package/mobile/out/src/monitor/tasks/TaskCheckNoSends.d.ts +33 -0
  50. package/mobile/out/src/monitor/tasks/TaskCheckNoSends.d.ts.map +1 -0
  51. package/mobile/out/src/monitor/tasks/TaskCheckNoSends.js +65 -0
  52. package/mobile/out/src/monitor/tasks/TaskCheckNoSends.js.map +1 -0
  53. package/mobile/out/src/monitor/tasks/TaskClock.d.ts +14 -0
  54. package/mobile/out/src/monitor/tasks/TaskClock.d.ts.map +1 -0
  55. package/mobile/out/src/monitor/tasks/TaskClock.js +27 -0
  56. package/mobile/out/src/monitor/tasks/TaskClock.js.map +1 -0
  57. package/mobile/out/src/monitor/tasks/TaskFailAbandoned.d.ts +20 -0
  58. package/mobile/out/src/monitor/tasks/TaskFailAbandoned.d.ts.map +1 -0
  59. package/mobile/out/src/monitor/tasks/TaskFailAbandoned.js +52 -0
  60. package/mobile/out/src/monitor/tasks/TaskFailAbandoned.js.map +1 -0
  61. package/mobile/out/src/monitor/tasks/TaskNewHeader.d.ts +15 -0
  62. package/mobile/out/src/monitor/tasks/TaskNewHeader.d.ts.map +1 -0
  63. package/mobile/out/src/monitor/tasks/TaskNewHeader.js +43 -0
  64. package/mobile/out/src/monitor/tasks/TaskNewHeader.js.map +1 -0
  65. package/mobile/out/src/monitor/tasks/TaskPurge.d.ts +45 -0
  66. package/mobile/out/src/monitor/tasks/TaskPurge.d.ts.map +1 -0
  67. package/mobile/out/src/monitor/tasks/TaskPurge.js +34 -0
  68. package/mobile/out/src/monitor/tasks/TaskPurge.js.map +1 -0
  69. package/mobile/out/src/monitor/tasks/TaskReviewStatus.d.ts +26 -0
  70. package/mobile/out/src/monitor/tasks/TaskReviewStatus.d.ts.map +1 -0
  71. package/mobile/out/src/monitor/tasks/TaskReviewStatus.js +43 -0
  72. package/mobile/out/src/monitor/tasks/TaskReviewStatus.js.map +1 -0
  73. package/mobile/out/src/monitor/tasks/TaskSendWaiting.d.ts +35 -0
  74. package/mobile/out/src/monitor/tasks/TaskSendWaiting.d.ts.map +1 -0
  75. package/mobile/out/src/monitor/tasks/TaskSendWaiting.js +107 -0
  76. package/mobile/out/src/monitor/tasks/TaskSendWaiting.js.map +1 -0
  77. package/mobile/out/src/monitor/tasks/TaskSyncWhenIdle.d.ts +12 -0
  78. package/mobile/out/src/monitor/tasks/TaskSyncWhenIdle.d.ts.map +1 -0
  79. package/mobile/out/src/monitor/tasks/TaskSyncWhenIdle.js +22 -0
  80. package/mobile/out/src/monitor/tasks/TaskSyncWhenIdle.js.map +1 -0
  81. package/mobile/out/src/monitor/tasks/TaskUnFail.d.ts +41 -0
  82. package/mobile/out/src/monitor/tasks/TaskUnFail.d.ts.map +1 -0
  83. package/mobile/out/src/monitor/tasks/TaskUnFail.js +144 -0
  84. package/mobile/out/src/monitor/tasks/TaskUnFail.js.map +1 -0
  85. package/mobile/out/src/monitor/tasks/WalletMonitorTask.d.ts +40 -0
  86. package/mobile/out/src/monitor/tasks/WalletMonitorTask.d.ts.map +1 -0
  87. package/mobile/out/src/monitor/tasks/WalletMonitorTask.js +37 -0
  88. package/mobile/out/src/monitor/tasks/WalletMonitorTask.js.map +1 -0
  89. package/mobile/out/src/sdk/CertOpsWallet.d.ts +7 -0
  90. package/mobile/out/src/sdk/CertOpsWallet.d.ts.map +1 -0
  91. package/mobile/out/src/sdk/CertOpsWallet.js +3 -0
  92. package/mobile/out/src/sdk/CertOpsWallet.js.map +1 -0
  93. package/mobile/out/src/sdk/PrivilegedKeyManager.d.ts +125 -0
  94. package/mobile/out/src/sdk/PrivilegedKeyManager.d.ts.map +1 -0
  95. package/mobile/out/src/sdk/PrivilegedKeyManager.js +293 -0
  96. package/mobile/out/src/sdk/PrivilegedKeyManager.js.map +1 -0
  97. package/mobile/out/src/sdk/WERR_errors.d.ts +115 -0
  98. package/mobile/out/src/sdk/WERR_errors.d.ts.map +1 -0
  99. package/mobile/out/src/sdk/WERR_errors.js +158 -0
  100. package/mobile/out/src/sdk/WERR_errors.js.map +1 -0
  101. package/mobile/out/src/sdk/WalletError.d.ts +44 -0
  102. package/mobile/out/src/sdk/WalletError.d.ts.map +1 -0
  103. package/mobile/out/src/sdk/WalletError.js +118 -0
  104. package/mobile/out/src/sdk/WalletError.js.map +1 -0
  105. package/mobile/out/src/sdk/WalletServices.interfaces.d.ts +430 -0
  106. package/mobile/out/src/sdk/WalletServices.interfaces.d.ts.map +1 -0
  107. package/mobile/out/src/sdk/WalletServices.interfaces.js +3 -0
  108. package/mobile/out/src/sdk/WalletServices.interfaces.js.map +1 -0
  109. package/mobile/out/src/sdk/WalletSigner.interfaces.d.ts +10 -0
  110. package/mobile/out/src/sdk/WalletSigner.interfaces.d.ts.map +1 -0
  111. package/mobile/out/src/sdk/WalletSigner.interfaces.js +3 -0
  112. package/mobile/out/src/sdk/WalletSigner.interfaces.js.map +1 -0
  113. package/mobile/out/src/sdk/WalletStorage.interfaces.d.ts +452 -0
  114. package/mobile/out/src/sdk/WalletStorage.interfaces.d.ts.map +1 -0
  115. package/mobile/out/src/sdk/WalletStorage.interfaces.js +3 -0
  116. package/mobile/out/src/sdk/WalletStorage.interfaces.js.map +1 -0
  117. package/mobile/out/src/sdk/index.d.ts +10 -0
  118. package/mobile/out/src/sdk/index.d.ts.map +1 -0
  119. package/mobile/out/src/sdk/index.js +26 -0
  120. package/mobile/out/src/sdk/index.js.map +1 -0
  121. package/mobile/out/src/sdk/types.d.ts +158 -0
  122. package/mobile/out/src/sdk/types.d.ts.map +1 -0
  123. package/mobile/out/src/sdk/types.js +90 -0
  124. package/mobile/out/src/sdk/types.js.map +1 -0
  125. package/mobile/out/src/sdk/validationHelpers.d.ts +301 -0
  126. package/mobile/out/src/sdk/validationHelpers.d.ts.map +1 -0
  127. package/mobile/out/src/sdk/validationHelpers.js +629 -0
  128. package/mobile/out/src/sdk/validationHelpers.js.map +1 -0
  129. package/mobile/out/src/services/ServiceCollection.d.ts +25 -0
  130. package/mobile/out/src/services/ServiceCollection.d.ts.map +1 -0
  131. package/mobile/out/src/services/ServiceCollection.js +43 -0
  132. package/mobile/out/src/services/ServiceCollection.js.map +1 -0
  133. package/mobile/out/src/services/Services.d.ts +67 -0
  134. package/mobile/out/src/services/Services.d.ts.map +1 -0
  135. package/mobile/out/src/services/Services.js +391 -0
  136. package/mobile/out/src/services/Services.js.map +1 -0
  137. package/mobile/out/src/services/chaintracker/ChaintracksChainTracker.d.ts +15 -0
  138. package/mobile/out/src/services/chaintracker/ChaintracksChainTracker.d.ts.map +1 -0
  139. package/mobile/out/src/services/chaintracker/ChaintracksChainTracker.js +51 -0
  140. package/mobile/out/src/services/chaintracker/ChaintracksChainTracker.js.map +1 -0
  141. package/mobile/out/src/services/chaintracker/chaintracks/BlockHeaderApi.d.ts +98 -0
  142. package/mobile/out/src/services/chaintracker/chaintracks/BlockHeaderApi.d.ts.map +1 -0
  143. package/mobile/out/src/services/chaintracker/chaintracks/BlockHeaderApi.js +38 -0
  144. package/mobile/out/src/services/chaintracker/chaintracks/BlockHeaderApi.js.map +1 -0
  145. package/mobile/out/src/services/chaintracker/chaintracks/ChaintracksServiceClient.d.ts +36 -0
  146. package/mobile/out/src/services/chaintracker/chaintracks/ChaintracksServiceClient.d.ts.map +1 -0
  147. package/mobile/out/src/services/chaintracker/chaintracks/ChaintracksServiceClient.js +128 -0
  148. package/mobile/out/src/services/chaintracker/chaintracks/ChaintracksServiceClient.js.map +1 -0
  149. package/mobile/out/src/services/chaintracker/chaintracks/index.d.ts +3 -0
  150. package/mobile/out/src/services/chaintracker/chaintracks/index.d.ts.map +1 -0
  151. package/mobile/out/src/services/chaintracker/chaintracks/index.js +19 -0
  152. package/mobile/out/src/services/chaintracker/chaintracks/index.js.map +1 -0
  153. package/mobile/out/src/services/chaintracker/index.d.ts +3 -0
  154. package/mobile/out/src/services/chaintracker/index.d.ts.map +1 -0
  155. package/mobile/out/src/services/chaintracker/index.js +19 -0
  156. package/mobile/out/src/services/chaintracker/index.js.map +1 -0
  157. package/mobile/out/src/services/createDefaultWalletServicesOptions.d.ts +4 -0
  158. package/mobile/out/src/services/createDefaultWalletServicesOptions.d.ts.map +1 -0
  159. package/mobile/out/src/services/createDefaultWalletServicesOptions.js +46 -0
  160. package/mobile/out/src/services/createDefaultWalletServicesOptions.js.map +1 -0
  161. package/mobile/out/src/services/index.d.ts +2 -0
  162. package/mobile/out/src/services/index.d.ts.map +1 -0
  163. package/mobile/out/src/services/index.js +18 -0
  164. package/mobile/out/src/services/index.js.map +1 -0
  165. package/mobile/out/src/services/providers/ARC.d.ts +91 -0
  166. package/mobile/out/src/services/providers/ARC.d.ts.map +1 -0
  167. package/mobile/out/src/services/providers/ARC.js +267 -0
  168. package/mobile/out/src/services/providers/ARC.js.map +1 -0
  169. package/mobile/out/src/services/providers/Bitails.d.ts +49 -0
  170. package/mobile/out/src/services/providers/Bitails.d.ts.map +1 -0
  171. package/mobile/out/src/services/providers/Bitails.js +222 -0
  172. package/mobile/out/src/services/providers/Bitails.js.map +1 -0
  173. package/mobile/out/src/services/providers/SdkWhatsOnChain.d.ts +21 -0
  174. package/mobile/out/src/services/providers/SdkWhatsOnChain.d.ts.map +1 -0
  175. package/mobile/out/src/services/providers/SdkWhatsOnChain.js +67 -0
  176. package/mobile/out/src/services/providers/SdkWhatsOnChain.js.map +1 -0
  177. package/mobile/out/src/services/providers/WhatsOnChain.d.ts +71 -0
  178. package/mobile/out/src/services/providers/WhatsOnChain.d.ts.map +1 -0
  179. package/mobile/out/src/services/providers/WhatsOnChain.js +582 -0
  180. package/mobile/out/src/services/providers/WhatsOnChain.js.map +1 -0
  181. package/mobile/out/src/services/providers/echangeRates.d.ts +12 -0
  182. package/mobile/out/src/services/providers/echangeRates.d.ts.map +1 -0
  183. package/mobile/out/src/services/providers/echangeRates.js +237 -0
  184. package/mobile/out/src/services/providers/echangeRates.js.map +1 -0
  185. package/mobile/out/src/services/providers/getBeefForTxid.d.ts +4 -0
  186. package/mobile/out/src/services/providers/getBeefForTxid.d.ts.map +1 -0
  187. package/mobile/out/src/services/providers/getBeefForTxid.js +286 -0
  188. package/mobile/out/src/services/providers/getBeefForTxid.js.map +1 -0
  189. package/mobile/out/src/signer/WalletSigner.d.ts +11 -0
  190. package/mobile/out/src/signer/WalletSigner.d.ts.map +1 -0
  191. package/mobile/out/src/signer/WalletSigner.js +13 -0
  192. package/mobile/out/src/signer/WalletSigner.js.map +1 -0
  193. package/mobile/out/src/signer/methods/acquireDirectCertificate.d.ts +4 -0
  194. package/mobile/out/src/signer/methods/acquireDirectCertificate.d.ts.map +1 -0
  195. package/mobile/out/src/signer/methods/acquireDirectCertificate.js +45 -0
  196. package/mobile/out/src/signer/methods/acquireDirectCertificate.js.map +1 -0
  197. package/mobile/out/src/signer/methods/buildSignableTransaction.d.ts +10 -0
  198. package/mobile/out/src/signer/methods/buildSignableTransaction.d.ts.map +1 -0
  199. package/mobile/out/src/signer/methods/buildSignableTransaction.js +126 -0
  200. package/mobile/out/src/signer/methods/buildSignableTransaction.js.map +1 -0
  201. package/mobile/out/src/signer/methods/createAction.d.ts +20 -0
  202. package/mobile/out/src/signer/methods/createAction.d.ts.map +1 -0
  203. package/mobile/out/src/signer/methods/createAction.js +160 -0
  204. package/mobile/out/src/signer/methods/createAction.js.map +1 -0
  205. package/mobile/out/src/signer/methods/internalizeAction.d.ts +31 -0
  206. package/mobile/out/src/signer/methods/internalizeAction.d.ts.map +1 -0
  207. package/mobile/out/src/signer/methods/internalizeAction.js +95 -0
  208. package/mobile/out/src/signer/methods/internalizeAction.js.map +1 -0
  209. package/mobile/out/src/signer/methods/proveCertificate.d.ts +4 -0
  210. package/mobile/out/src/signer/methods/proveCertificate.d.ts.map +1 -0
  211. package/mobile/out/src/signer/methods/proveCertificate.js +29 -0
  212. package/mobile/out/src/signer/methods/proveCertificate.js.map +1 -0
  213. package/mobile/out/src/signer/methods/signAction.d.ts +13 -0
  214. package/mobile/out/src/signer/methods/signAction.d.ts.map +1 -0
  215. package/mobile/out/src/signer/methods/signAction.js +89 -0
  216. package/mobile/out/src/signer/methods/signAction.js.map +1 -0
  217. package/mobile/out/src/storage/StorageIdb.d.ts +208 -0
  218. package/mobile/out/src/storage/StorageIdb.d.ts.map +1 -0
  219. package/mobile/out/src/storage/StorageIdb.js +2296 -0
  220. package/mobile/out/src/storage/StorageIdb.js.map +1 -0
  221. package/mobile/out/src/storage/StorageProvider.d.ts +209 -0
  222. package/mobile/out/src/storage/StorageProvider.d.ts.map +1 -0
  223. package/mobile/out/src/storage/StorageProvider.js +550 -0
  224. package/mobile/out/src/storage/StorageProvider.js.map +1 -0
  225. package/mobile/out/src/storage/StorageReader.d.ts +76 -0
  226. package/mobile/out/src/storage/StorageReader.d.ts.map +1 -0
  227. package/mobile/out/src/storage/StorageReader.js +129 -0
  228. package/mobile/out/src/storage/StorageReader.js.map +1 -0
  229. package/mobile/out/src/storage/StorageReaderWriter.d.ts +87 -0
  230. package/mobile/out/src/storage/StorageReaderWriter.d.ts.map +1 -0
  231. package/mobile/out/src/storage/StorageReaderWriter.js +338 -0
  232. package/mobile/out/src/storage/StorageReaderWriter.js.map +1 -0
  233. package/mobile/out/src/storage/StorageSyncReader.d.ts +17 -0
  234. package/mobile/out/src/storage/StorageSyncReader.d.ts.map +1 -0
  235. package/mobile/out/src/storage/StorageSyncReader.js +38 -0
  236. package/mobile/out/src/storage/StorageSyncReader.js.map +1 -0
  237. package/mobile/out/src/storage/WalletStorageManager.d.ts +184 -0
  238. package/mobile/out/src/storage/WalletStorageManager.d.ts.map +1 -0
  239. package/mobile/out/src/storage/WalletStorageManager.js +665 -0
  240. package/mobile/out/src/storage/WalletStorageManager.js.map +1 -0
  241. package/mobile/out/src/storage/index.client.d.ts +8 -0
  242. package/mobile/out/src/storage/index.client.d.ts.map +1 -0
  243. package/mobile/out/src/storage/index.client.js +24 -0
  244. package/mobile/out/src/storage/index.client.js.map +1 -0
  245. package/mobile/out/src/storage/index.mobile.d.ts +7 -0
  246. package/mobile/out/src/storage/index.mobile.d.ts.map +1 -0
  247. package/mobile/out/src/storage/index.mobile.js +23 -0
  248. package/mobile/out/src/storage/index.mobile.js.map +1 -0
  249. package/mobile/out/src/storage/methods/ListActionsSpecOp.d.ts +16 -0
  250. package/mobile/out/src/storage/methods/ListActionsSpecOp.d.ts.map +1 -0
  251. package/mobile/out/src/storage/methods/ListActionsSpecOp.js +40 -0
  252. package/mobile/out/src/storage/methods/ListActionsSpecOp.js.map +1 -0
  253. package/mobile/out/src/storage/methods/ListOutputsSpecOp.d.ts +26 -0
  254. package/mobile/out/src/storage/methods/ListOutputsSpecOp.d.ts.map +1 -0
  255. package/mobile/out/src/storage/methods/ListOutputsSpecOp.js +71 -0
  256. package/mobile/out/src/storage/methods/ListOutputsSpecOp.js.map +1 -0
  257. package/mobile/out/src/storage/methods/attemptToPostReqsToNetwork.d.ts +41 -0
  258. package/mobile/out/src/storage/methods/attemptToPostReqsToNetwork.d.ts.map +1 -0
  259. package/mobile/out/src/storage/methods/attemptToPostReqsToNetwork.js +320 -0
  260. package/mobile/out/src/storage/methods/attemptToPostReqsToNetwork.js.map +1 -0
  261. package/mobile/out/src/storage/methods/createAction.d.ts +24 -0
  262. package/mobile/out/src/storage/methods/createAction.d.ts.map +1 -0
  263. package/mobile/out/src/storage/methods/createAction.js +705 -0
  264. package/mobile/out/src/storage/methods/createAction.js.map +1 -0
  265. package/mobile/out/src/storage/methods/generateChange.d.ts +119 -0
  266. package/mobile/out/src/storage/methods/generateChange.d.ts.map +1 -0
  267. package/mobile/out/src/storage/methods/generateChange.js +448 -0
  268. package/mobile/out/src/storage/methods/generateChange.js.map +1 -0
  269. package/mobile/out/src/storage/methods/getBeefForTransaction.d.ts +22 -0
  270. package/mobile/out/src/storage/methods/getBeefForTransaction.d.ts.map +1 -0
  271. package/mobile/out/src/storage/methods/getBeefForTransaction.js +92 -0
  272. package/mobile/out/src/storage/methods/getBeefForTransaction.js.map +1 -0
  273. package/mobile/out/src/storage/methods/getSyncChunk.d.ts +10 -0
  274. package/mobile/out/src/storage/methods/getSyncChunk.d.ts.map +1 -0
  275. package/mobile/out/src/storage/methods/getSyncChunk.js +271 -0
  276. package/mobile/out/src/storage/methods/getSyncChunk.js.map +1 -0
  277. package/mobile/out/src/storage/methods/internalizeAction.d.ts +38 -0
  278. package/mobile/out/src/storage/methods/internalizeAction.d.ts.map +1 -0
  279. package/mobile/out/src/storage/methods/internalizeAction.js +371 -0
  280. package/mobile/out/src/storage/methods/internalizeAction.js.map +1 -0
  281. package/mobile/out/src/storage/methods/listActionsIdb.d.ts +5 -0
  282. package/mobile/out/src/storage/methods/listActionsIdb.d.ts.map +1 -0
  283. package/mobile/out/src/storage/methods/listActionsIdb.js +155 -0
  284. package/mobile/out/src/storage/methods/listActionsIdb.js.map +1 -0
  285. package/mobile/out/src/storage/methods/listCertificates.d.ts +5 -0
  286. package/mobile/out/src/storage/methods/listCertificates.d.ts.map +1 -0
  287. package/mobile/out/src/storage/methods/listCertificates.js +68 -0
  288. package/mobile/out/src/storage/methods/listCertificates.js.map +1 -0
  289. package/mobile/out/src/storage/methods/listOutputsIdb.d.ts +5 -0
  290. package/mobile/out/src/storage/methods/listOutputsIdb.d.ts.map +1 -0
  291. package/mobile/out/src/storage/methods/listOutputsIdb.js +181 -0
  292. package/mobile/out/src/storage/methods/listOutputsIdb.js.map +1 -0
  293. package/mobile/out/src/storage/methods/processAction.d.ts +35 -0
  294. package/mobile/out/src/storage/methods/processAction.d.ts.map +1 -0
  295. package/mobile/out/src/storage/methods/processAction.js +311 -0
  296. package/mobile/out/src/storage/methods/processAction.js.map +1 -0
  297. package/mobile/out/src/storage/methods/purgeDataIdb.d.ts +4 -0
  298. package/mobile/out/src/storage/methods/purgeDataIdb.d.ts.map +1 -0
  299. package/mobile/out/src/storage/methods/purgeDataIdb.js +9 -0
  300. package/mobile/out/src/storage/methods/purgeDataIdb.js.map +1 -0
  301. package/mobile/out/src/storage/methods/reviewStatusIdb.d.ts +20 -0
  302. package/mobile/out/src/storage/methods/reviewStatusIdb.d.ts.map +1 -0
  303. package/mobile/out/src/storage/methods/reviewStatusIdb.js +35 -0
  304. package/mobile/out/src/storage/methods/reviewStatusIdb.js.map +1 -0
  305. package/mobile/out/src/storage/remoting/StorageClient.d.ts +283 -0
  306. package/mobile/out/src/storage/remoting/StorageClient.d.ts.map +1 -0
  307. package/mobile/out/src/storage/remoting/StorageClient.js +477 -0
  308. package/mobile/out/src/storage/remoting/StorageClient.js.map +1 -0
  309. package/mobile/out/src/storage/schema/StorageIdbSchema.d.ts +133 -0
  310. package/mobile/out/src/storage/schema/StorageIdbSchema.d.ts.map +1 -0
  311. package/mobile/out/src/storage/schema/StorageIdbSchema.js +3 -0
  312. package/mobile/out/src/storage/schema/StorageIdbSchema.js.map +1 -0
  313. package/mobile/out/src/storage/schema/entities/EntityBase.d.ts +105 -0
  314. package/mobile/out/src/storage/schema/entities/EntityBase.d.ts.map +1 -0
  315. package/mobile/out/src/storage/schema/entities/EntityBase.js +100 -0
  316. package/mobile/out/src/storage/schema/entities/EntityBase.js.map +1 -0
  317. package/mobile/out/src/storage/schema/entities/EntityCertificate.d.ts +43 -0
  318. package/mobile/out/src/storage/schema/entities/EntityCertificate.d.ts.map +1 -0
  319. package/mobile/out/src/storage/schema/entities/EntityCertificate.js +162 -0
  320. package/mobile/out/src/storage/schema/entities/EntityCertificate.js.map +1 -0
  321. package/mobile/out/src/storage/schema/entities/EntityCertificateField.d.ts +32 -0
  322. package/mobile/out/src/storage/schema/entities/EntityCertificateField.d.ts.map +1 -0
  323. package/mobile/out/src/storage/schema/entities/EntityCertificateField.js +111 -0
  324. package/mobile/out/src/storage/schema/entities/EntityCertificateField.js.map +1 -0
  325. package/mobile/out/src/storage/schema/entities/EntityCommission.d.ts +37 -0
  326. package/mobile/out/src/storage/schema/entities/EntityCommission.d.ts.map +1 -0
  327. package/mobile/out/src/storage/schema/entities/EntityCommission.js +127 -0
  328. package/mobile/out/src/storage/schema/entities/EntityCommission.js.map +1 -0
  329. package/mobile/out/src/storage/schema/entities/EntityOutput.d.ts +67 -0
  330. package/mobile/out/src/storage/schema/entities/EntityOutput.d.ts.map +1 -0
  331. package/mobile/out/src/storage/schema/entities/EntityOutput.js +264 -0
  332. package/mobile/out/src/storage/schema/entities/EntityOutput.js.map +1 -0
  333. package/mobile/out/src/storage/schema/entities/EntityOutputBasket.d.ts +35 -0
  334. package/mobile/out/src/storage/schema/entities/EntityOutputBasket.d.ts.map +1 -0
  335. package/mobile/out/src/storage/schema/entities/EntityOutputBasket.js +133 -0
  336. package/mobile/out/src/storage/schema/entities/EntityOutputBasket.js.map +1 -0
  337. package/mobile/out/src/storage/schema/entities/EntityOutputTag.d.ts +31 -0
  338. package/mobile/out/src/storage/schema/entities/EntityOutputTag.d.ts.map +1 -0
  339. package/mobile/out/src/storage/schema/entities/EntityOutputTag.js +104 -0
  340. package/mobile/out/src/storage/schema/entities/EntityOutputTag.js.map +1 -0
  341. package/mobile/out/src/storage/schema/entities/EntityOutputTagMap.d.ts +28 -0
  342. package/mobile/out/src/storage/schema/entities/EntityOutputTagMap.d.ts.map +1 -0
  343. package/mobile/out/src/storage/schema/entities/EntityOutputTagMap.js +97 -0
  344. package/mobile/out/src/storage/schema/entities/EntityOutputTagMap.js.map +1 -0
  345. package/mobile/out/src/storage/schema/entities/EntityProvenTx.d.ts +84 -0
  346. package/mobile/out/src/storage/schema/entities/EntityProvenTx.d.ts.map +1 -0
  347. package/mobile/out/src/storage/schema/entities/EntityProvenTx.js +276 -0
  348. package/mobile/out/src/storage/schema/entities/EntityProvenTx.js.map +1 -0
  349. package/mobile/out/src/storage/schema/entities/EntityProvenTxReq.d.ts +135 -0
  350. package/mobile/out/src/storage/schema/entities/EntityProvenTxReq.d.ts.map +1 -0
  351. package/mobile/out/src/storage/schema/entities/EntityProvenTxReq.js +522 -0
  352. package/mobile/out/src/storage/schema/entities/EntityProvenTxReq.js.map +1 -0
  353. package/mobile/out/src/storage/schema/entities/EntitySyncState.d.ts +67 -0
  354. package/mobile/out/src/storage/schema/entities/EntitySyncState.d.ts.map +1 -0
  355. package/mobile/out/src/storage/schema/entities/EntitySyncState.js +319 -0
  356. package/mobile/out/src/storage/schema/entities/EntitySyncState.js.map +1 -0
  357. package/mobile/out/src/storage/schema/entities/EntityTransaction.d.ts +67 -0
  358. package/mobile/out/src/storage/schema/entities/EntityTransaction.d.ts.map +1 -0
  359. package/mobile/out/src/storage/schema/entities/EntityTransaction.js +255 -0
  360. package/mobile/out/src/storage/schema/entities/EntityTransaction.js.map +1 -0
  361. package/mobile/out/src/storage/schema/entities/EntityTxLabel.d.ts +31 -0
  362. package/mobile/out/src/storage/schema/entities/EntityTxLabel.d.ts.map +1 -0
  363. package/mobile/out/src/storage/schema/entities/EntityTxLabel.js +104 -0
  364. package/mobile/out/src/storage/schema/entities/EntityTxLabel.js.map +1 -0
  365. package/mobile/out/src/storage/schema/entities/EntityTxLabelMap.d.ts +28 -0
  366. package/mobile/out/src/storage/schema/entities/EntityTxLabelMap.d.ts.map +1 -0
  367. package/mobile/out/src/storage/schema/entities/EntityTxLabelMap.js +97 -0
  368. package/mobile/out/src/storage/schema/entities/EntityTxLabelMap.js.map +1 -0
  369. package/mobile/out/src/storage/schema/entities/EntityUser.d.ts +29 -0
  370. package/mobile/out/src/storage/schema/entities/EntityUser.d.ts.map +1 -0
  371. package/mobile/out/src/storage/schema/entities/EntityUser.js +98 -0
  372. package/mobile/out/src/storage/schema/entities/EntityUser.js.map +1 -0
  373. package/mobile/out/src/storage/schema/entities/MergeEntity.d.ts +33 -0
  374. package/mobile/out/src/storage/schema/entities/MergeEntity.d.ts.map +1 -0
  375. package/mobile/out/src/storage/schema/entities/MergeEntity.js +62 -0
  376. package/mobile/out/src/storage/schema/entities/MergeEntity.js.map +1 -0
  377. package/mobile/out/src/storage/schema/entities/index.d.ts +17 -0
  378. package/mobile/out/src/storage/schema/entities/index.d.ts.map +1 -0
  379. package/mobile/out/src/storage/schema/entities/index.js +33 -0
  380. package/mobile/out/src/storage/schema/entities/index.js.map +1 -0
  381. package/mobile/out/src/storage/schema/tables/TableCertificate.d.ts +20 -0
  382. package/mobile/out/src/storage/schema/tables/TableCertificate.d.ts.map +1 -0
  383. package/mobile/out/src/storage/schema/tables/TableCertificate.js +3 -0
  384. package/mobile/out/src/storage/schema/tables/TableCertificate.js.map +1 -0
  385. package/mobile/out/src/storage/schema/tables/TableCertificateField.d.ts +12 -0
  386. package/mobile/out/src/storage/schema/tables/TableCertificateField.d.ts.map +1 -0
  387. package/mobile/out/src/storage/schema/tables/TableCertificateField.js +3 -0
  388. package/mobile/out/src/storage/schema/tables/TableCertificateField.js.map +1 -0
  389. package/mobile/out/src/storage/schema/tables/TableCommission.d.ts +13 -0
  390. package/mobile/out/src/storage/schema/tables/TableCommission.d.ts.map +1 -0
  391. package/mobile/out/src/storage/schema/tables/TableCommission.js +3 -0
  392. package/mobile/out/src/storage/schema/tables/TableCommission.js.map +1 -0
  393. package/mobile/out/src/storage/schema/tables/TableMonitorEvent.d.ts +9 -0
  394. package/mobile/out/src/storage/schema/tables/TableMonitorEvent.d.ts.map +1 -0
  395. package/mobile/out/src/storage/schema/tables/TableMonitorEvent.js +3 -0
  396. package/mobile/out/src/storage/schema/tables/TableMonitorEvent.js.map +1 -0
  397. package/mobile/out/src/storage/schema/tables/TableOutput.d.ts +36 -0
  398. package/mobile/out/src/storage/schema/tables/TableOutput.d.ts.map +1 -0
  399. package/mobile/out/src/storage/schema/tables/TableOutput.js +31 -0
  400. package/mobile/out/src/storage/schema/tables/TableOutput.js.map +1 -0
  401. package/mobile/out/src/storage/schema/tables/TableOutputBasket.d.ts +12 -0
  402. package/mobile/out/src/storage/schema/tables/TableOutputBasket.d.ts.map +1 -0
  403. package/mobile/out/src/storage/schema/tables/TableOutputBasket.js +3 -0
  404. package/mobile/out/src/storage/schema/tables/TableOutputBasket.js.map +1 -0
  405. package/mobile/out/src/storage/schema/tables/TableOutputTag.d.ts +10 -0
  406. package/mobile/out/src/storage/schema/tables/TableOutputTag.d.ts.map +1 -0
  407. package/mobile/out/src/storage/schema/tables/TableOutputTag.js +3 -0
  408. package/mobile/out/src/storage/schema/tables/TableOutputTag.js.map +1 -0
  409. package/mobile/out/src/storage/schema/tables/TableOutputTagMap.d.ts +9 -0
  410. package/mobile/out/src/storage/schema/tables/TableOutputTagMap.d.ts.map +1 -0
  411. package/mobile/out/src/storage/schema/tables/TableOutputTagMap.js +3 -0
  412. package/mobile/out/src/storage/schema/tables/TableOutputTagMap.js.map +1 -0
  413. package/mobile/out/src/storage/schema/tables/TableProvenTx.d.ts +14 -0
  414. package/mobile/out/src/storage/schema/tables/TableProvenTx.d.ts.map +1 -0
  415. package/mobile/out/src/storage/schema/tables/TableProvenTx.js +3 -0
  416. package/mobile/out/src/storage/schema/tables/TableProvenTx.js.map +1 -0
  417. package/mobile/out/src/storage/schema/tables/TableProvenTxReq.d.ts +64 -0
  418. package/mobile/out/src/storage/schema/tables/TableProvenTxReq.d.ts.map +1 -0
  419. package/mobile/out/src/storage/schema/tables/TableProvenTxReq.js +3 -0
  420. package/mobile/out/src/storage/schema/tables/TableProvenTxReq.js.map +1 -0
  421. package/mobile/out/src/storage/schema/tables/TableSettings.d.ts +17 -0
  422. package/mobile/out/src/storage/schema/tables/TableSettings.d.ts.map +1 -0
  423. package/mobile/out/src/storage/schema/tables/TableSettings.js +3 -0
  424. package/mobile/out/src/storage/schema/tables/TableSettings.js.map +1 -0
  425. package/mobile/out/src/storage/schema/tables/TableSyncState.d.ts +18 -0
  426. package/mobile/out/src/storage/schema/tables/TableSyncState.d.ts.map +1 -0
  427. package/mobile/out/src/storage/schema/tables/TableSyncState.js +3 -0
  428. package/mobile/out/src/storage/schema/tables/TableSyncState.js.map +1 -0
  429. package/mobile/out/src/storage/schema/tables/TableTransaction.d.ts +37 -0
  430. package/mobile/out/src/storage/schema/tables/TableTransaction.d.ts.map +1 -0
  431. package/mobile/out/src/storage/schema/tables/TableTransaction.js +21 -0
  432. package/mobile/out/src/storage/schema/tables/TableTransaction.js.map +1 -0
  433. package/mobile/out/src/storage/schema/tables/TableTxLabel.d.ts +10 -0
  434. package/mobile/out/src/storage/schema/tables/TableTxLabel.d.ts.map +1 -0
  435. package/mobile/out/src/storage/schema/tables/TableTxLabel.js +3 -0
  436. package/mobile/out/src/storage/schema/tables/TableTxLabel.js.map +1 -0
  437. package/mobile/out/src/storage/schema/tables/TableTxLabelMap.d.ts +9 -0
  438. package/mobile/out/src/storage/schema/tables/TableTxLabelMap.d.ts.map +1 -0
  439. package/mobile/out/src/storage/schema/tables/TableTxLabelMap.js +3 -0
  440. package/mobile/out/src/storage/schema/tables/TableTxLabelMap.js.map +1 -0
  441. package/mobile/out/src/storage/schema/tables/TableUser.d.ts +16 -0
  442. package/mobile/out/src/storage/schema/tables/TableUser.d.ts.map +1 -0
  443. package/mobile/out/src/storage/schema/tables/TableUser.js +3 -0
  444. package/mobile/out/src/storage/schema/tables/TableUser.js.map +1 -0
  445. package/mobile/out/src/storage/schema/tables/index.d.ts +17 -0
  446. package/mobile/out/src/storage/schema/tables/index.d.ts.map +1 -0
  447. package/mobile/out/src/storage/schema/tables/index.js +33 -0
  448. package/mobile/out/src/storage/schema/tables/index.js.map +1 -0
  449. package/mobile/out/src/utility/ScriptTemplateBRC29.d.ts +25 -0
  450. package/mobile/out/src/utility/ScriptTemplateBRC29.d.ts.map +1 -0
  451. package/mobile/out/src/utility/ScriptTemplateBRC29.js +48 -0
  452. package/mobile/out/src/utility/ScriptTemplateBRC29.js.map +1 -0
  453. package/mobile/out/src/utility/identityUtils.d.ts +31 -0
  454. package/mobile/out/src/utility/identityUtils.d.ts.map +1 -0
  455. package/mobile/out/src/utility/identityUtils.js +116 -0
  456. package/mobile/out/src/utility/identityUtils.js.map +1 -0
  457. package/mobile/out/src/utility/index.client.d.ts +7 -0
  458. package/mobile/out/src/utility/index.client.d.ts.map +1 -0
  459. package/mobile/out/src/utility/index.client.js +23 -0
  460. package/mobile/out/src/utility/index.client.js.map +1 -0
  461. package/mobile/out/src/utility/parseTxScriptOffsets.d.ts +14 -0
  462. package/mobile/out/src/utility/parseTxScriptOffsets.d.ts.map +1 -0
  463. package/mobile/out/src/utility/parseTxScriptOffsets.js +26 -0
  464. package/mobile/out/src/utility/parseTxScriptOffsets.js.map +1 -0
  465. package/mobile/out/src/utility/stampLog.d.ts +18 -0
  466. package/mobile/out/src/utility/stampLog.d.ts.map +1 -0
  467. package/mobile/out/src/utility/stampLog.js +72 -0
  468. package/mobile/out/src/utility/stampLog.js.map +1 -0
  469. package/mobile/out/src/utility/tscProofToMerklePath.d.ts +8 -0
  470. package/mobile/out/src/utility/tscProofToMerklePath.d.ts.map +1 -0
  471. package/mobile/out/src/utility/tscProofToMerklePath.js +41 -0
  472. package/mobile/out/src/utility/tscProofToMerklePath.js.map +1 -0
  473. package/mobile/out/src/utility/utilityHelpers.d.ts +129 -0
  474. package/mobile/out/src/utility/utilityHelpers.d.ts.map +1 -0
  475. package/mobile/out/src/utility/utilityHelpers.js +266 -0
  476. package/mobile/out/src/utility/utilityHelpers.js.map +1 -0
  477. package/mobile/out/src/utility/utilityHelpers.noBuffer.d.ts +9 -0
  478. package/mobile/out/src/utility/utilityHelpers.noBuffer.d.ts.map +1 -0
  479. package/mobile/out/src/utility/utilityHelpers.noBuffer.js +23 -0
  480. package/mobile/out/src/utility/utilityHelpers.noBuffer.js.map +1 -0
  481. package/mobile/out/src/wab-client/WABClient.d.ts +49 -0
  482. package/mobile/out/src/wab-client/WABClient.d.ts.map +1 -0
  483. package/mobile/out/src/wab-client/WABClient.js +80 -0
  484. package/mobile/out/src/wab-client/WABClient.js.map +1 -0
  485. package/mobile/out/src/wab-client/auth-method-interactors/AuthMethodInteractor.d.ts +34 -0
  486. package/mobile/out/src/wab-client/auth-method-interactors/AuthMethodInteractor.d.ts.map +1 -0
  487. package/mobile/out/src/wab-client/auth-method-interactors/AuthMethodInteractor.js +16 -0
  488. package/mobile/out/src/wab-client/auth-method-interactors/AuthMethodInteractor.js.map +1 -0
  489. package/mobile/out/src/wab-client/auth-method-interactors/PersonaIDInteractor.d.ts +7 -0
  490. package/mobile/out/src/wab-client/auth-method-interactors/PersonaIDInteractor.d.ts.map +1 -0
  491. package/mobile/out/src/wab-client/auth-method-interactors/PersonaIDInteractor.js +36 -0
  492. package/mobile/out/src/wab-client/auth-method-interactors/PersonaIDInteractor.js.map +1 -0
  493. package/mobile/out/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.d.ts +28 -0
  494. package/mobile/out/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.d.ts.map +1 -0
  495. package/mobile/out/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.js +69 -0
  496. package/mobile/out/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.js.map +1 -0
  497. package/mobile/out/tsconfig.mobile.tsbuildinfo +1 -0
  498. package/mobile/package-lock.json +5 -12
  499. package/mobile/package.json +1 -1
  500. package/package.json +1 -1
  501. package/tsconfig.json +3 -0
  502. package/tsconfig.mobile.json +22 -0
@@ -0,0 +1,1255 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CWIStyleWalletManager = exports.OverlayUMPTokenInteractor = exports.DEFAULT_PROFILE_ID = exports.PBKDF2_NUM_ROUNDS = void 0;
4
+ const sdk_1 = require("@bsv/sdk");
5
+ const PrivilegedKeyManager_1 = require("./sdk/PrivilegedKeyManager");
6
+ /**
7
+ * Number of rounds used in PBKDF2 for deriving password keys.
8
+ */
9
+ exports.PBKDF2_NUM_ROUNDS = 7777;
10
+ /**
11
+ * Unique Identifier for the default profile (16 zero bytes).
12
+ */
13
+ exports.DEFAULT_PROFILE_ID = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
14
+ /**
15
+ * @class OverlayUMPTokenInteractor
16
+ *
17
+ * A concrete implementation of the UMPTokenInteractor interface that interacts
18
+ * with Overlay Services and the UMP (User Management Protocol) topic. This class
19
+ * is responsible for:
20
+ *
21
+ * 1) Locating UMP tokens via overlay lookups (ls_users).
22
+ * 2) Creating and publishing new or updated UMP token outputs on-chain under
23
+ * the "tm_users" topic.
24
+ * 3) Consuming (spending) an old token if provided.
25
+ */
26
+ class OverlayUMPTokenInteractor {
27
+ /**
28
+ * Construct a new OverlayUMPTokenInteractor.
29
+ *
30
+ * @param resolver A LookupResolver instance for performing overlay queries (ls_users).
31
+ * @param broadcaster A SHIPBroadcaster instance for sharing new or updated tokens across the `tm_users` overlay.
32
+ */
33
+ constructor(resolver = new sdk_1.LookupResolver(), broadcaster = new sdk_1.SHIPBroadcaster(['tm_users'])) {
34
+ this.resolver = resolver;
35
+ this.broadcaster = broadcaster;
36
+ }
37
+ /**
38
+ * Finds a UMP token on-chain by the given presentation key hash, if it exists.
39
+ * Uses the ls_users overlay service to perform the lookup.
40
+ *
41
+ * @param hash The 32-byte SHA-256 hash of the presentation key.
42
+ * @returns A UMPToken object (including currentOutpoint) if found, otherwise undefined.
43
+ */
44
+ async findByPresentationKeyHash(hash) {
45
+ // Query ls_users for the given presentationHash
46
+ const question = {
47
+ service: 'ls_users',
48
+ query: { presentationHash: sdk_1.Utils.toHex(hash) }
49
+ };
50
+ const answer = await this.resolver.query(question);
51
+ return this.parseLookupAnswer(answer);
52
+ }
53
+ /**
54
+ * Finds a UMP token on-chain by the given recovery key hash, if it exists.
55
+ * Uses the ls_users overlay service to perform the lookup.
56
+ *
57
+ * @param hash The 32-byte SHA-256 hash of the recovery key.
58
+ * @returns A UMPToken object (including currentOutpoint) if found, otherwise undefined.
59
+ */
60
+ async findByRecoveryKeyHash(hash) {
61
+ const question = {
62
+ service: 'ls_users',
63
+ query: { recoveryHash: sdk_1.Utils.toHex(hash) }
64
+ };
65
+ const answer = await this.resolver.query(question);
66
+ return this.parseLookupAnswer(answer);
67
+ }
68
+ /**
69
+ * Creates or updates (replaces) a UMP token on-chain. If `oldTokenToConsume` is provided,
70
+ * it is spent in the same transaction that creates the new token output. The new token is
71
+ * then broadcast and published under the `tm_users` topic using a SHIP broadcast, ensuring
72
+ * overlay participants see the updated token.
73
+ *
74
+ * @param wallet The wallet used to build and sign the transaction (MUST be operating under the DEFAULT profile).
75
+ * @param adminOriginator The domain/FQDN of the administrative originator (wallet operator).
76
+ * @param token The new UMPToken to create on-chain.
77
+ * @param oldTokenToConsume Optionally, an existing token to consume/spend in the same transaction.
78
+ * @returns The outpoint of the newly created UMP token (e.g. "abcd1234...ef.0").
79
+ */
80
+ async buildAndSend(wallet, // This wallet MUST be the one built for the default profile
81
+ adminOriginator, token, oldTokenToConsume) {
82
+ // 1) Construct the data fields for the new UMP token.
83
+ const fields = [];
84
+ fields[0] = token.passwordSalt;
85
+ fields[1] = token.passwordPresentationPrimary;
86
+ fields[2] = token.passwordRecoveryPrimary;
87
+ fields[3] = token.presentationRecoveryPrimary;
88
+ fields[4] = token.passwordPrimaryPrivileged;
89
+ fields[5] = token.presentationRecoveryPrivileged;
90
+ fields[6] = token.presentationHash;
91
+ fields[7] = token.recoveryHash;
92
+ fields[8] = token.presentationKeyEncrypted;
93
+ fields[9] = token.passwordKeyEncrypted;
94
+ fields[10] = token.recoveryKeyEncrypted;
95
+ // Optional field (11) for encrypted profiles
96
+ if (token.profilesEncrypted) {
97
+ fields[11] = token.profilesEncrypted;
98
+ }
99
+ // 2) Create a PushDrop script referencing these fields, locked with the admin key.
100
+ const script = await new sdk_1.PushDrop(wallet, adminOriginator).lock(fields, [2, 'admin user management token'], // protocolID
101
+ '1', // keyID
102
+ 'self', // counterparty
103
+ /*forSelf=*/ true,
104
+ /*includeSignature=*/ true);
105
+ // 3) Prepare the createAction call. If oldTokenToConsume is provided, gather the outpoint.
106
+ const inputs = [];
107
+ let inputToken;
108
+ if (oldTokenToConsume === null || oldTokenToConsume === void 0 ? void 0 : oldTokenToConsume.currentOutpoint) {
109
+ inputToken = await this.findByOutpoint(oldTokenToConsume.currentOutpoint);
110
+ // If there is no token on the overlay, we can't consume it. Just start over with a new token.
111
+ if (!inputToken) {
112
+ oldTokenToConsume = undefined;
113
+ // Otherwise, add the input
114
+ }
115
+ else {
116
+ inputs.push({
117
+ outpoint: oldTokenToConsume.currentOutpoint,
118
+ unlockingScriptLength: 73, // typical signature length
119
+ inputDescription: 'Consume old UMP token'
120
+ });
121
+ }
122
+ }
123
+ const outputs = [
124
+ {
125
+ lockingScript: script.toHex(),
126
+ satoshis: 1,
127
+ outputDescription: 'New UMP token output'
128
+ }
129
+ ];
130
+ // 4) Build the partial transaction via createAction.
131
+ let createResult;
132
+ try {
133
+ createResult = await wallet.createAction({
134
+ description: oldTokenToConsume ? 'Renew UMP token (consume old, create new)' : 'Create new UMP token',
135
+ inputs,
136
+ outputs,
137
+ inputBEEF: inputToken === null || inputToken === void 0 ? void 0 : inputToken.beef,
138
+ options: {
139
+ randomizeOutputs: false,
140
+ acceptDelayedBroadcast: false
141
+ }
142
+ }, adminOriginator);
143
+ }
144
+ catch (e) {
145
+ console.error('Error with UMP token update. Attempting a last-ditch effort to get a new one', e);
146
+ createResult = await wallet.createAction({
147
+ description: 'Recover UMP token',
148
+ outputs,
149
+ options: {
150
+ randomizeOutputs: false,
151
+ acceptDelayedBroadcast: false
152
+ }
153
+ }, adminOriginator);
154
+ }
155
+ // If the transaction is fully processed by the wallet
156
+ if (!createResult.signableTransaction) {
157
+ const finalTxid = createResult.txid || (createResult.tx ? sdk_1.Transaction.fromAtomicBEEF(createResult.tx).id('hex') : undefined);
158
+ if (!finalTxid) {
159
+ throw new Error('No signableTransaction and no final TX found.');
160
+ }
161
+ // Now broadcast to `tm_users` using SHIP
162
+ const broadcastTx = sdk_1.Transaction.fromAtomicBEEF(createResult.tx);
163
+ const result = await this.broadcaster.broadcast(broadcastTx);
164
+ console.log('BROADCAST RESULT', result);
165
+ return `${finalTxid}.0`;
166
+ }
167
+ // 5) If oldTokenToConsume is present, we must sign the input referencing it.
168
+ // (If there's no old token, there's nothing to sign for the input.)
169
+ let finalTxid = '';
170
+ const reference = createResult.signableTransaction.reference;
171
+ const partialTx = sdk_1.Transaction.fromBEEF(createResult.signableTransaction.tx);
172
+ if (oldTokenToConsume === null || oldTokenToConsume === void 0 ? void 0 : oldTokenToConsume.currentOutpoint) {
173
+ // Unlock the old token with a matching PushDrop unlocker
174
+ const unlocker = new sdk_1.PushDrop(wallet, adminOriginator).unlock([2, 'admin user management token'], '1', 'self');
175
+ const unlockingScript = await unlocker.sign(partialTx, 0);
176
+ // Provide it to the wallet
177
+ const signResult = await wallet.signAction({
178
+ reference,
179
+ spends: {
180
+ 0: {
181
+ unlockingScript: unlockingScript.toHex()
182
+ }
183
+ }
184
+ }, adminOriginator);
185
+ finalTxid = signResult.txid || (signResult.tx ? sdk_1.Transaction.fromAtomicBEEF(signResult.tx).id('hex') : '');
186
+ if (!finalTxid) {
187
+ throw new Error('Could not finalize transaction for renewed UMP token.');
188
+ }
189
+ // 6) Broadcast to `tm_users`
190
+ const finalAtomicTx = signResult.tx;
191
+ if (!finalAtomicTx) {
192
+ throw new Error('Final transaction data missing after signing renewed UMP token.');
193
+ }
194
+ const broadcastTx = sdk_1.Transaction.fromAtomicBEEF(finalAtomicTx);
195
+ const result = await this.broadcaster.broadcast(broadcastTx);
196
+ console.log('BROADCAST RESULT', result);
197
+ return `${finalTxid}.0`;
198
+ }
199
+ else {
200
+ // Fallback for creating a new token (no input spending)
201
+ const signResult = await wallet.signAction({ reference, spends: {} }, adminOriginator);
202
+ finalTxid = signResult.txid || (signResult.tx ? sdk_1.Transaction.fromAtomicBEEF(signResult.tx).id('hex') : '');
203
+ if (!finalTxid) {
204
+ throw new Error('Failed to finalize new UMP token transaction.');
205
+ }
206
+ const finalAtomicTx = signResult.tx;
207
+ if (!finalAtomicTx) {
208
+ throw new Error('Final transaction data missing after signing new UMP token.');
209
+ }
210
+ const broadcastTx = sdk_1.Transaction.fromAtomicBEEF(finalAtomicTx);
211
+ const result = await this.broadcaster.broadcast(broadcastTx);
212
+ console.log('BROADCAST RESULT', result);
213
+ return `${finalTxid}.0`;
214
+ }
215
+ }
216
+ /**
217
+ * Attempts to parse a LookupAnswer from the UMP lookup service. If successful,
218
+ * extracts the token fields from the resulting transaction and constructs
219
+ * a UMPToken object.
220
+ *
221
+ * @param answer The LookupAnswer returned by a query to ls_users.
222
+ * @returns The parsed UMPToken or `undefined` if none found/decodable.
223
+ */
224
+ parseLookupAnswer(answer) {
225
+ var _a;
226
+ if (answer.type !== 'output-list') {
227
+ return undefined;
228
+ }
229
+ if (!answer.outputs || answer.outputs.length === 0) {
230
+ return undefined;
231
+ }
232
+ const { beef, outputIndex } = answer.outputs[0];
233
+ try {
234
+ const tx = sdk_1.Transaction.fromBEEF(beef);
235
+ const outpoint = `${tx.id('hex')}.${outputIndex}`;
236
+ const decoded = sdk_1.PushDrop.decode(tx.outputs[outputIndex].lockingScript);
237
+ // Expecting 11 or more fields for UMP
238
+ if (!decoded.fields || decoded.fields.length < 11) {
239
+ console.warn(`Unexpected number of fields in UMP token: ${(_a = decoded.fields) === null || _a === void 0 ? void 0 : _a.length}`);
240
+ return undefined;
241
+ }
242
+ // Build the UMP token from these fields, preserving outpoint
243
+ const t = {
244
+ // Order matches buildAndSend and serialize/deserialize
245
+ passwordSalt: decoded.fields[0],
246
+ passwordPresentationPrimary: decoded.fields[1],
247
+ passwordRecoveryPrimary: decoded.fields[2],
248
+ presentationRecoveryPrimary: decoded.fields[3],
249
+ passwordPrimaryPrivileged: decoded.fields[4],
250
+ presentationRecoveryPrivileged: decoded.fields[5],
251
+ presentationHash: decoded.fields[6],
252
+ recoveryHash: decoded.fields[7],
253
+ presentationKeyEncrypted: decoded.fields[8],
254
+ passwordKeyEncrypted: decoded.fields[9],
255
+ recoveryKeyEncrypted: decoded.fields[10],
256
+ profilesEncrypted: decoded.fields[12] ? decoded.fields[11] : undefined, // If there's a signature in field 12, use field 11
257
+ currentOutpoint: outpoint
258
+ };
259
+ return t;
260
+ }
261
+ catch (e) {
262
+ console.error('Failed to parse or decode UMP token:', e);
263
+ return undefined;
264
+ }
265
+ }
266
+ /**
267
+ * Finds by outpoint for unlocking / spending previous tokens.
268
+ * @param outpoint The outpoint we are searching by
269
+ * @returns The result so that we can use it to unlock the transaction
270
+ */
271
+ async findByOutpoint(outpoint) {
272
+ const results = await this.resolver.query({
273
+ service: 'ls_users',
274
+ query: {
275
+ outpoint
276
+ }
277
+ });
278
+ if (results.type !== 'output-list') {
279
+ return undefined;
280
+ }
281
+ if (!results.outputs || !results.outputs.length) {
282
+ return undefined;
283
+ }
284
+ return results.outputs[0];
285
+ }
286
+ }
287
+ exports.OverlayUMPTokenInteractor = OverlayUMPTokenInteractor;
288
+ /**
289
+ * Manages a "CWI-style" wallet that uses a UMP token and a
290
+ * multi-key authentication scheme (password, presentation key, and recovery key),
291
+ * supporting multiple user profiles under a single account.
292
+ */
293
+ class CWIStyleWalletManager {
294
+ /**
295
+ * Constructs a new CWIStyleWalletManager.
296
+ *
297
+ * @param adminOriginator The domain name of the administrative originator.
298
+ * @param walletBuilder A function that can build an underlying wallet instance for a profile.
299
+ * @param interactor An instance of UMPTokenInteractor.
300
+ * @param recoveryKeySaver A function to persist a new recovery key.
301
+ * @param passwordRetriever A function to request the user's password.
302
+ * @param newWalletFunder Optional function to fund a new wallet.
303
+ * @param stateSnapshot Optional previously saved state snapshot.
304
+ */
305
+ constructor(adminOriginator, walletBuilder, interactor = new OverlayUMPTokenInteractor(), recoveryKeySaver, passwordRetriever, newWalletFunder, stateSnapshot) {
306
+ /**
307
+ * Current mode of authentication.
308
+ */
309
+ this.authenticationMode = 'presentation-key-and-password';
310
+ /**
311
+ * Indicates new user or existing user flow.
312
+ */
313
+ this.authenticationFlow = 'new-user';
314
+ /**
315
+ * The currently active profile ID (null or DEFAULT_PROFILE_ID means default profile).
316
+ */
317
+ this.activeProfileId = exports.DEFAULT_PROFILE_ID;
318
+ /**
319
+ * List of loaded non-default profiles.
320
+ */
321
+ this.profiles = [];
322
+ this.adminOriginator = adminOriginator;
323
+ this.walletBuilder = walletBuilder;
324
+ this.UMPTokenInteractor = interactor;
325
+ this.recoveryKeySaver = recoveryKeySaver;
326
+ this.passwordRetriever = passwordRetriever;
327
+ this.authenticated = false;
328
+ this.newWalletFunder = newWalletFunder;
329
+ // If a saved snapshot is provided, attempt to load it.
330
+ // Note: loadSnapshot now returns a promise. We don't await it here,
331
+ // as the constructor must be synchronous. The caller should check
332
+ // `this.authenticated` after construction if a snapshot was provided.
333
+ if (stateSnapshot) {
334
+ this.loadSnapshot(stateSnapshot).catch(err => {
335
+ console.error('Failed to load snapshot during construction:', err);
336
+ // Clear potentially partially loaded state
337
+ this.destroy();
338
+ });
339
+ }
340
+ }
341
+ // --- Authentication Methods ---
342
+ /**
343
+ * Provides the presentation key.
344
+ */
345
+ async providePresentationKey(key) {
346
+ if (this.authenticated) {
347
+ throw new Error('User is already authenticated');
348
+ }
349
+ if (this.authenticationMode === 'recovery-key-and-password') {
350
+ throw new Error('Presentation key is not needed in this mode');
351
+ }
352
+ const hash = sdk_1.Hash.sha256(key);
353
+ const token = await this.UMPTokenInteractor.findByPresentationKeyHash(hash);
354
+ if (!token) {
355
+ // No token found -> New user
356
+ this.authenticationFlow = 'new-user';
357
+ this.presentationKey = key;
358
+ }
359
+ else {
360
+ // Found token -> existing user
361
+ this.authenticationFlow = 'existing-user';
362
+ this.presentationKey = key;
363
+ this.currentUMPToken = token;
364
+ }
365
+ }
366
+ /**
367
+ * Provides the password.
368
+ */
369
+ async providePassword(password) {
370
+ if (this.authenticated) {
371
+ throw new Error('User is already authenticated');
372
+ }
373
+ if (this.authenticationMode === 'presentation-key-and-recovery-key') {
374
+ throw new Error('Password is not needed in this mode');
375
+ }
376
+ if (this.authenticationFlow === 'existing-user') {
377
+ // Existing user flow
378
+ if (!this.currentUMPToken) {
379
+ throw new Error('Provide presentation or recovery key first.');
380
+ }
381
+ const derivedPasswordKey = sdk_1.Hash.pbkdf2(sdk_1.Utils.toArray(password, 'utf8'), this.currentUMPToken.passwordSalt, exports.PBKDF2_NUM_ROUNDS, 32, 'sha512');
382
+ let rootPrimaryKey;
383
+ let rootPrivilegedKey; // Only needed for recovery mode
384
+ if (this.authenticationMode === 'presentation-key-and-password') {
385
+ if (!this.presentationKey)
386
+ throw new Error('No presentation key found!');
387
+ const xorKey = this.XOR(this.presentationKey, derivedPasswordKey);
388
+ rootPrimaryKey = new sdk_1.SymmetricKey(xorKey).decrypt(this.currentUMPToken.passwordPresentationPrimary);
389
+ }
390
+ else {
391
+ // 'recovery-key-and-password'
392
+ if (!this.recoveryKey)
393
+ throw new Error('No recovery key found!');
394
+ const primaryDecryptionKey = this.XOR(this.recoveryKey, derivedPasswordKey);
395
+ rootPrimaryKey = new sdk_1.SymmetricKey(primaryDecryptionKey).decrypt(this.currentUMPToken.passwordRecoveryPrimary);
396
+ const privilegedDecryptionKey = this.XOR(rootPrimaryKey, derivedPasswordKey);
397
+ rootPrivilegedKey = new sdk_1.SymmetricKey(privilegedDecryptionKey).decrypt(this.currentUMPToken.passwordPrimaryPrivileged);
398
+ }
399
+ // Build root infrastructure, load profiles, and switch to default profile initially
400
+ await this.setupRootInfrastructure(rootPrimaryKey, rootPrivilegedKey);
401
+ await this.switchProfile(this.activeProfileId);
402
+ }
403
+ else {
404
+ // New user flow (only 'presentation-key-and-password')
405
+ if (this.authenticationMode !== 'presentation-key-and-password') {
406
+ throw new Error('New-user flow requires presentation key and password mode.');
407
+ }
408
+ if (!this.presentationKey) {
409
+ throw new Error('No presentation key provided for new-user flow.');
410
+ }
411
+ // Generate new keys/salt
412
+ const recoveryKey = (0, sdk_1.Random)(32);
413
+ await this.recoveryKeySaver(recoveryKey);
414
+ const passwordSalt = (0, sdk_1.Random)(32);
415
+ const passwordKey = sdk_1.Hash.pbkdf2(sdk_1.Utils.toArray(password, 'utf8'), passwordSalt, exports.PBKDF2_NUM_ROUNDS, 32, 'sha512');
416
+ const rootPrimaryKey = (0, sdk_1.Random)(32);
417
+ const rootPrivilegedKey = (0, sdk_1.Random)(32);
418
+ // Build XOR keys
419
+ const presentationPassword = new sdk_1.SymmetricKey(this.XOR(this.presentationKey, passwordKey));
420
+ const presentationRecovery = new sdk_1.SymmetricKey(this.XOR(this.presentationKey, recoveryKey));
421
+ const recoveryPassword = new sdk_1.SymmetricKey(this.XOR(recoveryKey, passwordKey));
422
+ const primaryPassword = new sdk_1.SymmetricKey(this.XOR(rootPrimaryKey, passwordKey));
423
+ // Temp manager for encryption
424
+ const tempPrivilegedKeyManager = new PrivilegedKeyManager_1.PrivilegedKeyManager(async () => new sdk_1.PrivateKey(rootPrivilegedKey));
425
+ // Build new UMP token (no profiles initially)
426
+ const newToken = {
427
+ passwordSalt,
428
+ passwordPresentationPrimary: presentationPassword.encrypt(rootPrimaryKey),
429
+ passwordRecoveryPrimary: recoveryPassword.encrypt(rootPrimaryKey),
430
+ presentationRecoveryPrimary: presentationRecovery.encrypt(rootPrimaryKey),
431
+ passwordPrimaryPrivileged: primaryPassword.encrypt(rootPrivilegedKey),
432
+ presentationRecoveryPrivileged: presentationRecovery.encrypt(rootPrivilegedKey),
433
+ presentationHash: sdk_1.Hash.sha256(this.presentationKey),
434
+ recoveryHash: sdk_1.Hash.sha256(recoveryKey),
435
+ presentationKeyEncrypted: (await tempPrivilegedKeyManager.encrypt({
436
+ plaintext: this.presentationKey,
437
+ protocolID: [2, 'admin key wrapping'],
438
+ keyID: '1'
439
+ })).ciphertext,
440
+ passwordKeyEncrypted: (await tempPrivilegedKeyManager.encrypt({
441
+ plaintext: passwordKey,
442
+ protocolID: [2, 'admin key wrapping'],
443
+ keyID: '1'
444
+ })).ciphertext,
445
+ recoveryKeyEncrypted: (await tempPrivilegedKeyManager.encrypt({
446
+ plaintext: recoveryKey,
447
+ protocolID: [2, 'admin key wrapping'],
448
+ keyID: '1'
449
+ })).ciphertext,
450
+ profilesEncrypted: undefined // No profiles yet
451
+ };
452
+ this.currentUMPToken = newToken;
453
+ // Setup root infrastructure and switch to default profile
454
+ await this.setupRootInfrastructure(rootPrimaryKey);
455
+ await this.switchProfile(exports.DEFAULT_PROFILE_ID);
456
+ // Fund the *default* wallet if funder provided
457
+ if (this.newWalletFunder && this.underlying) {
458
+ try {
459
+ await this.newWalletFunder(this.presentationKey, this.underlying, this.adminOriginator);
460
+ }
461
+ catch (e) {
462
+ console.error('Error funding new wallet:', e);
463
+ // Decide if this should halt the process or just log
464
+ }
465
+ }
466
+ // Publish the new UMP token *after* potentially funding
467
+ // We need the default profile wallet to sign the UMP creation TX
468
+ if (!this.underlying) {
469
+ throw new Error('Default profile wallet not built before attempting to publish UMP token.');
470
+ }
471
+ this.currentUMPToken.currentOutpoint = await this.UMPTokenInteractor.buildAndSend(this.underlying, // Use the default profile wallet
472
+ this.adminOriginator, newToken);
473
+ }
474
+ }
475
+ /**
476
+ * Provides the recovery key.
477
+ */
478
+ async provideRecoveryKey(recoveryKey) {
479
+ if (this.authenticated) {
480
+ throw new Error('Already authenticated');
481
+ }
482
+ if (this.authenticationFlow === 'new-user') {
483
+ throw new Error('Do not submit recovery key in new-user flow');
484
+ }
485
+ if (this.authenticationMode === 'presentation-key-and-password') {
486
+ throw new Error('No recovery key required in this mode');
487
+ }
488
+ else if (this.authenticationMode === 'recovery-key-and-password') {
489
+ // Wait for password
490
+ const hash = sdk_1.Hash.sha256(recoveryKey);
491
+ const token = await this.UMPTokenInteractor.findByRecoveryKeyHash(hash);
492
+ if (!token)
493
+ throw new Error('No user found with this recovery key');
494
+ this.recoveryKey = recoveryKey;
495
+ this.currentUMPToken = token;
496
+ }
497
+ else {
498
+ // 'presentation-key-and-recovery-key'
499
+ if (!this.presentationKey)
500
+ throw new Error('Provide the presentation key first');
501
+ if (!this.currentUMPToken)
502
+ throw new Error('Current UMP token not found');
503
+ const xorKey = this.XOR(this.presentationKey, recoveryKey);
504
+ const rootPrimaryKey = new sdk_1.SymmetricKey(xorKey).decrypt(this.currentUMPToken.presentationRecoveryPrimary);
505
+ const rootPrivilegedKey = new sdk_1.SymmetricKey(xorKey).decrypt(this.currentUMPToken.presentationRecoveryPrivileged);
506
+ // Build root infrastructure, load profiles, switch to default
507
+ await this.setupRootInfrastructure(rootPrimaryKey, rootPrivilegedKey);
508
+ await this.switchProfile(this.activeProfileId);
509
+ }
510
+ }
511
+ // --- State Management Methods ---
512
+ /**
513
+ * Saves the current wallet state (root key, UMP token, active profile) into an encrypted snapshot.
514
+ * Version 2 format: [1 byte version=2] + [32 byte snapshot key] + [16 byte activeProfileId] + [encrypted payload]
515
+ * Encrypted Payload: [32 byte rootPrimaryKey] + [varint token length + serialized UMP token]
516
+ *
517
+ * @returns Encrypted snapshot bytes.
518
+ */
519
+ saveSnapshot() {
520
+ if (!this.rootPrimaryKey || !this.currentUMPToken) {
521
+ throw new Error('No root primary key or current UMP token set');
522
+ }
523
+ const snapshotKey = (0, sdk_1.Random)(32);
524
+ const snapshotPreimageWriter = new sdk_1.Utils.Writer();
525
+ // Write root primary key
526
+ snapshotPreimageWriter.write(this.rootPrimaryKey);
527
+ // Write serialized UMP token (must have outpoint)
528
+ if (!this.currentUMPToken.currentOutpoint) {
529
+ throw new Error('UMP token cannot be saved without a current outpoint.');
530
+ }
531
+ const serializedToken = this.serializeUMPToken(this.currentUMPToken);
532
+ snapshotPreimageWriter.writeVarIntNum(serializedToken.length);
533
+ snapshotPreimageWriter.write(serializedToken);
534
+ // Encrypt the payload
535
+ const snapshotPreimage = snapshotPreimageWriter.toArray();
536
+ const snapshotPayload = new sdk_1.SymmetricKey(snapshotKey).encrypt(snapshotPreimage);
537
+ // Build final snapshot (Version 2)
538
+ const snapshotWriter = new sdk_1.Utils.Writer();
539
+ snapshotWriter.writeUInt8(2); // Version
540
+ snapshotWriter.write(snapshotKey);
541
+ snapshotWriter.write(this.activeProfileId); // Active profile ID
542
+ snapshotWriter.write(snapshotPayload); // Encrypted data
543
+ return snapshotWriter.toArray();
544
+ }
545
+ /**
546
+ * Loads a previously saved state snapshot. Restores root key, UMP token, profiles, and active profile.
547
+ * Handles Version 1 (legacy) and Version 2 formats.
548
+ *
549
+ * @param snapshot Encrypted snapshot bytes.
550
+ */
551
+ async loadSnapshot(snapshot) {
552
+ try {
553
+ const reader = new sdk_1.Utils.Reader(snapshot);
554
+ const version = reader.readUInt8();
555
+ let snapshotKey;
556
+ let encryptedPayload;
557
+ let activeProfileId = exports.DEFAULT_PROFILE_ID; // Default for V1
558
+ if (version === 1) {
559
+ snapshotKey = reader.read(32);
560
+ encryptedPayload = reader.read();
561
+ }
562
+ else if (version === 2) {
563
+ snapshotKey = reader.read(32);
564
+ activeProfileId = reader.read(16); // Read active profile ID
565
+ encryptedPayload = reader.read();
566
+ }
567
+ else {
568
+ throw new Error(`Unsupported snapshot version: ${version}`);
569
+ }
570
+ // Decrypt payload
571
+ const decryptedPayload = new sdk_1.SymmetricKey(snapshotKey).decrypt(encryptedPayload);
572
+ const payloadReader = new sdk_1.Utils.Reader(decryptedPayload);
573
+ // Read root primary key
574
+ const rootPrimaryKey = payloadReader.read(32);
575
+ // Read serialized UMP token
576
+ const tokenLen = payloadReader.readVarIntNum();
577
+ const tokenBytes = payloadReader.read(tokenLen);
578
+ const token = this.deserializeUMPToken(tokenBytes);
579
+ // Assign loaded data
580
+ this.currentUMPToken = token;
581
+ // Setup root infrastructure, load profiles, and switch to the loaded active profile
582
+ await this.setupRootInfrastructure(rootPrimaryKey); // Will automatically load profiles
583
+ await this.switchProfile(activeProfileId); // Switch to the profile saved in the snapshot
584
+ this.authenticationFlow = 'existing-user'; // Loading implies existing user
585
+ }
586
+ catch (error) {
587
+ this.destroy(); // Clear state on error
588
+ throw new Error(`Failed to load snapshot: ${error.message}`);
589
+ }
590
+ }
591
+ /**
592
+ * Destroys the wallet state, clearing keys, tokens, and profiles.
593
+ */
594
+ destroy() {
595
+ this.underlying = undefined;
596
+ this.rootPrivilegedKeyManager = undefined;
597
+ this.authenticated = false;
598
+ this.rootPrimaryKey = undefined;
599
+ this.currentUMPToken = undefined;
600
+ this.presentationKey = undefined;
601
+ this.recoveryKey = undefined;
602
+ this.profiles = [];
603
+ this.activeProfileId = exports.DEFAULT_PROFILE_ID;
604
+ this.authenticationMode = 'presentation-key-and-password';
605
+ this.authenticationFlow = 'new-user';
606
+ }
607
+ // --- Profile Management Methods ---
608
+ /**
609
+ * Lists all available profiles, including the default profile.
610
+ * @returns Array of profile info objects, including an 'active' flag.
611
+ */
612
+ listProfiles() {
613
+ if (!this.authenticated) {
614
+ throw new Error('Not authenticated.');
615
+ }
616
+ const profileList = [
617
+ // Default profile
618
+ {
619
+ id: exports.DEFAULT_PROFILE_ID,
620
+ name: 'default',
621
+ createdAt: null, // Default profile doesn't have a creation timestamp in the same way
622
+ active: this.activeProfileId.every(x => x === 0)
623
+ },
624
+ // Other profiles
625
+ ...this.profiles.map(p => ({
626
+ id: p.id,
627
+ name: p.name,
628
+ createdAt: p.createdAt,
629
+ active: this.activeProfileId.every((x, i) => x === p.id[i])
630
+ }))
631
+ ];
632
+ return profileList;
633
+ }
634
+ /**
635
+ * Adds a new profile with the given name.
636
+ * Generates necessary pads and updates the UMP token.
637
+ * Does not switch to the new profile automatically.
638
+ *
639
+ * @param name The desired name for the new profile.
640
+ * @returns The ID of the newly created profile.
641
+ */
642
+ async addProfile(name) {
643
+ if (!this.authenticated || !this.rootPrimaryKey || !this.currentUMPToken || !this.rootPrivilegedKeyManager) {
644
+ throw new Error('Wallet not fully initialized or authenticated.');
645
+ }
646
+ // Ensure name is unique (including 'default')
647
+ if (name === 'default' || this.profiles.some(p => p.name.toLowerCase() === name.toLowerCase())) {
648
+ throw new Error(`Profile name "${name}" is already in use.`);
649
+ }
650
+ const newProfile = {
651
+ name,
652
+ id: (0, sdk_1.Random)(16),
653
+ primaryPad: (0, sdk_1.Random)(32),
654
+ privilegedPad: (0, sdk_1.Random)(32),
655
+ createdAt: Math.floor(Date.now() / 1000)
656
+ };
657
+ this.profiles.push(newProfile);
658
+ // Update the UMP token with the new profile list
659
+ await this.updateAuthFactors(this.currentUMPToken.passwordSalt,
660
+ // Need to re-derive/decrypt factors needed for re-encryption
661
+ await this.getFactor('passwordKey'), await this.getFactor('presentationKey'), await this.getFactor('recoveryKey'), this.rootPrimaryKey, await this.getFactor('privilegedKey'), // Get ROOT privileged key
662
+ this.profiles // Pass the updated profile list
663
+ );
664
+ return newProfile.id;
665
+ }
666
+ /**
667
+ * Deletes a profile by its ID.
668
+ * Cannot delete the default profile. If the active profile is deleted,
669
+ * it switches back to the default profile.
670
+ *
671
+ * @param profileId The 16-byte ID of the profile to delete.
672
+ */
673
+ async deleteProfile(profileId) {
674
+ if (!this.authenticated || !this.rootPrimaryKey || !this.currentUMPToken || !this.rootPrivilegedKeyManager) {
675
+ throw new Error('Wallet not fully initialized or authenticated.');
676
+ }
677
+ if (profileId.every(x => x === 0)) {
678
+ throw new Error('Cannot delete the default profile.');
679
+ }
680
+ const profileIndex = this.profiles.findIndex(p => p.id.every((x, i) => x === profileId[i]));
681
+ if (profileIndex === -1) {
682
+ throw new Error('Profile not found.');
683
+ }
684
+ // Remove the profile
685
+ this.profiles.splice(profileIndex, 1);
686
+ // If the deleted profile was active, switch to default
687
+ if (this.activeProfileId.every((x, i) => x === profileId[i])) {
688
+ await this.switchProfile(exports.DEFAULT_PROFILE_ID); // This rebuilds the wallet
689
+ }
690
+ // Update the UMP token
691
+ await this.updateAuthFactors(this.currentUMPToken.passwordSalt, await this.getFactor('passwordKey'), await this.getFactor('presentationKey'), await this.getFactor('recoveryKey'), this.rootPrimaryKey, await this.getFactor('privilegedKey'), // Get ROOT privileged key
692
+ this.profiles // Pass updated list
693
+ );
694
+ }
695
+ /**
696
+ * Switches the active profile. This re-derives keys and rebuilds the underlying wallet.
697
+ *
698
+ * @param profileId The 16-byte ID of the profile to switch to (use DEFAULT_PROFILE_ID for default).
699
+ */
700
+ async switchProfile(profileId) {
701
+ if (!this.authenticated || !this.rootPrimaryKey || !this.rootPrivilegedKeyManager) {
702
+ throw new Error('Cannot switch profile: Wallet not authenticated or root keys missing.');
703
+ }
704
+ let profilePrimaryKey;
705
+ let profilePrivilegedPad; // Pad for the target profile
706
+ if (profileId.every(x => x === 0)) {
707
+ // Switching to default profile
708
+ profilePrimaryKey = this.rootPrimaryKey;
709
+ profilePrivilegedPad = undefined; // No pad for default
710
+ this.activeProfileId = exports.DEFAULT_PROFILE_ID;
711
+ }
712
+ else {
713
+ // Switching to a non-default profile
714
+ const profile = this.profiles.find(p => p.id.every((x, i) => x === profileId[i]));
715
+ if (!profile) {
716
+ throw new Error('Profile not found.');
717
+ }
718
+ profilePrimaryKey = this.XOR(this.rootPrimaryKey, profile.primaryPad);
719
+ profilePrivilegedPad = profile.privilegedPad;
720
+ this.activeProfileId = profileId;
721
+ }
722
+ // Create a *profile-specific* PrivilegedKeyManager.
723
+ // It uses the ROOT manager internally but applies the profile's pad.
724
+ const profilePrivilegedKeyManager = new PrivilegedKeyManager_1.PrivilegedKeyManager(async (reason) => {
725
+ // Request the ROOT privileged key using the root manager
726
+ const rootPrivileged = await this.rootPrivilegedKeyManager.getPrivilegedKey(reason);
727
+ const rootPrivilegedBytes = rootPrivileged.toArray();
728
+ // Apply the profile's pad if applicable
729
+ const profilePrivilegedBytes = profilePrivilegedPad
730
+ ? this.XOR(rootPrivilegedBytes, profilePrivilegedPad)
731
+ : rootPrivilegedBytes;
732
+ return new sdk_1.PrivateKey(profilePrivilegedBytes);
733
+ });
734
+ // Build the underlying wallet for the specific profile
735
+ this.underlying = await this.walletBuilder(profilePrimaryKey, profilePrivilegedKeyManager, // Pass the profile-specific manager
736
+ this.activeProfileId // Pass the ID of the profile being activated
737
+ );
738
+ }
739
+ // --- Key Management Methods ---
740
+ /**
741
+ * Changes the user's password. Re-wraps keys and updates the UMP token.
742
+ */
743
+ async changePassword(newPassword) {
744
+ if (!this.authenticated || !this.currentUMPToken || !this.rootPrimaryKey || !this.rootPrivilegedKeyManager) {
745
+ throw new Error('Not authenticated or missing required data.');
746
+ }
747
+ const passwordSalt = (0, sdk_1.Random)(32);
748
+ const newPasswordKey = sdk_1.Hash.pbkdf2(sdk_1.Utils.toArray(newPassword, 'utf8'), passwordSalt, exports.PBKDF2_NUM_ROUNDS, 32, 'sha512');
749
+ // Decrypt existing factors needed for re-encryption, using the *root* privileged key manager
750
+ const recoveryKey = await this.getFactor('recoveryKey');
751
+ const presentationKey = await this.getFactor('presentationKey');
752
+ const rootPrivilegedKey = await this.getFactor('privilegedKey'); // Get ROOT privileged key
753
+ await this.updateAuthFactors(passwordSalt, newPasswordKey, presentationKey, recoveryKey, this.rootPrimaryKey, rootPrivilegedKey, // Pass the explicitly fetched root key
754
+ this.profiles // Preserve existing profiles
755
+ );
756
+ }
757
+ /**
758
+ * Retrieves the current recovery key. Requires privileged access.
759
+ */
760
+ async getRecoveryKey() {
761
+ if (!this.authenticated || !this.currentUMPToken || !this.rootPrivilegedKeyManager) {
762
+ throw new Error('Not authenticated or missing required data.');
763
+ }
764
+ return this.getFactor('recoveryKey');
765
+ }
766
+ /**
767
+ * Changes the user's recovery key. Prompts user to save the new key.
768
+ */
769
+ async changeRecoveryKey() {
770
+ if (!this.authenticated || !this.currentUMPToken || !this.rootPrimaryKey || !this.rootPrivilegedKeyManager) {
771
+ throw new Error('Not authenticated or missing required data.');
772
+ }
773
+ // Decrypt existing factors needed
774
+ const passwordKey = await this.getFactor('passwordKey');
775
+ const presentationKey = await this.getFactor('presentationKey');
776
+ const rootPrivilegedKey = await this.getFactor('privilegedKey'); // Get ROOT privileged key
777
+ // Generate and save new recovery key
778
+ const newRecoveryKey = (0, sdk_1.Random)(32);
779
+ await this.recoveryKeySaver(newRecoveryKey);
780
+ await this.updateAuthFactors(this.currentUMPToken.passwordSalt, passwordKey, presentationKey, newRecoveryKey, // Use the new key
781
+ this.rootPrimaryKey, rootPrivilegedKey, this.profiles // Preserve profiles
782
+ );
783
+ }
784
+ /**
785
+ * Changes the user's presentation key.
786
+ */
787
+ async changePresentationKey(newPresentationKey) {
788
+ if (!this.authenticated || !this.currentUMPToken || !this.rootPrimaryKey || !this.rootPrivilegedKeyManager) {
789
+ throw new Error('Not authenticated or missing required data.');
790
+ }
791
+ if (newPresentationKey.length !== 32) {
792
+ throw new Error('Presentation key must be 32 bytes.');
793
+ }
794
+ // Decrypt existing factors
795
+ const recoveryKey = await this.getFactor('recoveryKey');
796
+ const passwordKey = await this.getFactor('passwordKey');
797
+ const rootPrivilegedKey = await this.getFactor('privilegedKey'); // Get ROOT privileged key
798
+ await this.updateAuthFactors(this.currentUMPToken.passwordSalt, passwordKey, newPresentationKey, // Use the new key
799
+ recoveryKey, this.rootPrimaryKey, rootPrivilegedKey, this.profiles // Preserve profiles
800
+ );
801
+ // Update the temporarily stored key if it was set
802
+ if (this.presentationKey) {
803
+ this.presentationKey = newPresentationKey;
804
+ }
805
+ }
806
+ // --- Internal Helper Methods ---
807
+ /**
808
+ * Performs XOR operation on two byte arrays.
809
+ */
810
+ XOR(n1, n2) {
811
+ if (n1.length !== n2.length) {
812
+ // Provide more context in error
813
+ throw new Error(`XOR length mismatch: ${n1.length} vs ${n2.length}`);
814
+ }
815
+ const r = new Array(n1.length);
816
+ for (let i = 0; i < n1.length; i++) {
817
+ r[i] = n1[i] ^ n2[i];
818
+ }
819
+ return r;
820
+ }
821
+ /**
822
+ * Helper to decrypt a specific factor (key) stored encrypted in the UMP token.
823
+ * Requires the root privileged key manager.
824
+ * @param factorName Name of the factor to decrypt ('passwordKey', 'presentationKey', 'recoveryKey', 'privilegedKey').
825
+ * @param getRoot If true and factorName is 'privilegedKey', returns the root privileged key bytes directly.
826
+ * @returns The decrypted key bytes.
827
+ */
828
+ async getFactor(factorName) {
829
+ if (!this.authenticated || !this.currentUMPToken || !this.rootPrivilegedKeyManager) {
830
+ throw new Error(`Cannot get factor "${factorName}": Wallet not ready.`);
831
+ }
832
+ const protocolID = [2, 'admin key wrapping']; // Protocol used for encrypting factors
833
+ const keyID = '1'; // Key ID used
834
+ try {
835
+ switch (factorName) {
836
+ case 'passwordKey':
837
+ return (await this.rootPrivilegedKeyManager.decrypt({
838
+ ciphertext: this.currentUMPToken.passwordKeyEncrypted,
839
+ protocolID,
840
+ keyID
841
+ })).plaintext;
842
+ case 'presentationKey':
843
+ return (await this.rootPrivilegedKeyManager.decrypt({
844
+ ciphertext: this.currentUMPToken.presentationKeyEncrypted,
845
+ protocolID,
846
+ keyID
847
+ })).plaintext;
848
+ case 'recoveryKey':
849
+ return (await this.rootPrivilegedKeyManager.decrypt({
850
+ ciphertext: this.currentUMPToken.recoveryKeyEncrypted,
851
+ protocolID,
852
+ keyID
853
+ })).plaintext;
854
+ case 'privilegedKey': {
855
+ // This needs careful handling based on whether the ROOT or PROFILE key is needed.
856
+ // This helper is mostly used for UMP updates, which need the ROOT key.
857
+ // We retrieve the PrivateKey object first.
858
+ const pk = await this.rootPrivilegedKeyManager.getPrivilegedKey('UMP token update', true); // Force retrieval of root key
859
+ return pk.toArray(); // Return bytes
860
+ }
861
+ default:
862
+ throw new Error(`Unknown factor name: ${factorName}`);
863
+ }
864
+ }
865
+ catch (error) {
866
+ console.error(`Error decrypting factor ${factorName}:`, error);
867
+ throw new Error(`Failed to decrypt factor "${factorName}": ${error.message}`);
868
+ }
869
+ }
870
+ /**
871
+ * Recomputes UMP token fields with updated factors and profiles, then publishes the update.
872
+ * This operation requires the *root* privileged key and the *default* profile wallet.
873
+ */
874
+ async updateAuthFactors(passwordSalt, passwordKey, presentationKey, recoveryKey, rootPrimaryKey, rootPrivilegedKey, // Explicitly pass the root key bytes
875
+ profiles // Pass current/new profiles list
876
+ ) {
877
+ if (!this.authenticated || !this.rootPrimaryKey || !this.currentUMPToken) {
878
+ throw new Error('Wallet is not properly authenticated or missing data for update.');
879
+ }
880
+ // Ensure we have the OLD token to consume
881
+ const oldTokenToConsume = { ...this.currentUMPToken };
882
+ if (!oldTokenToConsume.currentOutpoint) {
883
+ throw new Error('Cannot update UMP token: Old token has no outpoint.');
884
+ }
885
+ // Derive symmetrical encryption keys using XOR for the *root* keys
886
+ const presentationPassword = new sdk_1.SymmetricKey(this.XOR(presentationKey, passwordKey));
887
+ const presentationRecovery = new sdk_1.SymmetricKey(this.XOR(presentationKey, recoveryKey));
888
+ const recoveryPassword = new sdk_1.SymmetricKey(this.XOR(recoveryKey, passwordKey));
889
+ const primaryPassword = new sdk_1.SymmetricKey(this.XOR(rootPrimaryKey, passwordKey)); // Use rootPrimaryKey
890
+ // Build a temporary privileged key manager using the explicit ROOT privileged key
891
+ const tempRootPrivilegedKeyManager = new PrivilegedKeyManager_1.PrivilegedKeyManager(async () => new sdk_1.PrivateKey(rootPrivilegedKey));
892
+ // Encrypt profiles if provided
893
+ let profilesEncrypted;
894
+ if (profiles && profiles.length > 0) {
895
+ const profilesJson = JSON.stringify(profiles);
896
+ const profilesBytes = sdk_1.Utils.toArray(profilesJson, 'utf8');
897
+ profilesEncrypted = new sdk_1.SymmetricKey(rootPrimaryKey).encrypt(profilesBytes);
898
+ }
899
+ // Construct the new UMP token data
900
+ const newTokenData = {
901
+ passwordSalt,
902
+ passwordPresentationPrimary: presentationPassword.encrypt(rootPrimaryKey),
903
+ passwordRecoveryPrimary: recoveryPassword.encrypt(rootPrimaryKey),
904
+ presentationRecoveryPrimary: presentationRecovery.encrypt(rootPrimaryKey),
905
+ passwordPrimaryPrivileged: primaryPassword.encrypt(rootPrivilegedKey),
906
+ presentationRecoveryPrivileged: presentationRecovery.encrypt(rootPrivilegedKey),
907
+ presentationHash: sdk_1.Hash.sha256(presentationKey),
908
+ recoveryHash: sdk_1.Hash.sha256(recoveryKey),
909
+ presentationKeyEncrypted: (await tempRootPrivilegedKeyManager.encrypt({
910
+ plaintext: presentationKey,
911
+ protocolID: [2, 'admin key wrapping'],
912
+ keyID: '1'
913
+ })).ciphertext,
914
+ passwordKeyEncrypted: (await tempRootPrivilegedKeyManager.encrypt({
915
+ plaintext: passwordKey,
916
+ protocolID: [2, 'admin key wrapping'],
917
+ keyID: '1'
918
+ })).ciphertext,
919
+ recoveryKeyEncrypted: (await tempRootPrivilegedKeyManager.encrypt({
920
+ plaintext: recoveryKey,
921
+ protocolID: [2, 'admin key wrapping'],
922
+ keyID: '1'
923
+ })).ciphertext,
924
+ profilesEncrypted // Add encrypted profiles
925
+ // currentOutpoint will be set after publishing
926
+ };
927
+ // We need the wallet built for the DEFAULT profile to publish the UMP token.
928
+ // If the current active profile is not default, temporarily switch, publish, then switch back.
929
+ const currentActiveId = this.activeProfileId;
930
+ let walletToUse = this.underlying;
931
+ if (!currentActiveId.every(x => x === 0)) {
932
+ console.log('Temporarily switching to default profile to update UMP token...');
933
+ await this.switchProfile(exports.DEFAULT_PROFILE_ID); // This rebuilds this.underlying
934
+ walletToUse = this.underlying;
935
+ }
936
+ if (!walletToUse) {
937
+ throw new Error('Default profile wallet could not be activated for UMP token update.');
938
+ }
939
+ // Publish the new token on-chain, consuming the old one
940
+ try {
941
+ newTokenData.currentOutpoint = await this.UMPTokenInteractor.buildAndSend(walletToUse, this.adminOriginator, newTokenData, oldTokenToConsume // Consume the previous token
942
+ );
943
+ // Update the manager's state
944
+ this.currentUMPToken = newTokenData;
945
+ // Profiles are already updated in this.profiles if they were passed in
946
+ }
947
+ finally {
948
+ // Switch back if we temporarily switched
949
+ if (!currentActiveId.every(x => x === 0)) {
950
+ console.log('Switching back to original profile...');
951
+ await this.switchProfile(currentActiveId);
952
+ }
953
+ }
954
+ }
955
+ /**
956
+ * Serializes a UMP token to binary format (Version 2 with optional profiles).
957
+ * Layout: [1 byte version=2] + [11 * (varint len + bytes) for standard fields] + [1 byte profile_flag] + [IF flag=1 THEN varint len + profile bytes] + [varint len + outpoint bytes]
958
+ */
959
+ serializeUMPToken(token) {
960
+ if (!token.currentOutpoint) {
961
+ throw new Error('Token must have outpoint for serialization');
962
+ }
963
+ const writer = new sdk_1.Utils.Writer();
964
+ writer.writeUInt8(2); // Version 2
965
+ const writeArray = (arr) => {
966
+ writer.writeVarIntNum(arr.length);
967
+ writer.write(arr);
968
+ };
969
+ // Write standard fields in specific order
970
+ writeArray(token.passwordSalt); // 0
971
+ writeArray(token.passwordPresentationPrimary); // 1
972
+ writeArray(token.passwordRecoveryPrimary); // 2
973
+ writeArray(token.presentationRecoveryPrimary); // 3
974
+ writeArray(token.passwordPrimaryPrivileged); // 4
975
+ writeArray(token.presentationRecoveryPrivileged); // 5
976
+ writeArray(token.presentationHash); // 6
977
+ writeArray(token.recoveryHash); // 7
978
+ writeArray(token.presentationKeyEncrypted); // 8
979
+ writeArray(token.passwordKeyEncrypted); // 9 - Swapped order vs original doc comment
980
+ writeArray(token.recoveryKeyEncrypted); // 10
981
+ // Write optional profiles field
982
+ if (token.profilesEncrypted && token.profilesEncrypted.length > 0) {
983
+ writer.writeUInt8(1); // Flag indicating profiles present
984
+ writeArray(token.profilesEncrypted);
985
+ }
986
+ else {
987
+ writer.writeUInt8(0); // Flag indicating no profiles
988
+ }
989
+ // Write outpoint string
990
+ const outpointBytes = sdk_1.Utils.toArray(token.currentOutpoint, 'utf8');
991
+ writer.writeVarIntNum(outpointBytes.length);
992
+ writer.write(outpointBytes);
993
+ return writer.toArray();
994
+ }
995
+ /**
996
+ * Deserializes a UMP token from binary format (Handles Version 1 and 2).
997
+ */
998
+ deserializeUMPToken(bin) {
999
+ const reader = new sdk_1.Utils.Reader(bin);
1000
+ const version = reader.readUInt8();
1001
+ if (version !== 1 && version !== 2) {
1002
+ throw new Error(`Unsupported UMP token serialization version: ${version}`);
1003
+ }
1004
+ const readArray = () => {
1005
+ const length = reader.readVarIntNum();
1006
+ return reader.read(length);
1007
+ };
1008
+ // Read standard fields (order matches serialization V2)
1009
+ const passwordSalt = readArray(); // 0
1010
+ const passwordPresentationPrimary = readArray(); // 1
1011
+ const passwordRecoveryPrimary = readArray(); // 2
1012
+ const presentationRecoveryPrimary = readArray(); // 3
1013
+ const passwordPrimaryPrivileged = readArray(); // 4
1014
+ const presentationRecoveryPrivileged = readArray(); // 5
1015
+ const presentationHash = readArray(); // 6
1016
+ const recoveryHash = readArray(); // 7
1017
+ const presentationKeyEncrypted = readArray(); // 8
1018
+ const passwordKeyEncrypted = readArray(); // 9
1019
+ const recoveryKeyEncrypted = readArray(); // 10
1020
+ // Read optional profiles (only in V2)
1021
+ let profilesEncrypted;
1022
+ if (version === 2) {
1023
+ const profilesFlag = reader.readUInt8();
1024
+ if (profilesFlag === 1) {
1025
+ profilesEncrypted = readArray();
1026
+ }
1027
+ }
1028
+ // Read outpoint string
1029
+ const outpointLen = reader.readVarIntNum();
1030
+ const outpointBytes = reader.read(outpointLen);
1031
+ const currentOutpoint = sdk_1.Utils.toUTF8(outpointBytes);
1032
+ const token = {
1033
+ passwordSalt,
1034
+ passwordPresentationPrimary,
1035
+ passwordRecoveryPrimary,
1036
+ presentationRecoveryPrimary,
1037
+ passwordPrimaryPrivileged,
1038
+ presentationRecoveryPrivileged,
1039
+ presentationHash,
1040
+ recoveryHash,
1041
+ presentationKeyEncrypted,
1042
+ passwordKeyEncrypted, // Corrected order
1043
+ recoveryKeyEncrypted,
1044
+ profilesEncrypted, // May be undefined
1045
+ currentOutpoint
1046
+ };
1047
+ return token;
1048
+ }
1049
+ /**
1050
+ * Sets up the root key infrastructure after authentication or loading from snapshot.
1051
+ * Initializes the root primary key, root privileged key manager, loads profiles,
1052
+ * and sets the authenticated flag. Does NOT switch profile initially.
1053
+ *
1054
+ * @param rootPrimaryKey The user's root primary key (32 bytes).
1055
+ * @param ephemeralRootPrivilegedKey Optional root privileged key (e.g., during recovery flows).
1056
+ */
1057
+ async setupRootInfrastructure(rootPrimaryKey, ephemeralRootPrivilegedKey) {
1058
+ if (!this.currentUMPToken) {
1059
+ throw new Error('A UMP token must exist before setting up root infrastructure!');
1060
+ }
1061
+ this.rootPrimaryKey = rootPrimaryKey;
1062
+ // Store ephemeral key if provided, for one-time use by the manager
1063
+ let oneTimePrivilegedKey = ephemeralRootPrivilegedKey
1064
+ ? new sdk_1.PrivateKey(ephemeralRootPrivilegedKey)
1065
+ : undefined;
1066
+ // Create the ROOT PrivilegedKeyManager
1067
+ this.rootPrivilegedKeyManager = new PrivilegedKeyManager_1.PrivilegedKeyManager(async (reason) => {
1068
+ // 1. Use one-time key if available (for recovery)
1069
+ if (oneTimePrivilegedKey) {
1070
+ const tempKey = oneTimePrivilegedKey;
1071
+ oneTimePrivilegedKey = undefined; // Consume it
1072
+ return tempKey;
1073
+ }
1074
+ // 2. Otherwise, derive from password
1075
+ const password = await this.passwordRetriever(reason, (passwordCandidate) => {
1076
+ try {
1077
+ const derivedPasswordKey = sdk_1.Hash.pbkdf2(sdk_1.Utils.toArray(passwordCandidate, 'utf8'), this.currentUMPToken.passwordSalt, exports.PBKDF2_NUM_ROUNDS, 32, 'sha512');
1078
+ const privilegedDecryptor = this.XOR(this.rootPrimaryKey, derivedPasswordKey);
1079
+ const decryptedPrivileged = new sdk_1.SymmetricKey(privilegedDecryptor).decrypt(this.currentUMPToken.passwordPrimaryPrivileged);
1080
+ return !!decryptedPrivileged; // Test passes if decryption works
1081
+ }
1082
+ catch (e) {
1083
+ return false;
1084
+ }
1085
+ });
1086
+ // Decrypt the root privileged key using the confirmed password
1087
+ const derivedPasswordKey = sdk_1.Hash.pbkdf2(sdk_1.Utils.toArray(password, 'utf8'), this.currentUMPToken.passwordSalt, exports.PBKDF2_NUM_ROUNDS, 32, 'sha512');
1088
+ const privilegedDecryptor = this.XOR(this.rootPrimaryKey, derivedPasswordKey);
1089
+ const rootPrivilegedBytes = new sdk_1.SymmetricKey(privilegedDecryptor).decrypt(this.currentUMPToken.passwordPrimaryPrivileged);
1090
+ return new sdk_1.PrivateKey(rootPrivilegedBytes); // Return the ROOT key object
1091
+ });
1092
+ // Decrypt and load profiles if present in the token
1093
+ this.profiles = []; // Clear existing profiles before loading
1094
+ if (this.currentUMPToken.profilesEncrypted && this.currentUMPToken.profilesEncrypted.length > 0) {
1095
+ try {
1096
+ const decryptedProfileBytes = new sdk_1.SymmetricKey(rootPrimaryKey).decrypt(this.currentUMPToken.profilesEncrypted);
1097
+ const profilesJson = sdk_1.Utils.toUTF8(decryptedProfileBytes);
1098
+ this.profiles = JSON.parse(profilesJson);
1099
+ }
1100
+ catch (error) {
1101
+ console.error('Failed to decrypt or parse profiles:', error);
1102
+ // Decide if this should be fatal or just log and continue without profiles
1103
+ this.profiles = []; // Ensure profiles are empty on error
1104
+ // Optionally re-throw or handle more gracefully
1105
+ throw new Error(`Failed to load profiles: ${error.message}`);
1106
+ }
1107
+ }
1108
+ this.authenticated = true;
1109
+ // Note: We don't call switchProfile here anymore.
1110
+ // It's called by the auth methods (providePassword/provideRecoveryKey) or loadSnapshot after this.
1111
+ }
1112
+ /*
1113
+ * ---------------------------------------------------------------------------------------
1114
+ * Standard WalletInterface methods proxying to the *active* underlying wallet.
1115
+ * Includes authentication checks and admin originator protection.
1116
+ * ---------------------------------------------------------------------------------------
1117
+ */
1118
+ checkAuthAndUnderlying(originator) {
1119
+ if (!this.authenticated) {
1120
+ throw new Error('User is not authenticated.');
1121
+ }
1122
+ if (!this.underlying) {
1123
+ // This might happen if authentication succeeded but profile switching failed
1124
+ throw new Error('Underlying wallet for the active profile is not initialized.');
1125
+ }
1126
+ if (originator === this.adminOriginator) {
1127
+ throw new Error('External applications are not allowed to use the admin originator.');
1128
+ }
1129
+ }
1130
+ // Example proxy method (repeat pattern for all others)
1131
+ async getPublicKey(args, originator) {
1132
+ this.checkAuthAndUnderlying(originator);
1133
+ return this.underlying.getPublicKey(args, originator);
1134
+ }
1135
+ async revealCounterpartyKeyLinkage(args, originator) {
1136
+ this.checkAuthAndUnderlying(originator);
1137
+ return this.underlying.revealCounterpartyKeyLinkage(args, originator);
1138
+ }
1139
+ async revealSpecificKeyLinkage(args, originator) {
1140
+ this.checkAuthAndUnderlying(originator);
1141
+ return this.underlying.revealSpecificKeyLinkage(args, originator);
1142
+ }
1143
+ async encrypt(args, originator) {
1144
+ this.checkAuthAndUnderlying(originator);
1145
+ return this.underlying.encrypt(args, originator);
1146
+ }
1147
+ async decrypt(args, originator) {
1148
+ this.checkAuthAndUnderlying(originator);
1149
+ return this.underlying.decrypt(args, originator);
1150
+ }
1151
+ async createHmac(args, originator) {
1152
+ this.checkAuthAndUnderlying(originator);
1153
+ return this.underlying.createHmac(args, originator);
1154
+ }
1155
+ async verifyHmac(args, originator) {
1156
+ this.checkAuthAndUnderlying(originator);
1157
+ return this.underlying.verifyHmac(args, originator);
1158
+ }
1159
+ async createSignature(args, originator) {
1160
+ this.checkAuthAndUnderlying(originator);
1161
+ return this.underlying.createSignature(args, originator);
1162
+ }
1163
+ async verifySignature(args, originator) {
1164
+ this.checkAuthAndUnderlying(originator);
1165
+ return this.underlying.verifySignature(args, originator);
1166
+ }
1167
+ async createAction(args, originator) {
1168
+ this.checkAuthAndUnderlying(originator);
1169
+ return this.underlying.createAction(args, originator);
1170
+ }
1171
+ async signAction(args, originator) {
1172
+ this.checkAuthAndUnderlying(originator);
1173
+ return this.underlying.signAction(args, originator);
1174
+ }
1175
+ async abortAction(args, originator) {
1176
+ this.checkAuthAndUnderlying(originator);
1177
+ return this.underlying.abortAction(args, originator);
1178
+ }
1179
+ async listActions(args, originator) {
1180
+ this.checkAuthAndUnderlying(originator);
1181
+ return this.underlying.listActions(args, originator);
1182
+ }
1183
+ async internalizeAction(args, originator) {
1184
+ this.checkAuthAndUnderlying(originator);
1185
+ return this.underlying.internalizeAction(args, originator);
1186
+ }
1187
+ async listOutputs(args, originator) {
1188
+ this.checkAuthAndUnderlying(originator);
1189
+ return this.underlying.listOutputs(args, originator);
1190
+ }
1191
+ async relinquishOutput(args, originator) {
1192
+ this.checkAuthAndUnderlying(originator);
1193
+ return this.underlying.relinquishOutput(args, originator);
1194
+ }
1195
+ async acquireCertificate(args, originator) {
1196
+ this.checkAuthAndUnderlying(originator);
1197
+ return this.underlying.acquireCertificate(args, originator);
1198
+ }
1199
+ async listCertificates(args, originator) {
1200
+ this.checkAuthAndUnderlying(originator);
1201
+ return this.underlying.listCertificates(args, originator);
1202
+ }
1203
+ async proveCertificate(args, originator) {
1204
+ this.checkAuthAndUnderlying(originator);
1205
+ return this.underlying.proveCertificate(args, originator);
1206
+ }
1207
+ async relinquishCertificate(args, originator) {
1208
+ this.checkAuthAndUnderlying(originator);
1209
+ return this.underlying.relinquishCertificate(args, originator);
1210
+ }
1211
+ async discoverByIdentityKey(args, originator) {
1212
+ this.checkAuthAndUnderlying(originator);
1213
+ return this.underlying.discoverByIdentityKey(args, originator);
1214
+ }
1215
+ async discoverByAttributes(args, originator) {
1216
+ this.checkAuthAndUnderlying(originator);
1217
+ return this.underlying.discoverByAttributes(args, originator);
1218
+ }
1219
+ async isAuthenticated(_, originator) {
1220
+ if (!this.authenticated) {
1221
+ throw new Error('User is not authenticated.');
1222
+ }
1223
+ if (originator === this.adminOriginator) {
1224
+ throw new Error('External applications are not allowed to use the admin originator.');
1225
+ }
1226
+ return { authenticated: true };
1227
+ }
1228
+ async waitForAuthentication(_, originator) {
1229
+ if (originator === this.adminOriginator) {
1230
+ throw new Error('External applications are not allowed to use the admin originator.');
1231
+ }
1232
+ while (!this.authenticated || !this.underlying) {
1233
+ await new Promise(resolve => setTimeout(resolve, 100));
1234
+ }
1235
+ return { authenticated: true };
1236
+ }
1237
+ async getHeight(_, originator) {
1238
+ this.checkAuthAndUnderlying(originator);
1239
+ return this.underlying.getHeight({}, originator);
1240
+ }
1241
+ async getHeaderForHeight(args, originator) {
1242
+ this.checkAuthAndUnderlying(originator);
1243
+ return this.underlying.getHeaderForHeight(args, originator);
1244
+ }
1245
+ async getNetwork(_, originator) {
1246
+ this.checkAuthAndUnderlying(originator);
1247
+ return this.underlying.getNetwork({}, originator);
1248
+ }
1249
+ async getVersion(_, originator) {
1250
+ this.checkAuthAndUnderlying(originator);
1251
+ return this.underlying.getVersion({}, originator);
1252
+ }
1253
+ }
1254
+ exports.CWIStyleWalletManager = CWIStyleWalletManager;
1255
+ //# sourceMappingURL=CWIStyleWalletManager.js.map