@seams/wallet 0.9.2 → 0.9.4

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 (322) hide show
  1. package/README.md +3 -3
  2. package/THIRD_PARTY_NOTICES.md +33 -1
  3. package/dist/.build-inputs.sha256 +1 -1
  4. package/dist/esm/core/signingEngine/flows/signNear/shared/signatureOnlySigning.js +4 -9
  5. package/dist/esm/core/signingEngine/flows/signNear/signDelegate.js +10 -2
  6. package/dist/esm/core/signingEngine/flows/signNear/signNep413.js +6 -1
  7. package/dist/esm/react/components/VoiceAssistantCard.css +313 -0
  8. package/dist/esm/react/components/VoiceAssistantCard.js +150 -0
  9. package/dist/esm/react/index.js +3 -1
  10. package/dist/esm/react/styles/styles.css +314 -0
  11. package/dist/esm/react/styles.css +1 -0
  12. package/dist/esm/sdk/{ConfirmationDrawer-DY0_yeUV.js → ConfirmationDrawer-Frj3uEee.js} +1 -1
  13. package/dist/{public/sdk/NonceCoordinator-CFFq8-Q9.js → esm/sdk/NonceCoordinator-S5ZbrkDp.js} +1 -1
  14. package/dist/{public/sdk/accountLifecycle-CAMVowDl.js → esm/sdk/accountLifecycle-HEUmDLus.js} +1 -1
  15. package/dist/esm/sdk/activeWalletSession-WdZkhtBB.js +1 -0
  16. package/dist/esm/sdk/{adapters-DdDOQzl4.js → adapters-DYPu0nK9.js} +2 -2
  17. package/dist/esm/sdk/{canonicalPrimitives-CKPGgpxg.js → canonicalPrimitives-Dsbsxgxc.js} +1 -1
  18. package/dist/esm/sdk/{capabilityKinds-CKQ4Uqnv.js → capabilityKinds-N8xo_IEh.js} +1 -1
  19. package/dist/esm/sdk/{chains-CiYQT1K4.js → chains-C_X_fNuS.js} +1 -1
  20. package/dist/esm/sdk/challengeDelivery-5lIu9spR.js +1 -0
  21. package/dist/{public/sdk/clientSessionPersistenceState-CImFWDj6.js → esm/sdk/clientSessionPersistenceState-DRdve9rC.js} +1 -1
  22. package/dist/esm/sdk/{commitQueue-iBNUt9Bz.js → commitQueue-qjvY_zWn.js} +1 -1
  23. package/dist/esm/sdk/{configHelpers-D8Ivi6p8.js → configHelpers-B-hs0mTO.js} +1 -1
  24. package/dist/esm/sdk/digestEncoding-CkUc5vtR.js +1 -0
  25. package/dist/esm/sdk/{display-ClqZq-Xt.js → display-DjoWrSgE.js} +1 -1
  26. package/dist/esm/sdk/domainIds-BzkGsRqO.js +1 -0
  27. package/dist/{public/sdk/ecdsaCapabilityManifest-BlzJAQF8.js → esm/sdk/ecdsaCapabilityManifest-ChszYCC0.js} +1 -1
  28. package/dist/esm/sdk/{ecdsaChainTarget-C8ZtMZ8l.js → ecdsaChainTarget-DJBXHzbH.js} +1 -1
  29. package/dist/{public/sdk/ecdsaDerivationClientWasm-CVeNEou2.js → esm/sdk/ecdsaDerivationClientWasm-CpH-b3jx.js} +1 -1
  30. package/dist/{public/sdk/ecdsaDerivationExport-BZFHSMCv.js → esm/sdk/ecdsaDerivationExport-C1cE5m0t.js} +1 -1
  31. package/dist/esm/sdk/{ecdsaWalletRecords-D4WeYc7H.js → ecdsaWalletRecords-Di_NUxD_.js} +1 -1
  32. package/dist/esm/sdk/emailOtpEcdsaDerivationIdentity-p0C1CQva.js +1 -0
  33. package/dist/esm/sdk/{enrichDisplayModelWithAbi-69bNckvi.js → enrichDisplayModelWithAbi-DZIhvE-x.js} +1 -1
  34. package/dist/esm/sdk/{evmCryptoWasm-BXsIyRon.js → evmCryptoWasm-DeobzyP-.js} +1 -1
  35. package/dist/{public/sdk/export-viewer-host-CsFeiIhd.js → esm/sdk/export-viewer-host-DUMwD6zP.js} +1 -1
  36. package/dist/{public/sdk/exportKeypairOperation-DGQIYML3.js → esm/sdk/exportKeypairOperation-DYCzCbqL.js} +1 -1
  37. package/dist/esm/sdk/{helpers-Ddy72ULN.js → helpers-BnkILY2_.js} +1 -1
  38. package/dist/esm/sdk/host-h55onlkx.js +1 -0
  39. package/dist/esm/sdk/{intentDigest-CE-tLw87.js → intentDigest-DJBrMyLJ.js} +1 -1
  40. package/dist/esm/sdk/{lanes-DnBwWv4l.js → lanes-Ck81oEGv.js} +1 -1
  41. package/dist/esm/sdk/{localOnly-ClCo6602.js → localOnly-KvZeKkH5.js} +1 -1
  42. package/dist/{public/sdk/messages-vxz27Way.js → esm/sdk/messages-DgJlG9NU.js} +1 -1
  43. package/dist/esm/sdk/{mountExportPrivateKeySurface-CBZ0wRYj.js → mountExportPrivateKeySurface-B4gH1Sel.js} +1 -1
  44. package/dist/{public/sdk/mountRecoveryCodeBackupSurface-B1qhFF6G.js → esm/sdk/mountRecoveryCodeBackupSurface-BA2ttbTM.js} +1 -1
  45. package/dist/esm/sdk/nearEd25519YaoMaterialActivation-CvDs4RtV.js +1 -0
  46. package/dist/esm/sdk/{nearEd25519YaoSigningPreparation-B0d1AG3u.js → nearEd25519YaoSigningPreparation-Eiq_ikXk.js} +1 -1
  47. package/dist/esm/sdk/{nonceLaneKeys-Fkvk2UPy.js → nonceLaneKeys-Do5Vs-De.js} +1 -1
  48. package/dist/esm/sdk/{normalization-DCvuCvh0.js → normalization-DJPmcXTg.js} +1 -1
  49. package/dist/esm/sdk/{operationFingerprint-CTR9G1NT.js → operationFingerprint-CUrnoh-M.js} +1 -1
  50. package/dist/esm/sdk/passkey-custody-Cd_yyoRa.js +1 -0
  51. package/dist/esm/sdk/{pendingWalletRecoveryCodeBackup-yJN8VAHn.js → pendingWalletRecoveryCodeBackup-BkIrbd6Q.js} +1 -1
  52. package/dist/esm/sdk/presignaturePool-CLHu7HaU.js +1 -0
  53. package/dist/esm/sdk/{prfCache-BMpqZZ-v.js → prfCache-DCkuB8Lu.js} +1 -1
  54. package/dist/esm/sdk/primitives-CqrjmIAH.js +1 -0
  55. package/dist/{public/sdk/recovery-entrypoint-Bl5GgbW9.js → esm/sdk/recovery-entrypoint-DoXswV9I.js} +1 -1
  56. package/dist/esm/sdk/{registration-C4sALQZO.js → registration-BFHEYmgh.js} +1 -1
  57. package/dist/esm/sdk/registration-Cfg9rWhA.js +1 -0
  58. package/dist/esm/sdk/{registrationAccounts-D4RVetMz.js → registrationAccounts-DP-32yCK.js} +1 -1
  59. package/dist/esm/sdk/{registrationAuthMethodInput-6ccY2Vuh.js → registrationAuthMethodInput-BBCeWDmw.js} +1 -1
  60. package/dist/esm/sdk/{registrationIds-CdPqm-Ya.js → registrationIds-ByuReLUc.js} +1 -1
  61. package/dist/esm/sdk/registrationIntent-BHU5k2Q-.js +1 -0
  62. package/dist/esm/sdk/{registrationSignerPlan-B9GCvpTV.js → registrationSignerPlan-dY9Rp0m_.js} +1 -1
  63. package/dist/esm/sdk/{requireStepUpAuth-DCVqmeee.js → requireStepUpAuth-C67sluoC.js} +1 -1
  64. package/dist/esm/sdk/routerAbNormalSigning-DVKFBYgV.js +1 -0
  65. package/dist/esm/sdk/{runtime-auth-BKFyLISf.js → runtime-auth-Ch4qvKL2.js} +1 -1
  66. package/dist/{public/sdk/runtime-device-link-ENxdEXQW.js → esm/sdk/runtime-device-link-DtNpEjq5.js} +1 -1
  67. package/dist/{public/sdk/runtime-ecdsa-tempo-DhGEb9U7.js → esm/sdk/runtime-ecdsa-tempo-Bntp_Zgx.js} +1 -1
  68. package/dist/esm/sdk/{runtime-email-otp-dgsP7XZi.js → runtime-email-otp-DEFt-Y-_.js} +1 -1
  69. package/dist/esm/sdk/{runtime-export-D2RCm5Gk.js → runtime-export-DE_umiS1.js} +1 -1
  70. package/dist/{public/sdk/runtime-near-Bf-9MFBQ.js → esm/sdk/runtime-near-uXqcLEz8.js} +1 -1
  71. package/dist/esm/sdk/runtime-preferences-C49p0VLC.js +1 -0
  72. package/dist/esm/sdk/runtime-recovery-D7wklehP.js +1 -0
  73. package/dist/esm/sdk/{runtime-recovery-codes-BZMiAR_5.js → runtime-recovery-codes-Dn-NccpU.js} +1 -1
  74. package/dist/esm/sdk/{sdkSentEvents-D3q1h-Uo.js → sdkSentEvents-DiQ3YVlj.js} +1 -1
  75. package/dist/esm/sdk/{secp256k1-DSLttQND.js → secp256k1-C-AETUpI.js} +1 -1
  76. package/dist/esm/sdk/{secureRandomId-BIekT8bE.js → secureRandomId-LwBFx84B.js} +1 -1
  77. package/dist/esm/sdk/{sessionPolicy-J-RrlPZQ.js → sessionPolicy-CBTZQe1n.js} +1 -1
  78. package/dist/esm/sdk/shared-D6RYxvYR.js +6 -0
  79. package/dist/{public/sdk/signEvmFamily-KUNWKVeh.js → esm/sdk/signEvmFamily-DjD3tn8e.js} +1 -1
  80. package/dist/esm/sdk/{signEvmFamilyWithUiConfirmForTempo-Dc57bJ3V.js → signEvmFamilyWithUiConfirmForTempo-CwRFbaLM.js} +1 -1
  81. package/dist/esm/sdk/{signEvmWithUiConfirm-CqxL7UbT.js → signEvmWithUiConfirm-BHG0dwVG.js} +1 -1
  82. package/dist/esm/sdk/signNear-DR50cpes.js +1 -0
  83. package/dist/esm/sdk/{signatureUses-CjJ233KX.js → signatureUses-8c8Ku_Fw.js} +1 -1
  84. package/dist/esm/sdk/{signerDomain-vQmlnsbF.js → signerDomain-DqLCvI-D.js} +1 -1
  85. package/dist/esm/sdk/{signingFlow-vrXxrhlG.js → signingFlow-Mym5j6aw.js} +1 -1
  86. package/dist/esm/sdk/signingQueue-2pr7lAUS.js +1 -0
  87. package/dist/esm/sdk/thresholdEcdsa-D-QMyevW.js +1 -0
  88. package/dist/esm/sdk/{trace-BvbCxdXF.js → trace-QLsbYdld.js} +1 -1
  89. package/dist/esm/sdk/{transaction-activity-D40ih2j-.js → transaction-activity-Cb2JyYKv.js} +1 -1
  90. package/dist/{public/sdk/transactionReviewAdmission-C-a3ctCJ.js → esm/sdk/transactionReviewAdmission-CIvR4W5_.js} +1 -1
  91. package/dist/{public/sdk/transactionState-DVinJk4K.js → esm/sdk/transactionState-CGULLokO.js} +1 -1
  92. package/dist/esm/sdk/{types-D3GM-uHR.js → types-WGrFMQSw.js} +1 -1
  93. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  94. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  95. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  96. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  97. package/dist/esm/sdk/wallet-recovery-D7ywcIHw.js +1 -0
  98. package/dist/{public/sdk/walletAuthMethodRecord-CXedSgpV.js → esm/sdk/walletAuthMethodRecord-CnBw27ED.js} +1 -1
  99. package/dist/esm/sdk/walletAuthority-BWvfaKIX.js +1 -0
  100. package/dist/esm/sdk/walletCustodyEcdsaContinuity-B8aO2NFb.js +1 -0
  101. package/dist/esm/sdk/{walletOwnershipGeneration-DoXVMDWe.js → walletOwnershipGeneration-CAycHv-H.js} +1 -1
  102. package/dist/esm/sdk/walletRecoveryCommit-C3EgMjo-.js +1 -0
  103. package/dist/esm/sdk/walletRecoveryRotate-D_1a8Agl.js +1 -0
  104. package/dist/esm/sdk/walletRegistrationSetupPrewarm-B9kpnrbK.js +1 -0
  105. package/dist/esm/sdk/walletSessionAuthorizationStatus-BLyzJbU8.js +1 -0
  106. package/dist/esm/sdk/{walletSessionAuthorizationStore-gEYPmu-G.js → walletSessionAuthorizationStore-BiKGIBWQ.js} +1 -1
  107. package/dist/esm/sdk/warmSessionHydration-B7-kCnJh.js +1 -0
  108. package/dist/esm/sdk/{webauthnP256-BEz4DEAs.js → webauthnP256-DZCusNY9.js} +1 -1
  109. package/dist/{public/sdk/webauthnPromptCoordinator-BEudHQBr.js → esm/sdk/webauthnPromptCoordinator-CS4Xc_jZ.js} +1 -1
  110. package/dist/public/headers.manifest.json +1 -1
  111. package/dist/public/sdk/{ConfirmationDrawer-DY0_yeUV.js → ConfirmationDrawer-Frj3uEee.js} +1 -1
  112. package/dist/{esm/sdk/NonceCoordinator-CFFq8-Q9.js → public/sdk/NonceCoordinator-S5ZbrkDp.js} +1 -1
  113. package/dist/{esm/sdk/accountLifecycle-CAMVowDl.js → public/sdk/accountLifecycle-HEUmDLus.js} +1 -1
  114. package/dist/public/sdk/activeWalletSession-WdZkhtBB.js +1 -0
  115. package/dist/public/sdk/{adapters-DdDOQzl4.js → adapters-DYPu0nK9.js} +2 -2
  116. package/dist/public/sdk/{canonicalPrimitives-CKPGgpxg.js → canonicalPrimitives-Dsbsxgxc.js} +1 -1
  117. package/dist/public/sdk/{capabilityKinds-CKQ4Uqnv.js → capabilityKinds-N8xo_IEh.js} +1 -1
  118. package/dist/public/sdk/{chains-CiYQT1K4.js → chains-C_X_fNuS.js} +1 -1
  119. package/dist/public/sdk/challengeDelivery-5lIu9spR.js +1 -0
  120. package/dist/{esm/sdk/clientSessionPersistenceState-CImFWDj6.js → public/sdk/clientSessionPersistenceState-DRdve9rC.js} +1 -1
  121. package/dist/public/sdk/{commitQueue-iBNUt9Bz.js → commitQueue-qjvY_zWn.js} +1 -1
  122. package/dist/public/sdk/{configHelpers-D8Ivi6p8.js → configHelpers-B-hs0mTO.js} +1 -1
  123. package/dist/public/sdk/digestEncoding-CkUc5vtR.js +1 -0
  124. package/dist/public/sdk/{display-ClqZq-Xt.js → display-DjoWrSgE.js} +1 -1
  125. package/dist/public/sdk/domainIds-BzkGsRqO.js +1 -0
  126. package/dist/{esm/sdk/ecdsaCapabilityManifest-BlzJAQF8.js → public/sdk/ecdsaCapabilityManifest-ChszYCC0.js} +1 -1
  127. package/dist/public/sdk/{ecdsaChainTarget-C8ZtMZ8l.js → ecdsaChainTarget-DJBXHzbH.js} +1 -1
  128. package/dist/{esm/sdk/ecdsaDerivationClientWasm-CVeNEou2.js → public/sdk/ecdsaDerivationClientWasm-CpH-b3jx.js} +1 -1
  129. package/dist/{esm/sdk/ecdsaDerivationExport-BZFHSMCv.js → public/sdk/ecdsaDerivationExport-C1cE5m0t.js} +1 -1
  130. package/dist/public/sdk/{ecdsaWalletRecords-D4WeYc7H.js → ecdsaWalletRecords-Di_NUxD_.js} +1 -1
  131. package/dist/public/sdk/emailOtpEcdsaDerivationIdentity-p0C1CQva.js +1 -0
  132. package/dist/public/sdk/{enrichDisplayModelWithAbi-69bNckvi.js → enrichDisplayModelWithAbi-DZIhvE-x.js} +1 -1
  133. package/dist/public/sdk/{evmCryptoWasm-BXsIyRon.js → evmCryptoWasm-DeobzyP-.js} +1 -1
  134. package/dist/{esm/sdk/export-viewer-host-CsFeiIhd.js → public/sdk/export-viewer-host-DUMwD6zP.js} +1 -1
  135. package/dist/{esm/sdk/exportKeypairOperation-DGQIYML3.js → public/sdk/exportKeypairOperation-DYCzCbqL.js} +1 -1
  136. package/dist/public/sdk/{helpers-Ddy72ULN.js → helpers-BnkILY2_.js} +1 -1
  137. package/dist/public/sdk/host-h55onlkx.js +1 -0
  138. package/dist/public/sdk/{intentDigest-CE-tLw87.js → intentDigest-DJBrMyLJ.js} +1 -1
  139. package/dist/public/sdk/{lanes-DnBwWv4l.js → lanes-Ck81oEGv.js} +1 -1
  140. package/dist/public/sdk/{localOnly-ClCo6602.js → localOnly-KvZeKkH5.js} +1 -1
  141. package/dist/{esm/sdk/messages-vxz27Way.js → public/sdk/messages-DgJlG9NU.js} +1 -1
  142. package/dist/public/sdk/{mountExportPrivateKeySurface-CBZ0wRYj.js → mountExportPrivateKeySurface-B4gH1Sel.js} +1 -1
  143. package/dist/{esm/sdk/mountRecoveryCodeBackupSurface-B1qhFF6G.js → public/sdk/mountRecoveryCodeBackupSurface-BA2ttbTM.js} +1 -1
  144. package/dist/public/sdk/nearEd25519YaoMaterialActivation-CvDs4RtV.js +1 -0
  145. package/dist/public/sdk/{nearEd25519YaoSigningPreparation-B0d1AG3u.js → nearEd25519YaoSigningPreparation-Eiq_ikXk.js} +1 -1
  146. package/dist/public/sdk/{nonceLaneKeys-Fkvk2UPy.js → nonceLaneKeys-Do5Vs-De.js} +1 -1
  147. package/dist/public/sdk/{normalization-DCvuCvh0.js → normalization-DJPmcXTg.js} +1 -1
  148. package/dist/public/sdk/{operationFingerprint-CTR9G1NT.js → operationFingerprint-CUrnoh-M.js} +1 -1
  149. package/dist/public/sdk/passkey-custody-Cd_yyoRa.js +1 -0
  150. package/dist/public/sdk/{pendingWalletRecoveryCodeBackup-yJN8VAHn.js → pendingWalletRecoveryCodeBackup-BkIrbd6Q.js} +1 -1
  151. package/dist/public/sdk/presignaturePool-CLHu7HaU.js +1 -0
  152. package/dist/public/sdk/{prfCache-BMpqZZ-v.js → prfCache-DCkuB8Lu.js} +1 -1
  153. package/dist/public/sdk/primitives-CqrjmIAH.js +1 -0
  154. package/dist/{esm/sdk/recovery-entrypoint-Bl5GgbW9.js → public/sdk/recovery-entrypoint-DoXswV9I.js} +1 -1
  155. package/dist/public/sdk/{registration-C4sALQZO.js → registration-BFHEYmgh.js} +1 -1
  156. package/dist/public/sdk/registration-Cfg9rWhA.js +1 -0
  157. package/dist/public/sdk/{registrationAccounts-D4RVetMz.js → registrationAccounts-DP-32yCK.js} +1 -1
  158. package/dist/public/sdk/{registrationAuthMethodInput-6ccY2Vuh.js → registrationAuthMethodInput-BBCeWDmw.js} +1 -1
  159. package/dist/public/sdk/{registrationIds-CdPqm-Ya.js → registrationIds-ByuReLUc.js} +1 -1
  160. package/dist/public/sdk/registrationIntent-BHU5k2Q-.js +1 -0
  161. package/dist/public/sdk/{registrationSignerPlan-B9GCvpTV.js → registrationSignerPlan-dY9Rp0m_.js} +1 -1
  162. package/dist/public/sdk/{requireStepUpAuth-DCVqmeee.js → requireStepUpAuth-C67sluoC.js} +1 -1
  163. package/dist/public/sdk/routerAbNormalSigning-DVKFBYgV.js +1 -0
  164. package/dist/public/sdk/{runtime-auth-BKFyLISf.js → runtime-auth-Ch4qvKL2.js} +1 -1
  165. package/dist/{esm/sdk/runtime-device-link-ENxdEXQW.js → public/sdk/runtime-device-link-DtNpEjq5.js} +1 -1
  166. package/dist/{esm/sdk/runtime-ecdsa-tempo-DhGEb9U7.js → public/sdk/runtime-ecdsa-tempo-Bntp_Zgx.js} +1 -1
  167. package/dist/public/sdk/{runtime-email-otp-dgsP7XZi.js → runtime-email-otp-DEFt-Y-_.js} +1 -1
  168. package/dist/public/sdk/{runtime-export-D2RCm5Gk.js → runtime-export-DE_umiS1.js} +1 -1
  169. package/dist/{esm/sdk/runtime-near-Bf-9MFBQ.js → public/sdk/runtime-near-uXqcLEz8.js} +1 -1
  170. package/dist/public/sdk/runtime-preferences-C49p0VLC.js +1 -0
  171. package/dist/public/sdk/runtime-recovery-D7wklehP.js +1 -0
  172. package/dist/public/sdk/{runtime-recovery-codes-BZMiAR_5.js → runtime-recovery-codes-Dn-NccpU.js} +1 -1
  173. package/dist/public/sdk/{sdkSentEvents-D3q1h-Uo.js → sdkSentEvents-DiQ3YVlj.js} +1 -1
  174. package/dist/public/sdk/{secp256k1-DSLttQND.js → secp256k1-C-AETUpI.js} +1 -1
  175. package/dist/public/sdk/{secureRandomId-BIekT8bE.js → secureRandomId-LwBFx84B.js} +1 -1
  176. package/dist/public/sdk/{sessionPolicy-J-RrlPZQ.js → sessionPolicy-CBTZQe1n.js} +1 -1
  177. package/dist/public/sdk/shared-D6RYxvYR.js +6 -0
  178. package/dist/{esm/sdk/signEvmFamily-KUNWKVeh.js → public/sdk/signEvmFamily-DjD3tn8e.js} +1 -1
  179. package/dist/public/sdk/{signEvmFamilyWithUiConfirmForTempo-Dc57bJ3V.js → signEvmFamilyWithUiConfirmForTempo-CwRFbaLM.js} +1 -1
  180. package/dist/public/sdk/{signEvmWithUiConfirm-CqxL7UbT.js → signEvmWithUiConfirm-BHG0dwVG.js} +1 -1
  181. package/dist/public/sdk/signNear-DR50cpes.js +1 -0
  182. package/dist/public/sdk/{signatureUses-CjJ233KX.js → signatureUses-8c8Ku_Fw.js} +1 -1
  183. package/dist/public/sdk/{signerDomain-vQmlnsbF.js → signerDomain-DqLCvI-D.js} +1 -1
  184. package/dist/public/sdk/{signingFlow-vrXxrhlG.js → signingFlow-Mym5j6aw.js} +1 -1
  185. package/dist/public/sdk/signingQueue-2pr7lAUS.js +1 -0
  186. package/dist/public/sdk/thresholdEcdsa-D-QMyevW.js +1 -0
  187. package/dist/public/sdk/{trace-BvbCxdXF.js → trace-QLsbYdld.js} +1 -1
  188. package/dist/public/sdk/{transaction-activity-D40ih2j-.js → transaction-activity-Cb2JyYKv.js} +1 -1
  189. package/dist/{esm/sdk/transactionReviewAdmission-C-a3ctCJ.js → public/sdk/transactionReviewAdmission-CIvR4W5_.js} +1 -1
  190. package/dist/{esm/sdk/transactionState-DVinJk4K.js → public/sdk/transactionState-CGULLokO.js} +1 -1
  191. package/dist/public/sdk/{types-D3GM-uHR.js → types-WGrFMQSw.js} +1 -1
  192. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  193. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  194. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  195. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  196. package/dist/public/sdk/wallet-recovery-D7ywcIHw.js +1 -0
  197. package/dist/{esm/sdk/walletAuthMethodRecord-CXedSgpV.js → public/sdk/walletAuthMethodRecord-CnBw27ED.js} +1 -1
  198. package/dist/public/sdk/walletAuthority-BWvfaKIX.js +1 -0
  199. package/dist/public/sdk/walletCustodyEcdsaContinuity-B8aO2NFb.js +1 -0
  200. package/dist/public/sdk/{walletOwnershipGeneration-DoXVMDWe.js → walletOwnershipGeneration-CAycHv-H.js} +1 -1
  201. package/dist/public/sdk/walletRecoveryCommit-C3EgMjo-.js +1 -0
  202. package/dist/public/sdk/walletRecoveryRotate-D_1a8Agl.js +1 -0
  203. package/dist/public/sdk/walletRegistrationSetupPrewarm-B9kpnrbK.js +1 -0
  204. package/dist/public/sdk/walletSessionAuthorizationStatus-BLyzJbU8.js +1 -0
  205. package/dist/public/sdk/{walletSessionAuthorizationStore-gEYPmu-G.js → walletSessionAuthorizationStore-BiKGIBWQ.js} +1 -1
  206. package/dist/public/sdk/warmSessionHydration-B7-kCnJh.js +1 -0
  207. package/dist/public/sdk/{webauthnP256-BEz4DEAs.js → webauthnP256-DZCusNY9.js} +1 -1
  208. package/dist/{esm/sdk/webauthnPromptCoordinator-BEudHQBr.js → public/sdk/webauthnPromptCoordinator-CS4Xc_jZ.js} +1 -1
  209. package/dist/public/sdk/workers/shamir3pass_runtime_bg.wasm +0 -0
  210. package/dist/public/wallet-assets.manifest.json +264 -240
  211. package/dist/public/wallet-service/index.html +4 -4
  212. package/dist/types/wallet/src/core/rpcClients/relayer/walletRegistrationSetupPrewarm.d.ts +4 -0
  213. package/dist/types/wallet/src/core/signingEngine/flows/signNear/shared/signatureOnlySigning.d.ts +2 -2
  214. package/dist/types/wallet/src/react/components/VoiceAssistantCard.d.ts +38 -0
  215. package/dist/types/wallet/src/react/components/VoiceAssistantCard.typecheck.d.ts +2 -0
  216. package/dist/types/wallet/src/react/index.d.ts +5 -1
  217. package/dist/workers/shamir3pass_runtime_bg.wasm +0 -0
  218. package/package.json +3 -2
  219. package/dist/esm/sdk/activeWalletSession-DiZcKjB_.js +0 -1
  220. package/dist/esm/sdk/challengeDelivery-DxXAkOfS.js +0 -1
  221. package/dist/esm/sdk/digestEncoding-Dzc1rzWV.js +0 -1
  222. package/dist/esm/sdk/emailOtpEcdsaDerivationIdentity-B8HzTh4T.js +0 -1
  223. package/dist/esm/sdk/host-c1__wJwz.js +0 -1
  224. package/dist/esm/sdk/nearEd25519YaoMaterialActivation-fWQI3rYj.js +0 -1
  225. package/dist/esm/sdk/normalize-kUDm5zfS.js +0 -1
  226. package/dist/esm/sdk/passkey-custody-BQj44jEM.js +0 -1
  227. package/dist/esm/sdk/presignaturePool-DwlTReFO.js +0 -1
  228. package/dist/esm/sdk/primitives-CAcl7ON7.js +0 -1
  229. package/dist/esm/sdk/registration-CEqVAgNJ.js +0 -1
  230. package/dist/esm/sdk/registrationIntent-DOkZcKSP.js +0 -1
  231. package/dist/esm/sdk/routerAbNormalSigning-BG75eyI2.js +0 -1
  232. package/dist/esm/sdk/runtime-preferences-LQ8SPE7o.js +0 -1
  233. package/dist/esm/sdk/runtime-recovery-BuEzJzuZ.js +0 -1
  234. package/dist/esm/sdk/shared-8ffIBYw2.js +0 -6
  235. package/dist/esm/sdk/signNear-BhTkDm2-.js +0 -1
  236. package/dist/esm/sdk/signingQueue-BrGJXBqe.js +0 -1
  237. package/dist/esm/sdk/thresholdEcdsa-CO7xo1So.js +0 -1
  238. package/dist/esm/sdk/wallet-recovery-C1kesLCF.js +0 -1
  239. package/dist/esm/sdk/walletAuthority-B5hXHWpK.js +0 -1
  240. package/dist/esm/sdk/walletCustodyEcdsaContinuity-abNZ_dvX.js +0 -1
  241. package/dist/esm/sdk/walletRecoveryCommit-Cc9AqHr0.js +0 -1
  242. package/dist/esm/sdk/walletRecoveryRotate-DWTAFYiv.js +0 -1
  243. package/dist/esm/sdk/walletSessionAuthorizationStatus-o1VgsLhA.js +0 -1
  244. package/dist/esm/sdk/warmSessionHydration-DgjuUacN.js +0 -1
  245. package/dist/public/sdk/activeWalletSession-DiZcKjB_.js +0 -1
  246. package/dist/public/sdk/challengeDelivery-DxXAkOfS.js +0 -1
  247. package/dist/public/sdk/digestEncoding-Dzc1rzWV.js +0 -1
  248. package/dist/public/sdk/emailOtpEcdsaDerivationIdentity-B8HzTh4T.js +0 -1
  249. package/dist/public/sdk/host-c1__wJwz.js +0 -1
  250. package/dist/public/sdk/nearEd25519YaoMaterialActivation-fWQI3rYj.js +0 -1
  251. package/dist/public/sdk/normalize-kUDm5zfS.js +0 -1
  252. package/dist/public/sdk/passkey-custody-BQj44jEM.js +0 -1
  253. package/dist/public/sdk/presignaturePool-DwlTReFO.js +0 -1
  254. package/dist/public/sdk/primitives-CAcl7ON7.js +0 -1
  255. package/dist/public/sdk/registration-CEqVAgNJ.js +0 -1
  256. package/dist/public/sdk/registrationIntent-DOkZcKSP.js +0 -1
  257. package/dist/public/sdk/routerAbNormalSigning-BG75eyI2.js +0 -1
  258. package/dist/public/sdk/runtime-preferences-LQ8SPE7o.js +0 -1
  259. package/dist/public/sdk/runtime-recovery-BuEzJzuZ.js +0 -1
  260. package/dist/public/sdk/shared-8ffIBYw2.js +0 -6
  261. package/dist/public/sdk/signNear-BhTkDm2-.js +0 -1
  262. package/dist/public/sdk/signingQueue-BrGJXBqe.js +0 -1
  263. package/dist/public/sdk/thresholdEcdsa-CO7xo1So.js +0 -1
  264. package/dist/public/sdk/wallet-recovery-C1kesLCF.js +0 -1
  265. package/dist/public/sdk/walletAuthority-B5hXHWpK.js +0 -1
  266. package/dist/public/sdk/walletCustodyEcdsaContinuity-abNZ_dvX.js +0 -1
  267. package/dist/public/sdk/walletRecoveryCommit-Cc9AqHr0.js +0 -1
  268. package/dist/public/sdk/walletRecoveryRotate-DWTAFYiv.js +0 -1
  269. package/dist/public/sdk/walletSessionAuthorizationStatus-o1VgsLhA.js +0 -1
  270. package/dist/public/sdk/warmSessionHydration-DgjuUacN.js +0 -1
  271. /package/dist/esm/sdk/{appearance-ZGVLwA4N.js → appearance-DITtYj-z.js} +0 -0
  272. /package/dist/esm/sdk/{authenticatorOptions-DMLnDWT2.js → authenticatorOptions-C9aCKgeF.js} +0 -0
  273. /package/dist/esm/sdk/{authorizationAdmission-Ckx6q6tp.js → authorizationAdmission-CGinGhXH.js} +0 -0
  274. /package/dist/esm/sdk/{base64-CsEj-_bC.js → base64-DW79QA0h.js} +0 -0
  275. /package/dist/esm/sdk/{browser-D4wUl_77.js → browser-DkCRXFkk.js} +0 -0
  276. /package/dist/esm/sdk/{bytes-BBYkulRB.js → bytes-DZRW2UDg.js} +0 -0
  277. /package/dist/esm/sdk/{canonicalSignerErrorCode-DEHsPxNm.js → canonicalSignerErrorCode-Cz48v4oy.js} +0 -0
  278. /package/dist/esm/sdk/{configBuilder-ZiZwFKt4.js → configBuilder-BMawmNpz.js} +0 -0
  279. /package/dist/esm/sdk/{errors-BZO3LF6G.js → errors-DIWY1KR9.js} +0 -0
  280. /package/dist/esm/sdk/{events-DsQJQ0Cl.js → events-1dzC4Ocx.js} +0 -0
  281. /package/dist/esm/sdk/{executeWorkerOperation-BInr8RYN.js → executeWorkerOperation-DKCRRq5E.js} +0 -0
  282. /package/dist/esm/sdk/{jsonRpc-DrCYQIM9.js → jsonRpc-YKL5n8VL.js} +0 -0
  283. /package/dist/esm/sdk/{jsxRuntime.module-BcZNe_OA.js → jsxRuntime.module-C8JOKu_4.js} +0 -0
  284. /package/dist/esm/sdk/{keccak-B02Fekdh.js → keccak-BArcwgbj.js} +0 -0
  285. /package/dist/esm/sdk/{normalization-CpLZcL2f.js → normalization-CeZT7ob0.js} +0 -0
  286. /package/dist/esm/sdk/{presignatures-DB2IPD-A.js → presignatures-DZm0d6Wy.js} +0 -0
  287. /package/dist/esm/sdk/{profileAccountProjection-DmmfMood.js → profileAccountProjection-B3LXAUmo.js} +0 -0
  288. /package/dist/esm/sdk/{promptText-D2f5Rg0h.js → promptText-B8RprJhO.js} +0 -0
  289. /package/dist/esm/sdk/{signerSlot-Dto7dObP.js → signerSlot-B4Eq8Oe2.js} +0 -0
  290. /package/dist/esm/sdk/{signingSessionSeal-CDLUmAFY.js → signingSessionSeal-DX41aXUL.js} +0 -0
  291. /package/dist/esm/sdk/{surface-measurement-reporter-IlPOI3QK.js → surface-measurement-reporter-DvVHPu_O.js} +0 -0
  292. /package/dist/esm/sdk/{theme-_AUTWLS_.js → theme-BKaFqCAj.js} +0 -0
  293. /package/dist/esm/sdk/{types-BNUuaUtl.js → types-DhtByIcQ.js} +0 -0
  294. /package/dist/esm/sdk/{walletIframeIdentity-DJ0KOBHg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
  295. /package/dist/esm/sdk/{walletSessionAuthorizationProjection-DWBksIJR.js → walletSessionAuthorizationProjection-DuU6w0FP.js} +0 -0
  296. /package/dist/esm/sdk/{walletSessionFailure-Bu4VPKTz.js → walletSessionFailure-YuhraC3P.js} +0 -0
  297. /package/dist/public/sdk/{appearance-ZGVLwA4N.js → appearance-DITtYj-z.js} +0 -0
  298. /package/dist/public/sdk/{authenticatorOptions-DMLnDWT2.js → authenticatorOptions-C9aCKgeF.js} +0 -0
  299. /package/dist/public/sdk/{authorizationAdmission-Ckx6q6tp.js → authorizationAdmission-CGinGhXH.js} +0 -0
  300. /package/dist/public/sdk/{base64-CsEj-_bC.js → base64-DW79QA0h.js} +0 -0
  301. /package/dist/public/sdk/{browser-D4wUl_77.js → browser-DkCRXFkk.js} +0 -0
  302. /package/dist/public/sdk/{bytes-BBYkulRB.js → bytes-DZRW2UDg.js} +0 -0
  303. /package/dist/public/sdk/{canonicalSignerErrorCode-DEHsPxNm.js → canonicalSignerErrorCode-Cz48v4oy.js} +0 -0
  304. /package/dist/public/sdk/{configBuilder-ZiZwFKt4.js → configBuilder-BMawmNpz.js} +0 -0
  305. /package/dist/public/sdk/{errors-BZO3LF6G.js → errors-DIWY1KR9.js} +0 -0
  306. /package/dist/public/sdk/{events-DsQJQ0Cl.js → events-1dzC4Ocx.js} +0 -0
  307. /package/dist/public/sdk/{executeWorkerOperation-BInr8RYN.js → executeWorkerOperation-DKCRRq5E.js} +0 -0
  308. /package/dist/public/sdk/{jsonRpc-DrCYQIM9.js → jsonRpc-YKL5n8VL.js} +0 -0
  309. /package/dist/public/sdk/{jsxRuntime.module-BcZNe_OA.js → jsxRuntime.module-C8JOKu_4.js} +0 -0
  310. /package/dist/public/sdk/{keccak-B02Fekdh.js → keccak-BArcwgbj.js} +0 -0
  311. /package/dist/public/sdk/{normalization-CpLZcL2f.js → normalization-CeZT7ob0.js} +0 -0
  312. /package/dist/public/sdk/{presignatures-DB2IPD-A.js → presignatures-DZm0d6Wy.js} +0 -0
  313. /package/dist/public/sdk/{profileAccountProjection-DmmfMood.js → profileAccountProjection-B3LXAUmo.js} +0 -0
  314. /package/dist/public/sdk/{promptText-D2f5Rg0h.js → promptText-B8RprJhO.js} +0 -0
  315. /package/dist/public/sdk/{signerSlot-Dto7dObP.js → signerSlot-B4Eq8Oe2.js} +0 -0
  316. /package/dist/public/sdk/{signingSessionSeal-CDLUmAFY.js → signingSessionSeal-DX41aXUL.js} +0 -0
  317. /package/dist/public/sdk/{surface-measurement-reporter-IlPOI3QK.js → surface-measurement-reporter-DvVHPu_O.js} +0 -0
  318. /package/dist/public/sdk/{theme-_AUTWLS_.js → theme-BKaFqCAj.js} +0 -0
  319. /package/dist/public/sdk/{types-BNUuaUtl.js → types-DhtByIcQ.js} +0 -0
  320. /package/dist/public/sdk/{walletIframeIdentity-DJ0KOBHg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
  321. /package/dist/public/sdk/{walletSessionAuthorizationProjection-DWBksIJR.js → walletSessionAuthorizationProjection-DuU6w0FP.js} +0 -0
  322. /package/dist/public/sdk/{walletSessionFailure-Bu4VPKTz.js → walletSessionFailure-YuhraC3P.js} +0 -0
@@ -0,0 +1 @@
1
+ import{D as e,M as t,O as n,S as r,T as i,f as a,h as o,j as s,r as c,x as l}from"./domainIds-BzkGsRqO.js";import{C as u,S as d,c as f}from"./chains-C_X_fNuS.js";import{D as p,E as m,M as ee,j as te,k as h,y as ne}from"./primitives-CqrjmIAH.js";import{t as re}from"./walletRegistrationSetupPrewarm-B9kpnrbK.js";import{r as ie}from"./base64-DW79QA0h.js";import{o as ae}from"./sessionPolicy-CBTZQe1n.js";import{d as oe,f as se,i as ce,r as le}from"./signingSessionSeal-DX41aXUL.js";import{i as ue,n as de,r as fe}from"./activeWalletSession-WdZkhtBB.js";import{d as g,g as pe,h as _,m as me}from"./capabilityKinds-N8xo_IEh.js";import{o as he,r as ge}from"./canonicalPrimitives-Dsbsxgxc.js";import{c as _e,l as ve,s as ye}from"./accountIds-BzZs7YoX.js";import{r as be}from"./registrationAuthMethodInput-BBCeWDmw.js";import{o as xe,u as Se}from"./registrationSignerPlan-dY9Rp0m_.js";import{a as v,l as Ce,o as we,s as Te}from"./ecdsaChainTarget-DJBXHzbH.js";import{n as Ee,r as De}from"./signerDomain-DqLCvI-D.js";import{P as Oe,a as ke,c as Ae,i as je,lt as Me,n as Ne,o as Pe,s as Fe,t as Ie,vt as Le,yt as Re}from"./registrationIntent-BHU5k2Q-.js";import{d as ze}from"./walletAuthority-BWvfaKIX.js";import{At as Be,C as Ve,Dt as y,E as He,K as Ue,M as We,b as Ge,en as Ke,it as qe,l as Je,nt as Ye,ot as Xe,q as Ze,rt as Qe,y as $e}from"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{K as b,O as et,U as tt}from"./challengeDelivery-5lIu9spR.js";import{r as nt}from"./walletAuthMethodRecord-CnBw27ED.js";import{a as rt,i as x}from"./registrationIds-ByuReLUc.js";import{d as S,t as it}from"./passkey-custody-Cd_yyoRa.js";import{n as at}from"./thresholdEcdsa-D-QMyevW.js";function ot(e){let t=T(e);if(!t||!(`kind`in t)||typeof t.kind!=`string`)return null;switch(t.kind){case`issued`:{if(!E(t,[`kind`,`session`])||!(`session`in t))return null;let e=st(t.session);return e===null?null:{kind:`issued`,session:e}}case`already_committed`:{if(!E(t,[`kind`,`session`,`next`])||!(`session`in t)||!(`next`in t)||t.next!==`unlock_exact_method`)return null;let e=ut(t.session);return e===null?null:{kind:`already_committed`,session:e,next:t.next}}default:return null}}function st(e){try{let t=T(e);if(!t||!E(t,[`kind`,`walletId`,`authorizationId`,`walletSessionId`,`quotaId`,`expiresAtMs`,`remainingUses`,`walletSession`,`operationCredential`,`tokens`])||!(`kind`in t)||!(`walletId`in t)||!(`authorizationId`in t)||!(`walletSessionId`in t)||!(`quotaId`in t)||!(`expiresAtMs`in t)||!(`remainingUses`in t)||!(`walletSession`in t)||!(`operationCredential`in t)||!(`tokens`in t)||t.kind!==`registration_established_wallet_session_v2`)return null;let r=n(t.walletId),i=_(t.walletSessionId),a=me(t.authorizationId),o=g(t.quotaId);if(!r.ok||!a.ok||!i.ok||!o.ok)return null;let s=w(t.expiresAtMs),c=w(t.remainingUses);if(s===null||s<=0||c===null||c<=0)return null;let l=de(t.walletSession),u=ue(t.operationCredential);if(l.walletId!==r.value||l.authorizationId!==a.value||l.quotaId!==o.value||l.expiresAtMs!==s||u.walletSessionId!==i.value)return null;let d=dt(t.tokens);return d===null||!ct(l,d)?null:{kind:`registration_established_wallet_session_v2`,walletId:r.value,authorizationId:a.value,walletSessionId:i.value,quotaId:o.value,expiresAtMs:s,remainingUses:c,walletSession:l,operationCredential:u,tokens:d}}catch{return null}}function ct(e,t){switch(t.kind){case`evm_family_ecdsa`:return C(e,`ecdsa_secp256k1`,t.ecdsa.materialActivation)&&!lt(e,`ecdsa_secp256k1`);case`near_ed25519`:return C(e,`ed25519`,t.ed25519.materialActivation)&&!lt(e,`ed25519`);case`near_ed25519_and_evm_family_ecdsa`:return C(e,`ecdsa_secp256k1`,t.ecdsa.materialActivation)&&C(e,`ed25519`,t.ed25519.materialActivation)&&!lt(e,`ed25519`,`ecdsa_secp256k1`);default:return!1}}function C(e,t,n){return e.capabilitySubjects.some(e=>e.kind===`sign`&&e.keyFamily===t&&c(e.materialActivation,n))}function lt(e,...t){return e.capabilitySubjects.some(e=>e.kind===`sign`&&!t.includes(e.keyFamily))}function ut(e){try{let t=T(e);if(!t||!E(t,[`kind`,`walletId`,`authorizationId`,`walletSessionId`,`quotaId`,`expiresAtMs`,`remainingUses`,`walletSession`,`tokens`])||!(`kind`in t)||!(`walletId`in t)||!(`authorizationId`in t)||!(`walletSessionId`in t)||!(`quotaId`in t)||!(`expiresAtMs`in t)||!(`remainingUses`in t)||!(`walletSession`in t)||!(`tokens`in t)||t.kind!==`registration_established_wallet_session_projection_v2`)return null;let r=n(t.walletId),i=me(t.authorizationId),a=_(t.walletSessionId),o=g(t.quotaId);if(!r.ok||!i.ok||!a.ok||!o.ok||new Set([i.value,a.value,o.value]).size!==3)return null;let s=w(t.expiresAtMs),c=w(t.remainingUses),l=de(t.walletSession),u=dt(t.tokens);return s===null||s<=0||c===null||u===null||l.walletId!==r.value||l.authorizationId!==i.value||l.quotaId!==o.value||l.expiresAtMs!==s||!ct(l,u)?null:{kind:`registration_established_wallet_session_projection_v2`,walletId:r.value,authorizationId:i.value,walletSessionId:a.value,quotaId:o.value,expiresAtMs:s,remainingUses:c,walletSession:l,tokens:u}}catch{return null}}function dt(e){let t=T(e);if(!t||!(`kind`in t)||typeof t.kind!=`string`)return null;switch(t.kind){case`evm_family_ecdsa`:{if(!E(t,[`kind`,`ecdsa`])||!(`ecdsa`in t))return null;let e=ft(t.ecdsa);return e===null?null:{kind:`evm_family_ecdsa`,ecdsa:e}}case`near_ed25519`:{if(!E(t,[`kind`,`ed25519`])||!(`ed25519`in t))return null;let e=pt(t.ed25519);return e===null?null:{kind:`near_ed25519`,ed25519:e}}case`near_ed25519_and_evm_family_ecdsa`:{if(!E(t,[`kind`,`ecdsa`,`ed25519`])||!(`ecdsa`in t)||!(`ed25519`in t))return null;let e=ft(t.ecdsa),n=pt(t.ed25519);return e===null||n===null?null:{kind:`near_ed25519_and_evm_family_ecdsa`,ecdsa:e,ed25519:n}}default:return null}}function ft(e){let t=T(e);if(!t||!E(t,[`sessionKind`,`thresholdSessionId`,`keyHandle`,`runtimePolicyScope`,`materialActivation`,`routerAbEcdsaDerivationNormalSigning`])||!(`sessionKind`in t)||!(`thresholdSessionId`in t)||!(`keyHandle`in t)||!(`runtimePolicyScope`in t)||!(`materialActivation`in t)||!(`routerAbEcdsaDerivationNormalSigning`in t)||t.sessionKind!==`credential_free_projection_v2`)return null;let n=l(t.thresholdSessionId);if(!n.ok)return null;try{let e=We(t.keyHandle),r=mt(t.runtimePolicyScope),i=o(t.materialActivation);if(!i.ok)return null;let a=Ue(t.routerAbEcdsaDerivationNormalSigning);if(!a)return null;let s=Ke(a.scope.material_activation);return c(i.value,s)?{sessionKind:`credential_free_projection_v2`,thresholdSessionId:n.value,keyHandle:e,runtimePolicyScope:r,materialActivation:i.value,routerAbEcdsaDerivationNormalSigning:a}:null}catch{return null}}function pt(e){let t=T(e);if(!t||!E(t,[`sessionKind`,`thresholdSessionId`,`nearAccountId`,`nearEd25519SigningKeyId`,`runtimePolicyScope`,`materialActivation`,`routerAbNormalSigning`])||!(`sessionKind`in t)||!(`thresholdSessionId`in t)||!(`nearAccountId`in t)||!(`nearEd25519SigningKeyId`in t)||!(`runtimePolicyScope`in t)||!(`materialActivation`in t)||!(`routerAbNormalSigning`in t)||t.sessionKind!==`credential_free_projection_v2`)return null;let n=r(t.thresholdSessionId),i=ve(t.nearAccountId);if(!n.ok||!i.ok)return null;try{let e=x(t.nearEd25519SigningKeyId),r=mt(t.runtimePolicyScope),a=o(t.materialActivation);if(!a.ok)return null;let s=oe(t.routerAbNormalSigning);return s?{sessionKind:`credential_free_projection_v2`,thresholdSessionId:n.value,nearAccountId:i.value,nearEd25519SigningKeyId:e,runtimePolicyScope:r,materialActivation:a.value,routerAbNormalSigning:s}:null}catch{return null}}function mt(e){let t=T(e);if(!t||!E(t,[`orgId`,`projectId`,`envId`,`signingRootVersion`])||!(`orgId`in t)||!(`projectId`in t)||!(`envId`in t)||!(`signingRootVersion`in t))throw Error(`runtime policy scope projection is invalid`);return ne({orgId:t.orgId,projectId:t.projectId,envId:t.envId,signingRootVersion:t.signingRootVersion})}function w(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:null}function T(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function E(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.prototype.hasOwnProperty.call(e,t))}function D(e){let t=String(e||``).trim().toLowerCase();return/^0x[0-9a-f]{40}$/.test(t)?t:``}const ht=/^ederivation-key-[A-Za-z0-9_-]+$/;function O(e){let t=String(e||``).trim();return t?ht.test(t)?{kind:`resolved`,keyHandle:t}:{kind:`invalid`}:{kind:`missing`}}function gt(e){let t=O(e.keyHandle),n=d(e.sharedEvmFamilyKey)?O(e.sharedEvmFamilyKey.keyHandle):{kind:`missing`};return t.kind===`missing`?{kind:`blocked`,reason:`missing_key_handle`}:t.kind===`invalid`||n.kind===`invalid`?{kind:`blocked`,reason:`invalid_key_handle`}:n.kind===`resolved`&&t.keyHandle!==n.keyHandle?{kind:`blocked`,reason:`duplicate_key_handles`}:{kind:`resolved`,keyHandle:t.keyHandle}}function _t(e){let t=(d(e.metadata.sharedEvmFamilyKey)?e.metadata.sharedEvmFamilyKey:null)||e.metadata,n=String(t.thresholdEcdsaPublicKeyB64u||e.metadata.thresholdEcdsaPublicKeyB64u||``).trim();if(!n)return null;let r=String(t.walletId||``).trim();if(!r)return null;try{He(n);let i=t.ecdsaThresholdKeyId||e.metadata.ecdsaThresholdKeyId,a=t.signingRootId||e.metadata.signingRootId,o=t.signingRootVersion||e.metadata.signingRootVersion,s=t.participantIds||e.metadata.participantIds,c=t.thresholdOwnerAddress||e.metadata.thresholdOwnerAddress||e.metadata.ownerAddress;return Je({walletId:r,keyHandle:e.keyHandle,chainTarget:e.chainTarget,ecdsaThresholdKeyId:i,signingRootId:a,signingRootVersion:o,participantIds:s,thresholdOwnerAddress:c,thresholdEcdsaPublicKeyB64u:n})}catch{return null}}function vt(e){try{let t=Ze(e.raw);return String(t.client_id)!==String(e.walletId)||t.public_identity.threshold_public_key33_b64u!==e.thresholdEcdsaPublicKeyB64u?null:t}catch{return null}}function yt(e){let t=e.signer;if(t.status!==`active`||t.signerKind!==De.thresholdEcdsa||t.signerAuthMethod!==Ee.passkey)return{kind:`skipped`};let n=d(t.metadata)?t.metadata:{};if(!d(n.chainTarget))return{kind:`blocked`,targetKey:``,reason:`missing_chain_target`};let r;try{r=v(n.chainTarget)}catch{return{kind:`blocked`,targetKey:``,reason:`invalid_chain_target`}}if(!e.configuredTargets.some(e=>Te(e,r)))return{kind:`skipped`};let i=we(r),a=gt(n);if(a.kind===`blocked`)return{kind:`blocked`,targetKey:i,reason:a.reason};let o=_t({metadata:n,keyHandle:a.keyHandle,chainTarget:r});if(!o)return{kind:`key_facts_inventory_required`,chainTarget:r,targetKey:i,keyHandle:a.keyHandle,reason:`missing_key_facts`};let s=vt({raw:n.publicCapability,walletId:e.walletId,thresholdEcdsaPublicKeyB64u:o.keyFacts.thresholdEcdsaPublicKeyB64u});return{kind:`active_wallet_key`,chainTarget:r,targetKey:i,walletKey:o,publicCapability:s?{kind:`persisted_public_capability`,value:s}:{kind:`missing_public_capability`}}}function bt(e){let{raw:t}=e;if(!d(t)||!d(t.chainTarget))return null;let n=d(t.key)?t.key:t,r;try{r=v(t.chainTarget)}catch{return null}let i=O(t.keyHandle),a=O(n.keyHandle),o=D(t.accountAddress),s=D(t.ownerAddress),c=String(n.walletId||``).trim(),l=String(n.subjectId||``).trim(),u=String(Ce({walletId:e.walletId})),f=String(n.rpId||``).trim(),p=String(n.thresholdEcdsaPublicKeyB64u||t.thresholdEcdsaPublicKeyB64u||``).trim(),m=D(n.thresholdOwnerAddress||t.ownerAddress||t.accountAddress||t.ethereumAddress);if(i.kind!==`resolved`||a.kind!==`resolved`||a.keyHandle!==i.keyHandle||!p||!s||!o||!m||c!==String(e.walletId)||l&&l!==u||f!==e.rpId||m!==s)return null;try{let a=vt({raw:t.publicCapability,walletId:e.walletId,thresholdEcdsaPublicKeyB64u:p});if(!a)return null;let c=Ve(i.keyHandle),l=Ge({record:{ecdsaThresholdKeyId:t.ecdsaThresholdKeyId}}),u=$e({signingRootId:t.signingRootId||n.signingRootId,signingRootVersion:t.signingRootVersion||n.signingRootVersion});return{accountAddress:o,ownerAddress:s,publicCapability:a,walletKey:Je({walletId:e.walletId,keyHandle:c,chainTarget:r,ecdsaThresholdKeyId:l,signingRootId:u.signingRootId,signingRootVersion:u.signingRootVersion,participantIds:n.participantIds||t.participantIds,thresholdOwnerAddress:m,thresholdEcdsaPublicKeyB64u:p})}}catch{return null}}function xt(e){let t=[];for(let n of e.records){let r=bt({walletId:e.walletId,rpId:e.rpId,raw:n});r&&t.push(r)}return t}function k(e){let t=String(e.value||``).trim();if(!t)throw Error(`${e.responseName} response missing ${e.field}`);return t}function A(e){if(!u(e.value))throw Error(`${e.responseName} response missing ${e.field}`);return e.value}function j(e,t,n){let r=new Set(t);for(let t of Object.keys(e))if(!r.has(t))throw Error(`${n} response contains unexpected ${t}`)}function M(e){let t=Number(e.value);if(!Number.isSafeInteger(t)||t<e.minimum)throw Error(`${e.responseName} response has invalid ${e.field}`);return t}function N(e,t){if(!Array.isArray(e)||e.length!==2)throw Error(`${t} response has invalid participantIds`);let n=M({responseName:t,field:`participantIds[0]`,value:e[0],minimum:1}),r=M({responseName:t,field:`participantIds[1]`,value:e[1],minimum:1});if(n===r)throw Error(`${t} response has duplicate participantIds`);if(n!==1||r!==2)throw Error(`${t} response has unsupported participantIds`);return[n,r]}function P(e,n){let r=t(e);if(!r.ok)throw Error(`${n} response has invalid rpId`);return r.value}function St(e,t){let n=A({responseName:t,field:`authorityScope`,value:e});switch(n.kind){case`passkey_rp`:return j(n,[`kind`,`rpId`],t),{kind:`passkey_rp`,rpId:P(n.rpId,t)};case`email_otp`:if(j(n,[`kind`,`provider`,`providerUserId`],t),n.provider!==`google`&&n.provider!==`email`)throw Error(`${t} response has invalid authorityScope provider`);return{kind:`email_otp`,provider:n.provider,providerUserId:k({responseName:t,field:`authorityScope.providerUserId`,value:n.providerUserId})};default:throw Error(`${t} response has invalid authorityScope`)}}function Ct(e,t){let n=A({responseName:t,field:`ed25519`,value:e});if(j(n,[`signerSlot`,`nearAccountId`,`nearEd25519SigningKeyId`,`publicKey`,`relayerKeyId`,`keyVersion`,`recoveryExportCapable`,`participantIds`],t),n.recoveryExportCapable!==!0)throw Error(`${t} response is not recovery/export capable`);return{signerSlot:M({responseName:t,field:`ed25519.signerSlot`,value:n.signerSlot,minimum:1}),nearAccountId:k({responseName:t,field:`ed25519.nearAccountId`,value:n.nearAccountId}),nearEd25519SigningKeyId:k({responseName:t,field:`ed25519.nearEd25519SigningKeyId`,value:n.nearEd25519SigningKeyId}),publicKey:k({responseName:t,field:`ed25519.publicKey`,value:n.publicKey}),relayerKeyId:k({responseName:t,field:`ed25519.relayerKeyId`,value:n.relayerKeyId}),keyVersion:k({responseName:t,field:`ed25519.keyVersion`,value:n.keyVersion}),recoveryExportCapable:!0,participantIds:N(n.participantIds,t)}}function wt(e,t){let n=A({responseName:t,field:`ed25519`,value:e});j(n,[`signerSlot`,`nearAccountId`,`nearEd25519SigningKeyId`,`publicKey`,`relayerKeyId`,`keyVersion`,`recoveryExportCapable`,`participantIds`,`thresholdSessionId`,`runtimePolicyScope`,`routerAbNormalSigning`],t);let i=Ct({signerSlot:n.signerSlot,nearAccountId:n.nearAccountId,nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,publicKey:n.publicKey,relayerKeyId:n.relayerKeyId,keyVersion:n.keyVersion,recoveryExportCapable:n.recoveryExportCapable,participantIds:n.participantIds},t),a=r(n.thresholdSessionId);if(!a.ok)throw Error(`${t} response has invalid ed25519.thresholdSessionId`);let o=ae(n.runtimePolicyScope);if(!o)throw Error(`${t} response has invalid ed25519.runtimePolicyScope`);return{...i,thresholdSessionId:a.value,runtimePolicyScope:o,routerAbNormalSigning:se(n.routerAbNormalSigning)}}function Tt(e,t){let n=A({responseName:t,field:`chainTarget`,value:e});switch(n.kind){case`evm`:return j(n,[`kind`,`namespace`,`chainId`,`networkSlug`],t),v(n);case`tempo`:return j(n,[`kind`,`chainId`,`networkSlug`],t),v(n);default:throw Error(`${t} response has invalid chainTarget kind`)}}function Et(e,t){let n=A({responseName:t,field:`ecdsa.walletKeys[]`,value:e});if(j(n,[`keyScope`,`chainTarget`,`walletId`,`evmFamilySigningKeySlotId`,`keyHandle`,`ecdsaThresholdKeyId`,`signingRootId`,`signingRootVersion`,`thresholdEcdsaPublicKeyB64u`,`thresholdOwnerAddress`,`relayerKeyId`,`relayerVerifyingShareB64u`,`contextBinding32B64u`,`derivationClientSharePublicKey33B64u`,`clientShareRetryCounter`,`relayerShareRetryCounter`,`participantIds`,`publicCapability`],t),n.keyScope!==`evm-family`)throw Error(`${t} response has invalid keyScope`);return{keyScope:`evm-family`,chainTarget:Tt(n.chainTarget,t),walletId:k({responseName:t,field:`walletId`,value:n.walletId}),evmFamilySigningKeySlotId:k({responseName:t,field:`evmFamilySigningKeySlotId`,value:n.evmFamilySigningKeySlotId}),keyHandle:k({responseName:t,field:`keyHandle`,value:n.keyHandle}),ecdsaThresholdKeyId:k({responseName:t,field:`ecdsaThresholdKeyId`,value:n.ecdsaThresholdKeyId}),signingRootId:k({responseName:t,field:`signingRootId`,value:n.signingRootId}),signingRootVersion:k({responseName:t,field:`signingRootVersion`,value:n.signingRootVersion}),thresholdEcdsaPublicKeyB64u:k({responseName:t,field:`thresholdEcdsaPublicKeyB64u`,value:n.thresholdEcdsaPublicKeyB64u}),thresholdOwnerAddress:k({responseName:t,field:`thresholdOwnerAddress`,value:n.thresholdOwnerAddress}),relayerKeyId:k({responseName:t,field:`relayerKeyId`,value:n.relayerKeyId}),relayerVerifyingShareB64u:k({responseName:t,field:`relayerVerifyingShareB64u`,value:n.relayerVerifyingShareB64u}),contextBinding32B64u:k({responseName:t,field:`contextBinding32B64u`,value:n.contextBinding32B64u}),derivationClientSharePublicKey33B64u:k({responseName:t,field:`derivationClientSharePublicKey33B64u`,value:n.derivationClientSharePublicKey33B64u}),clientShareRetryCounter:M({responseName:t,field:`clientShareRetryCounter`,value:n.clientShareRetryCounter,minimum:0}),relayerShareRetryCounter:M({responseName:t,field:`relayerShareRetryCounter`,value:n.relayerShareRetryCounter,minimum:0}),participantIds:N(n.participantIds,t),publicCapability:Ze(n.publicCapability)}}function Dt(e){switch(e){case`registrationIntentLoadMs`:case`registrationIntentDigestMs`:case`registrationIntentConsumeMs`:case`registrationAttemptGateMs`:case`registrationPreparationPersistMs`:case`registrationPreparationLoadMs`:case`registrationPreparationConsumeMs`:case`registrationPreparationScopeCheckMs`:case`registrationAuthorityVerifyMs`:case`registrationEcdsaPrepareMs`:case`registrationCeremonyPersistMs`:case`registerPrepareTotalMs`:case`registerStartTotalMs`:case`registrationEcdsaRespondMs`:case`registrationFinalizeReplayLoadMs`:case`registrationCeremonyLoadMs`:case`registrationEcdsaBootstrapVerifyMs`:case`sponsoredNearAccountCreateMs`:case`registrationKeygenMs`:case`registrationEmailOtpEnrollmentPlanMs`:case`relaySessionMintMs`:case`relayGoogleEmailOtpActivationPlanMs`:case`relayPersistenceMs`:case`registrationFinalizeReplayCacheMs`:case`registerFinalizeTotalMs`:return e;default:throw Error(`Wallet registration finalize response has invalid diagnostics timing name`)}}function Ot(e){let t=`Wallet registration finalize`,n=A({responseName:t,field:`registrationDiagnostics`,value:e});if(j(n,[`kind`,`route`,`entries`],t),n.kind!==`wallet_registration_route_diagnostics_v1`||n.route!==`wallets_register_finalize`||!Array.isArray(n.entries))throw Error(`${t} response has invalid registrationDiagnostics`);return{kind:`wallet_registration_route_diagnostics_v1`,route:`wallets_register_finalize`,entries:n.entries.map(e=>{let n=A({responseName:t,field:`registrationDiagnostics.entries[]`,value:e});if(j(n,[`name`,`durationMs`],t),typeof n.durationMs!=`number`||!Number.isFinite(n.durationMs)||n.durationMs<0)throw Error(`${t} response has invalid diagnostics durationMs`);return{name:Dt(n.name),durationMs:n.durationMs}})}}function kt(e){let t=`Wallet registration finalize`,n=A({responseName:t,field:`authority`,value:e});j(n,[`walletId`,`factor`,`verifier`,`bindingId`],t);let r=A({responseName:t,field:`authority.factor`,value:n.factor}),i=A({responseName:t,field:`authority.verifier`,value:n.verifier});switch(r.kind){case`passkey`:j(r,[`kind`,`credentialIdB64u`],t),j(i,[`kind`,`rpId`],t);break;case`email_otp`:j(r,[`kind`,`provider`,`providerUserId`],t),j(i,[`kind`,`emailHashHex`],t);break;default:throw Error(`${t} response has invalid authority factor`)}let a=Be(n);if(!a)throw Error(`${t} response has invalid authority`);return a}function At(e){let t=`Wallet registration finalize`,n=A({responseName:t,field:`authMethod`,value:e.response.authMethod});if(String(e.authority.walletId)!==String(e.walletId))throw Error(`${t} response authority wallet mismatch`);switch(n.kind){case`passkey`:{if(j(n,[`kind`,`credentialIdB64u`,`credentialPublicKeyB64u`],t),!y(e.authority))throw Error(`${t} response has inconsistent passkey authority`);let r=P(e.response.rpId,t),i=k({responseName:t,field:`authMethod.credentialIdB64u`,value:n.credentialIdB64u});if(String(e.authority.factor.credentialIdB64u)!==i||String(e.authority.verifier.rpId)!==String(r))throw Error(`${t} response passkey authority binding mismatch`);return{kind:`passkey`,rpId:r,authMethod:{kind:`passkey`,credentialIdB64u:i,credentialPublicKeyB64u:k({responseName:t,field:`authMethod.credentialPublicKeyB64u`,value:n.credentialPublicKeyB64u})}}}case`email_otp`:if(j(n,[`kind`,`registrationAuthorityId`],t),y(e.authority)||e.response.rpId!==void 0)throw Error(`${t} response has inconsistent email OTP authority`);return{kind:`email_otp`,authMethod:{kind:`email_otp`,registrationAuthorityId:k({responseName:t,field:`authMethod.registrationAuthorityId`,value:n.registrationAuthorityId})}};default:throw Error(`${t} response has invalid authMethod`)}}function jt(e){let t=`Wallet registration finalize`,n=A({responseName:t,field:`accountProvisioning`,value:e});switch(n.kind){case`implicit_account`:if(j(n,[`kind`,`accountIdSource`],t),n.accountIdSource!==`ed25519_public_key`)throw Error(`${t} response has invalid implicit account provisioning`);return{kind:`implicit_account`,accountIdSource:`ed25519_public_key`};case`sponsored_named_account`:{j(n,[`kind`,`requestedAccountId`,`sponsor`],t);let e=_e(n.requestedAccountId);if(!e.ok||n.sponsor!==`relayer`)throw Error(`${t} response has invalid named account provisioning`);return{kind:`sponsored_named_account`,requestedAccountId:e.value,sponsor:`relayer`}}default:throw Error(`${t} response has invalid accountProvisioning kind`)}}function Mt(e){let t=`Wallet registration finalize`,n=A({responseName:t,field:`resolvedAccount`,value:e});switch(n.kind){case`implicit_account`:{j(n,[`kind`,`nearAccountId`,`nearEd25519SigningKeyId`],t);let e=ye(n.nearAccountId);if(!e.ok)throw Error(`${t} response has invalid implicit nearAccountId`);return{kind:`implicit_account`,nearAccountId:e.value,nearEd25519SigningKeyId:x(n.nearEd25519SigningKeyId)}}case`sponsored_named_account`:{j(n,[`kind`,`nearAccountId`,`nearEd25519SigningKeyId`,`transactionHash`],t);let e=_e(n.nearAccountId);if(!e.ok)throw Error(`${t} response has invalid named nearAccountId`);return{kind:`sponsored_named_account`,nearAccountId:e.value,nearEd25519SigningKeyId:x(n.nearEd25519SigningKeyId),transactionHash:k({responseName:t,field:`resolvedAccount.transactionHash`,value:n.transactionHash})}}default:throw Error(`${t} response has invalid resolvedAccount kind`)}}function Nt(e){let t=`Wallet registration finalize`,n=A({responseName:t,field:`ecdsa`,value:e.value});if(j(n,[`walletKeys`],t),!Array.isArray(n.walletKeys)||n.walletKeys.length===0)throw Error(`${t} response has invalid walletKeys`);let r=new Set;return{walletKeys:n.walletKeys.map(n=>{let i=Et(n,t);if(i.walletId!==String(e.walletId))throw Error(`${t} response ECDSA walletId mismatch`);if(String(i.publicCapability.client_id)!==String(e.walletId)||i.publicCapability.public_identity.context_binding_b64u!==i.contextBinding32B64u||i.publicCapability.public_identity.derivation_client_share_public_key33_b64u!==i.derivationClientSharePublicKey33B64u||i.publicCapability.public_identity.threshold_public_key33_b64u!==i.thresholdEcdsaPublicKeyB64u||i.publicCapability.public_identity.client_share_retry_counter!==i.clientShareRetryCounter||i.publicCapability.public_identity.server_share_retry_counter!==i.relayerShareRetryCounter)throw Error(`${t} response ECDSA public capability mismatch`);let a=we(i.chainTarget);if(r.has(a))throw Error(`${t} response has duplicate ECDSA target ${a}`);return r.add(a),i})}}function Pt(e){let t=`Wallet registration finalize`,n=St(e.response.authorityScope,t),r=jt(e.response.accountProvisioning),i=Mt(e.response.resolvedAccount),a=wt(e.response.ed25519,t);if(r.kind!==i.kind||i.nearAccountId!==a.nearAccountId||i.nearEd25519SigningKeyId!==a.nearEd25519SigningKeyId)throw Error(`${t} response has inconsistent Ed25519 identity`);if(n.kind===`passkey_rp`&&(!y(e.authority)||String(e.authority.verifier.rpId)!==String(n.rpId))||n.kind===`email_otp`&&(y(e.authority)||e.authority.factor.provider!==n.provider||String(e.authority.factor.providerUserId)!==n.providerUserId))throw Error(`${t} response authorityScope mismatch`);return{authorityScope:n,accountProvisioning:r,resolvedAccount:i,ed25519:a}}function Ft(e){let t=`Wallet registration finalize`,n=A({responseName:t,field:`body`,value:e.value});if(j(n,[`ok`,`walletId`,`authority`,`foundingAuthority`,`foundingAuthMethod`,`registrationDiagnostics`,`rpId`,`authMethod`,`walletCustody`,`custodyKeyManifestDigestB64u`,`kind`,`authorityScope`,`accountProvisioning`,`resolvedAccount`,`ed25519`,`ecdsa`],t),n.ok!==!0||n.kind!==e.expectedKind)throw Error(`${t} response substituted signer branch`);let r=rt(k({responseName:t,field:`walletId`,value:n.walletId})),i=kt(n.authority),a=ze(n.foundingAuthority),o=nt(n.foundingAuthMethod);if(!a.ok)throw Error(`${t} response has an invalid founding authority: ${a.error.message}`);if(a.value.state!==`active`)throw Error(`${t} response has an inactive founding authority`);if(!o)throw Error(`${t} response has an invalid founding auth method`);if(o.status!==`active`)throw Error(`${t} response has an inactive founding auth method`);if(a.value.walletId!==r||o.walletId!==r)throw Error(`${t} response changed the founding wallet identity`);if(o.walletAuthorityId!==a.value.authorityId)throw Error(`${t} response has mismatched founding authority identities`);if(o.walletAuthMethodId!==i.bindingId)throw Error(`${t} response has mismatched founding auth-method identities`);let s=At({response:n,walletId:r,authority:i}),c=n.registrationDiagnostics===void 0?void 0:Ot(n.registrationDiagnostics),l=n.walletCustody===void 0?{}:{walletCustody:it(n.walletCustody,t)},u=n.custodyKeyManifestDigestB64u===void 0?void 0:k({responseName:t,field:`custodyKeyManifestDigestB64u`,value:n.custodyKeyManifestDigestB64u});if(u!==void 0&&ie(u).byteLength!==32)throw Error(`${t} response has invalid custodyKeyManifestDigestB64u`);let d=u===void 0?{}:{custodyKeyManifestDigestB64u:u};switch(n.kind){case`near_ed25519`:{if(n.ecdsa!==void 0)throw Error(`${t} response mixed signer branches`);let e=Pt({response:n,authority:i});return s.kind===`passkey`?{ok:!0,walletId:r,authority:i,foundingAuthority:a.value,foundingAuthMethod:o,...c?{registrationDiagnostics:c}:{},...l,...d,rpId:s.rpId,authMethod:s.authMethod,kind:`near_ed25519`,authorityScope:e.authorityScope,accountProvisioning:e.accountProvisioning,resolvedAccount:e.resolvedAccount,ed25519:e.ed25519}:{ok:!0,walletId:r,authority:i,foundingAuthority:a.value,foundingAuthMethod:o,...c?{registrationDiagnostics:c}:{},...l,...d,authMethod:s.authMethod,kind:`near_ed25519`,authorityScope:e.authorityScope,accountProvisioning:e.accountProvisioning,resolvedAccount:e.resolvedAccount,ed25519:e.ed25519}}case`evm_family_ecdsa`:{if(n.authorityScope!==void 0||n.accountProvisioning!==void 0||n.resolvedAccount!==void 0||n.ed25519!==void 0)throw Error(`${t} response mixed signer branches`);let e=Nt({value:n.ecdsa,walletId:r});return s.kind===`passkey`?{ok:!0,walletId:r,authority:i,foundingAuthority:a.value,foundingAuthMethod:o,...c?{registrationDiagnostics:c}:{},...l,...d,rpId:s.rpId,authMethod:s.authMethod,kind:`evm_family_ecdsa`,ecdsa:e}:{ok:!0,walletId:r,authority:i,foundingAuthority:a.value,foundingAuthMethod:o,...c?{registrationDiagnostics:c}:{},...l,...d,authMethod:s.authMethod,kind:`evm_family_ecdsa`,ecdsa:e}}default:throw Error(`${t} response has invalid kind`)}}const It=`/wallets/register/respond`,Lt=`/wallets/register/activate`,Rt=`/wallets/register/near-provisioning`,zt=`X-Seams-Environment-Id`;function Bt(e){let t=[It];e.evmFamilyEcdsa&&t.push(Lt),e.nearEd25519&&(e.evmFamilyEcdsa&&t.push(`/wallets/register/near-admission`),t.push(et,Rt,ce,le)),ee(e.relayerUrl,t)}function Vt(e){try{return new TextEncoder().encode(String(e||``)).length}catch{return String(e||``).length}}function Ht(){try{return globalThis.__SEAMS_REGISTRATION_BENCHMARK_DIAGNOSTICS===!0}catch{return!1}}function Ut(e){if(!(!e.value||typeof e.value!=`object`||Array.isArray(e.value))&&!(Object.keys(e.out).length>=64))for(let[t,n]of Object.entries(e.value)){if(Object.keys(e.out).length>=64)return;let r=e.path?`${e.path}.${t}`:t;typeof n==`string`?e.out[`${r}Bytes`]=Vt(n):Array.isArray(n)?e.out[`${r}Count`]=n.length:e.depth>0&&n&&typeof n==`object`&&Ut({value:n,out:e.out,path:r,depth:e.depth-1})}}function Wt(e){let t={};return Ut({value:e,out:t,path:``,depth:2}),t}function Gt(e){try{return JSON.parse(e)}catch{return}}function F(e,t){if(!(typeof e!=`object`||!e||Array.isArray(e)))return Reflect.get(e,t)}async function Kt(e){try{return await e.text()}catch{return`{}`}}async function I(e){let t=Date.now(),n=JSON.stringify(e.body),r=await fetch(`${te(e.relayerUrl,{trim:!1})}${e.path}`,p({headers:{...e.headers,"X-Seams-Wallet-Protocol":`3`},body:e.body,bodyJson:n}));if(e.onServerTiming)try{e.onServerTiming(r.headers.get(`Server-Timing`))}catch{}let i=await Kt(r),a=Gt(i);if(Ht()&&console.info(`[Registration] wallet route payload summary`,{path:e.path,status:r.status,requestBytes:Vt(n),requestSizeBreakdown:Wt(e.body),responseBytes:Vt(i),responseSizeBreakdown:Wt(a),totalMs:Date.now()-t}),!r.ok||F(a,`ok`)===!1)throw Error(String(F(a,`message`)||F(a,`error`)||F(a,`code`)||`HTTP ${r.status}`));return a}const qt=[`ok`,`walletId`,`nearAccountId`,`fundedAmountYocto`],Jt=[`transactionHash`,`message`],Yt=[`ok`,`code`,`message`];function Xt(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function Zt(e,t,n,r){let i=new Set([...t,...n]),a=Object.keys(e);if(a.some(e=>!i.has(e)))throw Error(`${r} contains unexpected fields`);for(let e of t)if(!a.includes(e))throw Error(`${r}.${e} is required`)}function L(e,t){return Reflect.get(e,t)}function R(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} must be a non-empty string`);return e.trim()}function Qt(e,t){if(e!==void 0){if(typeof e!=`string`)throw Error(`${t} must be a string`);return e}}function $t(e){let t=Xt(e,`fund implicit NEAR account response`),r=L(t,`ok`);if(r===!0){Zt(t,qt,Jt,`fund implicit NEAR account success response`);let e=n(L(t,`walletId`));if(!e.ok)throw Error(`fund implicit NEAR account walletId is invalid`);let r=ye(L(t,`nearAccountId`));if(!r.ok)throw Error(`fund implicit NEAR account nearAccountId is invalid`);let i=Qt(L(t,`transactionHash`),`fund implicit NEAR account transactionHash`),a=Qt(L(t,`message`),`fund implicit NEAR account message`);return{ok:!0,walletId:e.value,nearAccountId:r.value,fundedAmountYocto:R(L(t,`fundedAmountYocto`),`fund implicit NEAR account fundedAmountYocto`),...i===void 0?{}:{transactionHash:i},...a===void 0?{}:{message:a}}}if(r===!1)return Zt(t,Yt,[],`fund implicit NEAR account failure response`),{ok:!1,code:R(L(t,`code`),`fund implicit NEAR account code`),message:R(L(t,`message`),`fund implicit NEAR account message`)};throw Error(`fund implicit NEAR account response has an invalid ok discriminator`)}async function en(e){let t=String(e.walletId||``).trim(),n=String(e.nearAccountId||``).trim(),r=String(e.nearPublicKeyStr||``).trim(),i=String(e.walletSessionToken||``).trim();if(!t)throw Error(`walletId is required for implicit NEAR account funding`);if(!n)throw Error(`nearAccountId is required for implicit NEAR account funding`);if(!r)throw Error(`nearPublicKeyStr is required for implicit NEAR account funding`);if(!i)throw Error(`walletSessionToken is required for implicit NEAR account funding`);return $t(await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/near/implicit-account/fund`,headers:m({token:i,missingMessage:`walletSessionToken is required for implicit NEAR account funding`}),body:{nearAccountId:n,nearPublicKeyStr:r}}))}function tn(e){let t=String(e||``).trim();if(!t)throw Error(`Registration preparation id is required`);return t}const nn=[`formatVersion`,`walletId`,`evmFamilySigningKeySlotId`,`ecdsaThresholdKeyId`,`signingRootId`,`signingRootVersion`,`keyScope`,`relayerKeyId`,`registrationPreparationId`,`requestId`,`thresholdSessionId`,`ttlMs`,`remainingUses`,`participantIds`,`runtimePolicyScope`];function z(e){if(e.value===null||typeof e.value!=`object`||Array.isArray(e.value))throw Error(`${e.responseName} response missing ${e.field}`);return e.value}function B(e,t,n){if(!Object.keys(e).includes(t))throw Error(`${n} is missing ${t}`);return Reflect.get(e,t)}function V(e,t,n){if(Object.keys(e).includes(t))return Reflect.get(e,t)}function H(e,t,n){let r=new Set(t);for(let t of Object.keys(e))if(!r.has(t))throw Error(`${n} contains unexpected ${t}`)}function U(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e}function rn(e,t){return Object.keys(e).includes(t)}function an(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`${t} must be a non-empty canonical string`);return e}function on(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<n)throw Error(`${t} must be a safe integer`);return e}function W(e,t,n){return an(B(e,t,n),`${n}.${t}`)}function G(e,t,n){if(rn(e,t))return an(B(e,t,n),`${n}.${t}`)}function K(e,t,n,r){return on(B(e,t,n),`${n}.${t}`,r)}function sn(e,t){let n=U(e,t);if(n.length===0)throw Error(`${t} must not be empty`);let r=[];for(let e=0;e<n.length;e+=1)r.push(on(n[e],`${t}[${e}]`,1));return r}function cn(e,t){let n=sn(e,t);if(n.length!==2||n[0]!==1||n[1]!==2)throw Error(`${t} must be [1, 2]`);return[1,2]}function ln(e,t,n=!1){if(e===void 0)return;let r=`${t} runtimePolicyScope`,i=z({responseName:r,field:`value`,value:e});H(i,[`orgId`,`projectId`,`envId`,`signingRootVersion`],r);let a=G(i,`signingRootVersion`,r);if(n&&a===void 0)throw Error(`${r}.signingRootVersion is required`);let o={orgId:W(i,`orgId`,r),projectId:W(i,`projectId`,r),envId:W(i,`envId`,r)};return a===void 0?o:{...o,signingRootVersion:a}}function un(e,t){let n=ln(e,t,!0);if(!n||n.signingRootVersion===void 0)throw Error(`${t} runtimePolicyScope is invalid`);return{orgId:n.orgId,projectId:n.projectId,envId:n.envId,signingRootVersion:n.signingRootVersion}}function dn(e){let n=`Wallet registration setup intent authMethod`,r=z({responseName:n,field:`value`,value:e});switch(W(r,`kind`,n)){case`passkey`:if(H(r,[`kind`,`rpId`,`authenticatorOptions`],n),!t(W(r,`rpId`,n)).ok)throw Error(`${n}.rpId is invalid`);if(!rn(r,`authenticatorOptions`))break;if(B(r,`authenticatorOptions`,n)===void 0)throw Error(`${n}.authenticatorOptions must be defined when present`);break;case`email_otp`:switch(W(r,`proofKind`,n)){case`otp_challenge`:H(r,[`kind`,`proofKind`,`email`,`providerSubject`,`otpCode`,`challengeId`],n),G(r,`challengeId`,n),W(r,`email`,n),W(r,`providerSubject`,n),W(r,`otpCode`,n);break;case`google_sso_registration`:H(r,[`kind`,`proofKind`,`email`,`providerSubject`,`googleEmailOtpRegistrationAttemptId`,`googleEmailOtpRegistrationOfferId`,`googleEmailOtpRegistrationCandidateId`],n),W(r,`email`,n),W(r,`providerSubject`,n),W(r,`googleEmailOtpRegistrationAttemptId`,n),W(r,`googleEmailOtpRegistrationOfferId`,n),W(r,`googleEmailOtpRegistrationCandidateId`,n);break;default:throw Error(`${n}.proofKind is invalid`)}break;default:throw Error(`${n}.kind is invalid`)}let i=be(e);if(!i)throw Error(`${n} is invalid`);return i}function fn(e){let t=`Wallet registration setup intent accountProvisioning`,n=z({responseName:t,field:`value`,value:e}),r=W(n,`kind`,t);switch(r){case`implicit_account`:if(H(n,[`kind`,`accountIdSource`],t),W(n,`accountIdSource`,t)!==`ed25519_public_key`)throw Error(`${t}.accountIdSource is invalid`);return{kind:r,accountIdSource:`ed25519_public_key`};case`sponsored_named_account`:{if(H(n,[`kind`,`requestedAccountId`,`sponsor`],t),W(n,`sponsor`,t)!==`relayer`)throw Error(`${t}.sponsor is invalid`);let e=_e(W(n,`requestedAccountId`,t));if(!e.ok)throw Error(`${t}.requestedAccountId is invalid`);return{kind:r,requestedAccountId:e.value,sponsor:`relayer`}}default:throw Error(`${t}.kind is invalid`)}}function q(e,t){switch(e.kind){case`evm`:return t.kind===`evm`&&e.namespace===t.namespace&&e.chainId===t.chainId&&e.networkSlug===t.networkSlug;case`tempo`:return t.kind===`tempo`&&e.chainId===t.chainId&&e.networkSlug===t.networkSlug;default:return pn(e)}}function pn(e){throw Error(`Unsupported wallet registration setup chain target: ${String(e)}`)}function J(e,t){let n=z({responseName:t,field:`chainTarget`,value:e}),r=W(n,`kind`,t);switch(r){case`evm`:{if(H(n,[`kind`,`namespace`,`chainId`,`networkSlug`],t),W(n,`namespace`,t)!==`eip155`)throw Error(`${t}.namespace is invalid`);let e=K(n,`chainId`,t,1),i=G(n,`networkSlug`,t);return i===void 0?{kind:r,namespace:`eip155`,chainId:e}:{kind:r,namespace:`eip155`,chainId:e,networkSlug:i}}case`tempo`:{H(n,[`kind`,`chainId`,`networkSlug`],t);let e=K(n,`chainId`,t,1),i=G(n,`networkSlug`,t);return i===void 0?{kind:r,chainId:e}:{kind:r,chainId:e,networkSlug:i}}default:throw Error(`${t}.kind is invalid`)}}function mn(e){try{return J(e,`Wallet registration setup intent`)}catch{return null}}function hn(e){let t=`Wallet registration setup intent signer`,n=z({responseName:t,field:`value`,value:e}),r=W(n,`kind`,t);switch(r){case`near_ed25519`:if(H(n,[`kind`,`accountProvisioning`,`signerSlot`,`participantIds`,`derivationVersion`],t),K(n,`derivationVersion`,t,1)!==1)throw Error(`${t}.derivationVersion is invalid`);return{kind:r,accountProvisioning:fn(B(n,`accountProvisioning`,t)),signerSlot:K(n,`signerSlot`,t,1),participantIds:sn(B(n,`participantIds`,t),`${t}.participantIds`),derivationVersion:1};case`evm_family_ecdsa`:{H(n,[`kind`,`participantIds`,`chainTargets`],t);let e=U(B(n,`chainTargets`,t),`${t}.chainTargets`);if(e.length===0)throw Error(`${t}.chainTargets must not be empty`);let i=[];for(let n of e){let e=J(n,`${t}.chainTargets`);if(i.some(t=>q(t,e)))throw Error(`${t}.chainTargets contains a duplicate target`);i.push(e)}return{kind:r,participantIds:sn(B(n,`participantIds`,t),`${t}.participantIds`),chainTargets:i}}default:throw Error(`${t}.kind is invalid`)}}function gn(e){let t=`Wallet registration setup intent signerSelection`,n=z({responseName:t,field:`value`,value:e});if(H(n,[`kind`,`signers`],t),W(n,`kind`,t)!==`signer_set`)throw Error(`${t}.kind is invalid`);let r=U(B(n,`signers`,t),`${t}.signers`);if(r.length===0)throw Error(`${t}.signers must not be empty`);let i=[];for(let e of r)i.push(hn(e));return{kind:`signer_set`,signers:i}}function _n(e){let t=`Wallet registration setup intent`,r=z({responseName:t,field:`intent`,value:e});if(H(r,[`version`,`walletId`,`authMethod`,`signerSelection`,`foundingWalletAuthMethodId`,`runtimePolicyScope`,`nonceB64u`],t),W(r,`version`,t)!==`registration_intent_v1`)throw Error(`${t}.version is invalid`);let a=n(W(r,`walletId`,t));if(!a.ok)throw Error(`${t}.walletId is invalid`);let o=i(W(r,`foundingWalletAuthMethodId`,t));if(!o.ok)throw Error(`${t}.foundingWalletAuthMethodId is invalid`);let s=dn(B(r,`authMethod`,t)),c=gn(B(r,`signerSelection`,t)),l=ln(V(r,`runtimePolicyScope`,t),t),u=W(r,`nonceB64u`,t);return l===void 0?{version:`registration_intent_v1`,walletId:a.value,authMethod:s,signerSelection:c,foundingWalletAuthMethodId:o.value,nonceB64u:u}:{version:`registration_intent_v1`,walletId:a.value,authMethod:s,signerSelection:c,foundingWalletAuthMethodId:o.value,runtimePolicyScope:l,nonceB64u:u}}function vn(e){let t=`Wallet add-signer ECDSA derivation`,n=z({responseName:t,field:`response`,value:e});if(H(n,[`ok`,`addSignerCeremonyId`,`ecdsa`],`${t} response`),B(n,`ok`,`${t} response`)!==!0)throw Error(`${t} response is not successful`);let r=z({responseName:t,field:`ecdsa`,value:B(n,`ecdsa`,`${t} response`)});if(H(r,[`kind`,`strictResult`],`${t} response ecdsa`),B(r,`kind`,`${t} response ecdsa`)!==`router_ab_ecdsa_registration_forwarded_v1`)throw Error(`${t} response kind is invalid`);return{ok:!0,addSignerCeremonyId:k({responseName:t,field:`addSignerCeremonyId`,value:B(n,`addSignerCeremonyId`,t)}),ecdsa:{kind:`router_ab_ecdsa_registration_forwarded_v1`,strictResult:qe(B(r,`strictResult`,`${t} response ecdsa`))}}}function yn(e){let t=`Wallet add-signer ECDSA activation`,n=z({responseName:t,field:`response`,value:e});if(H(n,[`ok`,`addSignerCeremonyId`,`ecdsa`],`${t} response`),B(n,`ok`,`${t} response`)!==!0)throw Error(`${t} response is not successful`);let r=z({responseName:t,field:`ecdsa`,value:B(n,`ecdsa`,`${t} response`)});if(H(r,[`kind`,`activation`,`bootstrap`],`${t} response ecdsa`),B(r,`kind`,`${t} response ecdsa`)!==`router_ab_ecdsa_registration_activated_v1`)throw Error(`${t} response kind is invalid`);return{ok:!0,addSignerCeremonyId:k({responseName:t,field:`addSignerCeremonyId`,value:B(n,`addSignerCeremonyId`,t)}),ecdsa:{kind:`router_ab_ecdsa_registration_activated_v1`,activation:Ye(B(r,`activation`,`${t} response ecdsa`)),bootstrap:at(B(r,`bootstrap`,`${t} response ecdsa`))}}}function bn(e){return e.authMethod.kind===`email_otp`}function xn(e){let t=`Wallet add-auth-method intent`,n=z({responseName:t,field:`body`,value:e});if(H(n,[`ok`,`intent`,`addAuthMethodIntentDigestB64u`,`addAuthMethodIntentGrant`,`expiresAtMs`],t),B(n,`ok`,t)!==!0)throw Error(`${t} response is not successful`);let r=ke(B(n,`intent`,t)),i;try{i=ge(B(n,`addAuthMethodIntentDigestB64u`,t))}catch{throw Error(`${t} response has invalid addAuthMethodIntentDigestB64u`)}let a=B(n,`addAuthMethodIntentGrant`,t);if(typeof a!=`string`||!a.trim())throw Error(`${t} response is missing addAuthMethodIntentGrant`);return{ok:!0,intent:r,addAuthMethodIntentDigestB64u:i,addAuthMethodIntentGrant:Ie(a),expiresAtMs:M({responseName:t,field:`expiresAtMs`,value:B(n,`expiresAtMs`,t),minimum:1})}}function Sn(e){let t=`Wallet add-signer intent`,n=z({responseName:t,field:`body`,value:e});if(H(n,[`ok`,`intent`,`addSignerIntentDigestB64u`,`addSignerIntentGrant`,`expiresAtMs`],t),B(n,`ok`,t)!==!0)throw Error(`${t} response is not successful`);let r=Pe(B(n,`intent`,t)),i;try{i=ge(B(n,`addSignerIntentDigestB64u`,t))}catch{throw Error(`${t} response has invalid addSignerIntentDigestB64u`)}let a=B(n,`addSignerIntentGrant`,t);if(typeof a!=`string`||!a.trim())throw Error(`${t} response is missing addSignerIntentGrant`);return{ok:!0,intent:r,addSignerIntentDigestB64u:i,addSignerIntentGrant:Ne(a),expiresAtMs:M({responseName:t,field:`expiresAtMs`,value:B(n,`expiresAtMs`,t),minimum:1})}}function Cn(e){let r=`Wallet add-auth-method finalize`,i=z({responseName:r,field:`body`,value:e});if(B(i,`ok`,r)!==!0)throw Error(`${r} response is not successful`);let a=z({responseName:r,field:`authMethod`,value:B(i,`authMethod`,r)}),o=B(a,`kind`,`${r} authMethod`);if(o!==`passkey`&&o!==`email_otp`)throw Error(`${r} response has invalid authMethod kind`);let c=n(B(i,`walletId`,r));if(!c.ok)throw Error(`${r} response has invalid walletId`);let l=Be(B(i,`authority`,r));if(!l)throw Error(`${r} response has invalid authority`);if(l.walletId!==c.value)throw Error(`${r} response authority wallet mismatch`);if(o===`passkey`){if(H(i,[`ok`,`walletId`,`authority`,`rpId`,`authMethod`],r),H(a,[`kind`,`status`,`credentialIdB64u`,`credentialPublicKeyB64u`,`counter`,`device`],`${r} authMethod`),B(a,`status`,r)!==`active`)throw Error(`${r} response has invalid authMethod status`);if(l.factor.kind!==`passkey`||l.verifier.kind!==`webauthn`)throw Error(`${r} response has inconsistent passkey authority`);let e=t(B(i,`rpId`,r));if(!e.ok)throw Error(`${r} response has invalid rpId`);let n=s(B(a,`credentialIdB64u`,r));if(!n.ok)throw Error(`${r} response has invalid credentialIdB64u`);let o=B(a,`credentialPublicKeyB64u`,r);if(typeof o!=`string`||!o.trim())throw Error(`${r} response is missing credentialPublicKeyB64u`);let u=B(a,`counter`,r);if(typeof u!=`number`||!Number.isSafeInteger(u)||u<0)throw Error(`${r} response has invalid counter`);let d=Oe(B(a,`device`,r));if(!d)throw Error(`${r} response has invalid device`);if(l.factor.credentialIdB64u!==n.value||l.verifier.rpId!==e.value)throw Error(`${r} response passkey authority binding mismatch`);return{ok:!0,walletId:c.value,authority:l,rpId:e.value,authMethod:{kind:`passkey`,status:`active`,credentialIdB64u:n.value,credentialPublicKeyB64u:o.trim(),counter:u,device:d}}}if(H(i,[`ok`,`walletId`,`authority`,`authMethod`],r),H(a,[`kind`,`status`],`${r} authMethod`),B(a,`status`,r)!==`active`)throw Error(`${r} response has invalid authMethod status`);if(l.factor.kind!==`email_otp`||l.verifier.kind!==`email_otp_wallet_auth_method`)throw Error(`${r} response has inconsistent email OTP authority`);return{ok:!0,walletId:c.value,authority:l,authMethod:{kind:`email_otp`,status:`active`}}}function wn(e){let t=`Wallet add-auth-method start`,n=z({responseName:t,field:`body`,value:e.value});if(B(n,`ok`,t)!==!0)throw Error(`${t} response is not successful`);let r=k({responseName:t,field:`addAuthMethodCeremonyId`,value:B(n,`addAuthMethodCeremonyId`,t)}),i=En(B(n,`intent`,t),e.expectedIntent);return e.expectedIntent.authMethod.kind===`email_otp`?(H(n,[`ok`,`addAuthMethodCeremonyId`,`intent`,`custodyEnvelope`,`addAuthMethodCeremonyExpiresAtMs`],t),{ok:!0,addAuthMethodCeremonyId:r,intent:i,custodyEnvelope:S(B(n,`custodyEnvelope`,t)),addAuthMethodCeremonyExpiresAtMs:M({responseName:t,field:`addAuthMethodCeremonyExpiresAtMs`,value:B(n,`addAuthMethodCeremonyExpiresAtMs`,t),minimum:1})}):(H(n,[`ok`,`addAuthMethodCeremonyId`,`intent`,`custodyEnvelope`,`registration`,`addAuthMethodCeremonyExpiresAtMs`],t),{ok:!0,addAuthMethodCeremonyId:r,intent:i,custodyEnvelope:S(B(n,`custodyEnvelope`,t)),registration:Me(B(n,`registration`,t)),addAuthMethodCeremonyExpiresAtMs:M({responseName:t,field:`addAuthMethodCeremonyExpiresAtMs`,value:B(n,`addAuthMethodCeremonyExpiresAtMs`,t),minimum:1})})}function Tn(e,t){try{if(!Ae(Pe(e),t))throw Error(`intent mismatch`)}catch{throw Error(`Wallet add-signer start response changed the admitted intent`)}return t}function En(e,t){try{if(!Fe(ke(e),t))throw Error(`intent mismatch`)}catch{throw Error(`Wallet add-auth-method start response changed the admitted intent`)}return t}function Dn(e,t){let n=z({responseName:t,field:`ecdsa.prepare`,value:e});if(H(n,nn,t),B(n,`formatVersion`,t)!==`ecdsa-derivation-role-local`||B(n,`keyScope`,t)!==`evm-family`)throw Error(`${t} response has invalid prepare discriminator`);let r=ae(B(n,`runtimePolicyScope`,t));if(!r)throw Error(`${t} response has invalid runtimePolicyScope`);return{formatVersion:`ecdsa-derivation-role-local`,walletId:k({responseName:t,field:`prepare.walletId`,value:B(n,`walletId`,t)}),evmFamilySigningKeySlotId:k({responseName:t,field:`prepare.evmFamilySigningKeySlotId`,value:B(n,`evmFamilySigningKeySlotId`,t)}),ecdsaThresholdKeyId:k({responseName:t,field:`prepare.ecdsaThresholdKeyId`,value:B(n,`ecdsaThresholdKeyId`,t)}),signingRootId:k({responseName:t,field:`prepare.signingRootId`,value:B(n,`signingRootId`,t)}),signingRootVersion:k({responseName:t,field:`prepare.signingRootVersion`,value:B(n,`signingRootVersion`,t)}),keyScope:`evm-family`,relayerKeyId:k({responseName:t,field:`prepare.relayerKeyId`,value:B(n,`relayerKeyId`,t)}),registrationPreparationId:tn(k({responseName:t,field:`prepare.registrationPreparationId`,value:B(n,`registrationPreparationId`,t)})),requestId:k({responseName:t,field:`prepare.requestId`,value:B(n,`requestId`,t)}),thresholdSessionId:k({responseName:t,field:`prepare.thresholdSessionId`,value:B(n,`thresholdSessionId`,t)}),ttlMs:M({responseName:t,field:`prepare.ttlMs`,value:B(n,`ttlMs`,t),minimum:1}),remainingUses:M({responseName:t,field:`prepare.remainingUses`,value:B(n,`remainingUses`,t),minimum:0}),participantIds:[...N(B(n,`participantIds`,t),t)],runtimePolicyScope:r}}function On(e,t){let n=z({responseName:t,field:`ecdsa.prepare`,value:e});if(H(n,nn,t),B(n,`formatVersion`,t)!==`ecdsa-derivation-role-local`||B(n,`keyScope`,t)!==`evm-family`)throw Error(`${t} response has invalid prepare discriminator`);for(let e of[`walletId`,`evmFamilySigningKeySlotId`,`ecdsaThresholdKeyId`,`signingRootId`,`signingRootVersion`,`relayerKeyId`,`registrationPreparationId`,`requestId`,`thresholdSessionId`])W(n,e,t);K(n,`ttlMs`,t,1),K(n,`remainingUses`,t,0),cn(B(n,`participantIds`,t),`${t}.participantIds`),un(B(n,`runtimePolicyScope`,t),t)}function kn(e){let t=`Wallet registration setup ECDSA`,n=z({responseName:t,field:`ecdsa`,value:e});if(H(n,[`kind`,`chainTargets`,`prepare`,`strictRegistration`],t),B(n,`kind`,t)!==`evm_family_ecdsa_keygen`)throw Error(`${t} response has an invalid kind`);let r=B(n,`chainTargets`,t);if(!Array.isArray(r)||r.length===0)throw Error(`${t} response has invalid chainTargets`);let i=[];for(let e of r){let n=J(e,`${t}.chainTargets`);if(i.some(e=>q(e,n)))throw Error(`${t} response has duplicate chainTargets`);i.push(n)}let[a,...o]=i;if(!a)throw Error(`${t} response has invalid chainTargets`);let s=B(n,`prepare`,t);On(s,t);let c=Dn(s,t),l=Qe(B(n,`strictRegistration`,t));if(l.registration_purpose!==`wallet_registration`)throw Error(`${t} response has an invalid registration purpose`);return{kind:`evm_family_ecdsa_keygen`,chainTargets:[a,...o],prepare:c,strictRegistration:l}}function An(e){let t=!1,n=!1;for(let r of e.signerSelection.signers)switch(r.kind){case`near_ed25519`:t=!0;break;case`evm_family_ecdsa`:n=!0;break;default:return jn(r)}if(t&&n)return`near_ed25519_and_evm_family_ecdsa`;if(n)return`evm_family_ecdsa`;if(t)return`near_ed25519`;throw Error(`Wallet registration setup intent has no signer branch`)}function jn(e){throw Error(`Unsupported wallet registration setup signer: ${String(e)}`)}function Mn(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Nn(e,t){return e!==void 0&&e.orgId===t.orgId&&e.projectId===t.projectId&&e.envId===t.envId&&e.signingRootVersion===t.signingRootVersion}function Pn(e,t){try{return q(J(e,`Wallet registration setup intent`),t)}catch{return!1}}function Fn(e){let t=e.intent.signerSelection.signers.find(e=>e.kind===`evm_family_ecdsa`);if(!t)throw Error(`${e.responseName} response has no ECDSA intent branch`);if(t.chainTargets.length!==e.ecdsa.chainTargets.length||t.chainTargets.some((t,n)=>!Pn(t,e.ecdsa.chainTargets[n])))throw Error(`${e.responseName} response ECDSA chainTargets do not match intent`);if(!Mn(t.participantIds,e.ecdsa.prepare.participantIds))throw Error(`${e.responseName} response ECDSA participantIds do not match intent`);if(e.ecdsa.prepare.walletId!==String(e.walletId))throw Error(`${e.responseName} response ECDSA prepare walletId does not match response`);if(!Nn(e.intent.runtimePolicyScope,e.ecdsa.prepare.runtimePolicyScope))throw Error(`${e.responseName} response ECDSA runtimePolicyScope does not match intent`);let n=e.ecdsa.strictRegistration.lifecycle;if(n.lifecycle_id!==e.registrationCeremonyId||n.account_id!==String(e.walletId)||e.ecdsa.strictRegistration.client_id!==String(e.walletId))throw Error(`${e.responseName} response ECDSA identities do not match response`)}function In(e){let t=`Wallet registration setup`,r=z({responseName:t,field:`body`,value:e});if(B(r,`ok`,t)!==!0)throw Error(`${t} response is not successful`);let a=B(r,`kind`,t);if(a!==`near_ed25519`&&a!==`evm_family_ecdsa`&&a!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`${t} response kind is invalid`);let o=a!==`near_ed25519`;H(r,[`ok`,`registrationCeremonyId`,`walletId`,`walletAuthMethodId`,`registrationIntentDigestB64u`,`intent`,`signedSetup`,`home`,`kind`,...o?[`ecdsa`]:[]],t);let s=W(r,`registrationCeremonyId`,t),c=n(W(r,`walletId`,t));if(!c.ok)throw Error(`${t} response has an invalid walletId`);let l=i(W(r,`walletAuthMethodId`,t));if(!l.ok)throw Error(`${t} response has an invalid walletAuthMethodId`);let u=_n(B(r,`intent`,t));if(u.walletId!==c.value)throw Error(`${t} response walletId does not match intent`);if(u.foundingWalletAuthMethodId!==l.value)throw Error(`${t} response walletAuthMethodId does not match intent`);let d;try{d=ge(B(r,`registrationIntentDigestB64u`,t))}catch{throw Error(`${t} response has an invalid registrationIntentDigestB64u`)}let f=fe(B(r,`home`,t)),p=B(r,`signedSetup`,t);if(typeof p!=`string`||!p.trim())throw Error(`${t} response missing signedSetup`);if(!o){if(An(u)!==a)throw Error(`${t} response kind does not match intent`);return{ok:!0,registrationCeremonyId:s,walletId:c.value,walletAuthMethodId:l.value,registrationIntentDigestB64u:d,intent:u,signedSetup:p,home:f,kind:`near_ed25519`}}let m=kn(B(r,`ecdsa`,t));if(An(u)!==a)throw Error(`${t} response kind does not match intent`);return Fn({responseName:t,registrationCeremonyId:s,walletId:c.value,intent:u,ecdsa:m}),{ok:!0,registrationCeremonyId:s,walletId:c.value,walletAuthMethodId:l.value,registrationIntentDigestB64u:d,intent:u,signedSetup:p,home:f,kind:a,ecdsa:m}}function Ln(e){let t=be(e.authMethod);if(!t)throw Error(`Wallet registration setup request authMethod is invalid`);let n=xe(e.signerSelection);if(!n.ok)throw Error(`Wallet registration setup request signerSelection is invalid: ${n.message}`);let r=Se(n.value,{normalizeEcdsaChainTarget:mn});if(!r.ok)throw Error(`Wallet registration setup request signerSelection is invalid: ${r.message}`);return{wallet:e.wallet??{kind:`server_allocated`},authMethod:t,signerSelection:r.value}}function Rn(e,t){let n={version:`registration_intent_v1`,walletId:e.walletId,authMethod:t.authMethod,signerSelection:t.signerSelection,foundingWalletAuthMethodId:e.foundingWalletAuthMethodId,nonceB64u:e.nonceB64u};return e.runtimePolicyScope===void 0?n:{...n,runtimePolicyScope:e.runtimePolicyScope}}async function zn(e){if(e.requestedWallet?.kind===`provided`&&String(e.requestedWallet.walletId)!==e.response.walletId)throw Error(`Wallet registration setup response walletId does not match request`);if(await je(e.response.intent)!==e.response.registrationIntentDigestB64u)throw Error(`Wallet registration setup response digest does not match intent`);if(await je(Rn(e.response.intent,e.request))!==e.response.registrationIntentDigestB64u)throw Error(`Wallet registration setup response intent does not match request`)}function Bn(e,t){let n=`Wallet add-signer ECDSA start`,r=z({responseName:n,field:`ecdsa`,value:e});H(r,[`kind`,`chainTargets`,`prepare`,`strictRegistration`,`custodyEnvelope`],n);let i=B(r,`kind`,n),a=B(r,`chainTargets`,n);if(i!==`evm_family_ecdsa_keygen`||!Array.isArray(a))throw Error(`${n} response has invalid payload`);if(t.signerSelection.mode!==`ecdsa`)throw Error(`${n} response substituted signer branch`);let o=t.signerSelection.ecdsa.chainTargets;if(a.length!==o.length)throw Error(`${n} response changed target count`);let s=[];for(let e=0;e<a.length;e+=1){let t=a[e],r=Tt(t,n),i=o[e];if(!i||!Te(r,Tt(i,n)))throw Error(`${n} response changed chainTarget`);s.push(r)}let[c,...l]=s;if(!c)throw Error(`${n} response requires an EVM-family target`);let u=Dn(B(r,`prepare`,n),n),d=Qe(B(r,`strictRegistration`,n));if(d.registration_purpose!==`wallet_add_signer`)throw Error(`${n} response has invalid registration purpose`);return{kind:`evm_family_ecdsa_keygen`,chainTargets:[c,...l],prepare:u,strictRegistration:d}}function Vn(e){let t=`Wallet add-signer start`,n=z({responseName:t,field:`body`,value:e.value});if(H(n,[`ok`,`addSignerCeremonyId`,`intent`,`authorizationKind`,`kind`,`ed25519`,`ecdsa`],t),B(n,`ok`,t)!==!0)throw Error(`${t} response is not successful`);let r=k({responseName:t,field:`addSignerCeremonyId`,value:B(n,`addSignerCeremonyId`,t)}),i=Tn(B(n,`intent`,t),e.expectedIntent),a=B(n,`authorizationKind`,t);if(a!==`webauthn_assertion`)throw Error(`${t} response has invalid authorization kind`);switch(B(n,`kind`,t)){case`near_ed25519`:{if(a!==`webauthn_assertion`||i.signerSelection.mode!==`ed25519`||V(n,`ecdsa`,t)!==void 0)throw Error(`${t} response substituted signer branch`);let e=z({responseName:t,field:`ed25519`,value:B(n,`ed25519`,t)});H(e,[`admissionRequest`,`custodyEnvelope`],t);let o=b(B(e,`admissionRequest`,t));if(!o.ok)throw Error(o.message);return{ok:!0,addSignerCeremonyId:r,intent:i,authorizationKind:`webauthn_assertion`,kind:`near_ed25519`,ed25519:{admissionRequest:o.value,custodyEnvelope:S(B(e,`custodyEnvelope`,t))}}}case`evm_family_ecdsa`:{if(i.signerSelection.mode!==`ecdsa`||V(n,`ed25519`,t)!==void 0)throw Error(`${t} response substituted signer branch`);let e=B(n,`ecdsa`,t),a=Bn(e,i),o=z({responseName:t,field:`ecdsa`,value:e});return{ok:!0,addSignerCeremonyId:r,intent:i,authorizationKind:`webauthn_assertion`,kind:`evm_family_ecdsa`,ecdsa:{...a,custodyEnvelope:S(B(o,`custodyEnvelope`,t))}}}default:throw Error(`${t} response has invalid kind`)}}function Hn(e){let t=`Wallet add-signer finalize`,n=z({responseName:t,field:`body`,value:e.value});H(n,[`ok`,`walletId`,`kind`,`rpId`,`credentialIdB64u`,`ed25519`,`ecdsa`,`authority`],t);let r=B(n,`ok`,t),i=B(n,`kind`,t);if(r!==!0||i!==e.expectedKind)throw Error(`${t} response substituted signer branch`);let a=rt(k({responseName:t,field:`walletId`,value:B(n,`walletId`,t)})),o=P(B(n,`rpId`,t),t);switch(i){case`near_ed25519`:{if(V(n,`ecdsa`,t)!==void 0||V(n,`authority`,t)!==void 0)throw Error(`${t} response mixed signer branches`);let e=Ct(B(n,`ed25519`,t),`Wallet add-signer Ed25519 finalize`);return{ok:!0,walletId:a,kind:`near_ed25519`,rpId:o,credentialIdB64u:k({responseName:t,field:`credentialIdB64u`,value:B(n,`credentialIdB64u`,t)}),ed25519:e}}case`evm_family_ecdsa`:{if(V(n,`ed25519`,t)!==void 0||V(n,`credentialIdB64u`,t)!==void 0)throw Error(`${t} response mixed signer branches`);let e=z({responseName:t,field:`ecdsa`,value:B(n,`ecdsa`,t)});H(e,[`walletKeys`],t);let r=U(B(e,`walletKeys`,t),`${t} walletKeys`);if(r.length===0)throw Error(`${t} response has invalid walletKeys`);let i=ze(B(n,`authority`,t));if(!i.ok||i.value.state!==`active`||i.value.walletId!==a)throw Error(`${t} response has invalid authority`);return{ok:!0,walletId:a,kind:`evm_family_ecdsa`,rpId:o,ecdsa:{walletKeys:r.map(Un)},authority:i.value}}default:throw Error(`${t} response has invalid kind`)}}function Un(e){return Et(e,`Wallet add-signer ECDSA finalize`)}function Y(e){let t=String(e.expected||``).trim(),n=String(e.actual||``).trim();if(!t||!n)throw Error(`ECDSA registration bootstrap returned incomplete ${e.field}`);if(t!==n)throw Error(`ECDSA registration bootstrap ${e.field} mismatch`);return n}function Wn(e){let t=e.expected.map(e=>Math.floor(Number(e))),n=e.actual.map(e=>Math.floor(Number(e)));if(t.length===0||n.length===0||t.some(e=>!Number.isSafeInteger(e)||e<=0)||n.some(e=>!Number.isSafeInteger(e)||e<=0))throw Error(`ECDSA registration bootstrap returned incomplete participantIds`);if(t.length!==n.length||t.some((e,t)=>e!==n[t]))throw Error(`ECDSA registration bootstrap participantIds mismatch`);return n}function Gn(e){let t=e.clientBootstrap,n=e.serverBootstrap;Y({field:`derivationClientSharePublicKey33B64u`,expected:t.derivationClientSharePublicKey33B64u,actual:n.publicIdentity.derivationClientSharePublicKey33B64u});let r=Y({field:`contextBinding32B64u`,expected:t.contextBinding32B64u,actual:n.contextBinding32B64u}),i=Y({field:`walletId`,expected:t.walletId,actual:n.walletId}),a=Y({field:`evmFamilySigningKeySlotId`,expected:t.evmFamilySigningKeySlotId,actual:n.evmFamilySigningKeySlotId});Y({field:`activationEpoch`,expected:e.activationEpoch,actual:n.activationEpoch});let o=Wn({expected:t.participantIds,actual:n.participantIds}),s=Xe(n.routerAbEcdsaDerivationNormalSigning),c=String(n.ecdsaThresholdKeyId||``).trim(),l=String(n.keyHandle||``).trim(),u=String(n.signingRootId||``).trim(),d=String(n.signingRootVersion||``).trim(),f=String(n.applicationBindingDigestB64u||``).trim(),p=String(n.thresholdEcdsaPublicKeyB64u||``).trim(),m=String(n.ethereumAddress||``).trim(),ee=String(n.relayerKeyId||``).trim(),te=String(n.relayerVerifyingShareB64u||``).trim(),h=Math.floor(Number(n.relayerShareRetryCounter));if(!i||!a||!l||!c||!u||!d||!f||!p||!m||!ee||!te||!Number.isSafeInteger(h)||h<0||!o.length||o.some(e=>!Number.isSafeInteger(e)||e<=0))throw Error(`ECDSA registration bootstrap returned incomplete session material`);return{walletId:i,evmFamilySigningKeySlotId:a,ecdsaThresholdKeyId:c,relayerKeyId:ee,applicationBindingDigestB64u:f,contextBinding32B64u:r,publicIdentity:n.publicIdentity,relayerShareRetryCounter:h,keyHandle:l,signingRootId:u,signingRootVersion:d,thresholdEcdsaPublicKeyB64u:p,ethereumAddress:m,relayerVerifyingShareB64u:te,participantIds:o,routerAbEcdsaDerivationNormalSigning:s}}function Kn(e){let t=`Wallet ECDSA key-facts inventory`,n=z({responseName:t,field:`body`,value:e.value});if(H(n,[`ok`,`ecdsaKeyIdentityTargets`,`diagnostics`],t),B(n,`ok`,t)!==!0)throw Error(`${t} response is not successful`);let r=U(B(n,`ecdsaKeyIdentityTargets`,t),`${t} ecdsaKeyIdentityTargets`);return{ok:!0,records:xt({walletId:e.walletId,rpId:e.rpId,records:r}),diagnostics:B(n,`diagnostics`,t)}}async function qn(e){let t=String(e.auth?.publishableKey||``).trim(),n=String(e.auth?.environmentId||``).trim();if(!t||!n)return{ok:!1,code:`invalid_body`,message:`registration setup requires a publishable key and environment id`};let r=Ln(e.request),i=await Re({relayerUrl:e.relayerUrl,publishableKey:t,environmentId:n}),a=await Le.begin(i,r),o=In(await I({relayerUrl:e.relayerUrl,path:re,headers:{...e.headers,Authorization:`Bearer ${t}`,[zt]:n},body:{registrationOperationId:a.operationId,wallet:r.wallet,signerSelection:r.signerSelection,authMethod:r.authMethod},...e.onServerTiming?{onServerTiming:e.onServerTiming}:{}}));return o.ok?(await zn({response:o,...e.request.wallet?{requestedWallet:e.request.wallet}:{},request:r}),await Le.accept(a,o),o):o}async function Jn(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`walletId is required for add-signer intent`);let n=String(e.auth.publishableKey||``).trim(),r=String(e.auth.environmentId||``).trim();if(!n||!r)throw Error(`add-signer intent requires a publishable key and environment id`);return Sn(await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/signers/intent`,headers:{Authorization:`Bearer ${n}`,[zt]:r},body:e.request}))}function Yn(e){let t=`Wallet auth-method revoke`,r=z({responseName:t,field:`body`,value:e});if(B(r,`ok`,t)!==!0)throw Error(`${t} response is not successful`);let i=n(B(r,`walletId`,t));if(!i.ok)throw Error(`${t} response has invalid walletId`);let a=z({responseName:t,field:`authMethod`,value:B(r,`authMethod`,t)});if(H(a,[`kind`,`status`],`${t} response authMethod`),B(a,`status`,t)!==`revoked`)throw Error(`${t} response has invalid authMethod status`);switch(B(a,`kind`,t)){case`passkey`:return H(r,[`ok`,`walletId`,`authMethod`,`rpId`],t),{ok:!0,walletId:i.value,authMethod:{kind:`passkey`,status:`revoked`},rpId:P(B(r,`rpId`,t),t)};case`email_otp`:return H(r,[`ok`,`walletId`,`authMethod`],t),{ok:!0,walletId:i.value,authMethod:{kind:`email_otp`,status:`revoked`}};default:throw Error(`${t} response has invalid authMethod kind`)}}async function Xn(e){let t=String(e.walletId||``).trim(),n=String(e.walletAuthMethodId||``).trim();if(!t||!n)throw Error(`auth-method revoke requires a wallet and a target method`);let r={relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/auth-methods/${encodeURIComponent(n)}/revoke`,body:{walletId:t,walletAuthMethodId:n,requestedAtMs:e.requestedAtMs,sourceProof:e.sourceProof}},i;try{i=await I(r)}catch(e){if(!(e instanceof TypeError))throw e;i=await I(r)}return Yn(i)}async function Zn(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`walletId is required for add-auth-method intent`);let n=String(e.auth.publishableKey||``).trim(),r=String(e.auth.environmentId||``).trim();if(!n||!r)throw Error(`add-auth-method intent requires a publishable key and environment id`);let i=e.request.caller.caller===`same_device_addition`?{caller:`same_device_addition`,source:e.request.caller.source}:{caller:`linked_device_ceremony`};return xn(await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/auth-methods/intent`,headers:{Authorization:`Bearer ${n}`,[zt]:r},body:{walletId:e.request.walletId,rpId:e.request.rpId,authMethod:e.request.authMethod,...i}}))}function Qn(e){let t=`Wallet registration respond`,n=z({responseName:t,field:`body`,value:e});if(B(n,`ok`,t)!==!0)throw Error(`${t} response is not successful`);let r=k({responseName:t,field:`registrationCeremonyId`,value:B(n,`registrationCeremonyId`,t)}),i=B(n,`kind`,t);if(i!==`evm_family_ecdsa`&&i!==`near_ed25519_and_evm_family_ecdsa`&&i!==`near_ed25519`)throw Error(`${t} response kind is invalid`);let a=i!==`near_ed25519`,o=i!==`evm_family_ecdsa`;H(n,[`ok`,`registrationCeremonyId`,`kind`,...a?[`ecdsa`]:[],...o?[`ed25519`]:[]],t);let s=V(n,`ed25519`,t);if(o&&s===void 0)throw Error(`${t} signer plan is missing its ed25519 deferred work`);if(!a)return{ok:!0,registrationCeremonyId:r,kind:`near_ed25519`,ed25519:$n(s)};let c=z({responseName:t,field:`ecdsa`,value:B(n,`ecdsa`,t)});if(H(c,[`kind`,`strictResult`],`${t} ecdsa`),B(c,`kind`,`${t} ecdsa`)!==`router_ab_ecdsa_registration_forwarded_v1`)throw Error(`${t} ecdsa kind is invalid`);let l=o?er(s):null,u={kind:`router_ab_ecdsa_registration_forwarded_v1`,strictResult:qe(B(c,`strictResult`,`${t} ecdsa`))};return l?{ok:!0,registrationCeremonyId:r,kind:`near_ed25519_and_evm_family_ecdsa`,ecdsa:u,ed25519:l}:{ok:!0,registrationCeremonyId:r,kind:`evm_family_ecdsa`,ecdsa:u}}function $n(e){let t=`Wallet registration respond ed25519 admission`,n=z({responseName:t,field:`ed25519`,value:e});if(H(n,[`status`,`admissionRequest`,`admissionReceipt`],t),B(n,`status`,t)!==`admitted`)throw Error(`${t} status is invalid`);let r=b(B(n,`admissionRequest`,t)),i=tt(B(n,`admissionReceipt`,t));if(!r.ok||!i.ok)throw Error(`${t} request or receipt is invalid`);return{status:`admitted`,admissionRequest:r.value,admissionReceipt:i.value}}function er(e){let t=`Wallet registration respond ed25519`,n=z({responseName:t,field:`ed25519`,value:e});if(H(n,[`status`,`admissionRequest`],t),B(n,`status`,t)!==`deferred`)throw Error(`${t} status is invalid`);let r=b(B(n,`admissionRequest`,t));if(!r.ok)throw Error(`${t} admissionRequest is invalid`);return{status:`deferred`,admissionRequest:r.value}}function tr(e){let t={registrationCeremonyId:e.registrationCeremonyId,signedSetup:e.signedSetup,kind:e.signerPlanKind};switch(e.kind){case`passkey`:t.webauthn_registration=e.webauthnRegistration;break;case`email_otp`:t.emailOtpRegistrationProof=e.emailOtpRegistrationProof;break}return t.ecdsa=e.ecdsa,t}async function nr(e){return Qn(await I({relayerUrl:e.relayerUrl,path:It,headers:e.headers,body:tr(e),onServerTiming:e.onServerTiming}))}function rr(e,t){let n=ot(e);if(n===null||n.session.walletId!==t)throw Error(`Wallet registration established session direct session result is invalid`);return n}function ir(e,t){let n=`Wallet registration activate`,r=V(e,`registrationDiagnostics`,n),i=V(e,`rpId`,n),a=V(e,`walletCustody`,n),o=V(e,`custodyKeyManifestDigestB64u`,n);return{ok:B(e,`ok`,n),walletId:B(e,`walletId`,n),authority:B(e,`authority`,n),foundingAuthority:B(e,`foundingAuthority`,n),foundingAuthMethod:B(e,`foundingAuthMethod`,n),...r===void 0?{}:{registrationDiagnostics:r},...i===void 0?{}:{rpId:i},authMethod:B(e,`authMethod`,n),...a===void 0?{}:{walletCustody:a},...o===void 0?{}:{custodyKeyManifestDigestB64u:o},kind:`evm_family_ecdsa`,ecdsa:{walletKeys:B(t,`walletKeys`,n)}}}function ar(e){let t=`Wallet registration NEAR provisioning`,n=V(e,`registrationDiagnostics`,t),r=V(e,`rpId`,t),i=V(e,`walletCustody`,t),a=V(e,`custodyKeyManifestDigestB64u`,t);return{ok:B(e,`ok`,t),walletId:B(e,`walletId`,t),authority:B(e,`authority`,t),foundingAuthority:B(e,`foundingAuthority`,t),foundingAuthMethod:B(e,`foundingAuthMethod`,t),...n===void 0?{}:{registrationDiagnostics:n},...r===void 0?{}:{rpId:r},authMethod:B(e,`authMethod`,t),...i===void 0?{}:{walletCustody:i},...a===void 0?{}:{custodyKeyManifestDigestB64u:a},kind:`near_ed25519`,authorityScope:B(e,`authorityScope`,t),accountProvisioning:B(e,`accountProvisioning`,t),resolvedAccount:B(e,`resolvedAccount`,t),ed25519:B(e,`ed25519`,t)}}function or(e){let t=`Wallet registration activate`,n=z({responseName:t,field:`body`,value:e}),r=B(n,`kind`,t),i=V(n,`nearProvisioning`,t),a=V(n,`registrationEstablishedSession`,t);if(r!==`evm_family_ecdsa`)throw Error(`${t} response has invalid kind`);let o=z({responseName:t,field:`ecdsa`,value:B(n,`ecdsa`,t)});H(n,[`ok`,`walletId`,`authority`,`foundingAuthority`,`foundingAuthMethod`,`registrationDiagnostics`,`rpId`,`authMethod`,`walletCustody`,`custodyKeyManifestDigestB64u`,`kind`,`ecdsa`,`nearProvisioning`,`registrationEstablishedSession`],t),H(o,[`walletKeys`,`activation`,`bootstrap`],t);let s=V(o,`activation`,t),c=V(o,`bootstrap`,t);if(i!==void 0){let e=z({responseName:t,field:`nearProvisioning`,value:i});if(H(e,[`status`],`${t} nearProvisioning`),B(e,`status`,`${t} nearProvisioning`)!==`near_pending`)throw Error(`${t} nearProvisioning status is invalid`)}if(s===void 0||c===void 0)throw Error(`${t} is missing the activation payload the client needs to build its ECDSA session`);let l=Ft({value:ir(n,o),expectedKind:`evm_family_ecdsa`});if(!l.ok||l.kind!==`evm_family_ecdsa`)throw Error(`${t} did not return an activated ECDSA wallet`);let u=rr(a,l.walletId);return{...l,ecdsa:{...l.ecdsa,activation:Ye(s),bootstrap:at(c)},registrationEstablishedSession:u,...i===void 0?{}:{nearProvisioning:{status:`near_pending`}}}}function sr(e){let t={registrationCeremonyId:e.registrationCeremonyId,kind:e.signerPlanKind,signedSetup:e.signedSetup,idempotencyKey:e.idempotencyKey};return t.ecdsa=e.ecdsa,e.emailOtpEnrollment&&(t.emailOtpEnrollment=e.emailOtpEnrollment),e.walletCustodyCommit&&(t.walletCustodyCommit=e.walletCustodyCommit),t}async function cr(e){return or(await I({relayerUrl:e.relayerUrl,path:Lt,headers:e.headers,body:sr(e),onServerTiming:e.onServerTiming}))}function lr(e){let t=`Wallet registration session seal`,n=z({responseName:t,field:`body`,value:e});H(n,[`ciphertext`,`keyVersion`,`expiresAtMs`,`remainingUses`],t);let r=B(n,`ciphertext`,t),i=B(n,`keyVersion`,t),a=B(n,`expiresAtMs`,t),o=B(n,`remainingUses`,t);if(typeof r!=`string`||!r.trim()||typeof i!=`string`||!i.trim()||typeof a!=`number`||!Number.isSafeInteger(a)||a<=0||typeof o!=`number`||!Number.isSafeInteger(o)||o<0)throw Error(`${t} is invalid`);return{ciphertext:r,keyVersion:i,expiresAtMs:a,remainingUses:o}}function ur(e){let t=`Wallet registration NEAR provisioning`,n=z({responseName:t,field:`body`,value:e});if(B(n,`ok`,t)!==!0){H(n,[`ok`,`code`,`message`,`nearProvisioning`],t);let e=B(n,`code`,t),r=B(n,`message`,t);if(typeof e!=`string`||typeof r!=`string`)throw Error(`${t} failure is invalid`);let i=V(n,`nearProvisioning`,t);if(i!==void 0){let n=z({responseName:t,field:`nearProvisioning`,value:i});if(H(n,[`status`],`${t} nearProvisioning`),B(n,`status`,`${t} nearProvisioning`)!==`near_failed_retryable`)throw Error(`${t} failure status is invalid`);return{ok:!1,code:e,message:r,nearProvisioning:{status:`near_failed_retryable`}}}return{ok:!1,code:e,message:r}}H(n,[`ok`,`walletId`,`authority`,`foundingAuthority`,`foundingAuthMethod`,`registrationDiagnostics`,`rpId`,`authMethod`,`walletCustody`,`custodyKeyManifestDigestB64u`,`kind`,`accountProvisioning`,`resolvedAccount`,`ed25519`,`authorityScope`,`nearProvisioning`,`registrationEstablishedSession`,`sessionSeal`],t);let r=z({responseName:t,field:`nearProvisioning`,value:B(n,`nearProvisioning`,t)});if(H(r,[`status`],`${t} nearProvisioning`),B(r,`status`,`${t} nearProvisioning`)!==`near_ready`)throw Error(`${t} success status is invalid`);let i=Ft({value:ar(n),expectedKind:`near_ed25519`});if(!i.ok||i.kind!==`near_ed25519`)throw Error(`${t} did not return a finalized Ed25519 wallet`);let a=V(n,`sessionSeal`,t),o=rr(B(n,`registrationEstablishedSession`,t),i.walletId);if(bn(i)){if(a!==void 0)throw Error(`${t} returned a session seal for an Email OTP authority`);return{...i,nearProvisioning:{status:`near_ready`},registrationEstablishedSession:o}}let s={...i,nearProvisioning:{status:`near_ready`},registrationEstablishedSession:o};return a===void 0?s:{...s,sessionSeal:lr(a)}}async function dr(e){let t={registrationCeremonyId:e.registrationCeremonyId,signedSetup:e.signedSetup,idempotencyKey:e.idempotencyKey,ed25519:e.ed25519};return e.auth.kind===`email_otp`&&(t.emailOtpEnrollment=e.auth.enrollment),e.walletCustodyCommit&&(t.walletCustodyCommit=e.walletCustodyCommit),e.sessionSeal&&(t.sessionSeal=e.sessionSeal),ur(await I({relayerUrl:e.relayerUrl,path:Rt,headers:e.headers,body:t,...e.onServerTiming?{onServerTiming:e.onServerTiming}:{}}))}function fr(e){switch(e.kind){case`webauthn_assertion`:return{kind:`webauthn_assertion`,rpId:e.rpId,credential:e.credential,expectedChallengeDigestB64u:e.expectedChallengeDigestB64u}}}function pr(e){switch(e.kind){case`webauthn_assertion`:return{kind:`webauthn_assertion`,rpId:e.rpId,credential:e.credential,expectedChallengeDigestB64u:e.expectedChallengeDigestB64u};case`wallet_session`:return{kind:`wallet_session`};case`email_otp`:return{kind:`email_otp`,challengeId:e.challengeId,otpCode:e.otpCode,expectedChallengeDigestB64u:e.expectedChallengeDigestB64u}}}function mr(e){switch(e.kind){case`passkey`:return{};case`email_otp`:return{emailOtpRegistrationProof:e.emailOtpRegistrationProof}}}async function hr(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`walletId is required for add-signer start`);return Vn({value:await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/signers/start`,body:{addSignerIntentGrant:e.addSignerIntentGrant,addSignerIntentDigestB64u:e.addSignerIntentDigestB64u,intent:e.intent,auth:fr(e.auth)}}),expectedIntent:e.intent})}function gr(e){let t=`Email OTP enrollment code`,n=z({responseName:t,field:`body`,value:e});if(H(n,[`ok`,`challengeId`,`expiresAtMs`,`emailHint`],t),B(n,`ok`,t)!==!0)throw Error(`${t} response is not successful`);let r=B(n,`challengeId`,t);if(typeof r!=`string`||!r.trim())throw Error(`${t} response missing challengeId`);let i=B(n,`expiresAtMs`,t);if(typeof i!=`number`||!Number.isSafeInteger(i)||i<1)throw Error(`${t} response has invalid expiresAtMs`);let a=B(n,`emailHint`,t);if(typeof a!=`string`)throw Error(`${t} response has invalid emailHint`);return{challengeId:r.trim(),expiresAtMs:i,emailHint:a}}async function _r(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`walletId is required for the Email OTP enrollment code`);return gr(await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/auth-methods/email-otp/challenge`,body:{addAuthMethodIntentGrant:e.addAuthMethodIntentGrant,addAuthMethodIntentDigestB64u:e.addAuthMethodIntentDigestB64u}}))}async function vr(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`walletId is required for add-auth-method start`);return wn({value:await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/auth-methods/start`,body:{addAuthMethodIntentGrant:e.addAuthMethodIntentGrant,addAuthMethodIntentDigestB64u:e.addAuthMethodIntentDigestB64u,intent:e.intent,auth:pr(e.auth),...mr(e.authority)},...e.auth.kind===`wallet_session`?{headers:{authorization:`Bearer ${e.auth.walletSessionToken}`}}:{}}),expectedIntent:e.intent})}async function yr(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`walletId is required for add-signer ECDSA respond`);return vn(await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/signers/derivation/respond`,body:{addSignerCeremonyId:e.addSignerCeremonyId,ecdsa:e.ecdsa}}))}async function br(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`walletId is required for add-signer ECDSA activation`);return yn(await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/signers/derivation/activate`,body:{addSignerCeremonyId:e.addSignerCeremonyId,ecdsa:{kind:`router_ab_ecdsa_registration_activation_v1`,activationCorrelationId:e.activationCorrelationId,publicFacts:e.publicFacts,expectedActivationRequestDigest:e.expectedActivationRequestDigest}}}))}function xr(e){switch(e.kind){case`near_ed25519`:return{addSignerCeremonyId:e.addSignerCeremonyId,idempotencyKey:e.idempotencyKey,kind:e.kind,ed25519:e.ed25519,custodyKeySet:e.custodyKeySet};case`evm_family_ecdsa`:return{addSignerCeremonyId:e.addSignerCeremonyId,idempotencyKey:e.idempotencyKey,kind:e.kind,ecdsa:e.ecdsa,custodyKeySet:e.custodyKeySet}}}async function Sr(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`walletId is required for add-signer finalize`);return Hn({value:await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/signers/finalize`,body:xr(e)}),expectedKind:e.kind})}async function Cr(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`walletId is required for add-auth-method finalize`);let n=e.custodyEnvelope===void 0?{addAuthMethodCeremonyId:e.addAuthMethodCeremonyId}:e.webauthnRegistration===void 0?{addAuthMethodCeremonyId:e.addAuthMethodCeremonyId,custodyEnvelope:S(e.custodyEnvelope),emailOtpTarget:e.emailOtpTarget}:{addAuthMethodCeremonyId:e.addAuthMethodCeremonyId,webauthnRegistration:e.webauthnRegistration,custodyEnvelope:S(e.custodyEnvelope)},r={relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/auth-methods/finalize`,body:n},i;try{i=await I(r)}catch(e){if(!(e instanceof TypeError))throw e;i=await I(r)}return Cn(i)}async function wr(e){let t=String(e.walletId||``).trim(),n=String(e.rpId||``).trim(),r=e.operationCredential;if(!t)throw Error(`walletId is required for ECDSA key-facts inventory`);if(!n)throw Error(`rpId is required for ECDSA key-facts inventory`);return Kn({value:await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/signers/ecdsa/key-facts/inventory`,headers:h(r),body:{rpId:n,keyTargets:e.keyTargets,auth:{kind:r.kind,walletSessionId:r.walletSessionId}}}),walletId:e.walletId,rpId:n})}async function Tr(e){let t=String(e.walletId||``).trim(),n=String(e.rpId||``).trim(),r=String(e.serverNonceB64u||``).trim(),i=String(e.expectedChallengeDigestB64u||``).trim();if(!t)throw Error(`walletId is required for ECDSA key-facts inventory`);if(!n)throw Error(`rpId is required for ECDSA key-facts inventory`);if(!r||!i)throw Error(`WebAuthn ECDSA key-facts inventory requires challenge binding`);return Kn({value:await I({relayerUrl:e.relayerUrl,path:`/wallets/${encodeURIComponent(t)}/signers/ecdsa/key-facts/inventory`,body:{rpId:n,keyTargets:e.keyTargets,auth:{kind:`webauthn_assertion`,credential:e.credential,serverNonceB64u:r,expectedChallengeDigestB64u:i,...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{}}}}),walletId:e.walletId,rpId:n})}async function Er(e){return he(`seams:wallet-custody:challenge:v1|${f({walletId:e.walletId,operation:e.operation,payload:e.payload,requestOrigin:e.requestOrigin})}`)}function X(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let n=Object.keys(e);return n.length===t.length&&n.every(e=>t.includes(e))}const Dr=[`kind`,`walletId`,`authorityId`,`walletAuthMethodId`,`mintId`,`authorizationId`,`walletSessionId`,`quotaId`],Or=[`ok`,`code`,`message`,`next`,`committed`],kr=[`ok`,`code`,`message`,`next`,`kind`,`walletId`,`authorityId`,`walletAuthMethodId`,`mintId`,`authorizationId`,`walletSessionId`,`quotaId`],Ar=[...kr,`unlocked`,`unlockBackend`];function jr(t){if(!u(t)||!X(t,Dr)||t.kind!==`already_committed_wallet_session_v1`)return null;let r=n(t.walletId),a=e(t.authorityId),o=i(t.walletAuthMethodId),s=pe(t.mintId),c=me(t.authorizationId),l=_(t.walletSessionId),d=g(t.quotaId);return!r.ok||!a.ok||!o.ok||!s.ok||!c.ok||!l.ok||!d.ok?null:{kind:`already_committed_wallet_session_v1`,walletId:r.value,authorityId:a.value,walletAuthMethodId:o.value,mintId:s.value,authorizationId:c.value,walletSessionId:l.value,quotaId:d.value}}function Mr(e){return e.ok!==!1||e.code!==`already_committed`||typeof e.message!=`string`||e.next!==`unlock_exact_method`?null:{ok:!1,code:`already_committed`,message:e.message,next:`unlock_exact_method`}}function Nr(e){return!X(e,kr)&&!X(e,Ar)||X(e,Ar)&&(e.unlocked!==!1||e.unlockBackend!==`passkey`&&e.unlockBackend!==`email_otp`)||e.kind!==`already_committed`?null:jr({kind:`already_committed_wallet_session_v1`,walletId:e.walletId,authorityId:e.authorityId,walletAuthMethodId:e.walletAuthMethodId,mintId:e.mintId,authorizationId:e.authorizationId,walletSessionId:e.walletSessionId,quotaId:e.quotaId})}function Pr(e,t){return{ok:!1,code:`already_committed`,message:e.message,next:`unlock_exact_method`,committed:t}}function Fr(e){if(!u(e))return null;let t=Mr(e);if(!t||!X(e,Or))return null;let n=jr(e.committed);return n?Pr(t,n):null}function Ir(e){if(!u(e))return null;let t=Mr(e);if(!t)return null;let n=Nr(e);return n?Pr(t,n):null}var Z=class{retainProof(){return!0}constructor(){this.retainProof()}},Lr=class extends Z{constructor(e){super(),this.kind=`use_live_runtime`,this.capability=e.materialActivation.capability,this.materialOwner=e.materialActivation.materialOwner,this.authority=e.authority,this.runtime=e.runtime,this.materialActivation=e.materialActivation}},Rr=class extends Z{constructor(e){super(),this.kind=`rehydrate_material_activation`,this.capability=e.materialActivation.capability,this.materialOwner=e.materialActivation.materialOwner,this.authority=e.authority,this.materialActivation=e.materialActivation,this.sealedMaterial=e.sealedMaterial}},zr=class extends Z{constructor(e){super(),this.kind=`reauthorize_public_anchor`,this.capability=e.publicReauthAnchor.capability,this.materialOwner=e.publicReauthAnchor.materialOwner,this.authority=e.publicReauthAnchor.authority,this.retirement=e.retirement,this.publicReauthAnchor=e.publicReauthAnchor}},Br=class extends Z{constructor(...e){super(...e),this.kind=`blocked`}},Vr=class extends Br{constructor(...e){super(...e),this.capability=null,this.reason=`missing_capability`}},Hr=class extends Br{constructor(e){super(),this.capability=e.capability,this.reason=e.reason}};function Ur(e){return new Lr(e)}function Wr(e){return new Rr(e)}function Gr(e){return new zr(e)}function Q(e){return e.reason===`missing_capability`?new Vr:new Hr(e)}function Kr(e){if(!e.ok)throw Error(e.error.message);return e.value}function qr(e){return e.materialActivation}function Jr(e){return Kr(a(`near-ed25519-yao:${e.activationId}`))}function $(e,t){let n=e.sealed.kind===`available`?e.sealed.materialActivation.capability:e.runtime.kind===`live`?e.runtime.materialActivation.capability:e.publicLocator.kind===`available`?e.publicLocator.materialActivation.capability:null;return Q(n?{capability:n,reason:t}:{capability:null,reason:`missing_capability`})}function Yr(e){switch(e.publicLocator.kind){case`missing`:return Q({capability:null,reason:`missing_capability`});case`retired`:return Gr({retirement:e.publicLocator.retirement,publicReauthAnchor:e.publicLocator.publicReauthAnchor});case`conflict`:return $(e,`exact_record_conflict`);case`corrupt`:return $(e,`corrupt`);case`unavailable`:return Q({capability:e.publicLocator.capability,reason:`persistence_unavailable`});case`available`:break;default:e.publicLocator}let t=e.publicLocator.materialActivation;if(String(t.materialOwner)!==e.publicLocator.walletId)return $(e,`binding_mismatch`);switch(e.runtime.kind){case`live`:return c(t,e.runtime.materialActivation)?Ur({authority:e.publicLocator.authority,runtime:e.runtime.runtime,materialActivation:t}):$(e,`binding_mismatch`);case`absent`:break;default:e.runtime}switch(e.sealed.kind){case`missing`:return $(e,`missing_material`);case`corrupt`:return $(e,`corrupt`);case`available`:break;default:e.sealed}let n=e.sealed;if(String(n.authority.walletId)!==e.publicLocator.walletId||String(n.authority.authorityDigest)!==String(e.publicLocator.authority.authorityDigest)||String(n.materialActivation.materialOwner)!==e.publicLocator.walletId||!c(n.materialActivation,e.publicLocator.materialActivation))return $(e,`binding_mismatch`);switch(e.unlockSource.kind){case`unavailable`:return $(e,`missing_material`);case`available`:return String(e.unlockSource.authority.walletId)!==String(n.authority.walletId)||String(e.unlockSource.authority.authorityDigest)!==String(n.authority.authorityDigest)?$(e,`binding_mismatch`):Wr({authority:n.authority,materialActivation:n.materialActivation,sealedMaterial:n.sealedMaterial});default:e.unlockSource}throw Error(`Unsupported Near Ed25519 unlock-source observation`)}export{hr as A,Bt as C,Xn as D,nr as E,qn as O,Gn as S,yr as T,Tr as _,Wr as a,en as b,Ir as c,br as d,cr as f,wr as g,Jn as h,Q as i,yt as j,vr as k,X as l,Zn as m,Jr as n,Ur as o,dr as p,Yr as r,Fr as s,qr as t,Er as u,Cr as v,_r as w,bn as x,Sr as y};
@@ -1 +1 @@
1
- import{f as e,w as t}from"./normalize-kUDm5zfS.js";import{c as n}from"./chains-CiYQT1K4.js";import{t as r}from"./activeWalletSession-DiZcKjB_.js";import{l as i,o as a}from"./accountIds-BzZs7YoX.js";import{a as o,c as s,o as c}from"./ecdsaChainTarget-C8ZtMZ8l.js";import{C as l,Ct as u,Nt as d,T as ee,Tt as te,o as ne,wt as f,xt as p}from"./emailOtpEcdsaDerivationIdentity-B8HzTh4T.js";import{a as m,i as h,l as g,o as _,u as v}from"./challengeDelivery-DxXAkOfS.js";import{t as y}from"./signerSlot-Dto7dObP.js";import{c as b,r as x}from"./types-D3GM-uHR.js";function S(e){throw Error(`[SigningSession] unsupported exact signing lane branch: ${String(e)}`)}function C(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`[SigningSession] ${t} must be an object`);return e}function w(e,t){let n=String(e??``).trim();if(!n)throw Error(`[SigningSession] ${t} is required`);return n}function T(e,t,n){for(let r of t)if(e[r]!==void 0)throw Error(`[SigningSession] ${n} exact lane cannot include ${r}`)}function E(e){let t=C(e,`exact lane auth`);switch(t.kind){case`passkey`:return{kind:`passkey`,rpId:ee(t.rpId),credentialIdB64u:w(t.credentialIdB64u,`credentialIdB64u`)};case`email_otp`:return{kind:`email_otp`,providerSubjectId:w(t.providerSubjectId,`providerSubjectId`)};default:throw Error(`[SigningSession] exact lane auth kind is unsupported`)}}function D(e){let t=C(e,`ECDSA exact lane chainTarget`),n=o({kind:t.kind,namespace:t.namespace,chainId:t.chainId,networkSlug:t.networkSlug});if(t.key!=null&&String(t.key)!==c(n))throw Error(`[SigningSession] exact ECDSA lane chain target key mismatch`);return n}function O(e){let t=C(e,`ECDSA exact lane key identity`);if(t.keyScope!==`evm-family`)throw Error(`[SigningSession] exact ECDSA lane keyScope must be evm-family`);return ne({walletId:t.walletId,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,participantIds:t.participantIds,thresholdOwnerAddress:t.thresholdOwnerAddress})}function k(e){let n=t(e);if(!n.ok)throw Error(n.error.message);return n.value}function A(e){let t=i(e.nearAccountId);if(!t.ok)throw Error(`[SigningSession] invalid exact Ed25519 NEAR account: ${t.message}`);let n=g({walletId:s(e.walletId)});return a(t.value)?h({wallet:n,nearAccountId:t.value}):m({wallet:n,nearAccountId:t.value})}function j(e){let t=Number(e.signerSlot);if(!Number.isSafeInteger(t)||t<1)throw Error(`[SigningSession] exact Ed25519 signer requires signerSlot >= 1`);return _({account:A({walletId:e.walletId,nearAccountId:e.nearAccountId}),nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:t})}function M(e){if(String(e.key.walletId)!==String(e.walletId))throw Error(`[SigningSession] exact ECDSA lane identity wallet mismatch`);let t=k(e.materialActivation);if(String(t.materialOwner)!==String(e.walletId))throw Error(`[SigningSession] exact ECDSA lane material owner mismatch`);return{kind:`evm_family_ecdsa_signer`,walletId:s(e.walletId),chainTarget:e.chainTarget,keyHandle:e.keyHandle,key:e.key,materialActivation:t}}function N(e){let t=C(e,`ECDSA exact lane signer`);if(t.kind!==`evm_family_ecdsa_signer`)throw Error(`[SigningSession] expected EVM-family ECDSA signer`);let n=D(t.chainTarget),r=O(t.key);return M({walletId:s(t.walletId),chainTarget:n,keyHandle:l(t.keyHandle),key:r,materialActivation:k(t.materialActivation)})}function P(e){return e.kind===`evm`?{key:c(e),kind:`evm`,namespace:`eip155`,chainId:e.chainId}:{key:c(e),kind:`tempo`,chainId:e.chainId}}function F(e){return{walletId:String(e.walletId),keyScope:e.keyScope,ecdsaThresholdKeyId:String(e.ecdsaThresholdKeyId),signingRootId:String(e.signingRootId),signingRootVersion:String(e.signingRootVersion),participantIds:[...e.participantIds].map(e=>Number(e)),thresholdOwnerAddress:String(e.thresholdOwnerAddress).toLowerCase()}}function I(e){switch(e.kind){case`passkey`:return{kind:`passkey`,rpId:String(e.rpId),credentialIdB64u:String(e.credentialIdB64u)};case`email_otp`:return{kind:`email_otp`,providerSubjectId:String(e.providerSubjectId)};default:return S(e)}}function L(e){return{kind:`evm_family_ecdsa_signer`,walletId:String(e.walletId),keyHandle:String(e.keyHandle),chainTarget:P(e.chainTarget),key:F(e.key),materialActivation:{kind:e.materialActivation.kind,activationId:String(e.materialActivation.activationId),capability:String(e.materialActivation.capability),materialOwner:String(e.materialActivation.materialOwner),keyBinding:String(e.materialActivation.keyBinding),lifecycleBinding:String(e.materialActivation.lifecycleBinding),signingWorker:String(e.materialActivation.signingWorker)}}}function R(e){return Y(e)?{kind:`exact_signing_lane`,signer:L(e.signer),auth:I(e.auth)}:{kind:`exact_signing_lane`,signer:{kind:`near_ed25519_signer`,account:{kind:e.signer.account.kind,walletId:String(e.signer.account.wallet.walletId),nearAccountId:String(e.signer.account.nearAccountId)},nearEd25519SigningKeyId:String(e.signer.nearEd25519SigningKeyId),signerSlot:Number(e.signer.signerSlot)},auth:I(e.auth),walletSessionId:String(e.walletSessionId),quotaId:String(e.quotaId),thresholdSessionId:String(e.thresholdSessionId)}}function z(e){return n(R(e))}function B(e){return{kind:`exact_signing_lane`,signer:e.signer,auth:e.auth,walletSessionId:x.walletSession(e.walletSessionId),quotaId:x.walletSessionQuota(e.quotaId),thresholdSessionId:x.thresholdEd25519Session(e.thresholdSessionId)}}function V(e){return{kind:`exact_ed25519_export_material`,signer:e.signer,auth:e.auth,thresholdSessionId:x.thresholdEd25519Session(e.thresholdSessionId)}}function H(e){return{kind:`exact_signing_lane`,signer:e.signer,auth:e.auth}}function U(e){return e.identity}function W(e){return e.identity}function G(e){return e.identity}function K(e){let t=C(e,`exact Ed25519 export material identity`);if(t.kind!==`exact_ed25519_export_material`)throw Error(`[SigningSession] expected exact Ed25519 export material identity`);T(t,[`walletSessionId`,`quotaId`,`walletId`,`nearAccountId`,`nearEd25519SigningKeyId`,`chainTarget`,`keyHandle`,`key`,`curve`,`chainFamily`,`accountId`,`subjectId`,`authMethod`,`authorization`],`nested`);let n=v(C(t.signer,`exact Ed25519 export material signer`));if(!n.ok)throw Error(n.error.message);return V({signer:n.value,auth:E(t.auth),thresholdSessionId:t.thresholdSessionId})}function q(e){let t=J(e);if(Y(t))return t;throw Error(`[SigningSession] expected exact ECDSA lane identity`)}function J(e){let t=C(e,`exact signing lane identity`);if(t.kind!==`exact_signing_lane`)throw Error(`[SigningSession] expected exact signing lane identity`);T(t,[`walletId`,`nearAccountId`,`nearEd25519SigningKeyId`,`chainTarget`,`keyHandle`,`key`,`curve`,`chainFamily`,`accountId`,`subjectId`,`authMethod`,`authorization`],`nested`);let n=C(t.signer,`exact lane signer`),r=E(t.auth);switch(n.kind){case`near_ed25519_signer`:{let e=v(n);if(!e.ok)throw Error(e.error.message);return B({signer:e.value,auth:r,walletSessionId:t.walletSessionId,quotaId:t.quotaId,thresholdSessionId:t.thresholdSessionId})}case`evm_family_ecdsa_signer`:return H({signer:N(n),auth:r});default:throw Error(`[SigningSession] exact signing lane signer kind is unsupported`)}}function Y(e){return e.signer.kind===`evm_family_ecdsa_signer`}function X(e){switch(e.signer.kind){case`near_ed25519_signer`:return e.signer.account.wallet.walletId;case`evm_family_ecdsa_signer`:return e.signer.walletId;default:return S(e.signer)}}function Z(e,t){if(e.signer.kind!==`evm_family_ecdsa_signer`)throw Error(`[SigningSession] ${t} requires an EVM-family ECDSA signer`);return e.signer}function re(e,t){if(e.signer.kind!==`near_ed25519_signer`)throw Error(`[SigningSession] ${t} requires a NEAR Ed25519 signer`);return e.signer}function ie(e,t=`NEAR protocol projection`){let n=re(e,t);return{walletId:n.account.wallet.walletId,nearAccountId:n.account.nearAccountId,nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot}}function ae(e,t){return z(e)===z(t)}function oe(e){return String(te(e.authority))}function se(e){return f(e.authority)}function ce(e){return u(e.authority)}function le(e){switch(e.use.kind){case`session`:return`session`;case`single_use_pending`:case`single_use_consumed`:return`single_use`}throw e.use,Error(`[SigningSession] unsupported Email OTP auth use`)}function ue(e){return e.use.kind===`single_use_consumed`?e.use.consumedAtMs:null}function de(e){return e.use.kind===`session`}function fe(e){return e.use.kind===`single_use_pending`}function Q(e){if(e.policy===`per_operation`&&e.retention!==`single_use`)throw Error(`Invalid Email OTP auth context: per-operation sessions must be single-use`);if(e.retention===`single_use`&&Object.prototype.hasOwnProperty.call(e,`reason`))throw Error(`Invalid Email OTP auth context: single-use sessions must not carry reason`);let t=Math.floor(Number(e.consumedAtMs)||0),n=e.retention===`session`?{kind:`session`,reason:e.reason}:t>0?{kind:`single_use_consumed`,consumedAtMs:t}:{kind:`single_use_pending`};return{policy:e.policy,authMethod:`email_otp`,authority:e.authority,use:n}}function pe(e){let t=e.authority;if(e.retention===`session`)return Q({policy:e.policy,reason:e.reason,retention:`session`,authority:t});if(Object.prototype.hasOwnProperty.call(e,`reason`))throw Error(`Invalid Email OTP auth context: single-use sessions must not carry reason`);let n=Math.floor(Number(e.consumedAtMs)||0);return Q(n>0?{policy:e.policy,retention:`single_use`,authority:t,consumedAtMs:n}:{policy:e.policy,retention:`single_use`,authority:t})}function me(e){let t=p({walletId:e.walletId,provider:e.provider,providerUserId:e.providerUserId,emailHashHex:e.emailHashHex});if(e.retention===`session`)return Q({policy:e.policy,reason:e.reason,retention:`session`,authority:t});if(Object.prototype.hasOwnProperty.call(e,`reason`))throw Error(`Invalid Email OTP auth context: single-use sessions must not carry reason`);let n=Math.floor(Number(e.consumedAtMs)||0);return Q(n>0?{policy:e.policy,retention:`single_use`,authority:t,consumedAtMs:n}:{policy:e.policy,retention:`single_use`,authority:t})}function he(e){let t=y(e.signerSlot);if(t==null)throw Error(`[SigningSession] selected Ed25519 lane requires signerSlot >= 1`);let n=x.walletSession(e.walletSessionId),r=x.walletSessionQuota(e.quotaId),i=x.thresholdEd25519Session(e.thresholdSessionId);return{kind:`selected_lane`,identity:B({signer:j({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:t}),auth:e.auth,walletSessionId:n,quotaId:r,thresholdSessionId:i}),auth:e.auth,curve:`ed25519`,chain:`near`,walletSessionId:n,quotaId:r,thresholdSessionId:i}}function ge(e){if(!e.key)throw Error(`[SigningSession] selected ECDSA lane requires shared key identity`);let t=l(e.keyHandle);if(String(e.key.walletId)!==String(e.walletId))throw Error(`[SigningSession] selected ECDSA lane wallet mismatch`);return{kind:`selected_lane`,identity:H({signer:M({walletId:e.walletId,chainTarget:e.chainTarget,keyHandle:t,key:e.key,materialActivation:e.materialActivation}),auth:e.auth}),auth:e.auth,curve:`ecdsa`,chain:e.chainTarget.kind,materialActivation:e.materialActivation,authorization:e.authorization}}function _e(e){let t=Math.floor(Number(e.nowMs)||Date.now());return e.expiresAtMs<=t?`expired`:e.remainingUses<=0?`exhausted`:`ready`}function ve(e){return b(e.auth)}function ye(e){switch(e.kind){case`found`:return{kind:`authorized`,authorization:e.authorization};case`expired`:case`exhausted`:return{kind:`operation_step_up`,reason:e.kind};case`persistence_unavailable`:return{kind:`temporarily_unavailable`,reason:e.kind};case`missing`:case`corrupt`:case`upgrade_required`:case`superseded`:case`authority_unavailable`:case`method_unavailable`:case`capability_unavailable`:case`unavailable`:return{kind:`full_login_required`,reason:e.kind};default:throw Error(`[SigningEngine][near] unsupported Wallet Session authorization state`)}}function be(e){switch(e.kind){case`use_live_runtime`:case`rehydrate_material_activation`:case`reauthorize_public_anchor`:return e.authority;case`blocked`:return null;default:throw Error(`[SigningEngine][near] unsupported MPC hydration plan`)}}function $(e){let{selectedAuthority:t,selectedAuthMethod:n,selectedFactorAuthority:r}=e;return t.state!==`active`||t.walletId!==n.walletId||t.authorityId!==n.walletAuthorityId||t.signerActivations.ed25519===void 0||r.walletId!==n.walletId||r.bindingId!==n.walletAuthMethodId?!1:n.kind===`passkey`?r.factor.kind===`passkey`&&r.factor.credentialIdB64u===n.credentialIdB64u&&r.verifier.kind===`webauthn`&&r.verifier.rpId===n.rpId:r.factor.kind===`email_otp`&&r.verifier.kind===`email_otp_wallet_auth_method`&&r.verifier.emailHashHex===n.emailHashHex&&r.factor.providerUserId.trim().length>0}function xe(e){let{authorization:t,nowMs:n}=e,{selectedAuthority:i,selectedAuthMethod:a,session:o,operationCredential:s,status:c}=t;return!(!$({selectedAuthority:i,selectedAuthMethod:a,selectedFactorAuthority:t.selectedFactorAuthority})||o.kind!==`active_wallet_session_v1`||o.walletId!==i.walletId||o.authorityId!==i.authorityId||o.authMethodId!==a.walletAuthMethodId||o.authorityDigestB64u!==i.authorityDigestB64u||o.authorityRevocationEpoch!==i.revocationEpoch||s.kind!==`opaque_wallet_session_operation_credential_v1`||s.token.trim().length===0||s.walletSessionId.trim().length===0||o.authorizationId.trim().length===0||o.quotaId.trim().length===0||o.expiresAtMs<=n||c.status!==`active`||c.walletSessionId!==s.walletSessionId||c.quotaId!==o.quotaId||c.remainingUses<=0||c.expiresAtMs<=n||c.quotaLifecycle!==`active`||c.authorization.expiresAtMs!==o.expiresAtMs||!r(c.authorization,o))}function Se(t){let n=0;for(let r of t.session.capabilitySubjects)r.kind===`sign`&&r.keyFamily===`ed25519`&&e(r.materialActivation,t.materialActivation)&&(n+=1);return n===1}async function Ce(e){let t=be(e.hydration);if(!t)return;let n=await d({authority:e.authorization.selectedFactorAuthority});if(t.walletId!==n.walletId||t.walletAuthMethodId!==n.walletAuthMethodId||t.authorityDigest!==n.authorityDigest)throw Error(`[SigningEngine][near] Wallet Session authorization does not match material authority`)}function we(e){let{requirement:t,authorization:n}=e;if(t.kind!==n.selectedAuthMethod.kind)throw Error(`[SigningEngine][near] Wallet Session authorization does not match material factor`);if(t.kind===`passkey`){if(n.selectedAuthMethod.kind!==`passkey`||String(t.rpId)!==String(n.selectedAuthMethod.rpId)||t.credentialIdB64u!==n.selectedAuthMethod.credentialIdB64u)throw Error(`[SigningEngine][near] Wallet Session authorization does not match Passkey factor`);return}if(n.selectedAuthMethod.kind!==`email_otp`||n.selectedFactorAuthority.factor.kind!==`email_otp`||t.providerSubjectId!==n.selectedFactorAuthority.factor.providerUserId)throw Error(`[SigningEngine][near] Wallet Session authorization does not match Email OTP factor`)}function Te(e){if(!Number.isSafeInteger(e.nowMs)||e.nowMs<0)throw Error(`[SigningEngine][near] Wallet Session authorization requires a valid timestamp`);let t={kind:`exact_near_ed25519_wallet_session_authorization_v1`,selectedAuthority:e.selectedAuthority,selectedAuthMethod:e.selectedAuthMethod,selectedFactorAuthority:e.selectedFactorAuthority,session:e.session,operationCredential:e.operationCredential,status:e.status};if(!xe({authorization:t,nowMs:e.nowMs}))throw Error(`[SigningEngine][near] Exact Wallet Session authorization identity is invalid`);return t}async function Ee(e){return we(e),await Ce(e),{kind:`near_ed25519_yao_signing_preparation`,hydration:e.hydration,authorization:{kind:`authorized`,authorization:e.authorization}}}function De(e){return{kind:`near_ed25519_yao_signing_preparation`,hydration:e.hydration,authorization:{kind:`authorization_required`,requirement:e.requirement}}}export{Y as A,V as C,z as D,U as E,Z as F,ie as M,q as N,ae as O,K as P,G as S,W as T,_e as _,Se as a,M as b,pe as c,se as d,oe as f,ve as g,de as h,ye as i,j,X as k,ue as l,fe as m,De as n,Q as o,le as p,Ee as r,me as s,Te as t,ce as u,ge as v,B as w,H as x,he as y};
1
+ import{h as e,r as t}from"./domainIds-BzkGsRqO.js";import{c as n}from"./chains-C_X_fNuS.js";import{t as r}from"./activeWalletSession-WdZkhtBB.js";import{l as i,o as a}from"./accountIds-BzZs7YoX.js";import{a as o,c as s,o as c}from"./ecdsaChainTarget-DJBXHzbH.js";import{C as l,Ct as u,Nt as d,T as ee,Tt as te,o as ne,wt as f,xt as p}from"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{a as m,i as h,l as g,o as _,u as v}from"./challengeDelivery-5lIu9spR.js";import{t as y}from"./signerSlot-B4Eq8Oe2.js";import{c as b,r as x}from"./types-WGrFMQSw.js";function S(e){throw Error(`[SigningSession] unsupported exact signing lane branch: ${String(e)}`)}function C(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`[SigningSession] ${t} must be an object`);return e}function w(e,t){let n=String(e??``).trim();if(!n)throw Error(`[SigningSession] ${t} is required`);return n}function T(e,t,n){for(let r of t)if(e[r]!==void 0)throw Error(`[SigningSession] ${n} exact lane cannot include ${r}`)}function E(e){let t=C(e,`exact lane auth`);switch(t.kind){case`passkey`:return{kind:`passkey`,rpId:ee(t.rpId),credentialIdB64u:w(t.credentialIdB64u,`credentialIdB64u`)};case`email_otp`:return{kind:`email_otp`,providerSubjectId:w(t.providerSubjectId,`providerSubjectId`)};default:throw Error(`[SigningSession] exact lane auth kind is unsupported`)}}function D(e){let t=C(e,`ECDSA exact lane chainTarget`),n=o({kind:t.kind,namespace:t.namespace,chainId:t.chainId,networkSlug:t.networkSlug});if(t.key!=null&&String(t.key)!==c(n))throw Error(`[SigningSession] exact ECDSA lane chain target key mismatch`);return n}function O(e){let t=C(e,`ECDSA exact lane key identity`);if(t.keyScope!==`evm-family`)throw Error(`[SigningSession] exact ECDSA lane keyScope must be evm-family`);return ne({walletId:t.walletId,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,participantIds:t.participantIds,thresholdOwnerAddress:t.thresholdOwnerAddress})}function k(t){let n=e(t);if(!n.ok)throw Error(n.error.message);return n.value}function A(e){let t=i(e.nearAccountId);if(!t.ok)throw Error(`[SigningSession] invalid exact Ed25519 NEAR account: ${t.message}`);let n=g({walletId:s(e.walletId)});return a(t.value)?h({wallet:n,nearAccountId:t.value}):m({wallet:n,nearAccountId:t.value})}function j(e){let t=Number(e.signerSlot);if(!Number.isSafeInteger(t)||t<1)throw Error(`[SigningSession] exact Ed25519 signer requires signerSlot >= 1`);return _({account:A({walletId:e.walletId,nearAccountId:e.nearAccountId}),nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:t})}function M(e){if(String(e.key.walletId)!==String(e.walletId))throw Error(`[SigningSession] exact ECDSA lane identity wallet mismatch`);let t=k(e.materialActivation);if(String(t.materialOwner)!==String(e.walletId))throw Error(`[SigningSession] exact ECDSA lane material owner mismatch`);return{kind:`evm_family_ecdsa_signer`,walletId:s(e.walletId),chainTarget:e.chainTarget,keyHandle:e.keyHandle,key:e.key,materialActivation:t}}function N(e){let t=C(e,`ECDSA exact lane signer`);if(t.kind!==`evm_family_ecdsa_signer`)throw Error(`[SigningSession] expected EVM-family ECDSA signer`);let n=D(t.chainTarget),r=O(t.key);return M({walletId:s(t.walletId),chainTarget:n,keyHandle:l(t.keyHandle),key:r,materialActivation:k(t.materialActivation)})}function P(e){return e.kind===`evm`?{key:c(e),kind:`evm`,namespace:`eip155`,chainId:e.chainId}:{key:c(e),kind:`tempo`,chainId:e.chainId}}function F(e){return{walletId:String(e.walletId),keyScope:e.keyScope,ecdsaThresholdKeyId:String(e.ecdsaThresholdKeyId),signingRootId:String(e.signingRootId),signingRootVersion:String(e.signingRootVersion),participantIds:[...e.participantIds].map(e=>Number(e)),thresholdOwnerAddress:String(e.thresholdOwnerAddress).toLowerCase()}}function I(e){switch(e.kind){case`passkey`:return{kind:`passkey`,rpId:String(e.rpId),credentialIdB64u:String(e.credentialIdB64u)};case`email_otp`:return{kind:`email_otp`,providerSubjectId:String(e.providerSubjectId)};default:return S(e)}}function L(e){return{kind:`evm_family_ecdsa_signer`,walletId:String(e.walletId),keyHandle:String(e.keyHandle),chainTarget:P(e.chainTarget),key:F(e.key),materialActivation:{kind:e.materialActivation.kind,activationId:String(e.materialActivation.activationId),capability:String(e.materialActivation.capability),materialOwner:String(e.materialActivation.materialOwner),keyBinding:String(e.materialActivation.keyBinding),lifecycleBinding:String(e.materialActivation.lifecycleBinding),signingWorker:String(e.materialActivation.signingWorker)}}}function R(e){return Y(e)?{kind:`exact_signing_lane`,signer:L(e.signer),auth:I(e.auth)}:{kind:`exact_signing_lane`,signer:{kind:`near_ed25519_signer`,account:{kind:e.signer.account.kind,walletId:String(e.signer.account.wallet.walletId),nearAccountId:String(e.signer.account.nearAccountId)},nearEd25519SigningKeyId:String(e.signer.nearEd25519SigningKeyId),signerSlot:Number(e.signer.signerSlot)},auth:I(e.auth),walletSessionId:String(e.walletSessionId),quotaId:String(e.quotaId),thresholdSessionId:String(e.thresholdSessionId)}}function z(e){return n(R(e))}function B(e){return{kind:`exact_signing_lane`,signer:e.signer,auth:e.auth,walletSessionId:x.walletSession(e.walletSessionId),quotaId:x.walletSessionQuota(e.quotaId),thresholdSessionId:x.thresholdEd25519Session(e.thresholdSessionId)}}function V(e){return{kind:`exact_ed25519_export_material`,signer:e.signer,auth:e.auth,thresholdSessionId:x.thresholdEd25519Session(e.thresholdSessionId)}}function H(e){return{kind:`exact_signing_lane`,signer:e.signer,auth:e.auth}}function U(e){return e.identity}function W(e){return e.identity}function G(e){return e.identity}function K(e){let t=C(e,`exact Ed25519 export material identity`);if(t.kind!==`exact_ed25519_export_material`)throw Error(`[SigningSession] expected exact Ed25519 export material identity`);T(t,[`walletSessionId`,`quotaId`,`walletId`,`nearAccountId`,`nearEd25519SigningKeyId`,`chainTarget`,`keyHandle`,`key`,`curve`,`chainFamily`,`accountId`,`subjectId`,`authMethod`,`authorization`],`nested`);let n=v(C(t.signer,`exact Ed25519 export material signer`));if(!n.ok)throw Error(n.error.message);return V({signer:n.value,auth:E(t.auth),thresholdSessionId:t.thresholdSessionId})}function q(e){let t=J(e);if(Y(t))return t;throw Error(`[SigningSession] expected exact ECDSA lane identity`)}function J(e){let t=C(e,`exact signing lane identity`);if(t.kind!==`exact_signing_lane`)throw Error(`[SigningSession] expected exact signing lane identity`);T(t,[`walletId`,`nearAccountId`,`nearEd25519SigningKeyId`,`chainTarget`,`keyHandle`,`key`,`curve`,`chainFamily`,`accountId`,`subjectId`,`authMethod`,`authorization`],`nested`);let n=C(t.signer,`exact lane signer`),r=E(t.auth);switch(n.kind){case`near_ed25519_signer`:{let e=v(n);if(!e.ok)throw Error(e.error.message);return B({signer:e.value,auth:r,walletSessionId:t.walletSessionId,quotaId:t.quotaId,thresholdSessionId:t.thresholdSessionId})}case`evm_family_ecdsa_signer`:return H({signer:N(n),auth:r});default:throw Error(`[SigningSession] exact signing lane signer kind is unsupported`)}}function Y(e){return e.signer.kind===`evm_family_ecdsa_signer`}function X(e){switch(e.signer.kind){case`near_ed25519_signer`:return e.signer.account.wallet.walletId;case`evm_family_ecdsa_signer`:return e.signer.walletId;default:return S(e.signer)}}function Z(e,t){if(e.signer.kind!==`evm_family_ecdsa_signer`)throw Error(`[SigningSession] ${t} requires an EVM-family ECDSA signer`);return e.signer}function re(e,t){if(e.signer.kind!==`near_ed25519_signer`)throw Error(`[SigningSession] ${t} requires a NEAR Ed25519 signer`);return e.signer}function ie(e,t=`NEAR protocol projection`){let n=re(e,t);return{walletId:n.account.wallet.walletId,nearAccountId:n.account.nearAccountId,nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot}}function ae(e,t){return z(e)===z(t)}function oe(e){return String(te(e.authority))}function se(e){return f(e.authority)}function ce(e){return u(e.authority)}function le(e){switch(e.use.kind){case`session`:return`session`;case`single_use_pending`:case`single_use_consumed`:return`single_use`}throw e.use,Error(`[SigningSession] unsupported Email OTP auth use`)}function ue(e){return e.use.kind===`single_use_consumed`?e.use.consumedAtMs:null}function de(e){return e.use.kind===`session`}function fe(e){return e.use.kind===`single_use_pending`}function Q(e){if(e.policy===`per_operation`&&e.retention!==`single_use`)throw Error(`Invalid Email OTP auth context: per-operation sessions must be single-use`);if(e.retention===`single_use`&&Object.prototype.hasOwnProperty.call(e,`reason`))throw Error(`Invalid Email OTP auth context: single-use sessions must not carry reason`);let t=Math.floor(Number(e.consumedAtMs)||0),n=e.retention===`session`?{kind:`session`,reason:e.reason}:t>0?{kind:`single_use_consumed`,consumedAtMs:t}:{kind:`single_use_pending`};return{policy:e.policy,authMethod:`email_otp`,authority:e.authority,use:n}}function pe(e){let t=e.authority;if(e.retention===`session`)return Q({policy:e.policy,reason:e.reason,retention:`session`,authority:t});if(Object.prototype.hasOwnProperty.call(e,`reason`))throw Error(`Invalid Email OTP auth context: single-use sessions must not carry reason`);let n=Math.floor(Number(e.consumedAtMs)||0);return Q(n>0?{policy:e.policy,retention:`single_use`,authority:t,consumedAtMs:n}:{policy:e.policy,retention:`single_use`,authority:t})}function me(e){let t=p({walletId:e.walletId,provider:e.provider,providerUserId:e.providerUserId,emailHashHex:e.emailHashHex});if(e.retention===`session`)return Q({policy:e.policy,reason:e.reason,retention:`session`,authority:t});if(Object.prototype.hasOwnProperty.call(e,`reason`))throw Error(`Invalid Email OTP auth context: single-use sessions must not carry reason`);let n=Math.floor(Number(e.consumedAtMs)||0);return Q(n>0?{policy:e.policy,retention:`single_use`,authority:t,consumedAtMs:n}:{policy:e.policy,retention:`single_use`,authority:t})}function he(e){let t=y(e.signerSlot);if(t==null)throw Error(`[SigningSession] selected Ed25519 lane requires signerSlot >= 1`);let n=x.walletSession(e.walletSessionId),r=x.walletSessionQuota(e.quotaId),i=x.thresholdEd25519Session(e.thresholdSessionId);return{kind:`selected_lane`,identity:B({signer:j({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:t}),auth:e.auth,walletSessionId:n,quotaId:r,thresholdSessionId:i}),auth:e.auth,curve:`ed25519`,chain:`near`,walletSessionId:n,quotaId:r,thresholdSessionId:i}}function ge(e){if(!e.key)throw Error(`[SigningSession] selected ECDSA lane requires shared key identity`);let t=l(e.keyHandle);if(String(e.key.walletId)!==String(e.walletId))throw Error(`[SigningSession] selected ECDSA lane wallet mismatch`);return{kind:`selected_lane`,identity:H({signer:M({walletId:e.walletId,chainTarget:e.chainTarget,keyHandle:t,key:e.key,materialActivation:e.materialActivation}),auth:e.auth}),auth:e.auth,curve:`ecdsa`,chain:e.chainTarget.kind,materialActivation:e.materialActivation,authorization:e.authorization}}function _e(e){let t=Math.floor(Number(e.nowMs)||Date.now());return e.expiresAtMs<=t?`expired`:e.remainingUses<=0?`exhausted`:`ready`}function ve(e){return b(e.auth)}function ye(e){switch(e.kind){case`found`:return{kind:`authorized`,authorization:e.authorization};case`expired`:case`exhausted`:return{kind:`operation_step_up`,reason:e.kind};case`persistence_unavailable`:return{kind:`temporarily_unavailable`,reason:e.kind};case`missing`:case`corrupt`:case`upgrade_required`:case`superseded`:case`authority_unavailable`:case`method_unavailable`:case`capability_unavailable`:case`unavailable`:return{kind:`full_login_required`,reason:e.kind};default:throw Error(`[SigningEngine][near] unsupported Wallet Session authorization state`)}}function be(e){switch(e.kind){case`use_live_runtime`:case`rehydrate_material_activation`:case`reauthorize_public_anchor`:return e.authority;case`blocked`:return null;default:throw Error(`[SigningEngine][near] unsupported MPC hydration plan`)}}function $(e){let{selectedAuthority:t,selectedAuthMethod:n,selectedFactorAuthority:r}=e;return t.state!==`active`||t.walletId!==n.walletId||t.authorityId!==n.walletAuthorityId||t.signerActivations.ed25519===void 0||r.walletId!==n.walletId||r.bindingId!==n.walletAuthMethodId?!1:n.kind===`passkey`?r.factor.kind===`passkey`&&r.factor.credentialIdB64u===n.credentialIdB64u&&r.verifier.kind===`webauthn`&&r.verifier.rpId===n.rpId:r.factor.kind===`email_otp`&&r.verifier.kind===`email_otp_wallet_auth_method`&&r.verifier.emailHashHex===n.emailHashHex&&r.factor.providerUserId.trim().length>0}function xe(e){let{authorization:t,nowMs:n}=e,{selectedAuthority:i,selectedAuthMethod:a,session:o,operationCredential:s,status:c}=t;return!(!$({selectedAuthority:i,selectedAuthMethod:a,selectedFactorAuthority:t.selectedFactorAuthority})||o.kind!==`active_wallet_session_v1`||o.walletId!==i.walletId||o.authorityId!==i.authorityId||o.authMethodId!==a.walletAuthMethodId||o.authorityDigestB64u!==i.authorityDigestB64u||o.authorityRevocationEpoch!==i.revocationEpoch||s.kind!==`opaque_wallet_session_operation_credential_v1`||s.token.trim().length===0||s.walletSessionId.trim().length===0||o.authorizationId.trim().length===0||o.quotaId.trim().length===0||o.expiresAtMs<=n||c.status!==`active`||c.walletSessionId!==s.walletSessionId||c.quotaId!==o.quotaId||c.remainingUses<=0||c.expiresAtMs<=n||c.quotaLifecycle!==`active`||c.authorization.expiresAtMs!==o.expiresAtMs||!r(c.authorization,o))}function Se(e){let n=0;for(let r of e.session.capabilitySubjects)r.kind===`sign`&&r.keyFamily===`ed25519`&&t(r.materialActivation,e.materialActivation)&&(n+=1);return n===1}async function Ce(e){let t=be(e.hydration);if(!t)return;let n=await d({authority:e.authorization.selectedFactorAuthority});if(t.walletId!==n.walletId||t.walletAuthMethodId!==n.walletAuthMethodId||t.authorityDigest!==n.authorityDigest)throw Error(`[SigningEngine][near] Wallet Session authorization does not match material authority`)}function we(e){let{requirement:t,authorization:n}=e;if(t.kind!==n.selectedAuthMethod.kind)throw Error(`[SigningEngine][near] Wallet Session authorization does not match material factor`);if(t.kind===`passkey`){if(n.selectedAuthMethod.kind!==`passkey`||String(t.rpId)!==String(n.selectedAuthMethod.rpId)||t.credentialIdB64u!==n.selectedAuthMethod.credentialIdB64u)throw Error(`[SigningEngine][near] Wallet Session authorization does not match Passkey factor`);return}if(n.selectedAuthMethod.kind!==`email_otp`||n.selectedFactorAuthority.factor.kind!==`email_otp`||t.providerSubjectId!==n.selectedFactorAuthority.factor.providerUserId)throw Error(`[SigningEngine][near] Wallet Session authorization does not match Email OTP factor`)}function Te(e){if(!Number.isSafeInteger(e.nowMs)||e.nowMs<0)throw Error(`[SigningEngine][near] Wallet Session authorization requires a valid timestamp`);let t={kind:`exact_near_ed25519_wallet_session_authorization_v1`,selectedAuthority:e.selectedAuthority,selectedAuthMethod:e.selectedAuthMethod,selectedFactorAuthority:e.selectedFactorAuthority,session:e.session,operationCredential:e.operationCredential,status:e.status};if(!xe({authorization:t,nowMs:e.nowMs}))throw Error(`[SigningEngine][near] Exact Wallet Session authorization identity is invalid`);return t}async function Ee(e){return we(e),await Ce(e),{kind:`near_ed25519_yao_signing_preparation`,hydration:e.hydration,authorization:{kind:`authorized`,authorization:e.authorization}}}function De(e){return{kind:`near_ed25519_yao_signing_preparation`,hydration:e.hydration,authorization:{kind:`authorization_required`,requirement:e.requirement}}}export{Y as A,V as C,z as D,U as E,Z as F,ie as M,q as N,ae as O,K as P,G as S,W as T,_e as _,Se as a,M as b,pe as c,se as d,oe as f,ve as g,de as h,ye as i,j,X as k,ue as l,fe as m,De as n,Q as o,le as p,Ee as r,me as s,Te as t,ce as u,ge as v,B as w,H as x,he as y};
@@ -1 +1 @@
1
- import{r as e}from"./secureRandomId-BIekT8bE.js";import{o as t}from"./ecdsaChainTarget-C8ZtMZ8l.js";const n={Reserved:`reserved`,Released:`released`,Expired:`expired`,Signed:`signed`,SignedLeaseExpired:`signed_lease_expired`,BroadcastAccepted:`broadcast_accepted`,BroadcastRejected:`broadcast_rejected`,Finalized:`finalized`,Dropped:`dropped`,Replaced:`replaced`,Reconciled:`reconciled`},r={Reserved:n.Reserved,Signed:n.Signed,BroadcastAccepted:n.BroadcastAccepted},i={LeaseReserved:`nonce_lease_reserved`,LeaseReleased:`nonce_lease_released`,LeaseExpired:`nonce_lease_expired`,LeaseSigned:`nonce_lease_signed`,LeaseBroadcastAccepted:`nonce_lease_broadcast_accepted`,LeaseBroadcastRejected:`nonce_lease_broadcast_rejected`,LeaseFinalized:`nonce_lease_finalized`,LeaseDropped:`nonce_lease_dropped`,LeaseReplaced:`nonce_lease_replaced`,Metrics:`nonce_coordinator_metrics`,LaneAlert:`nonce_lane_alert`,CoordinationDegraded:`nonce_coordination_degraded`,LanesCleared:`nonce_lanes_cleared`,LaneReconciled:`nonce_lane_reconciled`},a={Dropped:`dropped`,Replaced:`replaced`},o={WebLocksUnavailable:`web_locks_unavailable`,IndexedDBUnavailable:`indexeddb_unavailable`,DurableLockTimeout:`durable_lock_timeout`,DurableStoreError:`durable_store_error`,MalformedDurableRecord:`malformed_durable_record`},s={InRuntimeLock:`in_runtime_lock`,None:`none`},c={NonceAdvancedHashMissing:`near_nonce_advanced_hash_missing`,HashMissingNonceNotAdvanced:`near_hash_missing_nonce_not_advanced`},l=Object.values(n);function u(e){return{family:`evm`,chainTarget:e.chainTarget,subjectId:e.subjectId,sender:e.sender,...e.nonceKey==null?{}:{nonceKey:e.nonceKey}}}function d(e){return y(e),{...m(e.lane),nonce:e.nonce,leaseId:e.leaseId,operationId:String(e.operationId),operationFingerprint:String(e.operationFingerprint),reservedAtMs:e.reservedAtMs,expiresAtMs:e.expiresAtMs}}function f(e){return u(e)}function p(e){return{leaseId:e.leaseId,operationId:String(e.operationId),operationFingerprint:String(e.operationFingerprint),nonce:String(e.nonce),...e.batchId?{batchId:e.batchId}:{},...Number.isSafeInteger(e.txIndex)?{txIndex:e.txIndex}:{}}}function m(e){return{chainTarget:e.chainTarget,subjectId:e.subjectId,sender:e.sender,...e.nonceKey==null?{}:{nonceKey:e.nonceKey}}}function h(e){return e.family===`near`?e.networkKey:t(e.chainTarget)}function g(e){return e.family===`near`?e.walletId:e.subjectId}function _(e){return e.family===`near`?v(e):C([`evm`,t(e.chainTarget),e.subjectId,e.sender.toLowerCase(),e.nonceKey==null?``:String(e.nonceKey)])}function v(e){return C([`near`,e.networkKey,e.walletId,e.nearAccountId,e.publicKey])}function y(e){if(e.lane.family!==`evm`)throw Error(`[NonceCoordinator] expected an EVM-family nonce lease`)}function b(e,t,n){if(e.operationId!==t)throw Error(`[NonceCoordinator] nonce lease operation mismatch`);if(e.operationFingerprint!==n)throw Error(`[NonceCoordinator] nonce lease operation fingerprint mismatch`)}function x(t){let n=e(`nonce-lease`,32,`nonce lease IDs`);return`nonce-lease-v1:${C([t.chain,t.operationId,t.nonce,n])}`}function S(t){let n=e(`nonce-batch`,32,`nonce batch IDs`);return`nonce-batch-v1:${C([t.chain,t.operationId,t.firstNonce,t.count,n])}`}function C(e){return e.map(e=>{let t=String(e);return`${t.length}:${t}`}).join(`|`)}function w(){return e(`nonce-runtime`,32,`nonce runtime IDs`)}export{o as _,w as a,r as b,d as c,h as d,g as f,c as g,l as h,x as i,u as l,a as m,b as n,m as o,p,S as r,f as s,y as t,_ as u,s as v,n as x,i as y};
1
+ import{r as e}from"./secureRandomId-LwBFx84B.js";import{o as t}from"./ecdsaChainTarget-DJBXHzbH.js";const n={Reserved:`reserved`,Released:`released`,Expired:`expired`,Signed:`signed`,SignedLeaseExpired:`signed_lease_expired`,BroadcastAccepted:`broadcast_accepted`,BroadcastRejected:`broadcast_rejected`,Finalized:`finalized`,Dropped:`dropped`,Replaced:`replaced`,Reconciled:`reconciled`},r={Reserved:n.Reserved,Signed:n.Signed,BroadcastAccepted:n.BroadcastAccepted},i={LeaseReserved:`nonce_lease_reserved`,LeaseReleased:`nonce_lease_released`,LeaseExpired:`nonce_lease_expired`,LeaseSigned:`nonce_lease_signed`,LeaseBroadcastAccepted:`nonce_lease_broadcast_accepted`,LeaseBroadcastRejected:`nonce_lease_broadcast_rejected`,LeaseFinalized:`nonce_lease_finalized`,LeaseDropped:`nonce_lease_dropped`,LeaseReplaced:`nonce_lease_replaced`,Metrics:`nonce_coordinator_metrics`,LaneAlert:`nonce_lane_alert`,CoordinationDegraded:`nonce_coordination_degraded`,LanesCleared:`nonce_lanes_cleared`,LaneReconciled:`nonce_lane_reconciled`},a={Dropped:`dropped`,Replaced:`replaced`},o={WebLocksUnavailable:`web_locks_unavailable`,IndexedDBUnavailable:`indexeddb_unavailable`,DurableLockTimeout:`durable_lock_timeout`,DurableStoreError:`durable_store_error`,MalformedDurableRecord:`malformed_durable_record`},s={InRuntimeLock:`in_runtime_lock`,None:`none`},c={NonceAdvancedHashMissing:`near_nonce_advanced_hash_missing`,HashMissingNonceNotAdvanced:`near_hash_missing_nonce_not_advanced`},l=Object.values(n);function u(e){return{family:`evm`,chainTarget:e.chainTarget,subjectId:e.subjectId,sender:e.sender,...e.nonceKey==null?{}:{nonceKey:e.nonceKey}}}function d(e){return y(e),{...m(e.lane),nonce:e.nonce,leaseId:e.leaseId,operationId:String(e.operationId),operationFingerprint:String(e.operationFingerprint),reservedAtMs:e.reservedAtMs,expiresAtMs:e.expiresAtMs}}function f(e){return u(e)}function p(e){return{leaseId:e.leaseId,operationId:String(e.operationId),operationFingerprint:String(e.operationFingerprint),nonce:String(e.nonce),...e.batchId?{batchId:e.batchId}:{},...Number.isSafeInteger(e.txIndex)?{txIndex:e.txIndex}:{}}}function m(e){return{chainTarget:e.chainTarget,subjectId:e.subjectId,sender:e.sender,...e.nonceKey==null?{}:{nonceKey:e.nonceKey}}}function h(e){return e.family===`near`?e.networkKey:t(e.chainTarget)}function g(e){return e.family===`near`?e.walletId:e.subjectId}function _(e){return e.family===`near`?v(e):C([`evm`,t(e.chainTarget),e.subjectId,e.sender.toLowerCase(),e.nonceKey==null?``:String(e.nonceKey)])}function v(e){return C([`near`,e.networkKey,e.walletId,e.nearAccountId,e.publicKey])}function y(e){if(e.lane.family!==`evm`)throw Error(`[NonceCoordinator] expected an EVM-family nonce lease`)}function b(e,t,n){if(e.operationId!==t)throw Error(`[NonceCoordinator] nonce lease operation mismatch`);if(e.operationFingerprint!==n)throw Error(`[NonceCoordinator] nonce lease operation fingerprint mismatch`)}function x(t){let n=e(`nonce-lease`,32,`nonce lease IDs`);return`nonce-lease-v1:${C([t.chain,t.operationId,t.nonce,n])}`}function S(t){let n=e(`nonce-batch`,32,`nonce batch IDs`);return`nonce-batch-v1:${C([t.chain,t.operationId,t.firstNonce,t.count,n])}`}function C(e){return e.map(e=>{let t=String(e);return`${t.length}:${t}`}).join(`|`)}function w(){return e(`nonce-runtime`,32,`nonce runtime IDs`)}export{o as _,w as a,r as b,d as c,h as d,g as f,c as g,l as h,x as i,u as l,a as m,b as n,m as o,p,S as r,f as s,y as t,_ as u,s as v,n as x,i as y};
@@ -1 +1 @@
1
- import{a as e,o as t}from"./normalize-kUDm5zfS.js";import{o as n}from"./ecdsaChainTarget-C8ZtMZ8l.js";function r(e){let n=t(e);return!n||n===`null`?null:n}function i(t){return e(t)}function a(t){return e(t)}function o(t){return e(t)}function s(e){return n(e)}function c(e){return typeof e==`string`&&e.length>0&&e.trim()===e?e:null}function l(e){return[e.chainIdKey,e.accountAddress].join(`\0`)}export{c as a,r as i,o as n,l as o,i as r,s,a as t};
1
+ import{L as e,R as t}from"./domainIds-BzkGsRqO.js";import{o as n}from"./ecdsaChainTarget-DJBXHzbH.js";function r(e){let n=t(e);return!n||n===`null`?null:n}function i(t){return e(t)}function a(t){return e(t)}function o(t){return e(t)}function s(e){return n(e)}function c(e){return typeof e==`string`&&e.length>0&&e.trim()===e?e:null}function l(e){return[e.chainIdKey,e.accountAddress].join(`\0`)}export{c as a,r as i,o as n,l as o,i as r,s,a as t};
@@ -1 +1 @@
1
- import{c as e,u as t}from"./chains-CiYQT1K4.js";import{i as n}from"./base64-CsEj-_bC.js";import{r}from"./canonicalPrimitives-CKPGgpxg.js";var i=class{retainProof(){return!0}constructor(e){this.retainProof(),this.tenantId=e.tenantId,this.principalId=e.principalId,this.capabilityId=e.capabilityId,this.operationId=e.operationId,this.operation=e.operation,this.digests=e.digests}};function a(e){return new i({tenantId:e.tenantId,principalId:e.principalId,capabilityId:e.capabilityId,operationId:e.operationId,operation:e.operation,digests:{laneDigest:e.digests.laneDigest,intentDigest:e.digests.intentDigest,displayDigest:e.digests.displayDigest}})}function o(t){return`seams:authorization:capability-operation-fingerprint:v1|${e({tenantId:t.tenantId,principalId:t.principalId,capabilityId:t.capabilityId,operationId:t.operationId,operation:t.operation,digests:t.digests})}`}async function s(e){return c(n(await t(o(e))))}function c(e){return r(e)}function l(e){if(typeof e!=`string`||!e.startsWith(`sha256:`))throw Error(`signing operation fingerprint must use the sha256: prefix`);return r(e.slice(7))}export{s as n,l as r,a as t};
1
+ import{c as e,u as t}from"./chains-C_X_fNuS.js";import{i as n}from"./base64-DW79QA0h.js";import{r}from"./canonicalPrimitives-Dsbsxgxc.js";var i=class{retainProof(){return!0}constructor(e){this.retainProof(),this.tenantId=e.tenantId,this.principalId=e.principalId,this.capabilityId=e.capabilityId,this.operationId=e.operationId,this.operation=e.operation,this.digests=e.digests}};function a(e){return new i({tenantId:e.tenantId,principalId:e.principalId,capabilityId:e.capabilityId,operationId:e.operationId,operation:e.operation,digests:{laneDigest:e.digests.laneDigest,intentDigest:e.digests.intentDigest,displayDigest:e.digests.displayDigest}})}function o(t){return`seams:authorization:capability-operation-fingerprint:v1|${e({tenantId:t.tenantId,principalId:t.principalId,capabilityId:t.capabilityId,operationId:t.operationId,operation:t.operation,digests:t.digests})}`}async function s(e){return c(n(await t(o(e))))}function c(e){return r(e)}function l(e){if(typeof e!=`string`||!e.startsWith(`sha256:`))throw Error(`signing operation fingerprint must use the sha256: prefix`);return r(e.slice(7))}export{s as n,l as r,a as t};
@@ -0,0 +1 @@
1
+ import{M as e,O as t,T as n,b as r,c as i,d as a,j as o,k as s,l as c,u as ee,v as l,x as u}from"./domainIds-BzkGsRqO.js";import{k as d}from"./chains-C_X_fNuS.js";import{_ as f,a as p,c as m,i as te,n as h,r as g,s as _,t as v}from"./primitives-CqrjmIAH.js";import{l as y}from"./digestEncoding-CkUc5vtR.js";import{i as b}from"./registrationIds-ByuReLUc.js";const x=`wallet_seed_parallel_hkdf_sha256_v1`;function ne(e){return e.kind===`wallet_custody_seed_v1`}function S(){return{kind:`wallet_custody_seed_v1`,derivationScheme:x}}function C(e){return{kind:`ed25519_yao_client_root_v1`,linkSessionId:e.linkSessionId,walletKeyId:e.walletKeyId,targetFactor:e.targetFactor,applicationBindingDigestB64u:e.applicationBindingDigestB64u,registeredPublicKeyB64u:e.registeredPublicKeyB64u,enrollmentId:e.enrollmentId,deviceId:e.deviceId,revocationEpoch:e.revocationEpoch}}function re(e){return{kind:`ed25519_lane_holder_share_v1`,walletKeyId:e.walletKeyId,laneId:e.laneId,laneShareEpoch:e.laneShareEpoch,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,registeredPublicKeyB64u:e.registeredPublicKeyB64u,participantBindingDigestB64u:e.participantBindingDigestB64u}}function ie(e){return{kind:`ecdsa_lane_holder_share_v1`,walletKeyId:e.walletKeyId,laneId:e.laneId,laneShareEpoch:e.laneShareEpoch,evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,thresholdSessionId:e.thresholdSessionId,thresholdPublicKey33B64u:e.thresholdPublicKey33B64u}}const w=[`kind`,`walletKeyId`,`laneId`,`laneShareEpoch`],T={wallet_custody_seed_v1:[`kind`,`derivationScheme`],ed25519_yao_client_root_v1:[`kind`,`linkSessionId`,`walletKeyId`,`targetFactor`,`applicationBindingDigestB64u`,`registeredPublicKeyB64u`,`enrollmentId`,`deviceId`,`revocationEpoch`],ed25519_lane_holder_share_v1:[...w,`nearEd25519SigningKeyId`,`registeredPublicKeyB64u`,`participantBindingDigestB64u`],ecdsa_lane_holder_share_v1:[...w,`evmFamilySigningKeySlotId`,`thresholdSessionId`,`thresholdPublicKey33B64u`]},ae=Array.from(new Set(Object.values(T).flat()));function E(e,t){if(e===`wallet_custody_seed_v1`||e===`ed25519_yao_client_root_v1`||e===`ed25519_lane_holder_share_v1`||e===`ecdsa_lane_holder_share_v1`)return e;throw Error(`${t}.kind must be a known passkey custody secret kind`)}function D(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`${t} must be a non-negative safe integer`);return e}function O(e,t){let n=d(e,t);if(f(n,[`kind`],t),n.kind===`passkey_prf`||n.kind===`email_otp`)return{kind:n.kind};throw Error(`${t}.kind must be passkey_prf or email_otp`)}function k(e,t){let n=s(e.walletKeyId);if(!n.ok)throw Error(`${t}.walletKeyId ${n.error.message}`);let a=r(e.laneId);if(!a.ok)throw Error(`${t}.laneId ${a.error.message}`);let o=i(e.laneShareEpoch);if(!o.ok)throw Error(`${t}.laneShareEpoch ${o.error.message}`);return{walletKeyId:n.value,laneId:a.value,laneShareEpoch:o.value}}function A(e,t){let n=u(e);if(!n.ok)throw Error(`${t} ${n.error.message}`);return n.value}function j(e,t=`passkeyCustodySecretBinding`){let n=d(e,t),r=E(n.kind,t);switch(f(n,T[r],t,ae),r){case`wallet_custody_seed_v1`:if(n.derivationScheme!==x)throw Error(`${t}.derivationScheme must be ${x}`);return S();case`ed25519_yao_client_root_v1`:{let e=c(n.linkSessionId);if(!e.ok)throw Error(`${t}.linkSessionId ${e.error.message}`);let r=s(n.walletKeyId);if(!r.ok)throw Error(`${t}.walletKeyId ${r.error.message}`);let i=ee(n.enrollmentId);if(!i.ok)throw Error(`${t}.enrollmentId ${i.error.message}`);let o=a(n.deviceId);if(!o.ok)throw Error(`${t}.deviceId ${o.error.message}`);return C({linkSessionId:e.value,walletKeyId:r.value,targetFactor:O(n.targetFactor,`${t}.targetFactor`),applicationBindingDigestB64u:v(n.applicationBindingDigestB64u,`${t}.applicationBindingDigestB64u`),registeredPublicKeyB64u:h(n.registeredPublicKeyB64u,`${t}.registeredPublicKeyB64u`),enrollmentId:i.value,deviceId:o.value,revocationEpoch:D(n.revocationEpoch,`${t}.revocationEpoch`)})}case`ed25519_lane_holder_share_v1`:{let e=k(n,t);return re({walletKeyId:e.walletKeyId,laneId:e.laneId,laneShareEpoch:e.laneShareEpoch,nearEd25519SigningKeyId:b(n.nearEd25519SigningKeyId),registeredPublicKeyB64u:h(n.registeredPublicKeyB64u,`${t}.registeredPublicKeyB64u`),participantBindingDigestB64u:v(n.participantBindingDigestB64u,`${t}.participantBindingDigestB64u`)})}case`ecdsa_lane_holder_share_v1`:{let e=k(n,t);return ie({walletKeyId:e.walletKeyId,laneId:e.laneId,laneShareEpoch:e.laneShareEpoch,evmFamilySigningKeySlotId:y(n.evmFamilySigningKeySlotId,`${t}.evmFamilySigningKeySlotId`),thresholdSessionId:A(n.thresholdSessionId,`${t}.thresholdSessionId`),thresholdPublicKey33B64u:_(n.thresholdPublicKey33B64u,`${t}.thresholdPublicKey33B64u`)})}}}const M=`wallet_custody_envelope_v2`,N=`passkey_prf_kek_hkdf_sha256_v1`,P=`email_otp_factor_kek_hkdf_sha256_v1`,F=[`kind`,`walletAuthMethodId`];function I(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);let r=e;switch(f(r,F,t),r.kind){case`unbound`:if(r.walletAuthMethodId!==void 0)throw Error(`${t}.walletAuthMethodId belongs to the method_bound branch`);return{kind:`unbound`};case`method_bound`:{let e=n(r.walletAuthMethodId);if(!e.ok)throw Error(`${t}.walletAuthMethodId ${e.error.message}`);return{kind:`method_bound`,walletAuthMethodId:e.value}}default:throw Error(`${t}.kind must be unbound or method_bound`)}}function L(e){return JSON.stringify({walletId:e.walletId,envelopeId:e.envelopeId,factor:e.factor,envelopeRevision:e.envelopeRevision,binding:e.binding,ownership:z(e.ownership)})}function R(e,t){if(e===`unbound`)return{kind:`unbound`};if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be "unbound" or a methodBound object`);let r=e;f(r,[`methodBound`],t);let i=r.methodBound;if(typeof i!=`object`||!i||Array.isArray(i))throw Error(`${t}.methodBound must be an object`);let a=i;f(a,[`walletAuthMethodId`],`${t}.methodBound`);let o=n(a.walletAuthMethodId);if(!o.ok)throw Error(`${t}.methodBound.walletAuthMethodId ${o.error.message}`);return{kind:`method_bound`,walletAuthMethodId:o.value}}function z(e){switch(e.kind){case`unbound`:return`unbound`;case`method_bound`:return{methodBound:{walletAuthMethodId:String(e.walletAuthMethodId)}};default:throw Error(`Unhandled custody envelope ownership: ${String(e)}`)}}function B(e){return{kind:`method_bound`,walletAuthMethodId:e}}function V(e){return{kind:`passkey`,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u,kekVersion:N}}function H(e){return{kind:`email_otp`,enrollmentId:e.enrollmentId,enrollmentSealKeyVersion:e.enrollmentSealKeyVersion,kekVersion:P}}function U(e){return{state:`active`,activatedAtMs:e.activatedAtMs}}function W(e){return{state:`retired`,activatedAtMs:e.activatedAtMs,retiredAtMs:e.retiredAtMs}}function G(e){return{state:`revoked`,activatedAtMs:e.activatedAtMs,revokedAtMs:e.revokedAtMs}}function K(e){return{kind:`wallet_custody_envelope_v2`,envelopeId:e.envelopeId,walletId:e.walletId,ownership:e.ownership,binding:e.binding,factor:e.factor,envelopeVersion:M,envelopeRevision:e.envelopeRevision,nonceB64u:e.nonceB64u,sealedCustodySecretB64u:e.sealedCustodySecretB64u,ciphertextDigestB64u:e.ciphertextDigestB64u,aadHashB64u:e.aadHashB64u,lifecycle:e.lifecycle,createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs}}const q=[`state`,`activatedAtMs`,`retiredAtMs`,`revokedAtMs`];function J(e,t=`lifecycle`){let n=d(e,t);f(n,q,t);let r=m(n.activatedAtMs,`${t}.activatedAtMs`);switch(n.state){case`active`:if(n.retiredAtMs!==void 0||n.revokedAtMs!==void 0)throw Error(`${t} cannot be active and carry a retired or revoked timestamp`);return U({activatedAtMs:r});case`retired`:{if(n.revokedAtMs!==void 0)throw Error(`${t} cannot be retired and carry a revoked timestamp`);let e=m(n.retiredAtMs,`${t}.retiredAtMs`);if(e<r)throw Error(`${t}.retiredAtMs cannot precede activation`);return W({activatedAtMs:r,retiredAtMs:e})}case`revoked`:{if(n.retiredAtMs!==void 0)throw Error(`${t} cannot be revoked and carry a retired timestamp`);let e=m(n.revokedAtMs,`${t}.revokedAtMs`);if(e<r)throw Error(`${t}.revokedAtMs cannot precede activation`);return G({activatedAtMs:r,revokedAtMs:e})}default:throw Error(`${t}.state must be active, retired, or revoked`)}}const Y=[`kind`,`rpId`,`credentialIdB64u`,`kekVersion`],X=[`kind`,`enrollmentId`,`enrollmentSealKeyVersion`,`kekVersion`],Z=Array.from(new Set([...Y,...X]));function Q(e,t){if(typeof e!=`string`||!e.trim())throw Error(`${t} is required`);return e}function oe(t,n=`factor`){let r=d(t,n);switch(r.kind){case`passkey`:{if(f(r,Y,n,Z),r.kekVersion!==N)throw Error(`${n}.kekVersion must be ${N}`);let t=e(r.rpId);if(!t.ok)throw Error(`${n}.rpId ${t.error.message}`);let i=o(r.credentialIdB64u);if(!i.ok)throw Error(`${n}.credentialIdB64u ${i.error.message}`);return V({rpId:t.value,credentialIdB64u:i.value})}case`email_otp`:if(f(r,X,n,Z),r.kekVersion!==P)throw Error(`${n}.kekVersion must be ${P}`);return H({enrollmentId:Q(r.enrollmentId,`${n}.enrollmentId`),enrollmentSealKeyVersion:Q(r.enrollmentSealKeyVersion,`${n}.enrollmentSealKeyVersion`)});default:throw Error(`${n}.kind must be passkey or email_otp`)}}const se=[`kind`,`envelopeId`,`walletId`,`ownership`,`binding`,`factor`,`envelopeVersion`,`envelopeRevision`,`nonceB64u`,`sealedCustodySecretB64u`,`ciphertextDigestB64u`,`aadHashB64u`,`lifecycle`,`createdAtMs`,`updatedAtMs`];function ce(e,n=`walletCustodyEnvelope`){let r=d(e,n);if(r.kind!==`wallet_custody_envelope_v2`)throw Error(`${n}.kind must be ${M}`);if(f(r,se,n),r.envelopeVersion!==`wallet_custody_envelope_v2`)throw Error(`${n}.envelopeVersion must be ${M}`);let i=l(r.envelopeId);if(!i.ok)throw Error(`${n}.envelopeId ${i.error.message}`);let a=t(r.walletId);if(!a.ok)throw Error(`${n}.walletId ${a.error.message}`);let o=I(r.ownership,`${n}.ownership`),s=m(r.createdAtMs,`${n}.createdAtMs`),c=m(r.updatedAtMs,`${n}.updatedAtMs`);if(c<s)throw Error(`${n}.updatedAtMs cannot precede createdAtMs`);return K({envelopeId:i.value,walletId:a.value,ownership:o,binding:j(r.binding,`${n}.binding`),factor:oe(r.factor,`${n}.factor`),envelopeRevision:p(r.envelopeRevision,`${n}.envelopeRevision`),nonceB64u:te(r.nonceB64u,`${n}.nonceB64u`),sealedCustodySecretB64u:g(r.sealedCustodySecretB64u,`${n}.sealedCustodySecretB64u`),ciphertextDigestB64u:v(r.ciphertextDigestB64u,`${n}.ciphertextDigestB64u`),aadHashB64u:v(r.aadHashB64u,`${n}.aadHashB64u`),lifecycle:J(r.lifecycle,`${n}.lifecycle`),createdAtMs:s,updatedAtMs:c})}function le(e,t){return e.kind===t.kind?e.kind===`unbound`?!0:t.kind===`method_bound`&&String(e.walletAuthMethodId)===String(t.walletAuthMethodId):!1}function $(e){if(!e.establishedCustody)throw Error(`only a custody-establishing commit issues recovery codes`);return{...e,recoveryBackupAcknowledged:!0}}function ue(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} walletCustody must be an object`);let n=e;switch(n.status){case`not_requested`:case`committed`:case`custody_already_established`:return{status:n.status};case`joined`:{let e=n.keyManifestDigestB64u;if(typeof e!=`string`||!e)throw Error(`${t} joined custody carries no key manifest digest`);return{status:`joined`,keyManifestDigestB64u:e}}case`rejected`:{let e=n.reason;if(typeof e!=`string`||!e)throw Error(`${t} rejected custody carries no reason`);return{status:`rejected`,reason:e}}default:throw Error(`${t} walletCustody status is unrecognised`)}}export{H as a,V as c,ce as d,R as f,ne as h,U as i,L as l,C as m,$ as n,B as o,le as p,M as r,K as s,ue as t,z as u};
@@ -1 +1 @@
1
- import{a as e,t}from"./singletons-8UH3gOnZ.js";import{p as n}from"./wallet-recovery-C1kesLCF.js";import{t as r}from"./surface-measurement-reporter-IlPOI3QK.js";const i=`Recovery-code backup was cancelled before acknowledgement`;async function a(e,t={kind:`disabled`},n={}){if(typeof document>`u`)throw Error(`Wallet recovery-code backup requires a browser or a backup handler`);let a=document.activeElement instanceof HTMLElement?document.activeElement:null;if(n.shouldCancel?.())throw Error(i);let o=await import(`./mountRecoveryCodeBackupSurface-B1qhFF6G.js`);if(n.shouldCancel?.())throw Error(i);let s=null,l=null,u=!1;return await new Promise((d,f)=>{let p=()=>{s?.disconnect(),s=null,l?.dispose(),l=null,a?.focus()},m=e=>{u||(u=!0,p(),e instanceof Error?f(e):d(e))},h=t=>{switch(t.kind){case`dismissed`:m(Error(i));return;case`recovery_codes`:if(t.acknowledged){m({kind:`wallet_recovery_codes_backed_up_v1`});return}if(e.kind===`direct_backup`&&e.request.continuation===`registration_may_defer`){m({kind:`wallet_recovery_code_backup_deferred_v1`});return}m(Error(i));return}};try{l=o.mountRecoveryCodeBackupSurface({parent:document.body,appearance:n.appearance,experience:e,surface:t.kind===`wallet_iframe`?`wallet-iframe`:`standalone`,onClose:h,onCancel:()=>m(Error(i)),onShown:e=>{u||t.kind!==`wallet_iframe`||(s=r({kind:`request_scroll_surface`,requestId:t.requestId,element:e,postMeasurement:c.bind(null,e,t.postMeasurement)}))}})}catch(e){m(e instanceof Error?e:Error(String(e)))}})}async function o(e,t={kind:`disabled`}){return await a({kind:`direct_backup`,request:e},t)}async function s(e,t={kind:`disabled`},n={}){return await a({kind:`account_menu`,...e},t,n)}function c(e,t,n){if(n.kind!==`measured_v1`)throw Error(`Recovery codes require a request surface measurement`);t({kind:`measured_v1`,requestId:n.requestId,sequence:n.sequence,widthCssPx:e.dataset.seamsRecoveryStage===`recovery_codes`?688:480,heightCssPx:n.heightCssPx})}const l=`wallet_recovery_codes_v1`,u=[`record_version`,`wallet_id`,`enrollment_id`,`recovery_codes_issued_at_ms`,`status`,`key`,`iv`,`ciphertext`];function d(e){return typeof CryptoKey<`u`&&e instanceof CryptoKey&&e.type===`secret`&&!e.extractable&&e.algorithm.name===`AES-GCM`&&e.usages.includes(`encrypt`)&&e.usages.includes(`decrypt`)}function f(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=new Map(Object.entries(e)),n=new Set(u);return t.size!==n.size||[...t.keys()].some(e=>!n.has(e))?null:{record_version:t.get(`record_version`),wallet_id:t.get(`wallet_id`),enrollment_id:t.get(`enrollment_id`),recovery_codes_issued_at_ms:t.get(`recovery_codes_issued_at_ms`),status:t.get(`status`),key:t.get(`key`),iv:t.get(`iv`),ciphertext:t.get(`ciphertext`)}}function p(e,t){let n=f(e);if(!n)return null;let r=Number(n.recovery_codes_issued_at_ms);return n.record_version!==1||n.wallet_id!==t||n.enrollment_id!==l||n.status!==`pending`||!Number.isSafeInteger(r)||r<=0||!d(n.key)||!(n.iv instanceof Uint8Array)||n.iv.byteLength!==12||!(n.ciphertext instanceof Uint8Array)||n.ciphertext.byteLength===0?null:{record_version:1,wallet_id:t,enrollment_id:l,recovery_codes_issued_at_ms:r,status:`pending`,key:n.key,iv:n.iv,ciphertext:n.ciphertext}}function m(e,t){return new TextEncoder().encode(JSON.stringify({kind:l,walletId:e,issuedAtMs:t}))}function h(e){return[e,l]}const g=new class{async write(r){let i=r.walletId.trim();if(!i)throw Error(`Pending recovery-code backup requires a wallet`);let a=n(r.recoveryCodes.map(String)),o=r.issuedAtMs??Date.now();if(!Number.isSafeInteger(o)||o<=0)throw Error(`Pending recovery-code backup issue time is invalid`);let s=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]),c=crypto.getRandomValues(new Uint8Array(12)),u=m(i,o),d=new TextEncoder().encode(JSON.stringify(a)),f=null;try{f=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:c,additionalData:u},s,d)),await t.runTransaction([e.pendingWalletRecoveryCodeBackups],`readwrite`,async t=>{await t.store(e.pendingWalletRecoveryCodeBackups).put({record_version:1,wallet_id:i,enrollment_id:l,recovery_codes_issued_at_ms:o,status:`pending`,key:s,iv:c,ciphertext:f})})}finally{u.fill(0),d.fill(0),f?.fill(0)}}async read(r){let i=r.trim();if(!i)return null;let a=p(await(await t.getDB()).get(e.pendingWalletRecoveryCodeBackups,h(i)),i);if(!a)return null;let o=m(i,a.recovery_codes_issued_at_ms),s=null;try{s=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.iv,additionalData:o},a.key,a.ciphertext));let e=JSON.parse(new TextDecoder().decode(s));if(!Array.isArray(e))throw Error(`Pending recovery-code backup is invalid`);return{walletId:i,recoveryCodes:n(e.map(String))}}finally{o.fill(0),s?.fill(0)}}async has(n){let r=n.trim();return r?p(await(await t.getDB()).get(e.pendingWalletRecoveryCodeBackups,h(r)),r)!==null:!1}async delete(n){let r=n.trim();r&&await t.runTransaction([e.pendingWalletRecoveryCodeBackups],`readwrite`,async t=>{await t.store(e.pendingWalletRecoveryCodeBackups).delete(h(r))})}};export{o as n,s as r,g as t};
1
+ import{a as e,t}from"./singletons-8UH3gOnZ.js";import{p as n}from"./wallet-recovery-D7ywcIHw.js";import{t as r}from"./surface-measurement-reporter-DvVHPu_O.js";const i=`Recovery-code backup was cancelled before acknowledgement`;async function a(e,t={kind:`disabled`},n={}){if(typeof document>`u`)throw Error(`Wallet recovery-code backup requires a browser or a backup handler`);let a=document.activeElement instanceof HTMLElement?document.activeElement:null;if(n.shouldCancel?.())throw Error(i);let o=await import(`./mountRecoveryCodeBackupSurface-BA2ttbTM.js`);if(n.shouldCancel?.())throw Error(i);let s=null,l=null,u=!1;return await new Promise((d,f)=>{let p=()=>{s?.disconnect(),s=null,l?.dispose(),l=null,a?.focus()},m=e=>{u||(u=!0,p(),e instanceof Error?f(e):d(e))},h=t=>{switch(t.kind){case`dismissed`:m(Error(i));return;case`recovery_codes`:if(t.acknowledged){m({kind:`wallet_recovery_codes_backed_up_v1`});return}if(e.kind===`direct_backup`&&e.request.continuation===`registration_may_defer`){m({kind:`wallet_recovery_code_backup_deferred_v1`});return}m(Error(i));return}};try{l=o.mountRecoveryCodeBackupSurface({parent:document.body,appearance:n.appearance,experience:e,surface:t.kind===`wallet_iframe`?`wallet-iframe`:`standalone`,onClose:h,onCancel:()=>m(Error(i)),onShown:e=>{u||t.kind!==`wallet_iframe`||(s=r({kind:`request_scroll_surface`,requestId:t.requestId,element:e,postMeasurement:c.bind(null,e,t.postMeasurement)}))}})}catch(e){m(e instanceof Error?e:Error(String(e)))}})}async function o(e,t={kind:`disabled`}){return await a({kind:`direct_backup`,request:e},t)}async function s(e,t={kind:`disabled`},n={}){return await a({kind:`account_menu`,...e},t,n)}function c(e,t,n){if(n.kind!==`measured_v1`)throw Error(`Recovery codes require a request surface measurement`);t({kind:`measured_v1`,requestId:n.requestId,sequence:n.sequence,widthCssPx:e.dataset.seamsRecoveryStage===`recovery_codes`?688:480,heightCssPx:n.heightCssPx})}const l=`wallet_recovery_codes_v1`,u=[`record_version`,`wallet_id`,`enrollment_id`,`recovery_codes_issued_at_ms`,`status`,`key`,`iv`,`ciphertext`];function d(e){return typeof CryptoKey<`u`&&e instanceof CryptoKey&&e.type===`secret`&&!e.extractable&&e.algorithm.name===`AES-GCM`&&e.usages.includes(`encrypt`)&&e.usages.includes(`decrypt`)}function f(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=new Map(Object.entries(e)),n=new Set(u);return t.size!==n.size||[...t.keys()].some(e=>!n.has(e))?null:{record_version:t.get(`record_version`),wallet_id:t.get(`wallet_id`),enrollment_id:t.get(`enrollment_id`),recovery_codes_issued_at_ms:t.get(`recovery_codes_issued_at_ms`),status:t.get(`status`),key:t.get(`key`),iv:t.get(`iv`),ciphertext:t.get(`ciphertext`)}}function p(e,t){let n=f(e);if(!n)return null;let r=Number(n.recovery_codes_issued_at_ms);return n.record_version!==1||n.wallet_id!==t||n.enrollment_id!==l||n.status!==`pending`||!Number.isSafeInteger(r)||r<=0||!d(n.key)||!(n.iv instanceof Uint8Array)||n.iv.byteLength!==12||!(n.ciphertext instanceof Uint8Array)||n.ciphertext.byteLength===0?null:{record_version:1,wallet_id:t,enrollment_id:l,recovery_codes_issued_at_ms:r,status:`pending`,key:n.key,iv:n.iv,ciphertext:n.ciphertext}}function m(e,t){return new TextEncoder().encode(JSON.stringify({kind:l,walletId:e,issuedAtMs:t}))}function h(e){return[e,l]}const g=new class{async write(r){let i=r.walletId.trim();if(!i)throw Error(`Pending recovery-code backup requires a wallet`);let a=n(r.recoveryCodes.map(String)),o=r.issuedAtMs??Date.now();if(!Number.isSafeInteger(o)||o<=0)throw Error(`Pending recovery-code backup issue time is invalid`);let s=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]),c=crypto.getRandomValues(new Uint8Array(12)),u=m(i,o),d=new TextEncoder().encode(JSON.stringify(a)),f=null;try{f=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:c,additionalData:u},s,d)),await t.runTransaction([e.pendingWalletRecoveryCodeBackups],`readwrite`,async t=>{await t.store(e.pendingWalletRecoveryCodeBackups).put({record_version:1,wallet_id:i,enrollment_id:l,recovery_codes_issued_at_ms:o,status:`pending`,key:s,iv:c,ciphertext:f})})}finally{u.fill(0),d.fill(0),f?.fill(0)}}async read(r){let i=r.trim();if(!i)return null;let a=p(await(await t.getDB()).get(e.pendingWalletRecoveryCodeBackups,h(i)),i);if(!a)return null;let o=m(i,a.recovery_codes_issued_at_ms),s=null;try{s=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.iv,additionalData:o},a.key,a.ciphertext));let e=JSON.parse(new TextDecoder().decode(s));if(!Array.isArray(e))throw Error(`Pending recovery-code backup is invalid`);return{walletId:i,recoveryCodes:n(e.map(String))}}finally{o.fill(0),s?.fill(0)}}async has(n){let r=n.trim();return r?p(await(await t.getDB()).get(e.pendingWalletRecoveryCodeBackups,h(r)),r)!==null:!1}async delete(n){let r=n.trim();r&&await t.runTransaction([e.pendingWalletRecoveryCodeBackups],`readwrite`,async t=>{await t.store(e.pendingWalletRecoveryCodeBackups).delete(h(r))})}};export{o as n,s as r,g as t};
@@ -0,0 +1 @@
1
+ import{B as e,V as t}from"./domainIds-BzkGsRqO.js";import{A as n,k as r}from"./primitives-CqrjmIAH.js";import{i,r as a}from"./base64-DW79QA0h.js";import{r as o}from"./secureRandomId-LwBFx84B.js";import{B as s,F as c,G as l,I as u,R as d,dt as ee,z as f}from"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{I as p,L as m,R as h}from"./ecdsaCapabilityManifest-ChszYCC0.js";import{ct as g,n as _,ut as v}from"./walletOwnershipGeneration-CAycHv-H.js";import{t as y}from"./presignatures-DZm0d6Wy.js";import{i as b,n as x,r as te,u as S}from"./trace-QLsbYdld.js";import{A as ne,C,D as re,E as ie,O as ae,S as w,T,k as E,w as oe,x as D,y as se}from"./ecdsaDerivationClientWasm-CpH-b3jx.js";import{t as O}from"./authorizationAdmission-CGinGhXH.js";import{t as k}from"./walletSessionFailure-YuhraC3P.js";import{c as ce,f as A,o as le,t as j}from"./routerAbNormalSigning-DVKFBYgV.js";import{o as M,s as ue,t as de}from"./evmCryptoWasm-DeobzyP-.js";async function fe(e){let t=e.clientShare.material;if(t.kind===`worker_loaded`)return;let n=await se({materialHandle:e.clientShare.handle.materialHandle,bindingDigest:e.clientShare.handle.bindingDigest,stateBlob:t.stateBlob,workerCtx:e.workerCtx});if(n.materialHandle!==e.clientShare.handle.materialHandle||n.bindingDigest!==e.clientShare.handle.bindingDigest)throw Error(`[multichain] ECDSA role-local worker material handle mismatch`)}async function pe(e){let t=e.signerSession,n=t.clientShare;if(n.kind===`linked_holder_worker_share`){let e=n.holderHandleId;return{signerSession:t,clientSigningMaterial:me(e),cleanupAfterSign:async()=>void 0}}let r=n;return{signerSession:t,clientSigningMaterial:{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:async t=>(await fe({workerCtx:e.workerCtx,clientShare:r}),await ae({materialHandle:r.handle.materialHandle,material:r.material.kind===`worker_loaded`?{kind:`persisted`,materialRef:r.material.materialRef}:{kind:`runtime_loaded`,expectedBindingDigest:r.handle.bindingDigest},...t})),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`role_local_derivation_handle`),computeSignatureShareFromPresignatureHandle:T},cleanupAfterSign:async()=>void 0}}async function N(e,t){return await D({holderHandleId:e,...t})}function me(e){return{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:N.bind(void 0,e),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`linked_holder_signing_material`),computeSignatureShareFromPresignatureHandle:T}}function P(e,t,n,r){let i=Math.floor(Number(e));return Number.isFinite(i)?i<n?n:i>r?r:i:t}function he(e,t){return P(e,t,1,5)}function ge(e,t,n){return P(e,t,0,n)}function _e(e){let t=e||A,n=he(t.targetDepth,A.targetDepth),r=ge(t.lowWatermark,A.lowWatermark,n);return{enabled:typeof t.enabled==`boolean`?t.enabled:A.enabled,targetDepth:n,lowWatermark:r,maxRefillInFlight:P(t.maxRefillInFlight,A.maxRefillInFlight,1,8),refillAttemptTimeoutMs:P(t.refillAttemptTimeoutMs,A.refillAttemptTimeoutMs,5e3,12e4)}}function ve(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:2e4}function ye(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||``)}function be(e){return Error(`[router-ab-ecdsa-derivation] ${e.operation} request timed out after ${e.timeoutMs}ms`)}async function xe(e){let t=ve(e.timeoutMs),r=typeof AbortController==`function`?new AbortController:null,i={...e.init},a=null,o=null,s=!1;try{let c;if(r){let l=e.init.signal;if(l){if(l.aborted)r.abort();else if(typeof l.addEventListener==`function`){let e=()=>r.abort();l.addEventListener(`abort`,e,{once:!0}),o=()=>l.removeEventListener(`abort`,e)}}a=setTimeout(()=>{s=!0,r.abort()},t),c=await n(new Request(e.url,{...i,signal:r.signal}))}else c=await Promise.race([n(new Request(e.url,i)),new Promise((n,r)=>{a=setTimeout(()=>{s=!0,r(be({operation:e.operation,timeoutMs:t}))},t)})]);let l=await c.json().catch(()=>({}));if(s)throw be({operation:e.operation,timeoutMs:t});return{response:c,data:l}}catch(n){if(s)throw be({operation:e.operation,timeoutMs:t});let r=ye(n);throw Error(r||`[router-ab-ecdsa-derivation] ${e.operation} request failed`)}finally{a&&clearTimeout(a),o?.()}}const Se=5e3;function Ce(e,t){let n=Math.min(e-Date.now(),t??Se,Se);return Number.isFinite(n)&&n>0?n:null}function we(n){return t(e(n))||null}function Te(e){let t={"Content-Type":`application/json`};switch(e.credential.kind){case`operation_step_up`:return{ok:!0,headers:t,credentials:`omit`};case`wallet_session_opaque`:{let n=String(e.credential.walletSessionToken||``).trim();return n?(Object.assign(t,r({token:n,home:e.credential.home})),{ok:!0,headers:t,credentials:`omit`}):{ok:!1,code:`invalid_args`,message:`Missing opaque Wallet Session token for Router A/B ECDSA derivation presign pool fill`}}}}function Ee(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function De(e){let t=String(e.keyHandle||``).trim();return t?{ok:!0,value:{keyHandle:t}}:{ok:!1,code:`invalid_args`,message:`Missing keyHandle for Router A/B ECDSA derivation pool-fill init`}}async function Oe(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill init`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill init`};let n=De(e);if(!n.ok)return n;let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.poolFill.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/init`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({...n.value,count:Number.isFinite(e.count)?Math.max(1,Math.floor(Number(e.count))):1,...r?{requestTag:r}:{},poolFill:e.poolFill,presignSessionId:e.presignSessionId,firstMessageB64u:e.firstMessageB64u,...Ee(e)})}});return typeof s.presignSessionId==`string`&&x(s.presignSessionId,`init`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,presignSessionId:s.presignSessionId,...Number.isSafeInteger(s.ceremonyExpiresAtMs)?{ceremonyExpiresAtMs:s.ceremonyExpiresAtMs}:{},...Number.isSafeInteger(s.materialExpiresAtMs)?{materialExpiresAtMs:s.materialExpiresAtMs}:{},stage:s.stage,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill init`)}}}async function ke(e){return Oe({...e,path:c})}async function Ae(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill step`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill step`};let n=String(e.presignSessionId||``).trim();if(!n)return{ok:!1,code:`invalid_args`,message:`Missing presignSessionId for Router A/B ECDSA derivation pool-fill step`};let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/step`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({presignSessionId:n,ceremonyExpiresAtMs:e.ceremonyExpiresAtMs,materialExpiresAtMs:e.materialExpiresAtMs,stage:e.stage,outgoingMessagesB64u:Array.isArray(e.outgoingMessagesB64u)?e.outgoingMessagesB64u:[],...r?{requestTag:r}:{},...Ee(e)})}});return x(n,`step`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,stage:s.stage,event:s.event,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.presignatureId?{presignatureId:s.presignatureId}:{},...s.bigRB64u?{bigRB64u:s.bigRB64u}:{},...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill step`)}}}async function je(e){return Ae({...e,path:u})}var Me=class{constructor(){this.state={kind:`refilling`,revision:0},this.waiters=new Map}snapshot(){return this.state}hasForegroundWaiters(){for(let e of this.waiters.values())if(e===`foreground`)return!0;return!1}publishAvailable(){this.state.kind!==`settled`&&(this.state={kind:`refilling`,revision:this.state.revision+1},this.flushWaiters())}settle(){this.state.kind!==`settled`&&(this.state={kind:`settled`,revision:this.state.revision},this.flushWaiters())}waitForChange(e,t){return this.state.kind===`settled`||this.state.revision!==e.revision?Promise.resolve(this.state):new Promise(n=>{this.waiters.set(n,t),(this.state.kind===`settled`||this.state.revision!==e.revision)&&(this.waiters.delete(n),n(this.state))})}flushWaiters(){let e=this.state,t=[...this.waiters.keys()];this.waiters.clear();for(let n of t)n(e)}};function Ne(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`WebCrypto getRandomValues is required for ECDSA rerandomization`);return e.getRandomValues(new Uint8Array(32))}function F(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function Pe(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||`signature recovery failed`)}function I(e){e instanceof Uint8Array&&e.fill(0)}function Fe(e){if(e?.kind!==`router_ab_ecdsa_derivation_client_signing_material_source_v1`)throw Error(`Router A/B ECDSA derivation client signing material source is required`)}const Ie=6e4,L=new Map,R=new Map,z=new Map,B=new Map,V=new Map,H=new Map;function Le(e){return e===`triples_done`||e===`presign`||e===`done`}function Re(e){return Le(e.clientStage)&&Le(e.serverStage)?`presign`:`triples`}function ze(e){let t=L.get(e);if(!t?.length)return null;let n=t.shift()??null;return t.length?L.set(e,t):L.delete(e),n}async function U(e){return await Ue(e),ze(e.poolKey)}function Be(e,t,n){if(!K(n))return`invalid`;let r=L.get(e)||[];for(let e of r)if(e.materialHandle===n.materialHandle)return`duplicate`;return r.filter(e=>K(e)).length>=5?`capacity_full`:(r.push(n),L.set(e,r),R.set(e,t),`stored`)}function Ve(e,t=Date.now()){let n=L.get(e);if(!n?.length)return[];let r=[],i=[];for(let e of n)K(e,t)?r.push(e):i.push(e);return r.length>0?L.set(e,r):L.delete(e),i}async function He(e){for(let t of e.refs)await e.clientSigningMaterial.destroyClientPresignature({materialHandle:t.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}async function Ue(e){await He({refs:Ve(e.poolKey),poolIdentity:e.poolIdentity,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}async function W(e,t,n){try{await _(e.walletId,e.ownershipGeneration)}catch(r){throw await qe({poolIdentity:e,poolKey:g(e),clientSigningMaterial:t,workerCtx:n}),r}}async function We(e){await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx);let t=V.get(e.poolKey);if(t){await t;return}let n=Ge(e);V.set(e.poolKey,n);try{await n}finally{V.get(e.poolKey)===n&&V.delete(e.poolKey)}}async function Ge(e){await Ue(e);let t;t=await e.clientSigningMaterial.listAvailableClientPresignatures({poolIdentity:e.poolIdentity,workerCtx:e.workerCtx});try{await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(e.poolKey)!==e.generation){for(let n of t)I(n.bigR33),await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{});return}for(let n of t){let t=Be(e.poolKey,e.poolIdentity,{presignatureId:n.presignatureId,materialHandle:n.materialHandle,bigRB64u:i(n.bigR33),createdAtMs:n.createdAtMs,expiresAtMs:n.expiresAtMs});I(n.bigR33),(t===`invalid`||t===`capacity_full`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}}function G(e){let t=L.get(e);return t?t.reduce((e,t)=>e+(K(t)?1:0),0):0}function K(e,t=Date.now()){let n=Math.floor(Number(e.expiresAtMs));return!!(e.presignatureId&&e.bigRB64u&&e.materialHandle)&&Number.isSafeInteger(n)&&n>t+2e3}function q(e){let t=H.get(e);return t===void 0?(H.set(e,0),0):t}function Ke(e){Z(e);let t=q(e)+1;return H.set(e,t),t}async function qe(e){let t=L.get(e.poolKey)??[];$e(e.poolKey),await He({...e,refs:t})}function J(e){return B.get(e)||0}function Je(e){let t=J(e);B.set(e,t+1)}function Ye(e){let t=J(e);if(t<=1){B.delete(e),Q(e,0);return}B.set(e,t-1)}async function Xe(e,t){let n=z.get(e);if(!n)return;let r=n.snapshot();for(;G(e)===0&&r.kind===`refilling`;)r=await n.waitForChange(r,t)}async function Ze(e){let t=g(v({ownershipGeneration:e.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.scope,materialActivation:e.materialActivation}));return G(t)>0?!0:(await Xe(t,`background`),G(t)>0)}function Y(e,t,n){return{scheduled:!1,reason:e,depth:t,targetDepth:n}}function Qe(){let e=new Set([...X.keys(),...L.keys(),...z.keys(),...B.keys(),...H.keys()]);for(let t of e)Ke(t);L.clear(),R.clear();for(let e of z.values())e.settle();z.clear(),B.clear()}function $e(e){L.delete(e),R.delete(e),Ke(e),z.get(e)?.settle(),z.delete(e)}function et(e){let t=String(e).trim();if(!t)throw Error(`ECDSA presignature wallet id is required`);for(let[e,n]of[...R])n.walletId===t&&$e(e)}const X=new Map;function Z(e){let t=X.get(e);t&&t.timer!==null&&clearTimeout(t.timer),X.delete(e),X.size===0&&typeof window<`u`&&(window.removeEventListener(`online`,$),document.removeEventListener(`visibilitychange`,$))}function Q(e,t){let n=X.get(e);if(!n)return;n.timer!==null&&clearTimeout(n.timer);let r=n.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs-Date.now();if(r<=0||q(e)!==n.generation){Z(e);return}n.timer=setTimeout(tt,Math.min(t,r),e)}function $(){if(!(typeof document<`u`&&document.visibilityState===`hidden`))for(let e of X.keys())Q(e,0)}function tt(e){let t=X.get(e);if(!t)return;if(t.timer=null,Date.now()>=t.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs){Z(e);return}if(typeof navigator<`u`&&navigator.onLine===!1){Q(e,3e4);return}let n=at(t.input);n.scheduled||Q(e,n.depth>=n.targetDepth?3e4:5e3)}function nt(e,t){t.authorization.kind===`reusable_wallet_session`&&X.get(e)?.input!==t&&(Z(e),X.size===0&&typeof window<`u`&&(window.addEventListener(`online`,$),document.addEventListener(`visibilitychange`,$)),X.set(e,{input:t,generation:q(e),failures:0,timer:null}),Q(e,3e4))}function rt(e,t,n){let r=X.get(e);if(!(!r||r!==t)){switch(n){case`network_error`:case`internal`:case`presign_timeout`:case`temporarily_unavailable`:case`service_unavailable`:case`wallet_session_unavailable`:if(r.failures+=1,r.failures<=3)return}Z(e)}}async function it(e){let{args:t,refillInput:n,poolKey:r,poolIdentity:i,scheduledGeneration:a,targetDepth:o,refillAttemptTimeoutMs:s,progress:c}=e,l=X.get(r)??null;try{for(await We({poolKey:r,poolIdentity:i,clientSigningMaterial:t.clientSigningMaterial,workerCtx:t.workerCtx,generation:a}),G(r)>0&&c.publishAvailable();Date.now()<t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs;){if(q(r)!==a||(X.get(r)??null)!==l||G(r)>=o||J(r)>0||typeof navigator<`u`&&navigator.onLine===!1)return;let e=Math.min(Date.now()+s,t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs),i=await _t({...n,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:n.routerAbEcdsaDerivationPoolFill.scope,ceremonyExpiresAtMs:e,materialExpiresAtMs:n.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs},trafficClass:`background`});if(S(`evm-family`,{event:`ecdsa_background_refill_result`,authorization:t.authorization.kind,outcome:i.ok?`available`:`failed`,code:i.ok?null:i.code,depth:G(r),targetDepth:o}),!i.ok){rt(r,l,i.code);return}let u=X.get(r);u&&u===l&&(u.failures=0),c.publishAvailable()}}catch{rt(r,l,`internal`)}finally{c.settle(),z.get(r)===c&&z.delete(r);let e=X.get(r);if(e){let t=e.failures>0?2e3*2**e.failures:1e3;G(r)>=o&&(t=3e4),e!==l&&(t=0),Q(r,t)}}}function at(e){try{let t=_e(e.poolPolicy),n=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),r=g(n);R.set(r,n);let i=he(e.targetDepth,t.targetDepth),a=ge(e.triggerIfDepthAtOrBelow,t.lowWatermark,i),o=G(r),s=q(r);if(!t.enabled)return Y(`disabled`,o,i);if(e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs<=Date.now())return Z(r),Y(`invalid_args`,o,i);if(nt(r,e),o>a)return Y(`depth_above_trigger`,o,i);if(o>=i)return Y(`depth_at_or_above_target`,o,i);if(z.has(r)||J(r)>0)return Y(`in_flight_for_pool_key`,o,i);if(z.size>=t.maxRefillInFlight)return Y(`global_in_flight_limit`,o,i);let c={relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,clientVerifyingShareB64u:e.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)},l=new Me;return z.set(r,l),it({args:e,refillInput:c,poolKey:r,poolIdentity:n,scheduledGeneration:s,targetDepth:i,refillAttemptTimeoutMs:t.refillAttemptTimeoutMs,progress:l}),{scheduled:!0,reason:`scheduled`,depth:o,targetDepth:i}}catch{return Y(`invalid_args`,0,0)}}function ot(e){return e.map(e=>i(e))}function st(e){return Array.isArray(e)?e.map(e=>String(e||``).trim()).filter(e=>!!e).map(e=>a(e)):[]}async function ct(e){let t=String(e.thresholdEcdsaPublicKeyB64u||``).trim();if(t){let n=a(t);if(n.length!==33)throw Error(`thresholdEcdsaPublicKeyB64u must decode to 33 bytes`);return await M({publicKey33:n,workerCtx:e.workerCtx})}let n=String(e.clientVerifyingShareB64u||``).trim(),r=String(e.relayerVerifyingShareB64u||``).trim();if(!n||!r)throw Error(`Missing thresholdEcdsaPublicKeyB64u (or relayerVerifyingShareB64u fallback) for Router A/B ECDSA derivation signing`);let i=a(n),o=a(r);if(i.length!==33)throw Error(`clientVerifyingShareB64u must decode to 33 bytes`);if(o.length!==33)throw Error(`relayerVerifyingShareB64u must decode to 33 bytes`);return await de({left33:await M({publicKey33:i,workerCtx:e.workerCtx}),right33:await M({publicKey33:o,workerCtx:e.workerCtx}),workerCtx:e.workerCtx})}function lt(e){return e.trafficClass===`foreground`||z.get(e.poolKey)?.hasForegroundWaiters()?`foreground_presign_pool_refill`:`background_presign_pool_refill`}async function ut(e){for(let t=0;t<2;t+=1){let n=await dt(e);if(n.ok||!ft(n)||t===1)return n}return{ok:!1,code:`stale_session_state`,message:`Router A/B ECDSA derivation pool-fill session stayed stale after retry`}}async function dt(e){Fe(e.clientSigningMaterial);let t=performance.now(),n=e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs,r=e.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs,a=`ecdsa-presign-v2:${n}:${i(crypto.getRandomValues(new Uint8Array(32)))}`,o=a,s=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),c=null,l=null,u=null,d=null,ee=!1,f=`triples`,p=[],m=!0,h=!1;try{let t=await e.clientSigningMaterial.initClientPresignSession({sessionId:o,groupPublicKey33:e.groupPublicKey33,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,poolIdentity:s,workerCtx:e.workerCtx});if(t.stage!==`triples`||t.outgoingMessages.length!==1)return{ok:!1,code:`presign_init_failed`,message:`Client presign init must emit exactly one first message`};f=t.stage;let g=await ke({relayerUrl:e.relayerUrl,...e.poolFillInitKeySelector,count:1,presignSessionId:a,firstMessageB64u:i(t.outgoingMessages[0]),credential:e.credential,requestTag:lt(e),poolFill:e.routerAbEcdsaDerivationPoolFill,...F(e)});if(!g.ok)return{ok:!1,code:g.code||`presign_init_failed`,message:g.message||`Presign initialization failed`};if(g.presignSessionId!==a||g.ceremonyExpiresAtMs!==n||g.materialExpiresAtMs!==r||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Presign initialization changed the bound identity or deadlines`};let _=g.stage||`triples`,v=st(g.outgoingMessagesB64u);for(let t=0;t<64;t++){if(v.length>0&&!c){let t=await e.clientSigningMaterial.stepClientPresignSession({sessionId:o,stage:Re({clientStage:f,serverStage:_}),incomingMessages:v,workerCtx:e.workerCtx});f=t.stage,v=[],p.push(...t.outgoingMessages),t.presignatureHandle&&t.presignatureBigR33&&(c=t.presignatureHandle,l=t.presignatureBigR33)}if(!ee){let i=performance.now(),o=lt(e),s={relayerUrl:e.relayerUrl,presignSessionId:a,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,stage:Re({clientStage:f,serverStage:_}),outgoingMessagesB64u:ot(p),credential:e.credential,requestTag:o,...F(e)},c=await je(s);if(S(`evm-family`,{event:`ecdsa_presignature_round`,requestTag:o,presignSessionId:a,authorization:e.authorization.kind,round:t,stage:s.stage,durationMs:performance.now()-i,outcome:c.ok?`succeeded`:`failed`}),p=[],!c.ok)return{ok:!1,code:c.code||`presign_step_failed`,message:c.message||`Router A/B ECDSA derivation pool-fill step failed`};v=st(c.outgoingMessagesB64u),_=c.stage||_,c.event===`presign_done`&&(u=String(c.presignatureId||``).trim()||null,d=String(c.bigRB64u||``).trim()||null,ee=!0)}if(c&&l&&u&&d)break}if(!c||!l)return{ok:!1,code:`presign_timeout`,message:`Client presign session did not reach done state`};if(!u||!d)return{ok:!1,code:`presign_timeout`,message:`Server presign session did not reach done state`};if(l.length!==33)return{ok:!1,code:`internal`,message:`Invalid local presignature bigR bytes (expected 33, got ${l.length})`};try{let t=Date.now(),n=i(l);if(n!==d)return{ok:!1,code:`presign_mismatch`,message:`Client/server presignature mismatch (bigR mismatch)`};let a=await e.clientSigningMaterial.admitClientPresignature({materialHandle:c,expectedPresignatureId:u,poolIdentity:s,admissionMode:e.authorization.kind===`operation_step_up`?`resident`:`durable`,workerCtx:e.workerCtx});return a.kind===`discarded_capacity`?{ok:!1,code:`pool_full`,message:`Router A/B ECDSA derivation client presignature pool is full`}:a.kind===`discarded_ambiguous`?{ok:!1,code:`presign_failed`,message:`Router A/B ECDSA derivation client presignature admission was ambiguous`}:(h=!0,m=!1,{ok:!0,kind:`available`,presignature:{presignatureId:u,bigRB64u:n,materialHandle:c,createdAtMs:t,expiresAtMs:r}})}finally{I(l)}}catch(e){return{ok:!1,code:`presign_failed`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation pool-fill handshake failed`)}}finally{S(`evm-family`,{event:`ecdsa_presignature_generation`,requestTag:lt(e),presignSessionId:a,authorization:e.authorization.kind,durationMs:performance.now()-t,outcome:h?`available`:`failed`}),I(l),!h&&c&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:c,poolIdentity:s,workerCtx:e.workerCtx}).catch(()=>{}),m&&await e.clientSigningMaterial.abortClientPresignSession({sessionId:o,workerCtx:e.workerCtx}).catch(()=>{})}}function ft(e){return e.code===`stale_session_state`||e.code===`stale_pool_fill_session`}function pt(e){let t=l(e);return{ecdsaThresholdKeyId:p(t.ecdsa_threshold_key_id),clientVerifyingShareB64u:h(t.public_identity.derivation_client_share_public_key33_b64u),thresholdEcdsaPublicKeyB64u:t.public_identity.threshold_public_key33_b64u}}function mt(e){let t=Math.floor(Number(e.materialExpiresAtMs)),n=Number.isSafeInteger(e.authorizationExpiresAtMs)?Math.floor(Number(e.authorizationExpiresAtMs)):e.nowMs+Ie,r=Math.min(t,n,e.nowMs+Ie);return Number.isSafeInteger(r)&&r>e.nowMs?r:null}async function ht(e,t,n){let r=null,c=null,l=null,u=null,d=null,p={kind:`unclaimed`},m=null,h={kind:`before_prepare`};try{let _=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);if(!_)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation signing`};let y=pt(e.scope);if(!y.ecdsaThresholdKeyId)return{ok:!1,code:`invalid_args`,message:`Missing ecdsaThresholdKeyId for Router A/B ECDSA derivation signing`};let x=y.clientVerifyingShareB64u;if(!x)return{ok:!1,code:`invalid_args`,message:`Missing clientVerifyingShareB64u for Router A/B ECDSA derivation signing`};if(!(e.signingDigest32 instanceof Uint8Array)||e.signingDigest32.length!==32)return{ok:!1,code:`invalid_args`,message:`signingDigest32 must be 32 bytes for Router A/B ECDSA derivation signing`};let ne=performance.now(),C=await ct({clientVerifyingShareB64u:x,thresholdEcdsaPublicKeyB64u:y.thresholdEcdsaPublicKeyB64u,workerCtx:e.workerCtx});b(e.operationId,`public_key_validation`,ne),c=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:_,scope:e.scope,materialActivation:e.materialActivation}),await W(c,e.clientSigningMaterial,e.workerCtx),r=g(c),R.set(r,c),m=q(r);let re=performance.now();if(l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`pool_lookup`,re),!l){let t=performance.now();await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:m}),b(e.operationId,`pool_restore`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l){let t=performance.now();await Xe(r,`foreground`),b(e.operationId,`refill_wait`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l&&n.kind===`on_demand`){let t=performance.now();Je(r);try{let t=await _t({...n.refill,trafficClass:`foreground`});if(!t.ok&&t.code===`invalidated`&&(t=await _t({...n.refill,trafficClass:`foreground`})),!t.ok&&t.code!==`pool_full`)return t;!t.ok&&t.code===`pool_full`&&await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:q(r)})}finally{Ye(r)}m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`foreground_refill`,t)}if(S(`evm-family`,{event:`ecdsa_presignature_selection`,operationId:e.operationId,authorization:e.authorization.kind,outcome:l?`available`:`empty`,remainingDepth:G(r),attempt:t}),!l)return{ok:!1,code:`pool_empty`,message:`Router A/B ECDSA derivation client presignature pool is empty`};let ie=Date.now(),ae=mt({authorizationExpiresAtMs:e.expiresAtMs,materialExpiresAtMs:l.expiresAtMs,nowMs:ie});if(!ae)return{ok:!1,code:`pool_entry_expired`,message:`Router A/B ECDSA derivation client presignature is expired`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};d=Ne();let w=await ee(d),T=s({scope:e.scope,requestId:o(`router-ab-ecdsa-sign`,32,`Router A/B ECDSA derivation sign request`),operationId:e.operationId,operationDigests:e.operationDigests,authorization:e.authorization,materialActivation:e.materialActivation,clientPresignatureId:l.presignatureId,expiresAtMs:ae,signingDigest32:e.signingDigest32,clientRerandomizationCommitment32:w});I(w);let E=o(`router-ab-ecdsa-reservation`,32,`Router A/B ECDSA Client presignature reservation`);p={kind:`destroy`};let oe=performance.now(),D=await e.clientSigningMaterial.reserveClientPresignature({materialHandle:l.materialHandle,expectedPresignatureId:l.presignatureId,poolIdentity:c,requestBinding:T.request_id,reservationId:E,leaseExpiresAtMs:T.expires_at_ms,workerCtx:e.workerCtx});if(b(e.operationId,`presignature_reserve`,oe),D.kind===`unavailable`)return D.reason===`claimed_elsewhere`&&(p={kind:`owned_elsewhere`}),t<4?await ht(e,t+1,n):{ok:!1,code:D.reason===`expired`?`pool_entry_expired`:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature is unavailable: ${D.reason}`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};Q(r,0),h={kind:`prepare_submitted`};let se=performance.now(),O=await ce({relayServerUrl:_,credential:e.credential,request:T,onServerTiming:te.bind(void 0,e.operationId,`prepare`)});if(b(e.operationId,`prepare`,se),O.kind===`reusable_wallet_session`){if(!e.reconcileSession)throw Error(`Wallet Session reconciliation is required`);await e.reconcileSession(O.sessionStatus)}let k=O.signing;if(k.server_big_r33_b64u!==l.bigRB64u)return{ok:!1,code:`presign_mismatch`,message:`Router A/B ECDSA derivation SigningWorker returned a different presignature bigR`};let A=performance.now();await e.clientSigningMaterial.commitClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,workerCtx:e.workerCtx}),b(e.operationId,`presignature_commit`,A);let j=a(l.bigRB64u),M=a(k.signing_worker_rerandomization_contribution32_b64u);try{if(j.length!==33)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation presign bigR must decode to 33 bytes`};if(M.length!==32)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation SigningWorker rerandomization contribution must decode to 32 bytes`};let t=performance.now();u=await e.clientSigningMaterial.computeSignatureShareFromPresignatureHandle({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,groupPublicKey33:C,expectedPresignBigR33:j,digest32:e.signingDigest32,clientRerandomizationContribution32:d,signingWorkerRerandomizationContribution32:M,workerCtx:e.workerCtx}),b(e.operationId,`client_share`,t),p={kind:`consumed`}}finally{I(j),I(M)}if(u.length!==32)return{ok:!1,code:`internal`,message:`Invalid Router A/B ECDSA derivation client signature share length (expected 32, got ${u.length})`};let de=f({scope:e.scope,requestId:T.request_id,operationId:T.operation_id,operationDigests:T.operation_digests,authorization:e.authorization,materialActivation:e.materialActivation,expiresAtMs:T.expires_at_ms,signingDigest32:e.signingDigest32,serverPresignatureId:k.server_presignature_id,clientSignatureShare32:u,clientRerandomizationContribution32:d}),fe=performance.now(),pe=await le({relayServerUrl:_,credential:e.credential,request:de,onServerTiming:te.bind(void 0,e.operationId,`finalize`)});b(e.operationId,`finalize`,fe);let N=a(pe.signature65_b64u);if(N.length!==65)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned invalid signature length (expected 65, got ${N.length})`};try{let t=performance.now();await ue({digest32:e.signingDigest32,signature65:N,publicKey33:C,workerCtx:e.workerCtx}),b(e.operationId,`signature_verify`,t)}catch(e){return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned a signature that does not recover to the threshold group public key: ${Pe(e)}`}}return{ok:!0,signature65:N,signature65B64u:pe.signature65_b64u,rB64u:i(N.slice(0,32)),sB64u:i(N.slice(32,64)),recId:N[64]}}catch(t){if(t instanceof O||t instanceof k)throw t;let n=String(t&&typeof t==`object`&&`message`in t?t.message:t||`Router A/B ECDSA derivation signing failed`);return t instanceof j&&t.code===`expired_local_request`?{ok:!1,code:`pool_entry_expired`,message:n}:r&&c&&m!==null&&h.kind===`before_prepare`&&q(r)!==m?(await qe({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`}):{ok:!1,code:`router_ab_sign_failed`,message:n}}finally{if(I(u),I(d),l&&c&&p.kind!==`consumed`&&p.kind!==`owned_elsewhere`){let t=!1;if(p.kind===`unclaimed`&&r&&m!==null&&m===q(r)){let e=Be(r,c,l);t=e===`stored`||e===`duplicate`}t||await e.clientSigningMaterial.destroyClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,workerCtx:e.workerCtx}).catch(()=>{})}r&&Q(r,0)}}async function gt(e){let t=pt(e.scope),n=Math.floor(Number(e.expiresAtMs));if(!Number.isSafeInteger(n)||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Router A/B ECDSA derivation pool fill expiry is unavailable or expired`};let r={kind:`on_demand`,refill:{relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,clientVerifyingShareB64u:t.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:t.thresholdEcdsaPublicKeyB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:e.scope,ceremonyExpiresAtMs:Math.min(n,Date.now()+d-3e4),materialExpiresAtMs:e.authorization.kind===`operation_step_up`?n:Date.now()+y},workerCtx:e.workerCtx,...F(e)}},i=await ht(e,0,r);return!i.ok&&(i.code===`pool_entry_expired`||i.code===`pool_entry_unavailable`)?await ht(e,0,r):i}async function _t(e){try{let t=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation});await W(t,e.clientSigningMaterial,e.workerCtx);let n=g(t);await Ue({poolKey:n,poolIdentity:t,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx});let r=q(n),i=await ct({clientVerifyingShareB64u:e.clientVerifyingShareB64u,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,workerCtx:e.workerCtx}),a=await ut({relayerUrl:e.relayerUrl,poolFillInitKeySelector:{keyHandle:m(e.keyHandle)},clientSigningMaterial:e.clientSigningMaterial,groupPublicKey33:i,materialActivation:e.materialActivation,credential:e.credential,poolKey:n,trafficClass:e.trafficClass,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)});if(!a.ok)return a;try{await W(t,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(n)!==r)return await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!1,code:`invalidated`,message:`Router A/B ECDSA derivation presignature pool invalidated`};let o=Be(n,t,a.presignature);return(o===`capacity_full`||o===`invalid`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!0,presignatureId:a.presignature.presignatureId}}catch(e){return{ok:!1,code:`internal`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation presignature refill failed`)}}}export{Ze as a,pe as c,gt as i,et as n,_e as o,at as r,me as s,Qe as t};
@@ -1 +1 @@
1
- import{r as e}from"./secureRandomId-BIekT8bE.js";function t(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return Math.floor(e)}function n(t){return e(t,32,`passkey PRF cache session IDs`)}function r(e){let n=String(e.thresholdSessionId||``).trim(),r=String(e.prfFirstB64u||``).trim(),i=Number(e.expiresAtMs),a=t(e.remainingUses);if(!n||!r)throw Error(`Missing thresholdSessionId or prfFirstB64u for signing session hydration`);if(!Number.isFinite(i)||i<=0)throw Error(`Invalid expiresAtMs for signing session hydration`);if(a==null)throw Error(`Invalid remainingUses for signing session hydration`);let o={thresholdSessionId:n,prfFirstB64u:r,expiresAtMs:Math.floor(i),remainingUses:a,...e.diagnostics?{diagnostics:e.diagnostics}:{}};return e.preparedServerSeal?{...o,transport:e.transport,preparedServerSeal:e.preparedServerSeal}:{...o,...e.transport?{transport:e.transport}:{}}}async function i(e,t){let n=r(t),i={thresholdSessionId:n.thresholdSessionId,prfFirstB64u:n.prfFirstB64u,expiresAtMs:n.expiresAtMs,remainingUses:n.remainingUses,...n.diagnostics?{diagnostics:n.diagnostics}:{}};if(n.preparedServerSeal){await e.putWarmSessionMaterial({...i,transport:n.transport,preparedServerSeal:n.preparedServerSeal});return}await e.putWarmSessionMaterial({...i,...n.transport?{transport:n.transport}:{}})}export{n,i as t};
1
+ import{r as e}from"./secureRandomId-LwBFx84B.js";function t(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return Math.floor(e)}function n(t){return e(t,32,`passkey PRF cache session IDs`)}function r(e){let n=String(e.thresholdSessionId||``).trim(),r=String(e.prfFirstB64u||``).trim(),i=Number(e.expiresAtMs),a=t(e.remainingUses);if(!n||!r)throw Error(`Missing thresholdSessionId or prfFirstB64u for signing session hydration`);if(!Number.isFinite(i)||i<=0)throw Error(`Invalid expiresAtMs for signing session hydration`);if(a==null)throw Error(`Invalid remainingUses for signing session hydration`);let o={thresholdSessionId:n,prfFirstB64u:r,expiresAtMs:Math.floor(i),remainingUses:a,...e.diagnostics?{diagnostics:e.diagnostics}:{}};return e.preparedServerSeal?{...o,transport:e.transport,preparedServerSeal:e.preparedServerSeal}:{...o,...e.transport?{transport:e.transport}:{}}}async function i(e,t){let n=r(t),i={thresholdSessionId:n.thresholdSessionId,prfFirstB64u:n.prfFirstB64u,expiresAtMs:n.expiresAtMs,remainingUses:n.remainingUses,...n.diagnostics?{diagnostics:n.diagnostics}:{}};if(n.preparedServerSeal){await e.putWarmSessionMaterial({...i,transport:n.transport,preparedServerSeal:n.preparedServerSeal});return}await e.putWarmSessionMaterial({...i,...n.transport?{transport:n.transport}:{}})}export{n,i as t};
@@ -0,0 +1 @@
1
+ import{V as e,z as t}from"./domainIds-BzkGsRqO.js";import{C as n,k as r}from"./chains-C_X_fNuS.js";import{i,r as a}from"./base64-DW79QA0h.js";import{r as o}from"./canonicalPrimitives-Dsbsxgxc.js";function s(t,n={trim:!0}){let r=String(t??``);return e(n.trim?r.trim():r)}function c(e){let t=String(e.token??``).trim();if(!t)throw Error(e.missingMessage);return{Authorization:`Bearer ${t}`}}function l(e){return{method:`POST`,headers:{"Content-Type":`application/json`,...e.headers||{}},credentials:`omit`,body:e.bodyJson??JSON.stringify(e.body)}}function u(e,t){let n=s(e),r=globalThis.location?.origin,i;try{i=new URL(n).origin}catch{return}if(!(!r||i===r))for(let e of t)fetch(`${n}${e}`,{method:`OPTIONS`,credentials:`omit`}).catch(()=>{})}function d(e){return{...c({token:e.token,missingMessage:`Wallet Session token is required`}),...f(e.home)}}function f(e){switch(e.kind){case`direct`:return{};case`regional`:return{"X-Seams-Wallet-Region":e.region}}}async function p(e){let t=await fetch(e.clone());if(t.status!==409||!e.headers.has(`X-Seams-Wallet-Region`))return t;let r;try{r=await t.clone().json()}catch{return t}if(!n(r)||r.code!==`wallet_home_discovery_required`)return t;let i=new Headers(e.headers);return i.delete(`X-Seams-Wallet-Region`),fetch(new Request(e,{headers:i}))}const m=[1,2];function h(e){let t=Number(e);return!Number.isSafeInteger(t)||t<1||t>65535?null:t}function g(e){if(!Array.isArray(e)||e.length===0)return null;let t=[],n=new Set;for(let r of e){let e=h(r);if(!e)return null;n.has(e)||(n.add(e),t.push(e))}return t.sort((e,t)=>e-t),t.length?t:null}function _(e){if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let r of e){if(!r||typeof r!=`object`||Array.isArray(r))return null;let e=r,i=h(e.id),a=t(e.role);if(!i||a!==`client`&&a!==`relayer`)return null;let o={id:i,role:a},s=t(e.relayerUrl);s&&(o.relayerUrl=s);let c=t(e.relayerKeyId);c&&(o.relayerKeyId=c);let l=t(e.shareDerivation);(l===`prf_first_v1`||l===`derived_master_secret_v1`||l===`kv_random_v1`||l===`unknown`)&&(o.shareDerivation=l),n.push(o)}return n.length?n:null}function v(e){let n=t(e.relayerKeyId),r=t(e.relayerUrl),i=h(e.clientParticipantId)??1,a=h(e.relayerParticipantId)??2;return[{id:i,role:`client`,shareDerivation:e.clientShareDerivation||`prf_first_v1`},{id:a,role:`relayer`,...r?{relayerUrl:r}:{},...n?{relayerKeyId:n}:{},...e.relayerShareDerivation?{shareDerivation:e.relayerShareDerivation}:{}}]}function y(e,n){let r=t(n);if(!r)throw Error(`${e} is required`);return r}function b(e){return`${y(`projectId`,e.projectId)}:${y(`envId`,e.envId)}`}function x(e){let t=S(e);return{...t,signingRootVersion:y(`signingRootVersion`,t.signingRootVersion)}}function S(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`runtimePolicyScope must be an object`);let n=e;if(Object.prototype.hasOwnProperty.call(n,`environmentId`))throw Error(`runtimePolicyScope.environmentId is stale; use envId`);if(Object.prototype.hasOwnProperty.call(n,`runtimeSnapshotScope`))throw Error(`runtimePolicyScope.runtimeSnapshotScope is stale; use runtimePolicyScope`);return{orgId:y(`orgId`,n.orgId),projectId:y(`projectId`,n.projectId),envId:y(`envId`,n.envId),...t(n.signingRootVersion)?{signingRootVersion:t(n.signingRootVersion)}:{}}}function C(e,t){return e.orgId===t.orgId&&e.projectId===t.projectId&&e.envId===t.envId&&e.signingRootVersion===t.signingRootVersion}function w(e){return{signingRootId:b(e),signingRootVersion:y(`signingRootVersion`,e.signingRootVersion)}}const T=[`prf`,`kek`,`seed`,`scalar`,`secretkey`,`privatekey`,`plaintext`,`recoverycode`,`clientroot`,`holdershare`];function E(e,t,n,r=[]){let i=new Set(t),a=new Set(r);for(let t of Object.keys(e)){if(i.has(t))continue;if(a.has(t))throw Error(`${n}.${t} is not part of ${n}`);let e=t.toLowerCase().replace(/_/g,``);throw!e.includes(`publickey`)&&T.some(t=>e.includes(t))?Error(`${n}.${t} must never carry plaintext custody material`):Error(`${n}.${t} is not part of ${n}`)}}function D(e,t,n){let i=r(e,n);E(i,t,n);for(let e of t)if(!Object.prototype.hasOwnProperty.call(i,e)||i[e]===void 0)throw Error(`${n}.${e} is required`);return i}const O=Object.freeze([`export_keys`,`link_devices`,`revoke_devices`,`sign`]);Object.freeze([`sign`]);const k=new Set([`export_keys`,`link_devices`,`revoke_devices`,`sign`]),A=Symbol(`canonicalPermissionSetBrand`);var j=class e extends Array{constructor(e){super(...e),this[A]=!0,Object.freeze(this)}static create(t){return new e(t)}static get[Symbol.species](){return Array}};function M(e){return typeof e==`string`&&k.has(e)}function N(e){if(!Array.isArray(e))return W(e==null?`delegated wallet permissions are required`:`delegated wallet permissions must be an array`);if(e.length===0)return W(`delegated wallet permissions must be non-empty`);let t=[],n=new Set;for(let r of e){if(!M(r))return W(`delegated wallet permission is unsupported`);if(n.has(r))return W(`delegated wallet permission ${r} is duplicated`);n.add(r),t.push(r)}return t.sort(V),{ok:!0,value:j.create(H(t))}}function P(e){return{kind:`delegated_wallet_authority_v1`,permissions:e.permissions}}function F(e){if(!U(e))return G(`delegated wallet authority must contain exactly kind and permissions`);if(e.kind!==`delegated_wallet_authority_v1`)return G(`delegated wallet authority kind is unsupported`);let t=N(e.permissions);return t.ok?{ok:!0,value:P({permissions:t.value})}:t}function I(){return B(O)}function ee(){return P({permissions:I()})}function L(e,t){return e.permissions.includes(t)}function R(e){return Object.freeze([...e.permissions])}function z(e,t){if(e.kind!==t.kind||e.permissions.length!==t.permissions.length)return!1;for(let n=0;n<e.permissions.length;n+=1)if(e.permissions[n]!==t.permissions[n])return!1;return!0}function B(e){let t=N(e);if(!t.ok)throw Error(t.error.message);return t.value}function V(e,t){return e<t?-1:e>t?1:0}function H(e){let[t,...n]=e;if(!t)throw Error(`delegated wallet permissions must be non-empty`);return[t,...n]}function U(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.keys(e);return t.length===2&&t.includes(`kind`)&&t.includes(`permissions`)}function W(e){return{ok:!1,error:{code:`invalid`,message:e}}}function G(e){return{ok:!1,error:{code:`invalid`,message:e}}}const K=/^[A-Za-z0-9_-]+$/;function q(e,t){if(typeof e!=`string`||!K.test(e))throw Error(`${t} must be unpadded base64url`);let n;try{n=a(e)}catch{throw Error(`${t} must be valid base64url`)}if(i(n)!==e)throw Error(`${t} must be canonical base64url`);return n}function J(e,t){if(e.ok)return e.value;throw Error(`${t} ${e.error.message}`)}function Y(e,t){try{return o(e)}catch(e){throw Error(`${t} ${e instanceof Error?e.message:`is not a digest`}`)}}function X(e,t=`nonceB64u`){if(q(e,t).length!==12)throw Error(`${t} must decode to a 12-byte ChaCha20Poly1305 nonce`);return e}function Z(e,t=`ciphertextB64u`){if(q(e,t).length<17)throw Error(`${t} must decode to sealed ciphertext with an authentication tag`);return e}function Q(e,t=`registeredPublicKeyB64u`){if(q(e,t).length!==32)throw Error(`${t} must decode to a 32-byte Ed25519 public key`);return e}function $(e,t=`publicKey33B64u`){let n=q(e,t);if(n.length!==33)throw Error(`${t} must decode to a 33-byte compressed secp256k1 point`);if(n[0]!==2&&n[0]!==3)throw Error(`${t} must be a compressed secp256k1 public key`);return e}function te(e,t=`keyCreationSignerSlot`){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0||e>4294967295)throw Error(`${t} must be a positive u32`);return e}function ne(e,t=`envelopeRevision`){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer revision`);return e}function re(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive unix-millisecond timestamp`);return e}export{p as A,v as C,l as D,c as E,u as M,f as O,m as S,_ as T,E as _,ne as a,C as b,re as c,R as d,L as f,D as g,z as h,X as i,s as j,d as k,J as l,N as m,Q as n,te as o,F as p,Z as r,$ as s,Y as t,ee as u,b as v,g as w,w as x,x as y};
@@ -1 +1 @@
1
- import{V as e,h as t}from"./normalize-kUDm5zfS.js";import{d as n,l as r}from"./chains-CiYQT1K4.js";import{i}from"./base64-CsEj-_bC.js";import{r as a}from"./secureRandomId-BIekT8bE.js";import"./primitives-CAcl7ON7.js";import"./sessionPolicy-J-RrlPZQ.js";import"./signingSessionSeal-CDLUmAFY.js";import"./activeWalletSession-DiZcKjB_.js";import"./capabilityKinds-CKQ4Uqnv.js";import"./errors-BZO3LF6G.js";import"./digestEncoding-Dzc1rzWV.js";import"./accountIds-BzZs7YoX.js";import"./registrationSignerPlan-B9GCvpTV.js";import"./signerDomain-vQmlnsbF.js";import"./registrationIntent-DOkZcKSP.js";import"./singletons-8UH3gOnZ.js";import"./walletAuthority-B5hXHWpK.js";import"./emailOtpEcdsaDerivationIdentity-B8HzTh4T.js";import"./challengeDelivery-DxXAkOfS.js";import"./registrationIds-CdPqm-Ya.js";import{a as o,c as s}from"./passkey-custody-BQj44jEM.js";import{u as c}from"./walletCustodyEcdsaContinuity-abNZ_dvX.js";import"./keccak-B02Fekdh.js";import{f as l,m as u}from"./wallet-recovery-C1kesLCF.js";import{a as d,c as f,d as p,l as m,n as h,o as g,r as _,s as v,t as y,u as b}from"./walletRecoveryCommit-Cc9AqHr0.js";function x(e){throw Error(`Unhandled wallet recovery branch: ${String(e)}`)}function S(e){return e.target.kind===`google_email_otp`}function C(e,t){if(!e||e.stage===`prepared`||e.stage===`google_verified`||e.walletId!==t.walletId||e.target.kind!==t.target.kind)return null;switch(e.target.kind){case`passkey`:return t.kind===`credential_created`&&t.target.kind===`passkey`&&e.target.rpId===t.target.rpId?e:null;case`google_email_otp`:return t.kind===`email_otp_verified`&&t.target.kind===`google_email_otp`&&e.target.googleProvider===t.target.googleProvider?e:null}}function w(){return l(a(`wallet-recovery-reservation`,32,`wallet recovery operation reservations`))}function T(e){return e}const E=`seams:recovery:consumed-code-digests`;function D(){try{let e=JSON.parse(sessionStorage.getItem(E)??`[]`);return Array.isArray(e)?new Set(e.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function O(e,t){e.add(t);try{sessionStorage.setItem(E,JSON.stringify([...e].slice(-32)))}catch{}}function k(e){e&&e.byteLength>0&&new Uint8Array(e).fill(0)}function A(e){switch(e.recoveryCodeBytes.fill(0),e.stage){case`prepared`:case`google_verified`:return;case`credential_created`:k(e.replacement.factorSecret);return;case`email_otp_verified`:case`manifest_recovered`:k(e.replacement.kind===`passkey`?e.replacement.factorSecret:e.replacement.factor.factorSecret);return}}function j(){return{kind:`refused`}}function M(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`name`);return t===`NotAllowedError`||t===`AbortError`}function N(e,t){if(e.target.kind!==`passkey`||!e.prepared.registration)throw Error(`passkey recovery registration is unavailable`);return{stage:`credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:{kind:`passkey`,registration:t.registration,credentialIdB64u:t.credentialIdB64u,factorSecret:t.factorSecret}}}function P(e,t){return{stage:`email_otp_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:t}}function F(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return{replacementId:t.replacementId,walletAuthMethodId:t.walletAuthMethodId,factor:s({rpId:t.rpId,credentialIdB64u:e.replacement.credentialIdB64u}),factorSecret:e.replacement.factorSecret}}function I(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return t.challengeId}function L(e,t){return{stage:`manifest_recovered`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:e.replacement,recovered:t}}function R(e,t){return{stage:`manifest_recovered`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:e.replacement,recovered:t}}function z(e,t){switch(e.stage){case`credential_created`:return L(e,t);case`email_otp_verified`:return R(e,t);default:return x(e)}}function B(e){return e.authMethod.kind===`passkey`}function V(e){return e.target.kind===`passkey`&&e.replacement.kind===`passkey`}function H(e){return e.target.kind===`google_email_otp`&&e.replacement.kind===`email_otp`}async function U(e){return await e.context.signingEngine.getSignerWorkerContext().requestWorkerOperation({kind:`emailOtp`,request:{type:`releaseWalletRecoveryEmailOtpFactor`,payload:{relayUrl:e.relayUrl,walletId:String(e.walletId),recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId}}})}async function W(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return await m({relayUrl:e.relayUrl,walletId:e.walletId,reservationId:e.prepared.reservationId,recoveryOperationId:e.prepared.recoveryOperationId,targetDeviceId:e.prepared.targetDeviceId,targetAuthorityId:e.prepared.targetAuthorityId,targetWalletAuthMethodId:e.prepared.targetWalletAuthMethodId,challengeId:t.challengeId,replacementId:t.replacementId,webauthnRegistration:e.replacement.registration,replacementEnvelope:e.recovered.replacementEnvelope,ecdsaMaterialPossessionProofs:e.recovered.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.activation.possessionProof}))})}var G=class{constructor(e=null){this.rpc=e}#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i=new Map;#a=D();async prepareWithCode(t){if(this.#c(),t.signal.aborted)return j();if(t.target.kind===`passkey`){let n=e(t.context.signingEngine.getRpId());if(!n.ok||n.value!==t.target.rpId)return j()}let n=null;try{n=u(t.recoveryCode);let e=i(await r(n));if(this.#a.has(e))return{kind:`consumed`};let o=T(e),s=this.#r.get(o),c=s?.expiresAtMs&&s.expiresAtMs>Date.now()?s.reservationId:w(),l=await p({relayUrl:t.relayUrl,target:t.target,recoveryCodeB64u:i(n),reservationId:c});if(l.kind!==`prepared`)return l.kind===`retryable_conflict`||l.kind===`transport_uncertain`?this.#r.set(o,{reservationId:c,expiresAtMs:Date.now()+3e5}):this.#r.delete(o),l;if(this.#r.delete(o),t.signal.aborted)return this.#r.set(o,{reservationId:l.reservationId,expiresAtMs:l.reservationExpiresAtMs}),j();let d=a(`wallet-recovery-operation`,24,`wallet recovery client operation handles`);return this.#e.set(d,{stage:`prepared`,recoveryOperationId:d,walletId:l.walletId,relayUrl:t.relayUrl,target:t.target,prepared:l,custodyJson:b({walletId:l.walletId,prepared:l}),recoveryCodeBytes:n}),this.#i.set(d,o),n=null,{kind:`prepared`,recoveryOperationId:d,walletId:l.walletId,target:t.target}}catch{return j()}finally{n?.fill(0)}}createPasskey(e){this.#c();let t=this.#e.get(e.operation.recoveryOperationId);if(!t||t.stage!==`prepared`||t.walletId!==e.operation.walletId||t.target.kind!==`passkey`||e.operation.target.kind!==`passkey`||t.target.rpId!==e.operation.target.rpId||this.#n.has(t.recoveryOperationId)||!t.prepared.registration)return Promise.resolve({kind:`refused`});let n=new AbortController;this.#n.set(t.recoveryOperationId,n);let r;try{r=e.context.signingEngine.createWalletRecoveryReplacementCredential({walletId:t.walletId,registration:t.prepared.registration,cancellation:{kind:`abort_signal`,signal:n.signal}})}catch{return this.cancel(t.recoveryOperationId),Promise.resolve({kind:`refused`})}return this.#s({current:t,credentialPromise:r,promptController:n})}async verifyGoogle(e){this.#c();let t=this.#e.get(e.operation.recoveryOperationId);if(!this.rpc||!t||t.stage!==`prepared`||t.target.kind!==`google_email_otp`||e.operation.target.kind!==`google_email_otp`||t.walletId!==e.operation.walletId||t.target.googleProvider!==e.operation.target.googleProvider||t.relayUrl!==e.relayUrl)return j();let n=t.prepared;if(!S(n))return j();try{let r=await this.rpc.verifyGoogle({relayUrl:t.relayUrl,recoveryOperationId:n.recoveryOperationId,reservationId:n.reservationId,idToken:e.idToken});if(r.kind!==`verified`)return r;if(r.recoveryOperationId!==n.recoveryOperationId)return{kind:`transport_uncertain`};let i={kind:`google_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target,challengeId:r.challengeId,delivery:r.delivery,expiresAtMs:r.expiresAtMs},a={stage:`google_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,relayUrl:t.relayUrl,target:t.target,prepared:n,custodyJson:t.custodyJson,recoveryCodeBytes:t.recoveryCodeBytes,verification:i};return this.#e.set(a.recoveryOperationId,a),i}catch{return{kind:`transport_uncertain`}}}async verifyEmailOtp(e){this.#c();let n=this.#e.get(e.operation.recoveryOperationId);if(!this.rpc||!n||n.stage!==`google_verified`||n.walletId!==e.operation.walletId||n.target.kind!==`google_email_otp`||e.operation.target.kind!==`google_email_otp`||n.verification.challengeId!==e.operation.challengeId||e.challengeId!==e.operation.challengeId)return j();let r=t(e.challengeId);if(!r.ok)return j();try{let t=await this.rpc.verifyEmailOtp({relayUrl:n.relayUrl,recoveryOperationId:n.prepared.recoveryOperationId,reservationId:n.prepared.reservationId,challengeId:r.value,otpCode:e.otpCode});if(t.kind!==`verified`)return t;if(t.recoveryOperationId!==n.prepared.recoveryOperationId||t.challengeId!==e.challengeId)return{kind:`transport_uncertain`};let i=await U({context:e.context,relayUrl:n.relayUrl,walletId:n.walletId,recoveryOperationId:n.prepared.recoveryOperationId,reservationId:String(n.prepared.reservationId)});if(i.kind===`existing`){if(i.recoveryOperationId!==String(n.prepared.recoveryOperationId)||i.reservationId!==String(n.prepared.reservationId)||i.factorSecret32.byteLength!==32)return k(i.factorSecret32),{kind:`transport_uncertain`};let t=P(n,{kind:`email_otp`,factor:{replacementId:String(n.prepared.recoveryOperationId),walletAuthMethodId:n.prepared.targetWalletAuthMethodId,factor:o({enrollmentId:i.enrollmentId,enrollmentSealKeyVersion:i.enrollmentSealKeyVersion}),factorSecret:i.factorSecret32},enrollment:{kind:`existing`,enrollmentId:i.enrollmentId,enrollmentSealKeyVersion:i.enrollmentSealKeyVersion},providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,registrationAuthorityId:e.challengeId});return this.#e.set(t.recoveryOperationId,t),{kind:`email_otp_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target,challengeId:e.challengeId}}if(i.kind!==`create`)return i;if(i.recoveryOperationId!==String(n.prepared.recoveryOperationId)||i.reservationId!==String(n.prepared.reservationId))return{kind:`transport_uncertain`};let a=crypto.getRandomValues(new Uint8Array(32)),s=null;try{let t=await e.context.signingEngine.prepareEmailOtpRegistrationEnrollmentMaterialInternal({relayUrl:n.relayUrl,walletId:n.walletId,userId:i.providerSubject,clientSecret32:a});s=a.slice().buffer;let r=P(n,{kind:`email_otp`,factor:{replacementId:String(n.prepared.recoveryOperationId),walletAuthMethodId:n.prepared.targetWalletAuthMethodId,factor:o({enrollmentId:t.enrollmentId,enrollmentSealKeyVersion:t.enrollmentSealKeyVersion}),factorSecret:s},enrollment:{kind:`create`,enrollmentId:t.enrollmentId,providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,material:t.emailOtpEnrollment},providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,registrationAuthorityId:e.challengeId});return this.#e.set(r.recoveryOperationId,r),s=null,{kind:`email_otp_verified`,recoveryOperationId:r.recoveryOperationId,walletId:r.walletId,target:r.target,challengeId:e.challengeId}}finally{a.fill(0),s&&k(s)}}catch{return{kind:`refused`}}}async finalize(e){let t=String(e.operation.recoveryOperationId),n=this.#t.get(t);if(n)return n;let r=this.#o(e).finally(()=>{this.#t.delete(t)});return this.#t.set(t,r),r}async#o(e){this.#c();let t=C(this.#e.get(e.operation.recoveryOperationId),e.operation);if(!t)return j();try{if(t.stage===`credential_created`||t.stage===`email_otp_verified`){let n=t.stage===`credential_created`?F(t):t.replacement.factor,r=await e.context.signingEngine.recoverWalletCustodyManifest({walletId:t.walletId,prepared:t.prepared,custodyJson:t.custodyJson,recoveryCodeBytes:t.recoveryCodeBytes,replacementFactor:n,recoveryChallengeId:t.stage===`credential_created`?I(t):String(t.prepared.recoveryOperationId),relayUrl:t.relayUrl});if(this.#e.get(t.recoveryOperationId)!==t)return A(t),j();if(t.prepared.reservationExpiresAtMs<=Date.now())return this.cancel(t.recoveryOperationId),j();t.recoveryCodeBytes.fill(0),k(t.stage===`credential_created`?t.replacement.factorSecret:t.replacement.factor.factorSecret),t=z(t,r),this.#e.set(t.recoveryOperationId,t)}if(t.stage===`manifest_recovered`){if(!V(t)&&!H(t))return{kind:`transport_uncertain`};if(t.target.kind===`google_email_otp`&&!this.rpc)return{kind:`refused`};let e=await y({operation:t});if(this.#e.get(t.recoveryOperationId)!==t)return{kind:`transport_uncertain`};await c.putPendingWalletRecoveryCommit(e.pending);let r=V(t)?await W(t):this.rpc?await this.rpc.finalizeEmailOtp({relayUrl:t.relayUrl,walletId:t.walletId,recoveryOperationId:t.prepared.recoveryOperationId,reservationId:t.prepared.reservationId,targetDeviceId:t.prepared.targetDeviceId,targetAuthorityId:t.prepared.targetAuthorityId,targetWalletAuthMethodId:t.prepared.targetWalletAuthMethodId,expectedProviderSubject:t.replacement.providerSubject,expectedEmailHashHex:await n(t.replacement.verifiedEmail),expectedRegistrationAuthorityId:t.replacement.registrationAuthorityId,replacementEnvelope:t.recovered.replacementEnvelope,ecdsaMaterialPossessionProofs:t.recovered.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.activation.possessionProof})),emailOtpEnrollment:t.replacement.enrollment.kind===`create`?{kind:`create`,material:t.replacement.enrollment.material}:null}):{kind:`refused`};if(r.kind===`refused`)return await c.deletePendingWalletRecoveryCommit(t.prepared.recoveryOperationId),this.#e.get(t.recoveryOperationId)===t&&this.cancel(t.recoveryOperationId),r;if(this.#e.get(t.recoveryOperationId)!==t)return r.kind===`promoted`?{kind:`transport_uncertain`}:r;if(r.kind!==`promoted`)return r;if(t.replacement.kind===`passkey`&&r.authMethod.credentialIdB64u!==t.replacement.credentialIdB64u)return{kind:`transport_uncertain`};let i;if(f(e.payload)){if(!B(r))return{kind:`transport_uncertain`};i={kind:`passkey`,payload:e.payload,promotion:r}}else{if(B(r))return{kind:`transport_uncertain`};i={kind:`google_email_otp`,payload:e.payload,promotion:r}}await _({pending:await h({awaiting:e.pending,promotion:i}),payload:i.payload})}let r=this.#i.get(t.recoveryOperationId);return r&&O(this.#a,r),this.#e.delete(t.recoveryOperationId),this.#i.delete(t.recoveryOperationId),A(t),{kind:`ready_for_sign_in`,walletId:t.walletId}}catch{return{kind:`transport_uncertain`}}}async#s(e){try{let t=await e.credentialPromise;if(this.#e.get(e.current.recoveryOperationId)!==e.current||e.promptController.signal.aborted)return k(t.factorSecret),{kind:`dismissed`};if(e.current.prepared.reservationExpiresAtMs<=Date.now())return k(t.factorSecret),this.cancel(e.current.recoveryOperationId),{kind:`refused`};let n=N(e.current,t);return this.#e.set(n.recoveryOperationId,n),{kind:`credential_created`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target}}catch(t){return e.promptController.signal.aborted||M(t)?{kind:`dismissed`}:{kind:`transport_uncertain`}}finally{this.#n.get(e.current.recoveryOperationId)===e.promptController&&this.#n.delete(e.current.recoveryOperationId)}}cancel(e){this.#n.get(e)?.abort(),this.#n.delete(e);let t=this.#e.get(e);if(!t)return;let n=this.#i.get(e);this.#i.delete(e),n&&t.prepared.reservationExpiresAtMs>Date.now()&&this.#r.set(n,{reservationId:t.prepared.reservationId,expiresAtMs:t.prepared.reservationExpiresAtMs}),this.#e.delete(e),A(t)}#c(){let e=Date.now();for(let[t,n]of this.#r)n.expiresAtMs<=e&&this.#r.delete(t);for(let[t,n]of this.#e)n.prepared.reservationExpiresAtMs>e||(this.#n.get(t)?.abort(),this.#n.delete(t),this.#e.delete(t),this.#i.delete(t),A(n))}},K=class{#e=new G({verifyGoogle:v,verifyEmailOtp:g,finalizeEmailOtp:d});constructor(t,n){this.context=t,this.relayUrl=n;let r=e(t.signingEngine.getRpId());if(!r.ok)throw Error(`wallet recovery RP ID ${r.error.message}`);this.#t=r.value}#t;targetFor(e){switch(e){case`passkey`:return{kind:e,rpId:this.#t};case`google_email_otp`:return{kind:e,googleProvider:`google`}}}async prepare(e){let t=await this.#e.prepareWithCode({context:this.context,relayUrl:this.relayUrl,recoveryCode:e.recoveryCode,target:e.target,signal:e.signal});return t.kind===`prepared`?(t.target.kind,{kind:`hosted_recovery_prepared`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target}):t}createPasskey(e){return this.#n({kind:`prepared`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target})}async verifyGoogle(e,t){let n=await this.#e.verifyGoogle({relayUrl:this.relayUrl,operation:{kind:`prepared`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target},idToken:t});return n.kind===`google_verified`?{kind:`hosted_recovery_google_verified`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target,challengeId:n.challengeId,delivery:n.delivery,expiresAtMs:n.expiresAtMs}:n}async verifyEmailOtp(e,t){let n=await this.#e.verifyEmailOtp({context:this.context,operation:{kind:`google_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target,challengeId:e.challengeId,delivery:e.delivery,expiresAtMs:e.expiresAtMs},challengeId:t.challengeId,otpCode:t.otpCode});return n.kind===`email_otp_verified`?{kind:`hosted_recovery_email_otp_verified`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target,challengeId:n.challengeId}:n}async finalize(e){return e.kind===`hosted_recovery_credential_created`?await this.#e.finalize({context:this.context,operation:{kind:`credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target}}):await this.#e.finalize({context:this.context,operation:{kind:`email_otp_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target,challengeId:e.challengeId}})}async cancel(e){this.#e.cancel(e.recoveryOperationId)}async#n(e){let t=await this.#e.createPasskey({context:this.context,operation:e});return t.kind===`credential_created`?this.#r(t):t}#r(e){return{kind:`hosted_recovery_credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target}}};function q(e){return new K(e.context,e.relayUrl)}export{q as createHostedRecoveryPort};
1
+ import{M as e,o as t}from"./domainIds-BzkGsRqO.js";import{d as n,l as r}from"./chains-C_X_fNuS.js";import"./primitives-CqrjmIAH.js";import{i}from"./base64-DW79QA0h.js";import{r as a}from"./secureRandomId-LwBFx84B.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";import"./accountIds-BzZs7YoX.js";import"./registrationSignerPlan-dY9Rp0m_.js";import"./signerDomain-DqLCvI-D.js";import"./registrationIntent-BHU5k2Q-.js";import"./singletons-8UH3gOnZ.js";import"./walletAuthority-BWvfaKIX.js";import"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import"./challengeDelivery-5lIu9spR.js";import"./digestEncoding-CkUc5vtR.js";import"./registrationIds-ByuReLUc.js";import{a as o,c as s}from"./passkey-custody-Cd_yyoRa.js";import{u as c}from"./walletCustodyEcdsaContinuity-B8aO2NFb.js";import"./keccak-BArcwgbj.js";import{f as l,m as u}from"./wallet-recovery-D7ywcIHw.js";import{a as d,c as f,d as p,l as m,n as h,o as g,r as _,s as v,t as y,u as b}from"./walletRecoveryCommit-C3EgMjo-.js";function x(e){throw Error(`Unhandled wallet recovery branch: ${String(e)}`)}function S(e){return e.target.kind===`google_email_otp`}function C(e,t){if(!e||e.stage===`prepared`||e.stage===`google_verified`||e.walletId!==t.walletId||e.target.kind!==t.target.kind)return null;switch(e.target.kind){case`passkey`:return t.kind===`credential_created`&&t.target.kind===`passkey`&&e.target.rpId===t.target.rpId?e:null;case`google_email_otp`:return t.kind===`email_otp_verified`&&t.target.kind===`google_email_otp`&&e.target.googleProvider===t.target.googleProvider?e:null}}function w(){return l(a(`wallet-recovery-reservation`,32,`wallet recovery operation reservations`))}function T(e){return e}const E=`seams:recovery:consumed-code-digests`;function D(){try{let e=JSON.parse(sessionStorage.getItem(E)??`[]`);return Array.isArray(e)?new Set(e.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function O(e,t){e.add(t);try{sessionStorage.setItem(E,JSON.stringify([...e].slice(-32)))}catch{}}function k(e){e&&e.byteLength>0&&new Uint8Array(e).fill(0)}function A(e){switch(e.recoveryCodeBytes.fill(0),e.stage){case`prepared`:case`google_verified`:return;case`credential_created`:k(e.replacement.factorSecret);return;case`email_otp_verified`:case`manifest_recovered`:k(e.replacement.kind===`passkey`?e.replacement.factorSecret:e.replacement.factor.factorSecret);return}}function j(){return{kind:`refused`}}function M(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`name`);return t===`NotAllowedError`||t===`AbortError`}function N(e,t){if(e.target.kind!==`passkey`||!e.prepared.registration)throw Error(`passkey recovery registration is unavailable`);return{stage:`credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:{kind:`passkey`,registration:t.registration,credentialIdB64u:t.credentialIdB64u,factorSecret:t.factorSecret}}}function P(e,t){return{stage:`email_otp_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:t}}function F(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return{replacementId:t.replacementId,walletAuthMethodId:t.walletAuthMethodId,factor:s({rpId:t.rpId,credentialIdB64u:e.replacement.credentialIdB64u}),factorSecret:e.replacement.factorSecret}}function I(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return t.challengeId}function L(e,t){return{stage:`manifest_recovered`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:e.replacement,recovered:t}}function R(e,t){return{stage:`manifest_recovered`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:e.replacement,recovered:t}}function z(e,t){switch(e.stage){case`credential_created`:return L(e,t);case`email_otp_verified`:return R(e,t);default:return x(e)}}function B(e){return e.authMethod.kind===`passkey`}function V(e){return e.target.kind===`passkey`&&e.replacement.kind===`passkey`}function H(e){return e.target.kind===`google_email_otp`&&e.replacement.kind===`email_otp`}async function U(e){return await e.context.signingEngine.getSignerWorkerContext().requestWorkerOperation({kind:`emailOtp`,request:{type:`releaseWalletRecoveryEmailOtpFactor`,payload:{relayUrl:e.relayUrl,walletId:String(e.walletId),recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId}}})}async function W(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return await m({relayUrl:e.relayUrl,walletId:e.walletId,reservationId:e.prepared.reservationId,recoveryOperationId:e.prepared.recoveryOperationId,targetDeviceId:e.prepared.targetDeviceId,targetAuthorityId:e.prepared.targetAuthorityId,targetWalletAuthMethodId:e.prepared.targetWalletAuthMethodId,challengeId:t.challengeId,replacementId:t.replacementId,webauthnRegistration:e.replacement.registration,replacementEnvelope:e.recovered.replacementEnvelope,ecdsaMaterialPossessionProofs:e.recovered.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.activation.possessionProof}))})}var G=class{constructor(e=null){this.rpc=e}#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i=new Map;#a=D();async prepareWithCode(t){if(this.#c(),t.signal.aborted)return j();if(t.target.kind===`passkey`){let n=e(t.context.signingEngine.getRpId());if(!n.ok||n.value!==t.target.rpId)return j()}let n=null;try{n=u(t.recoveryCode);let e=i(await r(n));if(this.#a.has(e))return{kind:`consumed`};let o=T(e),s=this.#r.get(o),c=s?.expiresAtMs&&s.expiresAtMs>Date.now()?s.reservationId:w(),l=await p({relayUrl:t.relayUrl,target:t.target,recoveryCodeB64u:i(n),reservationId:c});if(l.kind!==`prepared`)return l.kind===`retryable_conflict`||l.kind===`transport_uncertain`?this.#r.set(o,{reservationId:c,expiresAtMs:Date.now()+3e5}):this.#r.delete(o),l;if(this.#r.delete(o),t.signal.aborted)return this.#r.set(o,{reservationId:l.reservationId,expiresAtMs:l.reservationExpiresAtMs}),j();let d=a(`wallet-recovery-operation`,24,`wallet recovery client operation handles`);return this.#e.set(d,{stage:`prepared`,recoveryOperationId:d,walletId:l.walletId,relayUrl:t.relayUrl,target:t.target,prepared:l,custodyJson:b({walletId:l.walletId,prepared:l}),recoveryCodeBytes:n}),this.#i.set(d,o),n=null,{kind:`prepared`,recoveryOperationId:d,walletId:l.walletId,target:t.target}}catch{return j()}finally{n?.fill(0)}}createPasskey(e){this.#c();let t=this.#e.get(e.operation.recoveryOperationId);if(!t||t.stage!==`prepared`||t.walletId!==e.operation.walletId||t.target.kind!==`passkey`||e.operation.target.kind!==`passkey`||t.target.rpId!==e.operation.target.rpId||this.#n.has(t.recoveryOperationId)||!t.prepared.registration)return Promise.resolve({kind:`refused`});let n=new AbortController;this.#n.set(t.recoveryOperationId,n);let r;try{r=e.context.signingEngine.createWalletRecoveryReplacementCredential({walletId:t.walletId,registration:t.prepared.registration,cancellation:{kind:`abort_signal`,signal:n.signal}})}catch{return this.cancel(t.recoveryOperationId),Promise.resolve({kind:`refused`})}return this.#s({current:t,credentialPromise:r,promptController:n})}async verifyGoogle(e){this.#c();let t=this.#e.get(e.operation.recoveryOperationId);if(!this.rpc||!t||t.stage!==`prepared`||t.target.kind!==`google_email_otp`||e.operation.target.kind!==`google_email_otp`||t.walletId!==e.operation.walletId||t.target.googleProvider!==e.operation.target.googleProvider||t.relayUrl!==e.relayUrl)return j();let n=t.prepared;if(!S(n))return j();try{let r=await this.rpc.verifyGoogle({relayUrl:t.relayUrl,recoveryOperationId:n.recoveryOperationId,reservationId:n.reservationId,idToken:e.idToken});if(r.kind!==`verified`)return r;if(r.recoveryOperationId!==n.recoveryOperationId)return{kind:`transport_uncertain`};let i={kind:`google_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target,challengeId:r.challengeId,delivery:r.delivery,expiresAtMs:r.expiresAtMs},a={stage:`google_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,relayUrl:t.relayUrl,target:t.target,prepared:n,custodyJson:t.custodyJson,recoveryCodeBytes:t.recoveryCodeBytes,verification:i};return this.#e.set(a.recoveryOperationId,a),i}catch{return{kind:`transport_uncertain`}}}async verifyEmailOtp(e){this.#c();let n=this.#e.get(e.operation.recoveryOperationId);if(!this.rpc||!n||n.stage!==`google_verified`||n.walletId!==e.operation.walletId||n.target.kind!==`google_email_otp`||e.operation.target.kind!==`google_email_otp`||n.verification.challengeId!==e.operation.challengeId||e.challengeId!==e.operation.challengeId)return j();let r=t(e.challengeId);if(!r.ok)return j();try{let t=await this.rpc.verifyEmailOtp({relayUrl:n.relayUrl,recoveryOperationId:n.prepared.recoveryOperationId,reservationId:n.prepared.reservationId,challengeId:r.value,otpCode:e.otpCode});if(t.kind!==`verified`)return t;if(t.recoveryOperationId!==n.prepared.recoveryOperationId||t.challengeId!==e.challengeId)return{kind:`transport_uncertain`};let i=await U({context:e.context,relayUrl:n.relayUrl,walletId:n.walletId,recoveryOperationId:n.prepared.recoveryOperationId,reservationId:String(n.prepared.reservationId)});if(i.kind===`existing`){if(i.recoveryOperationId!==String(n.prepared.recoveryOperationId)||i.reservationId!==String(n.prepared.reservationId)||i.factorSecret32.byteLength!==32)return k(i.factorSecret32),{kind:`transport_uncertain`};let t=P(n,{kind:`email_otp`,factor:{replacementId:String(n.prepared.recoveryOperationId),walletAuthMethodId:n.prepared.targetWalletAuthMethodId,factor:o({enrollmentId:i.enrollmentId,enrollmentSealKeyVersion:i.enrollmentSealKeyVersion}),factorSecret:i.factorSecret32},enrollment:{kind:`existing`,enrollmentId:i.enrollmentId,enrollmentSealKeyVersion:i.enrollmentSealKeyVersion},providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,registrationAuthorityId:e.challengeId});return this.#e.set(t.recoveryOperationId,t),{kind:`email_otp_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target,challengeId:e.challengeId}}if(i.kind!==`create`)return i;if(i.recoveryOperationId!==String(n.prepared.recoveryOperationId)||i.reservationId!==String(n.prepared.reservationId))return{kind:`transport_uncertain`};let a=crypto.getRandomValues(new Uint8Array(32)),s=null;try{let t=await e.context.signingEngine.prepareEmailOtpRegistrationEnrollmentMaterialInternal({relayUrl:n.relayUrl,walletId:n.walletId,userId:i.providerSubject,clientSecret32:a});s=a.slice().buffer;let r=P(n,{kind:`email_otp`,factor:{replacementId:String(n.prepared.recoveryOperationId),walletAuthMethodId:n.prepared.targetWalletAuthMethodId,factor:o({enrollmentId:t.enrollmentId,enrollmentSealKeyVersion:t.enrollmentSealKeyVersion}),factorSecret:s},enrollment:{kind:`create`,enrollmentId:t.enrollmentId,providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,material:t.emailOtpEnrollment},providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,registrationAuthorityId:e.challengeId});return this.#e.set(r.recoveryOperationId,r),s=null,{kind:`email_otp_verified`,recoveryOperationId:r.recoveryOperationId,walletId:r.walletId,target:r.target,challengeId:e.challengeId}}finally{a.fill(0),s&&k(s)}}catch{return{kind:`refused`}}}async finalize(e){let t=String(e.operation.recoveryOperationId),n=this.#t.get(t);if(n)return n;let r=this.#o(e).finally(()=>{this.#t.delete(t)});return this.#t.set(t,r),r}async#o(e){this.#c();let t=C(this.#e.get(e.operation.recoveryOperationId),e.operation);if(!t)return j();try{if(t.stage===`credential_created`||t.stage===`email_otp_verified`){let n=t.stage===`credential_created`?F(t):t.replacement.factor,r=await e.context.signingEngine.recoverWalletCustodyManifest({walletId:t.walletId,prepared:t.prepared,custodyJson:t.custodyJson,recoveryCodeBytes:t.recoveryCodeBytes,replacementFactor:n,recoveryChallengeId:t.stage===`credential_created`?I(t):String(t.prepared.recoveryOperationId),relayUrl:t.relayUrl});if(this.#e.get(t.recoveryOperationId)!==t)return A(t),j();if(t.prepared.reservationExpiresAtMs<=Date.now())return this.cancel(t.recoveryOperationId),j();t.recoveryCodeBytes.fill(0),k(t.stage===`credential_created`?t.replacement.factorSecret:t.replacement.factor.factorSecret),t=z(t,r),this.#e.set(t.recoveryOperationId,t)}if(t.stage===`manifest_recovered`){if(!V(t)&&!H(t))return{kind:`transport_uncertain`};if(t.target.kind===`google_email_otp`&&!this.rpc)return{kind:`refused`};let e=await y({operation:t});if(this.#e.get(t.recoveryOperationId)!==t)return{kind:`transport_uncertain`};await c.putPendingWalletRecoveryCommit(e.pending);let r=V(t)?await W(t):this.rpc?await this.rpc.finalizeEmailOtp({relayUrl:t.relayUrl,walletId:t.walletId,recoveryOperationId:t.prepared.recoveryOperationId,reservationId:t.prepared.reservationId,targetDeviceId:t.prepared.targetDeviceId,targetAuthorityId:t.prepared.targetAuthorityId,targetWalletAuthMethodId:t.prepared.targetWalletAuthMethodId,expectedProviderSubject:t.replacement.providerSubject,expectedEmailHashHex:await n(t.replacement.verifiedEmail),expectedRegistrationAuthorityId:t.replacement.registrationAuthorityId,replacementEnvelope:t.recovered.replacementEnvelope,ecdsaMaterialPossessionProofs:t.recovered.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.activation.possessionProof})),emailOtpEnrollment:t.replacement.enrollment.kind===`create`?{kind:`create`,material:t.replacement.enrollment.material}:null}):{kind:`refused`};if(r.kind===`refused`)return await c.deletePendingWalletRecoveryCommit(t.prepared.recoveryOperationId),this.#e.get(t.recoveryOperationId)===t&&this.cancel(t.recoveryOperationId),r;if(this.#e.get(t.recoveryOperationId)!==t)return r.kind===`promoted`?{kind:`transport_uncertain`}:r;if(r.kind!==`promoted`)return r;if(t.replacement.kind===`passkey`&&r.authMethod.credentialIdB64u!==t.replacement.credentialIdB64u)return{kind:`transport_uncertain`};let i;if(f(e.payload)){if(!B(r))return{kind:`transport_uncertain`};i={kind:`passkey`,payload:e.payload,promotion:r}}else{if(B(r))return{kind:`transport_uncertain`};i={kind:`google_email_otp`,payload:e.payload,promotion:r}}await _({pending:await h({awaiting:e.pending,promotion:i}),payload:i.payload})}let r=this.#i.get(t.recoveryOperationId);return r&&O(this.#a,r),this.#e.delete(t.recoveryOperationId),this.#i.delete(t.recoveryOperationId),A(t),{kind:`ready_for_sign_in`,walletId:t.walletId}}catch{return{kind:`transport_uncertain`}}}async#s(e){try{let t=await e.credentialPromise;if(this.#e.get(e.current.recoveryOperationId)!==e.current||e.promptController.signal.aborted)return k(t.factorSecret),{kind:`dismissed`};if(e.current.prepared.reservationExpiresAtMs<=Date.now())return k(t.factorSecret),this.cancel(e.current.recoveryOperationId),{kind:`refused`};let n=N(e.current,t);return this.#e.set(n.recoveryOperationId,n),{kind:`credential_created`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target}}catch(t){return e.promptController.signal.aborted||M(t)?{kind:`dismissed`}:{kind:`transport_uncertain`}}finally{this.#n.get(e.current.recoveryOperationId)===e.promptController&&this.#n.delete(e.current.recoveryOperationId)}}cancel(e){this.#n.get(e)?.abort(),this.#n.delete(e);let t=this.#e.get(e);if(!t)return;let n=this.#i.get(e);this.#i.delete(e),n&&t.prepared.reservationExpiresAtMs>Date.now()&&this.#r.set(n,{reservationId:t.prepared.reservationId,expiresAtMs:t.prepared.reservationExpiresAtMs}),this.#e.delete(e),A(t)}#c(){let e=Date.now();for(let[t,n]of this.#r)n.expiresAtMs<=e&&this.#r.delete(t);for(let[t,n]of this.#e)n.prepared.reservationExpiresAtMs>e||(this.#n.get(t)?.abort(),this.#n.delete(t),this.#e.delete(t),this.#i.delete(t),A(n))}},K=class{#e=new G({verifyGoogle:v,verifyEmailOtp:g,finalizeEmailOtp:d});constructor(t,n){this.context=t,this.relayUrl=n;let r=e(t.signingEngine.getRpId());if(!r.ok)throw Error(`wallet recovery RP ID ${r.error.message}`);this.#t=r.value}#t;targetFor(e){switch(e){case`passkey`:return{kind:e,rpId:this.#t};case`google_email_otp`:return{kind:e,googleProvider:`google`}}}async prepare(e){let t=await this.#e.prepareWithCode({context:this.context,relayUrl:this.relayUrl,recoveryCode:e.recoveryCode,target:e.target,signal:e.signal});return t.kind===`prepared`?(t.target.kind,{kind:`hosted_recovery_prepared`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target}):t}createPasskey(e){return this.#n({kind:`prepared`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target})}async verifyGoogle(e,t){let n=await this.#e.verifyGoogle({relayUrl:this.relayUrl,operation:{kind:`prepared`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target},idToken:t});return n.kind===`google_verified`?{kind:`hosted_recovery_google_verified`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target,challengeId:n.challengeId,delivery:n.delivery,expiresAtMs:n.expiresAtMs}:n}async verifyEmailOtp(e,t){let n=await this.#e.verifyEmailOtp({context:this.context,operation:{kind:`google_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target,challengeId:e.challengeId,delivery:e.delivery,expiresAtMs:e.expiresAtMs},challengeId:t.challengeId,otpCode:t.otpCode});return n.kind===`email_otp_verified`?{kind:`hosted_recovery_email_otp_verified`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target,challengeId:n.challengeId}:n}async finalize(e){return e.kind===`hosted_recovery_credential_created`?await this.#e.finalize({context:this.context,operation:{kind:`credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target}}):await this.#e.finalize({context:this.context,operation:{kind:`email_otp_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target,challengeId:e.challengeId}})}async cancel(e){this.#e.cancel(e.recoveryOperationId)}async#n(e){let t=await this.#e.createPasskey({context:this.context,operation:e});return t.kind===`credential_created`?this.#r(t):t}#r(e){return{kind:`hosted_recovery_credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target}}};function q(e){return new K(e.context,e.relayUrl)}export{q as createHostedRecoveryPort};